### macOS Installation Guide for U++ Framework Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Outlines the setup procedure for macOS, including installing Xcode and Homebrew, installing necessary dependencies like gtk+3 and libnotify, downloading U++, and running TheIDE. It also mentions configuring build paths within TheIDE. ```bash # Install Xcode from App Store # Install Homebrew if not present /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" # Install dependencies brew install gtk+3 libnotify # Download and extract U++ # Run TheIDE application bundle open theide.app # Configure build paths in Setup -> Build Methods ``` -------------------------------- ### POSIX Installation Guide for U++ Framework Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Details the installation process for Linux and Unix-like systems, including installing dependencies via apt-get, cloning the U++ repository, building the framework, and running TheIDE. It also demonstrates how to build packages using the command line. ```bash # Install dependencies on Ubuntu/Debian sudo apt-get install g++ make libgtk-3-dev libnotify-dev \ libbz2-dev libssl-dev # Clone and build U++ git clone https://github.com/ultimatepp/ultimatepp.git cd ultimatepp make # Run TheIDE ./theide # Build a package using command line umk MyApp GCC -br RELEASE ``` -------------------------------- ### Win32 Installation Guide for U++ Framework Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Provides command-line instructions for downloading, installing, and configuring the U++ framework on Windows platforms, including setting up the MSVC compiler in TheIDE. This guide is essential for Windows users to begin development with U++. ```bash # Download the U++ installation package # Run the installer and follow the setup wizard # Configure compiler paths in TheIDE # Example: Setting up MSVC compiler in TheIDE # 1. Open TheIDE # 2. Setup -> Build Methods # 3. Add MSVC compiler path: C:\ Program Files\Microsoft Visual Studio\... # 4. Test compilation with a sample project ``` -------------------------------- ### Create Main Application Window with Menus and Toolbars (C++) Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates the creation of a main application window using TopWindow. Includes setup for a menu bar, toolbar, status bar, and basic window properties like title, size, and icon. Event handling for menu items is also shown. ```cpp #include using namespace Upp; class MyApp : public TopWindow { MenuBar menu; ToolBar toolbar; StatusBar status; public: MyApp() { Title("My Application"); Sizeable().Zoomable(); Icon(CtrlImg::exclamation()); SetRect(0, 0, 800, 600); AddFrame(menu); AddFrame(toolbar); AddFrame(status); menu.Set(THISBACK(MainMenu)); status = "Ready"; } void MainMenu(Bar& bar) { bar.Add("File", THISBACK(FileMenu)); bar.Add("Edit", THISBACK(EditMenu)); bar.Add("Help", THISBACK(HelpMenu)); } void FileMenu(Bar& bar) { bar.Add("New", THISBACK(FileNew)) .Key(K_CTRL_N) .Help("Create new file"); bar.Add("Open", THISBACK(FileOpen)) .Key(K_CTRL_O); bar.Separator(); bar.Add("Exit", THISBACK(Close)) .Key(K_ALT_F4); } void EditMenu(Bar& bar) {} void HelpMenu(Bar& bar) {} void FileNew() { status = "New file"; } // Placeholder for FileNew logic void FileOpen() { status = "Open file"; } // Placeholder for FileOpen logic }; GUI_APP_MAIN { MyApp app; app.Run(); } ``` -------------------------------- ### UMK Command Line Builder Usage (Bash) Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Explains the syntax and provides examples for using UMK, the command-line build tool for U++ projects. It covers building, exporting makefiles, showing package information, and cleaning the build, applicable in a bash environment. ```bash # Build syntax umk # Examples umk examples/HelloWorld GCC -br RELEASE umk MyApp CLANG -br DEBUG +SDL umk examples/Bombs MSC9 -br SPEED # Export makefile umk examples/HelloWorld MAKE > Makefile # Show package information umk examples/HelloWorld GCC -i # Clean build umk MyApp GCC -c ``` -------------------------------- ### ArrayCtrl Grid/Table Control Example (C++) Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates how to use the ArrayCtrl for displaying and editing tabular data. It includes adding, removing, and exporting data, along with basic UI element configuration. Requires the CtrlLib library. ```cpp #include using namespace Upp; struct Person { int id; String name; String email; int age; }; class GridWindow : public TopWindow { ArrayCtrl grid; Button btnAdd, btnRemove; Vector people; public: GridWindow() { Title("People Database").Sizeable(); SetRect(0, 0, 700, 500); Add(grid.HSizePosZ(10, 10).VSizePosZ(10, 50)); Add(btnAdd.SetLabel("Add").LeftPosZ(10, 80).BottomPosZ(10, 30)); Add(btnRemove.SetLabel("Remove").LeftPosZ(100, 80).BottomPosZ(10, 30)); // Configure columns grid.AddColumn("ID", 60).Edit(edtId); grid.AddColumn("Name", 200).Edit(edtName); grid.AddColumn("Email", 250).Edit(edtEmail); grid.AddColumn("Age", 80).Edit(edtAge); grid.Editable().MultiSelect(); grid.WhenBar = THISBACK(GridMenu); btnAdd << THISBACK(AddPerson); btnRemove << THISBACK(RemovePerson); // Sample data LoadSampleData(); RefreshGrid(); } EditInt edtId; EditString edtName, edtEmail; EditInt edtAge; void LoadSampleData() { people << Person{1, "Alice", "alice@example.com", 28} << Person{2, "Bob", "bob@example.com", 35} << Person{3, "Charlie", "charlie@example.com", 42}; } void RefreshGrid() { grid.Clear(); for(const Person& p : people) { grid.Add(p.id, p.name, p.email, p.age); } } void AddPerson() { int newId = people.GetCount() + 1; people.Add(Person{newId, "New Person", "new@example.com", 25}); RefreshGrid(); } void RemovePerson() { if(grid.IsCursor()) { int row = grid.GetCursor(); people.Remove(row); RefreshGrid(); } } void GridMenu(Bar& bar) { bar.Add("Add", THISBACK(AddPerson)); bar.Add("Remove", THISBACK(RemovePerson)); bar.Separator(); bar.Add("Export CSV", THISBACK(ExportCSV)); } void ExportCSV() { FileSel fs; fs.Type("CSV files", "*.csv"); if(!fs.ExecuteSaveAs()) return; FileOut out(fs); out << "ID,Name,Email,Age\n"; for(const Person& p : people) out << Format("%d,%s,%s,%d\n", p.id, p.name, p.email, p.age); } }; GUI_APP_MAIN { GridWindow().Run(); } ``` -------------------------------- ### Execute Remote Commands and Transfer Files via SSH using C++ Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt This C++ code snippet demonstrates establishing an SSH connection to a remote server, executing commands, and performing file transfers using SFTP. It utilizes the Upp::SshSession and Upp::SFtp classes. The example includes connecting, executing a remote command, uploading a local file, downloading a remote file, and listing directory contents. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { // SSH Session SshSession session; session.Timeout(30000); if(!session.Connect("server.example.com", 22, "username", "password")) { LOG("Connection failed: " << session.GetErrorDesc()); return; } LOG("Connected successfully!"); // Execute command String output, errors; int exitcode; if(session.Execute("ls -la /home", output, errors, exitcode)) { LOG("Output:\n" << output); LOG("Exit code: " << exitcode); if(!errors.IsEmpty()) LOG("Errors: " << errors); } // SFTP file transfer SFtp sftp(session); if(!sftp.Connect()) { LOG("SFTP failed: " << sftp.GetErrorDesc()); return; } // Upload file String localFile = LoadFile("/local/path/file.txt"); if(sftp.SaveFile("/remote/path/file.txt", localFile)) LOG("File uploaded"); // Download file String remoteContent; if(sftp.LoadFile("/remote/path/data.txt", remoteContent)) LOG("Downloaded: " << remoteContent); // List directory Vector entries; if(sftp.ListDir("/remote/path", entries)) { for(const auto& entry : entries) { LOG(entry.filename << " (" << entry.size << " bytes)"); } } sftp.Disconnect(); session.Disconnect(); } ``` -------------------------------- ### TcpSocket: C++ Network Communication Client and Server Examples Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates basic TCP network communication using the TcpSocket class in C++. Includes a simple TCP client that sends an HTTP request and receives a response, and a basic TCP server that listens for connections and echoes received data. Ensure network ports are available. ```cpp #include using namespace Upp; // Simple TCP client void TcpClientExample() { TcpSocket socket; if(!socket.Connect("example.com", 80)) { LOG("Connection failed: " << socket.GetErrorDesc()); return; } // Send HTTP request String request = "GET / HTTP/1.1\r\n" "Host: example.com\r\n" "Connection: close\r\n\r\n"; socket.Put(request); // Read response String response; while(!socket.IsEof()) { int c = socket.Get(); if(c < 0) break; response.Cat(c); } LOG(response); socket.Close(); } // Simple TCP server void TcpServerExample() { TcpSocket server; if(!server.Listen(8080, 5)) { LOG("Failed to listen on port 8080"); return; } LOG("Server listening on port 8080..."); while(true) { TcpSocket client; if(server.Accept(client)) { LOG("Client connected"); String data = client.GetLine(); LOG("Received: " << data); client.Put("Echo: " + data + "\r\n"); client.Close(); } } } CONSOLE_APP_MAIN { TcpClientExample(); } ``` -------------------------------- ### JSON Support: Parsing and Generating JSON Data in C++ Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Provides C++ examples for parsing JSON strings into U++ types and generating JSON data from C++ objects. Features automatic mapping between JSON and C++ structures using the Jsonize method. Handles JSON arrays and potential parsing errors. ```cpp #include using namespace Upp; struct Person { String name; int age; String email; void Jsonize(JsonIO& json) { json("name", name) ("age", age) ("email", email); } }; CONSOLE_APP_MAIN { // Parse JSON string String jsonData = R"({ "name": "Alice", "age": 28, "email": "alice@example.com" })"; Person person; if(!LoadFromJson(person, jsonData)) { LOG("Failed to parse JSON"); return; } DUMP(person.name); // Alice DUMP(person.age); // 28 DUMP(person.email); // alice@example.com // Generate JSON person.age = 29; String output = StoreAsJson(person); DUMP(output); // Output: {"name":"Alice","age":29,"email":"alice@example.com"} // Parse JSON array String arrJson = R"([1, 2, 3, 4, 5])"; Value arr = ParseJSON(arrJson); if(arr.IsError()) { LOG("Parse error: " << arr); return; } ValueArray va = arr; for(int i = 0; i < va.GetCount(); i++) LOG(va[i]); } ``` -------------------------------- ### HttpRequest - C++ HTTP Client for REST API and Web Scraping Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates using the HttpRequest class for making various HTTP requests like GET, POST with JSON data, setting custom headers, downloading files, and handling responses. It includes error checking and JSON parsing capabilities. Requires the Core library. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { // Simple GET request HttpRequest http("https://api.example.com/data"); String response = http.Execute(); if(http.IsError()) { LOG("HTTP Error: " << http.GetErrorDesc()); return; } DUMP(http.GetStatusCode()); // 200 DUMP(response); // POST request with JSON HttpRequest post("https://api.example.com/users"); post.Post() .ContentType("application/json") .PostData(R"({\"name\":\"John\",\"email\":\"john@example.com\"})"); String result = post.Execute(); DUMP(result); // Custom headers HttpRequest auth("https://api.example.com/protected"); auth.Header("Authorization", "Bearer token123") .Header("Accept", "application/json"); String data = auth.Execute(); // Download file HttpRequest download("https://example.com/file.zip"); download.WhenContent = [](const void *ptr, int size) { // Process downloaded data in chunks LOG("Received " << size << " bytes"); }; download.Execute(); // Parse JSON response Value jsonValue = ParseJSON(response); if(!jsonValue.IsError()) { ValueMap map = jsonValue; DUMP(map["result"]); } } ``` -------------------------------- ### Create a 'Hello World' GUI Application in TheIDE (C++) Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates how to create a basic 'Hello World' GUI application using the U++ framework within TheIDE. It covers creating a new package, defining a simple window, and running the application. This snippet is for C++ development. ```cpp // Create a new application in TheIDE // File -> New Package // Select "GUI application" template // Package name: HelloWorld #include using namespace Upp; class HelloWindow : public TopWindow { public: HelloWindow() { Title("Hello World").Sizeable().Zoomable(); SetRect(0, 0, 300, 200); } }; GUI_APP_MAIN { HelloWindow().Run(); } // Build: F7 // Debug: F5 // Release build: Ctrl+F7 ``` -------------------------------- ### U++ Package Structure and Usage (C++) Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Illustrates the file structure of a U++ package and the format of the `.upp` package file, including `description`, `uses`, `file`, and `mainconfig` directives. It also shows how to include one package within another. ```cpp // Package structure: MyPackage/ // - MyPackage.upp (package file) // - MyCode.cpp // - MyCode.h // - MyCode.lay (layout file) // MyPackage.upp file format: description "My custom package\377"; uses CtrlLib, Core; file MyCode.cpp, MyCode.h, MyCode.lay; mainconfig "" = "GUI"; // Use in another package: // Add "MyPackage" to the uses section ``` -------------------------------- ### Connect and Query PostgreSQL with UltimatePP SQL Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates connecting to a PostgreSQL database, creating tables, inserting data, performing select queries, updating, deleting, and managing transactions using UltimatePP's SQL interface. Requires PostgreSQL to be running and accessible. ```cpp #include #include using namespace Upp; CONSOLE_APP_MAIN { // Connect to PostgreSQL PostgreSQL postgres; if(!postgres.Open("host=localhost dbname=mydb user=myuser password=mypass")) { LOG("Connection failed: " << postgres.GetLastError()); return; } SQL = postgres; // Set global SQL session // Create table SQL.Execute("CREATE TABLE IF NOT EXISTS users (\n"\ "id SERIAL PRIMARY KEY, \n"\ "name VARCHAR(100), \n"\ "email VARCHAR(100), \n"\ "age INTEGER)"); // Insert data SQL * Insert(USERS) (NAME, "Alice") (EMAIL, "alice@example.com") (AGE, 28); SQL * Insert(USERS) (NAME, "Bob") (EMAIL, "bob@example.com") (AGE, 35); if(SQL.WasError()) { LOG("Insert error: " << SQL.GetLastError()); return; } // Select query Sql sql; sql * Select(ID, NAME, EMAIL, AGE).From(USERS).Where(AGE > 25); while(sql.Fetch()) { int id = sql[ID]; String name = sql[NAME]; String email = sql[EMAIL]; int age = sql[AGE]; LOG(Format("ID: %d, Name: %s, Email: %s, Age: %d", id, name, email, age)); } // Update SQL * Update(USERS)(EMAIL, "newemail@example.com") .Where(NAME == "Alice"); // Delete SQL * Delete(USERS).Where(AGE < 30); // Transaction { SqlTransaction trans(SQL); SQL * Insert(USERS)(NAME, "Charlie")(EMAIL, "charlie@example.com")(AGE, 40); SQL * Insert(USERS)(NAME, "David")(EMAIL, "david@example.com")(AGE, 45); trans.Commit(); // or trans.Rollback() } } ``` -------------------------------- ### Create Data Entry Form with Validation and Buttons (C++) Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Illustrates building a form window with various input controls like EditString and EditInt. It demonstrates layout positioning, button event handling, data retrieval, basic validation (email format, age range), and user feedback using message boxes. Dependencies include CtrlLib. ```cpp #include using namespace Upp; class FormWindow : public TopWindow { Label lblName, lblEmail, lblAge; EditString edtName, edtEmail; EditInt edtAge; Button btnSubmit; public: FormWindow() { Title("User Form").Sizeable(); SetRect(0, 0, 400, 250); // Layout controls Add(lblName.SetLabel("Name:").LeftPosZ(20, 80).TopPosZ(20, 20)); Add(edtName.LeftPosZ(110, 250).TopPosZ(20, 20)); Add(lblEmail.SetLabel("Email:").LeftPosZ(20, 80).TopPosZ(50, 20)); Add(edtEmail.LeftPosZ(110, 250).TopPosZ(50, 20)); Add(lblAge.SetLabel("Age:").LeftPosZ(20, 80).TopPosZ(80, 20)); Add(edtAge.LeftPosZ(110, 100).TopPosZ(80, 20)); Add(btnSubmit.SetLabel("Submit").LeftPosZ(110, 100).TopPosZ(120, 30)); // Event handlers btnSubmit << THISBACK(OnSubmit); // Validation edtAge.Min(0).Max(150); edtEmail.WhenAction = THISBACK(ValidateEmail); } void ValidateEmail() { String email = edtEmail.GetData(); if(email.Find('@') < 0) edtEmail.SetColor(EditField::PAPER, Color(255, 200, 200)); else edtEmail.ClearColor(); } void OnSubmit() { String name = edtName.GetData(); String email = edtEmail.GetData(); int age = edtAge.GetData(); if(name.IsEmpty() || email.IsEmpty()) { Exclamation("Please fill all fields!"); return; } if(PromptYesNo("Submit data?")) { PromptOK(Format("Name: %s\nEmail: %s\nAge: %d", name, email, age)); } } }; GUI_APP_MAIN { FormWindow().Run(); } ``` -------------------------------- ### Thread and Multithreading - C++ Synchronization and Parallelism Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates fundamental multithreading concepts in C++ using UltimatePP's Thread and Mutex classes. It covers creating and managing threads, using RAII-style locks for safe access to shared resources, and employing CoWork for efficient parallel task execution. Requires the Core library. ```cpp #include using namespace Upp; Mutex mutex; int sharedCounter = 0; void WorkerFunction() { for(int i = 0; i < 1000; i++) { Mutex::Lock lock(mutex); // RAII lock sharedCounter++; } } CONSOLE_APP_MAIN { // Create and start threads Thread t1, t2, t3; t1.Run(callback(WorkerFunction)); t2.Run(callback(WorkerFunction)); t3.Run(callback(WorkerFunction)); // Wait for completion t1.Wait(); t2.Wait(); t3.Wait(); DUMP(sharedCounter); // 3000 // CoWork - parallel task processing Vector numbers; for(int i = 0; i < 100; i++) numbers.Add(i); int64 sum = 0; Mutex sumMutex; CoWork co; for(int i = 0; i < numbers.GetCount(); i++) { co & [&, i] { int square = numbers[i] * numbers[i]; Mutex::Lock lock(sumMutex); sum += square; }; } co.Finish(); // Wait for all tasks DUMP(sum); // Sum of squares: 328350 } ``` -------------------------------- ### Layout Designer (.lay file) Usage (C++) Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Shows how to define a GUI layout using a .lay file and then integrate it into a C++ application. This system allows for visual design and code generation for UI elements. Requires CtrlLib and CtrlCore libraries. ```cpp // MyLayout.lay file: LAYOUT(MyFormLayout, 400, 300) ITEM(Label, lblName, SetLabel("Name:").LeftPosZ(20, 80).TopPosZ(20, 20)) ITEM(EditString, edtName, LeftPosZ(110, 250).TopPosZ(20, 20)) ITEM(Label, lblEmail, SetLabel("Email:").LeftPosZ(20, 80).TopPosZ(50, 20)) ITEM(EditString, edtEmail, LeftPosZ(110, 250).TopPosZ(50, 20)) ITEM(Button, btnOK, SetLabel("OK").LeftPosZ(110, 80).TopPosZ(90, 30)) ITEM(Button, btnCancel, SetLabel("Cancel").LeftPosZ(200, 80).TopPosZ(90, 30)) END_LAYOUT // Usage in code: #include using namespace Upp; #define LAYOUTFILE #include class MyDialog : public WithMyFormLayout { public: MyDialog() { CtrlLayout(*this, "My Form"); btnOK << [=] { AcceptBreak(IDOK); }; btnCancel << [=] { RejectBreak(IDCANCEL); }; } String GetName() { return ~edtName; } String GetEmail() { return ~edtEmail; } }; GUI_APP_MAIN { MyDialog dlg; if(dlg.Execute() == IDOK) { PromptOK(Format("Name: %s\nEmail: %s", dlg.GetName(), dlg.GetEmail())); } } ``` -------------------------------- ### Image Processing with Ultimate++ Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates creating, manipulating, and saving raster images using the Ultimate++ library. It covers drawing gradients, basic transformations like resizing, rotating, and mirroring, applying filters such as blur and sharpen, and converting images to grayscale. Input is buffer data and image files; output is processed image files. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { // Create image buffer ImageBuffer ib(256, 256); // Draw gradient for(int y = 0; y < 256; y++) { for(int x = 0; x < 256; x++) { RGBA& pixel = ib[y][x]; pixel.r = x; pixel.g = y; pixel.b = 128; pixel.a = 255; } } Image img = ib; // Save image PNGEncoder encoder; encoder.SaveFile(ConfigFile("gradient.png"), img); // Load image Image loaded = StreamRaster::LoadFileAny(ConfigFile("gradient.png")); DUMP(loaded.GetSize()); // Image transformations Image scaled = Rescale(img, Size(128, 128)); Image rotated = Rotate(img, 90); Image mirrored = MirrorHorz(img); // Apply effects Image blurred = Blur(img, 5); Image sharpened = Sharpen(img, 5); // Color adjustments ImageBuffer ib2(img); for(int y = 0; y < ib2.GetHeight(); y++) { for(int x = 0; x < ib2.GetWidth(); x++) { RGBA& p = ib2[y][x]; // Convert to grayscale int gray = (p.r + p.g + p.b) / 3; p.r = p.g = p.b = gray; } } Image grayscale = ib2; PNGEncoder().SaveFile(ConfigFile("processed.png"), grayscale); } ``` -------------------------------- ### XML Parsing and Generation - C++ DOM-style Access Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Illustrates how to parse XML strings into a DOM-like structure using XmlParser and XmlNode, allowing for easy access to elements, attributes, and text content. It also shows how to generate XML documents programmatically. Requires the Core library. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { // Parse XML string String xml = "" "" " " " Alice" " alice@example.com" " " " " " Bob" " bob@example.com" " " ""; XmlParser parser(xml); try { XmlNode root = ParseXML(parser); // Access root element DUMP(root.GetTag()); // users // Iterate child nodes for(int i = 0; i < root.GetCount(); i++) { const XmlNode& user = root[i]; if(user.GetTag() == "user") { String id = user.Attr("id"); String name = user["name"][0].GetText(); String email = user["email"][0].GetText(); LOG("User " << id << ": " << name << " - " << email); } } } catch(XmlError e) { LOG("XML Parse Error: " << e); } // Generate XML XmlNode output("response"); output.Add("status", "success"); XmlNode& data = output.Add("data"); data.SetAttr("timestamp", Format("%", GetSysTime())); data.Add("message", "Operation completed"); String xmlOutput = AsXML(output); DUMP(xmlOutput); } ``` -------------------------------- ### Stream Operations: File, String, and Memory I/O in C++ Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates unified I/O operations for files, strings, and memory buffers using Ultimate++'s stream classes. Includes file input/output, string stream manipulation, and memory stream reading. Ensure files are accessible and writable. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { // File output stream { FileOut out("/tmp/data.txt"); if(!out) { LOG("Cannot create file"); return; } out << "Hello World\n"; out << "Number: " << 42 << "\n"; // Automatically closed on destruction } // File input stream { FileIn in("/tmp/data.txt"); if(!in) { LOG("Cannot open file"); return; } String line; while(!in.IsEof()) { line = in.GetLine(); LOG(line); } } // String stream StringStream ss; ss << "Value: " << 123; String result = ss.GetResult(); // "Value: 123" DUMP(result); // Memory stream MemReadStream mem("data in memory", 14); String data = mem.Get(14); DUMP(data); } ``` -------------------------------- ### U++ NTL Vector Container Usage (C++) Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Demonstrates the usage of the `Vector` container from U++'s NTL library in C++. It covers adding, accessing, iterating, inserting, removing, finding, and sorting elements within a dynamic array. Includes `DUMP` and `LOG` for output. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { Vector names; // Adding elements names.Add("Alice"); names.Add("Bob"); names << "Charlie" << "David"; // Stream operator // Access elements DUMP(names[0]); // Alice DUMP(names.GetCount()); // 4 // Iteration for(const String& name : names) LOG(name); // Insert and remove names.Insert(1, "Eve"); // Insert at position 1 names.Remove(2); // Remove element at index 2 // Find element int idx = FindIndex(names, "Bob"); if(idx >= 0) LOG("Found Bob at index " << idx); // Sort Sort(names); // Output: Alice, Bob, Charlie, David, Eve } ``` -------------------------------- ### Sending Emails with SMTP Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Enables sending emails programmatically using the SMTP protocol, with support for attachments and both plain text and HTML bodies. The code configures SMTP server details, authentication, recipient, subject, and message content. It includes error handling for sending failures and demonstrates configuring for both TLS and SSL connections. Input is email content and server credentials; output is a sent email. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { Smtp smtp; // Configure SMTP server smtp.Host("smtp.gmail.com") .Port(587) .Auth("your-email@gmail.com", "your-app-password") .StartTLS(); // Create email message smtp.To("recipient@example.com") .Subject("Test Email from U++") .Body("This is a test email sent using U++ SMTP library.\n\n" "Best regards,\nYour Application"); // Add attachment String fileContent = LoadFile("/path/to/document.pdf"); smtp.Attach("document.pdf", fileContent, "application/pdf"); // Send if(!smtp.Send()) { LOG("Failed to send email: " << smtp.GetError()); return; } LOG("Email sent successfully!"); // HTML email Smtp html_mail; html_mail.Host("smtp.example.com") .Port(465) .SSL() .Auth("user@example.com", "password") .To("recipient@example.com") .Subject("HTML Newsletter") .Body("" "

Welcome!

" "

This is an HTML email.

" "", "text/html"); html_mail.Send(); } ``` -------------------------------- ### UltimatePP Draw Interface: 2D Graphics Rendering Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Illustrates the use of UltimatePP's cross-platform 2D drawing API for rendering vector and raster graphics within a GUI application. This includes drawing basic shapes, text, polygons, images, clipping, and gradients. Requires a GUI environment. ```cpp #include using namespace Upp; class DrawingCtrl : public Ctrl { public: virtual void Paint(Draw& w) { Size sz = GetSize(); // Fill background w.DrawRect(sz, White()); // Draw line w.DrawLine(10, 10, 200, 10, 2, Black()); // Draw rectangle w.DrawRect(10, 30, 100, 60, Blue()); // Draw filled ellipse w.DrawEllipse(150, 30, 100, 60, Yellow(), 1, Black()); // Draw text Font fnt = Arial(20).Bold(); w.DrawText(10, 110, "Hello Drawing!", fnt, Red()); // Draw polygon Vector poly; poly << Point(300, 10) << Point(350, 50) << Point(320, 100) << Point(280, 50); w.DrawPolygon(poly, Green(), 2, Black()); // Draw image Image img = CtrlImg::exclamation(); w.DrawImage(400, 10, img); // Clipping w.Clip(10, 150, 200, 100); w.DrawRect(0, 140, 300, 120, LtBlue()); w.End(); // Gradient for(int i = 0; i < 100; i++) { int alpha = 255 * i / 100; w.DrawRect(220, 150 + i, 100, 1, Color(255, 0, 0, alpha)); } } }; GUI_APP_MAIN { TopWindow win; DrawingCtrl ctrl; win.Add(ctrl.SizePos()); win.Sizeable().Zoomable(); win.SetRect(0, 0, 600, 400); win.Run(); } ``` -------------------------------- ### Retrieve Emails from POP3 Server using C++ Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt This C++ code snippet demonstrates how to connect to a POP3 server, retrieve email messages, parse their content (sender, subject, date, body), and handle attachments. It uses the Upp::Pop3 class for POP3 operations. Error handling for connection and message retrieval is included. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { Pop3 pop; // Connect to server if(!pop.Connect("pop.gmail.com", 995, "user@gmail.com", "password", true)) { LOG("Connection failed: " << pop.GetError()); return; } // Get message count int count = pop.GetMessageCount(); LOG("You have " << count << " messages"); // Retrieve messages for(int i = 1; i <= count; i++) { InetMessage msg; if(!pop.GetMessage(i, msg)) { LOG("Failed to retrieve message " << i); continue; } LOG("From: " << msg.from); LOG("Subject: " << msg.subject); LOG("Date: " << msg.date); LOG("Body: " << msg.body); // Process attachments for(int j = 0; j < msg.attachment.GetCount(); j++) { const InetMessage::Attachment& att = msg.attachment[j]; LOG("Attachment: " << att.filename << " (" << att.data.GetCount() << " bytes)"); SaveFile("/tmp/" + att.filename, att.data); } // Delete message (optional) // pop.DeleteMessage(i); LOG("---"); } pop.Close(); } ``` -------------------------------- ### Advanced 2D Graphics with Painter API Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Utilizes the Ultimate++ Painter API for high-quality 2D graphics rendering, including anti-aliasing and transformations. This snippet demonstrates drawing smooth curves, filled shapes with gradients, applying transformations like translation and rotation to text, and rendering circles with transparency. Input is drawing commands; output is rendered graphics on a window. ```cpp #include using namespace Upp; class PainterCtrl : public Ctrl { public: virtual void Paint(Draw& w) { Size sz = GetSize(); BufferPainter painter(sz); // Set high quality rendering painter.Clear(White()); // Draw smooth curve painter.Move(50, 200) .Line(100, 50) .Cubic(150, 300, 250, 50, 300, 200); painter.Stroke(3, Blue()); // Draw filled shape with gradient painter.Move(350, 50) .Line(450, 100) .Line(400, 200) .Line(300, 150) .Close(); // Create gradient painter.Fill(350, 50, Yellow(), 400, 200, Red()); // Text with transformation painter.Translate(100, 300) .Rotate(M_PI / 6); Font fnt = Arial(30).Bold(); painter.Text(0, 0, "Rotated Text", fnt) .Fill(Black()); painter.Identity(); // Reset transformation // Circle with opacity painter.Circle(200, 350, 50) .Fill(Color(0, 255, 0, 128)); // Apply to window painter.Paint(w, 0, 0); } }; GUI_APP_MAIN { TopWindow win; PainterCtrl ctrl; win.Add(ctrl.SizePos()); win.SetRect(0, 0, 600, 500); win.Run(); } ``` -------------------------------- ### Define and Use Type-Safe Database Schemas with .sch Files Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Explains how to define database schemas using .sch files for type-safe SQL operations. This includes schema definition syntax and usage with SQLite for creating tables and executing type-safe queries. Requires a SQLite database file. ```cpp // Users.sch file: TABLE(USERS) INT (ID) PRIMARY_KEY AUTO_INCREMENT STRING (NAME) NOT_NULL STRING (EMAIL) NOT_NULL UNIQUE INT (AGE) DATE (CREATED_AT) END_TABLE TABLE(ORDERS) INT (ID) PRIMARY_KEY AUTO_INCREMENT INT (USER_ID) NOT_NULL REFERENCES(USERS, ID) DOUBLE (AMOUNT) DATE (ORDER_DATE) END_TABLE // Usage: #include #define SCHEMADIALECT #define MODEL #include using namespace Upp; CONSOLE_APP_MAIN { Sqlite3Session sqlite; sqlite.Open(ConfigFile("myapp.db")); SQL = sqlite; // Create tables from schema SqlSchema schema(SQLITE3); All_Tables(schema); SqlPerformScript(schema.Upgrade()); SqlPerformScript(schema.Attributes()); // Type-safe queries using schema SQL * Insert(USERS) (NAME, "Alice") (EMAIL, "alice@example.com") (AGE, 28) (CREATED_AT, GetSysDate()); int userId = SQL.GetInsertedId(); SQL * Insert(ORDERS) (USER_ID, userId) (AMOUNT, 99.99) (ORDER_DATE, GetSysDate()); // Join query Sql sql; sql * Select(USERS[NAME], ORDERS[AMOUNT]) .From(USERS) .InnerJoin(ORDERS).On(USERS[ID] == ORDERS[USER_ID]); while(sql.Fetch()) { LOG(sql[0] << ": $" << sql[1]); } } ``` -------------------------------- ### Value Type: Universal Type Handling and Conversions in C++ Source: https://context7.com/context7/ultimatepp_www_uppweb_documentation/llms.txt Illustrates the use of the Value type in C++ for storing any data type and performing automatic conversions. Demonstrates type checking, explicit conversions, and the use of ValueMap and ValueArray for structured data. Handles null values gracefully. ```cpp #include using namespace Upp; CONSOLE_APP_MAIN { // Store different types Value v1 = 42; Value v2 = "Hello"; Value v3 = Date(2025, 1, 15); Value v4 = Null; // Null value // Type checking DUMP(IsNumber(v1)); // true DUMP(IsString(v2)); // true DUMP(IsNull(v4)); // true // Conversion int num = v1; String str = v2; Date date = v3; // ValueMap - dictionary ValueMap map; map("name", "John") ("age", 30) ("city", "New York"); DUMP(map["name"]); // John DUMP(map["age"]); // 30 // ValueArray - array ValueArray arr; arr << "first" << "second" << 123; DUMP(arr[0]); // first DUMP(arr.GetCount()); // 3 // JSON serialization String json = AsJSON(map); DUMP(json); // {"name":"John","age":30,"city":"New York"} } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.