⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 kceasy.cpp

📁 Last change: 2008-02-03 This is the source code of KCeasy。
💻 CPP
📖 第 1 页 / 共 3 页
字号:
/*
This file is part of KCeasy (http://www.kceasy.com)
Copyright (C) 2002-2004 Markus Kern <mkern@kceasy.com>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
*/
//---------------------------------------------------------------------------
#include <vcl.h>
#include <KCeasy.h>
#pragma hdrstop

#include <stdio.h>
#include "BrowserPage.h"
#include "SearchPage.h"
#include "TransferPage.h"
#include "LibraryPage.h"
#include "PlayerPage.h"
#include "ChatPage.h"
#include "StatusPage.h"
#include "AboutDialog.h"
#include "ConfigDialog.h"
#include "ConfigWizard.h"
#include "UpdateForm.h"
#include "BanlistUpdate.h"
#include "MagnetDialog.h"
#include "SP2Fix.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
#pragma link "ThemeMgr"

TMainForm *MainForm;
TEngine* Engine = NULL;
TFileConfig* Config = NULL;
TPathMapper* PathMapper = NULL;
TBrand* Brand = NULL;
//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent* Owner)
:   TForm(Owner),
    ThemeManager(NULL),
    IconManager(NULL),
    TrayIcon(NULL),
    MessageTarget(NULL),
    ShuttingDown(false),
    PreviousSP2Limit(0)
{
    // load branding stuff
    Brand = TBrand::Create();
    // init PRNG
    Randomize();

    // load configuration
    Config = new TFileConfig();
    Config->SetDefaults(BRAND_DEFAULT_CONFIG);
    // get KCeasy path
    string ConfPath = Application->ExeName.c_str();
    ConfPath.erase(ConfPath.rfind('\\'));
    ConfPath += Brand->ReplaceAppName(AnsiString(KCEASY_CONF_PATH)).c_str();
    Config->SetFilePath(ConfPath.c_str());
    // save defaults if no file exists
    if(!Config->Load(true,true))
        Config->Save();

    // gettext init
    TP_GlobalIgnoreClass(__classid(TCppWebBrowser));
    TP_GlobalIgnoreClass(__classid(TFont));
    TP_GlobalIgnoreClass(__classid(TXiRC));
    UseLanguage(Config->GetValue("gui/language").c_str());
    TranslateComponent(this);

    // customize this form
    Application->Title = Brand->GetAppName();
    Caption = Brand->ReplaceAppName(Caption);
    // MainMenu->AutoHotkeys must be maManual for menus to translate properly
    KCeasyMnu->Caption = Brand->ReplaceAppName(KCeasyMnu->Caption);

    // setup message target for receiving external windows messages
    MessageTarget = new TMessageTarget("MessageTarget",BRAND_EXTERNAL_MSG_TARGET);
    MessageTarget->AddHandler(WM_KCEASY_EXTERNAL_SHOW,ShowMsgHandler);
    MessageTarget->AddHandler(WM_KCEASY_EXTERNAL_SHUTDOWN,ShutdownMsgHandler);

    // support XP alpha icons
    TImageList* OrgImageList = new TImageList(this);
    OrgImageList->Assign(FileImageList);
    FileImageList->Handle = (unsigned int)::ImageList_Create(16,16,ILC_COLOR32 | ILC_MASK,4,4);
    FileImageList->Assign(OrgImageList);
    delete OrgImageList;
    IconManager = new TIconManager(FileImageList);

    // init XP Theme support
    if(Config->GetValueInt("gui/use_themes")) {
        ThemeManager = new TThemeManager(this);
        ThemeManager->CollectForms(NULL);
    }

    // adjust hint times
    Application->HintHidePause = 10000;

    // create tray icon
    if(Config->GetValueInt("gui/minimize_to_tray")) {
        TrayIcon = new TTrayIcon(TrayPopup);
        TrayIcon->SetHint(Brand->GetAppName().c_str());
    }
    WM_TASKBARCREATED = ::RegisterWindowMessage("TaskBarCreated");

    // create engine
    Engine = new TEngine(Brand->GetAppName().c_str(),Brand->GetVersionString().c_str());
    Engine->SetCallbackWnd(this->Handle);
    Engine->Init();

    // load banned words and file extensions
    string Banned = Config->GetValue("search/banned_words");
    Engine->SetBannedWords(string_split(Banned,","));
    Banned = Config->GetValue("search/banned_extensions");
    Engine->SetBannedExtensions(string_split(Banned,","));

    // load path mappings
    PathMapper = new TPathMapper();
    PathMapper->Unserialize(Config->GetValue("gift/mapped_paths"));

    // update run registry key from config file
    if(Config->GetValueInt("gui/run_on_startup"))
        WriteRegKey(Brand->ReplaceAppName(AnsiString(KCEASY_STARTUP_KEY)).c_str(),(Application->ExeName + " /hide").c_str());
    else
        WriteRegKey(Brand->ReplaceAppName(AnsiString(KCEASY_STARTUP_KEY)).c_str(),NULL);

    // if local gift is not configured run config wizard
    if(Engine->GiftInstalled() && !Config->GetValueInt("gift/remote")) {
        if(Engine->GetGiftConf()->GetValueInt("main/setup") == 0) {
            // set complete and incomming dir
            string Path = Engine->GetLauncher()->GetGiftPath() + "\\incoming";
            Engine->GetGiftConf()->SetValue("download/incoming",WindowsToUnixPath(Path));
            Path = Application->ExeName.c_str();
            Path.erase(ConfPath.rfind('\\'));
            Path += "\\My Shared Folder";
            Engine->GetGiftConf()->SetValue("download/completed",WindowsToUnixPath(Path));
            Engine->GetGiftConf()->Save();

            // run wizard, don't allow cancel on first run
            TConfigWizardForm* WizardDlg = new TConfigWizardForm(this,Engine->GetLauncher(),true);

            if(WizardDlg->ShowModal() == mrOk) {
                Engine->GetGiftConf()->SetValueInt("main/setup",1);
                Engine->GetGiftConf()->Save();
            }
            delete WizardDlg;
            ConfigWizardMnu->Enabled = true;

            // run automatic node file update since this is first run after install
            TBanlistUpdateForm* BanlistDialog = new TBanlistUpdateForm(this,true);
            BanlistDialog->ShowModal();
            delete BanlistDialog;
        }

        // decide whether openft is allowed to become a search node
        // FIXME: this is so ugly to have here, needs to be in gift
        unsigned int Uptime = 0;
        list<string> UptimeList = string_split(Config->GetValue("gift/uptime"), ",");
        for(list<string>::iterator itr = UptimeList.begin(); itr != UptimeList.end(); ++itr)
            Uptime += string_to_int(*itr);
        if (!UptimeList.empty())
            Uptime /= UptimeList.size();

        bool GoodSpecs = RunningWindowsNT() &&
                         GetPhysicalMem() >= 400 &&
                         GetCPUSpeed() >= 2000 &&
                         Uptime > 60 && // in minutes
                         Config->GetValueInt("gift/max_downstream") >= 16000 &&
                         Config->GetValueInt("gift/max_upstream") >= 16000;

        TFileConfig *OpenftConf = new TFileConfig(Engine->GetLauncher()->GetConfPath() + "\\OpenFT\\OpenFT.conf");

        if(OpenftConf->Load(true)) {
            OpenftConf->SetValueInt("main/class_allow", GoodSpecs ? 3 : 1);
            OpenftConf->Save();
        }
        delete OpenftConf;

        // enable various local options
        RemoveSharesDbMnu->Enabled = true;
        UpdateBanlistsMnu->Enabled = true;
    } else {
        // gift ist not installed locally, disable menu option for config wizard
        ConfigWizardMnu->Enabled = false;
        RemoveSharesDbMnu->Enabled = false;
        UpdateBanlistsMnu->Enabled = false;
    }

    BrowserForm = new TBrowserForm(this);   BrowserForm->Parent = this;  BrowserForm->Hide();
    SearchForm = new TSearchForm(this);     SearchForm->Parent = this;   SearchForm->Hide();
    TransferForm = new TTransferForm(this); TransferForm->Parent = this; TransferForm->Hide();
    LibraryForm = new TLibraryForm(this);   LibraryForm->Parent = this;  LibraryForm->Hide();
    PlayerForm = new TPlayerForm(this);     PlayerForm->Parent = this;   PlayerForm->Hide();
    ChatForm = new TChatForm(this);         ChatForm->Parent = this;     ChatForm->Hide();
    StatusForm = new TStatusForm(this);     StatusForm->Parent = this;   StatusForm->Hide();

    if(Config->GetValueInt("gui/show_browser_page")) {
        SetVisiblePage(BrowserForm);
    } else {
        BrowserPageBtn->Visible = false;
        SetVisiblePage(NULL);
    }

    if(!Config->GetValueInt("gui/show_chat_page"))
        ChatPageBtn->Visible = false;

    if(!Config->GetValueInt("gui/show_status_page")) {
        StatusPageBtn->Visible = false;
        StatusForm->GiftLoggingBtn->Down = false;
        StatusForm->InterfaceLoggingBtn->Down = false;
    }

    // set main toolbar style
    MainToolBar->List = !Config->GetValueInt("gui/page_icons_above_text");
    for(int i = 0; i < MainToolBar->ButtonCount; i++)
        MainToolBar->Buttons[i]->AutoSize = MainToolBar->List;

    PlayerPanel->Visible = Config->GetValueInt("player/show_bottom_controls");
    BottomSpacerPanel->Visible = PlayerPanel->Visible;

    PlayBtn->OnClick = PlayerForm->PlayBtnClick;
    PauseBtn->OnClick = PlayerForm->PauseBtnClick;
    StopBtn->OnClick = PlayerForm->StopBtnClick;

    ConnectMnu->Enabled = true;
    DisconnectMnu->Enabled = false;
    SearchPageBtn->Enabled = false;
    TransferPageBtn->Enabled = false;
    LibraryPageBtn->Enabled = false;
    PlayerPageBtn->Enabled = false;

    // TRANSLATOR: status bar when offline
    MainStatusBar->Panels->Items[0]->Text = _("Offline");
    // connect to giFT
    ConnectMnu->Click();
    // check for update every update_check_interval days
    unsigned int CheckInterval = Config->GetValueInt("gui/update_check_interval");
    if(CheckInterval)
    {
        FILETIME ft;
        LARGE_INTEGER Now;
        ::GetSystemTimeAsFileTime (&ft);
        Now.LowPart = ft.dwLowDateTime;
        Now.HighPart = ft.dwHighDateTime;
        Now.QuadPart /= 10 * 1000 * 1000; // make secs from 100 nsecs
        Now.QuadPart /= 60 * 60; // make hours from secs

        unsigned int Last = Config->GetValueInt("gui/update_last_check");
        if(((unsigned int)Now.QuadPart) - Last > CheckInterval * 24)
        {
            new TAutoUpdate(Application);
            Config->SetValueInt("gui/update_last_check", (int)Now.LowPart);
        }
    }

    // restore old window position
    list<string> PosList = string_split(Config->GetValue("gui/window_pos"),",");
    if (PosList.size() >= 5) {
        string State = PosList.front(); PosList.pop_front();
        if(State == "minimized" || State == "normal") {
            MainForm->Left = string_to_int(PosList.front()); PosList.pop_front();
            MainForm->Top = string_to_int(PosList.front()); PosList.pop_front();
            MainForm->Width = string_to_int(PosList.front()); PosList.pop_front();
            MainForm->Height = string_to_int(PosList.front()); PosList.pop_front();
        }
        if(State == "minimized")      MainForm->WindowState = wsMinimized;
        else if(State == "maximized") MainForm->WindowState = wsMaximized;
        else                          MainForm->WindowState = wsNormal;
    }

    if(FindCmdLineSwitch("hide", true)) {
        if(TrayIcon) {
//            TrayIcon->HideApp();
            Application->ShowMainForm = false;
        } else
            WindowState = wsMinimized;
    }
}

__fastcall TMainForm::~TMainForm()
{
    BrowserForm->Release();
    SearchForm->Release();
    TransferForm->Release();
    LibraryForm->Release();
    PlayerForm->Release();
    ChatForm->Release();
    StatusForm->Release();

    delete MessageTarget;
    delete TrayIcon;
    delete IconManager;
//    don't delete ThemeManager because it causes an exception, let the parent do it
//    delete ThemeManager;
    delete Engine;
    delete PathMapper;

    Config->Save();
    delete Config;

    delete Brand;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::Dispatch(void *Message)
{
    if(((PMessage)Message)->Msg == WM_TASKBARCREATED)
    {
       WMTaskbarCreated(*((TMessage *)Message));
       return;
    }

    switch (((PMessage)Message)->Msg)
    {
    case WM_ENGINE_CALLBACK:
       WMEngineCallback(*((TMessage *)Message));
       break;
       
    default:
        TForm::Dispatch(Message);
        break;
    }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FormClose(TObject *Sender, TCloseAction &Action)
{
    if(TrayIcon) {
        TrayIcon->HideApp();
        Action = caNone;
    } else {
        ExitMnu->Click();
        Action = caNone;
    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -