Tuesday, January 14, 2025

Make a Chromium-based browser

Here’s a guide on creating a basic Chromium-based browser using the Chromium Embedded Framework (CEF). This example sets up a simple browser with basic functionality.

Requirements
Install a C++ development environment (e.g., Visual Studio, CMake).
Download Chromium or CEF SDK.
Ensure necessary dependencies like Git, Python3, and Ninja are installed.
Project Structure

/MyBrowser
    |-- CMakeLists.txt
    |-- main.cpp
    |-- simple_handler.cpp
    |-- simple_handler.h

1. CMakeLists.txt

cmake_minimum_required(VERSION 3.10)
project(MyBrowser)

# Set C++ standard
set(CMAKE_CXX_STANDARD 17)

# CEF root directory
set(CEF_ROOT "path/to/cef_binary")

# Add CEF as a subdirectory
add_subdirectory(${CEF_ROOT} cef_target_dir)

# Add source files
add_executable(MyBrowser main.cpp simple_handler.cpp)

# Link CEF libraries
target_link_libraries(MyBrowser libcef_lib cef_sandbox_lib)

2. main.cpp
This is the entry point of the application. It initializes CEF, creates a browser window, and runs the CEF message loop.

#include "include/cef_app.h"
#include "simple_handler.h"

int main(int argc, char* argv[]) {
    // CEF main arguments
    CefMainArgs main_args(argc, argv);

    // Implement a custom CEF app
    CefRefPtr<CefApp> app;

    // Execute sub-processes
    int exit_code = CefExecuteProcess(main_args, app, nullptr);
    if (exit_code >= 0) {
        return exit_code;
    }

    // CEF initialization settings
    CefSettings settings;
    settings.no_sandbox = true;

    // Initialize CEF
    CefInitialize(main_args, settings, app, nullptr);

    // Create the main browser window
    CefRefPtr<SimpleHandler> handler(new SimpleHandler());
    CefWindowInfo window_info;
    CefBrowserSettings browser_settings;

    // Create a browser instance
    CefBrowserHost::CreateBrowser(window_info, handler, "https://www.google.com", browser_settings, nullptr, nullptr);

    // Run the CEF message loop
    CefRunMessageLoop();

    // Shutdown CEF
    CefShutdown();
    return 0;
}

3. simple_handler.h
This file defines a handler class to manage browser events.

#ifndef SIMPLE_HANDLER_H_
#define SIMPLE_HANDLER_H_

#include "include/cef_client.h"

class SimpleHandler : public CefClient, public CefLifeSpanHandler {
public:
    SimpleHandler() = default;
    ~SimpleHandler() override = default;

    CefRefPtr<CefLifeSpanHandler> GetLifeSpanHandler() override {
        return this;
    }

    void OnAfterCreated(CefRefPtr<CefBrowser> browser) override {
        CEF_REQUIRE_UI_THREAD();
        browser_list_.push_back(browser);
    }

    void OnBeforeClose(CefRefPtr<CefBrowser> browser) override {
        CEF_REQUIRE_UI_THREAD();
        browser_list_.remove(browser);
        if (browser_list_.empty()) {
            CefQuitMessageLoop();
        }
    }

private:
    std::list<CefRefPtr<CefBrowser>> browser_list_;

    IMPLEMENT_REFCOUNTING(SimpleHandler);
};

#endif  // SIMPLE_HANDLER_H_

4. simple_handler.cpp
This file provides implementations for SimpleHandler.

#include "simple_handler.h"
#include "include/cef_browser.h"

void SimpleHandler::OnAfterCreated(CefRefPtr<CefBrowser> browser) {
    CefClient::OnAfterCreated(browser);
}

How to Run
1.Download the CEF SDK: Obtain the latest SDK from the CEF website.
2.Configure the project path: Replace CEF_ROOT in the CMakeLists.txt file with the path to your CEF installation.
3.Build the project:

mkdir build
cd build
cmake ..
cmake --build .

4.Run the browser: Execute the generated binary.
How to Extend
1.Multi-Tab Support: Manage multiple CefBrowser instances in the SimpleHandler class.
2.Custom UI: Integrate a GUI framework like Qt or wxWidgets for a more polished interface.
3.Plugins and Extensions: Enable Chromium features for extensions or custom plugins.
4.Custom Features: Add APIs for file access, scripting, or other specific functionalities.
This setup provides a minimal browser framework.

Sunday, January 5, 2025

Use webpage to upload and download files

In the current code, uploaded files are not actually stored on a server. The files are just read and stored temporarily in the browser’s memory using JavaScript FileReader and Blob objects. These files are not uploaded to any server or remote storage, and are instead stored locally in the browser for temporary use.

How the file storage works:
When the user selects a file, it is read into an ArrayBuffer, then converted into a URL using Blob.
This temporary URL is saved in the browser’s memory using a Map object for easy access to the files.
When the user clicks the “Download” button, the file is downloaded using this temporary URL.
However, the file is not saved to any server, meaning if the page is refreshed, the uploaded files will be lost. If you want to save uploaded files on a server and provide download links, you’ll need to implement server-side storage.

Code Functionality:
This code implements a simple webpage file upload download and refresh functionality:

The user can select multiple files to upload, but the files are only stored in the browser’s memory and not uploaded to a server.
The uploaded files are displayed on the page, and users can download these files.
There is a “Refresh Page” button on the page that, when clicked, reloads the entire page and resets the file list.
Code Implementation:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Transfer Tool</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
    #fileList { margin-top: 20px; }
    button { margin-top: 20px; }
  </style>
</head>
<body>
  <h1>File Transfer Tool</h1>
  <p>Upload and download files using this page.</p>
  
  <!-- File Upload Section -->
  <input type="file" id="fileInput" multiple>
  <button id="uploadBtn">Upload Files</button>
  
  <!-- Refresh Button -->
  <button id="refreshBtn">Refresh Page</button>

  <!-- File List -->
  <div id="fileList">
    <h3>Uploaded Files</h3>
    <ul id="files"></ul>
  </div>

  <script>
    const fileInput = document.getElementById('fileInput');
    const uploadBtn = document.getElementById('uploadBtn');
    const refreshBtn = document.getElementById('refreshBtn');
    const fileList = document.getElementById('files');

    // Store uploaded files in memory
    const uploadedFiles = new Map();

    // File upload functionality
    uploadBtn.addEventListener('click', () => {
      const files = fileInput.files;
      if (files.length === 0) {
        alert('Please select files!');
        return;
      }

      // Store files in memory
      Array.from(files).forEach((file) => {
        const fileURL = URL.createObjectURL(file);  // Create a temporary URL
        uploadedFiles.set(file.name, { file, fileURL });
      });

      alert('Files uploaded successfully');
      // Update the file list
      updateFileList();
    });

    // Update the file list
    function updateFileList() {
      fileList.innerHTML = '';  // Clear the list
      uploadedFiles.forEach((fileData, fileName) => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
          <span>${fileName}</span>
          <a href="${fileData.fileURL}" download="${fileName}" style="margin-left: 10px;">Download</a>
        `;
        fileList.appendChild(listItem);
      });
    }

    // Refresh page functionality
    refreshBtn.addEventListener('click', () => {
      location.reload();  // Reload the entire page
    });
  </script>
</body>
</html>

Code Explanation:
File Upload Functionality:

When the user clicks the “Upload Files” button, the selected files are given a temporary URL using URL.createObjectURL() and stored in the browser’s memory.
The uploaded files will be displayed on the page by calling updateFileList().
File List Update:

After uploading files, the updateFileList() function is called to refresh the file list on the page. Files are shown with their names and a download link.
Refresh Page:

When the “Refresh Page” button is clicked, location.reload() is called to reload the entire page, simulating a browser refresh. This clears the file list and resets the page content.
—————–
How to upload files to a server
To ensure that uploaded files are stored on the server and can be downloaded, you would need both front-end and back-end implementation:

Frontend: Use the FormData object to send the file to the server.
Backend: The server will receive the file and store it at a designated location.
Example: File upload using Node.js backend
1. Frontend: Uploading files to the server
Here’s an updated version of the front-end code to handle file uploads to the server.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Transfer Tool</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
    #fileList { margin-top: 20px; }
  </style>
</head>
<body>
  <h1>File Transfer Tool</h1>
  <p>Use this page to upload and download files.</p>
  
  <!-- File upload section -->
  <input type="file" id="fileInput" multiple>
  <button id="uploadBtn">Upload File</button>

  <!-- File list -->
  <div id="fileList">
    <h3>Uploaded Files</h3>
    <ul id="files"></ul>
  </div>

  <script>
    const fileInput = document.getElementById('fileInput');
    const uploadBtn = document.getElementById('uploadBtn');
    const fileList = document.getElementById('files');

    // File upload functionality
    uploadBtn.addEventListener('click', () => {
      const files = fileInput.files;
      if (files.length === 0) {
        alert('Please select a file!');
        return;
      }

      const formData = new FormData();
      for (const file of files) {
        formData.append('files', file);  // Add the file to the FormData object
      }

      // Send the file to the server
      fetch('/upload', {
        method: 'POST',
        body: formData,
      })
      .then(response => response.json())
      .then(data => {
        alert('File uploaded successfully');
        // Update file list (show file paths or information returned from server)
        updateFileList(data.files);
      })
      .catch(error => {
        console.error('File upload failed:', error);
        alert('File upload failed');
      });
    });

    // Update file list
    function updateFileList(files) {
      fileList.innerHTML = '';
      files.forEach(file => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
          <span>${file.name}</span>
          <a href="${file.url}" download="${file.name}" style="margin-left: 10px;">Download</a>
        `;
        fileList.appendChild(listItem);
      });
    }
  </script>
</body>
</html>

2. Backend: Using Node.js to handle file storage
You can use Node.js with Express and the Multer library to handle the file upload and storage on the server.

First, install the necessary packages:

npm install express multer

Then, set up the Node.js server:

const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();

// Configure storage settings for uploaded files
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');  // Folder where the files will be stored
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));  // Filename format
  }
});

const upload = multer({ storage: storage });

// File upload route
app.post('/upload', upload.array('files'), (req, res) => {
  const files = req.files.map(file => ({
    name: file.originalname,
    url: `http://localhost:3000/uploads/${file.filename}`,  // URL to access the file
  }));

  res.json({ files });  // Return file information to the frontend
});

// Serve static files (uploaded files)
app.use('/uploads', express.static('uploads'));

// Start the server
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Explanation:
Frontend: Sends the file to the server using FormData. Upon successful upload, the server returns the file information (name and URL), which is then displayed on the webpage.
Backend: The multer library handles file uploads, stores the files in the uploads/ folder, and generates a URL to access each uploaded file.
How to Test:
1.Start the Node.js server.
2.Open the HTML page and upload a file.
3.Once the file is uploaded, it will be stored on the server in the uploads/ directory, and you can download it by clicking the download link.
This method will actually store the uploaded files on the server, allowing them to be accessed and downloaded by the user.

Saturday, January 4, 2025

How to Check if Sleep Mode is Enabled on Windows 11 Using Command Line

You can use the powercfg command to check the status of sleep mode in Windows 11. Here’s how:

Steps to Check Sleep Mode Status
1.Open Command Prompt as Administrator

Press Win + S, search for Command Prompt.
Right-click on Command Prompt and select Run as administrator.
2.View Power Plan and Sleep Settings Run the following command to view the detailed power plan settings, including sleep mode:

powercfg /query

This will display all current settings, including the timeout for sleep mode under both plugged-in and battery conditions.

3.Check Specific Sleep Timeout To check the specific sleep timeout values:

For sleep timeout on AC power:

powercfg -query SCHEME_CURRENT SUB_SLEEP STANDBYIDLE

For sleep timeout on battery power:

powercfg -query SCHEME_CURRENT SUB_SLEEP STANDBYIDLE

4.Check Hibernate (Standby) Mode Use the following command to see if hibernation is enabled and supported on your system:

powercfg /a
or
powercfg -a

This will list the available power states, including Standby (S3) and Hibernate, if enabled.

Example Output
Example 1: Output for powercfg /query

Power Setting GUID: SUB_SLEEP
Power Setting Name: Sleep idle timeout (AC)
Possible Settings: ...
Current AC Power Setting Index: 30 (minutes)

Example 2: Output for powercfg /a

The following sleep states are available on this system:
    Standby (S3)
    Hibernate

Summary
Sleep Mode Timeout: Use powercfg -query to check sleep mode timeout settings.
Hibernate Mode: Use powercfg /a to verify if hibernation is enabled.
Adjust Settings: If necessary, modify sleep settings using powercfg -change.

How to Disable Sleep and Standby Modes on Windows 11 Using Command Line

Here’s how you can turn off sleep and standby modes using the PowerCfg command on Windows 11:

Steps:
1. Open Command Prompt (Run as Administrator)
Press Win + S and search for “cmd”.
Right-click on “Command Prompt” and select Run as administrator.
2. Disable Sleep Mode
Run the following commands to disable sleep mode:

powercfg -change -standby-timeout-ac 0
powercfg -change -standby-timeout-dc 0

-standby-timeout-ac: Disables sleep mode when plugged into AC power.
-standby-timeout-dc: Disables sleep mode when on battery power.
0: Sets the timeout to 0, effectively disabling sleep mode.
3. Disable Hibernate (Standby) Mode
Run the following command to turn off hibernation:

powercfg -hibernate off

Restore Settings (Optional)
To re-enable sleep or standby modes, use these commands:

To enable sleep mode (e.g., set to 30 minutes):

powercfg -change -standby-timeout-ac 30
powercfg -change -standby-timeout-dc 30

To enable hibernation:

powercfg -hibernate on

Verify the Settings
Run this command to view the current power plan settings:

powercfg /query

Check if the changes have been applied successfully.

With these steps, you can manage sleep and standby modes on your Windows 11 system easily.

Tuesday, December 31, 2024

Here is the simplified version of the code, with only the text chatting functionality retained.

Here is the simplified version of the code, with only the text chatting functionality retained.

Final Version: index.html
This HTML file builds the chat window and handles the user input.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat Room</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        #chat-container {
            text-align: center;
        }
        #chat { 
            height: 500px; 
            overflow-y: scroll; 
            border: 1px solid #ccc; 
            padding: 10px; 
            width: 600px; 
            margin-bottom: 10px;
        }
        #message { width: 400px; }
        #name { display: none; }
    </style>
</head>
<body>
    <div id="chat-container">
        <h1>Chat Room</h1>
        <div id="chat"></div>
        <input type="hidden" id="name" value="">
        <input type="text" id="message" placeholder="Type your message here...">
        <button onclick="sendMessage()">Send</button>
    </div>
    <script>
        let name = 'User' + Math.floor(Math.random() * 10000);
        document.getElementById('name').value = name;

        function sendMessage() {
            let message = document.getElementById('message').value;
            if (message.trim() === '') return;
            let xhr = new XMLHttpRequest();
            xhr.open('POST', 'chat.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send('name=' + encodeURIComponent(name) + '&message=' + encodeURIComponent(message));
            document.getElementById('message').value = '';
        }

        function loadMessages() {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', 'chat.php', true);
            xhr.onload = function () {
                if (xhr.status === 200) {
                    document.getElementById('chat').innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }

        document.getElementById('message').addEventListener('keydown', function(event) {
            if (event.key === 'Enter') {
                sendMessage();
                event.preventDefault(); // Prevent the Enter key from submitting the form
            }
        });

        setInterval(loadMessages, 1000);
    </script>
</body>
</html>

Final Version: chat.php
This PHP file handles the chat messages and stores them in a text file.

<?php
$chatFile = '/usr/share/nginx/mydomain.com/chat3/chat.txt';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = htmlspecialchars($_POST['name']);
    $message = htmlspecialchars($_POST['message']);
    $time = date('H:i:s');

    $entry = "<p><strong>$name</strong> [$time]: $message</p>n";
    if (!file_exists($chatFile)) {
        file_put_contents($chatFile, $entry);
    } else {
        file_put_contents($chatFile, $entry, FILE_APPEND);
    }
    echo 'Message sent';
} else {
    if (file_exists($chatFile)) {
        echo file_get_contents($chatFile);
    } else {
        echo '<p>No messages yet.</p>';
    }
}
?>

Ensure Proper Permissions
Ensure that the chat.txt file exists and has the correct permissions:

touch /usr/share/nginx/mydomain.com/chat3/chat.txt
chmod 666 /usr/share/nginx/mydomain.com/chat3/chat.txt

With these final simplified versions of the code, you will retain a functional text chat room.