Загрузка данных


@echo off
set "SELF=%~f0"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$c=Get-Content -Raw -LiteralPath $env:SELF; $ps=$c -split '### POWERSHELL START ###',2; Invoke-Expression $ps[1]"
exit /b

### POWERSHELL START ###

try {
    $ErrorActionPreference = "Stop"

    Add-Type -AssemblyName System.Windows.Forms

    Add-Type @"
using System;
using System.Text;
using System.Runtime.InteropServices;

public class WinApi {
    public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern bool IsWindowVisible(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, UInt32 uFlags);

    [DllImport("user32.dll")]
    public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
}
"@

    function Find-CommandPath {
        param([string[]]$Names)

        foreach ($name in $Names) {
            $cmd = Get-Command $name -ErrorAction SilentlyContinue | Select-Object -First 1
            if ($cmd) {
                return $cmd.Source
            }
        }

        return $null
    }

    function Get-TopWindows {
        $script:topWindows = @()

        $callback = [WinApi+EnumWindowsProc]{
            param([IntPtr]$hWnd, [IntPtr]$lParam)

            if ([WinApi]::IsWindowVisible($hWnd)) {
                $sb = New-Object System.Text.StringBuilder 512
                [void][WinApi]::GetWindowText($hWnd, $sb, $sb.Capacity)

                $title = $sb.ToString()

                if ($title.Trim().Length -gt 0) {
                    $script:topWindows += [pscustomobject]@{
                        Handle = $hWnd
                        Title  = $title
                    }
                }
            }

            return $true
        }

        [void][WinApi]::EnumWindows($callback, [IntPtr]::Zero)

        return $script:topWindows
    }

    function Move-WindowHandle {
        param(
            [IntPtr]$Handle,
            [int]$X,
            [int]$Y,
            [int]$Width,
            [int]$Height
        )

        $SW_RESTORE = 9
        $SWP_NOZORDER = 0x0004
        $SWP_SHOWWINDOW = 0x0040

        [void][WinApi]::ShowWindow($Handle, $SW_RESTORE)
        [void][WinApi]::SetWindowPos($Handle, [IntPtr]::Zero, $X, $Y, $Width, $Height, $SWP_NOZORDER -bor $SWP_SHOWWINDOW)
    }

    function Move-WindowByTitle {
        param(
            [string]$TitleRegex,
            [int]$X,
            [int]$Y,
            [int]$Width,
            [int]$Height
        )

        for ($i = 0; $i -lt 40; $i++) {
            Start-Sleep -Milliseconds 250

            $win = Get-TopWindows |
                Where-Object { $_.Title -match $TitleRegex } |
                Select-Object -First 1

            if ($win) {
                Move-WindowHandle -Handle $win.Handle -X $X -Y $Y -Width $Width -Height $Height
                return $true
            }
        }

        return $false
    }

    # Размеры рабочей области экрана
    $screen = [System.Windows.Forms.Screen]::PrimaryScreen.WorkingArea

    $leftX = $screen.X
    $topY = $screen.Y
    $halfWidth = [int]($screen.Width / 2)
    $height = $screen.Height
    $rightX = $screen.X + $halfWidth

    # Рабочий стол и папка Projects
    $desktop = [Environment]::GetFolderPath("Desktop")
    $projects = Join-Path $desktop "Projects"

    if (!(Test-Path -LiteralPath $projects)) {
        New-Item -ItemType Directory -Path $projects | Out-Null
    }

    # Создание файла с сегодняшней датой: 2026-04-27_1.py, 2026-04-27_2.py и т.д.
    $date = Get-Date -Format "yyyy-MM-dd"
    $n = 1

    do {
        $pyFile = Join-Path $projects ("{0}_{1}.py" -f $date, $n)
        $n++
    } while (Test-Path -LiteralPath $pyFile)

    New-Item -ItemType File -Path $pyFile | Out-Null

    # Поиск Chrome
    $pf86 = [Environment]::GetEnvironmentVariable("ProgramFiles(x86)")

    $chromeCandidates = @(
        "$env:ProgramFiles\Google\Chrome\Application\chrome.exe",
        "$pf86\Google\Chrome\Application\chrome.exe",
        "$env:LocalAppData\Google\Chrome\Application\chrome.exe"
    )

    $chrome = $chromeCandidates | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1

    if (!$chrome) {
        $chrome = Find-CommandPath @("chrome.exe")
    }

    if (!$chrome) {
        throw "Google Chrome не найден. Установи Chrome или добавь chrome.exe в PATH."
    }

    # Открытие сайта слева
    Start-Process -FilePath $chrome -ArgumentList @(
        "--new-window",
        "https://kompege.ru",
        "--window-position=$leftX,$topY",
        "--window-size=$halfWidth,$height"
    ) | Out-Null

    Move-WindowByTitle -TitleRegex "Chrome" -X $leftX -Y $topY -Width $halfWidth -Height $height | Out-Null

    # Поиск Python / IDLE
    $pythonExe = $null
    $pythonPrefixArgs = @()

    $pyw = Find-CommandPath @("pyw.exe")
    $py = Find-CommandPath @("py.exe")
    $pythonw = Find-CommandPath @("pythonw.exe")
    $python = Find-CommandPath @("python.exe")

    if ($pyw) {
        $pythonExe = $pyw
        $pythonPrefixArgs = @("-3")
    }
    elseif ($pythonw) {
        $pythonExe = $pythonw
    }
    elseif ($py) {
        $pythonExe = $py
        $pythonPrefixArgs = @("-3")
    }
    elseif ($python) {
        $pythonExe = $python
    }

    if (!$pythonExe) {
        throw "Python не найден. Установи Python с IDLE и поставь галочку 'Add Python to PATH'."
    }

    # Открытие созданного .py файла в IDLE справа
    $quotedPyFile = '"' + $pyFile + '"'
    $idleArgs = $pythonPrefixArgs + @("-m", "idlelib", $quotedPyFile)

    Start-Process -FilePath $pythonExe -ArgumentList $idleArgs | Out-Null

    $fileNameRegex = [regex]::Escape([System.IO.Path]::GetFileName($pyFile))
    Move-WindowByTitle -TitleRegex $fileNameRegex -X $rightX -Y $topY -Width $halfWidth -Height $height | Out-Null
}
catch {
    Add-Type -AssemblyName System.Windows.Forms -ErrorAction SilentlyContinue
    [System.Windows.Forms.MessageBox]::Show($_.Exception.Message, "Ошибка запуска") | Out-Null
}