summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--plugins/AutoShutdown/common.h93
-rw-r--r--plugins/AutoShutdown/cpuusage.c257
-rw-r--r--plugins/AutoShutdown/cpuusage.h24
-rw-r--r--plugins/AutoShutdown/docs/Info_Src.txt31
-rw-r--r--plugins/AutoShutdown/docs/License_Appendix.txt64
-rw-r--r--plugins/AutoShutdown/docs/Shutdown-Developer.txt49
-rw-r--r--plugins/AutoShutdown/docs/Shutdown-License.txt278
-rw-r--r--plugins/AutoShutdown/docs/Shutdown-Readme.txt329
-rw-r--r--plugins/AutoShutdown/docs/Shutdown-Translation.txt240
-rw-r--r--plugins/AutoShutdown/docs/countdown.wavbin0 -> 654 bytes
-rw-r--r--plugins/AutoShutdown/frame.c644
-rw-r--r--plugins/AutoShutdown/frame.h28
-rw-r--r--plugins/AutoShutdown/m_shutdown.h196
-rw-r--r--plugins/AutoShutdown/main.c192
-rw-r--r--plugins/AutoShutdown/options.c189
-rw-r--r--plugins/AutoShutdown/options.h24
-rw-r--r--plugins/AutoShutdown/res/Thumbs.dbbin0 -> 6144 bytes
-rw-r--r--plugins/AutoShutdown/res/active.icobin0 -> 1406 bytes
-rw-r--r--plugins/AutoShutdown/res/header.icobin0 -> 2238 bytes
-rw-r--r--plugins/AutoShutdown/res/inactive.icobin0 -> 1406 bytes
-rw-r--r--plugins/AutoShutdown/resource.h58
-rw-r--r--plugins/AutoShutdown/resource.rc253
-rw-r--r--plugins/AutoShutdown/settingsdlg.c512
-rw-r--r--plugins/AutoShutdown/settingsdlg.h30
-rw-r--r--plugins/AutoShutdown/shutdown.def11
-rw-r--r--plugins/AutoShutdown/shutdown.dep394
-rw-r--r--plugins/AutoShutdown/shutdown.dsp451
-rw-r--r--plugins/AutoShutdown/shutdown.dsw29
-rw-r--r--plugins/AutoShutdown/shutdown.mak435
-rw-r--r--plugins/AutoShutdown/shutdownsvc.c624
-rw-r--r--plugins/AutoShutdown/shutdownsvc.h29
-rw-r--r--plugins/AutoShutdown/utils.c458
-rw-r--r--plugins/AutoShutdown/utils.h48
-rw-r--r--plugins/AutoShutdown/version.h40
-rw-r--r--plugins/AutoShutdown/version.rc51
-rw-r--r--plugins/AutoShutdown/watcher.c408
-rw-r--r--plugins/AutoShutdown/watcher.h29
-rw-r--r--plugins/AvatarHistory/AvatarDlg.cpp621
-rw-r--r--plugins/AvatarHistory/AvatarHistory.cpp999
-rw-r--r--plugins/AvatarHistory/AvatarHistory.h109
-rw-r--r--plugins/AvatarHistory/AvatarHistory.rc236
-rw-r--r--plugins/AvatarHistory/AvatarHistory.vcxproj564
-rw-r--r--plugins/AvatarHistory/AvatarHistory.vcxproj.filters82
-rw-r--r--plugins/AvatarHistory/AvatarOverlay.icobin0 -> 1150 bytes
-rw-r--r--plugins/AvatarHistory/Docs/avatarhist.pngbin0 -> 25934 bytes
-rw-r--r--plugins/AvatarHistory/Docs/avatarhist_changelog.txt78
-rw-r--r--plugins/AvatarHistory/Docs/avatarhist_readme.txt29
-rw-r--r--plugins/AvatarHistory/Docs/avatarhist_version.txt1
-rw-r--r--plugins/AvatarHistory/Docs/langpack_avatarhist.txt114
-rw-r--r--plugins/AvatarHistory/history.icobin0 -> 1150 bytes
-rw-r--r--plugins/AvatarHistory/icolib.cpp135
-rw-r--r--plugins/AvatarHistory/options.cpp234
-rw-r--r--plugins/AvatarHistory/popup.cpp279
-rw-r--r--plugins/AvatarHistory/popup.h53
-rw-r--r--plugins/AvatarHistory/resource.h88
-rw-r--r--plugins/ExternalAPI/m_HTTPServer.h12
-rw-r--r--plugins/ExternalAPI/m_autoreplacer.h39
-rw-r--r--plugins/ExternalAPI/m_avatarhist.h56
-rw-r--r--plugins/ExternalAPI/m_ftpfile.h119
-rw-r--r--plugins/ExternalAPI/m_hddinfo.h6
-rw-r--r--plugins/ExternalAPI/m_mucc.h189
-rw-r--r--plugins/ExternalAPI/m_sendss.h66
-rw-r--r--plugins/FTPFileYM/common.h129
-rw-r--r--plugins/FTPFileYM/curl/curl.h1919
-rw-r--r--plugins/FTPFileYM/curl/curlbuild.h584
-rw-r--r--plugins/FTPFileYM/curl/curlrules.h249
-rw-r--r--plugins/FTPFileYM/curl/curlver.h70
-rw-r--r--plugins/FTPFileYM/curl/easy.h103
-rw-r--r--plugins/FTPFileYM/curl/mprintf.h82
-rw-r--r--plugins/FTPFileYM/curl/multi.h346
-rw-r--r--plugins/FTPFileYM/curl/stdcheaders.h34
-rw-r--r--plugins/FTPFileYM/curl/typecheck-gcc.h551
-rw-r--r--plugins/FTPFileYM/curl/types.h1
-rw-r--r--plugins/FTPFileYM/dbentry.cpp169
-rw-r--r--plugins/FTPFileYM/dbentry.h51
-rw-r--r--plugins/FTPFileYM/deletetimer.cpp73
-rw-r--r--plugins/FTPFileYM/deletetimer.h47
-rw-r--r--plugins/FTPFileYM/dialog.cpp456
-rw-r--r--plugins/FTPFileYM/dialog.h84
-rw-r--r--plugins/FTPFileYM/docs/ftpfile_licence.txt340
-rw-r--r--plugins/FTPFileYM/docs/ftpfile_readme.txt135
-rw-r--r--plugins/FTPFileYM/docs/ftpfile_translate.txt103
-rw-r--r--plugins/FTPFileYM/ftpfile.cpp634
-rw-r--r--plugins/FTPFileYM/ftpfile.rc317
-rw-r--r--plugins/FTPFileYM/ftpfile_10.vcxproj435
-rw-r--r--plugins/FTPFileYM/ftpfile_10.vcxproj.filters175
-rw-r--r--plugins/FTPFileYM/icons/clear.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/clipboard.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/delete.icobin0 -> 2550 bytes
-rw-r--r--plugins/FTPFileYM/icons/ftp0.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/ftp1.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/ftp2.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/ftp3.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/ftp4.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/menu.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/pause.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/icons/resume.icobin0 -> 1150 bytes
-rw-r--r--plugins/FTPFileYM/job_delete.cpp124
-rw-r--r--plugins/FTPFileYM/job_delete.h50
-rw-r--r--plugins/FTPFileYM/job_generic.cpp255
-rw-r--r--plugins/FTPFileYM/job_generic.h109
-rw-r--r--plugins/FTPFileYM/job_packer.cpp354
-rw-r--r--plugins/FTPFileYM/job_packer.h63
-rw-r--r--plugins/FTPFileYM/job_upload.cpp551
-rw-r--r--plugins/FTPFileYM/job_upload.h84
-rw-r--r--plugins/FTPFileYM/lib/libcurl.dllbin0 -> 1048064 bytes
-rw-r--r--plugins/FTPFileYM/lib/libcurl64.dllbin0 -> 1196032 bytes
-rw-r--r--plugins/FTPFileYM/libcurl.cpp73
-rw-r--r--plugins/FTPFileYM/libcurl.h69
-rw-r--r--plugins/FTPFileYM/manager.cpp449
-rw-r--r--plugins/FTPFileYM/manager.h88
-rw-r--r--plugins/FTPFileYM/mir_db.cpp198
-rw-r--r--plugins/FTPFileYM/mir_db.h57
-rw-r--r--plugins/FTPFileYM/options.cpp310
-rw-r--r--plugins/FTPFileYM/options.h69
-rw-r--r--plugins/FTPFileYM/resource.h101
-rw-r--r--plugins/FTPFileYM/serverlist.cpp113
-rw-r--r--plugins/FTPFileYM/serverlist.h79
-rw-r--r--plugins/FTPFileYM/utils.cpp237
-rw-r--r--plugins/FTPFileYM/utils.h71
-rw-r--r--plugins/FTPFileYM/version.h4
-rw-r--r--plugins/FTPFileYM/version.rc37
-rw-r--r--plugins/FTPFileYM/zip/crypt.h131
-rw-r--r--plugins/FTPFileYM/zip/ioapi.c235
-rw-r--r--plugins/FTPFileYM/zip/ioapi.h200
-rw-r--r--plugins/FTPFileYM/zip/zconf.h416
-rw-r--r--plugins/FTPFileYM/zip/zip.c2004
-rw-r--r--plugins/FTPFileYM/zip/zip.h362
-rw-r--r--plugins/FTPFileYM/zip/zlib.h1605
-rw-r--r--plugins/SendScreenshotPlus/CSend.cpp416
-rw-r--r--plugins/SendScreenshotPlus/CSend.h113
-rw-r--r--plugins/SendScreenshotPlus/CSendEmail.cpp221
-rw-r--r--plugins/SendScreenshotPlus/CSendEmail.h63
-rw-r--r--plugins/SendScreenshotPlus/CSendFTPFile.cpp99
-rw-r--r--plugins/SendScreenshotPlus/CSendFTPFile.h59
-rw-r--r--plugins/SendScreenshotPlus/CSendFile.cpp53
-rw-r--r--plugins/SendScreenshotPlus/CSendFile.h55
-rw-r--r--plugins/SendScreenshotPlus/CSendHTTPServer.cpp143
-rw-r--r--plugins/SendScreenshotPlus/CSendHTTPServer.h67
-rw-r--r--plugins/SendScreenshotPlus/CSendImageShack.cpp299
-rw-r--r--plugins/SendScreenshotPlus/CSendImageShack.h77
-rw-r--r--plugins/SendScreenshotPlus/Main.cpp406
-rw-r--r--plugins/SendScreenshotPlus/Main.h65
-rw-r--r--plugins/SendScreenshotPlus/SendSS_9.vcproj621
-rw-r--r--plugins/SendScreenshotPlus/UAboutForm.cpp212
-rw-r--r--plugins/SendScreenshotPlus/UAboutForm.h69
-rw-r--r--plugins/SendScreenshotPlus/UMainForm.cpp1180
-rw-r--r--plugins/SendScreenshotPlus/UMainForm.h157
-rw-r--r--plugins/SendScreenshotPlus/Utils.cpp579
-rw-r--r--plugins/SendScreenshotPlus/Utils.h81
-rw-r--r--plugins/SendScreenshotPlus/ctrl_button.cpp699
-rw-r--r--plugins/SendScreenshotPlus/ctrl_button.h43
-rw-r--r--plugins/SendScreenshotPlus/dlg_msgbox.cpp854
-rw-r--r--plugins/SendScreenshotPlus/dlg_msgbox.h108
-rw-r--r--plugins/SendScreenshotPlus/global.h196
-rw-r--r--plugins/SendScreenshotPlus/mir_icolib.cpp382
-rw-r--r--plugins/SendScreenshotPlus/mir_icolib.h139
-rw-r--r--plugins/SendScreenshotPlus/mir_string.cpp179
-rw-r--r--plugins/SendScreenshotPlus/mir_string.h129
-rw-r--r--plugins/SendScreenshotPlus/res/UEditForm_nvr_1.bmpbin0 -> 12342 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/UEditForm_nvr_2.bmpbin0 -> 596 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/credits.txt10
-rw-r--r--plugins/SendScreenshotPlus/res/license.txt15
-rw-r--r--plugins/SendScreenshotPlus/res/overlay_disabled.icobin0 -> 1150 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/overlay_enabled.icobin0 -> 1150 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssArrow_Left.icobin0 -> 6830 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssArrow_Right.icobin0 -> 6830 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssCamera_1.icobin0 -> 6830 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssCamera_2.icobin0 -> 2550 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssDefault.icobin0 -> 1406 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssDelOff.icobin0 -> 6830 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssDelOn.icobin0 -> 6830 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssDeskOff.icobin0 -> 6830 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssDeskOn.icobin0 -> 6830 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssMonitor.icobin0 -> 6830 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssOpen.icobin0 -> 5430 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/ssTarget.icobin0 -> 766 bytes
-rw-r--r--plugins/SendScreenshotPlus/res/sshelp.icobin0 -> 2550 bytes
-rw-r--r--plugins/SendScreenshotPlus/resource.h102
-rw-r--r--plugins/SendScreenshotPlus/resource.rc274
-rw-r--r--plugins/SendScreenshotPlus/resource_6.rc2
-rw-r--r--plugins/SendScreenshotPlus/sdk/DevKey.h3
-rw-r--r--plugins/SendScreenshotPlus/sdk/icons.h112
-rw-r--r--plugins/SendScreenshotPlus/version.h45
-rw-r--r--plugins/SendScreenshotPlus/version.rc38
-rw-r--r--plugins/ShlExt/clean.bat1
-rw-r--r--plugins/ShlExt/docs/HowToBuild.txt22
-rw-r--r--plugins/ShlExt/docs/shlext release notes.txt344
-rw-r--r--plugins/ShlExt/inc/README.txt92
-rw-r--r--plugins/ShlExt/inc/m_addcontact.inc54
-rw-r--r--plugins/ShlExt/inc/m_api.pas75
-rw-r--r--plugins/ShlExt/inc/m_awaymsg.inc40
-rw-r--r--plugins/ShlExt/inc/m_clc.inc284
-rw-r--r--plugins/ShlExt/inc/m_clist.inc641
-rw-r--r--plugins/ShlExt/inc/m_clui.inc215
-rw-r--r--plugins/ShlExt/inc/m_contacts.inc90
-rw-r--r--plugins/ShlExt/inc/m_database.inc654
-rw-r--r--plugins/ShlExt/inc/m_email.inc39
-rw-r--r--plugins/ShlExt/inc/m_file.inc66
-rw-r--r--plugins/ShlExt/inc/m_findadd.inc38
-rw-r--r--plugins/ShlExt/inc/m_globaldefs.pas99
-rw-r--r--plugins/ShlExt/inc/m_globaldefs.ppubin0 -> 8913 bytes
-rw-r--r--plugins/ShlExt/inc/m_helpers.inc613
-rw-r--r--plugins/ShlExt/inc/m_history.inc37
-rw-r--r--plugins/ShlExt/inc/m_icq.inc191
-rw-r--r--plugins/ShlExt/inc/m_ignore.inc74
-rw-r--r--plugins/ShlExt/inc/m_langpack.inc82
-rw-r--r--plugins/ShlExt/inc/m_message.inc57
-rw-r--r--plugins/ShlExt/inc/m_netlib.inc713
-rw-r--r--plugins/ShlExt/inc/m_options.inc109
-rw-r--r--plugins/ShlExt/inc/m_plugins.inc70
-rw-r--r--plugins/ShlExt/inc/m_popup.inc222
-rw-r--r--plugins/ShlExt/inc/m_protocols.inc180
-rw-r--r--plugins/ShlExt/inc/m_protomod.inc105
-rw-r--r--plugins/ShlExt/inc/m_protosvc.inc753
-rw-r--r--plugins/ShlExt/inc/m_skin.inc120
-rw-r--r--plugins/ShlExt/inc/m_system.inc170
-rw-r--r--plugins/ShlExt/inc/m_url.inc39
-rw-r--r--plugins/ShlExt/inc/m_userinfo.inc84
-rw-r--r--plugins/ShlExt/inc/m_utils.inc279
-rw-r--r--plugins/ShlExt/inc/m_v8.inc62
-rw-r--r--plugins/ShlExt/inc/newpluginapi.inc94
-rw-r--r--plugins/ShlExt/inc/statusmodes.inc54
-rw-r--r--plugins/ShlExt/inc/testdll.dpr60
-rw-r--r--plugins/ShlExt/make.bat9
-rw-r--r--plugins/ShlExt/resource.h13
-rw-r--r--plugins/ShlExt/shlc.inc168
-rw-r--r--plugins/ShlExt/shlcom.pas2383
-rw-r--r--plugins/ShlExt/shldlgs.rc93
-rw-r--r--plugins/ShlExt/shldlgs.resbin0 -> 2616 bytes
-rw-r--r--plugins/ShlExt/shlext.dpr379
-rw-r--r--plugins/ShlExt/shlicons.pas162
-rw-r--r--plugins/ShlExt/shlipc.pas369
-rw-r--r--plugins/SmartAutoReplier/ActionsHandler.cpp31
-rw-r--r--plugins/SmartAutoReplier/ActionsHandler.h30
-rw-r--r--plugins/SmartAutoReplier/AggressiveOptimize.h59
-rw-r--r--plugins/SmartAutoReplier/Crc32Static.cpp139
-rw-r--r--plugins/SmartAutoReplier/Crc32Static.h33
-rw-r--r--plugins/SmartAutoReplier/CrushLog.cpp165
-rw-r--r--plugins/SmartAutoReplier/CrushLog.h54
-rw-r--r--plugins/SmartAutoReplier/GUI/AddRuleDlg.cpp219
-rw-r--r--plugins/SmartAutoReplier/GUI/AddRuleDlg.h67
-rw-r--r--plugins/SmartAutoReplier/GUI/EditReplyDlg.cpp88
-rw-r--r--plugins/SmartAutoReplier/GUI/EditReplyDlg.h55
-rw-r--r--plugins/SmartAutoReplier/GUI/OptionsDlg.cpp528
-rw-r--r--plugins/SmartAutoReplier/GUI/OptionsDlg.h119
-rw-r--r--plugins/SmartAutoReplier/GUI/SelectUserDlg.cpp109
-rw-r--r--plugins/SmartAutoReplier/GUI/SelectUserDlg.h58
-rw-r--r--plugins/SmartAutoReplier/GUI/SettingsDlgHolder.cpp207
-rw-r--r--plugins/SmartAutoReplier/GUI/SettingsDlgHolder.h69
-rw-r--r--plugins/SmartAutoReplier/Interfaces/ISettings.h34
-rw-r--r--plugins/SmartAutoReplier/Interfaces/ISingletone.h35
-rw-r--r--plugins/SmartAutoReplier/LuaBridge.cpp127
-rw-r--r--plugins/SmartAutoReplier/LuaBridge.h96
-rw-r--r--plugins/SmartAutoReplier/LuaScript.cpp215
-rw-r--r--plugins/SmartAutoReplier/LuaScript.h68
-rw-r--r--plugins/SmartAutoReplier/MessagesHandler.cpp469
-rw-r--r--plugins/SmartAutoReplier/MessagesHandler.h72
-rw-r--r--plugins/SmartAutoReplier/ModeMessHandler.cpp119
-rw-r--r--plugins/SmartAutoReplier/ModeMessHandler.h34
-rw-r--r--plugins/SmartAutoReplier/RuleItem.h47
-rw-r--r--plugins/SmartAutoReplier/RulesStorage.cpp536
-rw-r--r--plugins/SmartAutoReplier/RulesStorage.h63
-rw-r--r--plugins/SmartAutoReplier/SAR.cpp462
-rw-r--r--plugins/SmartAutoReplier/SAR.rc274
-rw-r--r--plugins/SmartAutoReplier/SAR.sln25
-rw-r--r--plugins/SmartAutoReplier/SAR.vcxproj189
-rw-r--r--plugins/SmartAutoReplier/SAR.vcxproj.filters77
-rw-r--r--plugins/SmartAutoReplier/SarLuaScript.cpp358
-rw-r--r--plugins/SmartAutoReplier/SarLuaScript.h57
-rw-r--r--plugins/SmartAutoReplier/ScriptsReader.cpp175
-rw-r--r--plugins/SmartAutoReplier/ScriptsReader.h57
-rw-r--r--plugins/SmartAutoReplier/SettingsHandler.cpp204
-rw-r--r--plugins/SmartAutoReplier/SettingsHandler.h96
-rw-r--r--plugins/SmartAutoReplier/comfunc.cpp74
-rw-r--r--plugins/SmartAutoReplier/comfunc.h26
-rw-r--r--plugins/SmartAutoReplier/comlogging.h42
-rw-r--r--plugins/SmartAutoReplier/luainc.h31
-rw-r--r--plugins/SmartAutoReplier/lualib/ReadMe.txt37
-rw-r--r--plugins/SmartAutoReplier/lualib/lapi.c922
-rw-r--r--plugins/SmartAutoReplier/lualib/lapi.h16
-rw-r--r--plugins/SmartAutoReplier/lualib/lauxlib.c591
-rw-r--r--plugins/SmartAutoReplier/lualib/lauxlib.h145
-rw-r--r--plugins/SmartAutoReplier/lualib/lbaselib.c674
-rw-r--r--plugins/SmartAutoReplier/lualib/lcode.c714
-rw-r--r--plugins/SmartAutoReplier/lualib/lcode.h74
-rw-r--r--plugins/SmartAutoReplier/lualib/ldblib.c299
-rw-r--r--plugins/SmartAutoReplier/lualib/ldebug.c585
-rw-r--r--plugins/SmartAutoReplier/lualib/ldebug.h31
-rw-r--r--plugins/SmartAutoReplier/lualib/ldo.c458
-rw-r--r--plugins/SmartAutoReplier/lualib/ldo.h60
-rw-r--r--plugins/SmartAutoReplier/lualib/ldump.c170
-rw-r--r--plugins/SmartAutoReplier/lualib/lfunc.c135
-rw-r--r--plugins/SmartAutoReplier/lualib/lfunc.h25
-rw-r--r--plugins/SmartAutoReplier/lualib/lgc.c493
-rw-r--r--plugins/SmartAutoReplier/lualib/lgc.h25
-rw-r--r--plugins/SmartAutoReplier/lualib/liolib.c750
-rw-r--r--plugins/SmartAutoReplier/lualib/llex.c417
-rw-r--r--plugins/SmartAutoReplier/lualib/llex.h75
-rw-r--r--plugins/SmartAutoReplier/lualib/llimits.h185
-rw-r--r--plugins/SmartAutoReplier/lualib/lmathlib.c246
-rw-r--r--plugins/SmartAutoReplier/lualib/lmem.c91
-rw-r--r--plugins/SmartAutoReplier/lualib/lmem.h44
-rw-r--r--plugins/SmartAutoReplier/lualib/loadlib.c205
-rw-r--r--plugins/SmartAutoReplier/lualib/lobject.c195
-rw-r--r--plugins/SmartAutoReplier/lualib/lobject.h336
-rw-r--r--plugins/SmartAutoReplier/lualib/lopcodes.c102
-rw-r--r--plugins/SmartAutoReplier/lualib/lopcodes.h238
-rw-r--r--plugins/SmartAutoReplier/lualib/lparser.c1329
-rw-r--r--plugins/SmartAutoReplier/lualib/lparser.h71
-rw-r--r--plugins/SmartAutoReplier/lualib/lstate.c220
-rw-r--r--plugins/SmartAutoReplier/lualib/lstate.h195
-rw-r--r--plugins/SmartAutoReplier/lualib/lstring.c102
-rw-r--r--plugins/SmartAutoReplier/lualib/lstring.h33
-rw-r--r--plugins/SmartAutoReplier/lualib/lstrlib.c770
-rw-r--r--plugins/SmartAutoReplier/lualib/ltable.c509
-rw-r--r--plugins/SmartAutoReplier/lualib/ltable.h31
-rw-r--r--plugins/SmartAutoReplier/lualib/ltablib.c250
-rw-r--r--plugins/SmartAutoReplier/lualib/ltests.c852
-rw-r--r--plugins/SmartAutoReplier/lualib/ltm.c70
-rw-r--r--plugins/SmartAutoReplier/lualib/ltm.h51
-rw-r--r--plugins/SmartAutoReplier/lualib/lua.h391
-rw-r--r--plugins/SmartAutoReplier/lualib/luainc.h12
-rw-r--r--plugins/SmartAutoReplier/lualib/lualib.h56
-rw-r--r--plugins/SmartAutoReplier/lualib/lualib.vcxproj138
-rw-r--r--plugins/SmartAutoReplier/lualib/lualib.vcxproj.filters186
-rw-r--r--plugins/SmartAutoReplier/lualib/lundump.c286
-rw-r--r--plugins/SmartAutoReplier/lualib/lundump.h34
-rw-r--r--plugins/SmartAutoReplier/lualib/lvm.c780
-rw-r--r--plugins/SmartAutoReplier/lualib/lvm.h35
-rw-r--r--plugins/SmartAutoReplier/lualib/lzio.c81
-rw-r--r--plugins/SmartAutoReplier/lualib/lzio.h64
-rw-r--r--plugins/SmartAutoReplier/lualib/targetver.h8
-rw-r--r--plugins/SmartAutoReplier/resource.h52
-rw-r--r--plugins/SmartAutoReplier/sar.icobin0 -> 318 bytes
-rw-r--r--plugins/SmartAutoReplier/stdafx.cpp27
-rw-r--r--plugins/SmartAutoReplier/stdafx.h74
-rw-r--r--plugins/SmartAutoReplier/wtl/atlapp.h2035
-rw-r--r--plugins/SmartAutoReplier/wtl/atlcrack.h2384
-rw-r--r--plugins/SmartAutoReplier/wtl/atlctrls.h10041
-rw-r--r--plugins/SmartAutoReplier/wtl/atlctrlw.h4157
-rw-r--r--plugins/SmartAutoReplier/wtl/atlctrlx.h5004
-rw-r--r--plugins/SmartAutoReplier/wtl/atlddx.h679
-rw-r--r--plugins/SmartAutoReplier/wtl/atldlgs.h6403
-rw-r--r--plugins/SmartAutoReplier/wtl/atldwm.h461
-rw-r--r--plugins/SmartAutoReplier/wtl/atlfind.h1032
-rw-r--r--plugins/SmartAutoReplier/wtl/atlframe.h3688
-rw-r--r--plugins/SmartAutoReplier/wtl/atlgdi.h3891
-rw-r--r--plugins/SmartAutoReplier/wtl/atlmisc.h3817
-rw-r--r--plugins/SmartAutoReplier/wtl/atlprint.h1109
-rw-r--r--plugins/SmartAutoReplier/wtl/atlres.h263
-rw-r--r--plugins/SmartAutoReplier/wtl/atlresce.h93
-rw-r--r--plugins/SmartAutoReplier/wtl/atlribbon.h3446
-rw-r--r--plugins/SmartAutoReplier/wtl/atlscrl.h2011
-rw-r--r--plugins/SmartAutoReplier/wtl/atlsplit.h917
-rw-r--r--plugins/SmartAutoReplier/wtl/atltheme.h1218
-rw-r--r--plugins/SmartAutoReplier/wtl/atluser.h1391
-rw-r--r--plugins/SmartAutoReplier/wtl/atlwince.h2987
-rw-r--r--plugins/SmartAutoReplier/wtl/atlwinx.h525
-rw-r--r--plugins/XSoundNotify/DebugLogger.hpp91
-rw-r--r--plugins/XSoundNotify/EventProcessor.cpp84
-rw-r--r--plugins/XSoundNotify/EventProcessor.h27
-rw-r--r--plugins/XSoundNotify/README1
-rw-r--r--plugins/XSoundNotify/SettingsDialog.cpp124
-rw-r--r--plugins/XSoundNotify/SettingsDialog.h60
-rw-r--r--plugins/XSoundNotify/SoundNotifyData.cpp37
-rw-r--r--plugins/XSoundNotify/SoundNotifyData.h33
-rw-r--r--plugins/XSoundNotify/SoundNotifyDataStorage.cpp74
-rw-r--r--plugins/XSoundNotify/SoundNotifyDataStorage.h34
-rw-r--r--plugins/XSoundNotify/XSound Notify Miranda Plugin.sln20
-rw-r--r--plugins/XSoundNotify/XSoundNotify.rcbin0 -> 5494 bytes
-rw-r--r--plugins/XSoundNotify/resource.hbin0 -> 1556 bytes
-rw-r--r--plugins/XSoundNotify/testplug.vcxproj167
-rw-r--r--plugins/XSoundNotify/xsn_main.cpp122
-rw-r--r--plugins/XSoundNotify/xsn_types.cpp32
-rw-r--r--plugins/XSoundNotify/xsn_types.h33
-rw-r--r--plugins/XSoundNotify/xsn_utils.cpp60
-rw-r--r--plugins/XSoundNotify/xsn_utils.h18
-rw-r--r--protocols/Tlen/codec/gsm.h65
-rw-r--r--protocols/Tlen/codec/gsm_codec.c283
-rw-r--r--protocols/Tlen/codec/gsm_long.c183
-rw-r--r--protocols/Tlen/codec/gsm_lpc.c208
-rw-r--r--protocols/Tlen/codec/gsm_preprocess.c103
-rw-r--r--protocols/Tlen/codec/gsm_rpe.c248
-rw-r--r--protocols/Tlen/codec/gsm_short.c211
-rw-r--r--protocols/Tlen/commons.h32
-rw-r--r--protocols/Tlen/crypto/aes.c1336
-rw-r--r--protocols/Tlen/crypto/bignum.c2097
-rw-r--r--protocols/Tlen/crypto/padlock.c162
-rw-r--r--protocols/Tlen/crypto/polarssl/aes.h167
-rw-r--r--protocols/Tlen/crypto/polarssl/bignum.h587
-rw-r--r--protocols/Tlen/crypto/polarssl/bn_mul.h738
-rw-r--r--protocols/Tlen/crypto/polarssl/config.h625
-rw-r--r--protocols/Tlen/crypto/polarssl/padlock.h100
-rw-r--r--protocols/Tlen/docs/InstallScript.xml27
-rw-r--r--protocols/Tlen/docs/changelog_tlen.txt269
-rw-r--r--protocols/Tlen/docs/gpl.txt340
-rw-r--r--protocols/Tlen/docs/gpl_comment.txt20
-rw-r--r--protocols/Tlen/docs/readme_tlen.txt60
-rw-r--r--protocols/Tlen/docs/tlen-translation.txt153
-rw-r--r--protocols/Tlen/icos/auth_grant.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/auth_request.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/groupchats.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/image.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/mail.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/microphone.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/speaker.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/tlen.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/tlenchats.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/icos/voicechat.icobin0 -> 2550 bytes
-rw-r--r--protocols/Tlen/jabber.h438
-rw-r--r--protocols/Tlen/jabber_iq.c114
-rw-r--r--protocols/Tlen/jabber_iq.h61
-rw-r--r--protocols/Tlen/jabber_iqid.c629
-rw-r--r--protocols/Tlen/jabber_list.c314
-rw-r--r--protocols/Tlen/jabber_list.h90
-rw-r--r--protocols/Tlen/jabber_misc.c219
-rw-r--r--protocols/Tlen/jabber_opt.c708
-rw-r--r--protocols/Tlen/jabber_svc.c1300
-rw-r--r--protocols/Tlen/jabber_thread.c1465
-rw-r--r--protocols/Tlen/jabber_util.c635
-rw-r--r--protocols/Tlen/jabber_ws.c159
-rw-r--r--protocols/Tlen/jabber_xml.c568
-rw-r--r--protocols/Tlen/jabber_xml.h78
-rw-r--r--protocols/Tlen/resource.h147
-rw-r--r--protocols/Tlen/tlen.c636
-rw-r--r--protocols/Tlen/tlen.rc439
-rw-r--r--protocols/Tlen/tlen_10.sln44
-rw-r--r--protocols/Tlen/tlen_10.vcxproj928
-rw-r--r--protocols/Tlen/tlen_advsearch.c113
-rw-r--r--protocols/Tlen/tlen_avatar.c422
-rw-r--r--protocols/Tlen/tlen_avatar.h34
-rw-r--r--protocols/Tlen/tlen_czaty/AdminWindow.cpp490
-rw-r--r--protocols/Tlen/tlen_czaty/AdminWindow.h63
-rw-r--r--protocols/Tlen/tlen_czaty/ChatContainer.cpp480
-rw-r--r--protocols/Tlen/tlen_czaty/ChatContainer.h100
-rw-r--r--protocols/Tlen/tlen_czaty/ChatEvent.cpp174
-rw-r--r--protocols/Tlen/tlen_czaty/ChatEvent.h60
-rw-r--r--protocols/Tlen/tlen_czaty/ChatGroup.cpp99
-rw-r--r--protocols/Tlen/tlen_czaty/ChatGroup.h55
-rw-r--r--protocols/Tlen/tlen_czaty/ChatRoom.cpp68
-rw-r--r--protocols/Tlen/tlen_czaty/ChatRoom.h51
-rw-r--r--protocols/Tlen/tlen_czaty/ChatUser.cpp83
-rw-r--r--protocols/Tlen/tlen_czaty/ChatUser.h49
-rw-r--r--protocols/Tlen/tlen_czaty/ChatWindow.cpp2108
-rw-r--r--protocols/Tlen/tlen_czaty/ChatWindow.h196
-rw-r--r--protocols/Tlen/tlen_czaty/FontList.cpp206
-rw-r--r--protocols/Tlen/tlen_czaty/FontList.h90
-rw-r--r--protocols/Tlen/tlen_czaty/HelperDialog.cpp589
-rw-r--r--protocols/Tlen/tlen_czaty/HelperDialog.h95
-rw-r--r--protocols/Tlen/tlen_czaty/ManagerWindow.cpp1067
-rw-r--r--protocols/Tlen/tlen_czaty/ManagerWindow.h93
-rw-r--r--protocols/Tlen/tlen_czaty/Options.cpp789
-rw-r--r--protocols/Tlen/tlen_czaty/Options.h75
-rw-r--r--protocols/Tlen/tlen_czaty/Utils.cpp138
-rw-r--r--protocols/Tlen/tlen_czaty/Utils.h38
-rw-r--r--protocols/Tlen/tlen_czaty/icos/admin.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/administration.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/blank.icobin0 -> 318 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/bold.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/chat.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/delete.icobin0 -> 1406 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/glowner.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/invite.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/italic.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/message.icobin0 -> 1406 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/next.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/options.icobin0 -> 1406 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/owner.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/prev.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/r_anon.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/r_memb.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/r_mod.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/registered.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/save.icobin0 -> 318 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/search.icobin0 -> 1406 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/sendmail.icobin0 -> 1406 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/smile.icobin0 -> 1406 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/tlenbig.icobin0 -> 2238 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/tlensmall.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/icos/underline.icobin0 -> 894 bytes
-rw-r--r--protocols/Tlen/tlen_czaty/mucc.cpp188
-rw-r--r--protocols/Tlen/tlen_czaty/mucc.h106
-rw-r--r--protocols/Tlen/tlen_czaty/mucc.rc579
-rw-r--r--protocols/Tlen/tlen_czaty/mucc.sln43
-rw-r--r--protocols/Tlen/tlen_czaty/mucc.vcxproj1245
-rw-r--r--protocols/Tlen/tlen_czaty/mucc_services.cpp140
-rw-r--r--protocols/Tlen/tlen_czaty/mucc_services.h35
-rw-r--r--protocols/Tlen/tlen_czaty/resource.h218
-rw-r--r--protocols/Tlen/tlen_file.c718
-rw-r--r--protocols/Tlen/tlen_file.h34
-rw-r--r--protocols/Tlen/tlen_muc.c1071
-rw-r--r--protocols/Tlen/tlen_muc.h45
-rw-r--r--protocols/Tlen/tlen_p2p_new.c361
-rw-r--r--protocols/Tlen/tlen_p2p_old.c536
-rw-r--r--protocols/Tlen/tlen_p2p_old.h66
-rw-r--r--protocols/Tlen/tlen_picture.c320
-rw-r--r--protocols/Tlen/tlen_picture.h41
-rw-r--r--protocols/Tlen/tlen_presence.c314
-rw-r--r--protocols/Tlen/tlen_presence.h37
-rw-r--r--protocols/Tlen/tlen_userinfo.c335
-rw-r--r--protocols/Tlen/tlen_voice.c1122
-rw-r--r--protocols/Tlen/tlen_voice.h68
503 files changed, 157194 insertions, 0 deletions
diff --git a/plugins/AutoShutdown/common.h b/plugins/AutoShutdown/common.h
new file mode 100644
index 0000000000..eec97b0873
--- /dev/null
+++ b/plugins/AutoShutdown/common.h
@@ -0,0 +1,93 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include <stdio.h> /* for mir_sntprintf() */
+#include <time.h> /* for mktime(),time() */
+#include <wchar.h> /* for _itow() */
+#include <tchar.h>
+
+#define _WIN32_WINNT 0x0700
+#define __RPCASYNC_H__ /* VC6 shows warning there */
+#include <windows.h>
+#pragma warning(disable:4201) /* nonstandard extension used : nameless struct/union */
+#include <commctrl.h>
+#pragma warning(default:4201) /* nonstandard extension used : nameless struct/union */
+#include <win2k.h>
+
+/* WinXP+: shutdown reason codes */
+#if defined(EWX_RESTARTAPPS) /* new MS Platform SDK */
+ #include <reason.h>
+#else
+ #define SHTDN_REASON_MAJOR_OTHER 0x00000000
+ #define SHTDN_REASON_MINOR_OTHER 0x00000000
+ #define SHTDN_REASON_FLAG_PLANNED 0x80000000
+#endif
+
+/* RAS */
+#undef WINVER
+#define WINVER 0x400 /* prevent INVALID_BUFFER error */
+#include <ras.h> /* for RasEnumConnections(), RasHangUp() */
+#include <raserror.h> /* error codes for RAS */
+
+#define MIRANDA_VER 0x0702
+#include <newpluginapi.h>
+#include <m_utils.h>
+#include <m_database.h>
+#include <m_clist.h>
+#include <m_clui.h>
+#include <m_langpack.h>
+#include <m_system.h>
+#include <m_skin.h>
+#include <m_protosvc.h>
+#include <m_protocols.h>
+#include <m_plugins.h>
+#include <m_options.h>
+#include <m_message.h>
+#include <m_file.h>
+#include <m_idle.h>
+#include <m_weather.h>
+#include <m_hddinfo.h>
+#include <m_cluiframes.h>
+#include <m_clistint.h>
+#include <m_toptoolbar.h>
+#include <m_fontservice.h>
+#include <m_hotkey.h>
+#include <m_hotkeysplus.h>
+#include <m_hotkeysservice.h>
+#include <m_icolib.h>
+#include <m_clc.h>
+#include <m_genmenu.h>
+#include <m_trigger.h>
+#include <m_mwclc.h>
+#include <m_button.h>
+#include <m_autoreplacer.h>
+#include <m_magneticwindows.h>
+#include <m_snappingwindows.h>
+
+#include "m_shutdown.h"
+#include "cpuusage.h"
+#include "frame.h"
+#include "options.h"
+#include "settingsdlg.h"
+#include "shutdownsvc.h"
+#include "utils.h"
+#include "watcher.h"
+#include "resource.h"
diff --git a/plugins/AutoShutdown/cpuusage.c b/plugins/AutoShutdown/cpuusage.c
new file mode 100644
index 0000000000..1270fe02ec
--- /dev/null
+++ b/plugins/AutoShutdown/cpuusage.c
@@ -0,0 +1,257 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include "common.h"
+
+/************************* Stat Switch ********************************/
+
+#define Li2Double(x) ((double)((x).HighPart)*4.294967296E9+(double)((x).LowPart))
+
+static BOOL WinNT_PerfStatsSwitch(TCHAR *pszServiceName,BOOL fDisable)
+{
+ HKEY hKeyServices,hKeyService,hKeyPerf;
+ DWORD dwData,dwDataSize;
+ BOOL fSwitched=FALSE;
+ /* Win2000+ */
+ if(!RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("System\\CurrentControlSet\\Services"),0,KEY_QUERY_VALUE|KEY_SET_VALUE,&hKeyServices)) {
+ if(!RegOpenKeyEx(hKeyServices,pszServiceName,0,KEY_QUERY_VALUE|KEY_SET_VALUE,&hKeyService)) {
+ if(!RegOpenKeyEx(hKeyService,_T("Performance"),0,KEY_QUERY_VALUE|KEY_SET_VALUE,&hKeyPerf)) {
+ dwDataSize=sizeof(DWORD);
+ if(!RegQueryValueEx(hKeyPerf,_T("Disable Performance Counters"),NULL,NULL,(BYTE*)&dwData,&dwDataSize))
+ if((dwData!=0)!=fDisable)
+ fSwitched=!RegSetValueEx(hKeyPerf,_T("Disable Performance Counters"),0,REG_DWORD,(BYTE*)&fDisable,dwDataSize);
+ RegCloseKey(hKeyPerf);
+ }
+ RegCloseKey(hKeyService);
+ }
+ RegCloseKey(hKeyServices);
+ }
+ return fSwitched;
+}
+
+#if !defined(_UNICODE)
+static void Win9x_PerfStatsSwitch(HKEY hKey,char *pszAction,char *pszName)
+{
+ DWORD dwData,dwSize;
+ dwSize=sizeof(dwData);
+ if(!RegOpenKeyExA(hKey,pszAction,0,KEY_QUERY_VALUE,&hKey)) {
+ /* a simple query does the trick (data and size must not be NULL!) */
+ RegQueryValueExA(hKey,pszName,NULL,NULL,(BYTE*)&dwData,&dwSize);
+ RegCloseKey(hKey);
+ }
+}
+#endif
+
+/************************* Poll Thread ********************************/
+
+struct CpuUsageThreadParams {
+ DWORD dwDelayMillis;
+ CPUUSAGEAVAILPROC pfnDataAvailProc;
+ LPARAM lParam;
+ HANDLE hFirstEvent;
+ DWORD *pidThread;
+};
+
+static BOOL CallBackAndWait(struct CpuUsageThreadParams *param,BYTE nCpuUsage)
+{
+ if(param->hFirstEvent!=NULL) {
+ /* return value for PollCpuUsage() */
+ *param->pidThread=GetCurrentThreadId();
+ SetEvent(param->hFirstEvent);
+ param->hFirstEvent=NULL;
+ /* lower priority after first call */
+ SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_IDLE);
+ }
+ if(!param->pfnDataAvailProc(nCpuUsage,param->lParam)) return FALSE;
+ SleepEx(param->dwDelayMillis,TRUE);
+ return !Miranda_Terminated();
+}
+
+#if !defined(_UNICODE)
+static void Win9x_PollThread(struct CpuUsageThreadParams *param)
+{
+ HKEY hKeyStats,hKeyData;
+ DWORD dwBufferSize,dwData;
+
+ if(!RegOpenKeyExA(HKEY_DYN_DATA,"PerfStats",0,KEY_QUERY_VALUE,&hKeyStats)) {
+ /* start query */
+ /* not needed for kernel
+ * Win9x_PerfStatsSwitch(hKeyStats,"StartSrv","KERNEL"); */
+ Win9x_PerfStatsSwitch(hKeyStats,"StartStat","KERNEL\\CPUUsage");
+ /* retrieve cpu usage */
+ if(!RegOpenKeyExA(hKeyStats,"StatData",0,KEY_QUERY_VALUE,&hKeyData)) {
+ dwBufferSize=sizeof(dwData);
+ while(!RegQueryValueExA(hKeyData,"KERNEL\\CPUUsage",NULL,NULL,(BYTE*)&dwData,&dwBufferSize)) {
+ dwBufferSize=sizeof(dwData);
+ if(!CallBackAndWait(param,(BYTE)dwData)) break;
+ }
+ RegCloseKey(hKeyData);
+ }
+ /* stop query */
+ Win9x_PerfStatsSwitch(hKeyStats,"StopStat","KERNEL\\CPUUsage");
+ /* not needed for kernel
+ * Win9x_PerfStatsSwitch(hKeyStats,"StopSrv","KERNEL"); */
+ RegCloseKey(hKeyStats);
+ }
+ /* return error for PollCpuUsage() if never succeeded */
+ if(param->hFirstEvent!=NULL) SetEvent(param->hFirstEvent);
+ mir_free(param);
+}
+#endif /* !_UNICODE */
+
+static void WinNT_PollThread(struct CpuUsageThreadParams *param)
+{
+ DWORD dwBufferSize=0,dwCount;
+ BYTE *pBuffer=NULL;
+ PERF_DATA_BLOCK *pPerfData=NULL;
+ LONG res,lCount;
+ PERF_OBJECT_TYPE *pPerfObj;
+ PERF_COUNTER_DEFINITION *pPerfCounter;
+ PERF_INSTANCE_DEFINITION *pPerfInstance;
+ PERF_COUNTER_BLOCK *pPerfCounterBlock;
+ DWORD dwObjectId,dwCounterId;
+ WCHAR wszValueName[11],*pwszInstanceName;
+ BYTE nCpuUsage;
+ BOOL fSwitched,fFound,fIsFirst=FALSE;
+ LARGE_INTEGER liPrevCounterValue={0},liCurrentCounterValue={0},liPrevPerfTime100nSec={0};
+
+ /* init */
+ if(IsWinVer2000Plus()) { /* Win2000+: */
+ dwObjectId=238; /*'Processor' object */
+ dwCounterId=6; /* '% processor time' counter */
+ pwszInstanceName=L"_Total"; /* '_Total' instance */
+ } else { /* WinNT4: */
+ dwObjectId=2; /* 'System' object */
+ dwCounterId=240; /* '% Total processor time' counter */
+ pwszInstanceName=NULL;
+ }
+ _itow(dwObjectId,wszValueName,10);
+ fSwitched=WinNT_PerfStatsSwitch(_T("PerfOS"),FALSE);
+
+ /* poll */
+ for(;;) {
+ /* retrieve data for given object */
+ res=RegQueryValueExW(HKEY_PERFORMANCE_DATA,wszValueName,NULL,NULL,(BYTE*)pPerfData,&dwBufferSize);
+ while(!pBuffer || res==ERROR_MORE_DATA) {
+ pBuffer=(BYTE*)mir_realloc(pPerfData,dwBufferSize+=256);
+ if(!pBuffer) break;
+ pPerfData=(PERF_DATA_BLOCK*)pBuffer;
+ res=RegQueryValueExW(HKEY_PERFORMANCE_DATA,wszValueName,NULL,NULL,pBuffer,&dwBufferSize);
+ }
+ if(res!=ERROR_SUCCESS) break;
+
+ /* find object in data */
+ fFound=FALSE;
+ /* first object */
+ pPerfObj=(PERF_OBJECT_TYPE*)((BYTE*)pPerfData+pPerfData->HeaderLength);
+ for(dwCount=0;dwCount<pPerfData->NumObjectTypes;++dwCount) {
+ if(pPerfObj->ObjectNameTitleIndex==dwObjectId) {
+ /* find counter in object data */
+ /* first counter */
+ pPerfCounter=(PERF_COUNTER_DEFINITION*)((BYTE*)pPerfObj+pPerfObj->HeaderLength);
+ for(dwCount=0;dwCount<(pPerfObj->NumCounters);++dwCount) {
+ if(pPerfCounter->CounterNameTitleIndex==dwCounterId) {
+ /* find instance in counter data */
+ if(pPerfObj->NumInstances==PERF_NO_INSTANCES) {
+ pPerfCounterBlock=(PERF_COUNTER_BLOCK*)((BYTE*)pPerfObj+pPerfObj->DefinitionLength);
+ liCurrentCounterValue=*(LARGE_INTEGER*)((BYTE*)pPerfCounterBlock+pPerfCounter->CounterOffset);
+ fFound=TRUE;
+ }
+ else {
+ /* first instance */
+ pPerfInstance=(PERF_INSTANCE_DEFINITION*)((BYTE*)pPerfObj+pPerfObj->DefinitionLength);
+ for(lCount=0;lCount<(pPerfObj->NumInstances);++lCount) {
+ pPerfCounterBlock=(PERF_COUNTER_BLOCK*)((BYTE*)pPerfInstance+pPerfInstance->ByteLength);
+ if(!lstrcmpiW(pwszInstanceName,(WCHAR*)((BYTE*)pPerfInstance+pPerfInstance->NameOffset)) || !pwszInstanceName) {
+ liCurrentCounterValue=*(LARGE_INTEGER*)((BYTE*)pPerfCounterBlock+pPerfCounter->CounterOffset);
+ fFound=TRUE;
+ break;
+ }
+ /* next instance */
+ pPerfInstance=(PPERF_INSTANCE_DEFINITION)((BYTE*)pPerfCounterBlock+pPerfCounterBlock->ByteLength);
+ }
+ }
+ break;
+ }
+ /* next counter */
+ pPerfCounter=(PERF_COUNTER_DEFINITION*)((BYTE*)pPerfCounter+pPerfCounter->ByteLength);
+ }
+ break;
+ }
+ /* next object */
+ pPerfObj=(PERF_OBJECT_TYPE*)((BYTE*)pPerfObj+pPerfObj->TotalByteLength);
+ }
+ if(!fFound) break;
+
+ /* calc val from data, we need two samplings
+ * counter type: PERF_100NSEC_TIMER_INV
+ * calc: time base=100Ns, value=100*(1-(data_diff)/(100NsTime_diff)) */
+ if(!fIsFirst) {
+ nCpuUsage=(BYTE)((1.0-(Li2Double(liCurrentCounterValue)-Li2Double(liPrevCounterValue))/(Li2Double(pPerfData->PerfTime100nSec)-Li2Double(liPrevPerfTime100nSec)))*100.0+0.5);
+ if(!CallBackAndWait(param,nCpuUsage)) break;
+ }
+ else fIsFirst=FALSE;
+ /* store current sampling for next */
+ CopyMemory(&liPrevCounterValue,&liCurrentCounterValue,sizeof(LARGE_INTEGER));
+ CopyMemory(&liPrevPerfTime100nSec,&pPerfData->PerfTime100nSec,sizeof(LARGE_INTEGER));
+ }
+
+ /* uninit */
+ if(pPerfData) mir_free(pPerfData);
+ if(fSwitched) WinNT_PerfStatsSwitch(_T("PerfOS"),TRUE);
+
+ /* return error for PollCpuUsage() if never succeeded */
+ if(param->hFirstEvent!=NULL) SetEvent(param->hFirstEvent);
+ mir_free(param);
+}
+
+/************************* Start Thread *******************************/
+
+// returns poll thread id on success
+DWORD PollCpuUsage(CPUUSAGEAVAILPROC pfnDataAvailProc,LPARAM lParam,DWORD dwDelayMillis)
+{
+ struct CpuUsageThreadParams *param;
+ DWORD idThread=0;
+ HANDLE hFirstEvent;
+
+ /* init params */
+ param=(struct CpuUsageThreadParams*)mir_alloc(sizeof(struct CpuUsageThreadParams));
+ if(param==NULL) return FALSE;
+ param->dwDelayMillis=dwDelayMillis;
+ param->pfnDataAvailProc=pfnDataAvailProc;
+ param->lParam=lParam;
+ param->pidThread=&idThread;
+ param->hFirstEvent=hFirstEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
+ if(hFirstEvent==NULL) {
+ mir_free(param);
+ return 0;
+ }
+ /* start thread */
+#if defined(_UNICODE)
+ if(mir_forkthread(WinNT_PollThread,param)!=-1)
+#else
+ if(mir_forkthread(IsWinVerNT()?WinNT_PollThread:Win9x_PollThread,param)!=-1)
+#endif
+ WaitForSingleObject(hFirstEvent,INFINITE); /* wait for first success */
+ else mir_free(param); /* thread not started */
+ CloseHandle(hFirstEvent);
+ return idThread;
+}
diff --git a/plugins/AutoShutdown/cpuusage.h b/plugins/AutoShutdown/cpuusage.h
new file mode 100644
index 0000000000..681a2c8213
--- /dev/null
+++ b/plugins/AutoShutdown/cpuusage.h
@@ -0,0 +1,24 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+/* Start Thread */
+typedef BOOL (CALLBACK* CPUUSAGEAVAILPROC)(BYTE nCpuUsage,LPARAM lParam);
+DWORD PollCpuUsage(CPUUSAGEAVAILPROC pfnDataAvailProc,LPARAM lParam,DWORD dwDelayMillis);
diff --git a/plugins/AutoShutdown/docs/Info_Src.txt b/plugins/AutoShutdown/docs/Info_Src.txt
new file mode 100644
index 0000000000..2b61a98f37
--- /dev/null
+++ b/plugins/AutoShutdown/docs/Info_Src.txt
@@ -0,0 +1,31 @@
+
+AutoShutdown 1.4.0.1 for Miranda IM 0.7+
+------------------------------------------------------------------------
+ Source Code
+
+Reminder:
+'AutoShutdown' is released under the terms of the GNU General Public License.
+See 'Shutdown-License.txt' for more details.
+'AutoShutdown' is copyright 2004-2007 by H. Herkenrath.
+
+Please notify me of any changes that improve
+'AutoShutdown' or add new features.
+If you have any questions on the code, feel free
+to contact me at my email address.
+
+ H. Herkenrath (hrathh at users.sourceforge.net)
+
+
+Notes
+------------------------------------------------------------------------
+The following files need to be changed to bump the version number:
+
+Info_Src.txt (1 place)
+version.h (4 places)
+m_shutdown.h (1 place)
+m_shutdown.inc (1 place)
+docs\Shutdown-Readme.txt (3 places)
+docs\Shutdown-Translation.txt (2 or 3 places)
+docs\Shutdown-Developer.txt (1 place)
+
+
diff --git a/plugins/AutoShutdown/docs/License_Appendix.txt b/plugins/AutoShutdown/docs/License_Appendix.txt
new file mode 100644
index 0000000000..c590c3f5fb
--- /dev/null
+++ b/plugins/AutoShutdown/docs/License_Appendix.txt
@@ -0,0 +1,64 @@
+
+Excecpt of GNU General Public License (Appendix):
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/plugins/AutoShutdown/docs/Shutdown-Developer.txt b/plugins/AutoShutdown/docs/Shutdown-Developer.txt
new file mode 100644
index 0000000000..9b15e2b09b
--- /dev/null
+++ b/plugins/AutoShutdown/docs/Shutdown-Developer.txt
@@ -0,0 +1,49 @@
+
+AutoShutdown 1.4.0.2 for Miranda IM 0.7+
+------------------------------------------------------------------------
+ Developer Information
+
+ Contents: -------------------------------
+ | Translation, Services/Events,
+ | Debug Symbols, Coding Language, Rebase Info
+
+Translation
+-----------------
+ The translation string listing can be found in
+ 'Shutdown-Translation.txt'.
+
+Services/Events
+-----------------
+ For more information about which service functions are offered by
+ 'AutoShutdown' and about how they can be used by your plugin,
+ please refer to 'm_shutdown.h'.
+ If you would like to use Delphi/Pascal please refer to 'm_shutdown.inc'.
+
+ Feel free to redirect any questions or extension ideas to me via e-mail:
+ hrathh at users.sourceforge.net
+
+Debug Symbols
+-----------------
+ Debug symbols are also available for debugging purposes.
+ Copy the PDB-files in the SDK-zip into the same directory as the
+ corresponding DLL-files.
+
+ To debug crashes the supplied MAP-file file might be helpful.
+
+Coding Language
+-----------------
+ 'AutoShutdown' was written using Microsoft Visual C++ 6.0 SP6
+ and the Microsoft Platform SDK shipped along with it.
+
+Rebase Info
+-----------------
+ 'AutoShutdown' has set its base address to:
+ 0x11070000
+
+ Please avoid using this base address for your plugins because it will
+ slightly slow down startup of Miranda IM.
+
+ With Microsoft Visual C++ the Base Address can be configured at:
+ 'Project' -> 'Settings' -> 'Linker' -> 'Output' -> 'Base Address'
+
+H. Herkenrath (hrathh at users.sourceforge.net)
diff --git a/plugins/AutoShutdown/docs/Shutdown-License.txt b/plugins/AutoShutdown/docs/Shutdown-License.txt
new file mode 100644
index 0000000000..a726a52df1
--- /dev/null
+++ b/plugins/AutoShutdown/docs/Shutdown-License.txt
@@ -0,0 +1,278 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
diff --git a/plugins/AutoShutdown/docs/Shutdown-Readme.txt b/plugins/AutoShutdown/docs/Shutdown-Readme.txt
new file mode 100644
index 0000000000..59524f620f
--- /dev/null
+++ b/plugins/AutoShutdown/docs/Shutdown-Readme.txt
@@ -0,0 +1,329 @@
+
+AutoShutdown 1.4.0.2
+------------------------------------------------------------------------
+ Plugin for Miranda IM 0.7 and +
+
+ Plugin Info: ----------------------------
+ | Version: 1.4.0.2
+ | Filename: shutdown.dll
+ | Author: H. Herkenrath (hrathh at users.sourceforge.net)
+ | Description: Adds the possibility to shutdown Miranda IM
+ | or the computer after at a specified time.
+
+ Contents: -------------------------------
+ | Features, Requirements, Usage, Installation,
+ | Bugs and Wishes, To-Do List, Version History,
+ | Thanks, Translation, License and Copyright
+
+Features
+----------------------
+ + Shutdown Miranda IM or your computer after a specified time,
+ when receiving a special message or when all file transfers are completed
+ + Offers the following shutdown possibilities:
+ Logoff, Restart, Shutdown, Standby mode, Hibernate mode, Lock workstation,
+ Hang up dialup connections, Close Miranda IM, Set Miranda offine
+ + The available shutdown possibilities are only shown if they
+ are supported on your system
+ + The available shutdown events are only shown if you have
+ protocols or plugins installed that support the features
+ + Displays a confirmation dialog which is shown for 30 seconds
+ to cancel the process
+ + Plays a sound on confirmation dialog
+ + Displays the countdown in a special window below contact list
+ (this feature needs a MultiWindow enabled Contact List plugin)
+ + Plays a sound when the confirmation dialog is displayed
+ + No data gets lost on shutdown especially no unread messages
+ + Allows you to pause the shutdown countdown
+ + If Miranda is closed while automatic shutdown is running it will
+ show a dialog on next start of Miranda IM where it can be selected
+ to start automatic shutdown again
+ + Provides shutdown services for other plugins
+ + Full Unicode support
+ + Automatic installation of all files, just unzip into Plugins directory
+ + Supported plugins/tools:
+ MultiWindow Contact Lists (frames and hotkeys), Hotkey Plugins,
+ Magnetic Windows, Snapping Windows, TopToolBar, AutoReplacer,
+ Trigger Plugin (http://www.pboon.nl/projects.htm), HDD Info,
+ Weather Protocol
+
+Requirements
+----------------------
+ -> Miranda IM 0.7+:
+ Miranda IM is needed in version 0.7 or later.
+
+ -> Optional: Weather Protocol 0.3.3.17+:
+ If you would like to use the thunderstorm shutdown feature,
+ you need to have Weather Protocol installed, version 0.3.3.17 or later.
+
+ -> Optional: HDD Info 0.1.2.0+:
+ If you would like to use the harddrive overheat shutdown feature,
+ you need to have the HDD Info plugin installed, version 0.1.2.0 or later.
+
+ -> Optional: Trigger Plugin 0.2.0.69+:
+ If you would like to use the Trigger feature,
+ you need to have the Trigger plugin installed, version 0.2.0.69 or later.
+
+Usage
+----------------------
+ AutoShutdown can be activated via the main menu:
+ 'Main Menu' -> 'Automatic Shutdown'
+
+ The options to use 'Hibernate mode' and 'Lock workstation'
+ are only available if your system supports it.
+ All other options are only available if they are enabled on your system.
+
+ Enabling 'Hibernate mode' on Windows ME/2000 and later:
+ 'Control Panel' -> 'Power Options' -> 'Hibernate'
+ To enable the Hibernate feature go to the Control Panel,
+ double-click Power Options, and then click the Hibernate tab.
+ Click to select the Enable Hibernate Support check box.
+
+Installation
+----------------------
+ Find 'miranda32.exe' on your computer.
+
+ Just copy all the contents of the zip-file as they are into the 'Plugins'
+ subdirectory in the Miranda IM folder.
+ 'AutoShutdown' will detect the files and move them into the appropriate
+ directories on it's first run.
+
+ You can also do all the installation by hand, if you want to:
+
+ Main Plugin: Copy the file 'shutdown.dll' into the 'Plugins' subdirectory
+ in the Miranda IM folder.
+
+ The Unicode version of the plugin will only work on Windows NT/2000/XP,
+ Windows Server 2000, Windows Vista or later with an installed
+ Unicode version of Miranda IM.
+ To use it on Windows 95/98/Me, please download the ANSI version of the plugin.
+
+ Documentation: The txt-files should be moved along with the SDK-zip into the
+ 'Docs' directory in the Miranda IM folder.
+
+ Sounds: The wav-files should be moved into the 'Sounds'
+ directory. They will get recognized automatically and be added to the sounds list.
+
+ That's it!
+
+Bugs and Wishes
+----------------------
+ Feel free to mail me your wishes about 'AutoShutdown' and tell
+ me all the bugs you may find: hrathh at users.sourceforge.net
+
+To-Do List (random ideas)
+----------------------
+ ? Design some icons for the shutdown types (shutdown, reboot, etc.)...anyone?
+ ? Ddd possibility to shutdown on status change of specific users
+ ? Support Alarms Plugin API (m_alarms.h):
+ This would replace countdown frame, showing the shutdown countdown
+ on the Alarms frame instead (don't know if this is a good idea, not yet possible)
+ ? Show system tray icon when automatic shutdown is enabled (not needed, bad looking)
+ ? Add possibility to set Miranda to a specific status instead of offline
+ (really shutdown related?)
+ ? Start a specified application on event (really shutdown related?)
+
+Version History
+----------------------
+ 1.4.0.2 - minor fixes
+ 1.4.0.1 - ensure correct threshold values for cpuusage
+ - uses langpack locale for combobox sorting
+ - fixed: fontservice items were registered too early
+ - fixed: unicode problem with tray menu item
+ - fixed: settings dialog did not show up with parent
+ - added v0.8 support
+ - minor other improvements
+ 1.4.0.0 - Added possibility to shutdown when computer finishes
+ a busy task (high cpu usage)
+ - Support for AutoReplacer in message editbox
+ - Fixed minor issue with reactivating on miranda startup
+ - Really fixed shutdown on message in unicode build
+ - Updated new miranda headers, use of mir_forkthread
+ - Fixed automatic installation routine, now works again
+ - Bug-Fix: countdown hours (and higher) were converted wrongly
+ - Fixes for Win9x and WinNT4
+ - Adjustments for hung apps
+ - Tweak: support for ENDSESSION_CLOSEAPP in Windows Vista
+ - Code reorganization
+ - Minor Vista and robustness tweaks
+ - Improved FontService and IcoLib support (core built-in)
+ 1.3.1.1 - Tweaks for blind users
+ - Minor speed-up for frame drawing when resized
+ - Cleanups
+ - workaround for frames not drawing when previously hidden
+ 1.3.1.0 - Added FontService support
+ - Added HDD Info overheat shutdown
+ - Updated Trigger plugin support (0.2)
+ - Updated TopToolBar support to latest version (0.7.3)
+ - Fixed 'lock workstation' on WinNT4
+ - Marquee on progress
+ - Minor fixes and improvements
+ - Minor updates for new Miranda
+ 1.3.0.8 - Bug-Fix: Check for unicode core was wrong
+ - Some other minor changes
+ 1.3.0.7 - Improvements to OKTOEXIT handling
+ - Bug-Fix: Daylight saving time was ignored in time conversion
+ 1.3.0.6 - Reduced ANSI file size (corrected compiler settings)
+ - Minor internal tweaks
+ - Bug-Fix: Confirmation countdown in options was not displayed correctly
+ - Included debug symbols (PDB) into SDK package
+ - Adjusted db settings
+ 1.3.0.5 - Minor internal tweaks
+ - Fixed crash on start when Trigger plugin installed
+ 1.3.0.4 - Minor improvements and some internal changes to the countdown frame
+ - Finally fully fixed the dialup shutdown problem
+ - Added: Now also adds Close Miranda and Set Miranda offline as
+ actions for the trigger plugin (was requested)
+ 1.3.0.3 - Bug-Fix: Another try to fix the 'hangup dialup connections' freeze
+ 1.3.0.2 - Bug-Fix: 'hang up dialup connection' freezed Miranda sometimes
+ 1.3.0.1 - Fix: On some rare situations Miranda was not shutdown correctly
+ - Fix: Frame was not shown correctly on clist_modern
+ - Fixed mw_clist hotkey
+ - Some minor improvements
+ - Added shutdown event
+ - Fixed minor workstation locked issue
+ - Fixed 'sec' not shown correctly on frame (bug in WinAPI)
+ - Made 'hang up dialup connections' code more robust
+ - Bug-Fix: countdown values were not saved
+ - Fixed: shutdown dates in past were sometimes not recognized correctly
+ 1.3.0.0 - Make use of FORCEIFHUNG flag instead of FORCE whenever it is possible
+ - Shutdown at [hh:mm] and [yy-mm-dd] instead of Shutdown only at [hh:mm]
+ (also making use of calendar common control)
+ - New shutdown type: set status to offline
+ - Make use of ME_IDLE_CHANGED to shutdown on idle
+ - Added 'Thunder Shutdown' functionality
+ - Now making use of marquee mode of progressbar of time countdown is to
+ long to be displayed
+ - Added: Hotkey support for toggling automatic shutdown on/off
+ - Added: IcoLib support
+ - Updated: DBEditor++ support
+ - Added: Support for Trigger plugin (shutdown actions)
+ - Added: Unicode support
+ - Added: Functionality of Thunder Shutdown plugin (see option page)
+ - Removed: AgressiveOptimize.h to make it work on all systems
+ - Improved: New service functions
+ - Added: Shows countdown frame in normal window when frames are not available
+ - Added: Hotkey support for hotkey services (toggle)
+ - Improved: Now makes use of StrFromTimeInterval, BroadcastSystemMessage
+ - Improved: Made file transfer shutdown logic more robust
+ - Imroved dialogs look and feel
+ - Cleaned up and revisited code
+ 1.2.0.4 - Changed time control to use windows default control
+ - Fix: The icon on the countdown frame was sqeezed a bit
+ - Improved shutdown dialog layout
+ - Some small string improvements/changes (see Shutdown-Translation.txt')
+ - Some other minor code changes and improvements
+ 1.2.0.3 - 'Shutdown on file transfer' and 'Shutdown on message receival'
+ are now only enabled if plugins and protocols are installed that
+ support file transfer and/or instant messaging features
+ - Some other minor changes
+ 1.2.0.2 - Fix: Shutdown on message receival only worked when
+ message dialog was closed (Thanks to Hurricane and Foo)
+ - Fix: Sound option dialog sometimes crashed
+ when selecting a different countdown sound file (Thanks to Rex)
+ - Minor string improvements (see 'Shutdown-Translation.txt')
+ - Some small internal improvements
+ 1.2.0.1 - Fix: TopToolBar button showed wrong behaviour if
+ dialog was already opened
+ 1.2.0.0 - Add: New shutdown type 'Hang up dialup connections'
+ - Fix: Combo box did not remember last option correctly
+ - Some other small fixes/changes/improvents
+ 1.1.3.1 - Fix: Tabulator did not work correctly on settings dialog
+ - Fix: Some problems with the 'last exit remembering'
+ - Fix: 'Cancel' button was not default button on shutdown dialog
+ - Some other minor fixes/improvements
+ 1.1.3.0 - Improved: Sending of WM_ENDSESSION
+ - Add: If Miranda is closed and automatic shutdown is running
+ it will remember it and shows on next Miranda start a message box
+ where the user can select to start automatic shutdown again
+ - Add: When no option is selected it does no longer allow the
+ user to click on OK
+ - Fix: Time input control sometimes got hidden when editing hours
+ - Some other minor improvements/fixes
+ 1.1.2.0 - Fix: The shutdown on file transfer completion feature
+ did not always work correctly, especially with ICQ file transfers
+ - Fix: If the default sound file isn't installed it doesn't
+ anylonger give out the windows default sound by default
+ - Add: If Miranda is closed and automatic shutdown is running
+ it will remember it and start on next Miranda start again
+ 1.1.1.1 - Fix: Shutdown on specific time sometimes did not work correctly
+ and crashed Miranda on opening the 30s confirmation window
+ 1.1.1.0 - Fix: Default time was sometimes not detected correctly
+ - Improved: Shutdown/Restart is now faster due to improved
+ sending of WM_ENDSESSION
+ - Improved: When the countdown is paused it shows a blinking text
+ - Change: Context menu can now also be opened via left click
+ - Change: Shutdown on message receival now checks for
+ if the message contains the specified text instead of checking for
+ exactly the same content
+ - Change: 'Cancel Countdown' in context menu now only stops the countdown
+ instead of stopping all shutdown causes
+ - Change: When using shutdown at time feature the countdown display will
+ show the time instead of the countdown (Suggested by Rootgar)
+ - Change: The context menu now show a different text instead of being
+ checked when the countdown is paused
+ - Added/Changed some strings (see 'Shutdown-Translation.txt')
+ - Some other minor changes/improvements
+ 1.1.0.0 - Add: Possibility to shut down when all file transfers are finished
+ - Add: Possibility to shut down on message receival
+ - Add: WM_ENDSESSION now gets send to all applications manually on
+ shutdown/restart to prevent data loss
+ - Add: Now containing default sound file boundled with zip
+ - Add: Possibility to pause/unpause the countdown via right click on it
+ - Fix: Shutdown/Restart was not shown on Windows 2000/XP
+ - Fix: Updated link on plugin options page
+ - Fix: Countdown got updated one second after reactivating clist
+ - Change: Sound now gets played repeatedly on 30s shutdown dialog
+ - Change: Now 'Cancel' is the default button on 30s shutdown dialog
+ - Improved/Added some strings (please see 'Shutdown-Translation.txt')
+ - Some other minor improvements
+ 1.0.0.0 - Initial release
+
+Thanks
+----------------------
+ * To Corsario (Angelo Luiz Tartari) for the first idea of a shutdown plugin
+ * To Dennys for the first idea of rebooting via message ('dReboot' plugin)
+ * To noname for the thunderstorm shutdown feature
+ * To Marek 'tusz' Tusiewicz for the sound file and testing
+ * To Rootgar and Tigerix for their bug reports and suggestions
+
+Translation
+----------------------
+ Translation strings can be found in 'Shutdown-Translation.txt'.
+
+License and Copyright
+----------------------
+ 'AutoShutdown' is released under the terms of the GNU General Public License.
+ See 'Shutdown-License.txt' for more details.
+
+ Copyright (c) 2004-2007 by H. Herkenrath. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ 1. Redistributions of source code must retain the copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. The origin of this software must not be misrepresented; you must
+ not claim that you wrote the original software. If you use this
+ software in a product, an acknowledgment in the product
+ documentation would be appreciated but is not required.
+ 3. Altered source versions must be plainly marked as such, and must
+ not be misrepresented as being the original software.
+ 4. The name of the author may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESS
+ OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+ GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+H. Herkenrath (hrathh at users.sourceforge.net)
diff --git a/plugins/AutoShutdown/docs/Shutdown-Translation.txt b/plugins/AutoShutdown/docs/Shutdown-Translation.txt
new file mode 100644
index 0000000000..3ff9b29186
--- /dev/null
+++ b/plugins/AutoShutdown/docs/Shutdown-Translation.txt
@@ -0,0 +1,240 @@
+
+AutoShutdown 1.4.0.2 for Miranda IM 0.7+
+------------------------------------------------------------------------
+ Translator Information
+
+ Contents: -------------------------------
+ | General Info, String Listing
+
+General Info
+-----------------------------
+ 'AutoShutdown' can be translated with the Miranda IM
+ language files.
+
+ Place the following strings listed in the following section in a
+ file called 'langpack_<language>.txt' in the Miranda IM directory.
+ Then you can translate them into your language.
+
+ If you need more info about Miranda IM language files visit:
+ http://miranda.svn.sourceforge.net/viewvc/*checkout*/miranda/trunk/miranda/i18n/readme.txt
+
+String Listing
+-----------------------------
+
+; --- Plugin: AutoShutdown 1.4.0.2 (German) ---
+
+; Translation by hrathh
+; Please report any mistakes or missing strings in here.
+
+[AutoShutdown]
+Automatisches Beenden
+[Adds the possibility to shutdown the computer when a specified event occurs.]
+Dieses Plugin erm�glicht es den Computer bei Eintreten festgelegter Ereignisse zu Beenden.
+[AutoShutdown Plugin]
+AutoShutdown-Plugin
+[The AutoShutdown plugin can not be loaded. It requires Miranda IM %hs or later.]
+Das AutoShutdown-Plugin kann nicht geladen werden. Es ben�tigt Miranda IM %hs oder neuer.
+
+; Menu Item
+[Automatic &shutdown...]
+Automatisches &Beenden...
+[Stop automatic &shutdown]
+Automatisches &Beenden abbrechen
+; TopToolBar Button
+[Start/Stop automatic shutdown]
+Automatisches Beenden de-/aktivieren
+[Start automatic shutdown]
+Automatisches Beenden aktivieren
+[Stop automatic shutdown]
+Automatisches Beenden deaktivieren
+
+; Sound
+;[Alerts]
+[Automatic Shutdown Countdown]
+Countdown beim Automatischen Beenden
+; Hotkey
+[Toggle Automatic Shutdown]
+Automatisches Beenden ein-/ausschalten
+
+; Icons
+[Active]
+Aktiviert
+[Inactive]
+Deaktiviert
+[Header]
+Illustration
+; Fonts and Colors
+[Countdown on Frame]
+Countdown im Rahmen
+[Background]
+Hintergrund
+[Progress Bar]
+Fortschrittsbalken
+
+; Settings Dialog
+[Automatic Shutdown]
+Automatisches Beenden
+[Select the automatic shutdown event]
+Ein Ereignis zum automatischen Beenden w�hlen
+[Shutdown at &specific time]
+Beenden zur festgelegten &Zeit
+[Shutdown a&t:]
+Durchf�hren u&m:
+[Shutdown i&n:]
+Durchf�hren i&n:
+[Second(s)]
+Sekunden(n)
+[Minute(s)]
+Minute(n)
+[Hour(s)]
+Stunde(n)
+[Day(s)]
+Tage(n)
+[Week(s)]
+Woche(n)
+[Month(s)]
+Monat(en)
+[Shutdown when a &message is received containing the following text:]
+Beenden, wenn eine &Nachricht eingeht, die den folgenden Text enth�lt:
+[Shutdown when all &file transfers are finished]
+Beenden, wenn alle &Datei�bertragungen abgeschlossen sind
+[Shutdown when &prozessor usage drops below:]
+Beenden, wenn die &Prozessorauslastung unter folgenden Wert f�llt:
+[(current: %u%%)]
+(aktuell: %u%%)
+;[%]
+[Shutdown when Miranda IM becomes &idle]
+Beenden, wenn Miranda IM im &Idle-Modus ist
+[Configure]
+Konfigurieren
+[Shutdown when all contacts are &offline]
+Beenden, wenn alle Kontakte &offline sind
+[&Action:]
+&Vorgang:
+[Close Miranda IM]
+Miranda IM schlie�en
+[Sets all Miranda IM protocols to offline and closes Miranda IM.]
+Setzt alle Netzwerkprotokolle auf "Offline" und beendet Miranda IM.
+[Set Miranda IM offline]
+Miranda IM offline schalten
+[Sets all Miranda IM protocols to offline.]
+Setzt alle Protokolle von Miranda IM auf Offline.
+[Log off user]
+Benutzer abmelden
+[Logs the current Windows user off so that another user can log in.]
+Meldet den aktuellen Benutzer von Windows ab, sodass sich ein anderer Benutzer anmelden kann.
+[Restart computer]
+Computer neu starten
+[Shuts down Windows and then restarts Windows.]
+Beendet die Windows-Sitzung und Windows und startet dann Windows erneut.
+[Shutdown computer]
+Computer herunterfahren
+[Closes all running programs and shuts down Windows to a point at which it is safe to turn off the power.]
+Beendet die Windows-Sitzung und f�hrt den Computer herunter. Der Computer wird ausgeschaltet.
+[Standby mode]
+Standby-Modus
+[Saves the current Windows session in memory and sets the system to suspend mode.]
+Beh�lt die Windows-Sitzung bei, speichert die Daten im Arbeitsspeicher und schaltet den Computer in den Energiesparmodus.
+[Hibernate mode]
+Ruhezustand
+[Saves the current Windows session on harddisc, so that the power can be turned off.]
+Speichert die Windows-Sitzung auf der Festplatte, sodass der Computer ausgeschaltet werden kann.
+[Lock workstation]
+Arbeitsplatz verriegeln
+[Locks the computer. To unlock the computer, you must log in.]
+Verriegelt den Computer gegen Zugriff. Um den Computer wieder zu entriegeln m�ssen Sie sich erneut anmelden.
+[Hang up dialup connections]
+DF�-Verbindungen trennen
+[Sets all protocols to offline and closes all RAS connections.]
+Setzt alle Netzwerkprotokolle auf "Offline" und trennt alle aktiven DF�-Netzwerkverbindungen.
+
+; Options
+[Shutdown]
+Beenden
+[&Show confirmation dialog before shutdown]
+&Best�tigungsfenster vor dem Beenden anzeigen
+[&Countdown starts at:]
+&Countdown beginnt bei:
+[seconds]
+Sekunden
+[Shutdown Events]
+Ereignisse
+[&Activate automatic shutdown with the same settings again if Miranda IM was closed with automatic shutdown enabled]
+&Automatisches Beenden mit den gleichen Einstellungen erneut aktivieren, wenn Miranda IM beendet wurde w�hrend es aktiviert war
+[&Ignore hidden or temporary contacts when watching for all contacts being offline]
+&Versteckte und tempor�re Kontakte beim Pr�fen auf Offline Status ignorieren
+[Critical Shutdown Events]
+Kritische Ereignisse
+[&Thunderstorm warning is issued (Weather)]
+Gewitterwarnung wird ausgegeben (Wetter)
+[&Harddrive overheats (HDD Info)]
+&Festplatte �berhitzt (HDD Info)
+
+; Trigger Plugin
+[Shutdown: Close Miranda IM]
+Herunterfahren: Miranda IM schlie�en
+[Shutdown: Set Miranda IM offline]
+Herunterfahren: Miranda IM offline schalten
+[Shutdown: Log off user]
+Herunterfahren: Abmelden
+[Shutdown: Restart computer]
+Herunterfahren: Neustart
+[Shutdown: Shutdown computer]
+Herunterfahren: Computer ausschalten
+[Shutdown: Standby mode]
+Herunterfahren: Standby-Modus
+[Shutdown: Hibernate mode]
+Herunterfahren: Ruhezustand
+[Shutdown: Lock workstation]
+Herunterfahren: Arbeitsplatz verriegeln
+[Shutdown: Hang up dialup connections]
+Herunterfahren: DF�-verbindungen trennen
+
+; Shutdown Dialog
+;[Automatic Shutdown]
+[Miranda IM is going to be automatically closed in %i second(s).]
+Miranda IM wird in %i Sekunde(n) automatisch geschlossen.
+[You will be logged off automatically in %i second(s).]
+Der Benutzer wird in %i Sekunde(n) automatisch abgemeldet.
+[The computer will automatically be restarted in %i second(s).]
+Der Computer wird in %i Sekunde(n) automatisch neu gestartet.
+[The computer will automatically be set to standby mode in %i second(s).]
+Der Computer wird in %i Sekunde(n) automatisch in den Stanby-Modus geschaltet.
+[The computer will automatically be set to hibernate mode in %i second(s).]
+Der Computer wird in %i Sekunde(n) automatisch in den Ruhezustand geschaltet.
+[The workstation will automatically get locked in %i second(s).]
+Der Arbeitsplatz wird in %i Sekunde(n) automatisch verriegelt.
+[The computer will automatically be shut down in %i second(s).]
+Der Computer wird in %i Sekunde(n) automatisch heruntergefahren.
+[All dialup connections will be closed in %i second(s).]
+Alle aktiven DF�-Netzwerkverbindungen werden in %i Sekunde(n) automatisch getrennt.
+[Unsaved data in open applications except Miranda IM might get lost.]
+Ungespeicherte Daten in ge�ffneten Anwendungen au�er Miranda IM k�nnten verloren gehen.
+[Please click "Cancel" if you would like to abort the process.]
+Bitte auf "Abbrechen" klicken, wenn der Vorgang nicht durchgef�hrt werden soll.
+[&Now!]
+&Sofort!
+
+; Countdown Frame
+[Time left:]
+Verbleibend:
+[Shutdown at:]
+Beenden um:
+[Paused]
+Pause
+[&Cancel Countdown]
+Countdown &abbrechen
+[&Pause Countdown]
+Countdown &pausieren
+[&Unpause Countdown]
+Countdown &fortsetzen
+
+; Error
+[Automatic Shutdown Error]
+Fehler beim Automatischen Beenden
+[The shutdown process failed!\nReason: %s]
+Der Beendevorgang konnte nicht gestartet werden!\nGrund: %s
+
+; ---
+
+H. Herkenrath (hrathh at users.sourceforge.net)
diff --git a/plugins/AutoShutdown/docs/countdown.wav b/plugins/AutoShutdown/docs/countdown.wav
new file mode 100644
index 0000000000..45baa854bb
--- /dev/null
+++ b/plugins/AutoShutdown/docs/countdown.wav
Binary files differ
diff --git a/plugins/AutoShutdown/frame.c b/plugins/AutoShutdown/frame.c
new file mode 100644
index 0000000000..f9266b1906
--- /dev/null
+++ b/plugins/AutoShutdown/frame.c
@@ -0,0 +1,644 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include "common.h"
+
+/* Show Frame */
+extern HINSTANCE hInst;
+static HWND hwndCountdownFrame;
+static WORD hFrame;
+/* Misc */
+static HANDLE hHookModulesLoaded;
+
+/************************* Helpers ************************************/
+
+#define FRAMEELEMENT_BAR 1
+#define FRAMEELEMENT_BKGRND 2
+#define FRAMEELEMENT_TEXT 3
+static COLORREF GetDefaultColor(BYTE id)
+{
+ switch(id) {
+ case FRAMEELEMENT_BAR:
+ return RGB(250,0,0); /* same color as used on header icon */
+ case FRAMEELEMENT_BKGRND:
+ return (COLORREF)DBGetContactSettingDword(NULL,"CLC","BkColour",CLCDEFAULT_BKCOLOUR);
+ case FRAMEELEMENT_TEXT:
+ return GetSysColor(COLOR_WINDOWTEXT);
+ }
+ return 0; /* never happens */
+}
+
+static LOGFONT* GetDefaultFont(LOGFONT *lf)
+{
+ NONCLIENTMETRICS ncm;
+ ZeroMemory(&ncm,sizeof(ncm));
+ ncm.cbSize=sizeof(ncm);
+ if(SystemParametersInfo(SPI_GETNONCLIENTMETRICS,ncm.cbSize,&ncm,0)) {
+ *lf=ncm.lfStatusFont;
+ return lf;
+ }
+ return (LOGFONT*)NULL;
+}
+
+static HICON SetFrameTitleIcon(WORD hFrame,HICON hNewIcon)
+{
+ HICON hPrevIcon;
+ hPrevIcon=(HICON)CallService(MS_CLIST_FRAMES_GETFRAMEOPTIONS,MAKEWPARAM(FO_ICON,hFrame),0);
+ CallService(MS_CLIST_FRAMES_SETFRAMEOPTIONS,MAKEWPARAM(FO_ICON,hFrame),(LPARAM)hNewIcon);
+ if((int)hPrevIcon==-1) return (HICON)NULL;
+ return hPrevIcon;
+}
+
+static LRESULT CALLBACK ProgressBarSubclassProc(HWND hwndProgress,UINT msg,WPARAM wParam,LPARAM lParam)
+{
+ switch(msg) {
+ case WM_ERASEBKGND:
+ return TRUE;
+ case WM_LBUTTONDOWN:
+ case WM_LBUTTONDBLCLK:
+ return SendMessage(GetParent(hwndProgress),msg,wParam,lParam);
+ }
+ return CallWindowProc((WNDPROC)GetWindowLong(hwndProgress,GWL_USERDATA),hwndProgress,msg,wParam,lParam);
+}
+
+/************************* Window Class *******************************/
+
+#define COUNTDOWNFRAME_CLASS _T("AutoShutdownCountdown")
+
+/* Data */
+struct CountdownFrameWndData { /* sizeof=57, max cbClsExtra=40 on Win32 */
+ time_t countdown,settingLastTime;
+ HANDLE hHookColorsChanged,hHookFontsChanged,hHookIconsChanged;
+ HANDLE hwndIcon,hwndProgress,hwndDesc,hwndTime,hwndToolTip;
+ HBRUSH hbrBackground;
+ COLORREF clrBackground,clrText;
+ HFONT hFont;
+ WORD fTimeFlags;
+ BYTE flags;
+};
+
+/* Flags */
+#define FWPDF_PAUSED 0x01
+#define FWPDF_PAUSEDSHOWN 0x02
+#define FWPDF_COUNTDOWNINVALID 0x04
+#define FWPDF_TIMEISCLIPPED 0x08
+
+/* Menu Items */
+#define MENUITEM_STOPCOUNTDOWN 1
+#define MENUITEM_PAUSECOUNTDOWN 2
+
+/* Messages */
+#define M_REFRESH_COLORS (WM_USER+0)
+#define M_REFRESH_ICONS (WM_USER+1)
+#define M_REFRESH_FONTS (WM_USER+2)
+#define M_SET_COUNTDOWN (WM_USER+3)
+#define M_UPDATE_COUNTDOWN (WM_USER+4)
+#define M_CHECK_CLIPPED (WM_USER+5)
+#define M_CLOSE_COUNTDOWN (WM_USER+6)
+#define M_PAUSE_COUNTDOWN (WM_USER+7)
+
+static LRESULT CALLBACK FrameWndProc(HWND hwndFrame,UINT msg,WPARAM wParam,LPARAM lParam)
+{
+ struct CountdownFrameWndData *dat=(struct CountdownFrameWndData*)GetWindowLong(hwndFrame,GWL_USERDATA);
+
+ switch(msg) {
+ case WM_NCCREATE: /* init window data */
+ dat=(struct CountdownFrameWndData*)mir_calloc(sizeof(*dat));
+ SetWindowLong(hwndFrame,GWL_USERDATA,(LONG)dat);
+ if(dat==NULL) return FALSE; /* creation failed */
+ dat->fTimeFlags=*(WORD*)((CREATESTRUCT*)lParam)->lpCreateParams;
+ dat->flags=FWPDF_COUNTDOWNINVALID;
+ break;
+ case WM_CREATE: /* create childs */
+ { CREATESTRUCT *params=(CREATESTRUCT*)lParam;
+ dat->hwndIcon=CreateWindowEx(WS_EX_NOPARENTNOTIFY,
+ _T("Static"),
+ NULL,
+ WS_CHILD|WS_VISIBLE|SS_ICON|SS_CENTERIMAGE|SS_NOTIFY,
+ 3, 0,
+ GetSystemMetrics(SM_CXICON),
+ GetSystemMetrics(SM_CYICON),
+ hwndFrame,
+ NULL,
+ params->hInstance,
+ NULL);
+ dat->hwndProgress=CreateWindowEx(WS_EX_NOPARENTNOTIFY,
+ PROGRESS_CLASS,
+ (dat->fTimeFlags&SDWTF_ST_TIME)?TranslateT("Shutdown at:"):TranslateT("Time left:"),
+ WS_CHILD|WS_VISIBLE|PBS_SMOOTH,
+ GetSystemMetrics(SM_CXICON)+5,
+ 5, 90,
+ (GetSystemMetrics(SM_CXICON)/2)-5,
+ hwndFrame,
+ NULL,
+ params->hInstance,
+ NULL);
+ if(dat->hwndProgress==NULL) return -1; /* creation failed, calls WM_DESTROY */
+ SendMessage(dat->hwndProgress,PBM_SETSTEP,(WPARAM)1,0);
+ SetWindowLong(dat->hwndProgress,GWL_USERDATA,SetWindowLong(dat->hwndProgress,GWL_WNDPROC,(LONG)ProgressBarSubclassProc));
+ dat->hwndDesc=CreateWindowEx(WS_EX_NOPARENTNOTIFY,
+ _T("Static"),
+ (dat->fTimeFlags&SDWTF_ST_TIME)?TranslateT("Shutdown at:"):TranslateT("Time left:"),
+ WS_CHILD|WS_VISIBLE|SS_LEFTNOWORDWRAP|SS_NOTIFY,
+ GetSystemMetrics(SM_CXICON)+5,
+ (GetSystemMetrics(SM_CXICON)/2),
+ 75,
+ (GetSystemMetrics(SM_CXICON)/2),
+ hwndFrame,
+ NULL,
+ params->hInstance,
+ NULL);
+ dat->hwndTime=CreateWindowEx(WS_EX_NOPARENTNOTIFY,
+ _T("Static"),
+ NULL, /* hh:mm:ss */
+ WS_CHILD|WS_VISIBLE|SS_RIGHT|SS_NOTIFY|SS_ENDELLIPSIS,
+ (GetSystemMetrics(SM_CXICON)+80),
+ (GetSystemMetrics(SM_CXICON)/2),
+ 35,
+ (GetSystemMetrics(SM_CXICON)/2),
+ hwndFrame,
+ NULL,
+ params->hInstance,
+ NULL);
+ if(dat->hwndTime==NULL) return -1; /* creation failed, calls WM_DESTROY */
+ /* create tooltips */
+ if(IsWinVer98Plus() || IsWinVer2000Plus()) {
+ TTTOOLINFO ti;
+ dat->hwndToolTip=CreateWindowEx(WS_EX_TOPMOST,
+ TOOLTIPS_CLASS,
+ NULL,
+ WS_POPUP|TTS_ALWAYSTIP|TTS_NOPREFIX,
+ CW_USEDEFAULT, CW_USEDEFAULT,
+ CW_USEDEFAULT, CW_USEDEFAULT,
+ hwndFrame,
+ NULL,
+ params->hInstance,
+ NULL);
+ if(dat->hwndToolTip!=NULL) {
+ SetWindowPos(dat->hwndToolTip,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
+ ZeroMemory(&ti,sizeof(ti));
+ ti.cbSize=sizeof(ti);
+ ti.hwnd=hwndFrame;
+ ti.uFlags=TTF_IDISHWND|TTF_SUBCLASS|TTF_TRANSPARENT;
+ ti.lpszText=LPSTR_TEXTCALLBACK; /* commctl 4.70+ */
+ ti.uId=(UINT)dat->hwndTime; /* in-place tooltip */
+ SendMessage(dat->hwndToolTip,TTM_ADDTOOL,0,(LPARAM)&ti);
+ ti.uFlags&=~TTF_TRANSPARENT;
+ ti.uId=(UINT)dat->hwndProgress;
+ SendMessage(dat->hwndToolTip,TTM_ADDTOOL,0,(LPARAM)&ti);
+ if(dat->hwndDesc!=NULL) {
+ ti.uId=(UINT)dat->hwndDesc;
+ SendMessage(dat->hwndToolTip,TTM_ADDTOOL,0,(LPARAM)&ti);
+ }
+ if(dat->hwndIcon!=NULL) {
+ ti.uId=(UINT)dat->hwndIcon;
+ SendMessage(dat->hwndToolTip,TTM_ADDTOOL,0,(LPARAM)&ti);
+ }
+ }
+ }
+ /* init layout */
+ dat->hHookColorsChanged=HookEventMessage(ME_COLOUR_RELOAD,hwndFrame,M_REFRESH_COLORS);
+ dat->hHookFontsChanged=HookEventMessage(ME_FONT_RELOAD,hwndFrame,M_REFRESH_FONTS);
+ dat->hHookIconsChanged=HookEventMessage(ME_SKIN2_ICONSCHANGED,hwndFrame,M_REFRESH_ICONS);
+ SendMessage(hwndFrame,M_REFRESH_COLORS,0,0);
+ SendMessage(hwndFrame,M_REFRESH_FONTS,0,0);
+ SendMessage(hwndFrame,M_REFRESH_ICONS,0,0);
+ SendMessage(hwndFrame,M_SET_COUNTDOWN,0,0);
+ SendMessage(hwndFrame,M_UPDATE_COUNTDOWN,0,0);
+ if(!SetTimer(hwndFrame,1,1000,NULL)) return -1; /* creation failed, calls WM_DESTROY */
+ return 0;
+ }
+ case WM_DESTROY:
+ { HICON hIcon;
+ if(dat==NULL) return 0;
+ UnhookEvent(dat->hHookColorsChanged);
+ UnhookEvent(dat->hHookFontsChanged);
+ UnhookEvent(dat->hHookIconsChanged);
+ /* other childs are destroyed automatically */
+ if(dat->hwndToolTip!=NULL) DestroyWindow(dat->hwndToolTip);
+ hIcon=(HICON)SendMessage(dat->hwndIcon,STM_SETIMAGE,IMAGE_ICON,(LPARAM)NULL);
+ IcoLib_ReleaseIcon(hIcon); /* does NULL check */
+ break;
+ }
+ case WM_NCDESTROY:
+ if(dat==NULL) return 0;
+ if(dat->hFont!=NULL) DeleteObject(dat->hFont);
+ if(dat->hbrBackground!=NULL) DeleteObject(dat->hbrBackground);
+ mir_free(dat);
+ SetWindowLong(hwndFrame,GWL_USERDATA,(LONG)NULL);
+ break;
+ case WM_SIZE:
+ { RECT rc;
+ LONG width,height;
+ HDWP hdwp;
+ UINT defflg=SWP_NOZORDER|SWP_NOOWNERZORDER|SWP_NOACTIVATE;
+ SetRect(&rc,0,0,LOWORD(lParam),HIWORD(lParam)); /* width,height */
+ /* workaround: reduce flickering of frame in clist */
+ InvalidateRect(hwndFrame,&rc,FALSE);
+ hdwp=BeginDeferWindowPos(3);
+ /* progress */
+ width=rc.right-GetSystemMetrics(SM_CXICON)-10;
+ height=rc.bottom-(GetSystemMetrics(SM_CYICON)/2)-5;
+ hdwp=DeferWindowPos(hdwp,dat->hwndProgress,NULL,0,0,width,height,SWP_NOMOVE|defflg);
+ /* desc */
+ if(dat->hwndDesc!=NULL) hdwp=DeferWindowPos(hdwp,dat->hwndDesc,NULL,GetSystemMetrics(SM_CXICON)+5,5+height,0,0,SWP_NOSIZE|defflg);
+ /* time */
+ hdwp=DeferWindowPos(hdwp,dat->hwndTime,NULL,GetSystemMetrics(SM_CXICON)+85,5+height,width-80,(GetSystemMetrics(SM_CXICON)/2),defflg);
+ EndDeferWindowPos(hdwp);
+ PostMessage(hwndFrame,M_CHECK_CLIPPED,0,0);
+ return 0;
+ }
+ case M_REFRESH_COLORS:
+ { COLORREF clrBar;
+ if(FontService_GetColor(TranslateT("Automatic Shutdown"),TranslateT("Progress Bar"),&clrBar))
+ clrBar=GetDefaultColor(FRAMEELEMENT_BAR);
+ if(FontService_GetColor(TranslateT("Automatic Shutdown"),TranslateT("Background"),&dat->clrBackground))
+ dat->clrBackground=GetDefaultColor(FRAMEELEMENT_BKGRND);
+ if(dat->hbrBackground!=NULL) DeleteObject(dat->hbrBackground);
+ dat->hbrBackground=CreateSolidBrush(dat->clrBackground);
+ SendMessage(dat->hwndProgress,PBM_SETBARCOLOR,0,(LPARAM)clrBar);
+ SendMessage(dat->hwndProgress,PBM_SETBKCOLOR,0,(LPARAM)dat->clrBackground);
+ InvalidateRect(hwndFrame,NULL,TRUE);
+ return 0;
+ }
+ case M_REFRESH_ICONS:
+ if(dat->hwndIcon!=NULL)
+ IcoLib_ReleaseIcon((HICON)SendMessage(dat->hwndIcon,STM_SETIMAGE,IMAGE_ICON,(LPARAM)IcoLib_GetIcon("AutoShutdown_Header")));
+ if(hFrame) /* refresh frame title icon */
+ IcoLib_ReleaseIcon(SetFrameTitleIcon(hFrame,IcoLib_GetIcon("AutoShutdown_Active")));
+ return 0;
+ case M_REFRESH_FONTS:
+ { LOGFONT lf;
+ if(!FontService_GetFont(TranslateT("Automatic Shutdown"),TranslateT("Countdown on Frame"),&dat->clrText,&lf)) {
+ if(dat->hFont!=NULL) DeleteObject(dat->hFont);
+ dat->hFont=CreateFontIndirect(&lf);
+ }
+ else {
+ dat->clrText=GetDefaultColor(FRAMEELEMENT_TEXT);
+ if(GetDefaultFont(&lf)!=NULL) {
+ if(dat->hFont!=NULL) DeleteObject(dat->hFont);
+ dat->hFont=CreateFontIndirect(&lf);
+ }
+ }
+ if(dat->hwndDesc!=NULL)
+ SendMessage(dat->hwndDesc,WM_SETFONT,(WPARAM)dat->hFont,FALSE);
+ SendMessage(dat->hwndTime,WM_SETFONT,(WPARAM)dat->hFont,FALSE);
+ InvalidateRect(hwndFrame,NULL,FALSE);
+ return 0;
+ }
+ case WM_SYSCOLORCHANGE:
+ SendMessage(hwndFrame,M_REFRESH_COLORS,0,0);
+ break;
+ case WM_SETTINGCHANGE: /* colors depend on windows settings */
+ SendMessage(hwndFrame,M_REFRESH_COLORS,0,0);
+ SendMessage(hwndFrame,M_REFRESH_FONTS,0,0);
+ SendMessage(hwndFrame,M_UPDATE_COUNTDOWN,0,0);
+ RedrawWindow(hwndFrame,NULL,NULL,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_ERASE);
+ break;
+ case WM_TIMECHANGE: /* windows system clock changed */
+ SendMessage(hwndFrame,M_SET_COUNTDOWN,0,0);
+ PostMessage(hwndFrame,M_UPDATE_COUNTDOWN,0,0);
+ break;
+ case WM_CTLCOLORDLG:
+ case WM_CTLCOLORSTATIC:
+ SetTextColor((HDC)wParam,dat->clrText);
+ SetBkColor((HDC)wParam,dat->clrBackground);
+ return (BOOL)dat->hbrBackground;
+ case WM_ERASEBKGND:
+ { RECT rc;
+ if(dat->hbrBackground!=NULL && GetClientRect(hwndFrame,&rc)) {
+ FillRect((HDC)wParam,&rc,dat->hbrBackground);
+ return TRUE;
+ }
+ return FALSE;
+ }
+ case M_SET_COUNTDOWN:
+ if(dat->fTimeFlags&SDWTF_ST_TIME) {
+ dat->settingLastTime=(time_t)DBGetContactSettingDword(NULL,"AutoShutdown","TimeStamp",SETTING_TIMESTAMP_DEFAULT);
+ dat->countdown=time(NULL);
+ if(dat->settingLastTime>dat->countdown) dat->countdown=dat->settingLastTime-dat->countdown;
+ else dat->countdown=0;
+ }
+ else if(dat->flags&FWPDF_COUNTDOWNINVALID) {
+ dat->countdown=(time_t)DBGetContactSettingDword(NULL,"AutoShutdown","Countdown",SETTING_COUNTDOWN_DEFAULT);
+ dat->countdown*=(time_t)DBGetContactSettingDword(NULL,"AutoShutdown","CountdownUnit",SETTING_COUNTDOWNUNIT_DEFAULT);
+ }
+ dat->flags&=~FWPDF_COUNTDOWNINVALID;
+ /* commctl 4.70+, Win95: 1-100 will work fine (wrap around) */
+ SendMessage(dat->hwndProgress,PBM_SETRANGE32,(WPARAM)0,(LPARAM)dat->countdown);
+ return 0;
+ case WM_TIMER:
+ if(dat==NULL) return 0;
+ if(dat->countdown!=0 && !(dat->flags&FWPDF_COUNTDOWNINVALID) && !(dat->flags&FWPDF_PAUSED)) {
+ dat->countdown--;
+ PostMessage(dat->hwndProgress,PBM_STEPIT,0,0);
+ }
+ if(IsWindowVisible(hwndFrame)) PostMessage(hwndFrame,M_UPDATE_COUNTDOWN,0,0);
+ if(dat->countdown==0) {
+ SendMessage(hwndFrame,M_CLOSE_COUNTDOWN,0,0);
+ ServiceShutdown(0,TRUE);
+ ServiceStopWatcher(0,0);
+ }
+ return 0;
+ case WM_SHOWWINDOW:
+ /* the text is kept unchanged while hidden */
+ if((BOOL)wParam) SendMessage(hwndFrame,M_UPDATE_COUNTDOWN,0,0);
+ break;
+ case M_UPDATE_COUNTDOWN:
+ if(dat->flags&FWPDF_PAUSED && !(dat->flags&FWPDF_PAUSEDSHOWN)) {
+ SetWindowText(dat->hwndTime,TranslateT("Paused"));
+ dat->flags|=FWPDF_PAUSEDSHOWN;
+ }
+ else {
+ TCHAR szOutput[256];
+ if(dat->fTimeFlags&SDWTF_ST_TIME)
+ GetFormatedDateTime(szOutput,SIZEOF(szOutput),dat->settingLastTime,TRUE);
+ else GetFormatedCountdown(szOutput,SIZEOF(szOutput),dat->countdown);
+ SetWindowText(dat->hwndTime,szOutput);
+ PostMessage(hwndFrame,M_CHECK_CLIPPED,0,0);
+ /* update tooltip text (if shown) */
+ if(dat->hwndToolTip!=NULL && !(dat->flags&FWPDF_PAUSED)) {
+ TTTOOLINFO ti;
+ ti.cbSize=sizeof(ti);
+ if(SendMessage(dat->hwndToolTip,TTM_GETCURRENTTOOL,0,(LPARAM)&ti) && (HWND)ti.uId!=dat->hwndIcon)
+ SendMessage(dat->hwndToolTip,TTM_UPDATE,0,0);
+ } else dat->flags&=~FWPDF_PAUSEDSHOWN;
+ }
+ return 0;
+ case M_CLOSE_COUNTDOWN:
+ KillTimer(hwndFrame,1);
+ dat->countdown=0;
+ dat->flags&=~FWPDF_PAUSED;
+ SendMessage(hwndFrame,M_UPDATE_COUNTDOWN,0,0);
+ dat->flags|=FWPDF_COUNTDOWNINVALID;
+ /* step up to upper range */
+ SendMessage(dat->hwndProgress,PBM_SETPOS,SendMessage(dat->hwndProgress,PBM_GETRANGE,FALSE,0),0);
+ SetWindowLong(dat->hwndProgress,GWL_STYLE,GetWindowLong(dat->hwndProgress,GWL_STYLE)|PBM_SETMARQUEE);
+ SendMessage(dat->hwndProgress,PBM_SETMARQUEE,TRUE,10); /* marquee for rest of time */
+ return 0;
+ case M_PAUSE_COUNTDOWN:
+ if(dat->flags&FWPDF_PAUSED) {
+ /* unpause */
+ dat->flags&=~(FWPDF_PAUSED|FWPDF_PAUSEDSHOWN);
+ SendMessage(hwndFrame,M_SET_COUNTDOWN,0,0);
+ SendMessage(dat->hwndProgress,PBM_SETSTATE,PBST_NORMAL,0); /* WinVista+ */
+ }
+ else {
+ /* pause */
+ dat->flags|=FWPDF_PAUSED;
+ SendMessage(dat->hwndProgress,PBM_SETSTATE,PBST_PAUSED,0); /* WinVista+ */
+ }
+ SendMessage(hwndFrame,M_UPDATE_COUNTDOWN,0,0);
+ return 0;
+ case WM_CONTEXTMENU:
+ { HMENU hContextMenu;
+ POINT pt;
+ if(dat->flags&FWPDF_COUNTDOWNINVALID) return 0;
+ POINTSTOPOINT(pt,MAKEPOINTS(lParam));
+ if(pt.x==-1 && pt.y==-1) { /* invoked by keyboard */
+ RECT rc;
+ /* position in middle above rect */
+ if(!GetWindowRect(hwndFrame, &rc)) return 0;
+ pt.x=rc.left+((int)(rc.right-rc.left)/2);
+ pt.y=rc.top+((int)(rc.bottom-rc.top)/2);
+ }
+ hContextMenu=CreatePopupMenu();
+ if(hContextMenu!=NULL) {
+ AppendMenu(hContextMenu,MF_STRING,MENUITEM_PAUSECOUNTDOWN,(dat->flags&FWPDF_PAUSED)?TranslateT("&Unpause Countdown"):TranslateT("&Pause Countdown"));
+ SetMenuDefaultItem(hContextMenu,MENUITEM_PAUSECOUNTDOWN,FALSE);
+ AppendMenu(hContextMenu,MF_STRING,MENUITEM_STOPCOUNTDOWN,TranslateT("&Cancel Countdown"));
+ TrackPopupMenuEx(hContextMenu,TPM_LEFTALIGN|TPM_TOPALIGN|TPM_HORPOSANIMATION|TPM_VERPOSANIMATION|TPM_RIGHTBUTTON,pt.x,pt.y,hwndFrame,NULL);
+ DestroyMenu(hContextMenu);
+ }
+ return 0;
+ }
+ case WM_LBUTTONDBLCLK:
+ if(!(dat->flags&FWPDF_COUNTDOWNINVALID))
+ SendMessage(hwndFrame,M_PAUSE_COUNTDOWN,0,0);
+ return 0;
+ case WM_COMMAND:
+ switch(LOWORD(wParam)) {
+ case MENUITEM_STOPCOUNTDOWN:
+ /* close only countdown window when other watcher types running */
+ if(dat->fTimeFlags&~(SDWTF_SPECIFICTIME|SDWTF_ST_MASK))
+ CloseCountdownFrame(); /* something else is running */
+ else ServiceStopWatcher(0,0); /* calls CloseCountdownFrame() */
+ return 0;
+ case MENUITEM_PAUSECOUNTDOWN:
+ SendMessage(hwndFrame,M_PAUSE_COUNTDOWN,0,0);
+ return 0;
+ }
+ break;
+ case M_CHECK_CLIPPED: /* for in-place tooltip on dat->hwndTime */
+ { RECT rc;
+ HDC hdc;
+ SIZE size;
+ HFONT hFontPrev=NULL;
+ TCHAR szOutput[256];
+ dat->flags&=~FWPDF_TIMEISCLIPPED;
+ if(GetWindowText(dat->hwndTime,szOutput,SIZEOF(szOutput)-1))
+ if(GetClientRect(dat->hwndTime,&rc)) {
+ hdc=GetDC(dat->hwndTime);
+ if(hdc!=NULL) {
+ if(dat->hFont!=NULL)
+ hFontPrev=SelectObject(hdc,dat->hFont);
+ if(GetTextExtentPoint32(hdc,szOutput,lstrlen(szOutput),&size))
+ if(size.cx>=(rc.right-rc.left))
+ dat->flags&=FWPDF_TIMEISCLIPPED;
+ if(dat->hFont!=NULL)
+ SelectObject(hdc,hFontPrev);
+ ReleaseDC(dat->hwndTime,hdc);
+ }
+ }
+ return 0;
+ }
+ case WM_NOTIFY:
+ if(((NMHDR*)lParam)->hwndFrom==dat->hwndToolTip)
+ switch(((NMHDR*)lParam)->code) {
+ case TTN_SHOW: /* 'in-place' tooltip on dat->hwndTime */
+ if(dat->flags&FWPDF_TIMEISCLIPPED && (HWND)wParam==dat->hwndTime && IsWinVer2000Plus()) {
+ RECT rc;
+ if(GetWindowRect(dat->hwndTime,&rc)) {
+ SetWindowLong(dat->hwndToolTip,GWL_STYLE,GetWindowLong(dat->hwndToolTip,GWL_STYLE)|TTS_NOANIMATE);
+ SetWindowLong(dat->hwndToolTip,GWL_EXSTYLE,GetWindowLong(dat->hwndToolTip,GWL_EXSTYLE)|WS_EX_TRANSPARENT);
+ SendMessage(dat->hwndToolTip,TTM_ADJUSTRECT,TRUE,(LPARAM)&rc);
+ SetWindowPos(dat->hwndToolTip,NULL,rc.left,rc.top,0,0,SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
+ return TRUE; /* self-defined position */
+ }
+ }
+ SetWindowLong(dat->hwndToolTip,GWL_STYLE,GetWindowLong(dat->hwndToolTip,GWL_STYLE)&(~TTS_NOANIMATE));
+ SetWindowLong(dat->hwndToolTip,GWL_EXSTYLE,GetWindowLong(dat->hwndToolTip,GWL_EXSTYLE)&(~WS_EX_TRANSPARENT));
+ return 0;
+ case TTN_POP:
+ /* workaround #5: frame does not get redrawn after
+ * in-place tooltip hidden on dat->hwndTime */
+ RedrawWindow(hwndCountdownFrame,NULL,NULL,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_ERASE);
+ return 0;
+ case TTN_NEEDTEXT:
+ { NMTTDISPINFO *ttdi=(NMTTDISPINFO*)lParam;
+ if(dat->flags&FWPDF_TIMEISCLIPPED && (HWND)wParam==dat->hwndTime) {
+ if(GetWindowText(dat->hwndTime,ttdi->szText,SIZEOF(ttdi->szText)-1))
+ ttdi->lpszText=ttdi->szText;
+ }
+ else if((HWND)wParam==dat->hwndIcon)
+ ttdi->lpszText=TranslateT("Automatic Shutdown");
+ else {
+ TCHAR szTime[SIZEOF(ttdi->szText)];
+ if(dat->fTimeFlags&SDWTF_ST_TIME)
+ GetFormatedDateTime(szTime,SIZEOF(szTime),dat->settingLastTime,FALSE);
+ else GetFormatedCountdown(szTime,SIZEOF(szTime),dat->countdown);
+ mir_sntprintf(ttdi->szText,SIZEOF(ttdi->szText),_T("%s %s"),(dat->fTimeFlags&SDWTF_ST_TIME)?TranslateT("Shutdown at:"):TranslateT("Time left:"),szTime);
+ ttdi->lpszText=ttdi->szText;
+ }
+ return 0;
+ }
+ }
+ break;
+ }
+ return DefWindowProc(hwndFrame,msg,wParam,lParam);
+}
+
+/************************* Show Frame *********************************/
+
+void ShowCountdownFrame(WORD fTimeFlags)
+{
+ hwndCountdownFrame=CreateWindowEx(WS_EX_CONTROLPARENT|WS_EX_NOPARENTNOTIFY|WS_EX_TRANSPARENT,
+ COUNTDOWNFRAME_CLASS,
+ NULL,
+ WS_CHILD|WS_TABSTOP,
+ 0, 0,
+ GetSystemMetrics(SM_CXICON)+103,
+ GetSystemMetrics(SM_CYICON)+2,
+ (HWND)CallService(MS_CLUI_GETHWND,0,0),
+ NULL,
+ hInst,
+ &fTimeFlags);
+ if(hwndCountdownFrame==NULL) return;
+
+ if(ServiceExists(MS_CLIST_FRAMES_ADDFRAME)) {
+ CLISTFrame clf;
+ ZeroMemory(&clf,sizeof(clf));
+ clf.cbSize=sizeof(clf);
+ clf.hIcon=IcoLib_GetIcon("AutoShutdown_Active"); /* CListFrames does not make a copy */
+ clf.align=alBottom;
+ clf.height=GetSystemMetrics(SM_CYICON);
+ clf.Flags=F_VISIBLE|F_SHOWTBTIP|F_NOBORDER|F_SKINNED;
+ clf.name=Translate("AutoShutdown");
+ clf.TBname=Translate("Automatic Shutdown");
+ clf.hWnd=hwndCountdownFrame;
+ hFrame=(WORD)CallService(MS_CLIST_FRAMES_ADDFRAME,(WPARAM)&clf,0);
+ if(hFrame) {
+ ShowWindow(hwndCountdownFrame,SW_SHOW);
+ CallService(MS_CLIST_FRAMES_SETFRAMEOPTIONS,MAKEWPARAM(FO_TBTIPNAME,hFrame),(LPARAM)clf.name);
+ /* HACKS TO FIX CLUI FRAMES:
+ * *** why is CLUIFrames is horribly buggy??! *** date: sept 2005, nothing changed until sept 2006
+ * workaround #1: MS_CLIST_FRAMES_REMOVEFRAME does not finish with destroy cycle (clist_modern, clist_nicer crashes) */
+ SendMessage((HWND)CallService(MS_CLUI_GETHWND,0,0),WM_SIZE,0,0);
+ /* workaround #2: drawing glitch after adding a frame (frame positioned wrongly when hidden) */
+ CallService(MS_CLIST_FRAMES_UPDATEFRAME,hFrame,FU_FMPOS|FU_FMREDRAW);
+ /* workaround #3: MS_CLIST_FRAMES_SETFRAMEOPTIONS does cause redrawing problems */
+ if(!(CallService(MS_CLIST_FRAMES_GETFRAMEOPTIONS,MAKEWPARAM(FO_FLAGS,hFrame),0)&F_VISIBLE))
+ CallService(MS_CLIST_FRAMES_SHFRAME,hFrame,0);
+ /* workaround #4: MS_CLIST_FRAMES_SHFRAME does cause redrawing problems when frame was hidden */
+ RedrawWindow(hwndCountdownFrame,NULL,NULL,RDW_INVALIDATE|RDW_ALLCHILDREN|RDW_ERASE);
+ /* workaround #5: for in-place tooltip TTN_POP
+ * workaround #6 and #7: see CloseCountdownFrame() */
+ }
+ }
+}
+
+void CloseCountdownFrame(void)
+{
+ if(hwndCountdownFrame!=NULL) {
+ SendMessage(hwndCountdownFrame,M_CLOSE_COUNTDOWN,0,0);
+ if(hFrame) {
+ IcoLib_ReleaseIcon(SetFrameTitleIcon(hFrame,NULL));
+ /* HACKS TO FIX CLUIFrames:
+ * workaround #6: MS_CLIST_FRAMES_REMOVEFRAME does not finish with
+ * destroy cycle (clist_modern, clist_nicer crashes) */
+ CallService(MS_CLIST_FRAMES_SETFRAMEOPTIONS,MAKEWPARAM(FO_FLAGS,hFrame),(LPARAM)CallService(MS_CLIST_FRAMES_GETFRAMEOPTIONS,MAKEWPARAM(FO_FLAGS,hFrame),0)&(~F_VISIBLE));
+ #if !defined(_DEBUG)
+ /* workaround #7: MS_CLIST_FRAMES_REMOVEFRAME crashes after two calls
+ * clist_nicer crashes after some calls (bug in it) */
+ CallService(MS_CLIST_FRAMES_REMOVEFRAME,hFrame,0);
+ #endif
+ }
+ else DestroyWindow(hwndCountdownFrame);
+ hwndCountdownFrame=NULL;
+ hFrame=0;
+ }
+
+}
+
+/************************* Misc ***************************************/
+
+static int FrameModulesLoaded(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ if(ServiceExists(MS_CLIST_FRAMES_ADDFRAME)) {
+ LOGFONT lf;
+ COLORREF clr;
+ HMODULE hUxThemeDLL;
+ BOOL (WINAPI *pfnIsThemeActive)(VOID);
+ /* built-in font module is not available before this hook */
+ clr=GetDefaultColor(FRAMEELEMENT_TEXT);
+ FontService_RegisterFont("AutoShutdown","CountdownFont",TranslateT("Automatic Shutdown"),TranslateT("Countdown on Frame"),0,FALSE,GetDefaultFont(&lf),clr);
+ clr=GetDefaultColor(FRAMEELEMENT_BKGRND);
+ FontService_RegisterColor("AutoShutdown","BkgColor",TranslateT("Automatic Shutdown"),TranslateT("Background"),clr);
+ /* progressbar color can only be changed in windows classic theme */
+ /* FIXME: should be registered/unregistered on WM_THEMECHANGED/ME_OPT_INITIALISE msg,
+ * currently not possible as no such font service exists */
+ hUxThemeDLL=LoadLibraryA("UXTHEME"); /* all ascii */
+ *(PROC*)&pfnIsThemeActive=(hUxThemeDLL!=NULL)?GetProcAddress(hUxThemeDLL,"IsThemeActive"):NULL;
+ if(pfnIsThemeActive==NULL || !pfnIsThemeActive()) {
+ /* progressbar color can only be changed with classic theme */
+ clr=GetDefaultColor(FRAMEELEMENT_BAR);
+ FontService_RegisterColor("AutoShutdown","ProgressColor",TranslateT("Automatic Shutdown"),TranslateT("Progress Bar"),clr);
+ }
+ if(hUxThemeDLL!=NULL) FreeLibrary(hUxThemeDLL);
+ }
+ return 0;
+}
+
+int InitFrame(void)
+{
+ WNDCLASSEX wcx;
+ ZeroMemory(&wcx,sizeof(wcx));
+ wcx.cbSize =sizeof(wcx);
+ wcx.style =CS_DBLCLKS|CS_PARENTDC;
+ wcx.lpfnWndProc =FrameWndProc;
+ wcx.hInstance =hInst;
+ wcx.hCursor =(HCURSOR)LoadImage(NULL,IDC_ARROW,IMAGE_CURSOR,0,0,LR_SHARED);
+ wcx.lpszClassName =COUNTDOWNFRAME_CLASS;
+ if(!RegisterClassEx(&wcx)) return 1;
+
+ hwndCountdownFrame=NULL;
+ hHookModulesLoaded=HookEvent(ME_SYSTEM_MODULESLOADED,FrameModulesLoaded);
+ return 0;
+}
+
+void UninitFrame(void)
+{
+ /* frame closed by UninitWatcher() */
+ UnregisterClass(COUNTDOWNFRAME_CLASS,hInst); /* fails if window still exists */
+ UnhookEvent(hHookModulesLoaded);
+}
diff --git a/plugins/AutoShutdown/frame.h b/plugins/AutoShutdown/frame.h
new file mode 100644
index 0000000000..1b0bffdafd
--- /dev/null
+++ b/plugins/AutoShutdown/frame.h
@@ -0,0 +1,28 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+/* Show Frame */
+void ShowCountdownFrame(WORD fTimeFlags);
+void CloseCountdownFrame(void);
+
+/* Misc */
+int InitFrame(void);
+void UninitFrame(void); \ No newline at end of file
diff --git a/plugins/AutoShutdown/m_shutdown.h b/plugins/AutoShutdown/m_shutdown.h
new file mode 100644
index 0000000000..87e25e8851
--- /dev/null
+++ b/plugins/AutoShutdown/m_shutdown.h
@@ -0,0 +1,196 @@
+/*
+
+'AutoShutdown'-Plugin for
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright (C) 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#ifndef M_SHUTDOWN_H__
+#define M_SHUTDOWN_H__
+
+#if defined (_MSC_VER) && (_MSC_VER >= 1020)
+ #pragma once
+#endif
+
+/*
+ AutoShutdown v1.4.0.2
+*/
+
+/* interface id */
+#if !defined(MIID_SHUTDOWN)
+ #define MIID_SHUTDOWN {0x142982a8,0x88cf,0x4c65,{0x87,0x21,0x6d,0xe2,0x7d,0x5c,0xe7,0xb5}}
+#endif
+
+/******************************************************************/
+/************************* SERVICES *******************************/
+/******************************************************************/
+
+/* Show settings dialog v1.3.0.0+
+Shows the dialog by which the shutdown watcher can be started.
+If the dialog is already opened this brings it to foreground.
+ wParam=lParam=0
+Returns 0 on success, nonzero otherwise.
+*/
+#define MS_AUTOSHUTDOWN_SHOWSETTINGSDIALOG "AutoShutdown/ShowSettingsDialog"
+
+/* Initiate shutdown process v1.3.0.0+
+Initiates the shutdown process for a given shutdown type.
+If another shutdown process is already pending it will return error.
+Associated events: ME_AUTOSHUTDOWN_OKTOSHUTDOWN, ME_AUTOSHUTDOWN_SHUTDOWN
+ wParam=shutdownType
+ lParam=(LPARAM)(BOOL)fShowConfirmDlg (whether to show the warning dialog or not)
+Returns 0 on success, nonzero otherwise.
+*/
+#define MS_AUTOSHUTDOWN_SHUTDOWN "AutoShutdown/Shutdown"
+
+/* shutdown types */
+#define SDSDT_CLOSEMIRANDA 1 // close miranda process
+#define SDSDT_SETMIRANDAOFFLINE 2 // set all protocols to offline
+#define SDSDT_LOGOFF 3 // logoff from Windows
+#define SDSDT_REBOOT 4 // reboot computer
+#define SDSDT_SHUTDOWN 5 // shutdown Windows and power off
+#define SDSDT_STANDBY 6 // standby mode
+#define SDSDT_HIBERNATE 7 // hibernate mode
+#define SDSDT_LOCKWORKSTATION 8 // lock the workstation
+#define SDSDT_CLOSERASCONNECTIONS 9 // close all dialup connections
+#define SDSDT_MAX 9
+
+/* Get shutdown type description v1.4.0.0+
+Gets a textual description of the given shutdown type.
+ wParam=shutdownType
+ lParam=flags (see GSTDF_* below)
+Returns a static buffer of the description of the given shutdown type.
+It does not need to be freed in any way.
+The returned text is already translated.
+Returns a pointer to a string on success, NULL on error.
+*/
+#define MS_AUTOSHUTDOWN_GETTYPEDESCRIPTION "AutoShutdown/GetTypeDescription"
+
+#define GSTDF_LONGDESC 0x0001 // returns a long description
+#define GSTDF_UNICODE 0x0002 // returns a Unicode string
+#define GSTDF_UNTRANSLATED 0x0004 // returns an untranslated string
+#if defined(_UNICODE)
+ #define GSTDF_TCHAR GSTDF_UNICODE // will return WCHAR*
+#else
+ #define GSTDF_TCHAR 0 // will return char*, as usual
+#endif
+
+/* Check if shutdown type is enabled v1.4.0.0+
+Tests if a specific shutdown type is activated and its use is possible
+on the system. For example hibernate and stand-by modes are not available on
+older versions of Windows (needs Windows ME/2000+).
+Shutdown might also be prohibited by security restrictions.
+This services checks it all.
+However, there is no need to call this before calling MS_AUTOSHUTDOWN_SHUTDOWN.
+MS_AUTOSHUTDOWN_SHUTDOWN will fail if the given shutdown type is not enabled.
+ wParam=shutdownType
+ lParam=0
+Returns TRUE if the given shutdown type is enabled, FALSE otherwise.
+*/
+#define MS_AUTOSHUTDOWN_ISTYPEENABLED "AutoShutdown/IsTypeEnabled"
+
+/* Start shutdown watcher v1.4.0.0+
+Starts the watcher using the last settings specified on the dialog
+shown by MS_AUTOSHUTDOWN_SHOWSETTINGSDIALOG.
+Call MS_AUTOSHUTDOWN_SHOWSETTINGSDIALOG instead to offer
+options about what watcher to use.
+Associated event: ME_AUTOSHUTDOWN_WATCHERCHANGED
+ wParam=lParam=0
+Returns 0 on success, nonzero otherwise.
+*/
+#define MS_AUTOSHUTDOWN_STARTWATCHER "AutoShutdown/StartWatcher"
+
+/* Stop shutdown watcher v1.4.0.0+
+Stops the currently running watcher.
+If the watcher is not running, it returns error.
+Associated event: ME_AUTOSHUTDOWN_WATCHERCHANGED
+ wParam=lParam=0
+Returns 0 on success, nonzero otherwise.
+*/
+#define MS_AUTOSHUTDOWN_STOPWATCHER "AutoShutdown/StopWatcher"
+
+/* Check if watcher is running v1.4.0.0+
+Checks if the watcher is currently active or not.
+ wParam=lParam=0
+Returns TRUE if the watcher is enabled, FALSE otherwise.
+*/
+#define MS_AUTOSHUTDOWN_ISWATCHERENABLED "AutoShutdown/IsWatcherEnabled"
+
+/******************************************************************/
+/************************** EVENTS ********************************/
+/******************************************************************/
+
+/* Disallow shutdown process (event) v1.3.0.0+
+Gets fired when MS_AUTOSHUTDOWN_SHUTDOWN is called.
+Parmeters are the same as specified at the call to MS_AUTOSHUTDOWN_SHUTDOWN.
+ wParam=shutdownType
+ lParam=(LPARAM)(BOOL)fShowConfirmDlg
+Return 0 to allow shutdown, 1 to disallow.
+*/
+#define ME_AUTOSHUTDOWN_OKTOSHUTDOWN "AutoShutdown/OkToShutdown"
+
+/* Shutdown process started (event) v1.3.0.1+
+Gets fired when ME_AUTOSHUTDOWN_OKTOSHUTDOWN was confirmed.
+Parmeters are the same as specified at the call
+to MS_AUTOSHUTDOWN_SHUTDOWN.
+ wParam=shutdownType
+ lParam=(LPARAM)(BOOL)fShowConfirmDlg
+Unused, return always 0 here.
+*/
+#define ME_AUTOSHUTDOWN_SHUTDOWN "AutoShutdown/ShutdownEvent"
+
+/* Watcher changed (event) v1.3.0.0+
+Fired when MS_AUTOSHUTDOWN_STARTWATCHER or MS_AUTOSHUTDOWN_STOPWATCHER
+is called.
+ wParam=(WPARAM)(BOOL)fIsStarted (whether whe watcher is running now)
+ lParam=0
+Unused, return always 0 here.
+*/
+#define ME_AUTOSHUTDOWN_WATCHERCHANGED "AutoShutdown/Watcher/Changed"
+
+
+#ifndef SHUTDOWN_NOSETTINGS
+#define SETTING_REMEMBERONRESTART_DEFAULT 0 // SDROR_RUNNING
+#define SETTING_SHOWCONFIRMDLG_DEFAULT 1
+#define SETTING_CONFIRMDLGCOUNTDOWN_DEFAULT 30 // seconds
+#define SETTING_WEATHERSHUTDOWN_DEFAULT 0
+#define SETTING_HDDOVERHEATSHUTDOWN_DEFAULT 1
+#define SETTING_SMARTOFFLINECHECK_DEFAULT 1
+
+#define SETTING_SHUTDOWNTYPE_DEFAULT SDSDT_SHUTDOWN
+#define SETTING_WATCHERFLAGS_DEFAULT (SDWTF_SPECIFICTIME|SDWTF_ST_COUNTDOWN)
+#define SETTING_COUNTDOWN_DEFAULT 30
+#define SETTING_COUNTDOWNUNIT_DEFAULT 60 // x times countdown seconds
+#define SETTING_TIMESTAMP_DEFAULT (DWORD)(time(NULL)+(SETTING_COUNTDOWN_DEFAULT*SETTING_COUNTDOWNUNIT_DEFAULT))
+#define SETTING_CPUUSAGETHRESHOLD_DEFAULT 90 // percent
+
+#define SDWTF_SPECIFICTIME 0x0001
+#define SDWTF_ST_TIME 0x0002
+#define SDWTF_ST_COUNTDOWN 0x0004
+#define SDWTF_ST_MASK 0x0006 /* bitmask for SDWTF_ST_* bits */
+#define SDWTF_MESSAGE 0x0008
+#define SDWTF_FILETRANSFER 0x0010
+#define SDWTF_IDLE 0x0020
+#define SDWTF_STATUS 0x0040
+#define SDWTF_CPUUSAGE 0x0080
+#define SDWTF_MASK 0x00FF /* bitmask for all SDWTF_* bits */
+
+#define SDROR_RUNNING 3
+#endif
+
+#endif // M_SHUTDOWN_H
diff --git a/plugins/AutoShutdown/main.c b/plugins/AutoShutdown/main.c
new file mode 100644
index 0000000000..d4f9a63480
--- /dev/null
+++ b/plugins/AutoShutdown/main.c
@@ -0,0 +1,192 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include "common.h"
+#include "version.h"
+
+HINSTANCE hInst;
+PLUGINLINK *pluginLink;
+struct MM_INTERFACE mmi;
+static HANDLE hHookModulesLoaded;
+HANDLE hActiveIcon,hInactiveIcon;
+
+PLUGININFOEX pluginInfo={
+ sizeof(PLUGININFOEX),
+ "AutoShutdown",
+ PLUGIN_VERSION,
+#if defined(_DEBUG)
+ "Development build not intended for release. ("__DATE__")",
+#else
+ "Adds the possibility to shutdown the computer when a specified event occurs.", /* autotranslated */
+#endif
+ "H. Herkenrath",
+ PLUGIN_EMAIL, /* @ will be set later */
+ "� 2004-2007 H. Herkenrath",
+ PLUGIN_WEBSITE,
+ UNICODE_AWARE,
+ 0,
+#if defined(_UNICODE)
+ // {9DE24579-5C5C-49aa-80E8-4D38E4344E63}
+ {0x9de24579,0x5c5c,0x49aa,{0x80,0xe8,0x4d,0x38,0xe4,0x34,0x4e,0x63}},
+#else
+ // {7C0DD208-94D8-4283-879A-E6F86135B826}
+ {0x7c0dd208,0x94d8,0x4283,{0x87,0x9a,0xe6,0xf8,0x61,0x35,0xb8,0x26}}
+#endif
+};
+static const MUUID interfaces[]={MIID_SHUTDOWN,MIID_LAST};
+
+BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,void *pReserved)
+{
+ UNREFERENCED_PARAMETER(pReserved);
+ if(fdwReason==DLL_PROCESS_ATTACH)
+ /* Do not call this function from a DLL that is linked to the static C run-time library (CRT).
+ * The static CRT requires DLL_THREAD_ATTACH and DLL_THREAD_DETATCH notifications to function properly. */
+ DisableThreadLibraryCalls(hInst=hinstDLL);
+ return TRUE;
+}
+
+static void InstallFile(const TCHAR *pszFileName,const TCHAR *pszDestSubDir)
+{
+ TCHAR szFileFrom[MAX_PATH+1],szFileTo[MAX_PATH+1],*p;
+ HANDLE hFile;
+
+ if(!GetModuleFileName(hInst,szFileFrom,SIZEOF(szFileFrom)-lstrlen(pszFileName)))
+ return;
+ p=_tcsrchr(szFileFrom,_T('\\'));
+ if(p!=NULL) *(++p)=0;
+ lstrcat(szFileFrom,pszFileName); /* buffer safe */
+
+ hFile=CreateFile(szFileFrom,0,FILE_SHARE_READ,0,OPEN_EXISTING,0,0);
+ if(hFile==INVALID_HANDLE_VALUE) return;
+ CloseHandle(hFile);
+
+ if(!GetModuleFileName(NULL,szFileTo,SIZEOF(szFileTo)-lstrlen(pszDestSubDir)-lstrlen(pszFileName)))
+ return;
+ p=_tcsrchr(szFileTo,_T('\\'));
+ if(p!=NULL) *(++p)=0;
+ lstrcat(szFileTo,pszDestSubDir); /* buffer safe */
+ CreateDirectory(szFileTo,NULL);
+ lstrcat(szFileTo,pszFileName); /* buffer safe */
+
+ if(!MoveFile(szFileFrom,szFileTo) && GetLastError()==ERROR_ALREADY_EXISTS) {
+ DeleteFile(szFileTo);
+ MoveFile(szFileFrom,szFileTo);
+ }
+}
+
+static int ShutdownModulesLoaded(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ if(ServiceExists("DBEditorpp/RegisterSingleModule"))
+ CallService("DBEditorpp/RegisterSingleModule",(WPARAM)"AutoShutdown",0);
+ /* merged thundershutdown plugin */
+ if(GetModuleHandleA("tshutdown.dll")) {
+ DBWriteContactSettingByte(NULL,"PluginDisable","tshutdown.dll",1);
+ DBWriteContactSettingByte(NULL,"AutoShutdown","WeatherShutdown",1);
+ }
+ return 0;
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+__declspec(dllexport) const PLUGININFO* MirandaPluginInfo(DWORD mirandaVersion)
+{
+ if(mirandaVersion<PLUGIN_MAKE_VERSION(0,1,0,1)) return NULL;
+ pluginInfo.cbSize=sizeof(PLUGININFO); /* needed as v0.6 does equality check */
+ /* email obfuscated, made .rdata writable */
+ pluginInfo.authorEmail[PLUGIN_EMAIL_ATT_POS-1]='@';
+ return (PLUGININFO*)&pluginInfo; /* header is the same */
+}
+
+__declspec(dllexport) const PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
+{
+ UNREFERENCED_PARAMETER(mirandaVersion);
+ pluginInfo.cbSize=sizeof(PLUGININFOEX);
+ /* email obfuscated, made .rdata writable */
+ pluginInfo.authorEmail[PLUGIN_EMAIL_ATT_POS-1]='@';
+ return &pluginInfo;
+}
+
+__declspec(dllexport) const MUUID* MirandaPluginInterfaces(void)
+{
+ return interfaces;
+}
+
+__declspec(dllexport) int Load(PLUGINLINK *link)
+{
+ INITCOMMONCONTROLSEX icc;
+ pluginLink=link;
+
+ /* existance of MS_SYSTEM_GETVERSION and MS_LANGPACK_TRANSLATESTRING
+ * is checked in MirandaPluginInfo().
+ * Not placed in MirandaPluginInfo() to avoid MessageBoxes on plugin options.
+ * Using ANSI as LANG_UNICODE might not be supported. */
+ if(CallService(MS_SYSTEM_GETVERSION,0,0)<NEEDED_MIRANDA_VERSION) {
+ char szText[256];
+ mir_snprintf(szText,sizeof(szText),Translate("The AutoShutdown plugin can not be loaded. It requires Miranda IM %hs or later."),NEEDED_MIRANDA_VERSION_STR);
+ MessageBoxA(NULL,szText,Translate("AutoShutdown Plugin"),MB_OK|MB_ICONERROR|MB_SETFOREGROUND|MB_TOPMOST|MB_TASKMODAL);
+ return 1;
+ }
+ if(!ServiceExists(MS_DB_CONTACT_GETSETTING_STR)) return 1; /* dbx3x v0.5.1.0 */
+ if(mir_getMMI(&mmi)) return 1;
+ icc.dwSize=sizeof(icc);
+ icc.dwICC=ICC_DATE_CLASSES|ICC_UPDOWN_CLASS|ICC_PROGRESS_CLASS;
+ if(!InitCommonControlsEx(&icc)) return 1;
+
+ if(InitFrame()) return 1; /* before icons */
+
+ /* shared */
+ IcoLib_AddIconRes("AutoShutdown_Header",TranslateT("Automatic Shutdown"),TranslateT("Header"),hInst,IDI_HEADER,TRUE);
+ hActiveIcon=IcoLib_AddIconRes("AutoShutdown_Active",TranslateT("Automatic Shutdown"),TranslateT("Active"),hInst,IDI_ACTIVE,FALSE);
+ hInactiveIcon=IcoLib_AddIconRes("AutoShutdown_Inactive",TranslateT("Automatic Shutdown"),TranslateT("Inactive"),hInst,IDI_INACTIVE,FALSE);
+
+ InitShutdownSvc();
+ InitWatcher(); /* before InitSettingsDlg() */
+ InitSettingsDlg();
+ InitOptions();
+
+ /* installation */
+ InstallFile(_T("Shutdown-Readme.txt"),_T("Docs\\"));
+ InstallFile(_T("Shutdown-License.txt"),_T("Docs\\"));
+ InstallFile(_T("Shutdown-SDK.zip"),_T("Docs\\"));
+ InstallFile(_T("countdown.wav"),_T("Sounds\\"));
+ hHookModulesLoaded=HookEvent(ME_SYSTEM_MODULESLOADED,ShutdownModulesLoaded);
+ return 0;
+}
+
+__declspec(dllexport) int Unload(void)
+{
+ UnhookEvent(hHookModulesLoaded);
+
+ UninitOptions();
+ UninitSettingsDlg(); /* before UninitWatcher() */
+ UninitWatcher(); /* before UninitFrame() */
+ UninitFrame();
+ UninitShutdownSvc();
+ return 0;
+}
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/plugins/AutoShutdown/options.c b/plugins/AutoShutdown/options.c
new file mode 100644
index 0000000000..2026038859
--- /dev/null
+++ b/plugins/AutoShutdown/options.c
@@ -0,0 +1,189 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include "common.h"
+
+/* Option Page */
+static HANDLE hHookOptInit;
+extern HINSTANCE hInst;
+/* Trigger */
+static HANDLE hHookModulesLoaded;
+
+/************************* Option Page ********************************/
+
+#define M_ENABLE_SUBCTLS (WM_APP+111)
+
+static int CALLBACK ShutdownOptDlgProc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
+{
+ switch(msg) {
+ case WM_INITDIALOG:
+ TranslateDialogDefault(hwndDlg);
+ { WORD setting=DBGetContactSettingWord(NULL,"AutoShutdown","ConfirmDlgCountdown",SETTING_CONFIRMDLGCOUNTDOWN_DEFAULT);
+ if(setting<3) setting=SETTING_CONFIRMDLGCOUNTDOWN_DEFAULT;
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_CONFIRMDLGCOUNTDOWN,UDM_SETRANGE,0,MAKELPARAM(999,3));
+ SendDlgItemMessage(hwndDlg,IDC_EDIT_CONFIRMDLGCOUNTDOWN,EM_SETLIMITTEXT,3,0);
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_CONFIRMDLGCOUNTDOWN,UDM_SETPOS,0,MAKELPARAM(setting,0));
+ SetDlgItemInt(hwndDlg,IDC_EDIT_CONFIRMDLGCOUNTDOWN,setting,FALSE);
+ }
+ CheckDlgButton(hwndDlg,IDC_CHECK_SMARTOFFLINECHECK,DBGetContactSettingByte(NULL,"AutoShutdown","SmartOfflineCheck",SETTING_SMARTOFFLINECHECK_DEFAULT)!=0);
+ CheckDlgButton(hwndDlg,IDC_CHECK_REMEMBERONRESTART,DBGetContactSettingByte(NULL,"AutoShutdown","RememberOnRestart",SETTING_REMEMBERONRESTART_DEFAULT)!=0);
+ CheckDlgButton(hwndDlg,IDC_CHECK_SHOWCONFIRMDLG,DBGetContactSettingByte(NULL,"AutoShutdown","ShowConfirmDlg",SETTING_SHOWCONFIRMDLG_DEFAULT)!=0);
+ { BOOL enabled=ServiceIsTypeEnabled(SDSDT_SHUTDOWN,0);
+ if(enabled) {
+ if(ServiceExists(MS_SYSINFO_HDDTEMP)) {
+ EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_HDDOVERHEAT),TRUE);
+ CheckDlgButton(hwndDlg,IDC_CHECK_HDDOVERHEAT,DBGetContactSettingByte(NULL,"AutoShutdown","HddOverheatShutdown",SETTING_HDDOVERHEATSHUTDOWN_DEFAULT)!=0);
+ }
+ if(ServiceExists(MS_WEATHER_UPDATE)) {
+ EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_WEATHER),TRUE);
+ CheckDlgButton(hwndDlg,IDC_CHECK_WEATHER,DBGetContactSettingByte(NULL,"AutoShutdown","WeatherShutdown",SETTING_WEATHERSHUTDOWN_DEFAULT)!=0);
+ }
+ }
+ }
+ SendMessage(hwndDlg,M_ENABLE_SUBCTLS,0,0);
+ return TRUE; /* default focus */
+ case M_ENABLE_SUBCTLS:
+ { BOOL checked=IsDlgButtonChecked(hwndDlg,IDC_CHECK_SHOWCONFIRMDLG)!=0;
+ if(checked!=IsWindowEnabled(GetDlgItem(hwndDlg,IDC_EDIT_CONFIRMDLGCOUNTDOWN))) {
+ EnableWindow(GetDlgItem(hwndDlg,IDC_EDIT_CONFIRMDLGCOUNTDOWN),checked);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_SPIN_CONFIRMDLGCOUNTDOWN),checked);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_TEXT_COUNTDOWNSTARTS),checked);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_TEXT_SECONDS),checked);
+ }
+ return TRUE;
+ }
+ case WM_COMMAND:
+ switch(LOWORD(wParam)) {
+ case IDC_EDIT_CONFIRMDLGCOUNTDOWN:
+ if(HIWORD(wParam)==EN_KILLFOCUS)
+ if((int)GetDlgItemInt(hwndDlg,IDC_EDIT_CONFIRMDLGCOUNTDOWN,NULL,TRUE)<3) {
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_CONFIRMDLGCOUNTDOWN,UDM_SETPOS,0,MAKELPARAM(3,0));
+ SetDlgItemInt(hwndDlg,IDC_EDIT_CONFIRMDLGCOUNTDOWN,3,FALSE);
+ }
+ if(HIWORD(wParam)!=EN_CHANGE || (HWND)lParam!=GetFocus())
+ return TRUE; /* no apply */
+ break;
+ }
+ PostMessage(hwndDlg,M_ENABLE_SUBCTLS,0,0);
+ PostMessage(GetParent(hwndDlg),PSM_CHANGED,0,0); /* enable apply */
+ return FALSE;
+ case WM_NOTIFY:
+ switch(((NMHDR*)lParam)->code) {
+ case PSN_APPLY:
+ DBWriteContactSettingByte(NULL,"AutoShutdown","ShowConfirmDlg",(BYTE)(IsDlgButtonChecked(hwndDlg,IDC_CHECK_SHOWCONFIRMDLG)!=0));
+ DBWriteContactSettingWord(NULL,"AutoShutdown","ConfirmDlgCountdown",(WORD)GetDlgItemInt(hwndDlg,IDC_EDIT_CONFIRMDLGCOUNTDOWN,NULL,FALSE));
+ DBWriteContactSettingByte(NULL,"AutoShutdown","RememberOnRestart",(BYTE)(IsDlgButtonChecked(hwndDlg,IDC_CHECK_REMEMBERONRESTART)!=0));
+ DBWriteContactSettingByte(NULL,"AutoShutdown","SmartOfflineCheck",(BYTE)(IsDlgButtonChecked(hwndDlg,IDC_CHECK_SMARTOFFLINECHECK)!=0));
+ if(IsWindowEnabled(GetDlgItem(hwndDlg,IDC_CHECK_WEATHER)))
+ DBWriteContactSettingByte(NULL,"AutoShutdown","WeatherShutdown",(BYTE)(IsDlgButtonChecked(hwndDlg,IDC_CHECK_WEATHER)!=0));
+ if(IsWindowEnabled(GetDlgItem(hwndDlg,IDC_CHECK_HDDOVERHEAT)))
+ DBWriteContactSettingByte(NULL,"AutoShutdown","HddOverheatShutdown",(BYTE)(IsDlgButtonChecked(hwndDlg,IDC_CHECK_HDDOVERHEAT)!=0));
+ return TRUE;
+ }
+ break;
+ }
+ return FALSE;
+}
+
+static int ShutdownOptInit(WPARAM wParam,LPARAM lParam)
+{
+ OPTIONSDIALOGPAGE odp;
+ UNREFERENCED_PARAMETER(lParam);
+ ZeroMemory(&odp,sizeof(odp));
+ odp.cbSize=sizeof(odp);
+ odp.hInstance=hInst;
+ odp.pszTemplate=MAKEINTRESOURCEA(IDD_OPT_SHUTDOWN);
+ odp.position=900000002;
+ odp.ptszGroup=_T("Events"); /* autotranslated */
+ odp.ptszTitle=_T("Automatic Shutdown"); /* autotranslated */
+ odp.ptszTab=_T("Automatic Shutdown"); /* autotranslated, can be made a tab */
+ odp.flags=ODPF_BOLDGROUPS|ODPF_EXPERTONLY|ODPF_TCHAR;
+ odp.pfnDlgProc=ShutdownOptDlgProc;
+ CallService(MS_OPT_ADDPAGE,wParam,(LPARAM)&odp);
+ return 0;
+}
+
+/************************* Trigger ************************************/
+
+static int __stdcall ActionProc(DWORD idAction,REPORTINFO *ri,int shutdownType)
+{
+ UNREFERENCED_PARAMETER(ri);
+ if(idAction&ACT_PERFORM) ServiceShutdown(shutdownType,TRUE);
+ return 0;
+}
+#define ActionProcJmp(shutdownType) { return ActionProc(id,ri,shutdownType); }
+
+static int CloseActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_CLOSEMIRANDA)
+static int SetOfflineActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_SETMIRANDAOFFLINE)
+static int LogoffActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_LOGOFF)
+static int RebootActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_REBOOT)
+static int ShutdownActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_SHUTDOWN)
+static int StandbyActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_STANDBY)
+static int HibernateActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_HIBERNATE)
+static int LockActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_LOCKWORKSTATION)
+static int HangupActionProc(DWORD id,REPORTINFO *ri) ActionProcJmp(SDSDT_CLOSERASCONNECTIONS)
+
+static int TriggerRegisterActions(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ /* new trigger API (0.2.0.69+) */
+ if(ServiceExists(MS_TRIGGER_REGISTERCONDITION)) {
+ ACTIONREGISTER ar;
+ BYTE shutdownType;
+ char *pszDesc,szName[138];
+ ACTIONFUNCTION actionFunctions[SDSDT_MAX]={CloseActionProc,SetOfflineActionProc,LogoffActionProc,
+ RebootActionProc,ShutdownActionProc,StandbyActionProc,
+ HibernateActionProc,LockActionProc,HangupActionProc};
+ ZeroMemory(&ar,sizeof(ar));
+ ar.cbSize=sizeof(ar);
+ ar.flags=ARF_TCHAR|ARF_FUNCTION;
+ ar.pszName=szName;
+ for(shutdownType=1;shutdownType<=SDSDT_MAX;++shutdownType)
+ if(ServiceIsTypeEnabled(shutdownType,0)) {
+ pszDesc=(char*)ServiceGetTypeDescription(shutdownType,GSTDF_UNTRANSLATED);
+ if(pszDesc!=NULL) {
+ mir_snprintf(szName,sizeof(szName),"Shutdown: %s",pszDesc); /* autotranslated */
+ ar.actionFunction=actionFunctions[shutdownType-1];
+ CallService(MS_TRIGGER_REGISTERACTION,0,(LPARAM)&ar);
+ }
+ }
+ }
+ return 0;
+}
+
+/************************* Misc ***************************************/
+
+void InitOptions(void)
+{
+ /* Option Page */
+ hHookOptInit=HookEvent(ME_OPT_INITIALISE,ShutdownOptInit);
+ /* Trigger */
+ hHookModulesLoaded=HookEvent(ME_SYSTEM_MODULESLOADED,TriggerRegisterActions);
+}
+
+void UninitOptions(void)
+{
+ /* Option Page */
+ UnhookEvent(hHookOptInit);
+ /* Trigger */
+ UnhookEvent(hHookModulesLoaded);
+}
diff --git a/plugins/AutoShutdown/options.h b/plugins/AutoShutdown/options.h
new file mode 100644
index 0000000000..8b8e63f04f
--- /dev/null
+++ b/plugins/AutoShutdown/options.h
@@ -0,0 +1,24 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+/* Misc */
+void InitOptions(void);
+void UninitOptions(void);
diff --git a/plugins/AutoShutdown/res/Thumbs.db b/plugins/AutoShutdown/res/Thumbs.db
new file mode 100644
index 0000000000..28fd3e08f0
--- /dev/null
+++ b/plugins/AutoShutdown/res/Thumbs.db
Binary files differ
diff --git a/plugins/AutoShutdown/res/active.ico b/plugins/AutoShutdown/res/active.ico
new file mode 100644
index 0000000000..83d1be2388
--- /dev/null
+++ b/plugins/AutoShutdown/res/active.ico
Binary files differ
diff --git a/plugins/AutoShutdown/res/header.ico b/plugins/AutoShutdown/res/header.ico
new file mode 100644
index 0000000000..4a31e98104
--- /dev/null
+++ b/plugins/AutoShutdown/res/header.ico
Binary files differ
diff --git a/plugins/AutoShutdown/res/inactive.ico b/plugins/AutoShutdown/res/inactive.ico
new file mode 100644
index 0000000000..6c69a4d40a
--- /dev/null
+++ b/plugins/AutoShutdown/res/inactive.ico
Binary files differ
diff --git a/plugins/AutoShutdown/resource.h b/plugins/AutoShutdown/resource.h
new file mode 100644
index 0000000000..4d8370f00a
--- /dev/null
+++ b/plugins/AutoShutdown/resource.h
@@ -0,0 +1,58 @@
+//{{NO_DEPENDENCIES}}
+// Microsoft Developer Studio generated include file.
+// Used by resource.rc
+//
+#define IDI_ACTIVE 101
+#define IDI_INACTIVE 102
+#define IDI_HEADER 103
+#define IDD_SETTINGS 104
+#define IDD_SHUTDOWNNOW 105
+#define IDD_OPT_SHUTDOWN 106
+#define IDC_ICON_HEADER 1001
+#define IDC_TEXT_HEADER 1002
+#define IDC_TEXT_HEADERDESC 1003
+#define IDC_RECT_HEADER 1004
+#define IDC_RADIO_STTIME 1005
+#define IDC_RADIO_STCOUNTDOWN 1006
+#define IDC_CHECK_SPECIFICTIME 1007
+#define IDC_TIME_TIMESTAMP 1008
+#define IDC_DATE_TIMESTAMP 1009
+#define IDC_EDIT_COUNTDOWN 1010
+#define IDC_SPIN_COUNTDOWN 1011
+#define IDC_COMBO_COUNTDOWNUNIT 1012
+#define IDC_COMBO_SHUTDOWNTYPE 1013
+#define IDC_TEXT_SHUTDOWNTYPE 1014
+#define IDC_TEXT_SECONDS 1015
+#define IDC_CHECK_FILETRANSFER 1016
+#define IDC_CHECK_IDLE 1017
+#define IDC_URL_IDLE 1018
+#define IDC_CHECK_MESSAGE 1019
+#define IDC_EDIT_MESSAGE 1020
+#define IDC_CHECK_STATUS 1021
+#define IDC_CHECK_CPUUSAGE 1022
+#define IDC_TEXT_CURRENTCPU 1023
+#define IDC_EDIT_CPUUSAGE 1024
+#define IDC_SPIN_CPUUSAGE 1025
+#define IDC_TEXT_PERCENT 1026
+#define IDC_BUTTON_SHUTDOWNNOW 1027
+#define IDC_TEXT_UNSAVEDWARNING 1028
+#define IDC_CHECK_SHOWCONFIRMDLG 1029
+#define IDC_TEXT_COUNTDOWNSTARTS 1030
+#define IDC_EDIT_CONFIRMDLGCOUNTDOWN 1031
+#define IDC_SPIN_CONFIRMDLGCOUNTDOWN 1032
+#define IDC_CHECK_REMEMBERONRESTART 1033
+#define IDC_CHECK_SMARTOFFLINECHECK 1034
+#define IDC_CHECK_WEATHER 1035
+#define IDC_CHECK_HDDOVERHEAT 1036
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NO_MFC 1
+#define _APS_NEXT_RESOURCE_VALUE 107
+#define _APS_NEXT_COMMAND_VALUE 40001
+#define _APS_NEXT_CONTROL_VALUE 1037
+#define _APS_NEXT_SYMED_VALUE 2001
+#endif
+#endif
diff --git a/plugins/AutoShutdown/resource.rc b/plugins/AutoShutdown/resource.rc
new file mode 100644
index 0000000000..a9bac86713
--- /dev/null
+++ b/plugins/AutoShutdown/resource.rc
@@ -0,0 +1,253 @@
+//Microsoft Developer Studio generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include <winres.h>
+#include <m_utils.h>
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// Englisch (GB) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG)
+#ifdef _WIN32
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK
+#pragma code_page(1252)
+#endif //_WIN32
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE MOVEABLE PURE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE MOVEABLE PURE
+BEGIN
+ "#include <winres.h>\r\n"
+ "#include <m_utils.h>\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE MOVEABLE PURE
+BEGIN
+ "#include ""version.rc""\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_OPT_SHUTDOWN DIALOGEX 0, 0, 201, 190
+STYLE DS_FIXEDSYS | WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg"
+BEGIN
+ GROUPBOX "Shutdown",IDC_STATIC,3,1,196,45
+ CONTROL "&Show confirmation dialog before shutdown",
+ IDC_CHECK_SHOWCONFIRMDLG,"Button",BS_AUTOCHECKBOX |
+ WS_GROUP | WS_TABSTOP,12,14,182,10
+ LTEXT "&Countdown starts at:",IDC_TEXT_COUNTDOWNSTARTS,24,29,
+ 79,8
+ EDITTEXT IDC_EDIT_CONFIRMDLGCOUNTDOWN,109,27,32,12,ES_AUTOHSCROLL |
+ ES_NUMBER
+ CONTROL "",IDC_SPIN_CONFIRMDLGCOUNTDOWN,"msctls_updown32",
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_HOTTRACK |
+ WS_TABSTOP,137,27,9,11
+ LTEXT "seconds",IDC_TEXT_SECONDS,146,29,48,8,NOT WS_GROUP
+ GROUPBOX "Shutdown Events",IDC_STATIC,3,51,196,66,WS_GROUP
+ CONTROL "&Activate automatic shutdown with the same settings again if Miranda IM was closed with automatic shutdown enabled",
+ IDC_CHECK_REMEMBERONRESTART,"Button",BS_AUTOCHECKBOX |
+ BS_TOP | BS_MULTILINE | WS_TABSTOP,12,64,182,27
+ CONTROL "&Ignore hidden or temporary contacts when watching for all contacts being offline",
+ IDC_CHECK_SMARTOFFLINECHECK,"Button",BS_AUTOCHECKBOX |
+ BS_TOP | BS_MULTILINE | WS_TABSTOP,12,93,182,20
+ GROUPBOX "Critical Shutdown Events",IDC_STATIC,3,123,196,66
+ LTEXT "Automatically shutdown the computer and turn the power off when one of the following occurs:",
+ IDC_STATIC,12,135,182,18,SS_NOPREFIX
+ CONTROL "&Thunderstorm warning is issued (Weather)",
+ IDC_CHECK_WEATHER,"Button",BS_AUTOCHECKBOX | BS_TOP |
+ WS_DISABLED | WS_TABSTOP,12,157,182,11
+ CONTROL "&Harddrive overheats (HDD Info)",IDC_CHECK_HDDOVERHEAT,
+ "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,12,
+ 172,182,10
+END
+
+IDD_SETTINGS DIALOGEX 0, 0, 239, 286
+STYLE DS_MODALFRAME | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER |
+ WS_VISIBLE | WS_CAPTION | WS_SYSMENU
+CAPTION "Automatic Shutdown"
+FONT 8, "MS Shell Dlg"
+BEGIN
+ LTEXT "",IDC_RECT_HEADER,0,0,243,25,NOT WS_GROUP
+ ICON "",IDC_ICON_HEADER,7,3,20,20,SS_CENTERIMAGE | WS_GROUP,
+ WS_EX_TRANSPARENT
+ LTEXT "Automatic Shutdown",IDC_TEXT_HEADER,34,4,201,8,
+ SS_NOPREFIX,WS_EX_TRANSPARENT
+ LTEXT "Select the automatic shutdown event",
+ IDC_TEXT_HEADERDESC,43,12,192,8,SS_NOPREFIX,
+ WS_EX_TRANSPARENT
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,0,25,243,1
+ CONTROL "Shutdown at &specific time",IDC_CHECK_SPECIFICTIME,
+ "Button",BS_AUTOCHECKBOX | WS_GROUP | WS_TABSTOP,13,35,
+ 212,10
+ CONTROL "Shutdown a&t:",IDC_RADIO_STTIME,"Button",
+ BS_AUTORADIOBUTTON | WS_TABSTOP,25,49,68,8
+ CONTROL "",IDC_TIME_TIMESTAMP,"SysDateTimePick32",DTS_UPDOWN |
+ WS_TABSTOP | 0x8,95,47,62,13
+ CONTROL "",IDC_DATE_TIMESTAMP,"SysDateTimePick32",WS_TABSTOP,159,
+ 47,66,13
+ CONTROL "Shutdown i&n:",IDC_RADIO_STCOUNTDOWN,"Button",
+ BS_AUTORADIOBUTTON | WS_TABSTOP,25,64,68,8
+ EDITTEXT IDC_EDIT_COUNTDOWN,95,62,62,13,ES_AUTOHSCROLL |
+ ES_NUMBER
+ CONTROL "",IDC_SPIN_COUNTDOWN,"msctls_updown32",UDS_WRAP |
+ UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY |
+ UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_HOTTRACK,146,62,12,
+ 14
+ COMBOBOX IDC_COMBO_COUNTDOWNUNIT,159,62,66,114,CBS_DROPDOWNLIST |
+ WS_VSCROLL | WS_TABSTOP
+ CONTROL "Shutdown when a &message is received containing the following text:",
+ IDC_CHECK_MESSAGE,"Button",BS_AUTOCHECKBOX | BS_TOP |
+ BS_MULTILINE | WS_GROUP | WS_TABSTOP,13,78,211,18
+ EDITTEXT IDC_EDIT_MESSAGE,25,96,199,21,ES_MULTILINE |
+ ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL
+ CONTROL "Shutdown when Miranda IM becomes &idle",IDC_CHECK_IDLE,
+ "Button",BS_AUTOCHECKBOX | BS_TOP | BS_MULTILINE |
+ WS_GROUP | WS_TABSTOP,13,123,164,9
+ CONTROL "Configure",IDC_URL_IDLE,"Hyperlink",WS_TABSTOP,179,124,
+ 46,9
+ CONTROL "Shutdown when &prozessor usage drops below:",
+ IDC_CHECK_CPUUSAGE,"Button",BS_AUTOCHECKBOX | BS_TOP |
+ BS_MULTILINE | WS_GROUP | WS_TABSTOP,13,139,159,22
+ EDITTEXT IDC_EDIT_CPUUSAGE,179,140,32,13,ES_AUTOHSCROLL |
+ ES_NUMBER
+ CONTROL "",IDC_SPIN_CPUUSAGE,"msctls_updown32",UDS_SETBUDDYINT |
+ UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS |
+ UDS_NOTHOUSANDS | UDS_HOTTRACK,205,140,11,14
+ LTEXT "%",IDC_TEXT_PERCENT,215,140,15,13,SS_NOPREFIX |
+ SS_CENTERIMAGE | NOT WS_GROUP
+ LTEXT "(current: 0%)",IDC_TEXT_CURRENTCPU,179,154,60,8,
+ SS_NOPREFIX | NOT WS_GROUP
+ CONTROL "Shutdown when all contacts are &offline",
+ IDC_CHECK_STATUS,"Button",BS_AUTOCHECKBOX | BS_TOP |
+ WS_GROUP | WS_TABSTOP,13,162,211,9
+ CONTROL "Shutdown when all &file transfers are finished",
+ IDC_CHECK_FILETRANSFER,"Button",BS_AUTOCHECKBOX | BS_TOP |
+ WS_GROUP | WS_TABSTOP,13,177,211,10
+ LTEXT "&Action:",IDC_STATIC,15,199,209,8
+ COMBOBOX IDC_COMBO_SHUTDOWNTYPE,14,209,210,103,CBS_DROPDOWNLIST |
+ WS_VSCROLL | WS_TABSTOP
+ LTEXT "",IDC_TEXT_SHUTDOWNTYPE,15,225,208,25,NOT WS_GROUP
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,0,258,245,1
+ DEFPUSHBUTTON "OK",IDOK,123,266,50,14,WS_GROUP
+ PUSHBUTTON "Cancel",IDCANCEL,179,266,50,14
+END
+
+IDD_SHUTDOWNNOW DIALOGEX 0, 0, 204, 98
+STYLE DS_MODALFRAME | DS_NOIDLEMSG | DS_SETFOREGROUND | DS_FIXEDSYS |
+ DS_NOFAILCREATE | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION |
+ WS_SYSMENU
+EXSTYLE WS_EX_TOPMOST
+CAPTION "Automatic Shutdown"
+FONT 8, "MS Shell Dlg"
+BEGIN
+ ICON "",IDC_ICON_HEADER,6,7,20,20,SS_CENTERIMAGE | WS_GROUP,
+ WS_EX_TRANSPARENT
+ LTEXT "",IDC_TEXT_HEADER,34,8,162,18,SS_NOPREFIX | NOT
+ WS_GROUP
+ LTEXT "Unsaved data in open applications except Miranda IM might get lost.",
+ IDC_TEXT_UNSAVEDWARNING,33,31,161,17,SS_NOPREFIX | NOT
+ WS_VISIBLE
+ LTEXT "Please click ""Cancel"" if you would like to abort the process.",
+ IDC_STATIC,33,49,161,17,SS_NOPREFIX
+ PUSHBUTTON "&Now!",IDC_BUTTON_SHUTDOWNNOW,32,75,67,14,WS_GROUP
+ DEFPUSHBUTTON "Cancel",IDCANCEL,103,75,68,14
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO DISCARDABLE
+BEGIN
+ IDD_OPT_SHUTDOWN, DIALOG
+ BEGIN
+ VERTGUIDE, 3
+ VERTGUIDE, 12
+ VERTGUIDE, 194
+ VERTGUIDE, 199
+ HORZGUIDE, 27
+ HORZGUIDE, 39
+ END
+
+ IDD_SETTINGS, DIALOG
+ BEGIN
+ VERTGUIDE, 13
+ VERTGUIDE, 25
+ VERTGUIDE, 95
+ VERTGUIDE, 159
+ VERTGUIDE, 179
+ VERTGUIDE, 224
+ HORZGUIDE, 266
+ HORZGUIDE, 280
+ END
+
+ IDD_SHUTDOWNNOW, DIALOG
+ BEGIN
+ VERTGUIDE, 34
+ VERTGUIDE, 196
+ HORZGUIDE, 8
+ HORZGUIDE, 31
+ HORZGUIDE, 75
+ HORZGUIDE, 89
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_ACTIVE ICON DISCARDABLE "res/active.ico"
+IDI_HEADER ICON DISCARDABLE "res/header.ico"
+IDI_INACTIVE ICON DISCARDABLE "res/inactive.ico"
+#endif // Englisch (GB) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+#include "version.rc"
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/plugins/AutoShutdown/settingsdlg.c b/plugins/AutoShutdown/settingsdlg.c
new file mode 100644
index 0000000000..03f514d61b
--- /dev/null
+++ b/plugins/AutoShutdown/settingsdlg.c
@@ -0,0 +1,512 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include "common.h"
+
+/* Menu Item */
+static HANDLE hServiceMenuCommand;
+/* Toolbar Button */
+static HANDLE hHookToolbarLoaded;
+/* Services */
+static HANDLE hServiceShowDlg;
+static HWND hwndSettingsDlg;
+extern HINSTANCE hInst;
+
+/************************* Dialog *************************************/
+
+static void EnableDlgItem(HWND hwndDlg,int idCtrl,BOOL fEnable)
+{
+ hwndDlg=GetDlgItem(hwndDlg,idCtrl);
+ if(hwndDlg!=NULL && IsWindowEnabled(hwndDlg)!=fEnable)
+ EnableWindow(hwndDlg,fEnable);
+}
+
+static BOOL CALLBACK DisplayCpuUsageProc(BYTE nCpuUsage,LPARAM lParam)
+{
+ TCHAR str[64];
+ /* dialog closed? */
+ if(!IsWindow((HWND)lParam)) return FALSE; /* stop poll thread */
+ mir_sntprintf(str,SIZEOF(str),TranslateT("(current: %u%%)"),nCpuUsage);
+ SetWindowText((HWND)lParam,str);
+ return TRUE;
+}
+
+static BOOL AnyProtoHasCaps(DWORD caps1)
+{
+ int nProtoCount,i;
+ PROTOCOLDESCRIPTOR **protos;
+ if(!CallService(MS_PROTO_ENUMPROTOCOLS,(WPARAM)&nProtoCount,(LPARAM)&protos))
+ for(i=0;i<nProtoCount;++i)
+ if(protos[i]->type==PROTOTYPE_PROTOCOL)
+ if(CallProtoService(protos[i]->szName,PS_GETCAPS,(WPARAM)PFLAGNUM_1,0)&caps1)
+ return TRUE; /* CALLSERVICE_NOTFOUND also handled gracefully */
+ return FALSE;
+}
+
+#define M_ENABLE_SUBCTLS (WM_APP+111)
+#define M_UPDATE_SHUTDOWNDESC (WM_APP+112)
+#define M_CHECK_DATETIME (WM_APP+113)
+static BOOL CALLBACK SettingsDlgProc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
+{
+ switch(msg) {
+ case WM_INITDIALOG:
+ { LCID locale;
+ hwndSettingsDlg=hwndDlg;
+ TranslateDialogDefault(hwndDlg);
+ locale=CallService(MS_LANGPACK_GETLOCALE,0,0);
+ SendDlgItemMessage(hwndDlg,IDC_ICON_HEADER,STM_SETIMAGE,IMAGE_ICON,(LPARAM)IcoLib_GetIcon("AutoShutdown_Header"));
+ { HFONT hBoldFont;
+ LOGFONT lf;
+ if(GetObject((HFONT)SendDlgItemMessage(hwndDlg,IDC_TEXT_HEADER,WM_GETFONT,0,0),sizeof(lf),&lf)) {
+ lf.lfWeight=FW_BOLD;
+ hBoldFont=CreateFontIndirect(&lf);
+ } else hBoldFont=NULL;
+ SendDlgItemMessage(hwndDlg,IDC_TEXT_HEADER,WM_SETFONT,(WPARAM)hBoldFont,FALSE);
+ }
+ /* read-in watcher flags */
+ { WORD watcherType;
+ watcherType=DBGetContactSettingWord(NULL,"AutoShutdown","WatcherFlags",SETTING_WATCHERFLAGS_DEFAULT);
+ CheckRadioButton(hwndDlg,IDC_RADIO_STTIME,IDC_RADIO_STCOUNTDOWN,(watcherType&SDWTF_ST_TIME)?IDC_RADIO_STTIME:IDC_RADIO_STCOUNTDOWN);
+ CheckDlgButton(hwndDlg,IDC_CHECK_SPECIFICTIME,(watcherType&SDWTF_SPECIFICTIME)!=0);
+ CheckDlgButton(hwndDlg,IDC_CHECK_MESSAGE,(watcherType&SDWTF_MESSAGE)!=0);
+ CheckDlgButton(hwndDlg,IDC_CHECK_FILETRANSFER,(watcherType&SDWTF_FILETRANSFER)!=0);
+ CheckDlgButton(hwndDlg,IDC_CHECK_IDLE,(watcherType&SDWTF_IDLE)!=0);
+ CheckDlgButton(hwndDlg,IDC_CHECK_STATUS,(watcherType&SDWTF_STATUS)!=0);
+ CheckDlgButton(hwndDlg,IDC_CHECK_CPUUSAGE,(watcherType&SDWTF_CPUUSAGE)!=0);
+ }
+ /* read-in countdown val */
+ { SYSTEMTIME st;
+ if(!TimeStampToSystemTime((time_t)DBGetContactSettingDword(NULL,"AutoShutdown","TimeStamp",SETTING_TIMESTAMP_DEFAULT),&st))
+ GetLocalTime(&st);
+ DateTime_SetSystemtime(GetDlgItem(hwndDlg,IDC_TIME_TIMESTAMP),GDT_VALID,&st);
+ DateTime_SetSystemtime(GetDlgItem(hwndDlg,IDC_DATE_TIMESTAMP),GDT_VALID,&st);
+ SendMessage(hwndDlg,M_CHECK_DATETIME,0,0);
+ }
+ { DWORD setting;
+ setting=DBGetContactSettingDword(NULL,"AutoShutdown","Countdown",SETTING_COUNTDOWN_DEFAULT);
+ if(setting<1) setting=SETTING_COUNTDOWN_DEFAULT;
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_COUNTDOWN,UDM_SETRANGE,0,MAKELPARAM(UD_MAXVAL,1));
+ SendDlgItemMessage(hwndDlg,IDC_EDIT_COUNTDOWN,EM_SETLIMITTEXT,(WPARAM)10,0);
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_COUNTDOWN,UDM_SETPOS,0,MAKELPARAM(setting,0));
+ SetDlgItemInt(hwndDlg,IDC_EDIT_COUNTDOWN,setting,FALSE);
+ }
+ { HWND hwndCombo;
+ DWORD lastUnit;
+ int i,index;
+ const DWORD unitValues[]={1,60,60*60,60*60*24,60*60*24*7,60*60*24*31};
+ const TCHAR *unitNames[]={_T("Second(s)"),_T("Minute(s)"),_T("Hour(s)"),
+ _T("Day(s)"),_T("Week(s)"),_T("Month(s)")};
+ hwndCombo=GetDlgItem(hwndDlg,IDC_COMBO_COUNTDOWNUNIT);
+ lastUnit=DBGetContactSettingDword(NULL,"AutoShutdown","CountdownUnit",SETTING_COUNTDOWNUNIT_DEFAULT);
+ SendMessage(hwndCombo,CB_SETLOCALE,(WPARAM)locale,0); /* sort order */
+ SendMessage(hwndCombo,CB_INITSTORAGE,SIZEOF(unitNames),SIZEOF(unitNames)*16); /* approx. */
+ for(i=0;i<SIZEOF(unitNames);++i) {
+ index=SendMessage(hwndCombo,CB_ADDSTRING,0,(LPARAM)TranslateTS(unitNames[i]));
+ if(index!=LB_ERR) {
+ SendMessage(hwndCombo,CB_SETITEMDATA,index,(LPARAM)unitValues[i]);
+ if(i==0 || unitValues[i]==lastUnit) SendMessage(hwndCombo,CB_SETCURSEL,index,0);
+ }
+ }
+ }
+ { DBVARIANT dbv;
+ if(!DBGetContactSettingTString(NULL,"AutoShutdown","Message",&dbv)) {
+ SetDlgItemText(hwndDlg,IDC_EDIT_MESSAGE,dbv.ptszVal);
+ mir_free(dbv.ptszVal);
+ }
+ if(ServiceExists(MS_AUTOREPLACER_ADDWINHANDLE))
+ CallService(MS_AUTOREPLACER_ADDWINHANDLE,0,(LPARAM)GetDlgItem(hwndDlg,IDC_EDIT_MESSAGE));
+ }
+ /* cpuusage threshold */
+ { BYTE setting;
+ setting=DBGetContactSettingRangedByte(NULL,"AutoShutdown","CpuUsageThreshold",SETTING_CPUUSAGETHRESHOLD_DEFAULT,1,100);
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_CPUUSAGE,UDM_SETRANGE,0,MAKELPARAM(100,1));
+ SendDlgItemMessage(hwndDlg,IDC_EDIT_CPUUSAGE,EM_SETLIMITTEXT,(WPARAM)3,0);
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_CPUUSAGE,UDM_SETPOS,0,MAKELPARAM(setting,0));
+ SetDlgItemInt(hwndDlg,IDC_EDIT_CPUUSAGE,setting,FALSE);
+ }
+ /* shutdown types */
+ { HWND hwndCombo;
+ BYTE lastShutdownType;
+ BYTE shutdownType;
+ int index;
+ TCHAR *pszText;
+ hwndCombo=GetDlgItem(hwndDlg,IDC_COMBO_SHUTDOWNTYPE);
+ lastShutdownType=DBGetContactSettingByte(NULL,"AutoShutdown","ShutdownType",SETTING_SHUTDOWNTYPE_DEFAULT);
+ SendMessage(hwndCombo,CB_SETLOCALE,(WPARAM)locale,0); /* sort order */
+ SendMessage(hwndCombo,CB_SETEXTENDEDUI,TRUE,0);
+ SendMessage(hwndCombo,CB_INITSTORAGE,SDSDT_MAX,SDSDT_MAX*32);
+ for(shutdownType=1;shutdownType<=SDSDT_MAX;++shutdownType)
+ if(ServiceIsTypeEnabled(shutdownType,0)) {
+ pszText=(TCHAR*)ServiceGetTypeDescription(shutdownType,GSTDF_TCHAR); /* never fails */
+ index=SendMessage(hwndCombo,CB_ADDSTRING,0,(LPARAM)pszText);
+ if(index!=LB_ERR) {
+ SendMessage(hwndCombo,CB_SETITEMDATA,index,(LPARAM)shutdownType);
+ if(shutdownType==1 || shutdownType==lastShutdownType) SendMessage(hwndCombo,CB_SETCURSEL,(WPARAM)index,0);
+ }
+ }
+ SendMessage(hwndDlg,M_UPDATE_SHUTDOWNDESC,0,(LPARAM)hwndCombo);
+ }
+ /* check if proto is installed that supports instant messages and check if a message dialog plugin is installed */
+ if(!AnyProtoHasCaps(PF1_IMRECV) || !ServiceExists(MS_MSG_SENDMESSAGE)) { /* no srmessage present? */
+ CheckDlgButton(hwndDlg,IDC_CHECK_MESSAGE,FALSE);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_MESSAGE),FALSE);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_EDIT_MESSAGE),FALSE);
+ }
+ /* check if proto is installed that supports file transfers and check if a file transfer dialog is available */
+ if((!AnyProtoHasCaps(PF1_FILESEND) && !AnyProtoHasCaps(PF1_FILERECV)) || !ServiceExists(MS_FILE_SENDFILE)) { /* no srfile present? */
+ CheckDlgButton(hwndDlg,IDC_CHECK_FILETRANSFER,FALSE);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_FILETRANSFER),FALSE);
+ }
+ /* check if cpu usage can be detected */
+ if(!PollCpuUsage(DisplayCpuUsageProc,(LPARAM)GetDlgItem(hwndDlg,IDC_TEXT_CURRENTCPU),1800)) {
+ CheckDlgButton(hwndDlg,IDC_CHECK_CPUUSAGE,FALSE);
+ EnableWindow(GetDlgItem(hwndDlg,IDC_CHECK_CPUUSAGE),FALSE);
+ }
+ SendMessage(hwndDlg,M_ENABLE_SUBCTLS,0,0);
+ MagneticWindows_AddWindow(hwndDlg);
+ Utils_RestoreWindowPositionNoSize(hwndDlg,NULL,"AutoShutdown","SettingsDlg_");
+ return TRUE; /* default focus */
+ }
+ case WM_DESTROY:
+ { HICON hIcon;
+ HFONT hFont;
+ if(ServiceExists(MS_AUTOREPLACER_ADDWINHANDLE))
+ CallService(MS_AUTOREPLACER_REMWINHANDLE,0,(LPARAM)GetDlgItem(hwndDlg,IDC_EDIT_MESSAGE));
+ Utils_SaveWindowPosition(hwndDlg,NULL,"AutoShutdown","SettingsDlg_");
+ MagneticWindows_RemoveWindow(hwndDlg);
+ hIcon=(HICON)SendDlgItemMessage(hwndDlg,IDC_ICON_HEADER,STM_SETIMAGE,IMAGE_ICON,(LPARAM)NULL);
+ IcoLib_ReleaseIcon(hIcon); /* does NULL check */
+ hFont=(HFONT)SendDlgItemMessage(hwndDlg,IDC_TEXT_HEADER,WM_GETFONT,0,0);
+ SendDlgItemMessage(hwndDlg,IDC_TEXT_HEADER,WM_SETFONT,(WPARAM)NULL,FALSE); /* no return value */
+ if(hFont!=NULL) DeleteObject(hFont);
+ hwndSettingsDlg=NULL;
+ return TRUE;
+ }
+ case WM_CTLCOLORSTATIC:
+ switch(GetDlgCtrlID((HWND)lParam)) {
+ case IDC_ICON_HEADER:
+ SetBkMode((HDC)wParam,TRANSPARENT);
+ case IDC_RECT_HEADER:
+ /* need to set COLOR_WINDOW manually for Win9x */
+ SetBkColor((HDC)wParam,GetSysColor(COLOR_WINDOW));
+ return (BOOL)GetSysColorBrush(COLOR_WINDOW);
+ case IDC_TEXT_HEADER:
+ case IDC_TEXT_HEADERDESC:
+ SetBkMode((HDC)wParam,TRANSPARENT);
+ return (BOOL)GetStockObject(NULL_BRUSH);
+ }
+ break;
+ case M_ENABLE_SUBCTLS:
+ { BOOL checked=IsDlgButtonChecked(hwndDlg,IDC_CHECK_MESSAGE)!=0;
+ EnableDlgItem(hwndDlg,IDC_EDIT_MESSAGE,checked);
+ checked=IsDlgButtonChecked(hwndDlg,IDC_CHECK_SPECIFICTIME)!=0;
+ EnableDlgItem(hwndDlg,IDC_RADIO_STTIME,checked);
+ EnableDlgItem(hwndDlg,IDC_RADIO_STCOUNTDOWN,checked);
+ checked=(IsDlgButtonChecked(hwndDlg,IDC_CHECK_SPECIFICTIME) && IsDlgButtonChecked(hwndDlg,IDC_RADIO_STTIME));
+ EnableDlgItem(hwndDlg,IDC_TIME_TIMESTAMP,checked);
+ EnableDlgItem(hwndDlg,IDC_DATE_TIMESTAMP,checked);
+ checked=(IsDlgButtonChecked(hwndDlg,IDC_CHECK_SPECIFICTIME) && IsDlgButtonChecked(hwndDlg,IDC_RADIO_STCOUNTDOWN));
+ EnableDlgItem(hwndDlg,IDC_EDIT_COUNTDOWN,checked);
+ EnableDlgItem(hwndDlg,IDC_SPIN_COUNTDOWN,checked);
+ EnableDlgItem(hwndDlg,IDC_COMBO_COUNTDOWNUNIT,checked);
+ checked=IsDlgButtonChecked(hwndDlg,IDC_CHECK_IDLE)!=0;
+ EnableDlgItem(hwndDlg,IDC_URL_IDLE,checked);
+ checked=IsDlgButtonChecked(hwndDlg,IDC_CHECK_CPUUSAGE)!=0;
+ EnableDlgItem(hwndDlg,IDC_EDIT_CPUUSAGE,checked);
+ EnableDlgItem(hwndDlg,IDC_SPIN_CPUUSAGE,checked);
+ EnableDlgItem(hwndDlg,IDC_TEXT_PERCENT,checked);
+ EnableDlgItem(hwndDlg,IDC_TEXT_CURRENTCPU,checked);
+ checked=(IsDlgButtonChecked(hwndDlg,IDC_CHECK_SPECIFICTIME) || IsDlgButtonChecked(hwndDlg,IDC_CHECK_MESSAGE) ||
+ IsDlgButtonChecked(hwndDlg,IDC_CHECK_IDLE) || IsDlgButtonChecked(hwndDlg,IDC_CHECK_STATUS) ||
+ IsDlgButtonChecked(hwndDlg,IDC_CHECK_FILETRANSFER) || IsDlgButtonChecked(hwndDlg,IDC_CHECK_CPUUSAGE));
+ EnableDlgItem(hwndDlg,IDOK,checked);
+ }
+ return TRUE;
+ case M_UPDATE_SHUTDOWNDESC: /* lParam=(LPARAM)(HWND)hwndCombo */
+ { BYTE shutdownType;
+ shutdownType=(BYTE)SendMessage((HWND)lParam,CB_GETITEMDATA,SendMessage((HWND)lParam,CB_GETCURSEL,0,0),0);
+ SetDlgItemText(hwndDlg,IDC_TEXT_SHUTDOWNTYPE,(TCHAR*)ServiceGetTypeDescription(shutdownType,GSTDF_LONGDESC|GSTDF_TCHAR));
+ return TRUE;
+ }
+ case WM_TIMECHANGE: /* system time changed */
+ SendMessage(hwndDlg,M_CHECK_DATETIME,0,0);
+ return TRUE;
+ case M_CHECK_DATETIME:
+ { SYSTEMTIME st,stBuf;
+ time_t timestamp;
+ DateTime_GetSystemtime(GetDlgItem(hwndDlg,IDC_DATE_TIMESTAMP),&stBuf);
+ DateTime_GetSystemtime(GetDlgItem(hwndDlg,IDC_TIME_TIMESTAMP),&st);
+ st.wDay=stBuf.wDay;
+ st.wDayOfWeek=stBuf.wDayOfWeek;
+ st.wMonth=stBuf.wMonth;
+ st.wYear=stBuf.wYear;
+ GetLocalTime(&stBuf);
+ if(SystemTimeToTimeStamp(&st,&timestamp)) {
+ /* set to current date if earlier */
+ if(timestamp<time(NULL)) {
+ st.wDay=stBuf.wDay;
+ st.wDayOfWeek=stBuf.wDayOfWeek;
+ st.wMonth=stBuf.wMonth;
+ st.wYear=stBuf.wYear;
+ if(SystemTimeToTimeStamp(&st,&timestamp)) {
+ /* step one day up if still earlier */
+ if(timestamp<time(NULL)) {
+ timestamp+=24*60*60;
+ TimeStampToSystemTime(timestamp,&st);
+ }
+ }
+ }
+ }
+ DateTime_SetRange(GetDlgItem(hwndDlg,IDC_DATE_TIMESTAMP),GDTR_MIN,&stBuf);
+ DateTime_SetRange(GetDlgItem(hwndDlg,IDC_TIME_TIMESTAMP),GDTR_MIN,&stBuf);
+ DateTime_SetSystemtime(GetDlgItem(hwndDlg,IDC_DATE_TIMESTAMP),GDT_VALID,&st);
+ DateTime_SetSystemtime(GetDlgItem(hwndDlg,IDC_TIME_TIMESTAMP),GDT_VALID,&st);
+ return TRUE;
+ }
+ case WM_NOTIFY:
+ switch(((NMHDR*)lParam)->idFrom) {
+ case IDC_TIME_TIMESTAMP:
+ case IDC_DATE_TIMESTAMP:
+ switch(((NMHDR*)lParam)->code) {
+ case DTN_CLOSEUP:
+ case NM_KILLFOCUS:
+ PostMessage(hwndDlg,M_CHECK_DATETIME,0,0);
+ return TRUE;
+ }
+ }
+ break;
+ case WM_COMMAND:
+ switch(LOWORD(wParam)) {
+ case IDC_CHECK_MESSAGE:
+ case IDC_CHECK_FILETRANSFER:
+ case IDC_CHECK_IDLE:
+ case IDC_CHECK_CPUUSAGE:
+ case IDC_CHECK_STATUS:
+ case IDC_CHECK_SPECIFICTIME:
+ case IDC_RADIO_STTIME:
+ case IDC_RADIO_STCOUNTDOWN:
+ SendMessage(hwndDlg,M_ENABLE_SUBCTLS,0,0);
+ return TRUE;
+ case IDC_EDIT_COUNTDOWN:
+ if(HIWORD(wParam)==EN_KILLFOCUS) {
+ if((int)GetDlgItemInt(hwndDlg,IDC_EDIT_COUNTDOWN,NULL,TRUE)<1) {
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_COUNTDOWN,UDM_SETPOS,0,MAKELPARAM(1,0));
+ SetDlgItemInt(hwndDlg,IDC_EDIT_COUNTDOWN,1,FALSE);
+ }
+ return TRUE;
+ }
+ break;
+ case IDC_EDIT_CPUUSAGE:
+ if(HIWORD(wParam)==EN_KILLFOCUS) {
+ WORD val;
+ val=(WORD)GetDlgItemInt(hwndDlg,IDC_EDIT_CPUUSAGE,NULL,FALSE);
+ if(val<1) val=1;
+ else if(val>100) val=100;
+ SendDlgItemMessage(hwndDlg,IDC_SPIN_CPUUSAGE,UDM_SETPOS,0,MAKELPARAM(val,0));
+ SetDlgItemInt(hwndDlg,IDC_EDIT_CPUUSAGE,val,FALSE);
+ return TRUE;
+ }
+ break;
+ case IDC_URL_IDLE:
+ { OPENOPTIONSDIALOG ood;
+ ood.cbSize=sizeof(ood);
+ ood.pszGroup="Status"; /* autotranslated */
+ ood.pszPage="Idle"; /* autotranslated */
+ ood.pszTab=NULL;
+ CallService(MS_OPT_OPENOPTIONS,0,(LPARAM)&ood);
+ return TRUE;
+ }
+ case IDC_COMBO_SHUTDOWNTYPE:
+ if(HIWORD(wParam)==CBN_SELCHANGE)
+ SendMessage(hwndDlg,M_UPDATE_SHUTDOWNDESC,0,lParam);
+ return TRUE;
+ case IDOK: /* save settings and start watcher */
+ ShowWindow(hwndDlg,SW_HIDE);
+ /* message text */
+ { HWND hwndEdit=GetDlgItem(hwndDlg,IDC_EDIT_MESSAGE);
+ int len=GetWindowTextLength(hwndEdit)+1;
+ TCHAR *pszText=(TCHAR*)mir_alloc(len*sizeof(TCHAR));
+ if(pszText!=NULL && GetWindowText(hwndEdit,pszText,len+1)) {
+ TrimString(pszText);
+ DBWriteContactSettingTString(NULL,"AutoShutdown","Message",pszText);
+ }
+ mir_free(pszText); /* does NULL check */
+ }
+ /* timestamp */
+ { SYSTEMTIME st;
+ time_t timestamp;
+ DateTime_GetSystemtime(GetDlgItem(hwndDlg,IDC_TIME_TIMESTAMP),&st); /* time gets synchronized */
+ if(!SystemTimeToTimeStamp(&st,&timestamp))
+ timestamp=time(NULL);
+ DBWriteContactSettingDword(NULL,"AutoShutdown","TimeStamp",(DWORD)timestamp);
+ }
+ /* shutdown type */
+ { int index;
+ index=SendDlgItemMessage(hwndDlg,IDC_COMBO_SHUTDOWNTYPE,CB_GETCURSEL,0,0);
+ if(index!=LB_ERR) DBWriteContactSettingByte(NULL,"AutoShutdown","ShutdownType",(BYTE)SendDlgItemMessage(hwndDlg,IDC_COMBO_SHUTDOWNTYPE,CB_GETITEMDATA,(WPARAM)index,0));
+ index=SendDlgItemMessage(hwndDlg,IDC_COMBO_COUNTDOWNUNIT,CB_GETCURSEL,0,0);
+ if(index!=LB_ERR) DBWriteContactSettingDword(NULL,"AutoShutdown","CountdownUnit",(DWORD)SendDlgItemMessage(hwndDlg,IDC_COMBO_COUNTDOWNUNIT,CB_GETITEMDATA,(WPARAM)index,0));
+ DBWriteContactSettingDword(NULL,"AutoShutdown","Countdown",(DWORD)GetDlgItemInt(hwndDlg,IDC_EDIT_COUNTDOWN,NULL,FALSE));
+ DBWriteContactSettingByte(NULL,"AutoShutdown","CpuUsageThreshold",(BYTE)GetDlgItemInt(hwndDlg,IDC_EDIT_CPUUSAGE,NULL,FALSE));
+ }
+ /* watcher type */
+ { WORD watcherType;
+ watcherType=(WORD)(IsDlgButtonChecked(hwndDlg,IDC_RADIO_STTIME)?SDWTF_ST_TIME:SDWTF_ST_COUNTDOWN);
+ if(IsDlgButtonChecked(hwndDlg,IDC_CHECK_SPECIFICTIME)) watcherType|=SDWTF_SPECIFICTIME;
+ if(IsDlgButtonChecked(hwndDlg,IDC_CHECK_MESSAGE)) watcherType|=SDWTF_MESSAGE;
+ if(IsDlgButtonChecked(hwndDlg,IDC_CHECK_FILETRANSFER)) watcherType|=SDWTF_FILETRANSFER;
+ if(IsDlgButtonChecked(hwndDlg,IDC_CHECK_IDLE)) watcherType|=SDWTF_IDLE;
+ if(IsDlgButtonChecked(hwndDlg,IDC_CHECK_STATUS)) watcherType|=SDWTF_STATUS;
+ if(IsDlgButtonChecked(hwndDlg,IDC_CHECK_CPUUSAGE)) watcherType|=SDWTF_CPUUSAGE;
+ DBWriteContactSettingWord(NULL,"AutoShutdown","WatcherFlags",watcherType);
+ ServiceStartWatcher(0,watcherType);
+ }
+ /* fall through */
+ case IDCANCEL: /* WM_CLOSE */
+ DestroyWindow(hwndDlg);
+ return TRUE;
+ }
+ break;
+ }
+ CallSnappingWindowProc(hwndDlg,msg,wParam,lParam); /* Snapping Windows plugin */
+ return FALSE;
+}
+
+/************************* Services ***********************************/
+
+static int ServiceShowSettingsDialog(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ if(hwndSettingsDlg!=NULL) { /* already opened, bring to front */
+ SetForegroundWindow(hwndSettingsDlg);
+ return 0;
+ }
+ return (CreateDialog(hInst,MAKEINTRESOURCE(IDD_SETTINGS),NULL,SettingsDlgProc)==NULL);
+}
+
+/************************* Toolbar ************************************/
+
+static WORD hToolbarButton;
+
+static int ToolbarLoaded(WPARAM wParam,LPARAM lParam)
+{
+ TTBButtonV2 ttbb;
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+
+ ZeroMemory(&ttbb,sizeof(ttbb));
+ ttbb.cbSize=sizeof(ttbb);
+ /* toptoolbar offers icolib support */
+ ttbb.hIconUp=(HICON)LoadImage(hInst,MAKEINTRESOURCE(IDI_ACTIVE),IMAGE_ICON,0,0,0);
+ ttbb.hIconDn=(HICON)LoadImage(hInst,MAKEINTRESOURCE(IDI_INACTIVE),IMAGE_ICON,0,0,0);
+ ttbb.pszServiceUp=ttbb.pszServiceDown="AutoShutdown/MenuCommand";
+ ttbb.dwFlags=TTBBF_VISIBLE|TTBBF_SHOWTOOLTIP;
+ ttbb.name=Translate("Start/Stop automatic shutdown");
+
+ hToolbarButton=(WORD)CallService(MS_TTB_ADDBUTTON,(WPARAM)&ttbb,0);
+ if(ttbb.hIconUp!=NULL) DestroyIcon(ttbb.hIconUp);
+ if(ttbb.hIconDn!=NULL) DestroyIcon(ttbb.hIconDn);
+ return 0;
+}
+
+void SetShutdownToolbarButton(BOOL fActive)
+{
+ if(hToolbarButton) {
+ CallService(MS_TTB_SETBUTTONSTATE,hToolbarButton,fActive?TTBST_PUSHED:TTBST_RELEASED);
+ CallService(MS_TTB_SETBUTTONOPTIONS,MAKEWPARAM(TTBO_TIPNAME,hToolbarButton),(LPARAM)(fActive?Translate("Sdop automatic shutdown"):Translate("Start automatic shutdown")));
+ }
+}
+
+/************************* Menu Item **********************************/
+
+static HANDLE hMainMenuItem,hTrayMenuItem;
+extern HANDLE hActiveIcon,hInactiveIcon;
+
+void SetShutdownMenuItem(BOOL fActive)
+{
+ CLISTMENUITEM cmi;
+ ZeroMemory(&cmi,sizeof(cmi));
+ cmi.cbSize=sizeof(cmi);
+
+ /* main menu */
+ cmi.position=2001090000;
+ cmi.icolibItem=fActive?hActiveIcon:hInactiveIcon;
+ cmi.ptszName=fActive?_T("Stop automatic &shutdown"):_T("Automatic &shutdown..."); /* autotranslated */
+ cmi.pszService="AutoShutdown/MenuCommand";
+ cmi.flags=CMIF_TCHAR|CMIF_ICONFROMICOLIB;
+ if(hMainMenuItem!=NULL) {
+ cmi.flags|=CMIM_NAME|CMIM_ICON;
+ CallService(MS_CLIST_MODIFYMENUITEM,(WPARAM)hMainMenuItem,(LPARAM)&cmi);
+ }
+ else hMainMenuItem=(HANDLE)CallService(MS_CLIST_ADDMAINMENUITEM,0,(LPARAM)&cmi);
+
+ /* tray menu */
+ cmi.position=899999;
+ if(hTrayMenuItem!=NULL) {
+ cmi.flags|=CMIM_NAME|CMIM_ICON;
+ CallService(MS_CLIST_MODIFYMENUITEM,(WPARAM)hTrayMenuItem,(LPARAM)&cmi);
+ }
+ else hTrayMenuItem=(HANDLE)CallService(MS_CLIST_ADDTRAYMENUITEM,0,(LPARAM)&cmi);
+
+ IcoLib_ReleaseIcon(cmi.hIcon);
+}
+
+static int MenuItemCommand(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ /* toggle between StopWatcher and ShowSettingsDdialog */
+ if(ServiceIsWatcherEnabled(0,0))
+ ServiceStopWatcher(0,0);
+ else
+ ServiceShowSettingsDialog(0,0);
+ return 0;
+}
+
+/************************* Misc ***************************************/
+
+void InitSettingsDlg(void)
+{
+ /* Menu Item */
+ hServiceMenuCommand=CreateServiceFunction("AutoShutdown/MenuCommand",MenuItemCommand);
+ hMainMenuItem=hTrayMenuItem=NULL;
+ SetShutdownMenuItem(FALSE);
+ /* Toolbar Item */
+ hToolbarButton=0;
+ hHookToolbarLoaded=HookEvent(ME_TTB_MODULELOADED,ToolbarLoaded); /* no service to check for */
+ /* Hotkey */
+ SkinAddNewHotkey("AutoShutdown_Toggle",Translate("Main"),Translate("Toggle Automatic Shutdown"),'T',HOTKEYF_CONTROL|HOTKEYF_SHIFT,"AutoShutdown/MenuCommand");
+ /* Services */
+ hwndSettingsDlg=NULL;
+ hServiceShowDlg=CreateServiceFunction(MS_AUTOSHUTDOWN_SHOWSETTINGSDIALOG,ServiceShowSettingsDialog);
+}
+
+void UninitSettingsDlg(void)
+{
+ /* Toolbar Item */
+ UnhookEvent(hHookToolbarLoaded);
+ /* Menu Item */
+ DestroyServiceFunction(hServiceMenuCommand);
+ /* Services */
+ DestroyServiceFunction(hServiceShowDlg);
+}
+
diff --git a/plugins/AutoShutdown/settingsdlg.h b/plugins/AutoShutdown/settingsdlg.h
new file mode 100644
index 0000000000..2f7bf8ea84
--- /dev/null
+++ b/plugins/AutoShutdown/settingsdlg.h
@@ -0,0 +1,30 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+/* Menu Item */
+void SetShutdownMenuItem(BOOL fActive);
+
+/* Toolbar Button */
+void SetShutdownToolbarButton(BOOL fActive);
+
+/* Misc */
+void InitSettingsDlg(void);
+void UninitSettingsDlg(void);
diff --git a/plugins/AutoShutdown/shutdown.def b/plugins/AutoShutdown/shutdown.def
new file mode 100644
index 0000000000..09d13e6c16
--- /dev/null
+++ b/plugins/AutoShutdown/shutdown.def
@@ -0,0 +1,11 @@
+LIBRARY shutdown BASE=0x11070000
+SECTIONS
+ ; obfuscated email address
+ .rdata READ WRITE
+EXPORTS
+ MirandaPluginInfo PRIVATE
+ Load PRIVATE
+ Unload PRIVATE
+ ; v0.8 support
+ MirandaPluginInfoEx PRIVATE
+ MirandaPluginInterfaces PRIVATE
diff --git a/plugins/AutoShutdown/shutdown.dep b/plugins/AutoShutdown/shutdown.dep
new file mode 100644
index 0000000000..ec15869669
--- /dev/null
+++ b/plugins/AutoShutdown/shutdown.dep
@@ -0,0 +1,394 @@
+# Microsoft Developer Studio erstellte Abh�ngigkeitsdatei, einbezogen von shutdown.mak
+
+.\cpuusage.c : \
+ ".\common.h"\
+ ".\cpuusage.h"\
+ ".\frame.h"\
+ ".\include\m_autoreplacer.h"\
+ ".\include\m_button.h"\
+ ".\include\m_clc.h"\
+ ".\include\m_clist.h"\
+ ".\include\m_clistint.h"\
+ ".\include\m_clui.h"\
+ ".\include\m_cluiframes.h"\
+ ".\include\m_database.h"\
+ ".\include\m_file.h"\
+ ".\include\m_fontservice.h"\
+ ".\include\m_genmenu.h"\
+ ".\include\m_hddinfo.h"\
+ ".\include\m_hotkey.h"\
+ ".\include\m_hotkeysplus.h"\
+ ".\include\m_hotkeysservice.h"\
+ ".\include\m_icolib.h"\
+ ".\include\m_idle.h"\
+ ".\include\m_langpack.h"\
+ ".\include\m_magneticwindows.h"\
+ ".\include\m_message.h"\
+ ".\include\m_mwclc.h"\
+ ".\include\m_options.h"\
+ ".\include\m_plugins.h"\
+ ".\include\m_protocols.h"\
+ ".\include\m_protosvc.h"\
+ ".\include\m_skin.h"\
+ ".\include\m_snappingwindows.h"\
+ ".\include\m_system.h"\
+ ".\include\m_toptoolbar.h"\
+ ".\include\m_trigger.h"\
+ ".\include\m_utils.h"\
+ ".\include\m_weather.h"\
+ ".\include\newpluginapi.h"\
+ ".\include\statusmodes.h"\
+ ".\include\win2k.h"\
+ ".\m_shutdown.h"\
+ ".\options.h"\
+ ".\settingsdlg.h"\
+ ".\shutdownsvc.h"\
+ ".\utils.h"\
+ ".\watcher.h"\
+ "e:\vc98\include\basetsd.h"\
+
+
+.\frame.c : \
+ ".\common.h"\
+ ".\cpuusage.h"\
+ ".\frame.h"\
+ ".\include\m_autoreplacer.h"\
+ ".\include\m_button.h"\
+ ".\include\m_clc.h"\
+ ".\include\m_clist.h"\
+ ".\include\m_clistint.h"\
+ ".\include\m_clui.h"\
+ ".\include\m_cluiframes.h"\
+ ".\include\m_database.h"\
+ ".\include\m_file.h"\
+ ".\include\m_fontservice.h"\
+ ".\include\m_genmenu.h"\
+ ".\include\m_hddinfo.h"\
+ ".\include\m_hotkey.h"\
+ ".\include\m_hotkeysplus.h"\
+ ".\include\m_hotkeysservice.h"\
+ ".\include\m_icolib.h"\
+ ".\include\m_idle.h"\
+ ".\include\m_langpack.h"\
+ ".\include\m_magneticwindows.h"\
+ ".\include\m_message.h"\
+ ".\include\m_mwclc.h"\
+ ".\include\m_options.h"\
+ ".\include\m_plugins.h"\
+ ".\include\m_protocols.h"\
+ ".\include\m_protosvc.h"\
+ ".\include\m_skin.h"\
+ ".\include\m_snappingwindows.h"\
+ ".\include\m_system.h"\
+ ".\include\m_toptoolbar.h"\
+ ".\include\m_trigger.h"\
+ ".\include\m_utils.h"\
+ ".\include\m_weather.h"\
+ ".\include\newpluginapi.h"\
+ ".\include\statusmodes.h"\
+ ".\include\win2k.h"\
+ ".\m_shutdown.h"\
+ ".\options.h"\
+ ".\settingsdlg.h"\
+ ".\shutdownsvc.h"\
+ ".\utils.h"\
+ ".\watcher.h"\
+ "e:\vc98\include\basetsd.h"\
+
+
+.\main.c : \
+ ".\common.h"\
+ ".\cpuusage.h"\
+ ".\frame.h"\
+ ".\include\m_autoreplacer.h"\
+ ".\include\m_button.h"\
+ ".\include\m_clc.h"\
+ ".\include\m_clist.h"\
+ ".\include\m_clistint.h"\
+ ".\include\m_clui.h"\
+ ".\include\m_cluiframes.h"\
+ ".\include\m_database.h"\
+ ".\include\m_file.h"\
+ ".\include\m_fontservice.h"\
+ ".\include\m_genmenu.h"\
+ ".\include\m_hddinfo.h"\
+ ".\include\m_hotkey.h"\
+ ".\include\m_hotkeysplus.h"\
+ ".\include\m_hotkeysservice.h"\
+ ".\include\m_icolib.h"\
+ ".\include\m_idle.h"\
+ ".\include\m_langpack.h"\
+ ".\include\m_magneticwindows.h"\
+ ".\include\m_message.h"\
+ ".\include\m_mwclc.h"\
+ ".\include\m_options.h"\
+ ".\include\m_plugins.h"\
+ ".\include\m_protocols.h"\
+ ".\include\m_protosvc.h"\
+ ".\include\m_skin.h"\
+ ".\include\m_snappingwindows.h"\
+ ".\include\m_system.h"\
+ ".\include\m_toptoolbar.h"\
+ ".\include\m_trigger.h"\
+ ".\include\m_utils.h"\
+ ".\include\m_weather.h"\
+ ".\include\newpluginapi.h"\
+ ".\include\statusmodes.h"\
+ ".\include\win2k.h"\
+ ".\m_shutdown.h"\
+ ".\options.h"\
+ ".\settingsdlg.h"\
+ ".\shutdownsvc.h"\
+ ".\utils.h"\
+ ".\version.h"\
+ ".\watcher.h"\
+ "e:\vc98\include\basetsd.h"\
+
+
+.\options.c : \
+ ".\common.h"\
+ ".\cpuusage.h"\
+ ".\frame.h"\
+ ".\include\m_autoreplacer.h"\
+ ".\include\m_button.h"\
+ ".\include\m_clc.h"\
+ ".\include\m_clist.h"\
+ ".\include\m_clistint.h"\
+ ".\include\m_clui.h"\
+ ".\include\m_cluiframes.h"\
+ ".\include\m_database.h"\
+ ".\include\m_file.h"\
+ ".\include\m_fontservice.h"\
+ ".\include\m_genmenu.h"\
+ ".\include\m_hddinfo.h"\
+ ".\include\m_hotkey.h"\
+ ".\include\m_hotkeysplus.h"\
+ ".\include\m_hotkeysservice.h"\
+ ".\include\m_icolib.h"\
+ ".\include\m_idle.h"\
+ ".\include\m_langpack.h"\
+ ".\include\m_magneticwindows.h"\
+ ".\include\m_message.h"\
+ ".\include\m_mwclc.h"\
+ ".\include\m_options.h"\
+ ".\include\m_plugins.h"\
+ ".\include\m_protocols.h"\
+ ".\include\m_protosvc.h"\
+ ".\include\m_skin.h"\
+ ".\include\m_snappingwindows.h"\
+ ".\include\m_system.h"\
+ ".\include\m_toptoolbar.h"\
+ ".\include\m_trigger.h"\
+ ".\include\m_utils.h"\
+ ".\include\m_weather.h"\
+ ".\include\newpluginapi.h"\
+ ".\include\statusmodes.h"\
+ ".\include\win2k.h"\
+ ".\m_shutdown.h"\
+ ".\options.h"\
+ ".\settingsdlg.h"\
+ ".\shutdownsvc.h"\
+ ".\utils.h"\
+ ".\watcher.h"\
+ "e:\vc98\include\basetsd.h"\
+
+
+.\settingsdlg.c : \
+ ".\common.h"\
+ ".\cpuusage.h"\
+ ".\frame.h"\
+ ".\include\m_autoreplacer.h"\
+ ".\include\m_button.h"\
+ ".\include\m_clc.h"\
+ ".\include\m_clist.h"\
+ ".\include\m_clistint.h"\
+ ".\include\m_clui.h"\
+ ".\include\m_cluiframes.h"\
+ ".\include\m_database.h"\
+ ".\include\m_file.h"\
+ ".\include\m_fontservice.h"\
+ ".\include\m_genmenu.h"\
+ ".\include\m_hddinfo.h"\
+ ".\include\m_hotkey.h"\
+ ".\include\m_hotkeysplus.h"\
+ ".\include\m_hotkeysservice.h"\
+ ".\include\m_icolib.h"\
+ ".\include\m_idle.h"\
+ ".\include\m_langpack.h"\
+ ".\include\m_magneticwindows.h"\
+ ".\include\m_message.h"\
+ ".\include\m_mwclc.h"\
+ ".\include\m_options.h"\
+ ".\include\m_plugins.h"\
+ ".\include\m_protocols.h"\
+ ".\include\m_protosvc.h"\
+ ".\include\m_skin.h"\
+ ".\include\m_snappingwindows.h"\
+ ".\include\m_system.h"\
+ ".\include\m_toptoolbar.h"\
+ ".\include\m_trigger.h"\
+ ".\include\m_utils.h"\
+ ".\include\m_weather.h"\
+ ".\include\newpluginapi.h"\
+ ".\include\statusmodes.h"\
+ ".\include\win2k.h"\
+ ".\m_shutdown.h"\
+ ".\options.h"\
+ ".\settingsdlg.h"\
+ ".\shutdownsvc.h"\
+ ".\utils.h"\
+ ".\watcher.h"\
+ "e:\vc98\include\basetsd.h"\
+
+
+.\shutdownsvc.c : \
+ ".\common.h"\
+ ".\cpuusage.h"\
+ ".\frame.h"\
+ ".\include\m_autoreplacer.h"\
+ ".\include\m_button.h"\
+ ".\include\m_clc.h"\
+ ".\include\m_clist.h"\
+ ".\include\m_clistint.h"\
+ ".\include\m_clui.h"\
+ ".\include\m_cluiframes.h"\
+ ".\include\m_database.h"\
+ ".\include\m_file.h"\
+ ".\include\m_fontservice.h"\
+ ".\include\m_genmenu.h"\
+ ".\include\m_hddinfo.h"\
+ ".\include\m_hotkey.h"\
+ ".\include\m_hotkeysplus.h"\
+ ".\include\m_hotkeysservice.h"\
+ ".\include\m_icolib.h"\
+ ".\include\m_idle.h"\
+ ".\include\m_langpack.h"\
+ ".\include\m_magneticwindows.h"\
+ ".\include\m_message.h"\
+ ".\include\m_mwclc.h"\
+ ".\include\m_options.h"\
+ ".\include\m_plugins.h"\
+ ".\include\m_protocols.h"\
+ ".\include\m_protosvc.h"\
+ ".\include\m_skin.h"\
+ ".\include\m_snappingwindows.h"\
+ ".\include\m_system.h"\
+ ".\include\m_toptoolbar.h"\
+ ".\include\m_trigger.h"\
+ ".\include\m_utils.h"\
+ ".\include\m_weather.h"\
+ ".\include\newpluginapi.h"\
+ ".\include\statusmodes.h"\
+ ".\include\win2k.h"\
+ ".\m_shutdown.h"\
+ ".\options.h"\
+ ".\settingsdlg.h"\
+ ".\shutdownsvc.h"\
+ ".\utils.h"\
+ ".\watcher.h"\
+ "e:\vc98\include\basetsd.h"\
+
+
+.\utils.c : \
+ ".\common.h"\
+ ".\cpuusage.h"\
+ ".\frame.h"\
+ ".\include\m_autoreplacer.h"\
+ ".\include\m_button.h"\
+ ".\include\m_clc.h"\
+ ".\include\m_clist.h"\
+ ".\include\m_clistint.h"\
+ ".\include\m_clui.h"\
+ ".\include\m_cluiframes.h"\
+ ".\include\m_database.h"\
+ ".\include\m_file.h"\
+ ".\include\m_fontservice.h"\
+ ".\include\m_genmenu.h"\
+ ".\include\m_hddinfo.h"\
+ ".\include\m_hotkey.h"\
+ ".\include\m_hotkeysplus.h"\
+ ".\include\m_hotkeysservice.h"\
+ ".\include\m_icolib.h"\
+ ".\include\m_idle.h"\
+ ".\include\m_langpack.h"\
+ ".\include\m_magneticwindows.h"\
+ ".\include\m_message.h"\
+ ".\include\m_mwclc.h"\
+ ".\include\m_options.h"\
+ ".\include\m_plugins.h"\
+ ".\include\m_protocols.h"\
+ ".\include\m_protosvc.h"\
+ ".\include\m_skin.h"\
+ ".\include\m_snappingwindows.h"\
+ ".\include\m_system.h"\
+ ".\include\m_toptoolbar.h"\
+ ".\include\m_trigger.h"\
+ ".\include\m_utils.h"\
+ ".\include\m_weather.h"\
+ ".\include\newpluginapi.h"\
+ ".\include\statusmodes.h"\
+ ".\include\win2k.h"\
+ ".\m_shutdown.h"\
+ ".\options.h"\
+ ".\settingsdlg.h"\
+ ".\shutdownsvc.h"\
+ ".\utils.h"\
+ ".\watcher.h"\
+ "e:\vc98\include\basetsd.h"\
+
+
+.\watcher.c : \
+ ".\common.h"\
+ ".\cpuusage.h"\
+ ".\frame.h"\
+ ".\include\m_autoreplacer.h"\
+ ".\include\m_button.h"\
+ ".\include\m_clc.h"\
+ ".\include\m_clist.h"\
+ ".\include\m_clistint.h"\
+ ".\include\m_clui.h"\
+ ".\include\m_cluiframes.h"\
+ ".\include\m_database.h"\
+ ".\include\m_file.h"\
+ ".\include\m_fontservice.h"\
+ ".\include\m_genmenu.h"\
+ ".\include\m_hddinfo.h"\
+ ".\include\m_hotkey.h"\
+ ".\include\m_hotkeysplus.h"\
+ ".\include\m_hotkeysservice.h"\
+ ".\include\m_icolib.h"\
+ ".\include\m_idle.h"\
+ ".\include\m_langpack.h"\
+ ".\include\m_magneticwindows.h"\
+ ".\include\m_message.h"\
+ ".\include\m_mwclc.h"\
+ ".\include\m_options.h"\
+ ".\include\m_plugins.h"\
+ ".\include\m_protocols.h"\
+ ".\include\m_protosvc.h"\
+ ".\include\m_skin.h"\
+ ".\include\m_snappingwindows.h"\
+ ".\include\m_system.h"\
+ ".\include\m_toptoolbar.h"\
+ ".\include\m_trigger.h"\
+ ".\include\m_utils.h"\
+ ".\include\m_weather.h"\
+ ".\include\newpluginapi.h"\
+ ".\include\statusmodes.h"\
+ ".\include\win2k.h"\
+ ".\m_shutdown.h"\
+ ".\options.h"\
+ ".\settingsdlg.h"\
+ ".\shutdownsvc.h"\
+ ".\utils.h"\
+ ".\watcher.h"\
+ "e:\vc98\include\basetsd.h"\
+
+
+.\resource.rc : \
+ ".\include\m_utils.h"\
+ ".\res\active.ico"\
+ ".\res\header.ico"\
+ ".\res\inactive.ico"\
+ ".\version.rc"\
+
diff --git a/plugins/AutoShutdown/shutdown.dsp b/plugins/AutoShutdown/shutdown.dsp
new file mode 100644
index 0000000000..52d65badfa
--- /dev/null
+++ b/plugins/AutoShutdown/shutdown.dsp
@@ -0,0 +1,451 @@
+# Microsoft Developer Studio Project File - Name="shutdown" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** NICHT BEARBEITEN **
+
+# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
+
+CFG=shutdown - Win32 Release
+!MESSAGE Dies ist kein g�ltiges Makefile. Zum Erstellen dieses Projekts mit NMAKE
+!MESSAGE verwenden Sie den Befehl "Makefile exportieren" und f�hren Sie den Befehl
+!MESSAGE
+!MESSAGE NMAKE /f "shutdown.mak".
+!MESSAGE
+!MESSAGE Sie k�nnen beim Ausf�hren von NMAKE eine Konfiguration angeben
+!MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel:
+!MESSAGE
+!MESSAGE NMAKE /f "shutdown.mak" CFG="shutdown - Win32 Release"
+!MESSAGE
+!MESSAGE F�r die Konfiguration stehen zur Auswahl:
+!MESSAGE
+!MESSAGE "shutdown - Win32 Release" (basierend auf "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "shutdown - Win32 Debug" (basierend auf "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "shutdown - Win32 Release Unicode" (basierend auf "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "shutdown - Win32 Debug Unicode" (basierend auf "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "shutdown - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "release/ANSI"
+# PROP BASE Intermediate_Dir "temp/Release/ANSI"
+# PROP BASE Target_Dir "release/ANSI"
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "temp/Release/ANSI"
+# PROP Intermediate_Dir "temp/Release/ANSI"
+# PROP Ignore_Export_Lib 1
+# PROP Target_Dir "release/ANSI"
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SHUTDOWN_EXPORTS" /YX /FD /c
+# ADD CPP /nologo /MD /W4 /GX /O2 /I ".\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "STRICT" /D "SHUTDOWN_EXPORTS" /U "NO_STRICT" /FR /FD /opt:nowin98 /c
+# SUBTRACT CPP /YX
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "NDEBUG" /win32
+# SUBTRACT MTL /mktyplib203 /Oicf
+# ADD BASE RSC /l 0x1009 /d "NDEBUG"
+# ADD RSC /l 0x409 /i ".\include" /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
+# ADD LINK32 kernel32.lib comctl32.lib gdi32.lib user32.lib shell32.lib advapi32.lib /nologo /base:"0x11070000" /dll /pdb:"./release/ANSI/shutdown.pdb" /map:"release/ANSI/shutdown.map" /debug /machine:I386 /nodefaultlib:"uuid.lib" /nodefaultlib:"OLDNAMES" /def:"shutdown.def" /out:"./release/ANSI/shutdown.dll" /mapinfo:lines /opt:nowin98 /ignore:4078 /RELEASE
+# SUBTRACT LINK32 /pdb:none
+
+!ELSEIF "$(CFG)" == "shutdown - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "temp/Debug/ANSI"
+# PROP BASE Intermediate_Dir "temp/Debug/ANSI"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "temp/Debug/ANSI"
+# PROP Intermediate_Dir "temp/Debug/ANSI"
+# PROP Ignore_Export_Lib 1
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SHUTDOWN_EXPORTS" /YX /FD /GZ /c
+# ADD CPP /nologo /MTd /W4 /Gm /Gi /GR /GX /ZI /Od /I ".\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "STRICT" /D "SHUTDOWN_EXPORTS" /U "NO_STRICT" /FR /FD /GZ /c
+# SUBTRACT CPP /WX /YX
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# SUBTRACT MTL /Oicf
+# ADD BASE RSC /l 0x1009 /d "_DEBUG"
+# ADD RSC /l 0x409 /i ".\include" /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib comctl32.lib gdi32.lib user32.lib shell32.lib advapi32.lib /nologo /base:"0x11070000" /dll /pdb:"D:/Miranda IM/ANSI/Plugins/shutdown.pdb" /map /debug /machine:I386 /nodefaultlib:"uuid.lib" /nodefaultlib:"OLDNAMES" /def:"shutdown.def" /out:"D:/Miranda IM/ANSI/Plugins/shutdown.dll" /pdbtype:sept
+# SUBTRACT LINK32 /verbose /pdb:none
+
+!ELSEIF "$(CFG)" == "shutdown - Win32 Release Unicode"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "release/Unicode"
+# PROP BASE Intermediate_Dir "temp/Release/Unicode"
+# PROP BASE Target_Dir "release/Unicode"
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "temp/Release/Unicode"
+# PROP Intermediate_Dir "temp/Release/Unicode"
+# PROP Ignore_Export_Lib 1
+# PROP Target_Dir "release/Unicode"
+# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SHUTDOWN_EXPORTS" /YX /FD /c
+# ADD CPP /nologo /MD /W4 /GX /O2 /I ".\include" /D "NDEBUG" /D "UNICODE" /D "_UNICODE" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "STRICT" /D "SHUTDOWN_EXPORTS" /U "_MBCS" /U "NO_STRICT" /FR /FD /opt:nowin98 /c
+# SUBTRACT CPP /YX
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "NDEBUG" /win32
+# SUBTRACT MTL /mktyplib203 /Oicf
+# ADD BASE RSC /l 0x1009 /d "NDEBUG" /d "_UNICODE" /d "UNICODE"
+# ADD RSC /l 0x409 /i ".\include" /d "NDEBUG" /d "_UNICODE" /d "UNICODE"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
+# ADD LINK32 kernel32.lib comctl32.lib gdi32.lib user32.lib shell32.lib advapi32.lib /nologo /base:"0x11070000" /dll /pdb:"./release/Unicode/shutdown.pdb" /map:"release/Unicode/shutdown.map" /debug /machine:I386 /nodefaultlib:"uuid.lib" /nodefaultlib:"OLDNAMES" /def:"shutdown.def" /out:"./release/Unicode/shutdown.dll" /mapinfo:lines /opt:nowin98 /ignore:4078 /RELEASE
+# SUBTRACT LINK32 /pdb:none
+
+!ELSEIF "$(CFG)" == "shutdown - Win32 Debug Unicode"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "temp/Debug/Unicode"
+# PROP BASE Intermediate_Dir "temp/Debug/Unicode"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "temp/Debug/Unicode"
+# PROP Intermediate_Dir "temp/Debug/Unicode"
+# PROP Ignore_Export_Lib 1
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SHUTDOWN_EXPORTS" /YX /FD /GZ /c
+# ADD CPP /nologo /MTd /W4 /Gm /Gi /GR /GX /ZI /Od /I ".\include" /D "_DEBUG" /D "UNICODE" /D "_UNICODE" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "STRICT" /D "SHUTDOWN_EXPORTS" /U "_MBCS" /U "NO_STRICT" /FR /FD /GZ /c
+# SUBTRACT CPP /WX /YX
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# SUBTRACT MTL /Oicf
+# ADD BASE RSC /l 0x1009 /d "_DEBUG" /d "_UNICODE" /d "UNICODE"
+# ADD RSC /l 0x409 /i ".\include" /d "_DEBUG" /d "_UNICODE" /d "UNICODE"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 kernel32.lib comctl32.lib gdi32.lib user32.lib shell32.lib advapi32.lib /nologo /base:"0x11070000" /dll /pdb:"D:/Miranda IM/Unicode/Plugins/shutdown.pdb" /map /debug /machine:I386 /nodefaultlib:"uuid.lib" /nodefaultlib:"OLDNAMES" /def:"shutdown.def" /out:"D:/Miranda IM/Unicode/Plugins/shutdown.dll" /pdbtype:sept
+# SUBTRACT LINK32 /pdb:none /nodefaultlib
+
+!ENDIF
+
+# Begin Target
+
+# Name "shutdown - Win32 Release"
+# Name "shutdown - Win32 Debug"
+# Name "shutdown - Win32 Release Unicode"
+# Name "shutdown - Win32 Debug Unicode"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=.\cpuusage.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\frame.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\main.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\options.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\settingsdlg.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\shutdownsvc.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\utils.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\watcher.c
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# Begin Source File
+
+SOURCE=.\common.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\cpuusage.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\frame.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\m_shutdown.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\options.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\settingsdlg.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\shutdownsvc.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\utils.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\watcher.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# Begin Source File
+
+SOURCE=.\res\active.ico
+# End Source File
+# Begin Source File
+
+SOURCE=.\res\header.ico
+# End Source File
+# Begin Source File
+
+SOURCE=.\res\inactive.ico
+# End Source File
+# Begin Source File
+
+SOURCE=.\resource.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\resource.rc
+# End Source File
+# Begin Source File
+
+SOURCE=.\version.h
+# End Source File
+# End Group
+# Begin Group "Documentation"
+
+# PROP Default_Filter "txt"
+# Begin Source File
+
+SOURCE=.\Extensions\countdown.wav
+# End Source File
+# Begin Source File
+
+SOURCE=.\m_shutdown.inc
+# End Source File
+# Begin Source File
+
+SOURCE=".\docs\Shutdown-Developer.txt"
+# End Source File
+# Begin Source File
+
+SOURCE=".\docs\Shutdown-License.txt"
+# End Source File
+# Begin Source File
+
+SOURCE=".\docs\Shutdown-Readme.txt"
+# End Source File
+# Begin Source File
+
+SOURCE=".\docs\Shutdown-Translation.txt"
+# End Source File
+# End Group
+# Begin Group "SDK"
+
+# PROP Default_Filter "*.h"
+# Begin Source File
+
+SOURCE=.\include\m_autoreplacer.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_button.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_clc.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_clist.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_clistint.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_clui.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_cluiframes.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_database.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_file.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_fontservice.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_genmenu.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_hddinfo.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_hotkey.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_hotkeysplus.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_hotkeysservice.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_icolib.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_idle.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_langpack.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_magneticwindows.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_message.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_mwclc.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_options.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_plugins.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_protocols.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_protomod.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_protosvc.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_skin.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_snappingwindows.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_system.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_toptoolbar.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_trigger.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_updater.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_utils.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\m_weather.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\newpluginapi.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\statusmodes.h
+# End Source File
+# Begin Source File
+
+SOURCE=.\include\win2k.h
+# End Source File
+# End Group
+# Begin Source File
+
+SOURCE=.\Info_Src.txt
+# End Source File
+# Begin Source File
+
+SOURCE=.\License_Appendix.txt
+# End Source File
+# End Target
+# End Project
diff --git a/plugins/AutoShutdown/shutdown.dsw b/plugins/AutoShutdown/shutdown.dsw
new file mode 100644
index 0000000000..b5435be4b4
--- /dev/null
+++ b/plugins/AutoShutdown/shutdown.dsw
@@ -0,0 +1,29 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00
+# WARNUNG: DIESE ARBEITSBEREICHSDATEI DARF NICHT BEARBEITET ODER GEL�SCHT WERDEN!
+
+###############################################################################
+
+Project: "shutdown"=".\shutdown.dsp" - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+}}}
+
+###############################################################################
+
+Global:
+
+Package=<5>
+{{{
+}}}
+
+Package=<3>
+{{{
+}}}
+
+###############################################################################
+
diff --git a/plugins/AutoShutdown/shutdown.mak b/plugins/AutoShutdown/shutdown.mak
new file mode 100644
index 0000000000..daaa0217de
--- /dev/null
+++ b/plugins/AutoShutdown/shutdown.mak
@@ -0,0 +1,435 @@
+# Microsoft Developer Studio Generated NMAKE File, Based on shutdown.dsp
+!IF "$(CFG)" == ""
+CFG=shutdown - Win32 Release
+!MESSAGE Keine Konfiguration angegeben. shutdown - Win32 Release wird als Standard verwendet.
+!ENDIF
+
+!IF "$(CFG)" != "shutdown - Win32 Release" && "$(CFG)" != "shutdown - Win32 Debug" && "$(CFG)" != "shutdown - Win32 Release Unicode" && "$(CFG)" != "shutdown - Win32 Debug Unicode"
+!MESSAGE Ung�ltige Konfiguration "$(CFG)" angegeben.
+!MESSAGE Sie k�nnen beim Ausf�hren von NMAKE eine Konfiguration angeben
+!MESSAGE durch Definieren des Makros CFG in der Befehlszeile. Zum Beispiel:
+!MESSAGE
+!MESSAGE NMAKE /f "shutdown.mak" CFG="shutdown - Win32 Release"
+!MESSAGE
+!MESSAGE F�r die Konfiguration stehen zur Auswahl:
+!MESSAGE
+!MESSAGE "shutdown - Win32 Release" (basierend auf "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "shutdown - Win32 Debug" (basierend auf "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "shutdown - Win32 Release Unicode" (basierend auf "Win32 (x86) Dynamic-Link Library")
+!MESSAGE "shutdown - Win32 Debug Unicode" (basierend auf "Win32 (x86) Dynamic-Link Library")
+!MESSAGE
+!ERROR Eine ung�ltige Konfiguration wurde angegeben.
+!ENDIF
+
+!IF "$(OS)" == "Windows_NT"
+NULL=
+!ELSE
+NULL=nul
+!ENDIF
+
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF "$(CFG)" == "shutdown - Win32 Release"
+
+OUTDIR=.\temp/Release/ANSI
+INTDIR=.\temp/Release/ANSI
+# Begin Custom Macros
+OutDir=.\temp/Release/ANSI
+# End Custom Macros
+
+ALL : ".\release\ANSI\shutdown.dll" "$(OUTDIR)\shutdown.bsc"
+
+
+CLEAN :
+ -@erase "$(INTDIR)\cpuusage.obj"
+ -@erase "$(INTDIR)\cpuusage.sbr"
+ -@erase "$(INTDIR)\frame.obj"
+ -@erase "$(INTDIR)\frame.sbr"
+ -@erase "$(INTDIR)\main.obj"
+ -@erase "$(INTDIR)\main.sbr"
+ -@erase "$(INTDIR)\options.obj"
+ -@erase "$(INTDIR)\options.sbr"
+ -@erase "$(INTDIR)\resource.res"
+ -@erase "$(INTDIR)\settingsdlg.obj"
+ -@erase "$(INTDIR)\settingsdlg.sbr"
+ -@erase "$(INTDIR)\shutdownsvc.obj"
+ -@erase "$(INTDIR)\shutdownsvc.sbr"
+ -@erase "$(INTDIR)\utils.obj"
+ -@erase "$(INTDIR)\utils.sbr"
+ -@erase "$(INTDIR)\vc60.idb"
+ -@erase "$(INTDIR)\watcher.obj"
+ -@erase "$(INTDIR)\watcher.sbr"
+ -@erase "$(OUTDIR)\shutdown.bsc"
+ -@erase "$(OUTDIR)\shutdown.exp"
+ -@erase ".\release\ANSI\shutdown.dll"
+ -@erase ".\release\ANSI\shutdown.pdb"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+CPP_PROJ=/nologo /MD /W4 /GX /O2 /I ".\include" /D "NDEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "STRICT" /D "SHUTDOWN_EXPORTS" /U "NO_STRICT" /FR"$(INTDIR)\\" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /opt:nowin98 /c
+MTL_PROJ=/nologo /D "NDEBUG" /win32
+RSC_PROJ=/l 0x409 /fo"$(INTDIR)\resource.res" /i ".\include" /d "NDEBUG"
+BSC32=bscmake.exe
+BSC32_FLAGS=/nologo /o"$(OUTDIR)\shutdown.bsc"
+BSC32_SBRS= \
+ "$(INTDIR)\cpuusage.sbr" \
+ "$(INTDIR)\frame.sbr" \
+ "$(INTDIR)\main.sbr" \
+ "$(INTDIR)\options.sbr" \
+ "$(INTDIR)\settingsdlg.sbr" \
+ "$(INTDIR)\shutdownsvc.sbr" \
+ "$(INTDIR)\utils.sbr" \
+ "$(INTDIR)\watcher.sbr"
+
+"$(OUTDIR)\shutdown.bsc" : "$(OUTDIR)" $(BSC32_SBRS)
+ $(BSC32) @<<
+ $(BSC32_FLAGS) $(BSC32_SBRS)
+<<
+
+LINK32=link.exe
+LINK32_FLAGS=kernel32.lib comctl32.lib gdi32.lib user32.lib shell32.lib advapi32.lib /nologo /base:"0x11070000" /dll /incremental:no /pdb:"./release/ANSI/shutdown.pdb" /debug /machine:I386 /nodefaultlib:"uuid.lib" /nodefaultlib:"OLDNAMES" /def:"shutdown.def" /out:"./release/ANSI/shutdown.dll" /implib:"$(OUTDIR)\shutdown.lib" /opt:nowin98 /ignore:4078 /RELEASE
+LINK32_OBJS= \
+ "$(INTDIR)\cpuusage.obj" \
+ "$(INTDIR)\frame.obj" \
+ "$(INTDIR)\main.obj" \
+ "$(INTDIR)\options.obj" \
+ "$(INTDIR)\settingsdlg.obj" \
+ "$(INTDIR)\shutdownsvc.obj" \
+ "$(INTDIR)\utils.obj" \
+ "$(INTDIR)\watcher.obj" \
+ "$(INTDIR)\resource.res"
+
+".\release\ANSI\shutdown.dll" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ELSEIF "$(CFG)" == "shutdown - Win32 Debug"
+
+OUTDIR=.\temp/Debug/ANSI
+INTDIR=.\temp/Debug/ANSI
+# Begin Custom Macros
+OutDir=.\temp/Debug/ANSI
+# End Custom Macros
+
+ALL : "..\Miranda IM\ANSI\Plugins\shutdown.dll" "$(OUTDIR)\shutdown.bsc"
+
+
+CLEAN :
+ -@erase "$(INTDIR)\cpuusage.obj"
+ -@erase "$(INTDIR)\cpuusage.sbr"
+ -@erase "$(INTDIR)\frame.obj"
+ -@erase "$(INTDIR)\frame.sbr"
+ -@erase "$(INTDIR)\main.obj"
+ -@erase "$(INTDIR)\main.sbr"
+ -@erase "$(INTDIR)\options.obj"
+ -@erase "$(INTDIR)\options.sbr"
+ -@erase "$(INTDIR)\resource.res"
+ -@erase "$(INTDIR)\settingsdlg.obj"
+ -@erase "$(INTDIR)\settingsdlg.sbr"
+ -@erase "$(INTDIR)\shutdownsvc.obj"
+ -@erase "$(INTDIR)\shutdownsvc.sbr"
+ -@erase "$(INTDIR)\utils.obj"
+ -@erase "$(INTDIR)\utils.sbr"
+ -@erase "$(INTDIR)\vc60.idb"
+ -@erase "$(INTDIR)\vc60.pdb"
+ -@erase "$(INTDIR)\watcher.obj"
+ -@erase "$(INTDIR)\watcher.sbr"
+ -@erase "$(OUTDIR)\shutdown.bsc"
+ -@erase "$(OUTDIR)\shutdown.exp"
+ -@erase "$(OUTDIR)\shutdown.map"
+ -@erase "..\Miranda IM\ANSI\Plugins\shutdown.dll"
+ -@erase "..\Miranda IM\ANSI\Plugins\shutdown.ilk"
+ -@erase "..\Miranda IM\ANSI\Plugins\shutdown.pdb"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+CPP_PROJ=/nologo /MTd /W4 /Gm /Gi /GR /GX /ZI /Od /I ".\include" /D "_DEBUG" /D "WIN32" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "STRICT" /D "SHUTDOWN_EXPORTS" /U "NO_STRICT" /FR"$(INTDIR)\\" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /GZ /c
+MTL_PROJ=/nologo /D "_DEBUG" /mktyplib203 /win32
+RSC_PROJ=/l 0x409 /fo"$(INTDIR)\resource.res" /i ".\include" /d "_DEBUG"
+BSC32=bscmake.exe
+BSC32_FLAGS=/nologo /o"$(OUTDIR)\shutdown.bsc"
+BSC32_SBRS= \
+ "$(INTDIR)\cpuusage.sbr" \
+ "$(INTDIR)\frame.sbr" \
+ "$(INTDIR)\main.sbr" \
+ "$(INTDIR)\options.sbr" \
+ "$(INTDIR)\settingsdlg.sbr" \
+ "$(INTDIR)\shutdownsvc.sbr" \
+ "$(INTDIR)\utils.sbr" \
+ "$(INTDIR)\watcher.sbr"
+
+"$(OUTDIR)\shutdown.bsc" : "$(OUTDIR)" $(BSC32_SBRS)
+ $(BSC32) @<<
+ $(BSC32_FLAGS) $(BSC32_SBRS)
+<<
+
+LINK32=link.exe
+LINK32_FLAGS=kernel32.lib comctl32.lib gdi32.lib user32.lib shell32.lib advapi32.lib /nologo /base:"0x11070000" /dll /incremental:yes /pdb:"C:/Dokumente und Einstellungen/bib-nutzer/Desktop/Miranda IM/ANSI/Plugins/shutdown.pdb" /map:"$(INTDIR)\shutdown.map" /debug /machine:I386 /nodefaultlib:"uuid.lib" /nodefaultlib:"OLDNAMES" /def:"shutdown.def" /out:"C:/Dokumente und Einstellungen/bib-nutzer/Desktop/Miranda IM/ANSI/Plugins/shutdown.dll" /implib:"$(OUTDIR)\shutdown.lib" /pdbtype:sept
+LINK32_OBJS= \
+ "$(INTDIR)\cpuusage.obj" \
+ "$(INTDIR)\frame.obj" \
+ "$(INTDIR)\main.obj" \
+ "$(INTDIR)\options.obj" \
+ "$(INTDIR)\settingsdlg.obj" \
+ "$(INTDIR)\shutdownsvc.obj" \
+ "$(INTDIR)\utils.obj" \
+ "$(INTDIR)\watcher.obj" \
+ "$(INTDIR)\resource.res"
+
+"..\Miranda IM\ANSI\Plugins\shutdown.dll" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ELSEIF "$(CFG)" == "shutdown - Win32 Release Unicode"
+
+OUTDIR=.\temp/Release/Unicode
+INTDIR=.\temp/Release/Unicode
+# Begin Custom Macros
+OutDir=.\temp/Release/Unicode
+# End Custom Macros
+
+ALL : ".\release\Unicode\shutdown.dll" "$(OUTDIR)\shutdown.bsc"
+
+
+CLEAN :
+ -@erase "$(INTDIR)\cpuusage.obj"
+ -@erase "$(INTDIR)\cpuusage.sbr"
+ -@erase "$(INTDIR)\frame.obj"
+ -@erase "$(INTDIR)\frame.sbr"
+ -@erase "$(INTDIR)\main.obj"
+ -@erase "$(INTDIR)\main.sbr"
+ -@erase "$(INTDIR)\options.obj"
+ -@erase "$(INTDIR)\options.sbr"
+ -@erase "$(INTDIR)\resource.res"
+ -@erase "$(INTDIR)\settingsdlg.obj"
+ -@erase "$(INTDIR)\settingsdlg.sbr"
+ -@erase "$(INTDIR)\shutdownsvc.obj"
+ -@erase "$(INTDIR)\shutdownsvc.sbr"
+ -@erase "$(INTDIR)\utils.obj"
+ -@erase "$(INTDIR)\utils.sbr"
+ -@erase "$(INTDIR)\vc60.idb"
+ -@erase "$(INTDIR)\watcher.obj"
+ -@erase "$(INTDIR)\watcher.sbr"
+ -@erase "$(OUTDIR)\shutdown.bsc"
+ -@erase "$(OUTDIR)\shutdown.exp"
+ -@erase ".\release\Unicode\shutdown.dll"
+ -@erase ".\release\Unicode\shutdown.pdb"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+CPP_PROJ=/nologo /MD /W4 /GX /O2 /I ".\include" /D "NDEBUG" /D "UNICODE" /D "_UNICODE" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "STRICT" /D "SHUTDOWN_EXPORTS" /U "_MBCS" /U "NO_STRICT" /FR"$(INTDIR)\\" /Fp"$(INTDIR)\shutdown.pch" /YX"common.h" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /opt:nowin98 /c
+MTL_PROJ=/nologo /D "NDEBUG" /win32
+RSC_PROJ=/l 0x409 /fo"$(INTDIR)\resource.res" /i ".\include" /d "NDEBUG" /d "_UNICODE" /d "UNICODE"
+BSC32=bscmake.exe
+BSC32_FLAGS=/nologo /o"$(OUTDIR)\shutdown.bsc"
+BSC32_SBRS= \
+ "$(INTDIR)\cpuusage.sbr" \
+ "$(INTDIR)\frame.sbr" \
+ "$(INTDIR)\main.sbr" \
+ "$(INTDIR)\options.sbr" \
+ "$(INTDIR)\settingsdlg.sbr" \
+ "$(INTDIR)\shutdownsvc.sbr" \
+ "$(INTDIR)\utils.sbr" \
+ "$(INTDIR)\watcher.sbr"
+
+"$(OUTDIR)\shutdown.bsc" : "$(OUTDIR)" $(BSC32_SBRS)
+ $(BSC32) @<<
+ $(BSC32_FLAGS) $(BSC32_SBRS)
+<<
+
+LINK32=link.exe
+LINK32_FLAGS=kernel32.lib comctl32.lib gdi32.lib user32.lib shell32.lib advapi32.lib /nologo /base:"0x11070000" /dll /incremental:no /pdb:"./release/Unicode/shutdown.pdb" /debug /machine:I386 /nodefaultlib:"uuid.lib" /nodefaultlib:"OLDNAMES" /def:"shutdown.def" /out:"./release/Unicode/shutdown.dll" /implib:"$(OUTDIR)\shutdown.lib" /opt:nowin98 /ignore:4078 /RELEASE
+LINK32_OBJS= \
+ "$(INTDIR)\cpuusage.obj" \
+ "$(INTDIR)\frame.obj" \
+ "$(INTDIR)\main.obj" \
+ "$(INTDIR)\options.obj" \
+ "$(INTDIR)\settingsdlg.obj" \
+ "$(INTDIR)\shutdownsvc.obj" \
+ "$(INTDIR)\utils.obj" \
+ "$(INTDIR)\watcher.obj" \
+ "$(INTDIR)\resource.res"
+
+".\release\Unicode\shutdown.dll" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ELSEIF "$(CFG)" == "shutdown - Win32 Debug Unicode"
+
+OUTDIR=.\temp/Debug/Unicode
+INTDIR=.\temp/Debug/Unicode
+# Begin Custom Macros
+OutDir=.\temp/Debug/Unicode
+# End Custom Macros
+
+ALL : "..\Miranda IM\Unicode\Plugins\shutdown.dll" "$(OUTDIR)\shutdown.bsc"
+
+
+CLEAN :
+ -@erase "$(INTDIR)\cpuusage.obj"
+ -@erase "$(INTDIR)\cpuusage.sbr"
+ -@erase "$(INTDIR)\frame.obj"
+ -@erase "$(INTDIR)\frame.sbr"
+ -@erase "$(INTDIR)\main.obj"
+ -@erase "$(INTDIR)\main.sbr"
+ -@erase "$(INTDIR)\options.obj"
+ -@erase "$(INTDIR)\options.sbr"
+ -@erase "$(INTDIR)\resource.res"
+ -@erase "$(INTDIR)\settingsdlg.obj"
+ -@erase "$(INTDIR)\settingsdlg.sbr"
+ -@erase "$(INTDIR)\shutdownsvc.obj"
+ -@erase "$(INTDIR)\shutdownsvc.sbr"
+ -@erase "$(INTDIR)\utils.obj"
+ -@erase "$(INTDIR)\utils.sbr"
+ -@erase "$(INTDIR)\vc60.idb"
+ -@erase "$(INTDIR)\vc60.pdb"
+ -@erase "$(INTDIR)\watcher.obj"
+ -@erase "$(INTDIR)\watcher.sbr"
+ -@erase "$(OUTDIR)\shutdown.bsc"
+ -@erase "$(OUTDIR)\shutdown.exp"
+ -@erase "$(OUTDIR)\shutdown.map"
+ -@erase "..\Miranda IM\Unicode\Plugins\shutdown.dll"
+ -@erase "..\Miranda IM\Unicode\Plugins\shutdown.ilk"
+ -@erase "..\Miranda IM\Unicode\Plugins\shutdown.pdb"
+
+"$(OUTDIR)" :
+ if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
+
+CPP_PROJ=/nologo /MTd /W4 /Gm /Gi /GR /GX /ZI /Od /I ".\include" /D "_DEBUG" /D "UNICODE" /D "_UNICODE" /D "WIN32" /D "_WINDOWS" /D "_USRDLL" /D "STRICT" /D "SHUTDOWN_EXPORTS" /U "_MBCS" /U "NO_STRICT" /FR"$(INTDIR)\\" /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /GZ /c
+MTL_PROJ=/nologo /D "_DEBUG" /mktyplib203 /win32
+RSC_PROJ=/l 0x409 /fo"$(INTDIR)\resource.res" /i ".\include" /d "_DEBUG" /d "_UNICODE" /d "UNICODE"
+BSC32=bscmake.exe
+BSC32_FLAGS=/nologo /o"$(OUTDIR)\shutdown.bsc"
+BSC32_SBRS= \
+ "$(INTDIR)\cpuusage.sbr" \
+ "$(INTDIR)\frame.sbr" \
+ "$(INTDIR)\main.sbr" \
+ "$(INTDIR)\options.sbr" \
+ "$(INTDIR)\settingsdlg.sbr" \
+ "$(INTDIR)\shutdownsvc.sbr" \
+ "$(INTDIR)\utils.sbr" \
+ "$(INTDIR)\watcher.sbr"
+
+"$(OUTDIR)\shutdown.bsc" : "$(OUTDIR)" $(BSC32_SBRS)
+ $(BSC32) @<<
+ $(BSC32_FLAGS) $(BSC32_SBRS)
+<<
+
+LINK32=link.exe
+LINK32_FLAGS=kernel32.lib comctl32.lib gdi32.lib user32.lib shell32.lib advapi32.lib /nologo /base:"0x11070000" /dll /incremental:yes /pdb:"C:/Dokumente und Einstellungen/bib-nutzer/Desktop/Miranda IM/Unicode/Plugins/shutdown.pdb" /map:"$(INTDIR)\shutdown.map" /debug /machine:I386 /nodefaultlib:"uuid.lib" /nodefaultlib:"OLDNAMES" /def:"shutdown.def" /out:"C:/Dokumente und Einstellungen/bib-nutzer/Desktop/Miranda IM/Unicode/Plugins/shutdown.dll" /implib:"$(OUTDIR)\shutdown.lib" /pdbtype:sept
+LINK32_OBJS= \
+ "$(INTDIR)\cpuusage.obj" \
+ "$(INTDIR)\frame.obj" \
+ "$(INTDIR)\main.obj" \
+ "$(INTDIR)\options.obj" \
+ "$(INTDIR)\settingsdlg.obj" \
+ "$(INTDIR)\shutdownsvc.obj" \
+ "$(INTDIR)\utils.obj" \
+ "$(INTDIR)\watcher.obj" \
+ "$(INTDIR)\resource.res"
+
+"..\Miranda IM\Unicode\Plugins\shutdown.dll" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
+ $(LINK32) @<<
+ $(LINK32_FLAGS) $(LINK32_OBJS)
+<<
+
+!ENDIF
+
+.c{$(INTDIR)}.obj::
+ $(CPP) @<<
+ $(CPP_PROJ) $<
+<<
+
+.cpp{$(INTDIR)}.obj::
+ $(CPP) @<<
+ $(CPP_PROJ) $<
+<<
+
+.cxx{$(INTDIR)}.obj::
+ $(CPP) @<<
+ $(CPP_PROJ) $<
+<<
+
+.c{$(INTDIR)}.sbr::
+ $(CPP) @<<
+ $(CPP_PROJ) $<
+<<
+
+.cpp{$(INTDIR)}.sbr::
+ $(CPP) @<<
+ $(CPP_PROJ) $<
+<<
+
+.cxx{$(INTDIR)}.sbr::
+ $(CPP) @<<
+ $(CPP_PROJ) $<
+<<
+
+
+!IF "$(NO_EXTERNAL_DEPS)" != "1"
+!IF EXISTS("shutdown.dep")
+!INCLUDE "shutdown.dep"
+!ELSE
+!MESSAGE Warning: cannot find "shutdown.dep"
+!ENDIF
+!ENDIF
+
+
+!IF "$(CFG)" == "shutdown - Win32 Release" || "$(CFG)" == "shutdown - Win32 Debug" || "$(CFG)" == "shutdown - Win32 Release Unicode" || "$(CFG)" == "shutdown - Win32 Debug Unicode"
+SOURCE=.\cpuusage.c
+
+"$(INTDIR)\cpuusage.obj" "$(INTDIR)\cpuusage.sbr" : $(SOURCE) "$(INTDIR)"
+
+
+SOURCE=.\frame.c
+
+"$(INTDIR)\frame.obj" "$(INTDIR)\frame.sbr" : $(SOURCE) "$(INTDIR)"
+
+
+SOURCE=.\main.c
+
+"$(INTDIR)\main.obj" "$(INTDIR)\main.sbr" : $(SOURCE) "$(INTDIR)"
+
+
+SOURCE=.\options.c
+
+"$(INTDIR)\options.obj" "$(INTDIR)\options.sbr" : $(SOURCE) "$(INTDIR)"
+
+
+SOURCE=.\settingsdlg.c
+
+"$(INTDIR)\settingsdlg.obj" "$(INTDIR)\settingsdlg.sbr" : $(SOURCE) "$(INTDIR)"
+
+
+SOURCE=.\shutdownsvc.c
+
+"$(INTDIR)\shutdownsvc.obj" "$(INTDIR)\shutdownsvc.sbr" : $(SOURCE) "$(INTDIR)"
+
+
+SOURCE=.\utils.c
+
+"$(INTDIR)\utils.obj" "$(INTDIR)\utils.sbr" : $(SOURCE) "$(INTDIR)"
+
+
+SOURCE=.\watcher.c
+
+"$(INTDIR)\watcher.obj" "$(INTDIR)\watcher.sbr" : $(SOURCE) "$(INTDIR)"
+
+
+SOURCE=.\resource.rc
+
+"$(INTDIR)\resource.res" : $(SOURCE) "$(INTDIR)"
+ $(RSC) $(RSC_PROJ) $(SOURCE)
+
+
+
+!ENDIF
+
diff --git a/plugins/AutoShutdown/shutdownsvc.c b/plugins/AutoShutdown/shutdownsvc.c
new file mode 100644
index 0000000000..2b519cc512
--- /dev/null
+++ b/plugins/AutoShutdown/shutdownsvc.c
@@ -0,0 +1,624 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include "common.h"
+
+/* Shutdown Dialog */
+static HWND hwndShutdownDlg;
+extern HINSTANCE hInst;
+/* Services */
+static HANDLE hEventOkToShutdown,hEventShutdown;
+static HANDLE hServiceShutdown,hServiceIsTypeEnabled,hServiceGetTypeDesc;
+
+/************************* Utils **************************************/
+
+static BOOL WinNT_SetPrivilege(TCHAR *pszPrivName,BOOL bEnable)
+{
+ BOOL bReturn=FALSE;
+ HANDLE hToken;
+ TOKEN_PRIVILEGES tkp;
+ /* get a token for this process */
+ if(OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,&hToken)) {
+ tkp.PrivilegeCount=1; /* one privilege is to set */
+ /* get the LUID for the shutdown privilege */
+ if(LookupPrivilegeValue(NULL,pszPrivName,&tkp.Privileges[0].Luid)) {
+ tkp.Privileges[0].Attributes=bEnable?SE_PRIVILEGE_ENABLED:0;
+ /* get the shutdown privilege for this process */
+ bReturn=AdjustTokenPrivileges(hToken,FALSE,&tkp,0,(PTOKEN_PRIVILEGES)NULL,0);
+ }
+ CloseHandle(hToken);
+ }
+ return bReturn;
+}
+
+static void BroadcastEndSession(DWORD dwRecipients,LPARAM lParam)
+{
+ LONG (WINAPI *pfnBroadcastSystemMessage)(DWORD,DWORD*,UINT,WPARAM,LPARAM);
+#if defined(_UNICODE)
+ *(PROC*)&pfnBroadcastSystemMessage=GetProcAddress(GetModuleHandleA("USER32"),"BroadcastSystemMessageW");
+#else
+ *(PROC*)&pfnBroadcastSystemMessage=GetProcAddress(GetModuleHandleA("USER32"),"BroadcastSystemMessageA");
+ if(!pfnBroadcastSystemMessage) /* Win95 has undecorated API */
+ *(PROC*)&pfnBroadcastSystemMessage=GetProcAddress(GetModuleHandleA("USER32"),"BroadcastSystemMessage");
+#endif
+ if(pfnBroadcastSystemMessage)
+ pfnBroadcastSystemMessage(BSF_FORCEIFHUNG,&dwRecipients,WM_ENDSESSION,TRUE,lParam);
+}
+
+static BOOL WinNT_IsWorkStationLocked(void)
+{
+ HDESK hDesk;
+ TCHAR szName[8];
+ DWORD cbName;
+ BOOL bLocked;
+ hDesk=OpenInputDesktop(0,FALSE,DESKTOP_READOBJECTS);
+ if(hDesk==NULL) return TRUE;
+ bLocked=(!GetUserObjectInformation(hDesk,UOI_NAME,szName,SIZEOF(szName),&cbName) || lstrcmpi(szName,_T("default"))!=0);
+ CloseDesktop(hDesk);
+ return bLocked;
+}
+
+#if !defined(_UNICODE)
+static void Win9x_TerminateExplorer(void)
+{
+ HANDLE hProcess;
+ DWORD idProcess;
+ if(GetWindowThreadProcessId(GetDesktopWindow(),&idProcess)) {
+ hProcess=OpenProcess(PROCESS_TERMINATE,FALSE,idProcess);
+ if(hProcess!=NULL) {
+ TerminateProcess(hProcess,0);
+ CloseHandle(hProcess);
+ }
+ }
+}
+#endif
+
+/************************* Workers ************************************/
+
+static BOOL IsShutdownTypeEnabled(BYTE shutdownType)
+{
+ BOOL bReturn=FALSE;
+ switch(shutdownType) {
+ case SDSDT_HIBERNATE:
+ case SDSDT_STANDBY:
+ { HMODULE hPowerDLL=LoadLibraryA("POWRPROF"); /* all ascii */
+ if(hPowerDLL!=NULL) {
+ BOOLEAN (STDAPICALLTYPE *pfnIsPwrModeAllowed)(void);
+ *(PROC*)&pfnIsPwrModeAllowed=GetProcAddress(hPowerDLL,(shutdownType==SDSDT_HIBERNATE)?"IsPwrHibernateAllowed":"IsPwrSuspendAllowed");
+ if(pfnIsPwrModeAllowed) bReturn=pfnIsPwrModeAllowed()!=0;
+ FreeLibrary(hPowerDLL);
+ }
+ }
+ /* test privilege */
+ if(bReturn && IsWinVerNT()) {
+ bReturn=WinNT_SetPrivilege(SE_SHUTDOWN_NAME,TRUE);
+ if(bReturn) WinNT_SetPrivilege(SE_SHUTDOWN_NAME,FALSE);
+ }
+ break;
+ case SDSDT_LOGOFF:
+ { HKEY hKey;
+ DWORD dwSetting,dwSize;
+ /* NoLogOff is BINARY on Win9x/ME and DWORD on Win2000+ */
+ bReturn=TRUE;
+ if(RegOpenKeyEx(HKEY_CURRENT_USER,_T("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"),0,KEY_QUERY_VALUE,&hKey)==ERROR_SUCCESS) {
+ dwSize=sizeof(dwSetting);
+ if(RegQueryValueEx(hKey,_T("NoLogOff"),0,NULL,(void*)&dwSetting,&dwSize)==ERROR_SUCCESS)
+ if(dwSetting) bReturn=FALSE;
+ RegCloseKey(hKey);
+ }
+ }
+ break;
+ case SDSDT_LOCKWORKSTATION:
+ { void (WINAPI *pfnLockWorkStation)(void);
+ *(PROC*)&pfnLockWorkStation=GetProcAddress(GetModuleHandleA("USER32"),"LockWorkStation");
+ if(pfnLockWorkStation) {
+ HKEY hKey;
+ DWORD dwSize,dwSetting;
+ /* DisableLockWorkstation is DWORD on Win2000+ */
+ bReturn=TRUE;
+ if(RegOpenKeyEx(HKEY_CURRENT_USER,_T("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"),0,KEY_QUERY_VALUE,&hKey)==ERROR_SUCCESS) {
+ dwSize=sizeof(dwSetting);
+ if(!RegQueryValueEx(hKey,_T("DisableLockWorkstation"),0,NULL,(void*)&dwSetting,&dwSize))
+ if(dwSetting) bReturn=FALSE;
+ RegCloseKey(hKey);
+ }
+ }
+ else if(IsWinVerNT()) /* for WinNT4 */
+ bReturn=SearchPath(NULL,_T("LOGIN.SCR"),NULL,0,NULL,NULL)!=0;
+ }
+ break;
+ case SDSDT_CLOSERASCONNECTIONS:
+ /* check if RAS installed/available */
+ bReturn=SearchPath(NULL,_T("RASAPI32"),_T(".DLL"),0,NULL,NULL)!=0;
+ break;
+ case SDSDT_SETMIRANDAOFFLINE:
+ case SDSDT_CLOSEMIRANDA:
+ bReturn=TRUE; /* always possible */
+ break;
+ case SDSDT_REBOOT:
+ case SDSDT_SHUTDOWN:
+ /* test privileges */
+ if(IsWinVerNT()) {
+ bReturn=WinNT_SetPrivilege(SE_SHUTDOWN_NAME,TRUE);
+ if(bReturn) WinNT_SetPrivilege(SE_SHUTDOWN_NAME,FALSE);
+ }
+ else bReturn=TRUE;
+ break;
+ }
+ return bReturn;
+}
+
+static DWORD ShutdownNow(BYTE shutdownType)
+{
+ DWORD dwErrCode=ERROR_SUCCESS;
+ switch(shutdownType) {
+ case SDSDT_CLOSEMIRANDA:
+ if(!Miranda_Terminated()) {
+ /* waiting for short until ready (but not too long...) */
+ DWORD dwLastTickCount=GetTickCount();
+ while(!CallService(MS_SYSTEM_OKTOEXIT,0,0)) {
+ /* infinite loop protection (max 5 sec) */
+ if(GetTickCount()-dwLastTickCount>=5000) { /* wraparound works */
+ OutputDebugStringA("Timeout (5 sec)\n"); /* tell others, all ascii */
+ break;
+ }
+ SleepEx(1000,TRUE);
+ if(Miranda_Terminated()) break; /* someone else did it */
+ OutputDebugStringA("Not ready to exit. Waiting...\n"); /* tell others, all ascii */
+ }
+ /* shutdown service must be called from main thread anyway */
+ if(!DestroyWindow((HWND)CallService(MS_CLUI_GETHWND,0,0)))
+ dwErrCode=GetLastError();
+ }
+ break;
+ case SDSDT_SETMIRANDAOFFLINE:
+ /* set global status mode to offline (is remembered by Miranda on exit) */
+ CallService(MS_CLIST_SETSTATUSMODE,(WPARAM)ID_STATUS_OFFLINE,(LPARAM)NULL);
+ break;
+ case SDSDT_STANDBY:
+ case SDSDT_HIBERNATE:
+ WinNT_SetPrivilege(SE_SHUTDOWN_NAME,TRUE);
+ if(!SetSystemPowerState(shutdownType==SDSDT_STANDBY,TRUE))
+ dwErrCode=GetLastError();
+ WinNT_SetPrivilege(SE_SHUTDOWN_NAME,FALSE);
+ break;
+ case SDSDT_LOCKWORKSTATION:
+ { BOOL (WINAPI *pfnLockWorkStation)(void);
+ *(PROC*)&pfnLockWorkStation=GetProcAddress(GetModuleHandleA("USER32"),"LockWorkStation");
+ if(pfnLockWorkStation!=NULL) /* Win2000+ */
+ if(!pfnLockWorkStation() && !WinNT_IsWorkStationLocked())
+ dwErrCode=GetLastError();
+ else if(IsWinVerNT()) { /* WinNT4 */
+ HKEY hKey;
+ /* start LOGON.SCR screensaver (locks workstation on NT4) */
+ if(!SearchPath(NULL,_T("LOGIN.SCR"),NULL,0,NULL,NULL)) {
+ if(RegCreateKeyEx(HKEY_CURRENT_USER,_T("Control Panel\\Desktop"),0,NULL,REG_OPTION_VOLATILE,KEY_QUERY_VALUE|KEY_SET_VALUE,NULL,&hKey,NULL)==ERROR_SUCCESS) {
+ TCHAR szScreenSaveActive[2],szScreenSaverIsSecure[2],szScrnsaveExe[MAX_PATH];
+ DWORD dwSize;
+ /* save old settings */
+ dwSize=sizeof(szScreenSaveActive); /* in bytes */
+ ZeroMemory(&szScreenSaveActive,dwSize);
+ RegQueryValueEx(hKey,_T("ScreenSaveActive"),0,NULL,(void*)szScreenSaveActive,&dwSize);
+ dwSize=sizeof(szScreenSaverIsSecure); /* in bytes */
+ ZeroMemory(&szScreenSaverIsSecure, dwSize);
+ RegQueryValueEx(hKey,_T("ScreenSaverIsSecure"),0,NULL,(void*)szScreenSaverIsSecure,&dwSize);
+ dwSize=sizeof(szScrnsaveExe); /* in bytes */
+ ZeroMemory(&szScrnsaveExe,dwSize);
+ RegQueryValueEx(hKey,_T("SCRNSAVE.EXE"),0,NULL,(void*)szScrnsaveExe,&dwSize);
+ /* set LOGON.SCR data */
+ if(!RegSetValueEx(hKey,_T("ScreenSaveActive"),0,REG_SZ,(void*)_T("1"),2) &&
+ !RegSetValueEx(hKey,_T("ScreenSaverIsSecure"),0,REG_SZ,(void*)"1",2) &&
+ !RegSetValueEx(hKey,_T("SCRNSAVE.EXE"),0,REG_SZ,(void*)_T("LOGIN.SCR"),10))
+ SendMessage(GetForegroundWindow(),WM_SYSCOMMAND,SC_SCREENSAVE,0);
+ else dwErrCode=GetLastError();
+ /* restore old settings */
+ RegSetValueEx(hKey,_T("ScreenSaveActive"),0,REG_SZ,(void*)szScreenSaveActive,(lstrlen(szScreenSaveActive)+1)*sizeof(TCHAR));
+ RegSetValueEx(hKey,_T("ScreenSaverIsSecure"),0,REG_SZ,(void*)szScreenSaverIsSecure,(lstrlen(szScreenSaverIsSecure)+1)*sizeof(TCHAR));
+ RegSetValueEx(hKey,_T("SCRNSAVE.EXE"),0,REG_SZ,(void*)szScrnsaveExe,(lstrlen(szScrnsaveExe)+1)*sizeof(TCHAR));
+ RegCloseKey(hKey);
+ } else dwErrCode=GetLastError();
+ } else dwErrCode=GetLastError();
+ } else dwErrCode=GetLastError();
+ }
+ break;
+ case SDSDT_CLOSERASCONNECTIONS:
+ ShutdownNow(SDSDT_SETMIRANDAOFFLINE); /* set Miranda offline */
+ /* hang up all ras connections */
+ { HMODULE hRasApiDLL=LoadLibrary(_T("RASAPI32")); /* all ascii */
+ if(hRasApiDLL!=NULL) {
+ DWORD (APIENTRY *pfnRasEnumConnections)(RASCONN*,DWORD*,DWORD*);
+ DWORD (APIENTRY *pfnRasHangUp)(HRASCONN);
+ DWORD (APIENTRY *pfnRasGetConnectStatus)(HRASCONN,RASCONNSTATUS*);
+ #if defined(_UNICODE)
+ *(PROC*)&pfnRasEnumConnections=GetProcAddress(hRasApiDLL,"RasEnumConnectionsW");
+ *(PROC*)&pfnRasHangUp=GetProcAddress(hRasApiDLL,"RasHangUpW");
+ *(PROC*)&pfnRasGetConnectStatus=GetProcAddress(hRasApiDLL,"RasGetConnectStatusW");
+ #else
+ *(PROC*)&pfnRasEnumConnections=GetProcAddress(hRasApiDLL,"RasEnumConnectionsA");
+ *(PROC*)&pfnRasHangUp=GetProcAddress(hRasApiDLL,"RasHangUpA");
+ *(PROC*)&pfnRasGetConnectStatus=GetProcAddress(hRasApiDLL,"RasGetConnectStatusA");
+ #endif
+ if(pfnRasEnumConnections && pfnRasGetConnectStatus && pfnRasHangUp) {
+ RASCONN *paConn;
+ RASCONN *paConnBuf;
+ DWORD dwConnSize,dwConnItems,dwRetries;
+ RASCONNSTATUS rcs;
+ DWORD dw,dwLastTickCount;
+
+ dwConnSize=sizeof(RASCONN);
+ dwConnItems=0;
+ paConn=(RASCONN*)mir_alloc(dwConnSize);
+ dwErrCode=ERROR_NOT_ENOUGH_MEMORY;
+ if(paConn!=NULL)
+ for(dwRetries=5;dwRetries!=0;dwRetries--) { /* prevent infinite loop (rare) */
+ ZeroMemory(paConn,dwConnSize);
+ paConn[0].dwSize=sizeof(RASCONN);
+ dwErrCode=pfnRasEnumConnections(paConn,&dwConnSize,&dwConnItems);
+ if(dwErrCode!=ERROR_BUFFER_TOO_SMALL) break;
+ paConnBuf=(RASCONN*)mir_realloc(paConn,dwConnSize);
+ if(paConnBuf!=NULL) {
+ mir_free(paConn);
+ paConn=NULL;
+ dwErrCode=ERROR_NOT_ENOUGH_MEMORY;
+ break;
+ }
+ paConn=paConnBuf;
+ }
+ if(dwErrCode==ERROR_SUCCESS || dwErrCode==ERROR_BUFFER_TOO_SMALL) {
+ for(dw=0;dw<dwConnItems;++dw) {
+ if(dwErrCode) {
+ if(pfnRasHangUp(paConn[dw].hrasconn))
+ paConn[dw].hrasconn=NULL; /* do not wait for on error */
+ } else {
+ dwErrCode=pfnRasHangUp(paConn[dw].hrasconn);
+ if(!dwErrCode) paConn[dw].hrasconn=NULL; /* do not wait for on error */
+ }
+ }
+ /* RAS does not allow to quit directly after HangUp (see docs) */
+ dwLastTickCount=GetTickCount();
+ ZeroMemory(&rcs,sizeof(RASCONNSTATUS));
+ rcs.dwSize=sizeof(RASCONNSTATUS);
+ for(dw=0;dw<dwConnItems;++dw)
+ if(paConn[dw].hrasconn!=NULL)
+ while(pfnRasGetConnectStatus(paConn[dw].hrasconn, &rcs)!=ERROR_INVALID_HANDLE) {
+ Sleep(0); /* give rest of time silce to other threads with equal priority */
+ /* infinite loop protection (3000ms defined in docs) */
+ dwRetries=GetTickCount();
+ if(dwRetries-dwLastTickCount>3000) break; /* wraparound works */
+ }
+ }
+ mir_free(paConn); /* does NULL check */
+ } else dwErrCode=GetLastError();
+ FreeLibrary(hRasApiDLL);
+ } else dwErrCode=GetLastError();
+ }
+ /* set Miranda to offline again, to remain offline with reconnection plugins */
+ ShutdownNow(SDSDT_SETMIRANDAOFFLINE);
+ break;
+ case SDSDT_REBOOT:
+ case SDSDT_SHUTDOWN:
+ if(GetSystemMetrics(SM_SHUTTINGDOWN)) { /* Win2000+, 0 on error */
+ dwErrCode=ERROR_SHUTDOWN_IN_PROGRESS;
+ break;
+ }
+ /* WinNT4/2000/XP */
+ { BOOL (WINAPI *pfnInitiateSystemShutdownEx)(const TCHAR*,const TCHAR*,DWORD,BOOL,BOOL,DWORD);
+ BOOL (WINAPI *pfnInitiateSystemShutdown)(const TCHAR*,const TCHAR*,DWORD,BOOL,BOOL);
+ #if defined(_UNICODE)
+ *(PROC*)&pfnInitiateSystemShutdownEx=GetProcAddress(GetModuleHandleA("ADVAPI32"),"InitiateSystemShutdownExW");
+ *(PROC*)&pfnInitiateSystemShutdown=GetProcAddress(GetModuleHandleA("ADVAPI32"),"InitiateSystemShutdownW");
+ #else
+ *(PROC*)&pfnInitiateSystemShutdownEx=GetProcAddress(GetModuleHandleA("ADVAPI32"),"InitiateSystemShutdownExA");
+ *(PROC*)&pfnInitiateSystemShutdown=GetProcAddress(GetModuleHandleA("ADVAPI32"),"InitiateSystemShutdownA");
+ #endif
+ if(pfnInitiateSystemShutdownEx!=NULL || pfnInitiateSystemShutdown!=NULL) {
+ WinNT_SetPrivilege(SE_SHUTDOWN_NAME,TRUE);
+
+ /* does not send out WM_ENDSESSION messages, so we do it manually to
+ * give the applications the chance to save their data */
+ WinNT_SetPrivilege(SE_TCB_NAME,TRUE); /* for BSM_ALLDESKTOPS */
+ BroadcastEndSession(BSM_APPLICATIONS|BSM_ALLDESKTOPS,ENDSESSION_CLOSEAPP); /* app should close itself */
+ WinNT_SetPrivilege(SE_TCB_NAME,FALSE);
+
+ if(pfnInitiateSystemShutdownEx!=NULL) {
+ if(!pfnInitiateSystemShutdownEx(NULL,TranslateT("AutoShutdown"),0,TRUE,shutdownType==SDSDT_REBOOT,SHTDN_REASON_MAJOR_OTHER|SHTDN_REASON_MINOR_OTHER|SHTDN_REASON_FLAG_PLANNED))
+ dwErrCode=GetLastError();
+ } else if(!pfnInitiateSystemShutdown(NULL,TranslateT("AutoShutdown"),0,TRUE,shutdownType==SDSDT_REBOOT))
+ dwErrCode=GetLastError();
+
+ /* cleanly close Miranda */
+ if(!dwErrCode) ShutdownNow(SDSDT_CLOSEMIRANDA);
+ break;
+ }
+ }
+ /* fall through for Win9x */
+ case SDSDT_LOGOFF:
+ { UINT flags;
+ switch(shutdownType) {
+ case SDSDT_LOGOFF: flags=EWX_LOGOFF; break;
+ case SDSDT_REBOOT: flags=EWX_REBOOT; break;
+ default: flags=EWX_SHUTDOWN|EWX_POWEROFF;
+ }
+ if(shutdownType==SDSDT_LOGOFF && IsWinVer2000Plus() && !WinNT_IsWorkStationLocked())
+ flags|=EWX_FORCEIFHUNG; /* only considered for WM_ENDSESSION messages */
+ else flags|=EWX_FORCE; /* must be used when workstation locked */
+
+ if(flags&EWX_FORCE) {
+ /* EWX_FORCE does not send out WM_ENDSESSION messages, so we do it
+ * manually to give the applications the chance to save their data */
+ BroadcastEndSession(BSM_APPLICATIONS,(shutdownType==SDSDT_LOGOFF)?ENDSESSION_LOGOFF:0);
+
+ /* Windows Me/98/95 (msdn): Because of the design of the shell,
+ * calling ExitWindowsEx with EWX_FORCE fails to completely log off
+ * the user (the system terminates the applications and displays the
+ * Enter Windows Password dialog box, however, the user's desktop remains.)
+ * To log off the user forcibly, terminate the Explorer process before calling
+ * ExitWindowsEx with EWX_LOGOFF and EWX_FORCE. */
+ #if !defined(_UNICODE)
+ if(shutdownType==SDSDT_LOGOFF && !IsWinVerNT()) Win9x_TerminateExplorer();
+ #endif
+ }
+ if(!ExitWindowsEx(flags,SHTDN_REASON_MAJOR_OTHER|SHTDN_REASON_MINOR_OTHER|SHTDN_REASON_FLAG_PLANNED))
+ dwErrCode=GetLastError();
+ /* cleanly close Miranda */
+ if(!dwErrCode) ShutdownNow(SDSDT_CLOSEMIRANDA);
+ }
+ break;
+ }
+ return dwErrCode;
+}
+
+/************************* Shutdown Dialog ****************************/
+
+#define M_START_SHUTDOWN (WM_APP+111)
+#define M_UPDATE_COUNTDOWN (WM_APP+112)
+static BOOL CALLBACK ShutdownDlgProc(HWND hwndDlg,UINT msg,WPARAM wParam,LPARAM lParam)
+{
+ BYTE shutdownType=(BYTE)GetWindowLong(hwndDlg,DWL_USER);
+ WORD countdown=(WORD)GetWindowLong(GetDlgItem(hwndDlg,IDC_TEXT_HEADER),GWL_USERDATA);
+ static BOOL (WINAPI *pfnLockSetForegroundWindow)(UINT);
+
+ switch(msg) {
+ case WM_INITDIALOG:
+ hwndShutdownDlg=hwndDlg;
+ SetWindowLong(hwndDlg,DWL_USER,(LONG)lParam);
+ TranslateDialogDefault(hwndDlg);
+
+ if(lParam==SDSDT_SHUTDOWN || lParam==SDSDT_REBOOT || lParam==SDSDT_LOGOFF)
+ ShowWindow(GetDlgItem(hwndDlg,IDC_TEXT_UNSAVEDWARNING),SW_SHOW);
+ SendDlgItemMessage(hwndDlg,IDC_ICON_HEADER,STM_SETIMAGE,IMAGE_ICON,(LPARAM)IcoLib_GetIcon("AutoShutdown_Header"));
+ { HFONT hBoldFont;
+ LOGFONT lf;
+ if(GetObject((HFONT)SendDlgItemMessage(hwndDlg,IDC_TEXT_HEADER,WM_GETFONT,0,0),sizeof(lf),&lf)) {
+ lf.lfWeight=FW_BOLD;
+ hBoldFont=CreateFontIndirect(&lf);
+ }
+ else hBoldFont=NULL;
+ SendDlgItemMessage(hwndDlg,IDC_TEXT_HEADER,WM_SETFONT,(WPARAM)hBoldFont,FALSE);
+ SetWindowLong(GetDlgItem(hwndDlg,IDC_TEXT_HEADER),GWL_USERDATA,(LONG)hBoldFont);
+ }
+ { WORD countdown=DBGetContactSettingWord(NULL,"AutoShutdown","ConfirmDlgCountdown",SETTING_CONFIRMDLGCOUNTDOWN_DEFAULT);
+ if(countdown<3) countdown=SETTING_CONFIRMDLGCOUNTDOWN_DEFAULT;
+ SetWindowLong(GetDlgItem(hwndDlg,IDC_TEXT_HEADER),GWL_USERDATA,countdown);
+ SendMessage(hwndDlg,M_UPDATE_COUNTDOWN,0,countdown);
+ }
+ SkinPlaySound("AutoShutdown_Countdown");
+ if(!SetTimer(hwndDlg,1,1000,NULL)) PostMessage(hwndDlg,M_START_SHUTDOWN,0,0);
+ Utils_RestoreWindowPositionNoSize(hwndDlg,NULL,"AutoShutdown","ConfirmDlg_");
+
+ /* disallow foreground window changes (WinMe/2000+) */
+ SetForegroundWindow(hwndDlg);
+ *(PROC*)&pfnLockSetForegroundWindow=GetProcAddress(GetModuleHandleA("USER32"),"LockSetForegroundWindow");
+ if(pfnLockSetForegroundWindow!=NULL)
+ pfnLockSetForegroundWindow(LSFW_LOCK);
+
+ SendMessage(hwndDlg,WM_NEXTDLGCTL,(WPARAM)GetDlgItem(hwndDlg,IDCANCEL),TRUE);
+ return FALSE; /* focus set on cancel */
+ case WM_DESTROY:
+ { HFONT hFont;
+ HICON hIcon;
+ hwndShutdownDlg=NULL;
+ ShowWindow(hwndDlg,SW_HIDE);
+ /* reallow foreground window changes (WinMe/2000+) */
+ if(pfnLockSetForegroundWindow) pfnLockSetForegroundWindow(LSFW_UNLOCK);
+ Utils_SaveWindowPosition(hwndDlg,NULL,"AutoShutdown","ConfirmDlg_");
+ hIcon=(HICON)SendDlgItemMessage(hwndDlg,IDC_ICON_HEADER,STM_SETIMAGE,IMAGE_ICON,(LPARAM)NULL);
+ IcoLib_ReleaseIcon(hIcon); /* does NULL check */
+ hFont=(HFONT)SendDlgItemMessage(hwndDlg,IDC_TEXT_HEADER,WM_GETFONT,0,0);
+ SendDlgItemMessage(hwndDlg,IDC_TEXT_HEADER,WM_SETFONT,(WPARAM)NULL,FALSE); /* no return value */
+ if(hFont!=NULL) DeleteObject(hFont);
+ return TRUE;
+ }
+ case M_START_SHUTDOWN:
+ if(IsWindowEnabled(GetDlgItem(hwndDlg,IDC_BUTTON_SHUTDOWNNOW))) {
+ DWORD dwErrCode;
+ EnableWindow(GetDlgItem(hwndDlg,IDC_BUTTON_SHUTDOWNNOW),FALSE);
+ ShowWindow(hwndDlg,SW_HIDE); /* get rid of the dialog immediately */
+ dwErrCode=ShutdownNow(shutdownType);
+ if(dwErrCode!=ERROR_SUCCESS) {
+ char *pszErr;
+ pszErr=GetWinErrorDescription(dwErrCode);
+ ShowInfoMessage(NIIF_ERROR,Translate("Automatic Shutdown Error"),Translate("The shutdown process failed!\nReason: %s"),(pszErr!=NULL)?pszErr:Translate("Unknown"));
+ if(pszErr!=NULL) LocalFree(pszErr);
+ }
+ DestroyWindow(hwndDlg);
+ }
+ return TRUE;
+ case WM_TIMER:
+ if(countdown) {
+ --countdown;
+ SetWindowLong(GetDlgItem(hwndDlg,IDC_TEXT_HEADER),GWL_USERDATA,countdown);
+ if(countdown==27 || countdown==24 || countdown==21 || countdown==19 ||
+ countdown==17 || countdown==15 || countdown==13 || countdown==11 ||
+ countdown<=10)
+ SkinPlaySound("AutoShutdown_Countdown");
+ }
+ else KillTimer(hwndDlg,wParam); /* countdown finished */
+ PostMessage(hwndDlg,M_UPDATE_COUNTDOWN,0,countdown);
+ return TRUE;
+ case M_UPDATE_COUNTDOWN: /* lParam=(WORD)countdown */
+ { TCHAR szText[256];
+ TCHAR *desc[]={_T("Miranda IM is going to be automatically closed in %u second(s)."),
+ _T("All Miranda IM protocols are going to be set to offline in %u second(s)."),
+ _T("You will be logged off automatically in %u second(s)."),
+ _T("The computer will automatically be restarted in %u second(s)."),
+ _T("The computer will automatically be set to standby mode in %u second(s)."),
+ _T("The computer will automatically be set to hibernate mode in %u second(s)."),
+ _T("The workstation will automatically get locked in %u second(s)."),
+ _T("All dialup connections will be closed in %u second(s)."),
+ _T("The computer will automatically be shut down in %u second(s).")};
+ mir_sntprintf(szText,SIZEOF(szText),TranslateTS(desc[shutdownType-1]),lParam);
+ SetDlgItemText(hwndDlg,IDC_TEXT_HEADER,szText);
+ /* countdown finished */
+ if(!lParam) PostMessage(hwndDlg,M_START_SHUTDOWN,0,0);
+ return TRUE;
+ }
+ case WM_COMMAND:
+ switch(LOWORD(wParam)) {
+ case IDC_BUTTON_SHUTDOWNNOW:
+ KillTimer(hwndDlg,1);
+ SetWindowLong(GetDlgItem(hwndDlg,IDC_TEXT_HEADER),GWL_USERDATA,0);
+ SendMessage(hwndDlg,M_UPDATE_COUNTDOWN,0,(LONG)0);
+ PostMessage(hwndDlg,M_START_SHUTDOWN,0,0);
+ return TRUE;
+ case IDCANCEL: /* WM_CLOSE */
+ if(countdown) {
+ KillTimer(hwndDlg,1);
+ DestroyWindow(hwndDlg);
+ }
+ return TRUE;
+ }
+ break;
+ }
+ return FALSE;
+}
+
+/************************* Services ***********************************/
+
+int ServiceShutdown(WPARAM wParam,LPARAM lParam)
+{
+ /* passing 0 as wParam is only to be used internally, undocumented */
+ if(!wParam) wParam=DBGetContactSettingByte(NULL,"AutoShutdown","ShutdownType",SETTING_SHUTDOWNTYPE_DEFAULT);
+ if(!IsShutdownTypeEnabled((BYTE)wParam)) return 1; /* does shutdownType range check */
+ if((BOOL)lParam && hwndShutdownDlg!=NULL) return 2;
+
+ /* ask others if allowed */
+ if(NotifyEventHooks(hEventOkToShutdown,wParam,lParam)) {
+ OutputDebugStringA("automatic shutdown denied by event hook\n"); /* all ascii */
+ return 3;
+ }
+ /* tell others */
+ NotifyEventHooks(hEventShutdown,wParam,lParam);
+ /* show dialog */
+ if(lParam && DBGetContactSettingByte(NULL,"AutoShutdown","ShowConfirmDlg",SETTING_SHOWCONFIRMDLG_DEFAULT))
+ if(CreateDialogParam(hInst,MAKEINTRESOURCE(IDD_SHUTDOWNNOW),NULL,ShutdownDlgProc,(LPARAM)(BYTE)wParam)!=NULL)
+ return 0;
+ /* show error */
+ { DWORD dwErrCode;
+ dwErrCode=ShutdownNow((BYTE)wParam);
+ if(dwErrCode!=ERROR_SUCCESS) {
+ char *pszErr;
+ pszErr=GetWinErrorDescription(dwErrCode);
+ ShowInfoMessage(NIIF_ERROR,Translate("Automatic Shutdown Error"),Translate("Inititiating the shutdown process failed!\nReason: %s"),(pszErr!=NULL)?pszErr:Translate("Unknown"));
+ if(pszErr!=NULL) LocalFree(pszErr);
+ return 4;
+ }
+ }
+ return 0;
+}
+
+int ServiceIsTypeEnabled(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(lParam);
+ return IsShutdownTypeEnabled((BYTE)wParam); /* does shutdownType range check */
+}
+
+int ServiceGetTypeDescription(WPARAM wParam,LPARAM lParam)
+{
+ TCHAR *pszDesc;
+ const TCHAR *apszShort[]={_T("Close Miranda IM"),_T("Set Miranda IM offline"),_T("Log off user"),
+ _T("Restart computer"),_T("Shutdown computer"),_T("Standby mode"),_T("Hibernate mode"),
+ _T("Lock workstation"),_T("Hang up dialup connections"),_T("Close Miranda IM"),
+ _T("Set Miranda IM offline"),_T("Log off user"),_T("Restart computer"),_T("Shutdown computer"),
+ _T("Standby mode"),_T("Hibernate mode"),_T("Lock workstation"),_T("Hang up dialup connections")};
+ const TCHAR *apszLong[]={_T("Sets all Miranda IM protocols to offline and closes Miranda IM."),
+ _T("Sets all Miranda IM protocols to offline."),
+ _T("Logs the current Windows user off so that another user can log in."),
+ _T("Shuts down Windows and then restarts Windows."),
+ _T("Closes all running programs and shuts down Windows to a point at which it is safe to turn off the power."),
+ _T("Saves the current Windows session in memory and sets the system to suspend mode."),
+ _T("Saves the current Windows session on harddisc, so that the power can be turned off."),
+ _T("Locks the computer. To unlock the computer, you must log in."),
+ _T("Sets all protocols to offline and closes all RAS connections.")};
+ /* shutdownType range check */
+ if(!wParam || (BYTE)wParam>SDSDT_MAX) return (int)NULL;
+ /* select description */
+ pszDesc=(TCHAR*)((lParam&GSTDF_LONGDESC)?apszLong:apszShort)[wParam-1];
+ if(!(lParam&GSTDF_UNTRANSLATED)) pszDesc=TranslateTS(pszDesc);
+ /* convert as needed */
+ #if defined(_UNICODE)
+ if(!(lParam&GSTDF_UNICODE)) {
+ static char szConvBuf[128];
+ char *buf=u2a(pszDesc);
+ if(buf==NULL) return (int)NULL;
+ lstrcpynA(szConvBuf,buf,sizeof(szConvBuf));
+ mir_free(buf);
+ return (int)szConvBuf;
+ }
+ #else
+ if(lParam&GSTDF_UNICODE) {
+ static WCHAR szConvBuf[128];
+ WCHAR *buf=a2u(pszDesc);
+ if(buf==NULL) return (int)NULL;
+ lstrcpynW(szConvBuf,buf,SIZEOF(szConvBuf));
+ mir_free(buf);
+ return (int)szConvBuf;
+ }
+ #endif
+ return (int)pszDesc;
+}
+
+/************************* Misc ***************************************/
+
+void InitShutdownSvc(void)
+{
+ /* Shutdown Dialog */
+ hwndShutdownDlg=NULL;
+ SkinAddNewSoundBundled("AutoShutdown_Countdown",Translate("Alerts"),Translate("Automatic Shutdown Countdown"),"Sounds\\","countdown.wav");
+ /* Services */
+ hEventOkToShutdown=CreateHookableEvent(ME_AUTOSHUTDOWN_OKTOSHUTDOWN);
+ hEventShutdown=CreateHookableEvent(ME_AUTOSHUTDOWN_SHUTDOWN);
+ hServiceShutdown=CreateServiceFunction(MS_AUTOSHUTDOWN_SHUTDOWN,ServiceShutdown);
+ hServiceIsTypeEnabled=CreateServiceFunction(MS_AUTOSHUTDOWN_ISTYPEENABLED,ServiceIsTypeEnabled);
+ hServiceGetTypeDesc=CreateServiceFunction(MS_AUTOSHUTDOWN_GETTYPEDESCRIPTION,ServiceGetTypeDescription);
+}
+
+void UninitShutdownSvc(void)
+{
+ /* Shutdown Dialog */
+ if(hwndShutdownDlg!=NULL) DestroyWindow(hwndShutdownDlg);
+ /* Services */
+ DestroyServiceFunction(hServiceShutdown);
+ DestroyServiceFunction(hServiceIsTypeEnabled);
+ DestroyServiceFunction(hServiceGetTypeDesc);
+ DestroyHookableEvent(hEventOkToShutdown);
+ DestroyHookableEvent(hEventShutdown);
+}
diff --git a/plugins/AutoShutdown/shutdownsvc.h b/plugins/AutoShutdown/shutdownsvc.h
new file mode 100644
index 0000000000..412db18ee6
--- /dev/null
+++ b/plugins/AutoShutdown/shutdownsvc.h
@@ -0,0 +1,29 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+/* Services */
+int ServiceShutdown(WPARAM wParam,LPARAM lParam);
+int ServiceIsTypeEnabled(WPARAM wParam,LPARAM lParam);
+int ServiceGetTypeDescription(WPARAM wParam,LPARAM lParam);
+
+/* Misc */
+void InitShutdownSvc(void);
+void UninitShutdownSvc(void);
diff --git a/plugins/AutoShutdown/utils.c b/plugins/AutoShutdown/utils.c
new file mode 100644
index 0000000000..b9bbddbc01
--- /dev/null
+++ b/plugins/AutoShutdown/utils.c
@@ -0,0 +1,458 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include "common.h"
+
+/************************* String *********************************/
+
+// mir_free() the return value
+#if !defined(_UNICODE)
+WCHAR* a2u(const char *pszAnsi)
+{
+ int codepage,cch;
+ WCHAR *psz;
+
+ if(pszAnsi==NULL) return NULL;
+ codepage=CallService(MS_LANGPACK_GETCODEPAGE,0,0);
+ cch=MultiByteToWideChar(codepage,0,pszAnsi,-1,NULL,0);
+ if(!cch) return NULL;
+
+ psz=(WCHAR*)mir_alloc(cch*sizeof(WCHAR));
+ if(psz!=NULL && !MultiByteToWideChar(codepage,0,pszAnsi,-1,psz,cch)) {
+ mir_free(psz);
+ return NULL;
+ }
+ return psz;
+}
+#endif
+
+// mir_free() the return value
+#if defined(_UNICODE)
+char* u2a(const WCHAR *pszUnicode)
+{
+ int codepage,cch;
+ char *psz;
+ DWORD flags;
+
+ if(pszUnicode==NULL) return NULL;
+ codepage=CallService(MS_LANGPACK_GETCODEPAGE,0,0);
+ /* without WC_COMPOSITECHECK some characters might get out strange (see MS blog) */
+ cch=WideCharToMultiByte(codepage,flags=WC_COMPOSITECHECK,pszUnicode,-1,NULL,0,NULL,NULL);
+ if(!cch) cch=WideCharToMultiByte(codepage,flags=0,pszUnicode,-1,NULL,0,NULL,NULL);
+ if(!cch) return NULL;
+
+ psz=(char*)mir_alloc(cch);
+ if(psz!=NULL && !WideCharToMultiByte(codepage,flags,pszUnicode,-1,psz,cch,NULL,NULL)){
+ mir_free(psz);
+ return NULL;
+ }
+ return psz;
+}
+#endif
+
+void TrimString(TCHAR *pszStr)
+{
+ int i;
+ TCHAR *psz,szChars[]=_T(" \r\n\t");
+ for(i=0;i<SIZEOF(szChars);++i) {
+ /* trim end */
+ psz=&pszStr[lstrlen(pszStr)-1];
+ while(pszStr[0] && *psz==szChars[i]) {
+ *psz=0;
+ psz=CharPrev(pszStr,psz);
+ }
+ /* trim beginning */
+ for(psz=pszStr;(*psz && *psz==szChars[i]);psz=CharNext(psz));
+ MoveMemory(pszStr,psz,(lstrlen(psz)+1)*sizeof(TCHAR));
+ }
+}
+
+/************************* Error Output ***************************/
+
+static void MessageBoxIndirectFree(MSGBOXPARAMSA *mbp)
+{
+ MessageBoxIndirectA(mbp);
+ mir_free((char*)mbp->lpszCaption); /* does NULL check */
+ mir_free((char*)mbp->lpszText); /* does NULL check */
+ mir_free(mbp);
+}
+
+void ShowInfoMessage(BYTE flags,const char *pszTitle,const char *pszTextFmt,...)
+{
+ char szText[256]; /* max for systray */
+ MSGBOXPARAMSA *mbp;
+
+ va_list va;
+ va_start(va,pszTextFmt);
+ mir_vsnprintf(szText,SIZEOF(szText),pszTextFmt,va);
+ va_end(va);
+
+ if(ServiceExists(MS_CLIST_SYSTRAY_NOTIFY)) {
+ MIRANDASYSTRAYNOTIFY msn;
+ msn.cbSize=sizeof(msn);
+ msn.szProto=NULL;
+ msn.szInfoTitle=(char*)pszTitle;
+ msn.szInfo=(char*)szText;
+ msn.uTimeout=30000; /* max timeout */
+ msn.dwInfoFlags=flags;
+ if(!CallServiceSync(MS_CLIST_SYSTRAY_NOTIFY,0,(LPARAM)&msn))
+ return; /* success */
+ }
+
+ mbp=(MSGBOXPARAMSA*)mir_calloc(sizeof(*mbp));
+ if(mbp==NULL) return;
+ mbp->cbSize=sizeof(*mbp);
+ mbp->lpszCaption=mir_strdup(pszTitle);
+ mbp->lpszText=mir_strdup(szText);
+ mbp->dwStyle=MB_OK|MB_SETFOREGROUND|MB_TASKMODAL;
+ mbp->dwLanguageId=LANGIDFROMLCID((LCID)CallService(MS_LANGPACK_GETLOCALE,0,0));
+ switch(flags&NIIF_ICON_MASK) {
+ case NIIF_INFO: mbp->dwStyle|=MB_ICONINFORMATION; break;
+ case NIIF_WARNING: mbp->dwStyle|=MB_ICONWARNING; break;
+ case NIIF_ERROR: mbp->dwStyle|=MB_ICONERROR;
+ }
+ mir_forkthread(MessageBoxIndirectFree,mbp);
+}
+
+// LocalFree() the return value
+char* GetWinErrorDescription(DWORD dwLastError)
+{
+ char *buf=NULL;
+ DWORD flags=FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM;
+ if(!FormatMessageA(flags,NULL,dwLastError,LANGIDFROMLCID((LCID)CallService(MS_LANGPACK_GETLOCALE,0,0)),(char*)&buf,0,NULL))
+ if(GetLastError()==ERROR_RESOURCE_LANG_NOT_FOUND)
+ FormatMessageA(flags,NULL,dwLastError,0,(char*)&buf,0,NULL);
+ return buf;
+}
+
+/************************* Time ***********************************/
+
+BOOL SystemTimeToTimeStamp(SYSTEMTIME *st,time_t *timestamp)
+{
+ struct tm ts;
+ ts.tm_isdst=-1; /* daylight saving time (-1=compute) */
+ ts.tm_sec=st->wSecond; /* 0-59 */
+ ts.tm_min=st->wMinute; /* 0-59 */
+ ts.tm_hour=st->wHour; /* 0-23 */
+ ts.tm_mday=st->wDay; /* 1-31 */
+ ts.tm_wday=st->wDayOfWeek; /* 0-6 (Sun-Sat) */
+ ts.tm_mon=st->wMonth-1; /* 0-11 (Jan-Dec) */
+ ts.tm_year=st->wYear-1900; /* current year minus 1900 */
+ ts.tm_yday=0; /* 0-365 (Jan1=0) */
+ *timestamp=mktime(&ts);
+ return (*timestamp!=-1);
+}
+
+BOOL TimeStampToSystemTime(time_t timestamp,SYSTEMTIME *st)
+{
+ struct tm *ts;
+ ts=localtime(&timestamp); /* statically alloced, local time correction */
+ if(ts==NULL) return FALSE;
+ st->wMilliseconds=0; /* 0-999 (not given in tm) */
+ st->wSecond=(WORD)ts->tm_sec; /* 0-59 */
+ st->wMinute=(WORD)ts->tm_min; /* 0-59 */
+ st->wHour=(WORD)ts->tm_hour; /* 0-23 */
+ st->wDay=(WORD)ts->tm_mday; /* 1-31 */
+ st->wDayOfWeek=(WORD)ts->tm_wday; /* 0-6 (Sun-Sat) */
+ st->wMonth=(WORD)(ts->tm_mon+1); /* 1-12 (Jan-Dec) */
+ st->wYear=(WORD)(ts->tm_year+1900); /* 1601-30827 */
+ return TRUE;
+}
+
+BOOL GetFormatedCountdown(TCHAR *pszOut,int nSize,time_t countdown)
+{
+ static BOOL fInited=FALSE;
+ static int (WINAPI *pfnStrFromTimeInterval)(TCHAR*,UINT,DWORD,int);
+ #if defined(_UNICODE)
+ static int (WINAPI *pfnGetDurationFormat)(LCID,DWORD,const SYSTEMTIME*,double,WCHAR*,WCHAR*,int);
+ #endif
+ /* Init */
+ if(!fInited) {
+ #if defined(_UNICODE)
+ *(PROC*)&pfnGetDurationFormat=GetProcAddress(GetModuleHandleA("KERNEL32"),"GetDurationFormat");
+ if(pfnGetDurationFormat==NULL) {
+ #endif
+ HMODULE hShlwDLL=LoadLibraryA("SHLWAPI"); /* all ascii */
+ #if defined(_UNICODE)
+ *(PROC*)&pfnStrFromTimeInterval=GetProcAddress(hShlwDLL,"StrFromTimeIntervalW");
+ #else
+ *(PROC*)&pfnStrFromTimeInterval=GetProcAddress(hShlwDLL,"StrFromTimeIntervalA");
+ #endif
+ #if defined(_UNICODE)
+ }
+ #endif
+ fInited=TRUE;
+ }
+ /* WinVista */
+ #if defined(_UNICODE)
+ if(pfnGetDurationFormat!=NULL) {
+ SYSTEMTIME st;
+ LCID locale;
+ locale=(LCID)CallService(MS_LANGPACK_GETLOCALE,0,0);
+ if(TimeStampToSystemTime(countdown,&st))
+ if(pfnGetDurationFormat(locale,0,&st,0,NULL,pszOut,nSize))
+ return TRUE;
+ return FALSE;
+ }
+ #endif
+ /* Win9x/NT/XP */
+ if(pfnStrFromTimeInterval!=NULL)
+ return pfnStrFromTimeInterval(pszOut,nSize,(countdown>(MAXDWORD/1000))?MAXDWORD:(countdown*1000),10)!=0;
+ return FALSE;
+}
+
+BOOL GetFormatedDateTime(TCHAR *pszOut,int nSize,time_t timestamp,BOOL fShowDateEvenToday)
+{
+ SYSTEMTIME st,stNow;
+ LCID locale;
+ locale=(LCID)CallService(MS_LANGPACK_GETLOCALE,0,0);
+ GetLocalTime(&stNow);
+ TimeStampToSystemTime(timestamp,&st);
+ /* today: no need to show the date */
+ if(!fShowDateEvenToday && st.wDay==stNow.wDay && st.wMonth==stNow.wMonth && st.wYear==stNow.wYear)
+ return GetTimeFormat(locale,((st.wSecond==0)?TIME_NOSECONDS:0)|TIME_FORCE24HOURFORMAT,&st,NULL,pszOut,nSize)!=0;
+ /* show both date and time */
+ { TCHAR szDate[128],szTime[128];
+ if(!GetTimeFormat(locale,((st.wSecond==0)?TIME_NOSECONDS:0)|TIME_FORCE24HOURFORMAT,&st,NULL,szTime,SIZEOF(szTime)))
+ return FALSE;
+ if(!GetDateFormat(locale,DATE_SHORTDATE,&st,NULL,szDate,SIZEOF(szDate)))
+ return FALSE;
+ mir_sntprintf(pszOut,nSize,_T("%s %s"),szTime,szDate);
+ return TRUE;
+ }
+}
+
+/************************* Fonts & Colors *************************/
+
+int FontService_RegisterFont(const char *pszDbModule,const char *pszDbName,const TCHAR *pszSection,const TCHAR *pszDescription,int position,BOOL bAllowEffects,LOGFONT *plfDefault,COLORREF clrDefault)
+{
+ FontIDT fid;
+ ZeroMemory(&fid,sizeof(fid));
+ fid.cbSize=sizeof(fid);
+ lstrcpynA(fid.dbSettingsGroup,pszDbModule,sizeof(fid.dbSettingsGroup)); /* buffer safe */
+ lstrcpynA(fid.prefix,pszDbName,sizeof(fid.prefix)); /* buffer safe */
+ lstrcpyn(fid.group,pszSection,SIZEOF(fid.group)); /* buffer safe */
+ lstrcpyn(fid.name,pszDescription,SIZEOF(fid.name)); /* buffer safe */
+ fid.flags=FIDF_ALLOWREREGISTER;
+ if(bAllowEffects) fid.flags|=FIDF_ALLOWEFFECTS;
+ fid.order=position;
+ if(plfDefault!=NULL) {
+ fid.flags|=FIDF_DEFAULTVALID;
+ fid.deffontsettings.colour=clrDefault;
+ fid.deffontsettings.size=(char)plfDefault->lfHeight;
+ if(plfDefault->lfItalic) fid.deffontsettings.style|=DBFONTF_ITALIC;
+ if(plfDefault->lfWeight!=FW_NORMAL) fid.deffontsettings.style|=DBFONTF_BOLD;
+ if(plfDefault->lfUnderline) fid.deffontsettings.style|=DBFONTF_UNDERLINE;
+ if(plfDefault->lfStrikeOut) fid.deffontsettings.style|=DBFONTF_STRIKEOUT;
+ fid.deffontsettings.charset=plfDefault->lfCharSet;
+ lstrcpyn(fid.deffontsettings.szFace,plfDefault->lfFaceName,SIZEOF(fid.deffontsettings.szFace)); /* buffer safe */
+ }
+ return CallService(MS_FONT_REGISTERT,(WPARAM)&fid,(LPARAM)&fid);
+}
+
+int FontService_GetFont(const TCHAR *pszSection,const TCHAR *pszDescription,COLORREF *pclr,LOGFONT *plf)
+{
+ FontIDT fid;
+ fid.cbSize=sizeof(fid);
+ lstrcpyn(fid.group,pszSection,SIZEOF(fid.group)); /* buffer sfae */
+ lstrcpyn(fid.name,pszDescription,SIZEOF(fid.name)); /* buffer safe */
+ *pclr=(COLORREF)CallService(MS_FONT_GETT,(WPARAM)&fid,(LPARAM)plf); /* uses fallback font on error */
+ return (int)*pclr==-1;
+}
+
+int FontService_RegisterColor(const char *pszDbModule,const char *pszDbName,const TCHAR *pszSection,const TCHAR *pszDescription,COLORREF clrDefault)
+{
+ ColourIDT cid;
+ ZeroMemory(&cid,sizeof(cid));
+ cid.cbSize=sizeof(cid);
+ cid.defcolour=clrDefault;
+ lstrcpynA(cid.dbSettingsGroup,pszDbModule,sizeof(cid.dbSettingsGroup)); /* buffer safe */
+ lstrcpynA(cid.setting,pszDbName,sizeof(cid.setting)); /* buffer safe */
+ lstrcpyn(cid.group,pszSection,SIZEOF(cid.group)); /* buffer safe */
+ lstrcpyn(cid.name,pszDescription,SIZEOF(cid.name)); /* buffer safe */
+ return CallService(MS_COLOUR_REGISTERT,(WPARAM)&cid,0);
+}
+
+int FontService_GetColor(const TCHAR *pszSection,const TCHAR *pszDescription,COLORREF *pclr)
+{
+ ColourIDT cid;
+ ZeroMemory(&cid,sizeof(cid));
+ cid.cbSize=sizeof(cid);
+ lstrcpyn(cid.group,pszSection,sizeof(cid.group)); /* buffer safe */
+ lstrcpyn(cid.name,pszDescription,sizeof(cid.name)); /* buffer safe */
+ *pclr=(COLORREF)CallService(MS_COLOUR_GETT,(WPARAM)&cid,0);
+ return (int)*pclr==-1;
+}
+
+/************************* Skin ***********************************/
+
+HANDLE IcoLib_AddIconRes(const char *pszDbName,const TCHAR *pszSection,const TCHAR *pszDesc,HINSTANCE hInst,WORD idRes,BOOL fLarge)
+{
+ SKINICONDESC sid;
+ TCHAR szFileName[MAX_PATH];
+ sid.cbSize=sizeof(SKINICONDESC);
+ sid.pszName=(char*)pszDbName;
+ sid.ptszSection=(TCHAR*)pszSection;
+ sid.ptszDescription=(TCHAR*)pszDesc;
+ sid.ptszDefaultFile=szFileName;
+ sid.iDefaultIndex=-idRes;
+ sid.cx=GetSystemMetrics(fLarge?SM_CXICON:SM_CXSMICON);
+ sid.cy=GetSystemMetrics(fLarge?SM_CYICON:SM_CYSMICON);
+ sid.hDefaultIcon=NULL;
+ sid.flags=SIDF_SORTED|SIDF_ALL_TCHAR;
+ if(!GetModuleFileName(hInst,szFileName,SIZEOF(szFileName)))
+ return NULL;
+ return (HANDLE)CallService(MS_SKIN2_ADDICON,0,(LPARAM)&sid);
+}
+
+HICON IcoLib_GetIcon(const char *pszDbName)
+{
+ return (HICON)CallService(MS_SKIN2_GETICON,0,(LPARAM)pszDbName);
+}
+
+int IcoLib_ReleaseIcon(HICON hIcon)
+{
+ return CallService(MS_SKIN2_RELEASEICON,(WPARAM)hIcon,0);
+}
+
+int SkinAddNewSoundBundled(const char *pszDbName,const char *pszSection,const char *pszDesc,const char *pszSubDir,const char *pszDefaultFile)
+{
+ SKINSOUNDDESCEX ssd;
+ char szFile[MAX_PATH],*p;
+ HANDLE hFile;
+
+ ssd.cbSize=sizeof(ssd);
+ ssd.pszName=pszDbName;
+ ssd.pszSection=pszSection;
+ ssd.pszDescription=pszDesc;
+ ssd.pszDefaultFile=NULL;
+ if(GetModuleFileNameA(NULL,szFile,SIZEOF(szFile)-lstrlenA(pszSubDir)-lstrlenA(pszDefaultFile))) {
+ p=strrchr(szFile,'\\');
+ if(p!=NULL) *(++p)=0;
+ lstrcatA(lstrcatA(szFile,pszSubDir),pszDefaultFile); /* buffer safe */
+ /* check if sound file exist */
+ hFile=CreateFileA(szFile,0,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL);
+ if(hFile!=INVALID_HANDLE_VALUE) {
+ ssd.pszDefaultFile=szFile; /* MS_UTILS_PATHTORELATIVET called automatically */
+ CloseHandle(hFile);
+ }
+ }
+ return CallService(MS_SKIN_ADDNEWSOUND,0,(LPARAM)&ssd);
+}
+
+/* workaround for 'Hotkey Service' plugin because it has needs an event catcher */
+static char szHotkeyService[MAXMODULELABELLENGTH];
+static int moduleId,itemId;
+static int HotkeysServiceHotkeyPressed(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(lParam);
+ if(((THKSEvent*)wParam)->moduleId==moduleId && ((THKSEvent*)wParam)->itemId==LOWORD(itemId))
+ CallService(szHotkeyService,0,0);
+ return 0;
+}
+
+/* defines for 'Hotkey Manager' */
+#define HK_ACT_OVERWRITE 0
+#define HKF_GLOBAL 0x00000001
+#define HKF_WPARNUM 0x00000008
+#define HKF_HEX 0x00000200
+#define HKF_LCURRENT 0x00001000
+#define HKT_SERVICE 2
+typedef struct {
+ void *reserved1;
+ void *reserved2;
+ int hotkey;
+ WCHAR* descr;
+ DWORD flags;
+ ATOM reserved3;
+ DWORD _type;
+ char* service;
+ WPARAM wparam;
+ LPARAM lparam;
+} HOTKEYREC;
+#define MS_HK_ADDHOTKEY "HotKey/AddHotkey"
+
+int SkinAddNewHotkey(const char *pszDbName,const char *pszSection,const char *pszDescription,UINT vk,UINT hotkeyfModifiers,const char *pszServiceName)
+{
+ if(ServiceExists(MS_SKIN_ADDHOTKEY)) { /* clist_mw, clist_modern */
+ SKINHOTKEYDESCEX shd;
+ ZeroMemory(&shd,sizeof(shd));
+ shd.cbSize=sizeof(shd);
+ shd.pszName=(char*)pszDbName;
+ shd.pszDescription=(char*)pszDescription;
+ shd.pszSection=(char*)pszSection;
+ shd.pszService=(char*)pszServiceName;
+ shd.DefHotKey=MAKEWORD(vk,hotkeyfModifiers);
+ CallService(MS_SKIN_ADDHOTKEY,0,(LPARAM)&shd);
+ /* no return */
+ }
+ if(ServiceExists(MS_HOTKEYSPLUS_ADDKEY)) /* 'Hotkeys Plus' */
+ return CallService(MS_HOTKEYSPLUS_ADDKEY,(WPARAM)pszServiceName,(LPARAM)pszDescription);
+ if(ServiceExists(HKS_REGISTERFUNCTION)) { /* mHotKey */
+ KEYHASH kh;
+ kh.isShift=(hotkeyfModifiers&HOTKEYF_SHIFT)!=0;
+ kh.isCtrl=(hotkeyfModifiers&HOTKEYF_CONTROL)!=0;
+ kh.isAlt=(hotkeyfModifiers&HOTKEYF_ALT)!=0;
+ kh.vkCode=vk;
+ return !CallService(HKS_REGISTERFUNCTION,(WPARAM)&kh,(LPARAM)pszServiceName);
+ }
+ if(ServiceExists(MS_HK_ADDHOTKEY)) { /* 'Hotkey Manager' */
+ HOTKEYREC hkr;
+ ZeroMemory(&hkr,sizeof(hkr));
+ hkr.hotkey=(int)MAKEWORD(vk,hotkeyfModifiers);
+ #if defined(_UNICODE)
+ hkr.descr=(WCHAR*)pszDescription;
+ #else
+ hkr.descr=(WCHAR*)a2u(pszDescription);
+ #endif
+ hkr.flags=HKF_GLOBAL|HKF_WPARNUM|HKF_LCURRENT|HKF_HEX;
+ hkr._type=HKT_SERVICE;
+ hkr.service=(char*)pszServiceName;
+ CallService(MS_HK_ADDHOTKEY,(WPARAM)&hkr,HK_ACT_OVERWRITE);
+ #if !defined(_UNICODE)
+ mir_free(hkr.descr);
+ #endif
+ return 0;
+ }
+ if(ServiceExists(MS_HKS_REGISTER_ITEM)) { /* 'Hotkeys Service' */
+ THKSItem item;
+ ZeroMemory(&item,sizeof(item));
+ item.name=(char*)pszSection;
+ item.itemType=HKS_ITEM_MODULE;
+ item.owner=LOWORD(CallService(MS_HKS_REGISTER_ITEM,(WPARAM)&item,0));
+ item.name=(char*)pszDescription;
+ item.itemType=HKS_ITEM_ACTION;
+ item.hotkey.key=(WORD)vk;
+ item.hotkey.modifiers=MOD_GLOBAL;
+ if(hotkeyfModifiers&HOTKEYF_ALT) item.hotkey.modifiers|=MOD_ALT;
+ if(hotkeyfModifiers&HOTKEYF_CONTROL) item.hotkey.modifiers|=MOD_CONTROL;
+ if(hotkeyfModifiers&HOTKEYF_SHIFT) item.hotkey.modifiers|=MOD_SHIFT;
+ if(hotkeyfModifiers&HOTKEYF_EXT) item.hotkey.modifiers|=MOD_WIN;
+ /* no possibility to specify a service to call,
+ * all processing needs to be done in the plugins */
+ moduleId=item.owner;
+ mir_snprintf(szHotkeyService,sizeof(szHotkeyService),"%s",pszServiceName); // only allows for one hotkey as a whole
+ HookEvent(ME_HKS_KEY_PRESSED,HotkeysServiceHotkeyPressed);
+ itemId=CallService(MS_HKS_REGISTER_ITEM,(WPARAM)&item,0);
+ return HIWORD(itemId);
+ }
+ return 1;
+}
diff --git a/plugins/AutoShutdown/utils.h b/plugins/AutoShutdown/utils.h
new file mode 100644
index 0000000000..98b4825ec0
--- /dev/null
+++ b/plugins/AutoShutdown/utils.h
@@ -0,0 +1,48 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+/* String */
+WCHAR *a2u(const char *pszAnsi);
+char *u2a(const WCHAR *pszUnicode);
+void TrimString(TCHAR *pszStr);
+
+/* Error Output */
+void ShowInfoMessage(BYTE flags,const char *pszTitle,const char *pszTextFmt,...);
+char* GetWinErrorDescription(DWORD dwLastError);
+
+/* Time */
+BOOL SystemTimeToTimeStamp(SYSTEMTIME *st,time_t *timestamp);
+BOOL TimeStampToSystemTime(time_t timestamp,SYSTEMTIME *st);
+BOOL GetFormatedCountdown(TCHAR *pszOut,int nSize,time_t countdown);
+BOOL GetFormatedDateTime(TCHAR *pszOut,int nSize,time_t timestamp,BOOL fShowDateEvenToday);
+
+/* Fonts & Colors */
+int FontService_RegisterFont(const char *pszDbModule,const char *pszDbName,const TCHAR *pszSection,const TCHAR *pszDescription,int position,BOOL bAllowEffects,LOGFONT *plfDefault,COLORREF clrDefault);
+int FontService_GetFont(const TCHAR *pszSection,const TCHAR *pszDescription,COLORREF *pclr,LOGFONT *plf);
+int FontService_RegisterColor(const char *pszDbModule,const char *pszDbName,const TCHAR *pszSection,const TCHAR *pszDescription,COLORREF clrDefault);
+int FontService_GetColor(const TCHAR *pszSection,const TCHAR *pszDescription,COLORREF *pclr);
+
+/* Skin */
+HANDLE IcoLib_AddIconRes(const char *pszDbName,const TCHAR *pszSection,const TCHAR *pszDesc,HINSTANCE hInst,WORD idRes,BOOL fLarge);
+HICON IcoLib_GetIcon(const char *pszDbName);
+int IcoLib_ReleaseIcon(HICON hIcon);
+int SkinAddNewSoundBundled(const char *pszDbName,const char *pszSection,const char *pszDesc,const char *pszSubDir,const char *pszDefaultFile);
+int SkinAddNewHotkey(const char *pszDbName,const char* pszSection,const char *pszDescription,UINT vk,UINT hotkeyfModifiers,const char *pszServiceName);
diff --git a/plugins/AutoShutdown/version.h b/plugins/AutoShutdown/version.h
new file mode 100644
index 0000000000..cba1fe2c93
--- /dev/null
+++ b/plugins/AutoShutdown/version.h
@@ -0,0 +1,40 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#define NEEDED_MIRANDA_VERSION PLUGIN_MAKE_VERSION(0,7,0,16)
+#define NEEDED_MIRANDA_VERSION_STR "0.7 alpha build #16"
+#define PLUGIN_VERSION PLUGIN_MAKE_VERSION(1,4,0,2)
+#define FILE_VERSION 1,4,0,2
+
+#if defined(_DEBUG)
+ #define FILE_VERSION_STR "1.4.0.3 alpha"
+#else
+ #define FILE_VERSION_STR "1.4.0.2"
+#endif
+
+#define PLUGIN_EMAIL "hrathh users.sourceforge.net"
+#define PLUGIN_EMAIL_ATT_POS 7 /* position of the @-sign in the email adress above */
+
+#if defined(_UNICODE)
+ #define PLUGIN_WEBSITE "http://addons.miranda-im.org/details.php?action=viewfile&id=3056"
+#else
+ #define PLUGIN_WEBSITE "http://addons.miranda-im.org/details.php?action=viewfile&id=1086"
+#endif
diff --git a/plugins/AutoShutdown/version.rc b/plugins/AutoShutdown/version.rc
new file mode 100644
index 0000000000..97f35498c3
--- /dev/null
+++ b/plugins/AutoShutdown/version.rc
@@ -0,0 +1,51 @@
+#ifndef _MAC
+
+#include "version.h"
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION FILE_VERSION
+ PRODUCTVERSION FILE_VERSION
+ FILEFLAGSMASK 0x0L
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE 0x2L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "000004b0"
+ BEGIN
+ VALUE "Comments", "Licensed under the terms of the GNU General Public License"
+ VALUE "FileDescription", "AutoShutdown Plugin for Miranda IM"
+ VALUE "FileVersion", FILE_VERSION_STR
+#ifdef _UNICODE
+ VALUE "InternalName", "AutoShutdown (Unicode)"
+#else
+ VALUE "InternalName", "AutoShutdown"
+#endif
+ VALUE "LegalCopyright", "Copyright � 2004-2007 H. Herkenrath"
+ VALUE "OriginalFilename", "shutdown.dll"
+ VALUE "ProductName", "Automatic Shutdown"
+ VALUE "ProductVersion", FILE_VERSION_STR
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x0, 1200
+ END
+END
+
+#endif // !_MAC
+
+
+
+
diff --git a/plugins/AutoShutdown/watcher.c b/plugins/AutoShutdown/watcher.c
new file mode 100644
index 0000000000..75a2881e98
--- /dev/null
+++ b/plugins/AutoShutdown/watcher.c
@@ -0,0 +1,408 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+#include "common.h"
+
+/* Msg Shutdown */
+static HANDLE hHookEventAdded;
+/* Transfer Shutdown */
+static HANDLE hHookProtoAck;
+/* Idle Shutdown */
+static HANDLE hHookIdleChanged;
+/* Status Shutdown */
+static HANDLE hHookSettingChanged;
+/* Weather Shutdown */
+static HANDLE hHookWeatherUpdated;
+/* Overheat Shutdown */
+static HANDLE hHookHddOverheat;
+/* Services */
+static HANDLE hServiceStartWatcher,hServiceStopWatcher,hServiceIsEnabled;
+static HANDLE hEventWatcherChanged;
+/* Misc */
+static HANDLE hHookModulesLoaded;
+
+/************************* Shared *************************************/
+
+static WORD currentWatcherType;
+
+static void __stdcall MainThreadMapping(HANDLE *phDoneEvent)
+{
+ ServiceShutdown(0,TRUE); /* ensure main thread (for cpu usage shutdown) */
+ ServiceStopWatcher(0,0);
+ if(*phDoneEvent!=NULL) SetEvent(*phDoneEvent);
+}
+
+static void __inline ShutdownAndStopWatcher(void)
+{
+ HANDLE hDoneEvent;
+ hDoneEvent=CreateEvent(NULL,FALSE,FALSE,NULL);
+ if(CallFunctionAsync(MainThreadMapping,&hDoneEvent))
+ if(hDoneEvent!=NULL) WaitForSingleObject(hDoneEvent,INFINITE);
+ if(hDoneEvent!=NULL) CloseHandle(hDoneEvent);
+}
+
+/************************* Msg Shutdown *******************************/
+
+// ppBlob might get reallocated, must have been allocated using mir_alloc()
+static TCHAR* GetMessageText(BYTE **ppBlob,DWORD *pcbBlob)
+{
+#if defined(_UNICODE)
+ DWORD cb;
+ (*ppBlob)[*pcbBlob]=0;
+ cb=lstrlenA((char*)*ppBlob);
+ /* use Unicode data if present */
+ if(*pcbBlob>(cb+3)) {
+ (*ppBlob)[*pcbBlob-1]=0;
+ return (WCHAR*)&(*ppBlob)[cb];
+ }
+ /* no Unicode data present, convert from ANSI */
+ { int len;
+ BYTE *buf;
+ len=MultiByteToWideChar(CP_ACP,0,(char*)*ppBlob,-1,NULL,0);
+ if(!len) return NULL;
+ buf=(BYTE*)mir_realloc(*ppBlob,(*pcbBlob)+(len*sizeof(WCHAR)));
+ if(buf==NULL) return NULL;
+ *pcbBlob+=len*sizeof(WCHAR);
+ *ppBlob=buf;
+ buf=&(*ppBlob)[cb];
+ MultiByteToWideChar(CP_ACP,0,(char*)*ppBlob,-1,(WCHAR*)buf,len);
+ ((WCHAR*)buf)[len-1]=0;
+ return (WCHAR*)buf;
+ }
+#else
+ (*ppBlob)[*pcbBlob]=0;
+ return (char*)*ppBlob;
+#endif
+}
+
+static int MsgEventAdded(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ if(currentWatcherType&SDWTF_MESSAGE) {
+ DBEVENTINFO dbe;
+ dbe.cbSize=sizeof(dbe);
+ dbe.cbBlob=(DWORD)CallService(MS_DB_EVENT_GETBLOBSIZE,(WPARAM)lParam,0);
+ dbe.pBlob=(BYTE*)mir_alloc(dbe.cbBlob+2); /* ensure term zero */
+ if(dbe.pBlob==NULL) return 0;
+ if(!CallService(MS_DB_EVENT_GET,(WPARAM)lParam,(LPARAM)&dbe))
+ if(dbe.eventType==EVENTTYPE_MESSAGE && !(dbe.flags&DBEF_SENT)) {
+ DBVARIANT dbv;
+ TCHAR *pszMsg;
+ if(!DBGetContactSettingTString(NULL,"AutoShutdown","Message",&dbv)) {
+ TrimString(dbv.ptszVal);
+ pszMsg=GetMessageText(&dbe.pBlob,&dbe.cbBlob);
+ if(pszMsg!=NULL && _tcsstr(pszMsg,dbv.ptszVal)!=NULL)
+ ShutdownAndStopWatcher(); /* msg with specified text recvd */
+ mir_free(dbv.ptszVal); /* does NULL check */
+ }
+ }
+ mir_free(dbe.pBlob);
+ }
+ return 0;
+}
+
+/************************* Transfer Shutdown **************************/
+
+static HANDLE *transfers;
+static int nTransfersCount;
+
+static int ProtoAck(WPARAM wParam,LPARAM lParam)
+{
+ ACKDATA *ack=(ACKDATA*)lParam;
+ UNREFERENCED_PARAMETER(wParam);
+ if(ack->type==ACKTYPE_FILE)
+ switch(ack->result) {
+ case ACKRESULT_DATA:
+ { int i;
+ for(i=0;i<nTransfersCount;++i)
+ if(transfers[i]==ack->hProcess)
+ break; /* already in list */
+ /* insert into list */
+ { HANDLE *buf=(HANDLE*)mir_realloc(transfers,(nTransfersCount+1)*sizeof(HANDLE)); if(buf!=NULL) {
+ transfers=buf;
+ transfers[nTransfersCount]=ack->hProcess;
+ ++nTransfersCount;
+ }
+ }
+ break;
+ }
+ case ACKRESULT_SUCCESS:
+ case ACKRESULT_FAILED:
+ case ACKRESULT_DENIED:
+ { int i;
+ for(i=0;i<nTransfersCount;++i)
+ if(transfers[i]==ack->hProcess) {
+ /* remove from list */
+ HANDLE *buf;
+ if(i<(nTransfersCount-1))
+ MoveMemory(&transfers[i],&transfers[i+1],(nTransfersCount-i-1)*sizeof(HANDLE));
+ --nTransfersCount;
+ buf=(HANDLE*)mir_realloc(transfers,nTransfersCount*sizeof(HANDLE));
+ if(buf!=NULL) transfers=buf;
+ else if(!nTransfersCount) transfers=NULL;
+ /* stop watcher */
+ if(!nTransfersCount && (currentWatcherType&SDWTF_FILETRANSFER))
+ ShutdownAndStopWatcher();
+ break;
+ }
+ break;
+ }
+ }
+ return 0;
+}
+
+/************************* Idle Shutdown ******************************/
+
+static int IdleChanged(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ if(currentWatcherType&SDWTF_IDLE && lParam&IDF_ISIDLE)
+ ShutdownAndStopWatcher();
+ return 0;
+}
+
+/************************* Status Shutdown ****************************/
+
+static BOOL CheckAllContactsOffline(void)
+{
+ BOOL fSmartCheck,fAllOffline=TRUE; /* tentatively */
+ HANDLE hContact;
+ char *pszProto;
+ fSmartCheck=DBGetContactSettingByte(NULL,"AutoShutdown","SmartOfflineCheck",SETTING_SMARTOFFLINECHECK_DEFAULT);
+ hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
+ while(hContact!=NULL) {
+ pszProto=(char*)CallService(MS_PROTO_GETCONTACTBASEPROTO,(WPARAM)hContact,0);
+ if(pszProto!=NULL && CallProtoService(pszProto,PS_GETSTATUS,0,0)!=ID_STATUS_OFFLINE)
+ if(DBGetContactSettingByte(hContact,pszProto,"ChatRoom",0)) continue;
+ if(DBGetContactSettingWord(hContact,pszProto,"Status",0)!=ID_STATUS_OFFLINE) {
+ if(fSmartCheck) {
+ if(DBGetContactSettingByte(hContact,"CList","Hidden",0)) continue;
+ if(DBGetContactSettingByte(hContact,"CList","NotOnList",0)) continue;
+ }
+ fAllOffline=FALSE;
+ break;
+ }
+ hContact=(HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)hContact,0);
+ }
+ return fAllOffline;
+}
+
+static int StatusSettingChanged(WPARAM wParam,LPARAM lParam)
+{
+ if(currentWatcherType&SDWTF_STATUS) {
+ DBCONTACTWRITESETTING *dbcws=(DBCONTACTWRITESETTING*)lParam;
+ if((HANDLE)wParam!=NULL && dbcws->value.wVal==ID_STATUS_OFFLINE && !lstrcmpA(dbcws->szSetting,"Status")) {
+ char *pszProto=(char*)CallService(MS_PROTO_GETCONTACTBASEPROTO,wParam,0);
+ if(pszProto!=NULL && !lstrcmpA(dbcws->szModule,pszProto))
+ if(CheckAllContactsOffline())
+ ShutdownAndStopWatcher();
+ }
+ }
+ return 0;
+}
+
+/************************* Cpu Shutdown *******************************/
+
+static DWORD idCpuUsageThread;
+
+static BOOL CALLBACK CpuUsageWatcherProc(BYTE nCpuUsage,LPARAM lParam)
+{
+ static BYTE nTimesBelow=0; /* only one watcher thread */
+ /* terminated? */
+ if(idCpuUsageThread!=GetCurrentThreadId()) {
+ nTimesBelow=0;
+ return FALSE; /* stop poll thread */
+ }
+ /* ignore random peaks */
+ if(nCpuUsage<(BYTE)lParam) ++nTimesBelow;
+ else nTimesBelow=0;
+ if(nTimesBelow==3) {
+ nTimesBelow=0;
+ ShutdownAndStopWatcher();
+ return FALSE; /* stop poll thread */
+ }
+ return TRUE;
+}
+
+/************************* Weather Shutdown ***************************/
+
+static int WeatherUpdated(WPARAM wParam,LPARAM lParam)
+{
+ char *pszProto=(char*)CallService(MS_PROTO_GETCONTACTBASEPROTO,wParam,0);
+ if((BOOL)lParam && pszProto!=NULL && CallProtoService(pszProto,PS_GETSTATUS,0,0)==THUNDER)
+ if(DBGetContactSettingByte(NULL,"AutoShutdown","WeatherShutdown",SETTING_WEATHERSHUTDOWN_DEFAULT))
+ ServiceShutdown(SDSDT_SHUTDOWN,TRUE);
+ return 0;
+}
+
+/************************* Overheat Shutdown **************************/
+
+static int HddOverheat(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ if(DBGetContactSettingByte(NULL,"AutoShutdown","HddOverheatShutdown",SETTING_HDDOVERHEATSHUTDOWN_DEFAULT))
+ ServiceShutdown(SDSDT_SHUTDOWN,TRUE);
+ return 0;
+}
+
+/************************* Services ***********************************/
+
+int ServiceStartWatcher(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+
+ /* passing watcherType as lParam is only to be used internally, undocumented */
+ if(lParam==0) lParam=(LPARAM)DBGetContactSettingWord(NULL,"AutoShutdown","WatcherFlags",0);
+
+ if(!(lParam&SDWTF_MASK)) return 1; /* invalid flags or empty? */
+ if(lParam&SDWTF_SPECIFICTIME && !(lParam&SDWTF_ST_MASK)) return 2; /* no specific time choice? */
+ if(currentWatcherType==(WORD)lParam) return 3;
+
+ if(currentWatcherType!=0) {
+ /* Time Shutdown */
+ CloseCountdownFrame(); /* fails if not opened */
+ /* Cpu Shutdown */
+ idCpuUsageThread=0;
+ }
+ SetShutdownMenuItem(TRUE);
+ SetShutdownToolbarButton(TRUE);
+ currentWatcherType=(WORD)lParam;
+ NotifyEventHooks(hEventWatcherChanged,TRUE,0);
+
+ /* Time Shutdown */
+ if(currentWatcherType&SDWTF_SPECIFICTIME)
+ ShowCountdownFrame(currentWatcherType); /* after modules loaded */
+ /* Cpu Shutdown */
+ if(currentWatcherType&SDWTF_CPUUSAGE)
+ idCpuUsageThread=PollCpuUsage(CpuUsageWatcherProc,(LPARAM)DBGetContactSettingRangedByte(NULL,"AutoShutdown","CpuUsageThreshold",SETTING_CPUUSAGETHRESHOLD_DEFAULT,1,100),1500);
+ /* Transfer Shutdown */
+ if(currentWatcherType&SDWTF_FILETRANSFER && !nTransfersCount)
+ ShutdownAndStopWatcher();
+ /* Status Shutdown */
+ if(currentWatcherType&SDWTF_STATUS && CheckAllContactsOffline())
+ ShutdownAndStopWatcher();
+ return 0;
+}
+
+int ServiceStopWatcher(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ if(currentWatcherType==0) return 1;
+
+ /* Time Shutdown */
+ if(currentWatcherType&SDWTF_SPECIFICTIME)
+ CloseCountdownFrame();
+ /* Cpu Shutdown */
+ idCpuUsageThread=0;
+
+ currentWatcherType=0;
+ SetShutdownMenuItem(FALSE);
+ SetShutdownToolbarButton(FALSE);
+ NotifyEventHooks(hEventWatcherChanged,FALSE,0);
+ return 0;
+}
+
+int ServiceIsWatcherEnabled(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+ return currentWatcherType!=0;
+}
+
+/************************* Misc ***********************************/
+
+static int WatcherModulesLoaded(WPARAM wParam,LPARAM lParam)
+{
+ UNREFERENCED_PARAMETER(wParam);
+ UNREFERENCED_PARAMETER(lParam);
+
+ /* Weather Shutdown */
+ if(ServiceExists(MS_WEATHER_UPDATE))
+ hHookWeatherUpdated=HookEvent(ME_WEATHER_UPDATED,WeatherUpdated);
+ /* Overheat Shutdown */
+ if(ServiceExists(MS_SYSINFO_HDDTEMP))
+ hHookHddOverheat=HookEvent(ME_SYSINFO_HDDOVERHEAT,HddOverheat);
+
+ /* restore watcher if it was running on last exit */
+ if(DBGetContactSettingByte(NULL,"AutoShutdown","RememberOnRestart",0)==SDROR_RUNNING) {
+ DBWriteContactSettingByte(NULL,"AutoShutdown","RememberOnRestart",1);
+ ServiceStartWatcher(0,0); /* after modules loaded */
+ }
+ return 0;
+}
+
+void InitWatcher(void)
+{
+ /* Shared */
+ currentWatcherType=0;
+ /* Message Shutdown */
+ hHookEventAdded=HookEvent(ME_DB_EVENT_ADDED,MsgEventAdded);
+ /* Status Shutdown*/
+ hHookSettingChanged=HookEvent(ME_DB_CONTACT_SETTINGCHANGED,StatusSettingChanged);
+ /* Idle Shutdown */
+ hHookIdleChanged=HookEvent(ME_IDLE_CHANGED,IdleChanged);
+ /* Transfer Shutdown */
+ transfers=NULL;
+ nTransfersCount=0;
+ hHookProtoAck=HookEvent(ME_PROTO_ACK,ProtoAck);
+ /* Weather Shutdown */
+ hHookWeatherUpdated=NULL;
+ /* Overheat Shutdown */
+ hHookHddOverheat=NULL;
+ /* Services */
+ hEventWatcherChanged=CreateHookableEvent(ME_AUTOSHUTDOWN_WATCHERCHANGED);
+ hServiceStartWatcher=CreateServiceFunction(MS_AUTOSHUTDOWN_STARTWATCHER,ServiceStartWatcher);
+ hServiceStopWatcher=CreateServiceFunction(MS_AUTOSHUTDOWN_STOPWATCHER,ServiceStopWatcher);
+ hServiceIsEnabled=CreateServiceFunction(MS_AUTOSHUTDOWN_ISWATCHERENABLED,ServiceIsWatcherEnabled);
+ /* Misc */
+ hHookModulesLoaded=HookEvent(ME_SYSTEM_MODULESLOADED,WatcherModulesLoaded);
+}
+
+void UninitWatcher(void)
+{
+ /* remember watcher if running */
+ if(!ServiceStopWatcher(0,0))
+ if(DBGetContactSettingByte(NULL,"AutoShutdown","RememberOnRestart",SETTING_REMEMBERONRESTART_DEFAULT))
+ DBWriteContactSettingByte(NULL,"AutoShutdown","RememberOnRestart",SDROR_RUNNING);
+
+ /* Message Shutdown */
+ UnhookEvent(hHookEventAdded);
+ /* Status Shutdown*/
+ UnhookEvent(hHookSettingChanged);
+ /* Idle Shutdown */
+ UnhookEvent(hHookIdleChanged);
+ /* Transfer Shutdown */
+ UnhookEvent(hHookProtoAck);
+ mir_free(transfers); /* does NULL check */
+ /* Weather Shutdown */
+ UnhookEvent(hHookWeatherUpdated); /* does NULL check */
+ /* Overheat Shutdown */
+ UnhookEvent(hHookHddOverheat); /* does NULL check */
+ /* Services */
+ DestroyServiceFunction(hServiceStartWatcher);
+ DestroyServiceFunction(hServiceStopWatcher);
+ DestroyServiceFunction(hServiceIsEnabled);
+ DestroyHookableEvent(hEventWatcherChanged);
+ /* Misc */
+ UnhookEvent(hHookModulesLoaded);
+}
diff --git a/plugins/AutoShutdown/watcher.h b/plugins/AutoShutdown/watcher.h
new file mode 100644
index 0000000000..20f4e431c3
--- /dev/null
+++ b/plugins/AutoShutdown/watcher.h
@@ -0,0 +1,29 @@
+/*
+
+'AutoShutdown'-Plugin for Miranda IM
+
+Copyright 2004-2007 H. Herkenrath
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program (Shutdown-License.txt); if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+
+/* Services */
+int ServiceStartWatcher(WPARAM wParam,LPARAM lParam);
+int ServiceStopWatcher(WPARAM wParam,LPARAM lParam);
+int ServiceIsWatcherEnabled(WPARAM wParam,LPARAM lParam);
+
+/* Misc */
+void InitWatcher(void);
+void UninitWatcher(void);
diff --git a/plugins/AvatarHistory/AvatarDlg.cpp b/plugins/AvatarHistory/AvatarDlg.cpp
new file mode 100644
index 0000000000..4abe154016
--- /dev/null
+++ b/plugins/AvatarHistory/AvatarDlg.cpp
@@ -0,0 +1,621 @@
+/*
+Avatar History Plugin
+ Copyright (C) 2006 Matthew Wild - Email: mwild1@gmail.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.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+*/
+
+#include "AvatarHistory.h"
+
+extern HINSTANCE hInst;
+HANDLE hMenu = NULL;
+DWORD WINAPI AvatarDialogThread(LPVOID param);
+static INT_PTR CALLBACK AvatarDlgProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);
+int ShowSaveDialog(HWND hwnd, TCHAR* fn,HANDLE hContact = NULL);
+
+BOOL ProtocolEnabled(const char *proto);
+int FillAvatarListFromDB(HWND list, HANDLE hContact);
+int FillAvatarListFromFolder(HWND list, HANDLE hContact);
+int CleanupAvatarPic(HWND hwnd);
+BOOL UpdateAvatarPic(HWND hwnd);
+TCHAR* GetCurrentSelFile(HWND list);
+TCHAR * GetContactFolder(TCHAR *fn, HANDLE hContact);
+BOOL ResolveShortcut(TCHAR *shortcut, TCHAR *file);
+
+static INT_PTR ShowDialogSvc(WPARAM wParam, LPARAM lParam);
+extern HANDLE hServices[];
+extern HANDLE hHooks[];
+
+struct AvatarDialogData
+{
+ HANDLE hContact;
+ TCHAR fn[MAX_PATH];
+ HWND parent;
+};
+
+
+class ListEntry
+{
+public:
+ ListEntry()
+ {
+ dbe = NULL;
+ filename = NULL;
+ filelink = NULL;
+ }
+
+ ~ListEntry()
+ {
+ mir_free(filename);
+ mir_free(filelink);
+ }
+
+ HANDLE dbe;
+ TCHAR *filename;
+ TCHAR *filelink;
+};
+
+int OpenAvatarDialog(HANDLE hContact, char* fn)
+{
+ HWND hAvatarWindow = WindowList_Find(hAvatarWindowsList, hContact);
+ if (hAvatarWindow)
+ {
+ SetForegroundWindow(hAvatarWindow);
+ SetFocus(hAvatarWindow);
+ return 0;
+ }
+
+ DWORD dwId;
+ struct AvatarDialogData *avdlg = (struct AvatarDialogData*)malloc(sizeof(struct AvatarDialogData));
+ ZeroMemory(avdlg, sizeof(struct AvatarDialogData));
+ avdlg->hContact = hContact;
+ if (fn == NULL)
+ {
+ avdlg->fn[0] = _T('\0');
+ }
+ else
+ {
+#ifdef _UNICODE
+ MultiByteToWideChar(CP_ACP, 0, fn, -1, avdlg->fn, MAX_REGS(avdlg->fn));
+#else
+ lstrcpyn(avdlg->fn, fn, sizeof(avdlg->fn));
+#endif
+ }
+
+ CloseHandle(CreateThread(NULL, 0, AvatarDialogThread, (LPVOID)avdlg, 0, &dwId));
+ return 0;
+}
+
+DWORD WINAPI AvatarDialogThread(LPVOID param)
+{
+ struct AvatarDialogData* data = (struct AvatarDialogData*)param;
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_AVATARDLG), data->parent, AvatarDlgProc, (LPARAM)param);
+ return 0;
+}
+
+void EnableDisableControls(HWND hwnd)
+{
+ HWND list = GetDlgItem(hwnd, IDC_AVATARLIST);
+
+ int cursel = SendMessage(list, LB_GETCURSEL, 0, 0);
+ int count = SendMessage(list, LB_GETCOUNT, 0, 0);
+
+ if (cursel == LB_ERR)
+ {
+ EnableWindow(GetDlgItem(hwnd, IDC_BACK), count > 0);
+ EnableWindow(GetDlgItem(hwnd, IDC_NEXT), count > 0);
+ }
+ else
+ {
+ EnableWindow(GetDlgItem(hwnd, IDC_BACK), cursel > 0);
+ EnableWindow(GetDlgItem(hwnd, IDC_NEXT), cursel < count-1);
+ }
+}
+
+static INT_PTR CALLBACK AvatarDlgProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
+{
+ switch(uMsg)
+ {
+ case WM_INITDIALOG:
+ {
+ AvatarDialogData *data = (struct AvatarDialogData*) lParam;
+ SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM) createDefaultOverlayedIcon(TRUE));
+ SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM) createDefaultOverlayedIcon(FALSE));
+ if (db_byte_get(NULL, MODULE_NAME, "LogToHistory", AVH_DEF_LOGTOHISTORY))
+ FillAvatarListFromDB(GetDlgItem(hwnd, IDC_AVATARLIST), data->hContact);
+ else if (opts.log_per_contact_folders)
+ FillAvatarListFromFolder(GetDlgItem(hwnd, IDC_AVATARLIST), data->hContact);
+ TCHAR *displayName = (TCHAR*) CallService(MS_CLIST_GETCONTACTDISPLAYNAME,(WPARAM) data->hContact,GCDNF_TCHAR);
+ if(displayName)
+ {
+ TCHAR title[MAX_PATH];
+ mir_sntprintf(title,MAX_PATH,TranslateT("Avatar History for %s"),displayName);
+ SetWindowText(hwnd,title);
+ }
+
+ SetWindowLongPtr(hwnd, GWLP_USERDATA, (ULONG_PTR)data->hContact);
+ UpdateAvatarPic(hwnd);
+ CheckDlgButton(hwnd, IDC_LOGUSER, (UINT)db_byte_get(data->hContact, MODULE_NAME, "LogToDisk", BST_INDETERMINATE));
+ CheckDlgButton(hwnd, IDC_POPUPUSER, (UINT)db_byte_get(data->hContact, MODULE_NAME, "AvatarPopups", BST_INDETERMINATE));
+ CheckDlgButton(hwnd, IDC_HISTORYUSER, (UINT)db_byte_get(data->hContact, MODULE_NAME, "LogToHistory", BST_INDETERMINATE));
+ ShowWindow(GetDlgItem(hwnd, IDC_OPENFOLDER), opts.log_per_contact_folders ? SW_SHOW : SW_HIDE);
+ Utils_RestoreWindowPositionNoSize(hwnd,NULL,MODULE_NAME,"AvatarHistoryDialog");
+ WindowList_Add(hAvatarWindowsList,hwnd,data->hContact);
+ TranslateDialogDefault(hwnd);
+ EnableDisableControls(hwnd);
+ free(data);
+ data = NULL;
+ break;
+ }
+ case WM_CLOSE:
+ {
+ CleanupAvatarPic(hwnd);
+ EndDialog(hwnd, 0);
+ return TRUE;
+ }
+ case WM_DESTROY:
+ {
+ Utils_SaveWindowPosition(hwnd,NULL,MODULE_NAME,"AvatarHistoryDialog");
+ WindowList_Remove(hAvatarWindowsList,hwnd);
+ DestroyIcon((HICON)SendMessage(hwnd, WM_SETICON, ICON_BIG, 0));
+ DestroyIcon((HICON)SendMessage(hwnd, WM_SETICON, ICON_SMALL, 0));
+ HWND list = GetDlgItem(hwnd, IDC_AVATARLIST);
+ int count = SendMessage(list, LB_GETCOUNT, 0, 0);
+ for(int i = 0; i < count; i++)
+ delete (ListEntry *) SendMessage(list, LB_GETITEMDATA, i, 0);
+ break;
+ }
+ case WM_CONTEXTMENU:
+ {
+ HWND list = GetDlgItem(hwnd, IDC_AVATARLIST);
+ HWND pic = GetDlgItem(hwnd, IDC_AVATAR);
+ int pos;
+
+ if ((HANDLE) wParam == list)
+ {
+ POINT p;
+ p.x = LOWORD(lParam);
+ p.y = HIWORD(lParam);
+
+ ScreenToClient(list, &p);
+
+ pos = SendMessage(list, LB_ITEMFROMPOINT, 0, MAKELONG(p.x, p.y));
+ if (HIWORD(pos))
+ break;
+ pos = LOWORD(pos);
+
+ int count = SendMessage(list, LB_GETCOUNT, 0, 0);
+ if (pos >= count)
+ break;
+
+ SendMessage(list, LB_SETCURSEL, pos, 0);
+ EnableDisableControls(hwnd);
+ }
+ else if ((HANDLE) wParam == pic)
+ {
+ pos = SendMessage(list, LB_GETCURSEL, 0, 0);
+ if (pos == LB_ERR)
+ break;
+ }
+ else
+ break;
+
+ HMENU menu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_MENU1));
+ HMENU submenu = GetSubMenu(menu, 0);
+ TranslateMenu(submenu);
+
+ if (!UpdateAvatarPic(hwnd))
+ {
+ RemoveMenu(submenu, 2, MF_BYPOSITION);
+ RemoveMenu(submenu, 0, MF_BYPOSITION);
+ }
+
+ POINT p;
+ p.x = LOWORD(lParam);
+ p.y = HIWORD(lParam);
+ int ret = TrackPopupMenu(submenu, TPM_TOPALIGN|TPM_LEFTALIGN|TPM_RIGHTBUTTON|TPM_RETURNCMD, p.x, p.y, 0, list, NULL);
+ DestroyMenu(menu);
+
+ switch(ret)
+ {
+ case ID_AVATARLISTPOPUP_SAVEAS:
+ {
+ HANDLE hContact = (HANDLE) GetWindowLongPtr(hwnd, GWLP_USERDATA);
+ ListEntry *le = (ListEntry*) SendMessage(list, LB_GETITEMDATA, pos, 0);
+ ShowSaveDialog(hwnd, le->filename, hContact);
+ break;
+ }
+ case ID_AVATARLISTPOPUP_DELETE:
+ {
+ ListEntry *le = (ListEntry*) SendMessage(list, LB_GETITEMDATA, pos, 0);
+
+ BOOL blDelete;
+
+ if(le->dbe)
+ blDelete = MessageBox(hwnd, TranslateT("Are you sure you wish to delete this history entry?\nOnly the entry in history will be deleted, bitmap file will be kept!"),
+ TranslateT("Delete avatar log?"), MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2|MB_SETFOREGROUND|MB_TOPMOST) == IDYES;
+ else
+ blDelete = MessageBox(hwnd, TranslateT("Are you sure you wish to delete this avatar shortcut?\nOnly shortcut will be deleted, bitmap file will be kept!"),
+ TranslateT("Delete avatar log?"), MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2|MB_SETFOREGROUND|MB_TOPMOST) == IDYES;
+
+ if (blDelete)
+ {
+ HANDLE hContact = (HANDLE) GetWindowLongPtr(hwnd, GWLP_USERDATA);
+
+ if(le->dbe)
+ CallService(MS_DB_EVENT_DELETE, (WPARAM) hContact, (LPARAM) le->dbe);
+ else
+ DeleteFile(le->filelink);
+
+ delete le;
+
+ SendMessage(list, LB_DELETESTRING, pos, 0);
+
+ int count = SendMessage(list, LB_GETCOUNT, 0, 0);
+ if (count > 0)
+ {
+ if (pos >= count)
+ pos = count -1;
+ SendMessage(list, LB_SETCURSEL, pos, 0);
+ }
+
+ UpdateAvatarPic(hwnd);
+ EnableDisableControls(hwnd);
+ }
+ break;
+ }
+ case ID_AVATARLISTPOPUP_DELETE_BOTH:
+ {
+ ListEntry *le = (ListEntry*) SendMessage(list, LB_GETITEMDATA, pos, 0);
+
+ BOOL blDelete;
+
+ if(le->dbe)
+ blDelete = MessageBox(hwnd, TranslateT("Are you sure you wish to delete this archived avatar?\nThis will delete the history entry and the bitmap file.\nWARNING:This can affect more than one entry in history!"),
+ TranslateT("Delete avatar?"), MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2|MB_SETFOREGROUND|MB_TOPMOST) == IDYES;
+ else
+ blDelete = MessageBox(hwnd, TranslateT("Are you sure you wish to delete this archived avatar?\nThis will delete the shortcut and the bitmap file.\nWARNING:This can affect more than one shortcut!"),
+ TranslateT("Delete avatar?"), MB_YESNO|MB_ICONWARNING|MB_DEFBUTTON2|MB_SETFOREGROUND|MB_TOPMOST) == IDYES;
+
+ if (blDelete)
+ {
+ HANDLE hContact = (HANDLE) GetWindowLongPtr(hwnd, GWLP_USERDATA);
+
+ DeleteFile(le->filename);
+
+ if(le->dbe)
+ CallService(MS_DB_EVENT_DELETE, (WPARAM) hContact, (LPARAM) le->dbe);
+ else
+ DeleteFile(le->filelink);
+
+ delete le;
+
+ SendMessage(list, LB_DELETESTRING, pos, 0);
+
+ int count = SendMessage(list, LB_GETCOUNT, 0, 0);
+ if (count > 0)
+ {
+ if (pos >= count)
+ pos = count -1;
+ SendMessage(list, LB_SETCURSEL, pos, 0);
+ }
+
+ UpdateAvatarPic(hwnd);
+ EnableDisableControls(hwnd);
+ }
+ break;
+ }
+ }
+ break;
+ }
+ case WM_COMMAND:
+ {
+ switch(LOWORD(wParam))
+ {
+ case IDOK:
+ if(HIWORD(wParam) == BN_CLICKED)
+ {
+ HANDLE hContact = (HANDLE) GetWindowLongPtr(hwnd, GWLP_USERDATA);
+
+ db_byte_set(hContact, MODULE_NAME, "AvatarPopups", (BYTE) IsDlgButtonChecked(hwnd, IDC_POPUPUSER));
+ db_byte_set(hContact, MODULE_NAME, "LogToDisk", (BYTE) IsDlgButtonChecked(hwnd, IDC_LOGUSER));
+ db_byte_set(hContact, MODULE_NAME, "LogToHistory", (BYTE) IsDlgButtonChecked(hwnd, IDC_HISTORYUSER));
+
+ CleanupAvatarPic(hwnd);
+ EndDialog(hwnd, 0);
+ return TRUE;
+ }
+ break;
+ case IDC_AVATARLIST:
+ if(HIWORD(wParam) == LBN_SELCHANGE)
+ {
+ UpdateAvatarPic(hwnd);
+ EnableDisableControls(hwnd);
+ return TRUE;
+ }
+ break;
+ case IDC_OPENFOLDER:
+ if(HIWORD(wParam) == BN_CLICKED)
+ {
+ if (opts.log_per_contact_folders)
+ {
+ TCHAR avfolder[MAX_PATH];
+ HANDLE hContact = (HANDLE)GetWindowLongPtr(hwnd, GWLP_USERDATA);
+ GetContactFolder(avfolder, hContact);
+ ShellExecute(NULL, db_byte_get(NULL, MODULE_NAME, "OpenFolderMethod", 0) ? _T("explore") : _T("open"), avfolder, NULL, NULL, SW_SHOWNORMAL);
+ return TRUE;
+ }
+ }
+ break;
+ case IDC_NEXT:
+ if(HIWORD(wParam) == BN_CLICKED)
+ {
+ HWND list = GetDlgItem(hwnd, IDC_AVATARLIST);
+ SendMessage(list, LB_SETCURSEL, SendMessage(list, LB_GETCURSEL, 0, 0) +1, 0);
+ UpdateAvatarPic(hwnd);
+ EnableDisableControls(hwnd);
+ return TRUE;
+ }
+ break;
+ case IDC_BACK:
+ if(HIWORD(wParam) == BN_CLICKED)
+ {
+ HWND list = GetDlgItem(hwnd, IDC_AVATARLIST);
+ int cursel = SendMessage(list, LB_GETCURSEL, 0, 0);
+ if (cursel == LB_ERR)
+ SendMessage(list, LB_SETCURSEL, SendMessage(list, LB_GETCOUNT, 0, 0) -1, 0);
+ else
+ SendMessage(list, LB_SETCURSEL, cursel -1, 0);
+ UpdateAvatarPic(hwnd);
+ EnableDisableControls(hwnd);
+ return TRUE;
+ }
+ break;
+ }
+ break;
+ }
+ }
+ return FALSE;
+}
+
+
+
+int FillAvatarListFromFolder(HWND list, HANDLE hContact)
+{
+ int max_pos = 0;
+ TCHAR dir[MAX_PATH], path[MAX_PATH], lnk[MAX_PATH];
+ WIN32_FIND_DATA finddata;
+
+ GetContactFolder(dir, hContact);
+ mir_sntprintf(path, MAX_PATH, _T("%s\\*.lnk"), dir);
+
+ HANDLE hFind = FindFirstFile(path, &finddata);
+ if (hFind == INVALID_HANDLE_VALUE)
+ return 0;
+
+ do
+ {
+ if(finddata.cFileName[0] != '.')
+ {
+ mir_sntprintf(lnk, MAX_PATH, _T("%s\\%s"), dir, finddata.cFileName);
+ if (ResolveShortcut(lnk, path))
+ {
+ // Add to list
+ ListEntry *le = new ListEntry();
+ le->filename = mir_tstrdup(path);
+ le->filelink = mir_tstrdup(lnk);
+
+ TCHAR *p = _tcschr(finddata.cFileName, _T('.'));
+ if (p != NULL)
+ p[0] = _T('\0');
+ max_pos = SendMessage(list, LB_ADDSTRING, 0, (LPARAM) finddata.cFileName);
+ SendMessage(list, LB_SETITEMDATA, max_pos, (LPARAM) le);
+ }
+ }
+ } while(FindNextFile(hFind, &finddata));
+ FindClose(hFind);
+ SendMessage(list, LB_SETCURSEL, max_pos, 0); // Set to first item
+ return 0;
+}
+
+
+
+int FillAvatarListFromDB(HWND list, HANDLE hContact)
+{
+ int max_pos = 0;
+ BYTE blob[2048];
+ HANDLE dbe = (HANDLE) CallService(MS_DB_EVENT_FINDFIRST, (WPARAM) hContact, 0);
+ while(dbe != NULL)
+ {
+ DBEVENTINFO dbei = {0};
+ dbei.cbSize = sizeof(dbei);
+ dbei.cbBlob = sizeof(blob);
+ dbei.pBlob = blob;
+ if (CallService(MS_DB_EVENT_GET, (WPARAM) dbe, (LPARAM) &dbei) == 0
+ && dbei.eventType == EVENTTYPE_AVATAR_CHANGE)
+ {
+
+ // Get last char from blob
+ int i = dbei.cbBlob - 2;
+ for(; i >= 0 && dbei.pBlob[i] != 0; i--) ;
+
+ if (i != (int) dbei.cbBlob - 2 && i >= 0)
+ {
+ // Oki, found one
+
+ // Get time
+ TCHAR date[64];
+ DBTIMETOSTRINGT tts = {0};
+ tts.szFormat = _T("d s");
+ tts.szDest = date;
+ tts.cbDest = sizeof(date);
+ CallService(MS_DB_TIME_TIMESTAMPTOSTRINGT, (WPARAM) dbei.timestamp, (LPARAM) &tts);
+
+ // Get file in disk
+ char path[MAX_PATH] = "";
+ CallService(MS_UTILS_PATHTOABSOLUTE,(WPARAM) (char *) &dbei.pBlob[i+1],(LPARAM)path);
+ TCHAR *filename = mir_a2t(path);
+
+ // Add to list
+ ListEntry *le = new ListEntry();
+ le->dbe = dbe;
+ le->filename = filename;
+
+ max_pos = SendMessage(list,LB_ADDSTRING, 0, (LPARAM) date);
+ SendMessage(list, LB_SETITEMDATA, max_pos, (LPARAM) le);
+ }
+ }
+
+ dbe = (HANDLE) CallService(MS_DB_EVENT_FINDNEXT, (WPARAM) dbe, 0);
+ }
+
+ SendMessage(list, LB_SETCURSEL, max_pos, 0); // Set to first item
+ return 0;
+}
+
+BOOL UpdateAvatarPic(HWND hwnd)
+{
+ HWND hwndpic = GetDlgItem(hwnd, IDC_AVATAR);
+ if (!hwnd || !hwndpic)
+ return -1;
+
+ HWND list = GetDlgItem(hwnd, IDC_AVATARLIST);
+ TCHAR *filename = GetCurrentSelFile(list);
+ if(!filename)
+ {
+ SetDlgItemText(hwnd,IDC_AVATARPATH,TranslateT("avatar path is null."));
+ return 0;
+ }
+ SetDlgItemText(hwnd,IDC_AVATARPATH,filename);
+
+ HBITMAP avpic = (HBITMAP) CallService(MS_IMG_LOAD, (WPARAM) filename, IMGL_TCHAR);
+
+ BOOL found_image = (avpic != NULL);
+
+ avpic = (HBITMAP)SendMessage(hwndpic, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)avpic);
+ if (avpic)
+ DeleteObject(avpic);
+
+ return found_image;
+}
+
+int CleanupAvatarPic(HWND hwnd)
+{
+ HWND hwndpic = GetDlgItem(hwnd, IDC_AVATAR);
+ if (!hwnd || !hwndpic)
+ return -1;
+
+ HBITMAP avpic = (HBITMAP)SendMessage(hwndpic, STM_GETIMAGE, 0, 0);
+ if(avpic)
+ DeleteObject(avpic);
+ return 0;
+}
+
+int PreBuildContactMenu(WPARAM wParam,LPARAM lParam)
+{
+ CLISTMENUITEM clmi = {0};
+ clmi.cbSize = sizeof(clmi);
+ clmi.flags = CMIM_FLAGS;
+
+ char *proto = (char*) CallService(MS_PROTO_GETCONTACTBASEPROTO, wParam, 0);
+ if (!ProtocolEnabled(proto))
+ clmi.flags |= CMIF_HIDDEN;
+
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) hMenu, (LPARAM) &clmi);
+
+ return 0;
+}
+
+void InitMenuItem()
+{
+ CLISTMENUITEM mi = {0};
+
+ hServices[2] = CreateServiceFunction(MS_AVATARHISTORY_SHOWDIALOG, ShowDialogSvc);
+
+ mi.cbSize = sizeof(mi);
+ mi.ptszName = LPGENT("View Avatar History");
+ mi.flags = CMIF_TCHAR;
+ mi.position = 1000090010;
+ mi.hIcon = createDefaultOverlayedIcon(FALSE);
+ mi.pszService = MS_AVATARHISTORY_SHOWDIALOG;
+ hMenu = (HANDLE)CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&mi);
+ DestroyIcon(mi.hIcon);
+}
+
+static INT_PTR ShowDialogSvc(WPARAM wParam, LPARAM lParam)
+{
+ OpenAvatarDialog((HANDLE)wParam, (char*)lParam);
+ return 0;
+}
+
+TCHAR* GetCurrentSelFile(HWND list)
+{
+ int cursel = SendMessage(list, LB_GETCURSEL, 0, 0);
+ if (cursel > -1)
+ return ((ListEntry*) SendMessage(list, LB_GETITEMDATA, cursel, 0))->filename;
+ else
+ return NULL;
+}
+
+int ShowSaveDialog(HWND hwnd, TCHAR* fn, HANDLE hContact)
+{
+ TCHAR filter[MAX_PATH];
+ TCHAR file[MAX_PATH];
+ OPENFILENAME ofn;
+ ZeroMemory(&ofn, sizeof(OPENFILENAME));
+ DBVARIANT dbvInitDir = {0};
+ bool ret = (DBGetContactSettingTString(hContact,MODULE_NAME,"SavedAvatarFolder",&dbvInitDir)== 0);
+ ofn.lStructSize = sizeof(OPENFILENAME);
+ ofn.hwndOwner = hwnd;
+ ofn.hInstance = hInst;
+
+ CallService(MS_UTILS_GETBITMAPFILTERSTRINGST, MAX_PATH, (LPARAM)filter);
+ ofn.lpstrFilter = filter;
+
+ ofn.nFilterIndex = 1;
+ lstrcpyn(file, _tcsrchr(fn, '\\')+1, sizeof(file));
+ ofn.lpstrFile = file;
+
+ TCHAR *displayName = (TCHAR*) CallService(MS_CLIST_GETCONTACTDISPLAYNAME,(WPARAM)hContact,GCDNF_TCHAR);
+ if(displayName)
+ {
+ TCHAR title[MAX_PATH];
+ mir_sntprintf(title,sizeof(title),TranslateT("Save Avatar for %s"),displayName);
+ ofn.lpstrTitle = title;
+ }
+ else
+ {
+ ofn.lpstrTitle = TranslateT("Save Avatar");
+ }
+ ofn.nMaxFile = MAX_PATH;
+ ofn.Flags = OFN_PATHMUSTEXIST | OFN_DONTADDTORECENT;
+ ofn.lpstrDefExt = _tcsrchr(fn, '.')+1;
+ if(ret)
+ {
+ ofn.lpstrInitialDir = dbvInitDir.ptszVal;
+ DBFreeVariant(&dbvInitDir);
+ }
+ else
+ {
+ ofn.lpstrInitialDir = _T(".");
+ }
+ if(GetSaveFileName(&ofn))
+ {
+ CopyFile(fn, file, FALSE);
+ DBWriteContactSettingTString(hContact,MODULE_NAME,"SavedAvatarFolder",file);
+ }
+ return 0;
+}
diff --git a/plugins/AvatarHistory/AvatarHistory.cpp b/plugins/AvatarHistory/AvatarHistory.cpp
new file mode 100644
index 0000000000..8dca674f77
--- /dev/null
+++ b/plugins/AvatarHistory/AvatarHistory.cpp
@@ -0,0 +1,999 @@
+/*
+Avatar History Plugin
+---------
+
+ This plugin uses the event provided by Avatar Service to
+ automatically back up contacts' avatars when they change.
+ Copyright (C) 2006 Matthew Wild - Email: mwild1@gmail.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.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+*/
+#include "AvatarHistory.h"
+
+HINSTANCE hInst;
+PLUGINLINK *pluginLink;
+DWORD mirVer;
+
+HANDLE hHooks[6] = {0};
+HANDLE hServices[3] = {0};
+
+HANDLE hFolder = NULL;
+
+char *metacontacts_proto = NULL;
+
+TCHAR profilePath[MAX_PATH]; // database profile path (read at startup only)
+TCHAR basedir[MAX_PATH];
+MM_INTERFACE mmi;
+UTF8_INTERFACE utfi;
+int hLangpack = 0;
+HANDLE hAvatarWindowsList = NULL;
+
+static int ModulesLoaded(WPARAM wParam, LPARAM lParam);
+static int PreShutdown(WPARAM wParam, LPARAM lParam);
+static int AvatarChanged(WPARAM wParam, LPARAM lParam);
+int OptInit(WPARAM wParam,LPARAM lParam);
+
+TCHAR * GetHistoryFolder(TCHAR *fn);
+TCHAR * GetProtocolFolder(TCHAR *fn, char *proto);
+TCHAR * GetOldStyleAvatarName(TCHAR *fn, HANDLE hContact);
+
+void InitMenuItem();
+
+void * GetHistoryEventText(HANDLE hContact, HANDLE hDbEvent, DBEVENTINFO *dbe, int format);
+
+// Services
+static INT_PTR IsEnabled(WPARAM wParam, LPARAM lParam);
+static INT_PTR GetCachedAvatar(WPARAM wParam, LPARAM lParam);
+TCHAR * GetCachedAvatar(char *proto, TCHAR *hash);
+BOOL CreateShortcut(TCHAR *file, TCHAR *shortcut);
+
+
+
+PLUGININFOEX pluginInfo={
+ sizeof(PLUGININFOEX),
+#ifdef _WIN64
+ "Avatar History (x64)",
+#elif _UNICODE
+ "Avatar History (Unicode)",
+#else
+ "Avatar History (Ansi)",
+#endif
+ PLUGIN_MAKE_VERSION(0,0,3,3),
+ "This plugin keeps backups of all your contacts' avatar changes and/or shows popups",
+ "Matthew Wild (MattJ), Ricardo Pescuma Domenecci",
+ "mwild1@gmail.com",
+ "© 2006-2012 Matthew Wild, Ricardo Pescuma Domenecci",
+ "http://pescuma.org/miranda/avatarhist",
+ UNICODE_AWARE,
+ 0, //doesn't replace anything built-in
+#ifdef _WIN64
+ { 0xe04702a2, 0x379, 0x4c69, { 0xbf, 0x8a, 0x84, 0xd5, 0xd0, 0xc9, 0x19, 0xcc } } // {E04702A2-0379-4C69-BF8A-84D5D0C919CC}
+#elif _UNICODE
+ { 0xdbe8c990, 0x7aa0, 0x458d, { 0xba, 0xb7, 0x33, 0xeb, 0x7, 0x23, 0x8e, 0x71 } } // {DBE8C990-7AA0-458d-BAB7-33EB07238E71}
+#else
+ { 0x4079923c, 0x8aa1, 0x4a2e, { 0x95, 0x8b, 0x9d, 0xc, 0xd0, 0xe8, 0x2e, 0xb2 } } // {4079923C-8AA1-4a2e-958B-9D0CD0E82EB2}
+#endif
+};
+
+extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
+{
+ hInst = hinstDLL;
+ return TRUE;
+}
+
+extern "C" __declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
+{
+ if(mirandaVersion < PLUGIN_MAKE_VERSION(0,9,50,3))
+ {
+ MessageBox(NULL,_T("AvatarHistory requires Miranda IM 0.9.50 or later."),_T("Avatar History"),MB_OK);
+ return NULL;
+ }
+ mirVer = mirandaVersion;
+ return &pluginInfo;
+}
+
+static const MUUID interfaces[] = { MIID_AVATAR_CHANGE_LOGGER, MIID_AVATAR_CHANGE_NOTIFIER, MIID_LAST };
+extern "C" __declspec(dllexport) const MUUID* MirandaPluginInterfaces(void)
+{
+ return interfaces;
+}
+
+static INT_PTR CALLBACK FirstRunDlgProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
+{
+ switch(uMsg)
+ {
+ case WM_INITDIALOG:
+ {
+ SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM) createDefaultOverlayedIcon(TRUE));
+ SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM) createDefaultOverlayedIcon(FALSE));
+ TranslateDialogDefault(hwnd);
+
+ CheckDlgButton(hwnd, IDC_MIR_PROTO, BST_CHECKED);
+ break;
+ }
+ case WM_COMMAND:
+ {
+ switch(LOWORD(wParam))
+ {
+ case IDOK:
+ {
+ int ret = 0;
+
+ if (IsDlgButtonChecked(hwnd, IDC_MIR_SAME))
+ ret = IDC_MIR_SAME;
+ else if (IsDlgButtonChecked(hwnd, IDC_MIR_PROTO))
+ ret = IDC_MIR_PROTO;
+ else if (IsDlgButtonChecked(hwnd, IDC_MIR_SHORT))
+ ret = IDC_MIR_SHORT;
+ else if (IsDlgButtonChecked(hwnd, IDC_SHORT))
+ ret = IDC_SHORT;
+ else if (IsDlgButtonChecked(hwnd, IDC_DUP))
+ ret = IDC_DUP;
+
+ EndDialog(hwnd, ret);
+ return TRUE;
+ }
+ }
+ break;
+ }
+ case WM_CLOSE:
+ {
+ EndDialog(hwnd, 0);
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+extern "C" int __declspec(dllexport) Load(PLUGINLINK *link)
+{
+ pluginLink=link;
+
+ if(mir_getMMI(&mmi))
+ {
+ MessageBox(NULL,_T("Avatar History"),_T("Miranda Memory manager not initialized, plugin cannot load.\nPlease update Miranda IM to the latest version."),MB_OK | MB_TOPMOST);
+ return 1;
+ }
+ if(mir_getUTFI(&utfi))
+ {
+ MessageBox(NULL,_T("Avatar History"),_T("Miranda UTF8 interface not initialized, plugin cannot load.\nPlease update Miranda IM to the latest version."),MB_OK | MB_TOPMOST);
+ return 1;
+ }
+ mir_getLP(&pluginInfo);
+
+ // Is first run?
+ if (DBGetContactSettingByte(NULL, MODULE_NAME, "FirstRun", 1))
+ {
+ // Show dialog
+ int ret = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_FIRST_RUN), NULL, FirstRunDlgProc, 0);
+ if (ret == 0)
+ return -1;
+
+ // Write settings
+
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "LogToDisk", 1);
+
+ if (ret == IDC_MIR_SAME)
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "LogKeepSameFolder", 1);
+ else
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "LogKeepSameFolder", 0);
+
+ if (ret == IDC_MIR_SHORT || ret == IDC_SHORT || ret == IDC_DUP)
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "LogPerContactFolders", 1);
+ else
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "LogPerContactFolders", 0);
+
+ if (ret == IDC_DUP)
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "StoreAsHash", 0);
+ else
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "StoreAsHash", 1);
+
+ if (ret == IDC_MIR_SAME || ret == IDC_MIR_PROTO || ret == IDC_MIR_SHORT)
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "LogToHistory", 1);
+ else
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "LogToHistory", 0);
+
+ DBWriteContactSettingByte(NULL, MODULE_NAME, "FirstRun", 0);
+ }
+
+ LoadOptions();
+
+ hHooks[0] = HookEvent(ME_SYSTEM_MODULESLOADED,ModulesLoaded);
+ hHooks[1] = HookEvent(ME_SYSTEM_PRESHUTDOWN, PreShutdown);
+ hHooks[3] = HookEvent(ME_OPT_INITIALISE, OptInit);
+ hHooks[4] = HookEvent(ME_SKIN2_ICONSCHANGED, IcoLibIconsChanged);
+ hHooks[5] = HookEvent(ME_CLIST_PREBUILDCONTACTMENU, PreBuildContactMenu);
+
+ hServices[0] = CreateServiceFunction(MS_AVATARHISTORY_ENABLED, IsEnabled);
+ hServices[1] = CreateServiceFunction(MS_AVATARHISTORY_GET_CACHED_AVATAR, GetCachedAvatar);
+
+ if(CallService(MS_DB_GETPROFILEPATHT, MAX_PATH, (LPARAM)profilePath) != 0)
+ _tcscpy(profilePath, _T(".")); // Failed, use current dir
+
+ SkinAddNewSoundExT("avatar_changed",LPGENT("Avatar History"),LPGENT("Contact changed avatar"));
+ SkinAddNewSoundExT("avatar_removed",LPGENT("Avatar History"),LPGENT("Contact removed avatar"));
+
+ hAvatarWindowsList = (HANDLE)CallService(MS_UTILS_ALLOCWINDOWLIST, 0, 0);
+
+ SetupIcoLib();
+ InitMenuItem();
+
+ return 0;
+}
+
+static int ModulesLoaded(WPARAM wParam, LPARAM lParam)
+{
+ mir_sntprintf(basedir, MAX_REGS(basedir), _T("%s\\Avatars History"), profilePath);
+
+ hFolder = FoldersRegisterCustomPathT(LPGEN("Avatars"), LPGEN("Avatar History"),
+ PROFILE_PATHT _T("\\") CURRENT_PROFILET _T("\\Avatars History"));
+ InitPopups();
+
+ if (ServiceExists(MS_MC_GETPROTOCOLNAME))
+ metacontacts_proto = (char *) CallService(MS_MC_GETPROTOCOLNAME, 0, 0);
+
+ // updater plugin support
+ if(ServiceExists(MS_UPDATE_REGISTER))
+ {
+ Update upd = {0};
+ char szCurrentVersion[30];
+
+ upd.cbSize = sizeof(upd);
+ upd.szComponentName = pluginInfo.shortName;
+
+ upd.szUpdateURL = UPDATER_AUTOREGISTER;
+
+ upd.szBetaVersionURL = "http://code.google.com/p/pescuma/downloads/list?q=label:Plugin-AVH";
+ upd.szBetaChangelogURL = "http://code.google.com/p/pescuma/source/list";
+#ifdef _WIN64
+ upd.pbBetaVersionPrefix = (BYTE *) "Avatar History (x64) ";
+ upd.szBetaUpdateURL = "http://pescuma.googlecode.com/files/avatarhistW.%VERSION%-x64.zip";
+#elif _UNICODE
+ upd.pbBetaVersionPrefix = (BYTE *) "Avatar History (Unicode) ";
+ upd.szBetaUpdateURL = "http://pescuma.googlecode.com/files/avatarhistW.%VERSION%.zip";
+#else
+ upd.pbBetaVersionPrefix = (BYTE *) "Avatar History (ANSI) ";
+ upd.szBetaUpdateURL = "http://pescuma.googlecode.com/files/avatarhist.%VERSION%.zip";
+#endif
+ upd.cpbBetaVersionPrefix = (int) strlen((char *)upd.pbBetaVersionPrefix);
+
+ upd.pbVersion = (BYTE *)CreateVersionStringPluginEx(&pluginInfo, szCurrentVersion);
+ upd.cpbVersion = (int) strlen((char *)upd.pbVersion);
+
+ CallService(MS_UPDATE_REGISTER, 0, (LPARAM)&upd);
+ }
+
+ if (DBGetContactSettingByte(NULL, MODULE_NAME, "LogToHistory", AVH_DEF_LOGTOHISTORY))
+ {
+ char *templates[] = { "Avatar change\nchanged his/her avatar",
+ "Avatar removal\nremoved his/her avatar" };
+ HICON hIcon = createDefaultOverlayedIcon(FALSE);
+ HistoryEvents_RegisterWithTemplates(MODULE_NAME, "avatarchange", "Avatar change", EVENTTYPE_AVATAR_CHANGE, hIcon,
+ HISTORYEVENTS_FORMAT_CHAR | HISTORYEVENTS_FORMAT_WCHAR | HISTORYEVENTS_FORMAT_RICH_TEXT,
+ HISTORYEVENTS_FLAG_SHOW_IM_SRMM | HISTORYEVENTS_FLAG_EXPECT_CONTACT_NAME_BEFORE,
+ GetHistoryEventText, templates, MAX_REGS(templates));
+ DestroyIcon(hIcon);
+ }
+
+ hHooks[2] = HookEvent(ME_AV_CONTACTAVATARCHANGED, AvatarChanged);
+
+ return 0;
+}
+
+static int PreShutdown(WPARAM wParam, LPARAM lParam)
+{
+ int i;
+
+ for (i = 0; i < MAX_REGS(hHooks); i++)
+ UnhookEvent(hHooks[i]);
+
+ for (i = 0; i < MAX_REGS(hServices); i++)
+ DestroyServiceFunction(hServices[i]);
+
+ WindowList_Broadcast(hAvatarWindowsList,WM_CLOSE,0,0);
+
+ return 0;
+}
+
+BOOL ProtocolEnabled(const char *proto)
+{
+ if (proto == NULL)
+ return FALSE;
+
+ char setting[256];
+ mir_snprintf(setting, sizeof(setting), "%sEnabled", proto);
+ return (BOOL) DBGetContactSettingByte(NULL, MODULE_NAME, setting, TRUE);
+}
+
+
+BOOL ContactEnabled(HANDLE hContact, char *setting, int def)
+{
+ if (hContact == NULL)
+ return FALSE;
+
+ char *proto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if (!ProtocolEnabled(proto))
+ return FALSE;
+
+ BYTE globpref = db_byte_get(NULL, MODULE_NAME, setting, def);
+ BYTE userpref = db_byte_get(hContact, MODULE_NAME, setting, BST_INDETERMINATE);
+
+ return (globpref && userpref == BST_INDETERMINATE) || userpref == BST_CHECKED;
+}
+
+// Returns true if the unicode buffer only contains 7-bit characters.
+BOOL IsUnicodeAscii(const WCHAR * pBuffer, int nSize)
+{
+ BOOL bResult = TRUE;
+ int nIndex;
+
+ for (nIndex = 0; nIndex < nSize; nIndex++) {
+ if (pBuffer[nIndex] > 0x7F) {
+ bResult = FALSE;
+ break;
+ }
+ }
+ return bResult;
+}
+
+void ConvertToFilename(TCHAR *str, size_t size) {
+ for(size_t i = 0; i < size && str[i] != '\0'; i++) {
+ switch(str[i]) {
+ case '/':
+ case '\\':
+ case ':':
+ case '*':
+ case '?':
+ case '"':
+ case '<':
+ case '>':
+ case '|':
+ //case '.':
+ str[i] = '_';
+ }
+ }
+}
+
+void ErrorExit(HANDLE hContact,LPTSTR lpszFunction)
+{
+ // Retrieve the system error message for the last-error code
+
+ LPVOID lpMsgBuf;
+ LPVOID lpDisplayBuf;
+ DWORD dw = GetLastError();
+
+ FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ dw,
+ MAKELANGID(LANG_GERMAN, SUBLANG_GERMAN),
+ (LPTSTR) &lpMsgBuf,
+ 0, NULL );
+
+ // Display the error message and exit the process
+
+ lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
+ (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
+ StringCchPrintf((LPTSTR)lpDisplayBuf,
+ LocalSize(lpDisplayBuf) / sizeof(TCHAR),
+ TEXT("%s failed with error %d: %s"),
+ lpszFunction, dw, lpMsgBuf);
+ ShowDebugPopup(hContact,TEXT("Error"), (LPCTSTR)lpDisplayBuf);
+
+ LocalFree(lpMsgBuf);
+ LocalFree(lpDisplayBuf);
+}
+
+#ifdef _UNICODE
+
+#define CS "%S"
+
+#else
+
+#define CS "%s"
+
+#endif
+
+
+TCHAR * GetExtension(TCHAR *file)
+{
+ if(file == NULL) return _T("");
+ TCHAR *ext = _tcsrchr(file, _T('.'));
+ if (ext != NULL)
+ ext++;
+ else
+ ext = _T("");
+
+ return ext;
+}
+
+
+void CreateOldStyleShortcut(HANDLE hContact, TCHAR *history_filename)
+{
+ TCHAR shortcut[MAX_PATH] = _T("");
+
+ GetOldStyleAvatarName(shortcut, hContact);
+
+ mir_sntprintf(shortcut, MAX_REGS(shortcut), _T("%s.%s.lnk"), shortcut,
+ GetExtension(history_filename));
+
+ if (!CreateShortcut(history_filename, shortcut))
+ {
+ ShowPopup(hContact, _T("Avatar History: Unable to create shortcut"), shortcut);
+ }
+ else
+ {
+ ShowDebugPopup(hContact, _T("AVH Debug: Shortcut created successfully"), shortcut);
+ }
+}
+
+
+BOOL CopyImageFile(TCHAR *old_file, TCHAR *new_file)
+{
+ TCHAR *ext = GetExtension(old_file);
+ mir_sntprintf(new_file, MAX_PATH, _T("%s.%s"), new_file, ext);
+
+ BOOL ret = CopyFile(old_file, new_file, TRUE);
+ if(!ret)
+ ErrorExit(NULL,_T("CopyImageFile"));
+ return !ret;
+}
+
+// fired when the contacts avatar changes
+// wParam = hContact
+// lParam = struct avatarCacheEntry *cacheEntry
+// the event CAN pass a NULL pointer in lParam which means that the avatar has changed,
+// but is no longer valid (happens, when a contact removes his avatar, for example).
+// DONT DESTROY the bitmap handle passed in the struct avatarCacheEntry *
+//
+// It is also possible that this event passes 0 as wParam (hContact), in which case,
+// a protocol picture (pseudo - avatar) has been changed.
+static int AvatarChanged(WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact = (HANDLE)wParam;
+ CONTACTAVATARCHANGEDNOTIFICATION* avatar = (CONTACTAVATARCHANGEDNOTIFICATION*)lParam;
+
+ if (hContact == NULL)
+ {
+ ShowDebugPopup(NULL, _T("AVH Debug"), _T("Invalid contact/avatar... skipping"));
+ return 0;
+ }
+
+ char *proto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, wParam, 0);
+ if (proto == NULL)
+ {
+ ShowDebugPopup(hContact, _T("AVH Debug"), _T("Invalid protocol... skipping"));
+ return 0;
+ }
+ else if (metacontacts_proto != NULL && strcmp(metacontacts_proto, proto) == 0)
+ {
+ ShowDebugPopup(hContact, _T("AVH Debug"), _T("Ignoring metacontacts notification"));
+ return 0;
+ }
+
+ DBVARIANT dbvOldHash = {0};
+ bool ret = (DBGetContactSettingTString(hContact,MODULE_NAME,"AvatarHash",&dbvOldHash) == 0);
+
+ if (avatar == NULL)
+ {
+ if (!ret || !_tcscmp(dbvOldHash.ptszVal, _T("-")))
+ {
+ //avoid duplicate "removed avatar" notifications
+ //do not notify on an empty profile
+ ShowDebugPopup(hContact, _T("AVH Debug"), _T("Removed avatar, no avatar before...skipping"));
+ DBFreeVariant(&dbvOldHash);
+ return 0;
+ }
+ SkinPlaySound("avatar_removed");
+
+ // Is a flash avatar or avs could not load it
+ DBWriteContactSettingTString(hContact, MODULE_NAME, "AvatarHash", _T("-"));
+
+ if (ContactEnabled(hContact, "AvatarPopups", AVH_DEF_AVPOPUPS) && opts.popup_show_removed)
+ ShowPopup(hContact, NULL, opts.popup_removed);
+
+ if (ContactEnabled(hContact, "LogToHistory", AVH_DEF_LOGTOHISTORY))
+ HistoryEvents_AddToHistorySimple(hContact, EVENTTYPE_AVATAR_CHANGE, 1, DBEF_READ);
+ }
+ else
+ {
+ if(ret && !_tcscmp(dbvOldHash.ptszVal, avatar->hash))
+ {
+ // same avatar hash, skipping
+ ShowDebugPopup(hContact, _T("AVH Debug"), _T("Hashes are the same... skipping"));
+ DBFreeVariant(&dbvOldHash);
+ return 0;
+ }
+ SkinPlaySound("avatar_changed");
+ DBWriteContactSettingTString(hContact, "AvatarHistory", "AvatarHash", avatar->hash);
+
+ TCHAR history_filename[MAX_PATH] = _T("");
+
+ if (ContactEnabled(hContact, "LogToDisk", AVH_DEF_LOGTODISK))
+ {
+ if (!opts.log_store_as_hash)
+ {
+ if (opts.log_per_contact_folders)
+ {
+ GetOldStyleAvatarName(history_filename, hContact);
+ if (CopyImageFile(avatar->filename, history_filename))
+ ShowPopup(hContact, _T("Avatar History: Unable to save avatar"), history_filename);
+ else
+ ShowDebugPopup(hContact, _T("AVH Debug: File copied successfully"), history_filename);
+
+ if (ServiceExists(MS_MC_GETMETACONTACT))
+ {
+ HANDLE hMetaContact = (HANDLE) CallService(MS_MC_GETMETACONTACT, wParam, 0);
+
+ if (hMetaContact != NULL && ContactEnabled(hMetaContact, "LogToDisk", AVH_DEF_LOGTOHISTORY))
+ {
+ TCHAR filename[MAX_PATH] = _T("");
+
+ GetOldStyleAvatarName(filename, hMetaContact);
+ if (CopyImageFile(avatar->filename, filename))
+ ShowPopup(hContact, _T("Avatar History: Unable to save avatar"), filename);
+ else
+ ShowDebugPopup(hContact, _T("AVH Debug: File copied successfully"), filename);
+ }
+ }
+ }
+ }
+ else
+ {
+ // See if we already have the avatar
+ TCHAR hash[128];
+ lstrcpyn(hash, avatar->hash, sizeof(hash));
+ ConvertToFilename(hash, sizeof(hash));
+
+ TCHAR *file = GetCachedAvatar(proto, hash);
+
+ if (file != NULL)
+ {
+ lstrcpyn(history_filename, file, MAX_REGS(history_filename));
+ mir_free(file);
+ }
+ else
+ {
+ if (opts.log_keep_same_folder)
+ GetHistoryFolder(history_filename);
+ else
+ GetProtocolFolder(history_filename, proto);
+
+ mir_sntprintf(history_filename, MAX_REGS(history_filename),
+ _T("%s\\%s"), history_filename, hash);
+
+ if (CopyImageFile(avatar->filename, history_filename))
+ ShowPopup(hContact, _T("Avatar History: Unable to save avatar"), history_filename);
+ else
+ ShowDebugPopup(hContact, _T("AVH Debug: File copied successfully"), history_filename);
+ }
+
+ if (opts.log_per_contact_folders)
+ {
+ CreateOldStyleShortcut(hContact, history_filename);
+
+ if (ServiceExists(MS_MC_GETMETACONTACT))
+ {
+ HANDLE hMetaContact = (HANDLE) CallService(MS_MC_GETMETACONTACT, wParam, 0);
+
+ if (hMetaContact != NULL && ContactEnabled(hMetaContact, "LogToDisk", AVH_DEF_LOGTOHISTORY))
+ CreateOldStyleShortcut(hMetaContact, history_filename);
+ }
+ }
+ }
+ }
+
+
+ if (ContactEnabled(hContact, "AvatarPopups", AVH_DEF_AVPOPUPS) && opts.popup_show_changed)
+ ShowPopup(hContact, NULL, opts.popup_changed);
+
+ if (ContactEnabled(hContact, "LogToHistory", AVH_DEF_LOGTOHISTORY))
+ {
+ TCHAR rel_path[MAX_PATH] = _T("");
+ CallService(MS_UTILS_PATHTORELATIVET,(WPARAM)history_filename,(LPARAM)rel_path);
+#ifdef _UNICODE
+ char *blob = mir_utf8encodeT(rel_path);
+ int flags = DBEF_READ | DBEF_UTF;
+#else
+ char *blob = mir_strdup(rel_path);
+ int flags = DBEF_READ;
+#endif
+ HistoryEvents_AddToHistoryEx(hContact, EVENTTYPE_AVATAR_CHANGE, 0, NULL, 0, (PBYTE) blob, (int) strlen(blob) + 1, flags);
+ }
+ }
+
+ return 0;
+}
+
+extern "C" int __declspec(dllexport) Unload(void)
+{
+ return 0;
+}
+
+
+static INT_PTR IsEnabled(WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact = (HANDLE) wParam;
+ return ContactEnabled(hContact, "LogToDisk", AVH_DEF_LOGTODISK)
+ || ContactEnabled(hContact, "AvatarPopups", AVH_DEF_AVPOPUPS)
+ || ContactEnabled(hContact, "LogToHistory", AVH_DEF_LOGTOHISTORY);
+}
+
+
+/*
+Get cached avatar
+
+wParam: (char *) protocol name
+lParam: (TCHAR *) hash
+return: (TCHAR *) NULL if none is found or the path to the avatar. You need to free this string
+ with mir_free.
+*/
+static INT_PTR GetCachedAvatar(WPARAM wParam, LPARAM lParam)
+{
+ TCHAR hash[128];
+ lstrcpyn(hash, (TCHAR *) lParam, sizeof(hash));
+ ConvertToFilename(hash, sizeof(hash));
+ return (INT_PTR) GetCachedAvatar((char *) wParam, hash);
+}
+
+TCHAR * GetCachedAvatar(char *proto, TCHAR *hash)
+{
+ TCHAR *ret = NULL;
+ TCHAR file[1024] = _T("");
+ TCHAR search[1024] = _T("");
+ if (opts.log_keep_same_folder)
+ GetHistoryFolder(file);
+ else
+ GetProtocolFolder(file, proto);
+
+ mir_sntprintf(search, MAX_REGS(search), _T("%s\\%s.*"), file, hash);
+
+ WIN32_FIND_DATA finddata;
+ HANDLE hFind = FindFirstFile(search, &finddata);
+ if (hFind == INVALID_HANDLE_VALUE)
+ return NULL;
+
+ do
+ {
+ size_t len = lstrlen(finddata.cFileName);
+ if (len > 4
+ && (!lstrcmpi(&finddata.cFileName[len-4], _T(".png"))
+ || !lstrcmpi(&finddata.cFileName[len-4], _T(".bmp"))
+ || !lstrcmpi(&finddata.cFileName[len-4], _T(".gif"))
+ || !lstrcmpi(&finddata.cFileName[len-4], _T(".jpg"))
+ || !lstrcmpi(&finddata.cFileName[len-5], _T(".jpeg"))))
+ {
+ mir_sntprintf(file, MAX_REGS(file), _T("%s\\%s"), file, finddata.cFileName);
+ ret = mir_tstrdup(file);
+ break;
+ }
+ } while(FindNextFile(hFind, &finddata));
+ FindClose(hFind);
+
+ return ret;
+}
+
+
+int GetUIDFromHContact(HANDLE contact, TCHAR* uinout, size_t uinout_len)
+{
+ CONTACTINFO cinfo;
+
+ ZeroMemory(&cinfo,sizeof(CONTACTINFO));
+ cinfo.cbSize = sizeof(CONTACTINFO);
+ cinfo.hContact = contact;
+ cinfo.dwFlag = CNF_UNIQUEID | CNF_TCHAR;
+
+ bool found = true;
+ if(CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&cinfo)==0)
+ {
+ if(cinfo.type == CNFT_ASCIIZ)
+ {
+ lstrcpyn(uinout, cinfo.pszVal, uinout_len);
+ // It is up to us to free the string
+ // The catch? We need to use Miranda's free(), not our CRT's :)
+ mir_free(cinfo.pszVal);
+ }
+ else if(cinfo.type == CNFT_DWORD)
+ {
+ _itot(cinfo.dVal,uinout,10);
+ }
+ else if(cinfo.type == CNFT_WORD)
+ {
+ _itot(cinfo.wVal,uinout,10);
+ }
+ else found = false;
+ }
+ else found = false;
+
+ if (!found)
+ {
+ lstrcpyn(uinout, TranslateT("Unknown UIN"),uinout_len);
+ }
+ return 0;
+}
+
+
+TCHAR * GetHistoryFolder(TCHAR *fn)
+{
+ if (fn == NULL) return NULL;
+ FoldersGetCustomPathT(hFolder, fn, MAX_PATH, basedir);
+ if(!CreateDirectory(fn, NULL))
+ ErrorExit(NULL,_T("GetHistoryFolder"));
+
+ return fn;
+}
+
+
+TCHAR * GetProtocolFolder(TCHAR *fn, char *proto)
+{
+ GetHistoryFolder(fn);
+
+ if (proto == NULL)
+ proto = Translate("Unknown Protocol");
+
+ mir_sntprintf(fn, MAX_PATH, _T("%s\\") _T(CS), fn, proto);
+ if(!CreateDirectory(fn, NULL))
+ ErrorExit(NULL,_T("CreateDirectory"));
+
+ return fn;
+}
+
+
+TCHAR * GetContactFolder(TCHAR *fn, HANDLE hContact)
+{
+ TCHAR uin[MAX_PATH];
+
+ char *proto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO,(WPARAM) hContact, 0);
+ GetProtocolFolder(fn, proto);
+
+ GetUIDFromHContact(hContact, uin, MAX_REGS(uin));
+ mir_sntprintf(fn, MAX_PATH, _T("%s\\%s"), fn, uin);
+ if(!CreateDirectory(fn, NULL))
+ ErrorExit(hContact,_T("CreateDirectory"));
+ ConvertToFilename(uin, sizeof(uin)); //added so that weather id's like "yw/CI0000" work
+
+#ifdef DBGPOPUPS
+ TCHAR log[1024];
+ mir_sntprintf(log, MAX_REGS(log), _T("Path: %s\nProto: ") _T(CS) _T("\nUIN: %s"), fn, proto, uin);
+ ShowPopup(hContact, _T("AVH Debug: GetContactFolder"), log);
+#endif
+
+ return fn;
+}
+
+TCHAR * GetOldStyleAvatarName(TCHAR *fn, HANDLE hContact)
+{
+ GetContactFolder(fn, hContact);
+
+ SYSTEMTIME curtime;
+ GetLocalTime(&curtime);
+ mir_sntprintf(fn, MAX_PATH,
+ _T("%s\\%04d-%02d-%02d %02dh%02dm%02ds"), fn,
+ curtime.wYear, curtime.wMonth, curtime.wDay,
+ curtime.wHour, curtime.wMinute, curtime.wSecond);
+ ShowDebugPopup(hContact,_T("AVH Debug: GetOldStyleAvatarName"),fn);
+ return fn;
+}
+
+BOOL CreateShortcut(TCHAR *file, TCHAR *shortcut)
+{
+ CoInitialize(NULL);
+
+ IShellLink* psl = NULL;
+
+ HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **) &psl);
+
+ if (SUCCEEDED(hr))
+ {
+ psl->SetPath(file);
+
+ IPersistFile* ppf = NULL;
+ hr = psl->QueryInterface(IID_IPersistFile, (void **) &ppf);
+
+ if (SUCCEEDED(hr))
+ {
+#ifdef _UNICODE
+ hr = ppf->Save(shortcut, TRUE);
+#else
+ WCHAR tmp[MAX_PATH];
+ MultiByteToWideChar(CP_ACP, 0, shortcut, -1, tmp, MAX_PATH);
+ hr = ppf->Save(tmp, TRUE);
+#endif
+ ppf->Release();
+ }
+
+ psl->Release();
+ }
+
+ if(FAILED(hr))
+ ErrorExit(NULL,_T("CreateShortcut"));
+ return SUCCEEDED(hr);
+}
+
+
+BOOL ResolveShortcut(TCHAR *shortcut, TCHAR *file)
+{
+ CoInitialize(NULL);
+
+ IShellLink* psl = NULL;
+
+ HRESULT hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void **) &psl);
+
+ if (SUCCEEDED(hr))
+ {
+ IPersistFile* ppf = NULL;
+ hr = psl->QueryInterface(IID_IPersistFile, (void **) &ppf);
+
+ if (SUCCEEDED(hr))
+ {
+#ifdef _UNICODE
+ hr = ppf->Load(shortcut, STGM_READ);
+#else
+ WCHAR tmp[MAX_PATH];
+ MultiByteToWideChar(CP_ACP, 0, shortcut, -1, tmp, MAX_PATH);
+ hr = ppf->Load(tmp, STGM_READ);
+#endif
+
+ if (SUCCEEDED(hr))
+ {
+ hr = psl->Resolve(NULL, SLR_UPDATE);
+
+ if (SUCCEEDED(hr))
+ {
+ WIN32_FIND_DATA wfd;
+ hr = psl->GetPath(file, MAX_PATH, &wfd, SLGP_RAWPATH);
+ }
+ }
+
+ ppf->Release();
+ }
+ psl->Release();
+ }
+
+ if(FAILED(hr))
+ ErrorExit(NULL,_T("CreateShortcut"));
+ return SUCCEEDED(hr);
+}
+
+
+template<class T>
+void ConvertToRTF(Buffer<char> *buffer, T *line)
+{
+ buffer->append("{\\uc1 ", 6);
+
+ for (; *line; line++)
+ {
+ if (*line == (T)'\r' && line[1] == (T)'\n') {
+ buffer->append("\\line ", 6);
+ line++;
+ }
+ else if (*line == (T)'\n') {
+ buffer->append("\\line ", 6);
+ }
+ else if (*line == (T)'\t') {
+ buffer->append("\\tab ", 5);
+ }
+ else if (*line == (T)'\\' || *line == (T)'{' || *line == (T)'}') {
+ buffer->append('\\');
+ buffer->append((char) *line);
+ }
+ else if (*line < 128) {
+ buffer->append((char) *line);
+ }
+ else
+ buffer->appendPrintf("\\u%d ?", *line);
+ }
+
+ buffer->append('}');
+}
+
+
+void GetRTFFor(Buffer<char> *buffer, HBITMAP hBitmap)
+{
+ BITMAP bmp;
+ GetObject(hBitmap, sizeof(bmp), &bmp);
+
+ DWORD dwLen = bmp.bmWidth * bmp.bmHeight * (bmp.bmBitsPixel / 8);
+ BYTE *p = (BYTE *) malloc(dwLen);
+ if (p == NULL)
+ return;
+
+ dwLen = GetBitmapBits(hBitmap, dwLen, p);
+
+ buffer->appendPrintf("{\\pict\\wbitmap0\\wbmbitspixel%u\\wbmplanes%u\\wbmwidthbytes%u\\picw%u\\pich%u ",
+ bmp.bmBitsPixel, bmp.bmPlanes, bmp.bmWidthBytes, bmp.bmWidth, bmp.bmHeight);
+
+ for (DWORD i = 0; i < dwLen; i++)
+ buffer->appendPrintf("%02X", p[i]);
+
+ buffer->append('}');
+
+
+/*
+ BITMAPINFOHEADER bih = { 0 };
+ HDC hdc = GetDC(NULL);
+ GetDIBits(hdc, hBitmap, 0, bmp.bmHeight, p, (BITMAPINFO *) & bih, DIB_RGB_COLORS);
+
+ buffer->appendPrintf("{\\pict\\wbitmap0\\wbmbitspixel%u\\wbmplanes%u\\wbmwidthbytes%u\\picw%u\\pich%u ",
+ bmp.bmBitsPixel, bmp.bmPlanes, bmp.bmWidthBytes, bmp.bmWidth, bmp.bmHeight);
+
+ DWORD i;
+ for (i = 0; i < sizeof(BITMAPINFOHEADER); i++)
+ buffer->appendPrintf("%02X", ((PBYTE) & bih)[i]);
+
+ for (i = 0; i < dwLen; i++)
+ buffer->appendPrintf("%02X", p[i]);
+
+ buffer->append('}');
+*/
+
+ free(p);
+}
+
+
+void * GetHistoryEventText(HANDLE hContact, HANDLE hDbEvent, DBEVENTINFO *dbe, int format)
+{
+ void *ret;
+
+ if (format & HISTORYEVENTS_FORMAT_CHAR)
+ {
+ ret = DbGetEventTextA(dbe, CP_ACP);
+ }
+ else if (format & HISTORYEVENTS_FORMAT_WCHAR)
+ {
+ ret = DbGetEventTextW(dbe, CP_ACP);
+ }
+ else if (format & HISTORYEVENTS_FORMAT_RICH_TEXT)
+ {
+ Buffer<char> buffer;
+
+ TCHAR *tmp = DbGetEventTextT(dbe, CP_ACP);
+ ConvertToRTF(&buffer, tmp);
+ mir_free(tmp);
+
+ // Load the image
+ size_t i;
+ for(i = dbe->cbBlob-2; i > 0 && dbe->pBlob[i] != 0; i--) ;
+ i++;
+
+ if (dbe->pBlob[i] != 0)
+ {
+ TCHAR absFile[MAX_PATH] = _T("");
+ CallService(MS_UTILS_PATHTOABSOLUTET,(WPARAM) &dbe->pBlob[i], (LPARAM)absFile);
+ if(absFile != NULL)
+ {
+ HBITMAP hBmp = (HBITMAP) CallService(MS_IMG_LOAD, (WPARAM) absFile, IMGL_TCHAR);
+
+ if (hBmp != NULL)
+ {
+ buffer.append("\\line ", 7);
+ GetRTFFor(&buffer, hBmp);
+ DeleteObject(hBmp);
+ }
+ }
+ }
+
+ buffer.append(' ');
+ buffer.pack();
+ ret = buffer.detach();
+ }
+
+ return ret;
+}
+
diff --git a/plugins/AvatarHistory/AvatarHistory.h b/plugins/AvatarHistory/AvatarHistory.h
new file mode 100644
index 0000000000..25ec454de2
--- /dev/null
+++ b/plugins/AvatarHistory/AvatarHistory.h
@@ -0,0 +1,109 @@
+#include <tchar.h>
+#include <windows.h>
+#include <stdio.h>
+#include <time.h>
+#include <strsafe.h>
+#include <commctrl.h> //for ImageList_*
+#include <prsht.h>
+#include <ShObjIdl.h>
+#include <ShlGuid.h>
+
+
+#define MIRANDA_VER 0x0900
+#include <newpluginapi.h>
+#include <m_clist.h>
+#include <m_skin.h>
+#include <m_avatars.h>
+#include <m_database.h>
+#include <m_system.h>
+#include <m_protosvc.h>
+#include <m_contacts.h>
+#include <m_popup.h>
+#include <m_options.h>
+#include <m_utils.h>
+#include <m_folders.h>
+#include <m_langpack.h>
+#include <m_metacontacts.h>
+#include <m_history.h>
+#include <m_updater.h>
+#include <m_imgsrvc.h>
+#include <m_icolib.h>
+
+// Globals
+extern HINSTANCE hInst;
+extern HANDLE hMenu;
+extern DWORD mirVer;
+extern HANDLE hAvatarWindowsList;
+
+#include "resource.h"
+#include "m_avatarhist.h"
+
+#include "../utils/mir_buffer.h"
+
+#include "../historyevents/m_historyevents.h"
+
+#define MODULE_NAME "AvatarHistory"
+
+#define AVH_DEF_POPUPFG 0
+#define AVH_DEF_POPUPBG 0x2DB6FF
+#define AVH_DEF_AVPOPUPS 0
+#define AVH_DEF_LOGTODISK 1
+#define AVH_DEF_LOGKEEPSAMEFOLDER 0
+#define AVH_DEF_LOGOLDSTYLE 0
+#define AVH_DEF_LOGTOHISTORY 1
+#define AVH_DEF_DEFPOPUPS 0
+#define AVH_DEF_SHOWMENU 1
+
+#define DEFAULT_TEMPLATE_REMOVED LPGENT("removed his/her avatar")
+#define DEFAULT_TEMPLATE_CHANGED LPGENT("changed his/her avatar")
+
+void LoadOptions();
+
+ // from icolib.cpp
+void SetupIcoLib();
+
+HICON createDefaultOverlayedIcon(BOOL big);
+HICON createProtoOverlayedIcon(HANDLE hContact);
+
+int PreBuildContactMenu(WPARAM wParam,LPARAM lParam);
+int IcoLibIconsChanged(WPARAM wParam,LPARAM lParam);
+
+int OpenAvatarDialog(HANDLE hContact, char* fn);
+
+#define MAX_REGS(_A_) ( sizeof(_A_) / sizeof(_A_[0]) )
+
+#define POPUP_ACTION_DONOTHING 0
+#define POPUP_ACTION_CLOSEPOPUP 1
+#define POPUP_ACTION_OPENAVATARHISTORY 2
+#define POPUP_ACTION_OPENHISTORY 3
+
+#define POPUP_DELAY_DEFAULT 0
+#define POPUP_DELAY_CUSTOM 1
+#define POPUP_DELAY_PERMANENT 2
+
+
+struct Options {
+ // Log
+ BOOL log_per_contact_folders;
+ BOOL log_keep_same_folder;
+ BOOL log_store_as_hash;
+
+ // Popup
+ BOOL popup_show_changed;
+ TCHAR popup_changed[1024];
+ BOOL popup_show_removed;
+ TCHAR popup_removed[1024];
+ WORD popup_delay_type;
+ WORD popup_timeout;
+ BYTE popup_use_win_colors;
+ BYTE popup_use_default_colors;
+ COLORREF popup_bkg_color;
+ COLORREF popup_text_color;
+ WORD popup_left_click_action;
+ WORD popup_right_click_action;
+};
+
+extern Options opts;
+
+
+#include "popup.h"
diff --git a/plugins/AvatarHistory/AvatarHistory.rc b/plugins/AvatarHistory/AvatarHistory.rc
new file mode 100644
index 0000000000..c9da3d1e39
--- /dev/null
+++ b/plugins/AvatarHistory/AvatarHistory.rc
@@ -0,0 +1,236 @@
+// Microsoft Visual C++ generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "afxres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// Neutral resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU)
+LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
+#pragma code_page(1252)
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Menu
+//
+
+IDR_MENU1 MENU
+BEGIN
+ POPUP "Avatar List Popup"
+ BEGIN
+ MENUITEM "Save As...", ID_AVATARLISTPOPUP_SAVEAS
+ MENUITEM "Delete this entry", ID_AVATARLISTPOPUP_DELETE
+ MENUITEM "Delete this entry and the bitmap file", ID_AVATARLISTPOPUP_DELETE_BOTH
+ END
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_AVATARDLG DIALOGEX 0, 0, 216, 195
+STYLE DS_SETFONT | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
+CAPTION "Avatar History"
+FONT 8, "MS Shell Dlg", 0, 0, 0x0
+BEGIN
+ LISTBOX IDC_AVATARLIST,7,7,110,74,LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+ CONTROL "",IDC_AVATAR,"Static",SS_BITMAP | SS_NOTIFY | SS_CENTERIMAGE | SS_REALSIZEIMAGE | SS_SUNKEN,125,7,84,74
+ LTEXT "Static",IDC_AVATARPATH,7,105,204,26
+ PUSHBUTTON "Open Folder",IDC_OPENFOLDER,6,81,49,14
+ PUSHBUTTON "<",IDC_BACK,138,82,31,10,BS_CENTER | BS_VCENTER
+ PUSHBUTTON ">",IDC_NEXT,172,82,31,10,BS_CENTER | BS_VCENTER
+ CONTROL "Store this user's old avatars in disk",IDC_LOGUSER,
+ "Button",BS_AUTO3STATE | WS_TABSTOP,7,135,202,10
+ CONTROL "Log this user's avatars changes to history",IDC_HISTORYUSER,
+ "Button",BS_AUTO3STATE | WS_TABSTOP,7,147,202,10
+ CONTROL "Show popups for this user",IDC_POPUPUSER,"Button",BS_AUTO3STATE | WS_TABSTOP,7,159,202,10
+ DEFPUSHBUTTON "OK",IDOK,73,169,50,14
+END
+
+IDD_OPTIONS DIALOGEX 0, 0, 314, 173
+STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_VISIBLE
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ GROUPBOX "Protocols",IDC_PROTOCOLS_G,3,3,308,157
+ LTEXT "Enable tracking for these protocols:",IDC_PROTOCOLS_L,13,17,157,11
+ CONTROL "List1",IDC_PROTOCOLS,"SysListView32",LVS_REPORT | LVS_SINGLESEL | LVS_SORTASCENDING | LVS_NOCOLUMNHEADER | LVS_NOSORTHEADER | WS_BORDER | WS_TABSTOP,12,31,158,119
+ LTEXT "MetaContacts have special handling: the info is always copied from subcontacts (notifications from a meta are ignored)",IDC_STATIC,181,31,124,119
+END
+
+IDD_POPUPS DIALOGEX 0, 0, 314, 235
+STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_VISIBLE
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ CONTROL "Show popup when a contact change his avatar",IDC_POPUPS,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,3,3,308,12
+ GROUPBOX "Colours",IDC_COLOURS_G,3,25,158,75
+ CONTROL "",IDC_BGCOLOR,"ColourPicker",WS_TABSTOP,12,37,34,14
+ LTEXT "Background colour",IDC_BGCOLOR_L,55,41,89,8
+ CONTROL "",IDC_TEXTCOLOR,"ColourPicker",WS_TABSTOP,12,55,34,14
+ LTEXT "Text colour",IDC_TEXTCOLOR_L,55,59,89,8
+ CONTROL "Use Windows colours",IDC_WINCOLORS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,74,132,10
+ CONTROL "Use default colours",IDC_DEFAULTCOLORS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,12,84,132,10
+ GROUPBOX "Delay",IDC_DELAY_G,166,25,145,75
+ CONTROL "From popup plugin",IDC_DELAYFROMPU,"Button",BS_AUTORADIOBUTTON | WS_GROUP,174,38,131,10
+ CONTROL "Custom",IDC_DELAYCUSTOM,"Button",BS_AUTORADIOBUTTON,174,52,131,10
+ CONTROL "Permanent",IDC_DELAYPERMANENT,"Button",BS_AUTORADIOBUTTON,174,82,131,10
+ EDITTEXT IDC_DELAY,208,65,31,14,ES_AUTOHSCROLL | ES_NUMBER
+ CONTROL "Spin1",IDC_DELAY_SPIN,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_ARROWKEYS | UDS_NOTHOUSANDS | UDS_HOTTRACK,239,67,11,11
+ GROUPBOX "Actions",IDC_ACTIONS_G,3,103,308,47
+ RTEXT "On right click:",IDC_RIGHT_ACTION_L,13,118,131,9
+ COMBOBOX IDC_RIGHT_ACTION,149,116,156,60,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
+ RTEXT "On left click:",IDC_LEFT_ACTION_L,13,132,131,9
+ COMBOBOX IDC_LEFT_ACTION,149,132,156,60,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
+ GROUPBOX "Track",IDC_TRACK_G,3,153,308,47
+ CONTROL "Avatar change:",IDC_CHANGED_L,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,166,89,10
+ EDITTEXT IDC_CHANGED,105,166,200,13,ES_AUTOHSCROLL
+ CONTROL "Avatar removal:",IDC_REMOVED_L,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,11,183,89,10
+ EDITTEXT IDC_REMOVED,105,183,200,13,ES_AUTOHSCROLL
+ PUSHBUTTON "Preview",IDC_PREV,132,206,50,14
+END
+
+IDD_FIRST_RUN DIALOGEX 0, 0, 451, 253
+STYLE DS_SETFONT | DS_MODALFRAME | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
+CAPTION "Avatar History: Select how to store history avatars"
+FONT 8, "MS Shell Dlg", 0, 0, 0x0
+BEGIN
+ LTEXT "Please select how the avatar history should be stored. This setting can NOT be changed in future, because it would cause all previous history to be lost.",IDC_STATIC,15,7,416,23
+ CONTROL "Store history in miranda history and all history avatars in same folder",IDC_MIR_SAME,
+ "Button",BS_AUTORADIOBUTTON | WS_GROUP,15,32,416,11
+ CONTROL "Store history in miranda history and history avatars in per protocol folders",IDC_MIR_PROTO,
+ "Button",BS_AUTORADIOBUTTON,15,66,416,11
+ CONTROL "Store history in miranda history and history avatars in per contact folders using shortcuts",IDC_MIR_SHORT,
+ "Button",BS_AUTORADIOBUTTON,15,99,416,11
+ CONTROL "Store history avatars in per contact folders using shortcuts",IDC_SHORT,
+ "Button",BS_AUTORADIOBUTTON,15,140,416,11
+ CONTROL "Store history avatars in per contact folders",IDC_DUP,
+ "Button",BS_AUTORADIOBUTTON,15,181,416,11
+ LTEXT "History is stored inside miranda db. It can be seen by History++ or Avatar History internal viewer.",IDC_STATIC,15,44,416,10
+ LTEXT "All avatars are stored as <Profile>\\Avatars History\\<Avatar Hash>",IDC_STATIC,15,54,416,10
+ LTEXT "History is stored inside miranda db. It can be seen by History++ or Avatar History internal viewer.",IDC_STATIC,15,77,416,10
+ LTEXT "All avatars are stored as <Profile>\\Avatars History\\<Protocol>\\<Avatar Hash>",IDC_STATIC,15,87,416,10
+ LTEXT "History is stored inside miranda db. It can be seen by History++ or Avatar History internal viewer.",IDC_STATIC,15,110,416,10
+ LTEXT "All avatars are stored as <Profile>\\Avatars History\\<Protocol>\\<Avatar Hash> and have a shortcut per history entry in <Profile>\\Avatars History\\<Protocol>\\<Contact ID>\\<Timestamp>",IDC_STATIC,15,120,416,18
+ LTEXT "History is stored only in disk. It can be seen by Avatar History internal viewer.",IDC_STATIC,15,151,416,10
+ LTEXT "All avatars are stored as <Profile>\\Avatars History\\<Protocol>\\<Avatar Hash> and have a shortcut per history entry in <Profile>\\Avatars History\\<Protocol>\\<Contact ID>\\<Timestamp>",IDC_STATIC,15,161,416,18
+ LTEXT "History is stored only in disk. It can be seen by Avatar History internal viewer.",IDC_STATIC,15,192,416,10
+ LTEXT "All avatars are stored as <Profile>\\Avatars History\\<Protocol>\\<Contact ID>\\<Timestamp> (the same image can be stored lot of times)",IDC_STATIC,15,203,416,18
+ DEFPUSHBUTTON "OK",IDOK,151,232,50,14
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO
+BEGIN
+ IDD_AVATARDLG, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 209
+ VERTGUIDE, 203
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 159
+ END
+
+ IDD_OPTIONS, DIALOG
+ BEGIN
+ LEFTMARGIN, 3
+ RIGHTMARGIN, 311
+ TOPMARGIN, 3
+ BOTTOMMARGIN, 171
+ HORZGUIDE, 150
+ END
+
+ IDD_POPUPS, DIALOG
+ BEGIN
+ LEFTMARGIN, 3
+ RIGHTMARGIN, 311
+ VERTGUIDE, 12
+ VERTGUIDE, 144
+ VERTGUIDE, 174
+ VERTGUIDE, 305
+ TOPMARGIN, 3
+ BOTTOMMARGIN, 225
+ END
+
+ IDD_FIRST_RUN, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 443
+ VERTGUIDE, 15
+ VERTGUIDE, 431
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 246
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+#endif // Neutral resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+/////////////////////////////////////////////////////////////////////////////
+// English (United Kingdom) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG)
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK
+#pragma code_page(1252)
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+#endif // English (United Kingdom) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/plugins/AvatarHistory/AvatarHistory.vcxproj b/plugins/AvatarHistory/AvatarHistory.vcxproj
new file mode 100644
index 0000000000..e5b0fb0b25
--- /dev/null
+++ b/plugins/AvatarHistory/AvatarHistory.vcxproj
@@ -0,0 +1,564 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Unicode Debug|Win32">
+ <Configuration>Unicode Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Unicode Debug|x64">
+ <Configuration>Unicode Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Unicode Release|Win32">
+ <Configuration>Unicode Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Unicode Release|x64">
+ <Configuration>Unicode Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <SccProjectName />
+ <SccLocalPath />
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Debug|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Debug|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Debug|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <LinkIncremental>true</LinkIncremental>
+ <TargetName>avatarhistW</TargetName>
+ <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\Plugins\</OutDir>
+ <IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <LinkIncremental>true</LinkIncremental>
+ <TargetName>avatarhistW</TargetName>
+ <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\Plugins\</OutDir>
+ <IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Debug|Win32'">
+ <LinkIncremental>true</LinkIncremental>
+ <TargetName>avatarhistW</TargetName>
+ <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\Plugins\</OutDir>
+ <IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Debug|x64'">
+ <LinkIncremental>true</LinkIncremental>
+ <TargetName>avatarhistW</TargetName>
+ <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\Plugins\</OutDir>
+ <IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <LinkIncremental>false</LinkIncremental>
+ <TargetName>avatarhistW</TargetName>
+ <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\Plugins\</OutDir>
+ <IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <LinkIncremental>false</LinkIncremental>
+ <TargetName>avatarhistW</TargetName>
+ <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\Plugins\</OutDir>
+ <IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|Win32'">
+ <LinkIncremental>false</LinkIncremental>
+ <TargetName>avatarhistW</TargetName>
+ <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\Plugins\</OutDir>
+ <IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|x64'">
+ <LinkIncremental>false</LinkIncremental>
+ <TargetName>avatarhistW</TargetName>
+ <IntDir>$(SolutionDir)obj\$(Platform)\$(Configuration)\</IntDir>
+ <OutDir>$(SolutionDir)$(Platform)\$(Configuration)\Plugins\</OutDir>
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <InlineFunctionExpansion>Default</InlineFunctionExpansion>
+ <FunctionLevelLinking>false</FunctionLevelLinking>
+ <Optimization>Disabled</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <MinimalRebuild>true</MinimalRebuild>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ <AdditionalIncludeDirectories>../../include;sdk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>DBGPOPUPS;WIN32;_DEBUG;_WINDOWS;_USRDLL;AvatarHistory_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BrowseInformation>false</BrowseInformation>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <PrecompiledHeaderFile>AvatarHistory.h</PrecompiledHeaderFile>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Debug\AvatarHistory.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(IntDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Console</SubSystem>
+ <ImportLibrary>.\Debug\avatarhist.lib</ImportLibrary>
+ <AdditionalDependencies>comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
+ </Link>
+ <PostBuildEvent>
+ <Command>if not exist "$(OutputPath)Docs\" mkdir "$(OutputPath)Docs\"
+copy "$(ProjectDir)Docs\*.*" "$(OutputPath)Docs\"</Command>
+ </PostBuildEvent>
+ <PostBuildEvent>
+ <Message>Preparing Release</Message>
+ </PostBuildEvent>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <InlineFunctionExpansion>Default</InlineFunctionExpansion>
+ <FunctionLevelLinking>false</FunctionLevelLinking>
+ <Optimization>Disabled</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <AdditionalIncludeDirectories>../../include;sdk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>DBGPOPUPS;_WIN64;_DEBUG;_WINDOWS;_USRDLL;AvatarHistory_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BrowseInformation>false</BrowseInformation>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <PrecompiledHeaderFile>AvatarHistory.h</PrecompiledHeaderFile>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Debug\AvatarHistory.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(IntDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Console</SubSystem>
+ <ImportLibrary>.\Debug\avatarhist.lib</ImportLibrary>
+ <AdditionalDependencies>comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
+ </Link>
+ <PostBuildEvent>
+ <Command>if not exist "$(OutputPath)Docs\" mkdir "$(OutputPath)Docs\"
+copy "$(ProjectDir)Docs\*.*" "$(OutputPath)Docs\"</Command>
+ </PostBuildEvent>
+ <PostBuildEvent>
+ <Message>Preparing Release</Message>
+ </PostBuildEvent>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Debug|Win32'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <InlineFunctionExpansion>Default</InlineFunctionExpansion>
+ <FunctionLevelLinking>false</FunctionLevelLinking>
+ <Optimization>Disabled</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <MinimalRebuild>true</MinimalRebuild>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ <AdditionalIncludeDirectories>../../include;sdk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>DBGPOPUPS;WIN32;_DEBUG;_WINDOWS;_UNICODE;UNICODE;_USRDLL;AvatarHistory_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BrowseInformation>false</BrowseInformation>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <PrecompiledHeaderFile>AvatarHistory.h</PrecompiledHeaderFile>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Unicode_Debug\AvatarHistory.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(IntDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Console</SubSystem>
+ <AdditionalDependencies>comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
+ </Link>
+ <PostBuildEvent>
+ <Command>if not exist "$(OutputPath)Docs\" mkdir "$(OutputPath)Docs\"
+copy "$(ProjectDir)Docs\*.*" "$(OutputPath)Docs\"</Command>
+ </PostBuildEvent>
+ <PostBuildEvent>
+ <Message>Preparing Release</Message>
+ </PostBuildEvent>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Debug|x64'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <InlineFunctionExpansion>Default</InlineFunctionExpansion>
+ <FunctionLevelLinking>false</FunctionLevelLinking>
+ <Optimization>Disabled</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <AdditionalIncludeDirectories>../../include;sdk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>DBGPOPUPS;_WIN64;_DEBUG;_WINDOWS;_UNICODE;UNICODE;_USRDLL;AvatarHistory_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BrowseInformation>false</BrowseInformation>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <PrecompiledHeaderFile>AvatarHistory.h</PrecompiledHeaderFile>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Unicode_Debug\AvatarHistory.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(IntDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Console</SubSystem>
+ <AdditionalDependencies>comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
+ </Link>
+ <PostBuildEvent>
+ <Command>if not exist "$(OutputPath)Docs\" mkdir "$(OutputPath)Docs\"
+copy "$(ProjectDir)Docs\*.*" "$(OutputPath)Docs\"</Command>
+ </PostBuildEvent>
+ <PostBuildEvent>
+ <Message>Preparing Release</Message>
+ </PostBuildEvent>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <StringPooling>true</StringPooling>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <Optimization>MinSpace</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <AdditionalIncludeDirectories>../../include;sdk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;AvatarHistory_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BrowseInformation>false</BrowseInformation>
+ <PrecompiledHeaderFile>AvatarHistory.h</PrecompiledHeaderFile>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Release\AvatarHistory.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(IntDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <SubSystem>Console</SubSystem>
+ <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+ <AdditionalDependencies>comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <GenerateDebugInformation>false</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
+ </Link>
+ <PostBuildEvent>
+ <Command>if not exist "$(OutputPath)Docs\" mkdir "$(OutputPath)Docs\"
+copy "$(ProjectDir)Docs\*.*" "$(OutputPath)Docs\"</Command>
+ </PostBuildEvent>
+ <PostBuildEvent>
+ <Message>Preparing Release</Message>
+ </PostBuildEvent>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <StringPooling>true</StringPooling>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <Optimization>MinSpace</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <AdditionalIncludeDirectories>../../include;sdk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>_WIN64;NDEBUG;_WINDOWS;_USRDLL;AvatarHistory_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BrowseInformation>false</BrowseInformation>
+ <PrecompiledHeaderFile>AvatarHistory.h</PrecompiledHeaderFile>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Release\AvatarHistory.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(IntDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <SubSystem>Console</SubSystem>
+ <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+ <ImportLibrary>.\Release\avatarhist.lib</ImportLibrary>
+ <AdditionalDependencies>comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <GenerateDebugInformation>false</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
+ </Link>
+ <PostBuildEvent>
+ <Command>if not exist "$(OutputPath)Docs\" mkdir "$(OutputPath)Docs\"
+copy "$(ProjectDir)Docs\*.*" "$(OutputPath)Docs\"</Command>
+ </PostBuildEvent>
+ <PostBuildEvent>
+ <Message>Preparing Release</Message>
+ </PostBuildEvent>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|Win32'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <StringPooling>true</StringPooling>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <Optimization>MinSpace</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <AdditionalIncludeDirectories>../../include;sdk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_UNICODE;UNICODE;_USRDLL;AvatarHistory_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BrowseInformation>false</BrowseInformation>
+ <PrecompiledHeaderFile>AvatarHistory.h</PrecompiledHeaderFile>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Unicode_Release\AvatarHistory.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(IntDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <SubSystem>Console</SubSystem>
+ <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+ <AdditionalDependencies>comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <GenerateDebugInformation>false</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
+ </Link>
+ <PostBuildEvent>
+ <Command>if not exist "$(OutputPath)Docs\" mkdir "$(OutputPath)Docs\"
+copy "$(ProjectDir)Docs\*.*" "$(OutputPath)Docs\"</Command>
+ </PostBuildEvent>
+ <PostBuildEvent>
+ <Message>Preparing Release</Message>
+ </PostBuildEvent>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Unicode Release|x64'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <StringPooling>true</StringPooling>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <Optimization>MinSpace</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <AdditionalIncludeDirectories>../../include;sdk;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>_WIN64;NDEBUG;_WINDOWS;_UNICODE;UNICODE;_USRDLL;AvatarHistory_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BrowseInformation>false</BrowseInformation>
+ <PrecompiledHeaderFile>AvatarHistory.h</PrecompiledHeaderFile>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Unicode_Release\AvatarHistory.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(IntDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <SubSystem>Console</SubSystem>
+ <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+ <AdditionalDependencies>comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
+ <GenerateDebugInformation>false</GenerateDebugInformation>
+ </Link>
+ <PostBuildEvent>
+ <Command>if not exist "$(OutputPath)Docs\" mkdir "$(OutputPath)Docs\"
+copy "$(ProjectDir)Docs\*.*" "$(OutputPath)Docs\"</Command>
+ </PostBuildEvent>
+ <PostBuildEvent>
+ <Message>Preparing Release</Message>
+ </PostBuildEvent>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="AvatarDlg.cpp" />
+ <ClCompile Include="AvatarHistory.cpp" />
+ <ClCompile Include="icolib.cpp" />
+ <ClCompile Include="..\utils\mir_options.cpp" />
+ <ClCompile Include="options.cpp" />
+ <ClCompile Include="popup.cpp" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="AvatarHistory.h" />
+ <ClInclude Include="m_avatarhist.h" />
+ <ClInclude Include="..\utils\mir_buffer.h" />
+ <ClInclude Include="..\utils\mir_memory.h" />
+ <ClInclude Include="..\utils\mir_options.h" />
+ <ClInclude Include="popup.h" />
+ <ClInclude Include="resource.h" />
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="AvatarHistory.rc" />
+ </ItemGroup>
+ <ItemGroup>
+ <CustomBuild Include="Docs\avatarhist_changelog.txt" />
+ <CustomBuild Include="Docs\avatarhist_readme.txt" />
+ <CustomBuild Include="Docs\avatarhist_version.txt" />
+ <CustomBuild Include="Docs\langpack_avatarhist.txt" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project> \ No newline at end of file
diff --git a/plugins/AvatarHistory/AvatarHistory.vcxproj.filters b/plugins/AvatarHistory/AvatarHistory.vcxproj.filters
new file mode 100644
index 0000000000..b405a21122
--- /dev/null
+++ b/plugins/AvatarHistory/AvatarHistory.vcxproj.filters
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup>
+ <Filter Include="Source Files">
+ <UniqueIdentifier>{82b52cc9-91bf-46bb-b045-52e8df41b13d}</UniqueIdentifier>
+ <Extensions>cpp;c;cxx;rc;def;r;odl;idl;hpj;bat</Extensions>
+ </Filter>
+ <Filter Include="Header Files">
+ <UniqueIdentifier>{e28f6fa3-76df-4c8d-8454-ee929e07f290}</UniqueIdentifier>
+ <Extensions>h;hpp;hxx;hm;inl</Extensions>
+ </Filter>
+ <Filter Include="Resource Files">
+ <UniqueIdentifier>{6ad471fb-470c-4466-b817-ec90cb51260c}</UniqueIdentifier>
+ <Extensions>ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe</Extensions>
+ </Filter>
+ <Filter Include="Docs">
+ <UniqueIdentifier>{72021e6b-0e9b-4cf3-b35f-db87ed4f6541}</UniqueIdentifier>
+ </Filter>
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="AvatarDlg.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="AvatarHistory.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="icolib.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="..\utils\mir_options.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="options.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="popup.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="AvatarHistory.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="m_avatarhist.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="..\utils\mir_buffer.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="..\utils\mir_memory.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="..\utils\mir_options.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="popup.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="resource.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="AvatarHistory.rc">
+ <Filter>Resource Files</Filter>
+ </ResourceCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <CustomBuild Include="Docs\avatarhist_changelog.txt">
+ <Filter>Docs</Filter>
+ </CustomBuild>
+ <CustomBuild Include="Docs\avatarhist_readme.txt">
+ <Filter>Docs</Filter>
+ </CustomBuild>
+ <CustomBuild Include="Docs\avatarhist_version.txt">
+ <Filter>Docs</Filter>
+ </CustomBuild>
+ <CustomBuild Include="Docs\langpack_avatarhist.txt">
+ <Filter>Docs</Filter>
+ </CustomBuild>
+ </ItemGroup>
+</Project> \ No newline at end of file
diff --git a/plugins/AvatarHistory/AvatarOverlay.ico b/plugins/AvatarHistory/AvatarOverlay.ico
new file mode 100644
index 0000000000..63557bad99
--- /dev/null
+++ b/plugins/AvatarHistory/AvatarOverlay.ico
Binary files differ
diff --git a/plugins/AvatarHistory/Docs/avatarhist.png b/plugins/AvatarHistory/Docs/avatarhist.png
new file mode 100644
index 0000000000..e9619f63a0
--- /dev/null
+++ b/plugins/AvatarHistory/Docs/avatarhist.png
Binary files differ
diff --git a/plugins/AvatarHistory/Docs/avatarhist_changelog.txt b/plugins/AvatarHistory/Docs/avatarhist_changelog.txt
new file mode 100644
index 0000000000..8689c4b656
--- /dev/null
+++ b/plugins/AvatarHistory/Docs/avatarhist_changelog.txt
@@ -0,0 +1,78 @@
+Avatar History
+
+Changelog:
+
+. 0.0.3.3
++ Added Updater support
+
+. 0.0.3.2
+-Show contact display name in save dialog
+-Added hidden debug setting:
+Add BYTE "Debug" in "AvatarHistory" module to show debug popups.
+ATTENTION: This is only recommended for advanced users to find problems,
+in normal usage they tend to become annoying
+-Fixed popups for removed avatars
+-Updated m_folders.h
+-Allow plugin to load in Miranda 0.9.50
+
+
+. 0.0.3.1
++ Show Contact Name in Avatar History dialog title
++ Show picture path in avatar history dialog
++ support for WindowList
+* fixed some issues reported by borkra
++ updated m_folders.h
+* fixed duplicate avatar notifications (thanks xaos)
+
+. 0.0.3.0
+THIS REQUIRES MIRANDA IM 0.10 ALPHA #3 OR ABOVE!!
+ + added x64 version
+ + improved unicode support
+ + added sounds
+ + added more debug information
+ * save position of avatar history dialog
+ ! fixed crash with empty avatar history
+ * BMP files are not converted to PNG any more
+ * fixed Updater support
+
+
+. 0.0.2.10
+ * Fix for get event text
+
+. 0.0.2.9
+ + Depends on history events to add events to history
+
+. 0.0.2.8
+ * Fix for radios in first run dialog
+
+. 0.0.2.7
+ + Added first run dialog and option to store avatars as version 1
+ * Changed to stop using avs services and use freeiamge services (requires miranda 0.7 #28)
+
+. 0.0.2.6
+ * Changed to always use online proto icon as base for popup icon
+
+. 0.0.2.5
+ + Added support for Miranda 0.8
+
+. 0.0.2.4
+ * Try to fix blank images
+
+. 0.0.2.3
+ + Hide contact menu item for disabled protocols
+ + Create shortcuts for metacontacts if it is a enabled protocol
+
+. 0.0.2.2
+ * Bug fixes (thanks borkra)
+ + Use shortcuts in avatar history dialog when history log is disabled (thanks Let)
+ + Option to delete only the entry or it and the avatar image
+ * Moved default place of menu entry to bellow View History
+ * Using default Miranda icon for History if possible
+ * Using icon based on avs for overlay
+ * Small changes in options dialog
+
+. 0.0.2.0
+ * Changed to store avatars in a proto dir (lost compatibility with old version)
+ * Changes in options and avatar dialog
+ + Keep only one copy of an image (even if contact switchs back to it)
+ + Updater support \ No newline at end of file
diff --git a/plugins/AvatarHistory/Docs/avatarhist_readme.txt b/plugins/AvatarHistory/Docs/avatarhist_readme.txt
new file mode 100644
index 0000000000..b07d99ee40
--- /dev/null
+++ b/plugins/AvatarHistory/Docs/avatarhist_readme.txt
@@ -0,0 +1,29 @@
+Avatar History plugin
+-----------------------------------
+
+CAUTION: THIS IS AN BETA STAGE PLUGIN. IT CAN DO VERY BAD THINGS. USE AT YOUR OWN RISK.
+
+This plugins keep a history of contact avatars. It stores the files on the disk and uses miranda history to keep track of then.
+
+This plugin is really made by MattJ, I'm only doing some changes to allow better handling of the avatars.
+
+If you want to import the old history to new format, you can use the Avatar History Importer plugin by TioDuke. It will import old avatars to new format, allowing to keep only one copy of each avatar (but new avatars may appear duplicated, because the hash function used by the importer may not be the same as the one used by the protocol). It can be downloaded at:
+Avatar History Importer Ansi Dll: http://pescuma.mirandaim.ru/miranda/avh_imp.zip
+Avatar History Importer Unicode Dll: http://pescuma.mirandaim.ru/miranda/avh_impW.zip
+Avatar History Importer Source: http://pescuma.mirandaim.ru/miranda/avh_imp_src.zip
+
+To user the importer, you should:
+1. Backup your profile and the old avatar history folder
+2. Install the new version of Avatar History
+3. Start miranda with all protocols offline
+4. Setup Avatar History options (some are better if set once and not changed anymore). You will need 'Show expert options' checkbox enabled
+5. Finish miranda and install Avatar History Importer
+6. Start miranda with all protocols offline
+7. A messagebox will appear, telling that the importer will run. Wait until the importer ended messagebox.
+8. Enjoy ;)
+
+Now all avatars are stored in per protocol folders. This is done to allow avoiding duplicated avatars. (If you enable 'Keep all in same folder' there will be only one folder for all protocols - this may help in case you have more than one instance of the same proto). The relation avatar <-> contact and the avatar history dialog is created from info from the contact history (and not using the files in HD). Since some people like to see the images in contacts folders, there is the option 'Also create per contact folders with shortcuts'. This option will create the contact folders (as previous version) and will create shortcuts inside it to the avatar stored in the protocol folder (if 2 avatars are the same, there will be 2 shortcuts but only one avatar in disk). Importer will use this option too when importing, but you must set it before importing everything.
+
+This plugin needs Avatar Service and Miranda 0.7 to be able to work. To log events to history it needs History Events plugin.
+
+To report bugs/make suggestions, go to the forum thread: http://forums.miranda-im.org/showthread.php?t=9118
diff --git a/plugins/AvatarHistory/Docs/avatarhist_version.txt b/plugins/AvatarHistory/Docs/avatarhist_version.txt
new file mode 100644
index 0000000000..7ed8590d76
--- /dev/null
+++ b/plugins/AvatarHistory/Docs/avatarhist_version.txt
@@ -0,0 +1 @@
+Avatar History 0.0.2.10 \ No newline at end of file
diff --git a/plugins/AvatarHistory/Docs/langpack_avatarhist.txt b/plugins/AvatarHistory/Docs/langpack_avatarhist.txt
new file mode 100644
index 0000000000..2bad91ae78
--- /dev/null
+++ b/plugins/AvatarHistory/Docs/langpack_avatarhist.txt
@@ -0,0 +1,114 @@
+; Avatar History
+; Author: MattJ and Pescuma
+
+[Avatar History]
+
+; Menu
+
+[View Avatar History]
+
+; Custom folders
+
+[Avatars]
+
+; Options
+
+[History]
+[Avatar]
+
+[ Logging options ]
+[Store old avatars on disk]
+[Also create per contact folders with shortcuts]
+[Log avatar changes to history]
+
+[ History templates ]
+[Avatar change:]
+[Track when contacts remove their avatars too]
+[Avatar removal:]
+
+[ Protocols ]
+[Enable tracking for these protocols:]
+[Keep all in same folder]
+
+[Popups]
+[Avatar Change]
+
+[Show popup when a contact change his avatar]
+
+[ Colours ]
+[Background colour]
+[Text colour]
+[Use Windows colours]
+[Use default colours]
+
+[ Delay ]
+[From popup plugin]
+[Custom]
+[Permanent]
+
+[ Actions ]
+[On right click:]
+[On left click:]
+[Do nothing]
+[Close popup]
+[Show avatar history]
+[Show contact history]
+
+[Preview]
+
+
+; Test popup
+
+[Test Contact]
+[Test description]
+
+
+; First run dialog
+
+[Avatar History: Select how to store history avatars]
+[Please select how the avatar history should be stored. This setting can NOT be changed in future, because it would cause all previous history to be lost.]
+[Store history in miranda history and all history avatars in same folder]
+[History is stored inside miranda db. It can be seen by History++ or Avatar History internal viewer.]
+[All avatars are stored as <Profile>\\Avatars History\\<Avatar Hash>]
+[Store history in miranda history and history avatars in per protocol folders]
+[All avatars are stored as <Profile>\\Avatars History\\<Protocol>\\<Avatar Hash>]
+[Store history in miranda history and history avatars in per contact folders using shortcuts]
+[All avatars are stored as <Profile>\\Avatars History\\<Protocol>\\<Avatar Hash> and have a shortcut per history entry in <Profile>\\Avatars History\\<Protocol>\\<Contact ID>\\<Timestamp>]
+[Store history avatars in per contact folders using shortcut]
+[History is stored only in disk. It can be seen by Avatar History internal viewer.]
+[All avatars are stored as <Profile>\\Avatars History\\<Protocol>\\<Avatar Hash> and have a shortcut per history entry in <Profile>\\Avatars History\\<Protocol>\\<Contact ID>\\<Timestamp>]
+[Store history avatars in per contact folders]
+[All avatars are stored as <Profile>\\Avatars History\\<Protocol>\\<Contact ID>\\<Timestamp> (the same image can be stored lot of times)]
+[OK]
+
+; Avatar dialog
+
+[Open Folder]
+[Save]
+[Delete]
+[<]
+[>]
+[Store this user's old avatars in disk]
+[Log this user's avatars changes to history]
+[Show popups for this user]
+[OK]
+[Save As...]
+[Delete this entry]
+[Delete this entry and the bitmap file]
+
+
+; Others
+
+[Please select an avatar from the list]
+[No avatar selected]
+
+[Delete avatar log?]
+[Are you sure you wish to delete this history entry?\nOnly the entry in history will be deleted, bitmap file will be kept!]
+[Are you sure you wish to delete this avatar shortcut?\nOnly shortcut will be deleted, bitmap file will be kept!]
+
+[Delete avatar?]
+[Are you sure you wish to delete this archived avatar?\nThis will delete the history entry and the bitmap file.\nWARNING:This can affect more than one entry in history!]
+[Are you sure you wish to delete this archived avatar?\nThis will delete the shortcut and the bitmap file.\nWARNING:This can affect more than one shortcut!]
+
+[Unknown Protocol]
+[Unknown UIN]
diff --git a/plugins/AvatarHistory/history.ico b/plugins/AvatarHistory/history.ico
new file mode 100644
index 0000000000..4b56c86221
--- /dev/null
+++ b/plugins/AvatarHistory/history.ico
Binary files differ
diff --git a/plugins/AvatarHistory/icolib.cpp b/plugins/AvatarHistory/icolib.cpp
new file mode 100644
index 0000000000..b8e54b0807
--- /dev/null
+++ b/plugins/AvatarHistory/icolib.cpp
@@ -0,0 +1,135 @@
+#include "AvatarHistory.h"
+
+enum IconIndex
+{
+ I_HISTORY,
+ I_OVERLAY
+};
+
+typedef struct
+{
+ TCHAR* szDescr;
+ char* szName;
+ int defIconID;
+ BOOL core;
+} IconStruct;
+
+static IconStruct iconList[] =
+{
+ { LPGENT("History"), "core_main_10", IDI_AVATARHIST, TRUE },
+ { LPGENT("Avatar Overlay"), "avh_overlay", IDI_AVATAROVERLAY, FALSE }
+};
+
+extern HANDLE hHooks[];
+
+static HICON LoadIconEx(IconIndex i)
+{
+ HICON hIcon;
+
+ if (hHooks[4])
+ hIcon = (HICON)CallService(MS_SKIN2_GETICON, 0, (LPARAM)iconList[(int)i].szName);
+ else
+ hIcon = (HICON)LoadImage(hInst, MAKEINTRESOURCE(iconList[(int)i].defIconID),
+ IMAGE_ICON, 0, 0, 0);
+
+ return hIcon;
+}
+
+
+static void ReleaseIconEx(HICON hIcon)
+{
+ if (hHooks[4])
+ CallService(MS_SKIN2_RELEASEICON, (WPARAM)hIcon, 0);
+ else
+ DestroyIcon(hIcon);
+}
+
+static void IcoLibUpdateMenus()
+{
+ CLISTMENUITEM mi = {0};
+
+ mi.cbSize = sizeof(mi);
+ mi.flags = CMIM_FLAGS | CMIM_ICON;
+ mi.hIcon = createDefaultOverlayedIcon(FALSE);
+ CallService( MS_CLIST_MODIFYMENUITEM, ( WPARAM )hMenu, ( LPARAM )&mi );
+ DestroyIcon(mi.hIcon);
+}
+
+int IcoLibIconsChanged(WPARAM wParam, LPARAM lParam)
+{
+ IcoLibUpdateMenus();
+ return 0;
+}
+
+void SetupIcoLib()
+{
+ if (hHooks[4])
+ {
+ SKINICONDESC sid = {0};
+ TCHAR path[MAX_PATH];
+
+ GetModuleFileName(hInst, path, sizeof(path));
+
+ sid.cbSize = SKINICONDESC_SIZE;
+ sid.ptszSection = LPGENT("Avatar History");
+ sid.ptszDefaultFile = path;
+ sid.flags = SIDF_ALL_TCHAR;
+
+ for (unsigned i = 0; i < MAX_REGS(iconList); i++)
+ {
+ if (!iconList[i].core)
+ {
+ sid.ptszDescription = iconList[i].szDescr;
+ sid.pszName = iconList[i].szName;
+ sid.iDefaultIndex = -iconList[i].defIconID;
+ CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
+ }
+ }
+ }
+ IcoLibUpdateMenus();
+}
+
+static HICON getOverlayedIcon(HICON icon, HICON overlay, BOOL big)
+{
+ HIMAGELIST il = ImageList_Create(
+ GetSystemMetrics(big?SM_CXICON:SM_CXSMICON),
+ GetSystemMetrics(big?SM_CYICON:SM_CYSMICON),
+ ILC_COLOR32|ILC_MASK, 2, 2);
+ ImageList_AddIcon(il, icon);
+ ImageList_AddIcon(il, overlay);
+ HIMAGELIST newImage = ImageList_Merge(il,0,il,1,0,0);
+ ImageList_Destroy(il);
+ HICON hIcon = ImageList_GetIcon(newImage, 0, 0);
+ ImageList_Destroy(newImage);
+ return hIcon; // the result should be destroyed by DestroyIcon()
+}
+
+
+HICON createDefaultOverlayedIcon(BOOL big)
+{
+ HICON icon0 = LoadIconEx(I_HISTORY);
+ HICON icon1 = LoadIconEx(I_OVERLAY);
+
+ HICON resIcon = getOverlayedIcon(icon0, icon1, FALSE);
+
+ ReleaseIconEx(icon0);
+ ReleaseIconEx(icon1);
+
+ return resIcon;
+}
+
+
+HICON createProtoOverlayedIcon(HANDLE hContact)
+{
+ HICON icon1 = LoadIconEx(I_OVERLAY);
+
+ char *szProto = (char *)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0);
+ HICON icon0 = LoadSkinnedProtoIcon(szProto, ID_STATUS_ONLINE);
+
+ HICON resIcon = getOverlayedIcon(icon0, icon1, FALSE);
+
+ ReleaseIconEx(icon1);
+ CallService(MS_SKIN2_RELEASEICON, (WPARAM)icon0, 0);
+
+ return resIcon;
+}
diff --git a/plugins/AvatarHistory/options.cpp b/plugins/AvatarHistory/options.cpp
new file mode 100644
index 0000000000..2d1a75116a
--- /dev/null
+++ b/plugins/AvatarHistory/options.cpp
@@ -0,0 +1,234 @@
+/*
+Avatar History Plugin
+ Copyright (C) 2006 Matthew Wild - Email: mwild1@gmail.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.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+*/
+
+#include "AvatarHistory.h"
+#include "../utils/mir_options.h"
+
+
+
+// Prototypes /////////////////////////////////////////////////////////////////////////////////////
+
+Options opts;
+
+
+static INT_PTR CALLBACK OptionsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK PopupsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+
+static OptPageControl optionsControls[] = {
+ { NULL, CONTROL_PROTOCOL_LIST, IDC_PROTOCOLS, "%sEnabled", TRUE }
+};
+
+
+static OptPageControl popupsControls[] = {
+ { NULL, CONTROL_CHECKBOX, IDC_POPUPS, "AvatarPopups", AVH_DEF_AVPOPUPS },
+ { &opts.popup_bkg_color, CONTROL_COLOR, IDC_BGCOLOR, "PopupsBgColor", AVH_DEF_POPUPBG },
+ { &opts.popup_text_color, CONTROL_COLOR, IDC_TEXTCOLOR, "PopupsTextColor", AVH_DEF_POPUPFG },
+ { &opts.popup_use_win_colors, CONTROL_CHECKBOX, IDC_WINCOLORS, "PopupsWinColors", FALSE },
+ { &opts.popup_use_default_colors, CONTROL_CHECKBOX, IDC_DEFAULTCOLORS, "PopupsDefaultColors", AVH_DEF_DEFPOPUPS },
+ { &opts.popup_delay_type, CONTROL_RADIO, IDC_DELAYFROMPU, "PopupsDelayType", POPUP_DELAY_DEFAULT, POPUP_DELAY_DEFAULT },
+ { NULL, CONTROL_RADIO, IDC_DELAYCUSTOM, "PopupsDelayType", POPUP_DELAY_DEFAULT, POPUP_DELAY_CUSTOM },
+ { NULL, CONTROL_RADIO, IDC_DELAYPERMANENT, "PopupsDelayType", POPUP_DELAY_DEFAULT, POPUP_DELAY_PERMANENT },
+ { &opts.popup_timeout, CONTROL_SPIN, IDC_DELAY, "PopupsTimeout", 10, IDC_DELAY_SPIN, (WORD) 1, (WORD) 255 },
+ { &opts.popup_right_click_action, CONTROL_COMBO, IDC_RIGHT_ACTION, "PopupsRightClick", POPUP_ACTION_CLOSEPOPUP },
+ { &opts.popup_left_click_action, CONTROL_COMBO, IDC_LEFT_ACTION, "PopupsLeftClick", POPUP_ACTION_OPENAVATARHISTORY },
+ { &opts.popup_show_changed, CONTROL_CHECKBOX, IDC_CHANGED_L, "PopupsShowChanged", TRUE },
+ { &opts.popup_changed, CONTROL_TEXT, IDC_CHANGED, "PopupsTextChanged", (ULONG_PTR) DEFAULT_TEMPLATE_CHANGED },
+ { &opts.popup_show_removed, CONTROL_CHECKBOX, IDC_REMOVED_L, "PopupsShowRemoved", TRUE },
+ { &opts.popup_removed, CONTROL_TEXT, IDC_REMOVED, "PopupsTextRemoved", (ULONG_PTR) DEFAULT_TEMPLATE_REMOVED }
+};
+
+static UINT popupsExpertControls[] = {
+ IDC_COLOURS_G, IDC_BGCOLOR, IDC_BGCOLOR_L, IDC_TEXTCOLOR, IDC_TEXTCOLOR_L, IDC_WINCOLORS, IDC_DEFAULTCOLORS,
+ IDC_DELAY_G, IDC_DELAYFROMPU, IDC_DELAYCUSTOM, IDC_DELAYPERMANENT, IDC_DELAY, IDC_DELAY_SPIN,
+ IDC_ACTIONS_G, IDC_RIGHT_ACTION_L, IDC_RIGHT_ACTION, IDC_LEFT_ACTION_L, IDC_LEFT_ACTION,
+ IDC_PREV
+};
+
+
+// Functions //////////////////////////////////////////////////////////////////////////////////////
+
+
+int OptInit(WPARAM wParam,LPARAM lParam)
+{
+ OPTIONSDIALOGPAGE odp;
+
+ ZeroMemory(&odp,sizeof(odp));
+ odp.cbSize=sizeof(odp);
+ odp.position=0;
+ odp.hInstance=hInst;
+ odp.ptszGroup = LPGENT("History"); // group to put your item under
+ odp.ptszTitle = LPGENT("Avatar"); // name of the item
+ odp.pfnDlgProc = OptionsDlgProc;
+ odp.pszTemplate = MAKEINTRESOURCEA(IDD_OPTIONS);
+ odp.flags = ODPF_BOLDGROUPS | ODPF_TCHAR | ODPF_EXPERTONLY;
+ CallService(MS_OPT_ADDPAGE,wParam,(LPARAM)&odp);
+
+ if(ServiceExists(MS_POPUP_ADDPOPUPT))
+ {
+ ZeroMemory(&odp,sizeof(odp));
+ odp.cbSize=sizeof(odp);
+ odp.position=0;
+ odp.hInstance=hInst;
+ odp.ptszGroup = LPGENT("Popups");
+ odp.ptszTitle = LPGENT("Avatar Change");
+ odp.pfnDlgProc = PopupsDlgProc;
+ odp.pszTemplate = MAKEINTRESOURCEA(IDD_POPUPS);
+ odp.flags = ODPF_BOLDGROUPS | ODPF_TCHAR;
+ odp.expertOnlyControls = popupsExpertControls;
+ odp.nExpertOnlyControls = MAX_REGS(popupsExpertControls);
+ odp.nIDBottomSimpleControl = IDC_POPUPS;
+ odp.nIDRightSimpleControl = IDC_POPUPS;
+ CallService(MS_OPT_ADDPAGE,wParam,(LPARAM)&odp);
+ }
+
+ return 0;
+}
+
+
+void LoadOptions()
+{
+ LoadOpts(optionsControls, MAX_REGS(optionsControls), MODULE_NAME);
+ LoadOpts(popupsControls, MAX_REGS(popupsControls), MODULE_NAME);
+
+ opts.log_per_contact_folders = DBGetContactSettingByte(NULL, MODULE_NAME, "LogPerContactFolders", 0);
+ opts.log_keep_same_folder = DBGetContactSettingByte(NULL, MODULE_NAME, "LogKeepSameFolder", 0);
+ opts.log_store_as_hash = DBGetContactSettingByte(NULL, MODULE_NAME, "StoreAsHash", 1);
+}
+
+
+static INT_PTR CALLBACK OptionsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ return SaveOptsDlgProc(optionsControls, MAX_REGS(optionsControls), MODULE_NAME, hwndDlg, msg, wParam, lParam);
+}
+
+
+static void PopupsEnableDisableCtrls(HWND hwndDlg)
+{
+ BOOL enabled = IsDlgButtonChecked(hwndDlg, IDC_POPUPS);
+
+ EnableWindow(GetDlgItem(hwndDlg, IDC_COLOURS_G), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_BGCOLOR_L), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_TEXTCOLOR_L), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DELAY_G), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DELAYFROMPU), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DELAYCUSTOM), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DELAYPERMANENT), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_ACTIONS_G), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_RIGHT_ACTION_L), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_RIGHT_ACTION), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_LEFT_ACTION_L), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_LEFT_ACTION), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_PREV), enabled);
+
+ EnableWindow(GetDlgItem(hwndDlg, IDC_BGCOLOR), enabled &&
+ !IsDlgButtonChecked(hwndDlg, IDC_WINCOLORS) &&
+ !IsDlgButtonChecked(hwndDlg, IDC_DEFAULTCOLORS));
+ EnableWindow(GetDlgItem(hwndDlg, IDC_TEXTCOLOR), enabled &&
+ !IsDlgButtonChecked(hwndDlg, IDC_WINCOLORS) &&
+ !IsDlgButtonChecked(hwndDlg, IDC_DEFAULTCOLORS));
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DEFAULTCOLORS), enabled &&
+ !IsDlgButtonChecked(hwndDlg, IDC_WINCOLORS));
+ EnableWindow(GetDlgItem(hwndDlg, IDC_WINCOLORS), enabled &&
+ !IsDlgButtonChecked(hwndDlg, IDC_DEFAULTCOLORS));
+
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DELAY), enabled &&
+ IsDlgButtonChecked(hwndDlg, IDC_DELAYCUSTOM));
+
+ EnableWindow(GetDlgItem(hwndDlg, IDC_CHANGED_L), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_REMOVED_L), enabled);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_CHANGED), enabled &&
+ IsDlgButtonChecked(hwndDlg, IDC_CHANGED_L));
+ EnableWindow(GetDlgItem(hwndDlg, IDC_REMOVED), enabled &&
+ IsDlgButtonChecked(hwndDlg, IDC_REMOVED_L));
+
+}
+
+
+static INT_PTR CALLBACK PopupsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch (msg)
+ {
+ case WM_INITDIALOG:
+ {
+ SendDlgItemMessage(hwndDlg, IDC_RIGHT_ACTION, CB_ADDSTRING, 0, (LPARAM) TranslateT("Do nothing"));
+ SendDlgItemMessage(hwndDlg, IDC_RIGHT_ACTION, CB_ADDSTRING, 0, (LPARAM) TranslateT("Close popup"));
+ SendDlgItemMessage(hwndDlg, IDC_RIGHT_ACTION, CB_ADDSTRING, 0, (LPARAM) TranslateT("Show avatar history"));
+ SendDlgItemMessage(hwndDlg, IDC_RIGHT_ACTION, CB_ADDSTRING, 0, (LPARAM) TranslateT("Show contact history"));
+
+ SendDlgItemMessage(hwndDlg, IDC_LEFT_ACTION, CB_ADDSTRING, 0, (LPARAM) TranslateT("Do nothing"));
+ SendDlgItemMessage(hwndDlg, IDC_LEFT_ACTION, CB_ADDSTRING, 0, (LPARAM) TranslateT("Close popup"));
+ SendDlgItemMessage(hwndDlg, IDC_LEFT_ACTION, CB_ADDSTRING, 0, (LPARAM) TranslateT("Show avatar history"));
+ SendDlgItemMessage(hwndDlg, IDC_LEFT_ACTION, CB_ADDSTRING, 0, (LPARAM) TranslateT("Show contact history"));
+
+ // Needs to be called here in this case
+ BOOL ret = SaveOptsDlgProc(popupsControls, MAX_REGS(popupsControls), MODULE_NAME, hwndDlg, msg, wParam, lParam);
+
+ PopupsEnableDisableCtrls(hwndDlg);
+
+ return ret;
+ }
+ case WM_COMMAND:
+ {
+ switch (LOWORD(wParam))
+ {
+ case IDC_POPUPS:
+ case IDC_WINCOLORS:
+ case IDC_DEFAULTCOLORS:
+ case IDC_DELAYFROMPU:
+ case IDC_DELAYPERMANENT:
+ case IDC_DELAYCUSTOM:
+ case IDC_CHANGED_L:
+ case IDC_REMOVED_L:
+ {
+ if (HIWORD(wParam) == BN_CLICKED)
+ PopupsEnableDisableCtrls(hwndDlg);
+
+ break;
+ }
+ case IDC_PREV:
+ {
+ Options op = opts;
+
+ if (IsDlgButtonChecked(hwndDlg, IDC_DELAYFROMPU))
+ op.popup_delay_type = POPUP_DELAY_DEFAULT;
+ else if (IsDlgButtonChecked(hwndDlg, IDC_DELAYCUSTOM))
+ op.popup_delay_type = POPUP_DELAY_CUSTOM;
+ else if (IsDlgButtonChecked(hwndDlg, IDC_DELAYPERMANENT))
+ op.popup_delay_type = POPUP_DELAY_PERMANENT;
+
+ op.popup_timeout = GetDlgItemInt(hwndDlg,IDC_DELAY, NULL, FALSE);
+ op.popup_bkg_color = SendDlgItemMessage(hwndDlg,IDC_BGCOLOR,CPM_GETCOLOUR,0,0);
+ op.popup_text_color = SendDlgItemMessage(hwndDlg,IDC_TEXTCOLOR,CPM_GETCOLOUR,0,0);
+ op.popup_use_win_colors = IsDlgButtonChecked(hwndDlg, IDC_WINCOLORS) != 0;
+ op.popup_use_default_colors = IsDlgButtonChecked(hwndDlg, IDC_DEFAULTCOLORS) != 0;
+
+ HANDLE hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDFIRST,0,0);
+ ShowTestPopup(hContact,TranslateT("Test Contact"), TranslateT("Test description"), &op);
+
+ break;
+ }
+ }
+ break;
+ }
+ }
+
+ return SaveOptsDlgProc(popupsControls, MAX_REGS(popupsControls), MODULE_NAME, hwndDlg, msg, wParam, lParam);
+}
diff --git a/plugins/AvatarHistory/popup.cpp b/plugins/AvatarHistory/popup.cpp
new file mode 100644
index 0000000000..dc03ee783d
--- /dev/null
+++ b/plugins/AvatarHistory/popup.cpp
@@ -0,0 +1,279 @@
+/*
+Copyright (C) 2005 Ricardo Pescuma Domenecci
+
+This is free software; you can redistribute it and/or
+modify it under the terms of the GNU Library General Public
+License as published by the Free Software Foundation; either
+version 2 of the License, or (at your option) any later version.
+
+This 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
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this file; see the file license.txt. If
+not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA 02111-1307, USA.
+*/
+
+
+#include "AvatarHistory.h"
+
+
+
+// Prototypes /////////////////////////////////////////////////////////////////////////////////////
+
+#define WMU_ACTION (WM_USER + 1)
+
+
+LRESULT CALLBACK PopupWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+
+HWND hPopupWindow = NULL;
+
+
+static LRESULT CALLBACK PopupDlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
+static LRESULT CALLBACK DumbPopupDlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
+
+
+
+// Functions //////////////////////////////////////////////////////////////////////////////////////
+
+
+// Initializations needed by popups
+void InitPopups()
+{
+ // window needed for popup commands
+ hPopupWindow = CreateWindowEx(WS_EX_TOOLWINDOW, _T("static"), _T(MODULE_NAME) _T("_PopupWindow"),
+ 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, HWND_DESKTOP,
+ NULL, hInst, NULL);
+ SetWindowLong(hPopupWindow, GWLP_WNDPROC, (LONG_PTR)PopupWndProc);
+}
+
+
+// Deinitializations needed by popups
+void DeInitPopups()
+{
+}
+
+
+// Show an error popup
+void ShowErrPopup(const TCHAR *description, const TCHAR *title)
+{
+ ShowPopupEx(NULL, title == NULL ? _T(MODULE_NAME) _T(" Error") : title, description,
+ NULL, POPUP_TYPE_ERROR, NULL);
+}
+
+
+void ShowTestPopup(HANDLE hContact,const TCHAR *title, const TCHAR *description, const Options *op)
+{
+ ShowPopupEx(hContact, title, description, NULL, POPUP_TYPE_TEST, op);
+}
+
+
+void ShowPopup(HANDLE hContact, const TCHAR *title, const TCHAR *description)
+{
+ ShowPopupEx(hContact, title, description, hContact, POPUP_TYPE_NORMAL, &opts);
+}
+
+void ShowDebugPopup(HANDLE hContact, const TCHAR *title, const TCHAR *description)
+{
+ if(DBGetContactSettingByte(NULL,MODULE_NAME,"Debug",0))
+ {
+ ShowPopup(hContact,title,description);
+ }
+}
+
+typedef struct
+{
+ void* plugin_data;
+ HICON hIcon;
+}
+PopupDataType;
+
+// Show an popup
+void ShowPopupEx(HANDLE hContact, const TCHAR *title, const TCHAR *description,
+ void *plugin_data, int type, const Options *op)
+{
+ if(ServiceExists(MS_POPUP_ADDPOPUPT))
+ {
+ // Make popup
+ POPUPDATAT ppd = {0};
+
+ ppd.lchContact = hContact;
+ ppd.lchIcon = createProtoOverlayedIcon(hContact);
+
+ ppd.PluginData = mir_alloc(sizeof(PopupDataType));
+ ((PopupDataType*)ppd.PluginData)->plugin_data = plugin_data;
+ ((PopupDataType*)ppd.PluginData)->hIcon = ppd.lchIcon;
+
+ if (title != NULL)
+ lstrcpyn(ppd.lptzContactName, title, MAX_REGS(ppd.lptzContactName));
+ else if (hContact != NULL)
+ lstrcpyn(ppd.lptzContactName, (TCHAR *) CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM)hContact, GCDNF_TCHAR | GCDNF_NOCACHE),
+ MAX_REGS(ppd.lptzContactName));
+
+ if (description != NULL)
+ lstrcpyn(ppd.lptzText, description, MAX_REGS(ppd.lptzText));
+
+ if (type == POPUP_TYPE_NORMAL || type == POPUP_TYPE_TEST)
+ {
+ if (op->popup_use_default_colors)
+ {
+ ppd.colorBack = 0;
+ ppd.colorText = 0;
+ }
+ else if (op->popup_use_win_colors)
+ {
+ ppd.colorBack = GetSysColor(COLOR_BTNFACE);
+ ppd.colorText = GetSysColor(COLOR_WINDOWTEXT);
+ }
+ else
+ {
+ ppd.colorBack = op->popup_bkg_color;
+ ppd.colorText = op->popup_text_color;
+ }
+ }
+ else // if (type == POPUP_TYPE_ERROR)
+ {
+ ppd.colorBack = RGB(200,0,0);
+ ppd.colorText = RGB(255,255,255);
+ }
+
+ if (type == POPUP_TYPE_NORMAL)
+ {
+ ppd.PluginWindowProc = PopupDlgProc;
+ }
+ else // if (type == POPUP_TYPE_TEST || type == POPUP_TYPE_ERROR)
+ {
+ ppd.PluginWindowProc = DumbPopupDlgProc;
+ }
+
+ if (type == POPUP_TYPE_NORMAL || type == POPUP_TYPE_TEST)
+ {
+ switch (op->popup_delay_type)
+ {
+ case POPUP_DELAY_CUSTOM:
+ ppd.iSeconds = opts.popup_timeout;
+ break;
+
+ case POPUP_DELAY_PERMANENT:
+ ppd.iSeconds = -1;
+ break;
+
+ case POPUP_DELAY_DEFAULT:
+ default:
+ ppd.iSeconds = 0;
+ break;
+ }
+ }
+ else // if (type == POPUP_TYPE_ERROR)
+ {
+ ppd.iSeconds = 0;
+ }
+
+ // Now that every field has been filled, we want to see the popup.
+ PUAddPopUpT(&ppd);
+ }
+ else
+ {
+ MessageBox(NULL, description, title ? title : (TCHAR *)CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM)hContact, GCDNF_TCHAR),
+ MB_OK);
+ }
+
+}
+
+
+// Handle to the hidden windows to handle actions for popup clicks
+// wParam has the number of MOTD in case of WMU_SHOW_MOTD_DETAILS
+LRESULT CALLBACK PopupWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ if (uMsg == WMU_ACTION)
+ {
+ if (lParam == POPUP_ACTION_OPENAVATARHISTORY)
+ {
+ CallService("AvatarHistory/ShowDialog", wParam, 0);
+ }
+ else if (lParam == POPUP_ACTION_OPENHISTORY)
+ {
+ CallService(MS_HISTORY_SHOWCONTACTHISTORY, wParam, 0);
+ }
+ }
+ return DefWindowProc(hWnd, uMsg, wParam, lParam);
+}
+
+
+// Handle to popup events
+static LRESULT CALLBACK PopupDlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
+{
+ switch(message) {
+ case WM_COMMAND:
+ {
+ PopupDataType* popup = (PopupDataType*)PUGetPluginData(hWnd);
+ PostMessage(hPopupWindow, WMU_ACTION, (WPARAM)popup->plugin_data, opts.popup_left_click_action);
+
+ if (opts.popup_left_click_action != POPUP_ACTION_DONOTHING)
+ PUDeletePopUp(hWnd);
+
+ return TRUE;
+ }
+
+ case WM_CONTEXTMENU:
+ {
+ PopupDataType* popup = (PopupDataType*)PUGetPluginData(hWnd);
+ PostMessage(hPopupWindow, WMU_ACTION, (WPARAM)popup->plugin_data, opts.popup_right_click_action);
+
+ if (opts.popup_right_click_action != POPUP_ACTION_DONOTHING)
+ PUDeletePopUp(hWnd);
+
+ return TRUE;
+ }
+
+ case UM_FREEPLUGINDATA:
+ {
+ PopupDataType* popup = (PopupDataType*)PUGetPluginData(hWnd);
+ if ((INT_PTR)popup != CALLSERVICE_NOTFOUND)
+ {
+ DestroyIcon(popup->hIcon);
+ mir_free(popup);
+ }
+ return FALSE; //the return value is ignored
+ }
+ }
+
+ return DefWindowProc(hWnd, message, wParam, lParam);
+}
+
+
+// Handle to popup events
+static LRESULT CALLBACK DumbPopupDlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
+{
+ switch(message) {
+ case WM_COMMAND:
+ {
+ PUDeletePopUp(hWnd);
+ return TRUE;
+ }
+
+ case WM_CONTEXTMENU:
+ {
+ PUDeletePopUp(hWnd);
+ return TRUE;
+ }
+
+ case UM_FREEPLUGINDATA:
+ {
+ PopupDataType* popup = (PopupDataType*)PUGetPluginData(hWnd);
+ if ((INT_PTR)popup != CALLSERVICE_NOTFOUND)
+ {
+ DestroyIcon(popup->hIcon);
+ mir_free(popup);
+ }
+ return FALSE; //the return value is ignored
+ }
+ }
+
+ return DefWindowProc(hWnd, message, wParam, lParam);
+}
+
+
diff --git a/plugins/AvatarHistory/popup.h b/plugins/AvatarHistory/popup.h
new file mode 100644
index 0000000000..2944ba0895
--- /dev/null
+++ b/plugins/AvatarHistory/popup.h
@@ -0,0 +1,53 @@
+/*
+Copyright (C) 2005 Ricardo Pescuma Domenecci
+
+This is free software; you can redistribute it and/or
+modify it under the terms of the GNU Library General Public
+License as published by the Free Software Foundation; either
+version 2 of the License, or (at your option) any later version.
+
+This 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
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this file; see the file license.txt. If
+not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA 02111-1307, USA.
+*/
+
+
+#ifndef __POPUP_H__
+# define __POPUP_H__
+
+#include <windows.h>
+
+
+// Initializations needed by popups
+void InitPopups();
+
+// Deinitializations needed by popups
+void DeInitPopups();
+
+
+#define POPUP_TYPE_NORMAL 0
+#define POPUP_TYPE_TEST 1
+#define POPUP_TYPE_ERROR 2
+
+// Show an popup
+void ShowPopup(HANDLE hContact, const TCHAR *title, const TCHAR *description);
+void ShowDebugPopup(HANDLE hContact, const TCHAR *title, const TCHAR *description);
+
+// Show an test
+void ShowTestPopup(HANDLE hContact,const TCHAR *title, const TCHAR *description, const Options *op);
+
+// Show an error popup
+void ShowErrPopup(const char *description, const char *title = NULL);
+
+void ShowPopupEx(HANDLE hContact, const TCHAR *title, const TCHAR *description,
+ void *plugin_data, int type, const Options *op);
+
+
+
+#endif // __POPUP_H__
diff --git a/plugins/AvatarHistory/resource.h b/plugins/AvatarHistory/resource.h
new file mode 100644
index 0000000000..9ec6008167
--- /dev/null
+++ b/plugins/AvatarHistory/resource.h
@@ -0,0 +1,88 @@
+//{{NO_DEPENDENCIES}}
+// Microsoft Visual C++ generated include file.
+// Used by AvatarHistory.rc
+//
+#define IDD_OPTIONS_OLD 101
+#define IDC_POPUPBG 102
+#define IDD_AVATARDLG 102
+#define IDC_POPUPFG 103
+#define IDI_AVATARHIST 104
+#define IDI_NEWAVATAR 105
+#define IDI_AVATAROVERLAY 106
+#define IDR_MENU1 108
+#define IDD_FIRST_RUN 109
+#define IDD_OPTIONS 119
+#define IDD_POPUPS 120
+#define IDC_CUSTOM1 1000
+#define IDC_AVATARPOPUPS 1001
+#define IDC_DELAY 1001
+#define IDC_LOGTODISK 1002
+#define IDC_WINCOLORS 1002
+#define IDC_LOGTOHISTORY 1003
+#define IDC_DEFAULTCOLORS 1003
+#define IDC_BGCOLOR 1004
+#define IDC_DEFPOPUPS 1005
+#define IDC_TEXTCOLOR 1005
+#define IDC_PREV 1006
+#define IDC_AVATAR 1007
+#define IDC_DELAYFROMPU 1007
+#define IDC_AVATARLIST 1008
+#define IDC_DELAYCUSTOM 1008
+#define IDC_SAVE 1009
+#define IDC_DELAYPERMANENT 1009
+#define IDC_DELETE 1010
+#define IDC_NEXT 1011
+#define IDC_BACK 1012
+#define IDC_LOGUSER 1013
+#define IDC_POPUPUSER 1014
+#define IDC_OPENFOLDER 1015
+#define IDC_PUFGTEXT 1016
+#define IDC_HISTORYUSER 1016
+#define IDC_PUBGTEXT 1017
+#define IDC_SHOWMENU 1019
+#define IDC_LOGGING_G 1020
+#define IDC_SAME_FOLDER 1021
+#define IDC_RIGHT_ACTION 1022
+#define IDC_MIR_SAME 1022
+#define IDC_LEFT_ACTION 1023
+#define IDC_MIR_PROTO 1023
+#define IDC_AVATARPATH 1023
+#define IDC_MIR_SHORT 1024
+#define IDC_SHORT 1025
+#define IDC_DUP 1026
+#define IDC_PROTOCOLS 1041
+#define IDC_CHANGED 1058
+#define IDC_REMOVED 1059
+#define IDC_POPUPS 1060
+#define IDC_DELAY_SPIN 1061
+#define IDC_LOG_DISK 1061
+#define IDC_LOG_HISTORY 1062
+#define IDC_TRACK_G 1063
+#define IDC_CHANGED_L 1064
+#define IDC_REMOVED_L 1065
+#define IDC_PROTOCOLS_G 1066
+#define IDC_PROTOCOLS_L 1067
+#define IDC_TRACK_CHANGE 1068
+#define IDC_COLOURS_G 1068
+#define IDC_OLD_STYLE 1068
+#define IDC_TRACK_REMOVE 1069
+#define IDC_BGCOLOR_L 1069
+#define IDC_TEXTCOLOR_L 1070
+#define IDC_DELAY_G 1071
+#define IDC_ACTIONS_G 1072
+#define IDC_RIGHT_ACTION_L 1073
+#define IDC_LEFT_ACTION_L 1074
+#define ID_AVATARLISTPOPUP_SAVEAS 40001
+#define ID_AVATARLISTPOPUP_DELETE 40002
+#define ID_AVATARLISTPOPUP_DELETE_BOTH 40003
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NEXT_RESOURCE_VALUE 110
+#define _APS_NEXT_COMMAND_VALUE 40004
+#define _APS_NEXT_CONTROL_VALUE 1025
+#define _APS_NEXT_SYMED_VALUE 103
+#endif
+#endif
diff --git a/plugins/ExternalAPI/m_HTTPServer.h b/plugins/ExternalAPI/m_HTTPServer.h
index 6cb6549ee0..c8de071838 100644
--- a/plugins/ExternalAPI/m_HTTPServer.h
+++ b/plugins/ExternalAPI/m_HTTPServer.h
@@ -100,6 +100,18 @@ typedef struct {
#define MS_HTTP_GET_ALL_SHARES "HTTPServer/GetAllShares"
+/////////////////////////////////////////////
+//// Service MS_HTTP_GET_LINK /////
+/////////////////////////////////////////////
+//
+// wParam = (char*)pszSrvPath;
+// lParam = 0
+// Return URL Link on success, 0 on failure
+// Return pointer must be mir_free by caller
+//
+// Return the URL link to the pszSrvPath
+
+#define MS_HTTP_GET_LINK "HTTPServer/GetLink"
#endif
diff --git a/plugins/ExternalAPI/m_autoreplacer.h b/plugins/ExternalAPI/m_autoreplacer.h
new file mode 100644
index 0000000000..57271a7163
--- /dev/null
+++ b/plugins/ExternalAPI/m_autoreplacer.h
@@ -0,0 +1,39 @@
+/*
+ AutoReplacer plugin
+ by Angelo Luiz Tartari
+*/
+
+#ifndef M_AUTOREPLACER_H
+#define M_AUTOREPLACER_H
+
+/*
+ Adds a window handle to AutoReplacer.
+ This handle must belong to any window based on a editbox (editbox, richtext, TMemo, TEdit, TMaskEdit, etc.).
+ After adding a handle, AutoReplacer will automatically work on this window.
+ wParam = 0
+ lParam = (LPARAM)(HWND)hwnd
+ Returns: 0 on success, -1 if hwnd is invalid, 1 on error.
+ Example:
+ if(ServiceExists(MS_AUTOREPLACER_ADDWINHANDLE))
+ autoreplacer_AddWinHandle(GetDlgItem(hwndDlg, IDC_EDIT1));
+*/
+#define MS_AUTOREPLACER_ADDWINHANDLE "AutoReplacer/AddWinHandle"
+static int __inline autoreplacer_AddWinHandle(HWND hwnd) {
+ return (int)CallService(MS_AUTOREPLACER_ADDWINHANDLE, (WPARAM)0, (LPARAM)hwnd);
+}
+
+/*
+ Removes a window handle from AutoReplacer's list.
+ wParam = 0
+ lParam = (LPARAM)(HWND)hwnd
+ Returns: 0 on success, -1 if hwnd is invalid, 1 if hwnd wasn't found.
+ Example:
+ if(ServiceExists(MS_AUTOREPLACER_REMWINHANDLE))
+ autoreplacer_RemWinHandle(GetDlgItem(hwndDlg, IDC_EDIT1));
+*/
+#define MS_AUTOREPLACER_REMWINHANDLE "AutoReplacer/RemWinHandle"
+static int __inline autoreplacer_RemWinHandle(HWND hwnd) {
+ return (int)CallService(MS_AUTOREPLACER_REMWINHANDLE, (WPARAM)0, (LPARAM)hwnd);
+}
+
+#endif \ No newline at end of file
diff --git a/plugins/ExternalAPI/m_avatarhist.h b/plugins/ExternalAPI/m_avatarhist.h
new file mode 100644
index 0000000000..6f1e5c8ebd
--- /dev/null
+++ b/plugins/ExternalAPI/m_avatarhist.h
@@ -0,0 +1,56 @@
+/*
+Copyright (C) 2006 MattJ, Ricardo Pescuma Domenecci
+
+This is free software; you can redistribute it and/or
+modify it under the terms of the GNU Library General Public
+License as published by the Free Software Foundation; either
+version 2 of the License, or (at your option) any later version.
+
+This 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
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this file; see the file license.txt. If
+not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA 02111-1307, USA.
+*/
+
+
+#ifndef __M_AVATARHISTORY_H__
+# define __M_AVATARHISTORY_H__
+
+
+#define MIID_AVATAR_CHANGE_LOGGER { 0x95e3f3d3, 0x9678, 0x4561, { 0x96, 0xf8, 0x95, 0x88, 0x33, 0x7b, 0x86, 0x68 } }
+#define MIID_AVATAR_CHANGE_NOTIFIER { 0x91af9298, 0x8570, 0x4063, { 0xbf, 0x2f, 0xca, 0x68, 0xd0, 0xe3, 0xb3, 0x6a } }
+
+
+#define EVENTTYPE_AVATAR_CHANGE 9003
+
+
+/*
+Return TRUE is Avatar History is enabled for this contact
+
+wParam: hContact
+lParam: ignored
+*/
+#define MS_AVATARHISTORY_ENABLED "AvatarHistory/IsEnabled"
+
+
+/*
+Get cached avatar
+
+wParam: (char *) protocol name
+lParam: (TCHAR *) hash
+return: (TCHAR *) NULL if none is found or the path to the avatar. You need to free this string
+ with mir_free.
+*/
+#define MS_AVATARHISTORY_GET_CACHED_AVATAR "AvatarHistory/GetCachedAvatar"
+
+
+#define MS_AVATARHISTORY_SHOWDIALOG "AvatarHistory/ShowDialog"
+
+
+
+#endif // __M_AVATARHISTORY_H__
diff --git a/plugins/ExternalAPI/m_ftpfile.h b/plugins/ExternalAPI/m_ftpfile.h
new file mode 100644
index 0000000000..6575fd9e3b
--- /dev/null
+++ b/plugins/ExternalAPI/m_ftpfile.h
@@ -0,0 +1,119 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+This is free software; you can redistribute it and/or
+modify it under the terms of the GNU Library General Public
+License as published by the Free Software Foundation; either
+version 2 of the License, or (at your option) any later version.
+
+This 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
+Library General Public License for more details.
+
+You should have received a copy of the GNU Library General Public
+License along with this file; see the file license.txt. If
+not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+Boston, MA 02111-1307, USA.
+*/
+
+
+#ifndef __M_FTP_FILE_H__
+#define __M_FTP_FILE_H__
+
+#define FNUM_DEFAULT 0 // user's default FTP server
+#define FNUM_FTP1 1 // first FTP server in setting
+#define FNUM_FTP2 2 // second...
+#define FNUM_FTP3 3
+#define FNUM_FTP4 4
+#define FNUM_FTP5 5
+
+#define FMODE_RAWFILE 1 // Object list contains path(s) to file(s) which will be uploaded as they are
+#define FMODE_ZIPFILE 2 // ... path(s) to file(s) which will be zipped and uploaded as one ZIP file
+#define FMODE_ZIPFOLDER 4 // ... path to folder which will be zipped and uploaded as one ZIP file (objectCount == 1)
+
+#define FUPL_UNICODE 1 // Object list contains WCHAR* paths
+
+#if defined _UNICODE || defined UNICODE
+#define FUPL_TCHAR FUPL_UNICODE
+#else
+#define FUPL_TCHAR 0
+#endif
+
+typedef struct
+{
+ int cbSize; // size of the structure
+ HANDLE hContact; // contact handle, can be NULL
+ BYTE ftpNum; // number of the FTP server which will be used for upload, can be one of FNUM_* values
+ BYTE mode; // upload mode, can be one of FMODE_* values
+ DWORD flags; // bitwise OR of the FUPL_* flags above
+
+ union {
+ TCHAR **pstzObjects; // pointer to the array of the object(s) to upload, content is determined by MODE value
+ char **pszObjects;
+ wchar_t **pswzObjects;
+ };
+
+ int objectCount; // number of items in Object list
+} FTPUPLOAD;
+
+//
+// Send file(s) or folder in selected mode to the FTP server
+// wParam = (WPARAM)0; not used
+// lParam = (LPARAM)(FTPUPLOAD*)&ftpu; pointer to FTPUPLOAD
+// returns 0 if upload started with no errors, nonzero otherwise
+//
+#define MS_FTPFILE_UPLOAD "FTPFile/Upload"
+
+__inline static INT_PTR FTPFileUploadA(HANDLE hContact, BYTE ftpNum, BYTE mode, char **pszObjects, int objCount)
+{
+ FTPUPLOAD ftpu = {0};
+ ftpu.cbSize = sizeof(ftpu);
+ ftpu.hContact = hContact;
+ ftpu.ftpNum = ftpNum;
+ ftpu.mode = mode;
+ ftpu.pszObjects = pszObjects;
+ ftpu.objectCount = objCount;
+ return CallService(MS_FTPFILE_UPLOAD, (WPARAM)0, (LPARAM)&ftpu);
+}
+
+__inline static INT_PTR FTPFileUploadW(HANDLE hContact, BYTE ftpNum, BYTE mode, wchar_t **pswzObjects, int objCount)
+{
+ FTPUPLOAD ftpu = {0};
+ ftpu.cbSize = sizeof(ftpu);
+ ftpu.hContact = hContact;
+ ftpu.ftpNum = ftpNum;
+ ftpu.mode = mode;
+ ftpu.flags = FUPL_UNICODE;
+ ftpu.pswzObjects = pswzObjects;
+ ftpu.objectCount = objCount;
+ return CallService(MS_FTPFILE_UPLOAD, (WPARAM)0, (LPARAM)&ftpu);
+}
+
+#if defined _UNICODE || defined UNICODE
+#define FTPFileUpload FTPFileUploadW
+#else
+#define FTPFileUpload FTPFileUploadA
+#endif
+
+//
+// Show a simple file manager
+// wParam = (WPARAM)0; not used
+// lParam = (LPARAM)0; not used
+// returns 0 always
+//
+#define MS_FTPFILE_SHOWMANAGER "FTPFile/ShowManager"
+
+__inline static INT_PTR FTPFileShowManager()
+{
+ return CallService(MS_FTPFILE_SHOWMANAGER, (WPARAM)0, (LPARAM)0);
+}
+
+//
+// OBSOLOTE SERVICE (used by Send Screenshot plugin)
+// Do NOT use it!
+//
+#define MS_FTPFILE_SHAREFILE "FTPFile/ShareFiles"
+
+#endif \ No newline at end of file
diff --git a/plugins/ExternalAPI/m_hddinfo.h b/plugins/ExternalAPI/m_hddinfo.h
new file mode 100644
index 0000000000..3f529ec1ff
--- /dev/null
+++ b/plugins/ExternalAPI/m_hddinfo.h
@@ -0,0 +1,6 @@
+#define MS_SYSINFO_HDDTEMP "SysInfo/HddTemp"
+ // checks current hdd temperature
+#define MS_SYSINFO_CUSTPOP "SysInfo/CustomPopup"
+ //shows special custom popup
+#define ME_SYSINFO_HDDOVERHEAT "SysInfo/HddOverheat"
+ // happens if one ot the drives has current temperature higher than set as normal
diff --git a/plugins/ExternalAPI/m_mucc.h b/plugins/ExternalAPI/m_mucc.h
new file mode 100644
index 0000000000..44fc7dd2f1
--- /dev/null
+++ b/plugins/ExternalAPI/m_mucc.h
@@ -0,0 +1,189 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef M_MUCC_INCLUDED
+#define M_MUCC_INCLUDED
+
+#define MUCC_WINDOW_CHATROOM 1
+#define MUCC_WINDOW_CHATLIST 2
+
+#define MUCC_WF_BOLD 0x0001 //enable the 'bold' button
+#define MUCC_WF_ITALIC 0x0002 //enable the 'italics' button
+#define MUCC_WF_UNDERLINE 0x0004 //enable the 'underline' button
+#define MUCC_WF_COLOR 0x0008 //enable the 'foreground color' button
+#define MUCC_WF_BKGCOLOR 0x0010 //enable the 'background color' button
+#define MUCC_WF_TYPNOTIF 0x0020 //enable typing notifications
+
+typedef struct {
+ int cbSize;
+ int iType; //Window type, MUCW_CHATROOM or MUCW_CHATLIST
+ DWORD dwFlags; //Window look & feel flags
+ const char *pszModule; //Identifier of the module owning the window
+ const char *pszModuleName; //Name of the module as displayed to the user
+ const char *pszID; //Unique identifier of the chat room
+ const char *pszName; //Name of the chat room
+ const char *pszUID; //Identifier of the user
+ const char *pszNick; //Nick name used by the user in the chat room
+ const char *pszStatusbarText; //Optional text to set in the statusbar
+} MUCCWINDOW;
+
+#define MS_MUCC_NEW_WINDOW "MUCC/NewWindow"
+
+typedef struct {
+ const char *pszID; //Unique identifier of the group or the chat room
+ const char *pszName; //Name of the group or the chat room
+ const char *pszNick; //Name of the user
+ const char *pszText; //Text, usage depends on type of event
+ int iCount; //Number of users in the chat room
+ DWORD dwFlags; //Item flags
+} MUCCQUERYITEM;
+
+typedef struct {
+ int cbSize;
+ int iType; //Query type, one of MUCC_EVENT_QUERY_* values
+ const char *pszModule; //Name of the module
+ const char *pszParent; //Parent of groups or the group chat rooms belong to
+ int iItemsNum; //Number of items pItems iws pointing to
+ MUCCQUERYITEM *pItems; //Pointer to array of result items
+ DWORD dwFlags; //Item flags
+ int iPage; //Number of page in room list
+ int iLastPage; //1 if the group has any child or there is a next page in room list, 0 otherwise
+} MUCCQUERYRESULT;
+
+#define MS_MUCC_QUERY_RESULT "MUCC/QueryResult"
+
+/*
+ * The following fields must be set for all events:
+ * cbSize - size of the structure
+ * pszModule - module name
+ * iType - event type (id)
+ */
+/*
+ * Incoming messages
+ */
+#define MUCC_EVENT_MESSAGE 0x0001
+/* pszID - room ID
+ * pszUID - user UID (login etc.)
+ * pszNick - user nick (i.e. the name to be displayed)
+ * pszText - message
+ * iFont - font index
+ * iFontSize - font size
+ * color - text color
+ * dwFlags - flags
+ * time - time
+ * bIsMe - TRUE if this is an outgoing message, FALSE otherwise
+ */
+#define MUCC_EVENT_STATUS 0x0002
+/* pszID - room ID
+ * pszUID - user UID (login etc.)
+ * pszNick - user nick (i.e. the name to be displayed)
+ * pszText - unused
+ * dwData - status
+ * dwFlags
+ * bIsMe
+ */
+#define MUCC_EVENT_INVITATION 0x0003
+/*
+*/
+#define MUCC_EVENT_ERROR 0x0004
+
+#define MUCC_EVENT_TOPIC 0x0005
+/* pszID
+ * pszText
+ */
+#define MUCC_EVENT_ROOM_INFO 0x0006
+
+/*
+ * Incoming & outgoing messages
+ */
+#define MUCC_EVENT_JOIN 0x0080
+#define MUCC_EVENT_LEAVE 0x0081
+/*
+ * Outgoing messages
+ */
+#define MUCC_EVENT_INVITE 0x0102
+#define MUCC_EVENT_START_PRIV 0x0103
+#define MUCC_EVENT_REGISTER_NICK 0x0105
+#define MUCC_EVENT_REMOVE_NICK 0x0106
+#define MUCC_EVENT_REGISTER_ROOM 0x0107
+#define MUCC_EVENT_REMOVE_ROOM 0x0108
+#define MUCC_EVENT_KICK_BAN 0x0109
+#define MUCC_EVENT_SET_USER_ROLE 0x010A
+#define MUCC_EVENT_UNBAN 0x010B
+/*
+ * Queries
+ */
+#define MUCC_EVENT_QUERY_GROUPS 0x0120
+#define MUCC_EVENT_QUERY_ROOMS 0x0121
+#define MUCC_EVENT_QUERY_USER_ROOMS 0x0122
+#define MUCC_EVENT_QUERY_USER_NICKS 0x0123
+#define MUCC_EVENT_QUERY_SEARCH 0x0124
+#define MUCC_EVENT_QUERY_CONTACTS 0x0130
+#define MUCC_EVENT_QUERY_USERS 0x0131
+/*
+ Event flags
+*/
+#define MUCC_EF_FONT_BOLD 0x000100 // Bold font flag (MUCC_EVENT_MESSAGE)
+#define MUCC_EF_FONT_ITALIC 0x000200 // Italic font flag (MUCC_EVENT_MESSAGE)
+#define MUCC_EF_FONT_UNDERLINE 0x000400 // Underlined font flags (MUCC_EVENT_MESSAGE)
+/*
+#define MUCC_EF_FONT_NAME 0x000800
+#define MUCC_EF_FONT_SIZE 0x001000
+#define MUCC_EF_FONT_COLOR 0x002000
+*/
+#define MUCC_EF_ROOM_PUBLIC 0x000001
+#define MUCC_EF_ROOM_NICKNAMES 0x000002
+#define MUCC_EF_ROOM_PERMANENT 0x000004
+#define MUCC_EF_ROOM_MEMBERS_ONLY 0x000008
+#define MUCC_EF_ROOM_MODERATED 0x000020
+#define MUCC_EF_ROOM_OFFICIAL 0x000040
+#define MUCC_EF_ROOM_NAME 0x100000
+
+#define MUCC_EF_USER_OWNER 0x000001
+#define MUCC_EF_USER_ADMIN 0x000002
+#define MUCC_EF_USER_REGISTERED 0x000004
+#define MUCC_EF_USER_MEMBER 0x000008
+#define MUCC_EF_USER_MODERATOR 0x000010
+#define MUCC_EF_USER_BANNED 0x000020
+#define MUCC_EF_USER_GLOBALOWNER 0x000040
+
+typedef struct {
+ int cbSize;
+ int iType; // Event type, one of MUCC_EVENT_* values
+ DWORD dwFlags; // Event flags - MUCC_EF_*
+ int iFont; // Text font index
+ int iFontSize; // Text font size
+ COLORREF color; // Text color
+ const char *pszModule; // Name of the module
+ const char *pszID; // Unique identifier of the chat room corresponding to the event,
+ const char *pszName; // Name of the chat room visible to the user
+ const char *pszUID; // User identifier, usage depends on type of event
+ const char *pszNick; // Nick, usage depends on type of event
+ const char *pszText; // Text, usage depends on type of event
+ DWORD dwData; // DWORD data e.g. status
+ BOOL bIsMe; // TRUE if the event is related to the user
+ time_t time; // Time of the event
+} MUCCEVENT;
+
+#define MS_MUCC_EVENT "MUCC/Event"
+#define ME_MUCC_EVENT "MUCC/OutgoingEvent"
+
+#endif
+
diff --git a/plugins/ExternalAPI/m_sendss.h b/plugins/ExternalAPI/m_sendss.h
new file mode 100644
index 0000000000..90cc84d421
--- /dev/null
+++ b/plugins/ExternalAPI/m_sendss.h
@@ -0,0 +1,66 @@
+//This file is part of Send Screenshot a Miranda IM plugin
+//Copyright (c) 2004-2006 S�rgio Vieira Rolanski
+//
+//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.
+//
+//You should have received a copy of the GNU General Public License
+//along with this program; if not, write to the Free Software
+//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+#ifndef _M_SENDSS_H_
+#define _M_SENDSS_H_
+
+//////////////////////////////////////////////////////////////////////////////
+// Open the main capture dialog, but does not capture anything
+// wParam = contact handle
+// lParam = 0
+// Returns zero on success
+// -1 if was not possibly to create capture window
+#define MS_SENDSS_OPENDIALOG "SendSS/OpenCaptureDialog"
+
+//////////////////////////////////////////////////////////////////////////////
+// Send an image to imageshack.us
+// wParam = (char*)filename
+// lParam = (HANDLE)contact (can be null)
+// v0.8.0.0+
+// Returns always 0 (if lParam != 0)
+// Returns (char*)URL or error message if lParam = 0. caller must mir_free the pointer
+#define MS_SENDSS_SEND2IMAGESHACK "SendSS/Send2ImageShack"
+
+//////////////////////////////////////////////////////////////////////////////
+// 1. Send a screenshot of the desktop to the selected contact
+// wParam = contact handle
+// lParam = 0
+// 2. Open the capture dialog in take screenshot only mode (it will not be sent)
+// wParam = 0
+// lParam = anything but 0
+// Returns:
+// zero on success
+// -1 if was not possibly to create capture window
+#define MS_SENDSS_SENDDESKTOP "SendSS/SendDesktop"
+
+//////////////////////////////////////////////////////////////////////////////
+// Edit a in-memory bitmap on the edit window
+// wParam = (SENDSSCB) callback function address to call when editing is done
+// lParam = (HBITMAP) bitmap handle, a copy is made so the calling function can free this handle after the service function returns
+// Returns:
+// Zero on success
+// -1 if could not create the edit window
+// -2 if was not possible to alocate needed memory
+#define MS_SENDSS_EDITBITMAP "SendSS/EditBitmap"
+
+// The parameter passed is the bitmap handle
+// the called function must free this handle when it's not needed anymore
+// Don't do much processing on the called function or you will lock miranda up
+typedef void (__stdcall *SENDSSCB)(LPVOID);
+
+#endif
+
diff --git a/plugins/FTPFileYM/common.h b/plugins/FTPFileYM/common.h
new file mode 100644
index 0000000000..d8d3ec56b4
--- /dev/null
+++ b/plugins/FTPFileYM/common.h
@@ -0,0 +1,129 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+// Modify the following defines if you have to target a platform prior to the ones specified below.
+// Refer to MSDN for the latest info on corresponding values for different platforms.
+#ifndef WINVER // Allow use of features specific to Windows XP or later.
+#define WINVER 0x0501 // Change this to the appropriate value to target other versions of Windows.
+#endif
+
+#ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later.
+#define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows.
+#endif
+
+#ifndef _WIN32_WINDOWS // Allow use of features specific to Windows 98 or later.
+#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
+#endif
+
+#ifndef _WIN32_IE // Allow use of features specific to IE 6.0 or later.
+#define _WIN32_IE 0x0600 // Change this to the appropriate value to target other versions of IE.
+#endif
+
+#define WIN32_LEAN_AND_MEAN
+#include <stdlib.h>
+#include <windows.h>
+#include <commdlg.h>
+#include <commctrl.h>
+#include <shellapi.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <uxtheme.h>
+#include <wininet.h>
+#include <windowsx.h>
+#include <shlobj.h>
+
+#ifdef _DEBUG
+#define _CRTDBG_MAP_ALLOC
+#include <crtdbg.h>
+#endif
+
+#include <vector>
+#include <iostream>
+using namespace std;
+
+#define MIRANDA_VER 0x0700
+#include <newpluginapi.h>
+#include <m_button.h>
+#include <m_clist.h>
+#include <m_clui.h>
+#include <m_database.h>
+#include <m_fontservice.h>
+#include <m_hotkeys.h>
+#include <m_icolib.h>
+#include <m_message.h>
+#include <m_langpack.h>
+#include <m_options.h>
+#include <m_popup.h>
+#include <m_protosvc.h>
+#include <m_skin.h>
+#include <m_system.h>
+#include <m_system_cpp.h>
+#include <m_utils.h>
+#include <win2k.h>
+
+#include "curl/curl.h"
+#include "sys/stat.h"
+
+#include "mir_db.h"
+#include "libcurl.h"
+
+#include "resource.h"
+#include "docs/m_ftpfile.h"
+#include "sdk/m_updater.h"
+#include "sdk/m_msg_buttonsbar.h"
+
+#if defined _WIN64
+#define MIID_FTPFILE { 0x6453cf27, 0xd111, 0x41f4, { 0xbe, 0xf5, 0xa8, 0xd8, 0x68, 0x8e, 0x44, 0xc6 } }
+#elif defined _UNICODE
+#define MIID_FTPFILE { 0x9502e511, 0x7e5d, 0x49a1, {0x8b, 0xa5, 0xb1, 0xae, 0xe7, 0xf, 0xa5, 0xbf } }
+#else
+#define MIID_FTPFILE { 0x64f80ef4, 0x856e, 0x4f27, { 0xb2, 0xa6, 0x47, 0x4a, 0x1, 0xff, 0x69, 0x83 } }
+#endif
+
+#ifndef SIZEOF
+#define SIZEOF(s) (sizeof(s) / sizeof((s)[0]))
+#endif
+
+#ifndef FREE
+#define FREE(X) if (X) { mir_free(X); X = NULL; }
+#endif
+
+#ifdef _DEBUG
+#define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
+#else
+#define DEBUG_CLIENTBLOCK
+#endif
+
+#ifdef _DEBUG
+#define new DEBUG_CLIENTBLOCK
+#endif
+
+#define MS_FTPFILE_SHAREFILE "FTPFile/ShareFiles"
+#define MS_FTPFILE_CONTACTMENU "FTPFile/ContactMenu"
+#define MS_FTPFILE_MAINMENU "FTPFile/MainMenu"
+
+#define MODULE "FTPFile"
+#define MODULE_FILES "FTPFile_Files"
+
+#define SOUND_UPCOMPLETE "ftpfile_upcomplete"
+#define SOUND_CANCEL "ftpfile_cancel"
+
+extern HINSTANCE hInst; \ No newline at end of file
diff --git a/plugins/FTPFileYM/curl/curl.h b/plugins/FTPFileYM/curl/curl.h
new file mode 100644
index 0000000000..973fdcc49d
--- /dev/null
+++ b/plugins/FTPFileYM/curl/curl.h
@@ -0,0 +1,1919 @@
+#ifndef __CURL_CURL_H
+#define __CURL_CURL_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: curl.h,v 1.390 2009-08-11 14:07:08 patrickm Exp $
+ ***************************************************************************/
+
+/*
+ * If you have libcurl problems, all docs and details are found here:
+ * http://curl.haxx.se/libcurl/
+ *
+ * curl-library mailing list subscription and unsubscription web interface:
+ * http://cool.haxx.se/mailman/listinfo/curl-library/
+ */
+
+#include "curlver.h" /* libcurl version defines */
+#include "curl/curlbuild.h" /* libcurl build definitions */
+#include "curlrules.h" /* libcurl rules enforcement */
+
+/*
+ * Define WIN32 when build target is Win32 API
+ */
+
+#if (defined(_WIN32) || defined(__WIN32__)) && \
+ !defined(WIN32) && !defined(__SYMBIAN32__)
+#define WIN32
+#endif
+
+#include <stdio.h>
+#include <limits.h>
+
+/* The include stuff here below is mainly for time_t! */
+#include <sys/types.h>
+#include <time.h>
+
+#if defined(WIN32) && !defined(_WIN32_WCE) && !defined(__GNUC__) && \
+ !defined(__CYGWIN__) || defined(__MINGW32__)
+#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H))
+/* The check above prevents the winsock2 inclusion if winsock.h already was
+ included, since they can't co-exist without problems */
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#else
+
+/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish
+ libc5-based Linux systems. Only include it on system that are known to
+ require it! */
+#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \
+ defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \
+ defined(ANDROID)
+#include <sys/select.h>
+#endif
+
+#ifndef _WIN32_WCE
+#include <sys/socket.h>
+#endif
+#if !defined(WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__)
+#include <sys/time.h>
+#endif
+#include <sys/types.h>
+#endif
+
+#ifdef __BEOS__
+#include <support/SupportDefs.h>
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void CURL;
+
+/*
+ * Decorate exportable functions for Win32 and Symbian OS DLL linking.
+ * This avoids using a .def file for building libcurl.dll.
+ */
+#if (defined(WIN32) || defined(_WIN32) || defined(__SYMBIAN32__)) && \
+ !defined(CURL_STATICLIB)
+#if defined(BUILDING_LIBCURL)
+#define CURL_EXTERN __declspec(dllexport)
+#else
+#define CURL_EXTERN __declspec(dllimport)
+#endif
+#else
+
+#ifdef CURL_HIDDEN_SYMBOLS
+/*
+ * This definition is used to make external definitions visible in the
+ * shared library when symbols are hidden by default. It makes no
+ * difference when compiling applications whether this is set or not,
+ * only when compiling the library.
+ */
+#define CURL_EXTERN CURL_EXTERN_SYMBOL
+#else
+#define CURL_EXTERN
+#endif
+#endif
+
+#ifndef curl_socket_typedef
+/* socket typedef */
+#ifdef WIN32
+typedef SOCKET curl_socket_t;
+#define CURL_SOCKET_BAD INVALID_SOCKET
+#else
+typedef int curl_socket_t;
+#define CURL_SOCKET_BAD -1
+#endif
+#define curl_socket_typedef
+#endif /* curl_socket_typedef */
+
+struct curl_httppost {
+ struct curl_httppost *next; /* next entry in the list */
+ char *name; /* pointer to allocated name */
+ long namelength; /* length of name length */
+ char *contents; /* pointer to allocated data contents */
+ long contentslength; /* length of contents field */
+ char *buffer; /* pointer to allocated buffer contents */
+ long bufferlength; /* length of buffer field */
+ char *contenttype; /* Content-Type */
+ struct curl_slist* contentheader; /* list of extra headers for this form */
+ struct curl_httppost *more; /* if one field name has more than one
+ file, this link should link to following
+ files */
+ long flags; /* as defined below */
+#define HTTPPOST_FILENAME (1<<0) /* specified content is a file name */
+#define HTTPPOST_READFILE (1<<1) /* specified content is a file name */
+#define HTTPPOST_PTRNAME (1<<2) /* name is only stored pointer
+ do not free in formfree */
+#define HTTPPOST_PTRCONTENTS (1<<3) /* contents is only stored pointer
+ do not free in formfree */
+#define HTTPPOST_BUFFER (1<<4) /* upload file from buffer */
+#define HTTPPOST_PTRBUFFER (1<<5) /* upload file from pointer contents */
+#define HTTPPOST_CALLBACK (1<<6) /* upload file contents by using the
+ regular read callback to get the data
+ and pass the given pointer as custom
+ pointer */
+
+ char *showfilename; /* The file name to show. If not set, the
+ actual file name will be used (if this
+ is a file part) */
+ void *userp; /* custom pointer used for
+ HTTPPOST_CALLBACK posts */
+};
+
+typedef int (*curl_progress_callback)(void *clientp,
+ double dltotal,
+ double dlnow,
+ double ultotal,
+ double ulnow);
+
+#ifndef CURL_MAX_WRITE_SIZE
+ /* Tests have proven that 20K is a very bad buffer size for uploads on
+ Windows, while 16K for some odd reason performed a lot better.
+ We do the ifndef check to allow this value to easier be changed at build
+ time for those who feel adventurous. */
+#define CURL_MAX_WRITE_SIZE 16384
+#endif
+/* This is a magic return code for the write callback that, when returned,
+ will signal libcurl to pause receiving on the current transfer. */
+#define CURL_WRITEFUNC_PAUSE 0x10000001
+typedef size_t (*curl_write_callback)(char *buffer,
+ size_t size,
+ size_t nitems,
+ void *outstream);
+
+/* These are the return codes for the seek callbacks */
+#define CURL_SEEKFUNC_OK 0
+#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */
+#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so
+ libcurl might try other means instead */
+typedef int (*curl_seek_callback)(void *instream,
+ curl_off_t offset,
+ int origin); /* 'whence' */
+
+/* This is a return code for the read callback that, when returned, will
+ signal libcurl to immediately abort the current transfer. */
+#define CURL_READFUNC_ABORT 0x10000000
+/* This is a return code for the read callback that, when returned, will
+ signal libcurl to pause sending data on the current transfer. */
+#define CURL_READFUNC_PAUSE 0x10000001
+
+typedef size_t (*curl_read_callback)(char *buffer,
+ size_t size,
+ size_t nitems,
+ void *instream);
+
+typedef enum {
+ CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */
+ CURLSOCKTYPE_LAST /* never use */
+} curlsocktype;
+
+typedef int (*curl_sockopt_callback)(void *clientp,
+ curl_socket_t curlfd,
+ curlsocktype purpose);
+
+struct curl_sockaddr {
+ int family;
+ int socktype;
+ int protocol;
+ unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it
+ turned really ugly and painful on the systems that
+ lack this type */
+ struct sockaddr addr;
+};
+
+typedef curl_socket_t
+(*curl_opensocket_callback)(void *clientp,
+ curlsocktype purpose,
+ struct curl_sockaddr *address);
+
+#ifndef CURL_NO_OLDIES
+ /* not used since 7.10.8, will be removed in a future release */
+typedef int (*curl_passwd_callback)(void *clientp,
+ const char *prompt,
+ char *buffer,
+ int buflen);
+#endif
+
+typedef enum {
+ CURLIOE_OK, /* I/O operation successful */
+ CURLIOE_UNKNOWNCMD, /* command was unknown to callback */
+ CURLIOE_FAILRESTART, /* failed to restart the read */
+ CURLIOE_LAST /* never use */
+} curlioerr;
+
+typedef enum {
+ CURLIOCMD_NOP, /* no operation */
+ CURLIOCMD_RESTARTREAD, /* restart the read stream from start */
+ CURLIOCMD_LAST /* never use */
+} curliocmd;
+
+typedef curlioerr (*curl_ioctl_callback)(CURL *handle,
+ int cmd,
+ void *clientp);
+
+/*
+ * The following typedef's are signatures of malloc, free, realloc, strdup and
+ * calloc respectively. Function pointers of these types can be passed to the
+ * curl_global_init_mem() function to set user defined memory management
+ * callback routines.
+ */
+typedef void *(*curl_malloc_callback)(size_t size);
+typedef void (*curl_free_callback)(void *ptr);
+typedef void *(*curl_realloc_callback)(void *ptr, size_t size);
+typedef char *(*curl_strdup_callback)(const char *str);
+typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size);
+
+/* the kind of data that is passed to information_callback*/
+typedef enum {
+ CURLINFO_TEXT = 0,
+ CURLINFO_HEADER_IN, /* 1 */
+ CURLINFO_HEADER_OUT, /* 2 */
+ CURLINFO_DATA_IN, /* 3 */
+ CURLINFO_DATA_OUT, /* 4 */
+ CURLINFO_SSL_DATA_IN, /* 5 */
+ CURLINFO_SSL_DATA_OUT, /* 6 */
+ CURLINFO_END
+} curl_infotype;
+
+typedef int (*curl_debug_callback)
+ (CURL *handle, /* the handle/transfer this concerns */
+ curl_infotype type, /* what kind of data */
+ char *data, /* points to the data */
+ size_t size, /* size of the data pointed to */
+ void *userptr); /* whatever the user please */
+
+/* All possible error codes from all sorts of curl functions. Future versions
+ may return other values, stay prepared.
+
+ Always add new return codes last. Never *EVER* remove any. The return
+ codes must remain the same!
+ */
+
+typedef enum {
+ CURLE_OK = 0,
+ CURLE_UNSUPPORTED_PROTOCOL, /* 1 */
+ CURLE_FAILED_INIT, /* 2 */
+ CURLE_URL_MALFORMAT, /* 3 */
+ CURLE_OBSOLETE4, /* 4 - NOT USED */
+ CURLE_COULDNT_RESOLVE_PROXY, /* 5 */
+ CURLE_COULDNT_RESOLVE_HOST, /* 6 */
+ CURLE_COULDNT_CONNECT, /* 7 */
+ CURLE_FTP_WEIRD_SERVER_REPLY, /* 8 */
+ CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server
+ due to lack of access - when login fails
+ this is not returned. */
+ CURLE_OBSOLETE10, /* 10 - NOT USED */
+ CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */
+ CURLE_OBSOLETE12, /* 12 - NOT USED */
+ CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */
+ CURLE_FTP_WEIRD_227_FORMAT, /* 14 */
+ CURLE_FTP_CANT_GET_HOST, /* 15 */
+ CURLE_OBSOLETE16, /* 16 - NOT USED */
+ CURLE_FTP_COULDNT_SET_TYPE, /* 17 */
+ CURLE_PARTIAL_FILE, /* 18 */
+ CURLE_FTP_COULDNT_RETR_FILE, /* 19 */
+ CURLE_OBSOLETE20, /* 20 - NOT USED */
+ CURLE_QUOTE_ERROR, /* 21 - quote command failure */
+ CURLE_HTTP_RETURNED_ERROR, /* 22 */
+ CURLE_WRITE_ERROR, /* 23 */
+ CURLE_OBSOLETE24, /* 24 - NOT USED */
+ CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */
+ CURLE_READ_ERROR, /* 26 - couldn't open/read from file */
+ CURLE_OUT_OF_MEMORY, /* 27 */
+ /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error
+ instead of a memory allocation error if CURL_DOES_CONVERSIONS
+ is defined
+ */
+ CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */
+ CURLE_OBSOLETE29, /* 29 - NOT USED */
+ CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */
+ CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */
+ CURLE_OBSOLETE32, /* 32 - NOT USED */
+ CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */
+ CURLE_HTTP_POST_ERROR, /* 34 */
+ CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */
+ CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */
+ CURLE_FILE_COULDNT_READ_FILE, /* 37 */
+ CURLE_LDAP_CANNOT_BIND, /* 38 */
+ CURLE_LDAP_SEARCH_FAILED, /* 39 */
+ CURLE_OBSOLETE40, /* 40 - NOT USED */
+ CURLE_FUNCTION_NOT_FOUND, /* 41 */
+ CURLE_ABORTED_BY_CALLBACK, /* 42 */
+ CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */
+ CURLE_OBSOLETE44, /* 44 - NOT USED */
+ CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */
+ CURLE_OBSOLETE46, /* 46 - NOT USED */
+ CURLE_TOO_MANY_REDIRECTS , /* 47 - catch endless re-direct loops */
+ CURLE_UNKNOWN_TELNET_OPTION, /* 48 - User specified an unknown option */
+ CURLE_TELNET_OPTION_SYNTAX , /* 49 - Malformed telnet option */
+ CURLE_OBSOLETE50, /* 50 - NOT USED */
+ CURLE_PEER_FAILED_VERIFICATION, /* 51 - peer's certificate or fingerprint
+ wasn't verified fine */
+ CURLE_GOT_NOTHING, /* 52 - when this is a specific error */
+ CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */
+ CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as
+ default */
+ CURLE_SEND_ERROR, /* 55 - failed sending network data */
+ CURLE_RECV_ERROR, /* 56 - failure in receiving network data */
+ CURLE_OBSOLETE57, /* 57 - NOT IN USE */
+ CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */
+ CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */
+ CURLE_SSL_CACERT, /* 60 - problem with the CA cert (path?) */
+ CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized transfer encoding */
+ CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */
+ CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */
+ CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */
+ CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind
+ that failed */
+ CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */
+ CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not
+ accepted and we failed to login */
+ CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */
+ CURLE_TFTP_PERM, /* 69 - permission problem on server */
+ CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */
+ CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */
+ CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */
+ CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */
+ CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */
+ CURLE_CONV_FAILED, /* 75 - conversion failed */
+ CURLE_CONV_REQD, /* 76 - caller must register conversion
+ callbacks using curl_easy_setopt options
+ CURLOPT_CONV_FROM_NETWORK_FUNCTION,
+ CURLOPT_CONV_TO_NETWORK_FUNCTION, and
+ CURLOPT_CONV_FROM_UTF8_FUNCTION */
+ CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing
+ or wrong format */
+ CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */
+ CURLE_SSH, /* 79 - error from the SSH layer, somewhat
+ generic so the error message will be of
+ interest when this has happened */
+
+ CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL
+ connection */
+ CURLE_AGAIN, /* 81 - socket is not ready for send/recv,
+ wait till it's ready and try again (Added
+ in 7.18.2) */
+ CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or
+ wrong format (Added in 7.19.0) */
+ CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in
+ 7.19.0) */
+ CURL_LAST /* never use! */
+} CURLcode;
+
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
+/* Backwards compatibility with older names */
+
+/* The following were added in 7.17.1 */
+/* These are scheduled to disappear by 2009 */
+#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION
+
+/* The following were added in 7.17.0 */
+/* These are scheduled to disappear by 2009 */
+#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* noone should be using this! */
+#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46
+#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44
+#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10
+#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16
+#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32
+#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29
+#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12
+#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20
+#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40
+#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24
+#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57
+#define CURLE_URL_MALFORMAT_USER CURLE_OBSOLETE4
+
+#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED
+#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE
+#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR
+#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL
+#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS
+#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR
+#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED
+
+/* The following were added earlier */
+
+#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT
+
+#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR
+#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED
+#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED
+
+#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE
+#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME
+
+/* This was the error code 50 in 7.7.3 and a few earlier versions, this
+ is no longer used by libcurl but is instead #defined here only to not
+ make programs break */
+#define CURLE_ALREADY_COMPLETE 99999
+
+#endif /*!CURL_NO_OLDIES*/
+
+/* This prototype applies to all conversion callbacks */
+typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length);
+
+typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */
+ void *ssl_ctx, /* actually an
+ OpenSSL SSL_CTX */
+ void *userptr);
+
+typedef enum {
+ CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use
+ CONNECT HTTP/1.1 */
+ CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT
+ HTTP/1.0 */
+ CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already
+ in 7.10 */
+ CURLPROXY_SOCKS5 = 5, /* added in 7.10 */
+ CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */
+ CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the
+ host name rather than the IP address. added
+ in 7.18.0 */
+} curl_proxytype; /* this enum was added in 7.10 */
+
+#define CURLAUTH_NONE 0 /* nothing */
+#define CURLAUTH_BASIC (1<<0) /* Basic (default) */
+#define CURLAUTH_DIGEST (1<<1) /* Digest */
+#define CURLAUTH_GSSNEGOTIATE (1<<2) /* GSS-Negotiate */
+#define CURLAUTH_NTLM (1<<3) /* NTLM */
+#define CURLAUTH_DIGEST_IE (1<<4) /* Digest with IE flavour */
+#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE) /* all fine types set */
+#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE))
+
+#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */
+#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */
+#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */
+#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */
+#define CURLSSH_AUTH_HOST (1<<2) /* host key files */
+#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */
+#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY
+
+#define CURL_ERROR_SIZE 256
+
+struct curl_khkey {
+ const char *key; /* points to a zero-terminated string encoded with base64
+ if len is zero, otherwise to the "raw" data */
+ size_t len;
+ enum type {
+ CURLKHTYPE_UNKNOWN,
+ CURLKHTYPE_RSA1,
+ CURLKHTYPE_RSA,
+ CURLKHTYPE_DSS
+ } keytype;
+};
+
+/* this is the set of return values expected from the curl_sshkeycallback
+ callback */
+enum curl_khstat {
+ CURLKHSTAT_FINE_ADD_TO_FILE,
+ CURLKHSTAT_FINE,
+ CURLKHSTAT_REJECT, /* reject the connection, return an error */
+ CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so
+ this causes a CURLE_DEFER error but otherwise the
+ connection will be left intact etc */
+ CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */
+};
+
+/* this is the set of status codes pass in to the callback */
+enum curl_khmatch {
+ CURLKHMATCH_OK, /* match */
+ CURLKHMATCH_MISMATCH, /* host found, key mismatch! */
+ CURLKHMATCH_MISSING, /* no matching host/key found */
+ CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */
+};
+
+typedef int
+ (*curl_sshkeycallback) (CURL *easy, /* easy handle */
+ const struct curl_khkey *knownkey, /* known */
+ const struct curl_khkey *foundkey, /* found */
+ enum curl_khmatch, /* libcurl's view on the keys */
+ void *clientp); /* custom pointer passed from app */
+
+/* parameter for the CURLOPT_USE_SSL option */
+typedef enum {
+ CURLUSESSL_NONE, /* do not attempt to use SSL */
+ CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */
+ CURLUSESSL_CONTROL, /* SSL for the control connection or fail */
+ CURLUSESSL_ALL, /* SSL for all communication or fail */
+ CURLUSESSL_LAST /* not an option, never use */
+} curl_usessl;
+
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
+/* Backwards compatibility with older names */
+/* These are scheduled to disappear by 2009 */
+
+#define CURLFTPSSL_NONE CURLUSESSL_NONE
+#define CURLFTPSSL_TRY CURLUSESSL_TRY
+#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL
+#define CURLFTPSSL_ALL CURLUSESSL_ALL
+#define CURLFTPSSL_LAST CURLUSESSL_LAST
+#define curl_ftpssl curl_usessl
+#endif /*!CURL_NO_OLDIES*/
+
+/* parameter for the CURLOPT_FTP_SSL_CCC option */
+typedef enum {
+ CURLFTPSSL_CCC_NONE, /* do not send CCC */
+ CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */
+ CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */
+ CURLFTPSSL_CCC_LAST /* not an option, never use */
+} curl_ftpccc;
+
+/* parameter for the CURLOPT_FTPSSLAUTH option */
+typedef enum {
+ CURLFTPAUTH_DEFAULT, /* let libcurl decide */
+ CURLFTPAUTH_SSL, /* use "AUTH SSL" */
+ CURLFTPAUTH_TLS, /* use "AUTH TLS" */
+ CURLFTPAUTH_LAST /* not an option, never use */
+} curl_ftpauth;
+
+/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */
+typedef enum {
+ CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */
+ CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD
+ again if MKD succeeded, for SFTP this does
+ similar magic */
+ CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD
+ again even if MKD failed! */
+ CURLFTP_CREATE_DIR_LAST /* not an option, never use */
+} curl_ftpcreatedir;
+
+/* parameter for the CURLOPT_FTP_FILEMETHOD option */
+typedef enum {
+ CURLFTPMETHOD_DEFAULT, /* let libcurl pick */
+ CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */
+ CURLFTPMETHOD_NOCWD, /* no CWD at all */
+ CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */
+ CURLFTPMETHOD_LAST /* not an option, never use */
+} curl_ftpmethod;
+
+/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */
+#define CURLPROTO_HTTP (1<<0)
+#define CURLPROTO_HTTPS (1<<1)
+#define CURLPROTO_FTP (1<<2)
+#define CURLPROTO_FTPS (1<<3)
+#define CURLPROTO_SCP (1<<4)
+#define CURLPROTO_SFTP (1<<5)
+#define CURLPROTO_TELNET (1<<6)
+#define CURLPROTO_LDAP (1<<7)
+#define CURLPROTO_LDAPS (1<<8)
+#define CURLPROTO_DICT (1<<9)
+#define CURLPROTO_FILE (1<<10)
+#define CURLPROTO_TFTP (1<<11)
+#define CURLPROTO_ALL (~0) /* enable everything */
+
+/* long may be 32 or 64 bits, but we should never depend on anything else
+ but 32 */
+#define CURLOPTTYPE_LONG 0
+#define CURLOPTTYPE_OBJECTPOINT 10000
+#define CURLOPTTYPE_FUNCTIONPOINT 20000
+#define CURLOPTTYPE_OFF_T 30000
+
+/* name is uppercase CURLOPT_<name>,
+ type is one of the defined CURLOPTTYPE_<type>
+ number is unique identifier */
+#ifdef CINIT
+#undef CINIT
+#endif
+
+#ifdef CURL_ISOCPP
+#define CINIT(name,type,number) CURLOPT_ ## name = CURLOPTTYPE_ ## type + number
+#else
+/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */
+#define LONG CURLOPTTYPE_LONG
+#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT
+#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT
+#define OFF_T CURLOPTTYPE_OFF_T
+#define CINIT(name,type,number) CURLOPT_/**/name = type + number
+#endif
+
+/*
+ * This macro-mania below setups the CURLOPT_[what] enum, to be used with
+ * curl_easy_setopt(). The first argument in the CINIT() macro is the [what]
+ * word.
+ */
+
+typedef enum {
+ /* This is the FILE * or void * the regular output should be written to. */
+ CINIT(FILE, OBJECTPOINT, 1),
+
+ /* The full URL to get/put */
+ CINIT(URL, OBJECTPOINT, 2),
+
+ /* Port number to connect to, if other than default. */
+ CINIT(PORT, LONG, 3),
+
+ /* Name of proxy to use. */
+ CINIT(PROXY, OBJECTPOINT, 4),
+
+ /* "name:password" to use when fetching. */
+ CINIT(USERPWD, OBJECTPOINT, 5),
+
+ /* "name:password" to use with proxy. */
+ CINIT(PROXYUSERPWD, OBJECTPOINT, 6),
+
+ /* Range to get, specified as an ASCII string. */
+ CINIT(RANGE, OBJECTPOINT, 7),
+
+ /* not used */
+
+ /* Specified file stream to upload from (use as input): */
+ CINIT(INFILE, OBJECTPOINT, 9),
+
+ /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE
+ * bytes big. If this is not used, error messages go to stderr instead: */
+ CINIT(ERRORBUFFER, OBJECTPOINT, 10),
+
+ /* Function that will be called to store the output (instead of fwrite). The
+ * parameters will use fwrite() syntax, make sure to follow them. */
+ CINIT(WRITEFUNCTION, FUNCTIONPOINT, 11),
+
+ /* Function that will be called to read the input (instead of fread). The
+ * parameters will use fread() syntax, make sure to follow them. */
+ CINIT(READFUNCTION, FUNCTIONPOINT, 12),
+
+ /* Time-out the read operation after this amount of seconds */
+ CINIT(TIMEOUT, LONG, 13),
+
+ /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about
+ * how large the file being sent really is. That allows better error
+ * checking and better verifies that the upload was successful. -1 means
+ * unknown size.
+ *
+ * For large file support, there is also a _LARGE version of the key
+ * which takes an off_t type, allowing platforms with larger off_t
+ * sizes to handle larger files. See below for INFILESIZE_LARGE.
+ */
+ CINIT(INFILESIZE, LONG, 14),
+
+ /* POST static input fields. */
+ CINIT(POSTFIELDS, OBJECTPOINT, 15),
+
+ /* Set the referrer page (needed by some CGIs) */
+ CINIT(REFERER, OBJECTPOINT, 16),
+
+ /* Set the FTP PORT string (interface name, named or numerical IP address)
+ Use i.e '-' to use default address. */
+ CINIT(FTPPORT, OBJECTPOINT, 17),
+
+ /* Set the User-Agent string (examined by some CGIs) */
+ CINIT(USERAGENT, OBJECTPOINT, 18),
+
+ /* If the download receives less than "low speed limit" bytes/second
+ * during "low speed time" seconds, the operations is aborted.
+ * You could i.e if you have a pretty high speed connection, abort if
+ * it is less than 2000 bytes/sec during 20 seconds.
+ */
+
+ /* Set the "low speed limit" */
+ CINIT(LOW_SPEED_LIMIT, LONG, 19),
+
+ /* Set the "low speed time" */
+ CINIT(LOW_SPEED_TIME, LONG, 20),
+
+ /* Set the continuation offset.
+ *
+ * Note there is also a _LARGE version of this key which uses
+ * off_t types, allowing for large file offsets on platforms which
+ * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE.
+ */
+ CINIT(RESUME_FROM, LONG, 21),
+
+ /* Set cookie in request: */
+ CINIT(COOKIE, OBJECTPOINT, 22),
+
+ /* This points to a linked list of headers, struct curl_slist kind */
+ CINIT(HTTPHEADER, OBJECTPOINT, 23),
+
+ /* This points to a linked list of post entries, struct curl_httppost */
+ CINIT(HTTPPOST, OBJECTPOINT, 24),
+
+ /* name of the file keeping your private SSL-certificate */
+ CINIT(SSLCERT, OBJECTPOINT, 25),
+
+ /* password for the SSL or SSH private key */
+ CINIT(KEYPASSWD, OBJECTPOINT, 26),
+
+ /* send TYPE parameter? */
+ CINIT(CRLF, LONG, 27),
+
+ /* send linked-list of QUOTE commands */
+ CINIT(QUOTE, OBJECTPOINT, 28),
+
+ /* send FILE * or void * to store headers to, if you use a callback it
+ is simply passed to the callback unmodified */
+ CINIT(WRITEHEADER, OBJECTPOINT, 29),
+
+ /* point to a file to read the initial cookies from, also enables
+ "cookie awareness" */
+ CINIT(COOKIEFILE, OBJECTPOINT, 31),
+
+ /* What version to specifically try to use.
+ See CURL_SSLVERSION defines below. */
+ CINIT(SSLVERSION, LONG, 32),
+
+ /* What kind of HTTP time condition to use, see defines */
+ CINIT(TIMECONDITION, LONG, 33),
+
+ /* Time to use with the above condition. Specified in number of seconds
+ since 1 Jan 1970 */
+ CINIT(TIMEVALUE, LONG, 34),
+
+ /* 35 = OBSOLETE */
+
+ /* Custom request, for customizing the get command like
+ HTTP: DELETE, TRACE and others
+ FTP: to use a different list command
+ */
+ CINIT(CUSTOMREQUEST, OBJECTPOINT, 36),
+
+ /* HTTP request, for odd commands like DELETE, TRACE and others */
+ CINIT(STDERR, OBJECTPOINT, 37),
+
+ /* 38 is not used */
+
+ /* send linked-list of post-transfer QUOTE commands */
+ CINIT(POSTQUOTE, OBJECTPOINT, 39),
+
+ /* Pass a pointer to string of the output using full variable-replacement
+ as described elsewhere. */
+ CINIT(WRITEINFO, OBJECTPOINT, 40),
+
+ CINIT(VERBOSE, LONG, 41), /* talk a lot */
+ CINIT(HEADER, LONG, 42), /* throw the header out too */
+ CINIT(NOPROGRESS, LONG, 43), /* shut off the progress meter */
+ CINIT(NOBODY, LONG, 44), /* use HEAD to get http document */
+ CINIT(FAILONERROR, LONG, 45), /* no output on http error codes >= 300 */
+ CINIT(UPLOAD, LONG, 46), /* this is an upload */
+ CINIT(POST, LONG, 47), /* HTTP POST method */
+ CINIT(DIRLISTONLY, LONG, 48), /* return bare names when listing directories */
+
+ CINIT(APPEND, LONG, 50), /* Append instead of overwrite on upload! */
+
+ /* Specify whether to read the user+password from the .netrc or the URL.
+ * This must be one of the CURL_NETRC_* enums below. */
+ CINIT(NETRC, LONG, 51),
+
+ CINIT(FOLLOWLOCATION, LONG, 52), /* use Location: Luke! */
+
+ CINIT(TRANSFERTEXT, LONG, 53), /* transfer data in text/ASCII format */
+ CINIT(PUT, LONG, 54), /* HTTP PUT */
+
+ /* 55 = OBSOLETE */
+
+ /* Function that will be called instead of the internal progress display
+ * function. This function should be defined as the curl_progress_callback
+ * prototype defines. */
+ CINIT(PROGRESSFUNCTION, FUNCTIONPOINT, 56),
+
+ /* Data passed to the progress callback */
+ CINIT(PROGRESSDATA, OBJECTPOINT, 57),
+
+ /* We want the referrer field set automatically when following locations */
+ CINIT(AUTOREFERER, LONG, 58),
+
+ /* Port of the proxy, can be set in the proxy string as well with:
+ "[host]:[port]" */
+ CINIT(PROXYPORT, LONG, 59),
+
+ /* size of the POST input data, if strlen() is not good to use */
+ CINIT(POSTFIELDSIZE, LONG, 60),
+
+ /* tunnel non-http operations through a HTTP proxy */
+ CINIT(HTTPPROXYTUNNEL, LONG, 61),
+
+ /* Set the interface string to use as outgoing network interface */
+ CINIT(INTERFACE, OBJECTPOINT, 62),
+
+ /* Set the krb4/5 security level, this also enables krb4/5 awareness. This
+ * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string
+ * is set but doesn't match one of these, 'private' will be used. */
+ CINIT(KRBLEVEL, OBJECTPOINT, 63),
+
+ /* Set if we should verify the peer in ssl handshake, set 1 to verify. */
+ CINIT(SSL_VERIFYPEER, LONG, 64),
+
+ /* The CApath or CAfile used to validate the peer certificate
+ this option is used only if SSL_VERIFYPEER is true */
+ CINIT(CAINFO, OBJECTPOINT, 65),
+
+ /* 66 = OBSOLETE */
+ /* 67 = OBSOLETE */
+
+ /* Maximum number of http redirects to follow */
+ CINIT(MAXREDIRS, LONG, 68),
+
+ /* Pass a long set to 1 to get the date of the requested document (if
+ possible)! Pass a zero to shut it off. */
+ CINIT(FILETIME, LONG, 69),
+
+ /* This points to a linked list of telnet options */
+ CINIT(TELNETOPTIONS, OBJECTPOINT, 70),
+
+ /* Max amount of cached alive connections */
+ CINIT(MAXCONNECTS, LONG, 71),
+
+ /* What policy to use when closing connections when the cache is filled
+ up */
+ CINIT(CLOSEPOLICY, LONG, 72),
+
+ /* 73 = OBSOLETE */
+
+ /* Set to explicitly use a new connection for the upcoming transfer.
+ Do not use this unless you're absolutely sure of this, as it makes the
+ operation slower and is less friendly for the network. */
+ CINIT(FRESH_CONNECT, LONG, 74),
+
+ /* Set to explicitly forbid the upcoming transfer's connection to be re-used
+ when done. Do not use this unless you're absolutely sure of this, as it
+ makes the operation slower and is less friendly for the network. */
+ CINIT(FORBID_REUSE, LONG, 75),
+
+ /* Set to a file name that contains random data for libcurl to use to
+ seed the random engine when doing SSL connects. */
+ CINIT(RANDOM_FILE, OBJECTPOINT, 76),
+
+ /* Set to the Entropy Gathering Daemon socket pathname */
+ CINIT(EGDSOCKET, OBJECTPOINT, 77),
+
+ /* Time-out connect operations after this amount of seconds, if connects
+ are OK within this time, then fine... This only aborts the connect
+ phase. [Only works on unix-style/SIGALRM operating systems] */
+ CINIT(CONNECTTIMEOUT, LONG, 78),
+
+ /* Function that will be called to store headers (instead of fwrite). The
+ * parameters will use fwrite() syntax, make sure to follow them. */
+ CINIT(HEADERFUNCTION, FUNCTIONPOINT, 79),
+
+ /* Set this to force the HTTP request to get back to GET. Only really usable
+ if POST, PUT or a custom request have been used first.
+ */
+ CINIT(HTTPGET, LONG, 80),
+
+ /* Set if we should verify the Common name from the peer certificate in ssl
+ * handshake, set 1 to check existence, 2 to ensure that it matches the
+ * provided hostname. */
+ CINIT(SSL_VERIFYHOST, LONG, 81),
+
+ /* Specify which file name to write all known cookies in after completed
+ operation. Set file name to "-" (dash) to make it go to stdout. */
+ CINIT(COOKIEJAR, OBJECTPOINT, 82),
+
+ /* Specify which SSL ciphers to use */
+ CINIT(SSL_CIPHER_LIST, OBJECTPOINT, 83),
+
+ /* Specify which HTTP version to use! This must be set to one of the
+ CURL_HTTP_VERSION* enums set below. */
+ CINIT(HTTP_VERSION, LONG, 84),
+
+ /* Specifically switch on or off the FTP engine's use of the EPSV command. By
+ default, that one will always be attempted before the more traditional
+ PASV command. */
+ CINIT(FTP_USE_EPSV, LONG, 85),
+
+ /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */
+ CINIT(SSLCERTTYPE, OBJECTPOINT, 86),
+
+ /* name of the file keeping your private SSL-key */
+ CINIT(SSLKEY, OBJECTPOINT, 87),
+
+ /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */
+ CINIT(SSLKEYTYPE, OBJECTPOINT, 88),
+
+ /* crypto engine for the SSL-sub system */
+ CINIT(SSLENGINE, OBJECTPOINT, 89),
+
+ /* set the crypto engine for the SSL-sub system as default
+ the param has no meaning...
+ */
+ CINIT(SSLENGINE_DEFAULT, LONG, 90),
+
+ /* Non-zero value means to use the global dns cache */
+ CINIT(DNS_USE_GLOBAL_CACHE, LONG, 91), /* To become OBSOLETE soon */
+
+ /* DNS cache timeout */
+ CINIT(DNS_CACHE_TIMEOUT, LONG, 92),
+
+ /* send linked-list of pre-transfer QUOTE commands */
+ CINIT(PREQUOTE, OBJECTPOINT, 93),
+
+ /* set the debug function */
+ CINIT(DEBUGFUNCTION, FUNCTIONPOINT, 94),
+
+ /* set the data for the debug function */
+ CINIT(DEBUGDATA, OBJECTPOINT, 95),
+
+ /* mark this as start of a cookie session */
+ CINIT(COOKIESESSION, LONG, 96),
+
+ /* The CApath directory used to validate the peer certificate
+ this option is used only if SSL_VERIFYPEER is true */
+ CINIT(CAPATH, OBJECTPOINT, 97),
+
+ /* Instruct libcurl to use a smaller receive buffer */
+ CINIT(BUFFERSIZE, LONG, 98),
+
+ /* Instruct libcurl to not use any signal/alarm handlers, even when using
+ timeouts. This option is useful for multi-threaded applications.
+ See libcurl-the-guide for more background information. */
+ CINIT(NOSIGNAL, LONG, 99),
+
+ /* Provide a CURLShare for mutexing non-ts data */
+ CINIT(SHARE, OBJECTPOINT, 100),
+
+ /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default),
+ CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and CURLPROXY_SOCKS5. */
+ CINIT(PROXYTYPE, LONG, 101),
+
+ /* Set the Accept-Encoding string. Use this to tell a server you would like
+ the response to be compressed. */
+ CINIT(ENCODING, OBJECTPOINT, 102),
+
+ /* Set pointer to private data */
+ CINIT(PRIVATE, OBJECTPOINT, 103),
+
+ /* Set aliases for HTTP 200 in the HTTP Response header */
+ CINIT(HTTP200ALIASES, OBJECTPOINT, 104),
+
+ /* Continue to send authentication (user+password) when following locations,
+ even when hostname changed. This can potentially send off the name
+ and password to whatever host the server decides. */
+ CINIT(UNRESTRICTED_AUTH, LONG, 105),
+
+ /* Specifically switch on or off the FTP engine's use of the EPRT command ( it
+ also disables the LPRT attempt). By default, those ones will always be
+ attempted before the good old traditional PORT command. */
+ CINIT(FTP_USE_EPRT, LONG, 106),
+
+ /* Set this to a bitmask value to enable the particular authentications
+ methods you like. Use this in combination with CURLOPT_USERPWD.
+ Note that setting multiple bits may cause extra network round-trips. */
+ CINIT(HTTPAUTH, LONG, 107),
+
+ /* Set the ssl context callback function, currently only for OpenSSL ssl_ctx
+ in second argument. The function must be matching the
+ curl_ssl_ctx_callback proto. */
+ CINIT(SSL_CTX_FUNCTION, FUNCTIONPOINT, 108),
+
+ /* Set the userdata for the ssl context callback function's third
+ argument */
+ CINIT(SSL_CTX_DATA, OBJECTPOINT, 109),
+
+ /* FTP Option that causes missing dirs to be created on the remote server.
+ In 7.19.4 we introduced the convenience enums for this option using the
+ CURLFTP_CREATE_DIR prefix.
+ */
+ CINIT(FTP_CREATE_MISSING_DIRS, LONG, 110),
+
+ /* Set this to a bitmask value to enable the particular authentications
+ methods you like. Use this in combination with CURLOPT_PROXYUSERPWD.
+ Note that setting multiple bits may cause extra network round-trips. */
+ CINIT(PROXYAUTH, LONG, 111),
+
+ /* FTP option that changes the timeout, in seconds, associated with
+ getting a response. This is different from transfer timeout time and
+ essentially places a demand on the FTP server to acknowledge commands
+ in a timely manner. */
+ CINIT(FTP_RESPONSE_TIMEOUT, LONG, 112),
+
+ /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to
+ tell libcurl to resolve names to those IP versions only. This only has
+ affect on systems with support for more than one, i.e IPv4 _and_ IPv6. */
+ CINIT(IPRESOLVE, LONG, 113),
+
+ /* Set this option to limit the size of a file that will be downloaded from
+ an HTTP or FTP server.
+
+ Note there is also _LARGE version which adds large file support for
+ platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */
+ CINIT(MAXFILESIZE, LONG, 114),
+
+ /* See the comment for INFILESIZE above, but in short, specifies
+ * the size of the file being uploaded. -1 means unknown.
+ */
+ CINIT(INFILESIZE_LARGE, OFF_T, 115),
+
+ /* Sets the continuation offset. There is also a LONG version of this;
+ * look above for RESUME_FROM.
+ */
+ CINIT(RESUME_FROM_LARGE, OFF_T, 116),
+
+ /* Sets the maximum size of data that will be downloaded from
+ * an HTTP or FTP server. See MAXFILESIZE above for the LONG version.
+ */
+ CINIT(MAXFILESIZE_LARGE, OFF_T, 117),
+
+ /* Set this option to the file name of your .netrc file you want libcurl
+ to parse (using the CURLOPT_NETRC option). If not set, libcurl will do
+ a poor attempt to find the user's home directory and check for a .netrc
+ file in there. */
+ CINIT(NETRC_FILE, OBJECTPOINT, 118),
+
+ /* Enable SSL/TLS for FTP, pick one of:
+ CURLFTPSSL_TRY - try using SSL, proceed anyway otherwise
+ CURLFTPSSL_CONTROL - SSL for the control connection or fail
+ CURLFTPSSL_ALL - SSL for all communication or fail
+ */
+ CINIT(USE_SSL, LONG, 119),
+
+ /* The _LARGE version of the standard POSTFIELDSIZE option */
+ CINIT(POSTFIELDSIZE_LARGE, OFF_T, 120),
+
+ /* Enable/disable the TCP Nagle algorithm */
+ CINIT(TCP_NODELAY, LONG, 121),
+
+ /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 123 OBSOLETE. Gone in 7.16.0 */
+ /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 127 OBSOLETE. Gone in 7.16.0 */
+ /* 128 OBSOLETE. Gone in 7.16.0 */
+
+ /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option
+ can be used to change libcurl's default action which is to first try
+ "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK
+ response has been received.
+
+ Available parameters are:
+ CURLFTPAUTH_DEFAULT - let libcurl decide
+ CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS
+ CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL
+ */
+ CINIT(FTPSSLAUTH, LONG, 129),
+
+ CINIT(IOCTLFUNCTION, FUNCTIONPOINT, 130),
+ CINIT(IOCTLDATA, OBJECTPOINT, 131),
+
+ /* 132 OBSOLETE. Gone in 7.16.0 */
+ /* 133 OBSOLETE. Gone in 7.16.0 */
+
+ /* zero terminated string for pass on to the FTP server when asked for
+ "account" info */
+ CINIT(FTP_ACCOUNT, OBJECTPOINT, 134),
+
+ /* feed cookies into cookie engine */
+ CINIT(COOKIELIST, OBJECTPOINT, 135),
+
+ /* ignore Content-Length */
+ CINIT(IGNORE_CONTENT_LENGTH, LONG, 136),
+
+ /* Set to non-zero to skip the IP address received in a 227 PASV FTP server
+ response. Typically used for FTP-SSL purposes but is not restricted to
+ that. libcurl will then instead use the same IP address it used for the
+ control connection. */
+ CINIT(FTP_SKIP_PASV_IP, LONG, 137),
+
+ /* Select "file method" to use when doing FTP, see the curl_ftpmethod
+ above. */
+ CINIT(FTP_FILEMETHOD, LONG, 138),
+
+ /* Local port number to bind the socket to */
+ CINIT(LOCALPORT, LONG, 139),
+
+ /* Number of ports to try, including the first one set with LOCALPORT.
+ Thus, setting it to 1 will make no additional attempts but the first.
+ */
+ CINIT(LOCALPORTRANGE, LONG, 140),
+
+ /* no transfer, set up connection and let application use the socket by
+ extracting it with CURLINFO_LASTSOCKET */
+ CINIT(CONNECT_ONLY, LONG, 141),
+
+ /* Function that will be called to convert from the
+ network encoding (instead of using the iconv calls in libcurl) */
+ CINIT(CONV_FROM_NETWORK_FUNCTION, FUNCTIONPOINT, 142),
+
+ /* Function that will be called to convert to the
+ network encoding (instead of using the iconv calls in libcurl) */
+ CINIT(CONV_TO_NETWORK_FUNCTION, FUNCTIONPOINT, 143),
+
+ /* Function that will be called to convert from UTF8
+ (instead of using the iconv calls in libcurl)
+ Note that this is used only for SSL certificate processing */
+ CINIT(CONV_FROM_UTF8_FUNCTION, FUNCTIONPOINT, 144),
+
+ /* if the connection proceeds too quickly then need to slow it down */
+ /* limit-rate: maximum number of bytes per second to send or receive */
+ CINIT(MAX_SEND_SPEED_LARGE, OFF_T, 145),
+ CINIT(MAX_RECV_SPEED_LARGE, OFF_T, 146),
+
+ /* Pointer to command string to send if USER/PASS fails. */
+ CINIT(FTP_ALTERNATIVE_TO_USER, OBJECTPOINT, 147),
+
+ /* callback function for setting socket options */
+ CINIT(SOCKOPTFUNCTION, FUNCTIONPOINT, 148),
+ CINIT(SOCKOPTDATA, OBJECTPOINT, 149),
+
+ /* set to 0 to disable session ID re-use for this transfer, default is
+ enabled (== 1) */
+ CINIT(SSL_SESSIONID_CACHE, LONG, 150),
+
+ /* allowed SSH authentication methods */
+ CINIT(SSH_AUTH_TYPES, LONG, 151),
+
+ /* Used by scp/sftp to do public/private key authentication */
+ CINIT(SSH_PUBLIC_KEYFILE, OBJECTPOINT, 152),
+ CINIT(SSH_PRIVATE_KEYFILE, OBJECTPOINT, 153),
+
+ /* Send CCC (Clear Command Channel) after authentication */
+ CINIT(FTP_SSL_CCC, LONG, 154),
+
+ /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */
+ CINIT(TIMEOUT_MS, LONG, 155),
+ CINIT(CONNECTTIMEOUT_MS, LONG, 156),
+
+ /* set to zero to disable the libcurl's decoding and thus pass the raw body
+ data to the application even when it is encoded/compressed */
+ CINIT(HTTP_TRANSFER_DECODING, LONG, 157),
+ CINIT(HTTP_CONTENT_DECODING, LONG, 158),
+
+ /* Permission used when creating new files and directories on the remote
+ server for protocols that support it, SFTP/SCP/FILE */
+ CINIT(NEW_FILE_PERMS, LONG, 159),
+ CINIT(NEW_DIRECTORY_PERMS, LONG, 160),
+
+ /* Set the behaviour of POST when redirecting. Values must be set to one
+ of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */
+ CINIT(POSTREDIR, LONG, 161),
+
+ /* used by scp/sftp to verify the host's public key */
+ CINIT(SSH_HOST_PUBLIC_KEY_MD5, OBJECTPOINT, 162),
+
+ /* Callback function for opening socket (instead of socket(2)). Optionally,
+ callback is able change the address or refuse to connect returning
+ CURL_SOCKET_BAD. The callback should have type
+ curl_opensocket_callback */
+ CINIT(OPENSOCKETFUNCTION, FUNCTIONPOINT, 163),
+ CINIT(OPENSOCKETDATA, OBJECTPOINT, 164),
+
+ /* POST volatile input fields. */
+ CINIT(COPYPOSTFIELDS, OBJECTPOINT, 165),
+
+ /* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */
+ CINIT(PROXY_TRANSFER_MODE, LONG, 166),
+
+ /* Callback function for seeking in the input stream */
+ CINIT(SEEKFUNCTION, FUNCTIONPOINT, 167),
+ CINIT(SEEKDATA, OBJECTPOINT, 168),
+
+ /* CRL file */
+ CINIT(CRLFILE, OBJECTPOINT, 169),
+
+ /* Issuer certificate */
+ CINIT(ISSUERCERT, OBJECTPOINT, 170),
+
+ /* (IPv6) Address scope */
+ CINIT(ADDRESS_SCOPE, LONG, 171),
+
+ /* Collect certificate chain info and allow it to get retrievable with
+ CURLINFO_CERTINFO after the transfer is complete. (Unfortunately) only
+ working with OpenSSL-powered builds. */
+ CINIT(CERTINFO, LONG, 172),
+
+ /* "name" and "pwd" to use when fetching. */
+ CINIT(USERNAME, OBJECTPOINT, 173),
+ CINIT(PASSWORD, OBJECTPOINT, 174),
+
+ /* "name" and "pwd" to use with Proxy when fetching. */
+ CINIT(PROXYUSERNAME, OBJECTPOINT, 175),
+ CINIT(PROXYPASSWORD, OBJECTPOINT, 176),
+
+ /* Comma separated list of hostnames defining no-proxy zones. These should
+ match both hostnames directly, and hostnames within a domain. For
+ example, local.com will match local.com and www.local.com, but NOT
+ notlocal.com or www.notlocal.com. For compatibility with other
+ implementations of this, .local.com will be considered to be the same as
+ local.com. A single * is the only valid wildcard, and effectively
+ disables the use of proxy. */
+ CINIT(NOPROXY, OBJECTPOINT, 177),
+
+ /* block size for TFTP transfers */
+ CINIT(TFTP_BLKSIZE, LONG, 178),
+
+ /* Socks Service */
+ CINIT(SOCKS5_GSSAPI_SERVICE, OBJECTPOINT, 179),
+
+ /* Socks Service */
+ CINIT(SOCKS5_GSSAPI_NEC, LONG, 180),
+
+ /* set the bitmask for the protocols that are allowed to be used for the
+ transfer, which thus helps the app which takes URLs from users or other
+ external inputs and want to restrict what protocol(s) to deal
+ with. Defaults to CURLPROTO_ALL. */
+ CINIT(PROTOCOLS, LONG, 181),
+
+ /* set the bitmask for the protocols that libcurl is allowed to follow to,
+ as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
+ to be set in both bitmasks to be allowed to get redirected to. Defaults
+ to all protocols except FILE and SCP. */
+ CINIT(REDIR_PROTOCOLS, LONG, 182),
+
+ /* set the SSH knownhost file name to use */
+ CINIT(SSH_KNOWNHOSTS, OBJECTPOINT, 183),
+
+ /* set the SSH host key callback, must point to a curl_sshkeycallback
+ function */
+ CINIT(SSH_KEYFUNCTION, FUNCTIONPOINT, 184),
+
+ /* set the SSH host key callback custom pointer */
+ CINIT(SSH_KEYDATA, OBJECTPOINT, 185),
+
+ CURLOPT_LASTENTRY /* the last unused */
+} CURLoption;
+
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
+/* Backwards compatibility with older names */
+/* These are scheduled to disappear by 2011 */
+
+/* This was added in version 7.19.1 */
+#define CURLOPT_POST301 CURLOPT_POSTREDIR
+
+/* These are scheduled to disappear by 2009 */
+
+/* The following were added in 7.17.0 */
+#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD
+#define CURLOPT_FTPAPPEND CURLOPT_APPEND
+#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY
+#define CURLOPT_FTP_SSL CURLOPT_USE_SSL
+
+/* The following were added earlier */
+
+#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD
+#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL
+
+#else
+/* This is set if CURL_NO_OLDIES is defined at compile-time */
+#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */
+#endif
+
+
+ /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host
+ name resolves addresses using more than one IP protocol version, this
+ option might be handy to force libcurl to use a specific IP version. */
+#define CURL_IPRESOLVE_WHATEVER 0 /* default, resolves addresses to all IP
+ versions that your system allows */
+#define CURL_IPRESOLVE_V4 1 /* resolve to ipv4 addresses */
+#define CURL_IPRESOLVE_V6 2 /* resolve to ipv6 addresses */
+
+ /* three convenient "aliases" that follow the name scheme better */
+#define CURLOPT_WRITEDATA CURLOPT_FILE
+#define CURLOPT_READDATA CURLOPT_INFILE
+#define CURLOPT_HEADERDATA CURLOPT_WRITEHEADER
+
+ /* These enums are for use with the CURLOPT_HTTP_VERSION option. */
+enum {
+ CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd
+ like the library to choose the best possible
+ for us! */
+ CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */
+ CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */
+
+ CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */
+};
+
+ /* These enums are for use with the CURLOPT_NETRC option. */
+enum CURL_NETRC_OPTION {
+ CURL_NETRC_IGNORED, /* The .netrc will never be read.
+ * This is the default. */
+ CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred
+ * to one in the .netrc. */
+ CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored.
+ * Unless one is set programmatically, the .netrc
+ * will be queried. */
+ CURL_NETRC_LAST
+};
+
+enum {
+ CURL_SSLVERSION_DEFAULT,
+ CURL_SSLVERSION_TLSv1,
+ CURL_SSLVERSION_SSLv2,
+ CURL_SSLVERSION_SSLv3,
+
+ CURL_SSLVERSION_LAST /* never use, keep last */
+};
+
+/* symbols to use with CURLOPT_POSTREDIR.
+ CURL_REDIR_POST_301 and CURL_REDIR_POST_302 can be bitwise ORed so that
+ CURL_REDIR_POST_301 | CURL_REDIR_POST_302 == CURL_REDIR_POST_ALL */
+
+#define CURL_REDIR_GET_ALL 0
+#define CURL_REDIR_POST_301 1
+#define CURL_REDIR_POST_302 2
+#define CURL_REDIR_POST_ALL (CURL_REDIR_POST_301|CURL_REDIR_POST_302)
+
+typedef enum {
+ CURL_TIMECOND_NONE,
+
+ CURL_TIMECOND_IFMODSINCE,
+ CURL_TIMECOND_IFUNMODSINCE,
+ CURL_TIMECOND_LASTMOD,
+
+ CURL_TIMECOND_LAST
+} curl_TimeCond;
+
+
+/* curl_strequal() and curl_strnequal() are subject for removal in a future
+ libcurl, see lib/README.curlx for details */
+CURL_EXTERN int (curl_strequal)(const char *s1, const char *s2);
+CURL_EXTERN int (curl_strnequal)(const char *s1, const char *s2, size_t n);
+
+/* name is uppercase CURLFORM_<name> */
+#ifdef CFINIT
+#undef CFINIT
+#endif
+
+#ifdef CURL_ISOCPP
+#define CFINIT(name) CURLFORM_ ## name
+#else
+/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */
+#define CFINIT(name) CURLFORM_/**/name
+#endif
+
+typedef enum {
+ CFINIT(NOTHING), /********* the first one is unused ************/
+
+ /* */
+ CFINIT(COPYNAME),
+ CFINIT(PTRNAME),
+ CFINIT(NAMELENGTH),
+ CFINIT(COPYCONTENTS),
+ CFINIT(PTRCONTENTS),
+ CFINIT(CONTENTSLENGTH),
+ CFINIT(FILECONTENT),
+ CFINIT(ARRAY),
+ CFINIT(OBSOLETE),
+ CFINIT(FILE),
+
+ CFINIT(BUFFER),
+ CFINIT(BUFFERPTR),
+ CFINIT(BUFFERLENGTH),
+
+ CFINIT(CONTENTTYPE),
+ CFINIT(CONTENTHEADER),
+ CFINIT(FILENAME),
+ CFINIT(END),
+ CFINIT(OBSOLETE2),
+
+ CFINIT(STREAM),
+
+ CURLFORM_LASTENTRY /* the last unused */
+} CURLformoption;
+
+#undef CFINIT /* done */
+
+/* structure to be used as parameter for CURLFORM_ARRAY */
+struct curl_forms {
+ CURLformoption option;
+ const char *value;
+};
+
+/* use this for multipart formpost building */
+/* Returns code for curl_formadd()
+ *
+ * Returns:
+ * CURL_FORMADD_OK on success
+ * CURL_FORMADD_MEMORY if the FormInfo allocation fails
+ * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form
+ * CURL_FORMADD_NULL if a null pointer was given for a char
+ * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed
+ * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used
+ * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error)
+ * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated
+ * CURL_FORMADD_MEMORY if some allocation for string copying failed.
+ * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array
+ *
+ ***************************************************************************/
+typedef enum {
+ CURL_FORMADD_OK, /* first, no error */
+
+ CURL_FORMADD_MEMORY,
+ CURL_FORMADD_OPTION_TWICE,
+ CURL_FORMADD_NULL,
+ CURL_FORMADD_UNKNOWN_OPTION,
+ CURL_FORMADD_INCOMPLETE,
+ CURL_FORMADD_ILLEGAL_ARRAY,
+ CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */
+
+ CURL_FORMADD_LAST /* last */
+} CURLFORMcode;
+
+/*
+ * NAME curl_formadd()
+ *
+ * DESCRIPTION
+ *
+ * Pretty advanced function for building multi-part formposts. Each invoke
+ * adds one part that together construct a full post. Then use
+ * CURLOPT_HTTPPOST to send it off to libcurl.
+ */
+CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost,
+ struct curl_httppost **last_post,
+ ...);
+
+/*
+ * callback function for curl_formget()
+ * The void *arg pointer will be the one passed as second argument to
+ * curl_formget().
+ * The character buffer passed to it must not be freed.
+ * Should return the buffer length passed to it as the argument "len" on
+ * success.
+ */
+typedef size_t (*curl_formget_callback)(void *arg, const char *buf, size_t len);
+
+/*
+ * NAME curl_formget()
+ *
+ * DESCRIPTION
+ *
+ * Serialize a curl_httppost struct built with curl_formadd().
+ * Accepts a void pointer as second argument which will be passed to
+ * the curl_formget_callback function.
+ * Returns 0 on success.
+ */
+CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg,
+ curl_formget_callback append);
+/*
+ * NAME curl_formfree()
+ *
+ * DESCRIPTION
+ *
+ * Free a multipart formpost previously built with curl_formadd().
+ */
+CURL_EXTERN void curl_formfree(struct curl_httppost *form);
+
+/*
+ * NAME curl_getenv()
+ *
+ * DESCRIPTION
+ *
+ * Returns a malloc()'ed string that MUST be curl_free()ed after usage is
+ * complete. DEPRECATED - see lib/README.curlx
+ */
+CURL_EXTERN char *curl_getenv(const char *variable);
+
+/*
+ * NAME curl_version()
+ *
+ * DESCRIPTION
+ *
+ * Returns a static ascii string of the libcurl version.
+ */
+CURL_EXTERN char *curl_version(void);
+
+/*
+ * NAME curl_easy_escape()
+ *
+ * DESCRIPTION
+ *
+ * Escapes URL strings (converts all letters consider illegal in URLs to their
+ * %XX versions). This function returns a new allocated string or NULL if an
+ * error occurred.
+ */
+CURL_EXTERN char *curl_easy_escape(CURL *handle,
+ const char *string,
+ int length);
+
+/* the previous version: */
+CURL_EXTERN char *curl_escape(const char *string,
+ int length);
+
+
+/*
+ * NAME curl_easy_unescape()
+ *
+ * DESCRIPTION
+ *
+ * Unescapes URL encoding in strings (converts all %XX codes to their 8bit
+ * versions). This function returns a new allocated string or NULL if an error
+ * occurred.
+ * Conversion Note: On non-ASCII platforms the ASCII %XX codes are
+ * converted into the host encoding.
+ */
+CURL_EXTERN char *curl_easy_unescape(CURL *handle,
+ const char *string,
+ int length,
+ int *outlength);
+
+/* the previous version */
+CURL_EXTERN char *curl_unescape(const char *string,
+ int length);
+
+/*
+ * NAME curl_free()
+ *
+ * DESCRIPTION
+ *
+ * Provided for de-allocation in the same translation unit that did the
+ * allocation. Added in libcurl 7.10
+ */
+CURL_EXTERN void curl_free(void *p);
+
+/*
+ * NAME curl_global_init()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_init() should be invoked exactly once for each application that
+ * uses libcurl and before any call of other libcurl functions.
+ *
+ * This function is not thread-safe!
+ */
+CURL_EXTERN CURLcode curl_global_init(long flags);
+
+/*
+ * NAME curl_global_init_mem()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_init() or curl_global_init_mem() should be invoked exactly once
+ * for each application that uses libcurl. This function can be used to
+ * initialize libcurl and set user defined memory management callback
+ * functions. Users can implement memory management routines to check for
+ * memory leaks, check for mis-use of the curl library etc. User registered
+ * callback routines with be invoked by this library instead of the system
+ * memory management routines like malloc, free etc.
+ */
+CURL_EXTERN CURLcode curl_global_init_mem(long flags,
+ curl_malloc_callback m,
+ curl_free_callback f,
+ curl_realloc_callback r,
+ curl_strdup_callback s,
+ curl_calloc_callback c);
+
+/*
+ * NAME curl_global_cleanup()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_cleanup() should be invoked exactly once for each application
+ * that uses libcurl
+ */
+CURL_EXTERN void curl_global_cleanup(void);
+
+/* linked-list structure for the CURLOPT_QUOTE option (and other) */
+struct curl_slist {
+ char *data;
+ struct curl_slist *next;
+};
+
+/*
+ * NAME curl_slist_append()
+ *
+ * DESCRIPTION
+ *
+ * Appends a string to a linked list. If no list exists, it will be created
+ * first. Returns the new list, after appending.
+ */
+CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *,
+ const char *);
+
+/*
+ * NAME curl_slist_free_all()
+ *
+ * DESCRIPTION
+ *
+ * free a previously built curl_slist.
+ */
+CURL_EXTERN void curl_slist_free_all(struct curl_slist *);
+
+/*
+ * NAME curl_getdate()
+ *
+ * DESCRIPTION
+ *
+ * Returns the time, in seconds since 1 Jan 1970 of the time string given in
+ * the first argument. The time argument in the second parameter is unused
+ * and should be set to NULL.
+ */
+CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused);
+
+/* info about the certificate chain, only for OpenSSL builds. Asked
+ for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */
+struct curl_certinfo {
+ int num_of_certs; /* number of certificates with information */
+ struct curl_slist **certinfo; /* for each index in this array, there's a
+ linked list with textual information in the
+ format "name: value" */
+};
+
+#define CURLINFO_STRING 0x100000
+#define CURLINFO_LONG 0x200000
+#define CURLINFO_DOUBLE 0x300000
+#define CURLINFO_SLIST 0x400000
+#define CURLINFO_MASK 0x0fffff
+#define CURLINFO_TYPEMASK 0xf00000
+
+typedef enum {
+ CURLINFO_NONE, /* first, never use this */
+ CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1,
+ CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2,
+ CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3,
+ CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4,
+ CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5,
+ CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6,
+ CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7,
+ CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8,
+ CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9,
+ CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10,
+ CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11,
+ CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12,
+ CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13,
+ CURLINFO_FILETIME = CURLINFO_LONG + 14,
+ CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15,
+ CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16,
+ CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17,
+ CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18,
+ CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19,
+ CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20,
+ CURLINFO_PRIVATE = CURLINFO_STRING + 21,
+ CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22,
+ CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23,
+ CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24,
+ CURLINFO_OS_ERRNO = CURLINFO_LONG + 25,
+ CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26,
+ CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27,
+ CURLINFO_COOKIELIST = CURLINFO_SLIST + 28,
+ CURLINFO_LASTSOCKET = CURLINFO_LONG + 29,
+ CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30,
+ CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31,
+ CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32,
+ CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33,
+ CURLINFO_CERTINFO = CURLINFO_SLIST + 34,
+ CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35,
+ /* Fill in new entries below here! */
+
+ CURLINFO_LASTONE = 35
+} CURLINFO;
+
+/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as
+ CURLINFO_HTTP_CODE */
+#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE
+
+typedef enum {
+ CURLCLOSEPOLICY_NONE, /* first, never use this */
+
+ CURLCLOSEPOLICY_OLDEST,
+ CURLCLOSEPOLICY_LEAST_RECENTLY_USED,
+ CURLCLOSEPOLICY_LEAST_TRAFFIC,
+ CURLCLOSEPOLICY_SLOWEST,
+ CURLCLOSEPOLICY_CALLBACK,
+
+ CURLCLOSEPOLICY_LAST /* last, never use this */
+} curl_closepolicy;
+
+#define CURL_GLOBAL_SSL (1<<0)
+#define CURL_GLOBAL_WIN32 (1<<1)
+#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32)
+#define CURL_GLOBAL_NOTHING 0
+#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL
+
+
+/*****************************************************************************
+ * Setup defines, protos etc for the sharing stuff.
+ */
+
+/* Different data locks for a single share */
+typedef enum {
+ CURL_LOCK_DATA_NONE = 0,
+ /* CURL_LOCK_DATA_SHARE is used internally to say that
+ * the locking is just made to change the internal state of the share
+ * itself.
+ */
+ CURL_LOCK_DATA_SHARE,
+ CURL_LOCK_DATA_COOKIE,
+ CURL_LOCK_DATA_DNS,
+ CURL_LOCK_DATA_SSL_SESSION,
+ CURL_LOCK_DATA_CONNECT,
+ CURL_LOCK_DATA_LAST
+} curl_lock_data;
+
+/* Different lock access types */
+typedef enum {
+ CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */
+ CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */
+ CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */
+ CURL_LOCK_ACCESS_LAST /* never use */
+} curl_lock_access;
+
+typedef void (*curl_lock_function)(CURL *handle,
+ curl_lock_data data,
+ curl_lock_access locktype,
+ void *userptr);
+typedef void (*curl_unlock_function)(CURL *handle,
+ curl_lock_data data,
+ void *userptr);
+
+typedef void CURLSH;
+
+typedef enum {
+ CURLSHE_OK, /* all is fine */
+ CURLSHE_BAD_OPTION, /* 1 */
+ CURLSHE_IN_USE, /* 2 */
+ CURLSHE_INVALID, /* 3 */
+ CURLSHE_NOMEM, /* out of memory */
+ CURLSHE_LAST /* never use */
+} CURLSHcode;
+
+typedef enum {
+ CURLSHOPT_NONE, /* don't use */
+ CURLSHOPT_SHARE, /* specify a data type to share */
+ CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */
+ CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */
+ CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */
+ CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock
+ callback functions */
+ CURLSHOPT_LAST /* never use */
+} CURLSHoption;
+
+CURL_EXTERN CURLSH *curl_share_init(void);
+CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...);
+CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *);
+
+/****************************************************************************
+ * Structures for querying information about the curl library at runtime.
+ */
+
+typedef enum {
+ CURLVERSION_FIRST,
+ CURLVERSION_SECOND,
+ CURLVERSION_THIRD,
+ CURLVERSION_FOURTH,
+ CURLVERSION_LAST /* never actually use this */
+} CURLversion;
+
+/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by
+ basically all programs ever that want to get version information. It is
+ meant to be a built-in version number for what kind of struct the caller
+ expects. If the struct ever changes, we redefine the NOW to another enum
+ from above. */
+#define CURLVERSION_NOW CURLVERSION_FOURTH
+
+typedef struct {
+ CURLversion age; /* age of the returned struct */
+ const char *version; /* LIBCURL_VERSION */
+ unsigned int version_num; /* LIBCURL_VERSION_NUM */
+ const char *host; /* OS/host/cpu/machine when configured */
+ int features; /* bitmask, see defines below */
+ const char *ssl_version; /* human readable string */
+ long ssl_version_num; /* not used anymore, always 0 */
+ const char *libz_version; /* human readable string */
+ /* protocols is terminated by an entry with a NULL protoname */
+ const char * const *protocols;
+
+ /* The fields below this were added in CURLVERSION_SECOND */
+ const char *ares;
+ int ares_num;
+
+ /* This field was added in CURLVERSION_THIRD */
+ const char *libidn;
+
+ /* These field were added in CURLVERSION_FOURTH */
+
+ /* Same as '_libiconv_version' if built with HAVE_ICONV */
+ int iconv_ver_num;
+
+ const char *libssh_version; /* human readable string */
+
+} curl_version_info_data;
+
+#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */
+#define CURL_VERSION_KERBEROS4 (1<<1) /* kerberos auth is supported */
+#define CURL_VERSION_SSL (1<<2) /* SSL options are present */
+#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */
+#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */
+#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth support */
+#define CURL_VERSION_DEBUG (1<<6) /* built with debug capabilities */
+#define CURL_VERSION_ASYNCHDNS (1<<7) /* asynchronous dns resolves */
+#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth */
+#define CURL_VERSION_LARGEFILE (1<<9) /* supports files bigger than 2GB */
+#define CURL_VERSION_IDN (1<<10) /* International Domain Names support */
+#define CURL_VERSION_SSPI (1<<11) /* SSPI is supported */
+#define CURL_VERSION_CONV (1<<12) /* character conversions supported */
+#define CURL_VERSION_CURLDEBUG (1<<13) /* debug memory tracking supported */
+
+/*
+ * NAME curl_version_info()
+ *
+ * DESCRIPTION
+ *
+ * This function returns a pointer to a static copy of the version info
+ * struct. See above.
+ */
+CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion);
+
+/*
+ * NAME curl_easy_strerror()
+ *
+ * DESCRIPTION
+ *
+ * The curl_easy_strerror function may be used to turn a CURLcode value
+ * into the equivalent human readable error string. This is useful
+ * for printing meaningful error messages.
+ */
+CURL_EXTERN const char *curl_easy_strerror(CURLcode);
+
+/*
+ * NAME curl_share_strerror()
+ *
+ * DESCRIPTION
+ *
+ * The curl_share_strerror function may be used to turn a CURLSHcode value
+ * into the equivalent human readable error string. This is useful
+ * for printing meaningful error messages.
+ */
+CURL_EXTERN const char *curl_share_strerror(CURLSHcode);
+
+/*
+ * NAME curl_easy_pause()
+ *
+ * DESCRIPTION
+ *
+ * The curl_easy_pause function pauses or unpauses transfers. Select the new
+ * state by setting the bitmask, use the convenience defines below.
+ *
+ */
+CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask);
+
+#define CURLPAUSE_RECV (1<<0)
+#define CURLPAUSE_RECV_CONT (0)
+
+#define CURLPAUSE_SEND (1<<2)
+#define CURLPAUSE_SEND_CONT (0)
+
+#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND)
+#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT)
+
+#ifdef __cplusplus
+}
+#endif
+
+/* unfortunately, the easy.h and multi.h include files need options and info
+ stuff before they can be included! */
+#include "easy.h" /* nothing in curl is fun without the easy stuff */
+#include "multi.h"
+
+/* the typechecker doesn't work in C++ (yet) */
+#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \
+ ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \
+ !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK)
+#include "typecheck-gcc.h"
+#else
+#if defined(__STDC__) && (__STDC__ >= 1)
+/* This preprocessor magic that replaces a call with the exact same call is
+ only done to make sure application authors pass exactly three arguments
+ to these functions. */
+#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param)
+#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg)
+#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
+#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
+#endif /* __STDC__ >= 1 */
+#endif /* gcc >= 4.3 && !__cplusplus */
+
+#endif /* __CURL_CURL_H */
diff --git a/plugins/FTPFileYM/curl/curlbuild.h b/plugins/FTPFileYM/curl/curlbuild.h
new file mode 100644
index 0000000000..9cb347323e
--- /dev/null
+++ b/plugins/FTPFileYM/curl/curlbuild.h
@@ -0,0 +1,584 @@
+#ifndef __CURL_CURLBUILD_H
+#define __CURL_CURLBUILD_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: curlbuild.h.dist,v 1.28 2009-05-12 01:57:54 yangtse Exp $
+ ***************************************************************************/
+
+/* ================================================================ */
+/* NOTES FOR CONFIGURE CAPABLE SYSTEMS */
+/* ================================================================ */
+
+/*
+ * NOTE 1:
+ * -------
+ *
+ * See file include/curl/curlbuild.h.in, run configure, and forget
+ * that this file exists it is only used for non-configure systems.
+ * But you can keep reading if you want ;-)
+ *
+ */
+
+/* ================================================================ */
+/* NOTES FOR NON-CONFIGURE SYSTEMS */
+/* ================================================================ */
+
+/*
+ * NOTE 1:
+ * -------
+ *
+ * Nothing in this file is intended to be modified or adjusted by the
+ * curl library user nor by the curl library builder.
+ *
+ * If you think that something actually needs to be changed, adjusted
+ * or fixed in this file, then, report it on the libcurl development
+ * mailing list: http://cool.haxx.se/mailman/listinfo/curl-library/
+ *
+ * Try to keep one section per platform, compiler and architecture,
+ * otherwise, if an existing section is reused for a different one and
+ * later on the original is adjusted, probably the piggybacking one can
+ * be adversely changed.
+ *
+ * In order to differentiate between platforms/compilers/architectures
+ * use only compiler built in predefined preprocessor symbols.
+ *
+ * This header file shall only export symbols which are 'curl' or 'CURL'
+ * prefixed, otherwise public name space would be polluted.
+ *
+ * NOTE 2:
+ * -------
+ *
+ * For any given platform/compiler curl_off_t must be typedef'ed to a
+ * 64-bit wide signed integral data type. The width of this data type
+ * must remain constant and independant of any possible large file
+ * support settings.
+ *
+ * As an exception to the above, curl_off_t shall be typedef'ed to a
+ * 32-bit wide signed integral data type if there is no 64-bit type.
+ *
+ * As a general rule, curl_off_t shall not be mapped to off_t. This
+ * rule shall only be violated if off_t is the only 64-bit data type
+ * available and the size of off_t is independant of large file support
+ * settings. Keep your build on the safe side avoiding an off_t gating.
+ * If you have a 64-bit off_t then take for sure that another 64-bit
+ * data type exists, dig deeper and you will find it.
+ *
+ * NOTE 3:
+ * -------
+ *
+ * Right now you might be staring at file include/curl/curlbuild.h.dist or
+ * at file include/curl/curlbuild.h, this is due to the following reason:
+ * file include/curl/curlbuild.h.dist is renamed to include/curl/curlbuild.h
+ * when the libcurl source code distribution archive file is created.
+ *
+ * File include/curl/curlbuild.h.dist is not included in the distribution
+ * archive. File include/curl/curlbuild.h is not present in the CVS tree.
+ *
+ * The distributed include/curl/curlbuild.h file is only intended to be used
+ * on systems which can not run the also distributed configure script.
+ *
+ * On systems capable of running the configure script, the configure process
+ * will overwrite the distributed include/curl/curlbuild.h file with one that
+ * is suitable and specific to the library being configured and built, which
+ * is generated from the include/curl/curlbuild.h.in template file.
+ *
+ * If you check out from CVS on a non-configure platform, you must run the
+ * appropriate buildconf* script to set up curlbuild.h and other local files.
+ *
+ */
+
+/* ================================================================ */
+/* DEFINITION OF THESE SYMBOLS SHALL NOT TAKE PLACE ANYWHERE ELSE */
+/* ================================================================ */
+
+#ifdef CURL_SIZEOF_LONG
+# error "CURL_SIZEOF_LONG shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_SIZEOF_LONG_already_defined
+#endif
+
+#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
+# error "CURL_TYPEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_already_defined
+#endif
+
+#ifdef CURL_SIZEOF_CURL_SOCKLEN_T
+# error "CURL_SIZEOF_CURL_SOCKLEN_T shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_already_defined
+#endif
+
+#ifdef CURL_TYPEOF_CURL_OFF_T
+# error "CURL_TYPEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_already_defined
+#endif
+
+#ifdef CURL_FORMAT_CURL_OFF_T
+# error "CURL_FORMAT_CURL_OFF_T shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_already_defined
+#endif
+
+#ifdef CURL_FORMAT_CURL_OFF_TU
+# error "CURL_FORMAT_CURL_OFF_TU shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_already_defined
+#endif
+
+#ifdef CURL_FORMAT_OFF_T
+# error "CURL_FORMAT_OFF_T shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_FORMAT_OFF_T_already_defined
+#endif
+
+#ifdef CURL_SIZEOF_CURL_OFF_T
+# error "CURL_SIZEOF_CURL_OFF_T shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_already_defined
+#endif
+
+#ifdef CURL_SUFFIX_CURL_OFF_T
+# error "CURL_SUFFIX_CURL_OFF_T shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_already_defined
+#endif
+
+#ifdef CURL_SUFFIX_CURL_OFF_TU
+# error "CURL_SUFFIX_CURL_OFF_TU shall not be defined except in curlbuild.h"
+ Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_already_defined
+#endif
+
+/* ================================================================ */
+/* EXTERNAL INTERFACE SETTINGS FOR NON-CONFIGURE SYSTEMS ONLY */
+/* ================================================================ */
+
+#if defined(__DJGPP__) || defined(__GO32__)
+# if defined(__DJGPP__) && (__DJGPP__ > 1)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# else
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__SALFORDC__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__BORLANDC__)
+# if (__BORLANDC__ < 0x520)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# else
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_FORMAT_OFF_T "%I64d"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__TURBOC__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__WATCOMC__)
+# if defined(__386__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_FORMAT_OFF_T "%I64d"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# else
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__POCC__)
+# if (__POCC__ < 280)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# elif defined(_MSC_VER)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_FORMAT_OFF_T "%I64d"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# else
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__LCC__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__SYMBIAN32__)
+# if defined(__EABI__) /* Treat all ARM compilers equally */
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(__CW32__)
+# pragma longlong on
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(__VC32__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__MWERKS__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(_WIN32_WCE)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_FORMAT_OFF_T "%I64d"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__MINGW32__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_FORMAT_OFF_T "%I64d"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__VMS)
+# if defined(__alpha) || defined(__ia64)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# else
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+#elif defined(__OS400__)
+# if defined(__ILEC400__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+# endif
+
+#elif defined(__MVS__)
+# if defined(__IBMC__) || defined(__IBMCPP__)
+# if defined(_ILP32)
+# define CURL_SIZEOF_LONG 4
+# elif defined(_LP64)
+# define CURL_SIZEOF_LONG 8
+# endif
+# if defined(_LONG_LONG)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(_LP64)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# else
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+# endif
+
+#elif defined(__370__)
+# if defined(__IBMC__) || defined(__IBMCPP__)
+# if defined(_ILP32)
+# define CURL_SIZEOF_LONG 4
+# elif defined(_LP64)
+# define CURL_SIZEOF_LONG 8
+# endif
+# if defined(_LONG_LONG)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(_LP64)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# else
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+# endif
+
+#elif defined(TPF)
+# define CURL_SIZEOF_LONG 8
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+/* ===================================== */
+/* KEEP MSVC THE PENULTIMATE ENTRY */
+/* ===================================== */
+
+#elif defined(_MSC_VER)
+# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_FORMAT_OFF_T "%I64d"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# else
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 4
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+
+/* ===================================== */
+/* KEEP GENERIC GCC THE LAST ENTRY */
+/* ===================================== */
+
+#elif defined(__GNUC__)
+# if defined(__i386__) || defined(__ppc__)
+# define CURL_SIZEOF_LONG 4
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_FORMAT_OFF_T "%lld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(__x86_64__) || defined(__ppc64__)
+# define CURL_SIZEOF_LONG 8
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_FORMAT_OFF_T "%ld"
+# define CURL_SIZEOF_CURL_OFF_T 8
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_SIZEOF_CURL_SOCKLEN_T 4
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+
+#else
+# error "Unknown non-configure build target!"
+ Error Compilation_aborted_Unknown_non_configure_build_target
+#endif
+
+/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */
+/* sys/types.h is required here to properly make type definitions below. */
+#ifdef CURL_PULL_SYS_TYPES_H
+# include <sys/types.h>
+#endif
+
+/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */
+/* sys/socket.h is required here to properly make type definitions below. */
+#ifdef CURL_PULL_SYS_SOCKET_H
+# include <sys/socket.h>
+#endif
+
+/* Data type definition of curl_socklen_t. */
+
+#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
+ typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
+#endif
+
+/* Data type definition of curl_off_t. */
+
+#ifdef CURL_TYPEOF_CURL_OFF_T
+ typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
+#endif
+
+#endif /* __CURL_CURLBUILD_H */
diff --git a/plugins/FTPFileYM/curl/curlrules.h b/plugins/FTPFileYM/curl/curlrules.h
new file mode 100644
index 0000000000..44018737d9
--- /dev/null
+++ b/plugins/FTPFileYM/curl/curlrules.h
@@ -0,0 +1,249 @@
+#ifndef __CURL_CURLRULES_H
+#define __CURL_CURLRULES_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: curlrules.h,v 1.6 2009-04-29 15:15:38 yangtse Exp $
+ ***************************************************************************/
+
+/* ================================================================ */
+/* COMPILE TIME SANITY CHECKS */
+/* ================================================================ */
+
+/*
+ * NOTE 1:
+ * -------
+ *
+ * All checks done in this file are intentionally placed in a public
+ * header file which is pulled by curl/curl.h when an application is
+ * being built using an already built libcurl library. Additionally
+ * this file is also included and used when building the library.
+ *
+ * If compilation fails on this file it is certainly sure that the
+ * problem is elsewhere. It could be a problem in the curlbuild.h
+ * header file, or simply that you are using different compilation
+ * settings than those used to build the library.
+ *
+ * Nothing in this file is intended to be modified or adjusted by the
+ * curl library user nor by the curl library builder.
+ *
+ * Do not deactivate any check, these are done to make sure that the
+ * library is properly built and used.
+ *
+ * You can find further help on the libcurl development mailing list:
+ * http://cool.haxx.se/mailman/listinfo/curl-library/
+ *
+ * NOTE 2
+ * ------
+ *
+ * Some of the following compile time checks are based on the fact
+ * that the dimension of a constant array can not be a negative one.
+ * In this way if the compile time verification fails, the compilation
+ * will fail issuing an error. The error description wording is compiler
+ * dependant but it will be quite similar to one of the following:
+ *
+ * "negative subscript or subscript is too large"
+ * "array must have at least one element"
+ * "-1 is an illegal array size"
+ * "size of array is negative"
+ *
+ * If you are building an application which tries to use an already
+ * built libcurl library and you are getting this kind of errors on
+ * this file, it is a clear indication that there is a mismatch between
+ * how the library was built and how you are trying to use it for your
+ * application. Your already compiled or binary library provider is the
+ * only one who can give you the details you need to properly use it.
+ */
+
+/*
+ * Verify that some macros are actually defined.
+ */
+
+#ifndef CURL_SIZEOF_LONG
+# error "CURL_SIZEOF_LONG definition is missing!"
+ Error Compilation_aborted_CURL_SIZEOF_LONG_is_missing
+#endif
+
+#ifndef CURL_TYPEOF_CURL_SOCKLEN_T
+# error "CURL_TYPEOF_CURL_SOCKLEN_T definition is missing!"
+ Error Compilation_aborted_CURL_TYPEOF_CURL_SOCKLEN_T_is_missing
+#endif
+
+#ifndef CURL_SIZEOF_CURL_SOCKLEN_T
+# error "CURL_SIZEOF_CURL_SOCKLEN_T definition is missing!"
+ Error Compilation_aborted_CURL_SIZEOF_CURL_SOCKLEN_T_is_missing
+#endif
+
+#ifndef CURL_TYPEOF_CURL_OFF_T
+# error "CURL_TYPEOF_CURL_OFF_T definition is missing!"
+ Error Compilation_aborted_CURL_TYPEOF_CURL_OFF_T_is_missing
+#endif
+
+#ifndef CURL_FORMAT_CURL_OFF_T
+# error "CURL_FORMAT_CURL_OFF_T definition is missing!"
+ Error Compilation_aborted_CURL_FORMAT_CURL_OFF_T_is_missing
+#endif
+
+#ifndef CURL_FORMAT_CURL_OFF_TU
+# error "CURL_FORMAT_CURL_OFF_TU definition is missing!"
+ Error Compilation_aborted_CURL_FORMAT_CURL_OFF_TU_is_missing
+#endif
+
+#ifndef CURL_FORMAT_OFF_T
+# error "CURL_FORMAT_OFF_T definition is missing!"
+ Error Compilation_aborted_CURL_FORMAT_OFF_T_is_missing
+#endif
+
+#ifndef CURL_SIZEOF_CURL_OFF_T
+# error "CURL_SIZEOF_CURL_OFF_T definition is missing!"
+ Error Compilation_aborted_CURL_SIZEOF_CURL_OFF_T_is_missing
+#endif
+
+#ifndef CURL_SUFFIX_CURL_OFF_T
+# error "CURL_SUFFIX_CURL_OFF_T definition is missing!"
+ Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_T_is_missing
+#endif
+
+#ifndef CURL_SUFFIX_CURL_OFF_TU
+# error "CURL_SUFFIX_CURL_OFF_TU definition is missing!"
+ Error Compilation_aborted_CURL_SUFFIX_CURL_OFF_TU_is_missing
+#endif
+
+/*
+ * Macros private to this header file.
+ */
+
+#define CurlchkszEQ(t, s) sizeof(t) == s ? 1 : -1
+
+#define CurlchkszGE(t1, t2) sizeof(t1) >= sizeof(t2) ? 1 : -1
+
+/*
+ * Verify that the size previously defined and expected for long
+ * is the same as the one reported by sizeof() at compile time.
+ */
+
+typedef char
+ __curl_rule_01__
+ [CurlchkszEQ(long, CURL_SIZEOF_LONG)];
+
+/*
+ * Verify that the size previously defined and expected for
+ * curl_off_t is actually the the same as the one reported
+ * by sizeof() at compile time.
+ */
+
+typedef char
+ __curl_rule_02__
+ [CurlchkszEQ(curl_off_t, CURL_SIZEOF_CURL_OFF_T)];
+
+/*
+ * Verify at compile time that the size of curl_off_t as reported
+ * by sizeof() is greater or equal than the one reported for long
+ * for the current compilation.
+ */
+
+typedef char
+ __curl_rule_03__
+ [CurlchkszGE(curl_off_t, long)];
+
+/*
+ * Verify that the size previously defined and expected for
+ * curl_socklen_t is actually the the same as the one reported
+ * by sizeof() at compile time.
+ */
+
+typedef char
+ __curl_rule_04__
+ [CurlchkszEQ(curl_socklen_t, CURL_SIZEOF_CURL_SOCKLEN_T)];
+
+/*
+ * Verify at compile time that the size of curl_socklen_t as reported
+ * by sizeof() is greater or equal than the one reported for int for
+ * the current compilation.
+ */
+
+typedef char
+ __curl_rule_05__
+ [CurlchkszGE(curl_socklen_t, int)];
+
+/* ================================================================ */
+/* EXTERNALLY AND INTERNALLY VISIBLE DEFINITIONS */
+/* ================================================================ */
+
+/*
+ * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow
+ * these to be visible and exported by the external libcurl interface API,
+ * while also making them visible to the library internals, simply including
+ * setup.h, without actually needing to include curl.h internally.
+ * If some day this section would grow big enough, all this should be moved
+ * to its own header file.
+ */
+
+/*
+ * Figure out if we can use the ## preprocessor operator, which is supported
+ * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__
+ * or __cplusplus so we need to carefully check for them too.
+ */
+
+#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \
+ defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \
+ defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \
+ defined(__ILEC400__)
+ /* This compiler is believed to have an ISO compatible preprocessor */
+#define CURL_ISOCPP
+#else
+ /* This compiler is believed NOT to have an ISO compatible preprocessor */
+#undef CURL_ISOCPP
+#endif
+
+/*
+ * Macros for minimum-width signed and unsigned curl_off_t integer constants.
+ */
+
+#ifdef CURL_ISOCPP
+# define __CURL_OFF_T_C_HELPER2(Val,Suffix) Val ## Suffix
+#else
+# define __CURL_OFF_T_C_HELPER2(Val,Suffix) Val/**/Suffix
+#endif
+#define __CURL_OFF_T_C_HELPER1(Val,Suffix) __CURL_OFF_T_C_HELPER2(Val,Suffix)
+#define CURL_OFF_T_C(Val) __CURL_OFF_T_C_HELPER1(Val,CURL_SUFFIX_CURL_OFF_T)
+#define CURL_OFF_TU_C(Val) __CURL_OFF_T_C_HELPER1(Val,CURL_SUFFIX_CURL_OFF_TU)
+
+/*
+ * Get rid of macros private to this header file.
+ */
+
+#undef CurlchkszEQ
+#undef CurlchkszGE
+
+/*
+ * Get rid of macros not intended to exist beyond this point.
+ */
+
+#undef CURL_PULL_WS2TCPIP_H
+#undef CURL_PULL_SYS_TYPES_H
+#undef CURL_PULL_SYS_SOCKET_H
+#undef CURL_PULL_STDINT_H
+#undef CURL_PULL_INTTYPES_H
+
+#undef CURL_TYPEOF_CURL_SOCKLEN_T
+#undef CURL_TYPEOF_CURL_OFF_T
+
+#endif /* __CURL_CURLRULES_H */
diff --git a/plugins/FTPFileYM/curl/curlver.h b/plugins/FTPFileYM/curl/curlver.h
new file mode 100644
index 0000000000..177f6cbd8d
--- /dev/null
+++ b/plugins/FTPFileYM/curl/curlver.h
@@ -0,0 +1,70 @@
+#ifndef __CURL_CURLVER_H
+#define __CURL_CURLVER_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: curlver.h,v 1.47 2009-05-18 07:58:00 bagder Exp $
+ ***************************************************************************/
+
+/* This header file contains nothing but libcurl version info, generated by
+ a script at release-time. This was made its own header file in 7.11.2 */
+
+/* This is the global package copyright */
+#define LIBCURL_COPYRIGHT "1996 - 2009 Daniel Stenberg, <daniel@haxx.se>."
+
+/* This is the version number of the libcurl package from which this header
+ file origins: */
+#define LIBCURL_VERSION "7.19.6"
+
+/* The numeric version number is also available "in parts" by using these
+ defines: */
+#define LIBCURL_VERSION_MAJOR 7
+#define LIBCURL_VERSION_MINOR 19
+#define LIBCURL_VERSION_PATCH 6
+
+/* This is the numeric version of the libcurl version number, meant for easier
+ parsing and comparions by programs. The LIBCURL_VERSION_NUM define will
+ always follow this syntax:
+
+ 0xXXYYZZ
+
+ Where XX, YY and ZZ are the main version, release and patch numbers in
+ hexadecimal (using 8 bits each). All three numbers are always represented
+ using two digits. 1.2 would appear as "0x010200" while version 9.11.7
+ appears as "0x090b07".
+
+ This 6-digit (24 bits) hexadecimal number does not show pre-release number,
+ and it is always a greater number in a more recent release. It makes
+ comparisons with greater than and less than work.
+*/
+#define LIBCURL_VERSION_NUM 0x071306
+
+/*
+ * This is the date and time when the full source package was created. The
+ * timestamp is not stored in CVS, as the timestamp is properly set in the
+ * tarballs by the maketgz script.
+ *
+ * The format of the date should follow this template:
+ *
+ * "Mon Feb 12 11:35:33 UTC 2007"
+ */
+#define LIBCURL_TIMESTAMP "Wed Aug 12 08:59:35 UTC 2009"
+
+#endif /* __CURL_CURLVER_H */
diff --git a/plugins/FTPFileYM/curl/easy.h b/plugins/FTPFileYM/curl/easy.h
new file mode 100644
index 0000000000..40449c3ec8
--- /dev/null
+++ b/plugins/FTPFileYM/curl/easy.h
@@ -0,0 +1,103 @@
+#ifndef __CURL_EASY_H
+#define __CURL_EASY_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: easy.h,v 1.14 2008-05-12 21:43:28 bagder Exp $
+ ***************************************************************************/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CURL_EXTERN CURL *curl_easy_init(void);
+CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
+CURL_EXTERN CURLcode curl_easy_perform(CURL *curl);
+CURL_EXTERN void curl_easy_cleanup(CURL *curl);
+
+/*
+ * NAME curl_easy_getinfo()
+ *
+ * DESCRIPTION
+ *
+ * Request internal information from the curl session with this function. The
+ * third argument MUST be a pointer to a long, a pointer to a char * or a
+ * pointer to a double (as the documentation describes elsewhere). The data
+ * pointed to will be filled in accordingly and can be relied upon only if the
+ * function returns CURLE_OK. This function is intended to get used *AFTER* a
+ * performed transfer, all results from this function are undefined until the
+ * transfer is completed.
+ */
+CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...);
+
+
+/*
+ * NAME curl_easy_duphandle()
+ *
+ * DESCRIPTION
+ *
+ * Creates a new curl session handle with the same options set for the handle
+ * passed in. Duplicating a handle could only be a matter of cloning data and
+ * options, internal state info and things like persistant connections cannot
+ * be transfered. It is useful in multithreaded applications when you can run
+ * curl_easy_duphandle() for each new thread to avoid a series of identical
+ * curl_easy_setopt() invokes in every thread.
+ */
+CURL_EXTERN CURL* curl_easy_duphandle(CURL *curl);
+
+/*
+ * NAME curl_easy_reset()
+ *
+ * DESCRIPTION
+ *
+ * Re-initializes a CURL handle to the default values. This puts back the
+ * handle to the same state as it was in when it was just created.
+ *
+ * It does keep: live connections, the Session ID cache, the DNS cache and the
+ * cookies.
+ */
+CURL_EXTERN void curl_easy_reset(CURL *curl);
+
+/*
+ * NAME curl_easy_recv()
+ *
+ * DESCRIPTION
+ *
+ * Receives data from the connected socket. Use after successful
+ * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
+ */
+CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen,
+ size_t *n);
+
+/*
+ * NAME curl_easy_send()
+ *
+ * DESCRIPTION
+ *
+ * Sends data over the connected socket. Use after successful
+ * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
+ */
+CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer,
+ size_t buflen, size_t *n);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/plugins/FTPFileYM/curl/mprintf.h b/plugins/FTPFileYM/curl/mprintf.h
new file mode 100644
index 0000000000..d7202de170
--- /dev/null
+++ b/plugins/FTPFileYM/curl/mprintf.h
@@ -0,0 +1,82 @@
+#ifndef __CURL_MPRINTF_H
+#define __CURL_MPRINTF_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2006, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: mprintf.h,v 1.16 2008-05-20 10:21:50 patrickm Exp $
+ ***************************************************************************/
+
+#include <stdarg.h>
+#include <stdio.h> /* needed for FILE */
+
+#include "curl.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CURL_EXTERN int curl_mprintf(const char *format, ...);
+CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...);
+CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...);
+CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength,
+ const char *format, ...);
+CURL_EXTERN int curl_mvprintf(const char *format, va_list args);
+CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args);
+CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args);
+CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength,
+ const char *format, va_list args);
+CURL_EXTERN char *curl_maprintf(const char *format, ...);
+CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args);
+
+#ifdef _MPRINTF_REPLACE
+# undef printf
+# undef fprintf
+# undef sprintf
+# undef vsprintf
+# undef snprintf
+# undef vprintf
+# undef vfprintf
+# undef vsnprintf
+# undef aprintf
+# undef vaprintf
+# define printf curl_mprintf
+# define fprintf curl_mfprintf
+#ifdef CURLDEBUG
+/* When built with CURLDEBUG we define away the sprintf() functions since we
+ don't want internal code to be using them */
+# define sprintf sprintf_was_used
+# define vsprintf vsprintf_was_used
+#else
+# define sprintf curl_msprintf
+# define vsprintf curl_mvsprintf
+#endif
+# define snprintf curl_msnprintf
+# define vprintf curl_mvprintf
+# define vfprintf curl_mvfprintf
+# define vsnprintf curl_mvsnprintf
+# define aprintf curl_maprintf
+# define vaprintf curl_mvaprintf
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CURL_MPRINTF_H */
diff --git a/plugins/FTPFileYM/curl/multi.h b/plugins/FTPFileYM/curl/multi.h
new file mode 100644
index 0000000000..153f7721c9
--- /dev/null
+++ b/plugins/FTPFileYM/curl/multi.h
@@ -0,0 +1,346 @@
+#ifndef __CURL_MULTI_H
+#define __CURL_MULTI_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2007, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: multi.h,v 1.45 2008-05-20 10:21:50 patrickm Exp $
+ ***************************************************************************/
+/*
+ This is an "external" header file. Don't give away any internals here!
+
+ GOALS
+
+ o Enable a "pull" interface. The application that uses libcurl decides where
+ and when to ask libcurl to get/send data.
+
+ o Enable multiple simultaneous transfers in the same thread without making it
+ complicated for the application.
+
+ o Enable the application to select() on its own file descriptors and curl's
+ file descriptors simultaneous easily.
+
+*/
+
+/*
+ * This header file should not really need to include "curl.h" since curl.h
+ * itself includes this file and we expect user applications to do #include
+ * <curl/curl.h> without the need for especially including multi.h.
+ *
+ * For some reason we added this include here at one point, and rather than to
+ * break existing (wrongly written) libcurl applications, we leave it as-is
+ * but with this warning attached.
+ */
+#include "curl.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef void CURLM;
+
+typedef enum {
+ CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or
+ curl_multi_socket*() soon */
+ CURLM_OK,
+ CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */
+ CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */
+ CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */
+ CURLM_INTERNAL_ERROR, /* this is a libcurl bug */
+ CURLM_BAD_SOCKET, /* the passed in socket argument did not match */
+ CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */
+ CURLM_LAST
+} CURLMcode;
+
+/* just to make code nicer when using curl_multi_socket() you can now check
+ for CURLM_CALL_MULTI_SOCKET too in the same style it works for
+ curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */
+#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM
+
+typedef enum {
+ CURLMSG_NONE, /* first, not used */
+ CURLMSG_DONE, /* This easy handle has completed. 'result' contains
+ the CURLcode of the transfer */
+ CURLMSG_LAST /* last, not used */
+} CURLMSG;
+
+struct CURLMsg {
+ CURLMSG msg; /* what this message means */
+ CURL *easy_handle; /* the handle it concerns */
+ union {
+ void *whatever; /* message-specific data */
+ CURLcode result; /* return code for transfer */
+ } data;
+};
+typedef struct CURLMsg CURLMsg;
+
+/*
+ * Name: curl_multi_init()
+ *
+ * Desc: inititalize multi-style curl usage
+ *
+ * Returns: a new CURLM handle to use in all 'curl_multi' functions.
+ */
+CURL_EXTERN CURLM *curl_multi_init(void);
+
+/*
+ * Name: curl_multi_add_handle()
+ *
+ * Desc: add a standard curl handle to the multi stack
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle,
+ CURL *curl_handle);
+
+ /*
+ * Name: curl_multi_remove_handle()
+ *
+ * Desc: removes a curl handle from the multi stack again
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
+ CURL *curl_handle);
+
+ /*
+ * Name: curl_multi_fdset()
+ *
+ * Desc: Ask curl for its fd_set sets. The app can use these to select() or
+ * poll() on. We want curl_multi_perform() called as soon as one of
+ * them are ready.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle,
+ fd_set *read_fd_set,
+ fd_set *write_fd_set,
+ fd_set *exc_fd_set,
+ int *max_fd);
+
+ /*
+ * Name: curl_multi_perform()
+ *
+ * Desc: When the app thinks there's data available for curl it calls this
+ * function to read/write whatever there is right now. This returns
+ * as soon as the reads and writes are done. This function does not
+ * require that there actually is data available for reading or that
+ * data can be written, it can be called just in case. It returns
+ * the number of handles that still transfer data in the second
+ * argument's integer-pointer.
+ *
+ * Returns: CURLMcode type, general multi error code. *NOTE* that this only
+ * returns errors etc regarding the whole multi stack. There might
+ * still have occurred problems on invidual transfers even when this
+ * returns OK.
+ */
+CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle,
+ int *running_handles);
+
+ /*
+ * Name: curl_multi_cleanup()
+ *
+ * Desc: Cleans up and removes a whole multi stack. It does not free or
+ * touch any individual easy handles in any way. We need to define
+ * in what state those handles will be if this function is called
+ * in the middle of a transfer.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle);
+
+/*
+ * Name: curl_multi_info_read()
+ *
+ * Desc: Ask the multi handle if there's any messages/informationals from
+ * the individual transfers. Messages include informationals such as
+ * error code from the transfer or just the fact that a transfer is
+ * completed. More details on these should be written down as well.
+ *
+ * Repeated calls to this function will return a new struct each
+ * time, until a special "end of msgs" struct is returned as a signal
+ * that there is no more to get at this point.
+ *
+ * The data the returned pointer points to will not survive calling
+ * curl_multi_cleanup().
+ *
+ * The 'CURLMsg' struct is meant to be very simple and only contain
+ * very basic informations. If more involved information is wanted,
+ * we will provide the particular "transfer handle" in that struct
+ * and that should/could/would be used in subsequent
+ * curl_easy_getinfo() calls (or similar). The point being that we
+ * must never expose complex structs to applications, as then we'll
+ * undoubtably get backwards compatibility problems in the future.
+ *
+ * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out
+ * of structs. It also writes the number of messages left in the
+ * queue (after this read) in the integer the second argument points
+ * to.
+ */
+CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle,
+ int *msgs_in_queue);
+
+/*
+ * Name: curl_multi_strerror()
+ *
+ * Desc: The curl_multi_strerror function may be used to turn a CURLMcode
+ * value into the equivalent human readable error string. This is
+ * useful for printing meaningful error messages.
+ *
+ * Returns: A pointer to a zero-terminated error message.
+ */
+CURL_EXTERN const char *curl_multi_strerror(CURLMcode);
+
+/*
+ * Name: curl_multi_socket() and
+ * curl_multi_socket_all()
+ *
+ * Desc: An alternative version of curl_multi_perform() that allows the
+ * application to pass in one of the file descriptors that have been
+ * detected to have "action" on them and let libcurl perform.
+ * See man page for details.
+ */
+#define CURL_POLL_NONE 0
+#define CURL_POLL_IN 1
+#define CURL_POLL_OUT 2
+#define CURL_POLL_INOUT 3
+#define CURL_POLL_REMOVE 4
+
+#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD
+
+#define CURL_CSELECT_IN 0x01
+#define CURL_CSELECT_OUT 0x02
+#define CURL_CSELECT_ERR 0x04
+
+typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */
+ curl_socket_t s, /* socket */
+ int what, /* see above */
+ void *userp, /* private callback
+ pointer */
+ void *socketp); /* private socket
+ pointer */
+/*
+ * Name: curl_multi_timer_callback
+ *
+ * Desc: Called by libcurl whenever the library detects a change in the
+ * maximum number of milliseconds the app is allowed to wait before
+ * curl_multi_socket() or curl_multi_perform() must be called
+ * (to allow libcurl's timed events to take place).
+ *
+ * Returns: The callback should return zero.
+ */
+typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */
+ long timeout_ms, /* see above */
+ void *userp); /* private callback
+ pointer */
+
+CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
+ int *running_handles);
+
+CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle,
+ curl_socket_t s,
+ int ev_bitmask,
+ int *running_handles);
+
+CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle,
+ int *running_handles);
+
+#ifndef CURL_ALLOW_OLD_MULTI_SOCKET
+/* This macro below was added in 7.16.3 to push users who recompile to use
+ the new curl_multi_socket_action() instead of the old curl_multi_socket()
+*/
+#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z)
+#endif
+
+/*
+ * Name: curl_multi_timeout()
+ *
+ * Desc: Returns the maximum number of milliseconds the app is allowed to
+ * wait before curl_multi_socket() or curl_multi_perform() must be
+ * called (to allow libcurl's timed events to take place).
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle,
+ long *milliseconds);
+
+#undef CINIT /* re-using the same name as in curl.h */
+
+#ifdef CURL_ISOCPP
+#define CINIT(name,type,num) CURLMOPT_ ## name = CURLOPTTYPE_ ## type + num
+#else
+/* The macro "##" is ISO C, we assume pre-ISO C doesn't support it. */
+#define LONG CURLOPTTYPE_LONG
+#define OBJECTPOINT CURLOPTTYPE_OBJECTPOINT
+#define FUNCTIONPOINT CURLOPTTYPE_FUNCTIONPOINT
+#define OFF_T CURLOPTTYPE_OFF_T
+#define CINIT(name,type,number) CURLMOPT_/**/name = type + number
+#endif
+
+typedef enum {
+ /* This is the socket callback function pointer */
+ CINIT(SOCKETFUNCTION, FUNCTIONPOINT, 1),
+
+ /* This is the argument passed to the socket callback */
+ CINIT(SOCKETDATA, OBJECTPOINT, 2),
+
+ /* set to 1 to enable pipelining for this multi handle */
+ CINIT(PIPELINING, LONG, 3),
+
+ /* This is the timer callback function pointer */
+ CINIT(TIMERFUNCTION, FUNCTIONPOINT, 4),
+
+ /* This is the argument passed to the timer callback */
+ CINIT(TIMERDATA, OBJECTPOINT, 5),
+
+ /* maximum number of entries in the connection cache */
+ CINIT(MAXCONNECTS, LONG, 6),
+
+ CURLMOPT_LASTENTRY /* the last unused */
+} CURLMoption;
+
+
+/*
+ * Name: curl_multi_setopt()
+ *
+ * Desc: Sets options for the multi handle.
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle,
+ CURLMoption option, ...);
+
+
+/*
+ * Name: curl_multi_assign()
+ *
+ * Desc: This function sets an association in the multi handle between the
+ * given socket and a private pointer of the application. This is
+ * (only) useful for curl_multi_socket uses.
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle,
+ curl_socket_t sockfd, void *sockp);
+
+#ifdef __cplusplus
+} /* end of extern "C" */
+#endif
+
+#endif
diff --git a/plugins/FTPFileYM/curl/stdcheaders.h b/plugins/FTPFileYM/curl/stdcheaders.h
new file mode 100644
index 0000000000..f739d7f9aa
--- /dev/null
+++ b/plugins/FTPFileYM/curl/stdcheaders.h
@@ -0,0 +1,34 @@
+#ifndef __STDC_HEADERS_H
+#define __STDC_HEADERS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: stdcheaders.h,v 1.9 2009-05-18 12:25:45 yangtse Exp $
+ ***************************************************************************/
+
+#include <sys/types.h>
+
+size_t fread (void *, size_t, size_t, FILE *);
+size_t fwrite (const void *, size_t, size_t, FILE *);
+
+int strcasecmp(const char *, const char *);
+int strncasecmp(const char *, const char *, size_t);
+
+#endif
diff --git a/plugins/FTPFileYM/curl/typecheck-gcc.h b/plugins/FTPFileYM/curl/typecheck-gcc.h
new file mode 100644
index 0000000000..9788305819
--- /dev/null
+++ b/plugins/FTPFileYM/curl/typecheck-gcc.h
@@ -0,0 +1,551 @@
+#ifndef __CURL_TYPECHECK_GCC_H
+#define __CURL_TYPECHECK_GCC_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2009, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ * $Id: typecheck-gcc.h,v 1.9 2009-01-25 23:26:31 bagder Exp $
+ ***************************************************************************/
+
+/* wraps curl_easy_setopt() with typechecking */
+
+/* To add a new kind of warning, add an
+ * if(_curl_is_sometype_option(_curl_opt) && ! _curl_is_sometype(value))
+ * _curl_easy_setopt_err_sometype();
+ * block and define _curl_is_sometype_option, _curl_is_sometype and
+ * _curl_easy_setopt_err_sometype below
+ *
+ * To add an option that uses the same type as an existing option, you'll just
+ * need to extend the appropriate _curl_*_option macro
+ */
+#define curl_easy_setopt(handle, option, value) \
+__extension__ ({ \
+ __typeof__ (option) _curl_opt = option; \
+ if (__builtin_constant_p(_curl_opt)) { \
+ if (_curl_is_long_option(_curl_opt) && !_curl_is_long(value)) \
+ _curl_easy_setopt_err_long(); \
+ if (_curl_is_off_t_option(_curl_opt) && !_curl_is_off_t(value)) \
+ _curl_easy_setopt_err_curl_off_t(); \
+ if (_curl_is_string_option(_curl_opt) && !_curl_is_string(value)) \
+ _curl_easy_setopt_err_string(); \
+ if (_curl_is_write_cb_option(_curl_opt) && !_curl_is_write_cb(value)) \
+ _curl_easy_setopt_err_write_callback(); \
+ if ((_curl_opt) == CURLOPT_READFUNCTION && !_curl_is_read_cb(value)) \
+ _curl_easy_setopt_err_read_cb(); \
+ if ((_curl_opt) == CURLOPT_IOCTLFUNCTION && !_curl_is_ioctl_cb(value)) \
+ _curl_easy_setopt_err_ioctl_cb(); \
+ if ((_curl_opt) == CURLOPT_SOCKOPTFUNCTION && !_curl_is_sockopt_cb(value))\
+ _curl_easy_setopt_err_sockopt_cb(); \
+ if ((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION && \
+ !_curl_is_opensocket_cb(value)) \
+ _curl_easy_setopt_err_opensocket_cb(); \
+ if ((_curl_opt) == CURLOPT_PROGRESSFUNCTION && \
+ !_curl_is_progress_cb(value)) \
+ _curl_easy_setopt_err_progress_cb(); \
+ if ((_curl_opt) == CURLOPT_DEBUGFUNCTION && !_curl_is_debug_cb(value)) \
+ _curl_easy_setopt_err_debug_cb(); \
+ if ((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION && \
+ !_curl_is_ssl_ctx_cb(value)) \
+ _curl_easy_setopt_err_ssl_ctx_cb(); \
+ if (_curl_is_conv_cb_option(_curl_opt) && !_curl_is_conv_cb(value)) \
+ _curl_easy_setopt_err_conv_cb(); \
+ if ((_curl_opt) == CURLOPT_SEEKFUNCTION && !_curl_is_seek_cb(value)) \
+ _curl_easy_setopt_err_seek_cb(); \
+ if (_curl_is_cb_data_option(_curl_opt) && !_curl_is_cb_data(value)) \
+ _curl_easy_setopt_err_cb_data(); \
+ if ((_curl_opt) == CURLOPT_ERRORBUFFER && !_curl_is_error_buffer(value)) \
+ _curl_easy_setopt_err_error_buffer(); \
+ if ((_curl_opt) == CURLOPT_STDERR && !_curl_is_FILE(value)) \
+ _curl_easy_setopt_err_FILE(); \
+ if (_curl_is_postfields_option(_curl_opt) && !_curl_is_postfields(value)) \
+ _curl_easy_setopt_err_postfields(); \
+ if ((_curl_opt) == CURLOPT_HTTPPOST && \
+ !_curl_is_arr((value), struct curl_httppost)) \
+ _curl_easy_setopt_err_curl_httpost(); \
+ if (_curl_is_slist_option(_curl_opt) && \
+ !_curl_is_arr((value), struct curl_slist)) \
+ _curl_easy_setopt_err_curl_slist(); \
+ if ((_curl_opt) == CURLOPT_SHARE && !_curl_is_ptr((value), CURLSH)) \
+ _curl_easy_setopt_err_CURLSH(); \
+ } \
+ curl_easy_setopt(handle, _curl_opt, value); \
+})
+
+/* wraps curl_easy_getinfo() with typechecking */
+/* FIXME: don't allow const pointers */
+#define curl_easy_getinfo(handle, info, arg) \
+__extension__ ({ \
+ __typeof__ (info) _curl_info = info; \
+ if (__builtin_constant_p(_curl_info)) { \
+ if (_curl_is_string_info(_curl_info) && !_curl_is_arr((arg), char *)) \
+ _curl_easy_getinfo_err_string(); \
+ if (_curl_is_long_info(_curl_info) && !_curl_is_arr((arg), long)) \
+ _curl_easy_getinfo_err_long(); \
+ if (_curl_is_double_info(_curl_info) && !_curl_is_arr((arg), double)) \
+ _curl_easy_getinfo_err_double(); \
+ if (_curl_is_slist_info(_curl_info) && \
+ !_curl_is_arr((arg), struct curl_slist *)) \
+ _curl_easy_getinfo_err_curl_slist(); \
+ } \
+ curl_easy_getinfo(handle, _curl_info, arg); \
+})
+
+/* TODO: typechecking for curl_share_setopt() and curl_multi_setopt(),
+ * for now just make sure that the functions are called with three
+ * arguments
+ */
+#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
+#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
+
+
+/* the actual warnings, triggered by calling the _curl_easy_setopt_err*
+ * functions */
+
+/* To define a new warning, use _CURL_WARNING(identifier, "message") */
+#define _CURL_WARNING(id, message) \
+ static void __attribute__((warning(message))) __attribute__((unused)) \
+ __attribute__((noinline)) id(void) { __asm__(""); }
+
+_CURL_WARNING(_curl_easy_setopt_err_long,
+ "curl_easy_setopt expects a long argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_curl_off_t,
+ "curl_easy_setopt expects a curl_off_t argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_string,
+ "curl_easy_setopt expects a string (char* or char[]) argument for this option"
+ )
+_CURL_WARNING(_curl_easy_setopt_err_write_callback,
+ "curl_easy_setopt expects a curl_write_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_read_cb,
+ "curl_easy_setopt expects a curl_read_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_ioctl_cb,
+ "curl_easy_setopt expects a curl_ioctl_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_sockopt_cb,
+ "curl_easy_setopt expects a curl_sockopt_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_opensocket_cb,
+ "curl_easy_setopt expects a curl_opensocket_callback argument for this option"
+ )
+_CURL_WARNING(_curl_easy_setopt_err_progress_cb,
+ "curl_easy_setopt expects a curl_progress_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_debug_cb,
+ "curl_easy_setopt expects a curl_debug_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_ssl_ctx_cb,
+ "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_conv_cb,
+ "curl_easy_setopt expects a curl_conv_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_seek_cb,
+ "curl_easy_setopt expects a curl_seek_callback argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_cb_data,
+ "curl_easy_setopt expects a private data pointer as argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_error_buffer,
+ "curl_easy_setopt expects a char buffer of CURL_ERROR_SIZE as argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_FILE,
+ "curl_easy_setopt expects a FILE* argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_postfields,
+ "curl_easy_setopt expects a void* or char* argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_curl_httpost,
+ "curl_easy_setopt expects a struct curl_httppost* argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_curl_slist,
+ "curl_easy_setopt expects a struct curl_slist* argument for this option")
+_CURL_WARNING(_curl_easy_setopt_err_CURLSH,
+ "curl_easy_setopt expects a CURLSH* argument for this option")
+
+_CURL_WARNING(_curl_easy_getinfo_err_string,
+ "curl_easy_getinfo expects a pointer to char * for this info")
+_CURL_WARNING(_curl_easy_getinfo_err_long,
+ "curl_easy_getinfo expects a pointer to long for this info")
+_CURL_WARNING(_curl_easy_getinfo_err_double,
+ "curl_easy_getinfo expects a pointer to double for this info")
+_CURL_WARNING(_curl_easy_getinfo_err_curl_slist,
+ "curl_easy_getinfo expects a pointer to struct curl_slist * for this info")
+
+/* groups of curl_easy_setops options that take the same type of argument */
+
+/* To add a new option to one of the groups, just add
+ * (option) == CURLOPT_SOMETHING
+ * to the or-expression. If the option takes a long or curl_off_t, you don't
+ * have to do anything
+ */
+
+/* evaluates to true if option takes a long argument */
+#define _curl_is_long_option(option) \
+ (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT)
+
+#define _curl_is_off_t_option(option) \
+ ((option) > CURLOPTTYPE_OFF_T)
+
+/* evaluates to true if option takes a char* argument */
+#define _curl_is_string_option(option) \
+ ((option) == CURLOPT_URL || \
+ (option) == CURLOPT_PROXY || \
+ (option) == CURLOPT_INTERFACE || \
+ (option) == CURLOPT_NETRC_FILE || \
+ (option) == CURLOPT_USERPWD || \
+ (option) == CURLOPT_USERNAME || \
+ (option) == CURLOPT_PASSWORD || \
+ (option) == CURLOPT_PROXYUSERPWD || \
+ (option) == CURLOPT_PROXYUSERNAME || \
+ (option) == CURLOPT_PROXYPASSWORD || \
+ (option) == CURLOPT_NOPROXY || \
+ (option) == CURLOPT_ENCODING || \
+ (option) == CURLOPT_REFERER || \
+ (option) == CURLOPT_USERAGENT || \
+ (option) == CURLOPT_COOKIE || \
+ (option) == CURLOPT_COOKIEFILE || \
+ (option) == CURLOPT_COOKIEJAR || \
+ (option) == CURLOPT_COOKIELIST || \
+ (option) == CURLOPT_FTPPORT || \
+ (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \
+ (option) == CURLOPT_FTP_ACCOUNT || \
+ (option) == CURLOPT_RANGE || \
+ (option) == CURLOPT_CUSTOMREQUEST || \
+ (option) == CURLOPT_SSLCERT || \
+ (option) == CURLOPT_SSLCERTTYPE || \
+ (option) == CURLOPT_SSLKEY || \
+ (option) == CURLOPT_SSLKEYTYPE || \
+ (option) == CURLOPT_KEYPASSWD || \
+ (option) == CURLOPT_SSLENGINE || \
+ (option) == CURLOPT_CAINFO || \
+ (option) == CURLOPT_CAPATH || \
+ (option) == CURLOPT_RANDOM_FILE || \
+ (option) == CURLOPT_EGDSOCKET || \
+ (option) == CURLOPT_SSL_CIPHER_LIST || \
+ (option) == CURLOPT_KRBLEVEL || \
+ (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \
+ (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \
+ (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \
+ (option) == CURLOPT_CRLFILE || \
+ (option) == CURLOPT_ISSUERCERT || \
+ 0)
+
+/* evaluates to true if option takes a curl_write_callback argument */
+#define _curl_is_write_cb_option(option) \
+ ((option) == CURLOPT_HEADERFUNCTION || \
+ (option) == CURLOPT_WRITEFUNCTION)
+
+/* evaluates to true if option takes a curl_conv_callback argument */
+#define _curl_is_conv_cb_option(option) \
+ ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \
+ (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \
+ (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION)
+
+/* evaluates to true if option takes a data argument to pass to a callback */
+#define _curl_is_cb_data_option(option) \
+ ((option) == CURLOPT_WRITEDATA || \
+ (option) == CURLOPT_READDATA || \
+ (option) == CURLOPT_IOCTLDATA || \
+ (option) == CURLOPT_SOCKOPTDATA || \
+ (option) == CURLOPT_OPENSOCKETDATA || \
+ (option) == CURLOPT_PROGRESSDATA || \
+ (option) == CURLOPT_WRITEHEADER || \
+ (option) == CURLOPT_DEBUGDATA || \
+ (option) == CURLOPT_SSL_CTX_DATA || \
+ (option) == CURLOPT_SEEKDATA || \
+ (option) == CURLOPT_PRIVATE || \
+ 0)
+
+/* evaluates to true if option takes a POST data argument (void* or char*) */
+#define _curl_is_postfields_option(option) \
+ ((option) == CURLOPT_POSTFIELDS || \
+ (option) == CURLOPT_COPYPOSTFIELDS || \
+ 0)
+
+/* evaluates to true if option takes a struct curl_slist * argument */
+#define _curl_is_slist_option(option) \
+ ((option) == CURLOPT_HTTPHEADER || \
+ (option) == CURLOPT_HTTP200ALIASES || \
+ (option) == CURLOPT_QUOTE || \
+ (option) == CURLOPT_POSTQUOTE || \
+ (option) == CURLOPT_PREQUOTE || \
+ (option) == CURLOPT_TELNETOPTIONS || \
+ 0)
+
+/* groups of curl_easy_getinfo infos that take the same type of argument */
+
+/* evaluates to true if info expects a pointer to char * argument */
+#define _curl_is_string_info(info) \
+ (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG)
+
+/* evaluates to true if info expects a pointer to long argument */
+#define _curl_is_long_info(info) \
+ (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE)
+
+/* evaluates to true if info expects a pointer to double argument */
+#define _curl_is_double_info(info) \
+ (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST)
+
+/* true if info expects a pointer to struct curl_slist * argument */
+#define _curl_is_slist_info(info) \
+ (CURLINFO_SLIST < (info))
+
+
+/* typecheck helpers -- check whether given expression has requested type*/
+
+/* For pointers, you can use the _curl_is_ptr/_curl_is_arr macros,
+ * otherwise define a new macro. Search for __builtin_types_compatible_p
+ * in the GCC manual.
+ * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is
+ * the actual expression passed to the curl_easy_setopt macro. This
+ * means that you can only apply the sizeof and __typeof__ operators, no
+ * == or whatsoever.
+ */
+
+/* XXX: should evaluate to true iff expr is a pointer */
+#define _curl_is_any_ptr(expr) \
+ (sizeof(expr) == sizeof(void*))
+
+/* evaluates to true if expr is NULL */
+/* XXX: must not evaluate expr, so this check is not accurate */
+#define _curl_is_NULL(expr) \
+ (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL)))
+
+/* evaluates to true if expr is type*, const type* or NULL */
+#define _curl_is_ptr(expr, type) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), type *) || \
+ __builtin_types_compatible_p(__typeof__(expr), const type *))
+
+/* evaluates to true if expr is one of type[], type*, NULL or const type* */
+#define _curl_is_arr(expr, type) \
+ (_curl_is_ptr((expr), type) || \
+ __builtin_types_compatible_p(__typeof__(expr), type []))
+
+/* evaluates to true if expr is a string */
+#define _curl_is_string(expr) \
+ (_curl_is_arr((expr), char) || \
+ _curl_is_arr((expr), signed char) || \
+ _curl_is_arr((expr), unsigned char))
+
+/* evaluates to true if expr is a long (no matter the signedness)
+ * XXX: for now, int is also accepted (and therefore short and char, which
+ * are promoted to int when passed to a variadic function) */
+#define _curl_is_long(expr) \
+ (__builtin_types_compatible_p(__typeof__(expr), long) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed long) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \
+ __builtin_types_compatible_p(__typeof__(expr), int) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed int) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \
+ __builtin_types_compatible_p(__typeof__(expr), short) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed short) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \
+ __builtin_types_compatible_p(__typeof__(expr), char) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed char) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned char))
+
+/* evaluates to true if expr is of type curl_off_t */
+#define _curl_is_off_t(expr) \
+ (__builtin_types_compatible_p(__typeof__(expr), curl_off_t))
+
+/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */
+/* XXX: also check size of an char[] array? */
+#define _curl_is_error_buffer(expr) \
+ (__builtin_types_compatible_p(__typeof__(expr), char *) || \
+ __builtin_types_compatible_p(__typeof__(expr), char[]))
+
+/* evaluates to true if expr is of type (const) void* or (const) FILE* */
+#if 0
+#define _curl_is_cb_data(expr) \
+ (_curl_is_ptr((expr), void) || \
+ _curl_is_ptr((expr), FILE))
+#else /* be less strict */
+#define _curl_is_cb_data(expr) \
+ _curl_is_any_ptr(expr)
+#endif
+
+/* evaluates to true if expr is of type FILE* */
+#define _curl_is_FILE(expr) \
+ (__builtin_types_compatible_p(__typeof__(expr), FILE *))
+
+/* evaluates to true if expr can be passed as POST data (void* or char*) */
+#define _curl_is_postfields(expr) \
+ (_curl_is_ptr((expr), void) || \
+ _curl_is_arr((expr), char))
+
+/* FIXME: the whole callback checking is messy...
+ * The idea is to tolerate char vs. void and const vs. not const
+ * pointers in arguments at least
+ */
+/* helper: __builtin_types_compatible_p distinguishes between functions and
+ * function pointers, hide it */
+#define _curl_callback_compatible(func, type) \
+ (__builtin_types_compatible_p(__typeof__(func), type) || \
+ __builtin_types_compatible_p(__typeof__(func), type*))
+
+/* evaluates to true if expr is of type curl_read_callback or "similar" */
+#define _curl_is_read_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), __typeof__(fread)) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_read_callback) || \
+ _curl_callback_compatible((expr), _curl_read_callback1) || \
+ _curl_callback_compatible((expr), _curl_read_callback2) || \
+ _curl_callback_compatible((expr), _curl_read_callback3) || \
+ _curl_callback_compatible((expr), _curl_read_callback4) || \
+ _curl_callback_compatible((expr), _curl_read_callback5) || \
+ _curl_callback_compatible((expr), _curl_read_callback6))
+typedef size_t (_curl_read_callback1)(char *, size_t, size_t, void*);
+typedef size_t (_curl_read_callback2)(char *, size_t, size_t, const void*);
+typedef size_t (_curl_read_callback3)(char *, size_t, size_t, FILE*);
+typedef size_t (_curl_read_callback4)(void *, size_t, size_t, void*);
+typedef size_t (_curl_read_callback5)(void *, size_t, size_t, const void*);
+typedef size_t (_curl_read_callback6)(void *, size_t, size_t, FILE*);
+
+/* evaluates to true if expr is of type curl_write_callback or "similar" */
+#define _curl_is_write_cb(expr) \
+ (_curl_is_read_cb(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), __typeof__(fwrite)) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_write_callback) || \
+ _curl_callback_compatible((expr), _curl_write_callback1) || \
+ _curl_callback_compatible((expr), _curl_write_callback2) || \
+ _curl_callback_compatible((expr), _curl_write_callback3) || \
+ _curl_callback_compatible((expr), _curl_write_callback4) || \
+ _curl_callback_compatible((expr), _curl_write_callback5) || \
+ _curl_callback_compatible((expr), _curl_write_callback6))
+typedef size_t (_curl_write_callback1)(const char *, size_t, size_t, void*);
+typedef size_t (_curl_write_callback2)(const char *, size_t, size_t,
+ const void*);
+typedef size_t (_curl_write_callback3)(const char *, size_t, size_t, FILE*);
+typedef size_t (_curl_write_callback4)(const void *, size_t, size_t, void*);
+typedef size_t (_curl_write_callback5)(const void *, size_t, size_t,
+ const void*);
+typedef size_t (_curl_write_callback6)(const void *, size_t, size_t, FILE*);
+
+/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */
+#define _curl_is_ioctl_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_ioctl_callback) || \
+ _curl_callback_compatible((expr), _curl_ioctl_callback1) || \
+ _curl_callback_compatible((expr), _curl_ioctl_callback2) || \
+ _curl_callback_compatible((expr), _curl_ioctl_callback3) || \
+ _curl_callback_compatible((expr), _curl_ioctl_callback4))
+typedef curlioerr (_curl_ioctl_callback1)(CURL *, int, void*);
+typedef curlioerr (_curl_ioctl_callback2)(CURL *, int, const void*);
+typedef curlioerr (_curl_ioctl_callback3)(CURL *, curliocmd, void*);
+typedef curlioerr (_curl_ioctl_callback4)(CURL *, curliocmd, const void*);
+
+/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */
+#define _curl_is_sockopt_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_sockopt_callback) || \
+ _curl_callback_compatible((expr), _curl_sockopt_callback1) || \
+ _curl_callback_compatible((expr), _curl_sockopt_callback2))
+typedef int (_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype);
+typedef int (_curl_sockopt_callback2)(const void *, curl_socket_t,
+ curlsocktype);
+
+/* evaluates to true if expr is of type curl_opensocket_callback or "similar" */
+#define _curl_is_opensocket_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_opensocket_callback) ||\
+ _curl_callback_compatible((expr), _curl_opensocket_callback1) || \
+ _curl_callback_compatible((expr), _curl_opensocket_callback2) || \
+ _curl_callback_compatible((expr), _curl_opensocket_callback3) || \
+ _curl_callback_compatible((expr), _curl_opensocket_callback4))
+typedef curl_socket_t (_curl_opensocket_callback1)
+ (void *, curlsocktype, struct curl_sockaddr *);
+typedef curl_socket_t (_curl_opensocket_callback2)
+ (void *, curlsocktype, const struct curl_sockaddr *);
+typedef curl_socket_t (_curl_opensocket_callback3)
+ (const void *, curlsocktype, struct curl_sockaddr *);
+typedef curl_socket_t (_curl_opensocket_callback4)
+ (const void *, curlsocktype, const struct curl_sockaddr *);
+
+/* evaluates to true if expr is of type curl_progress_callback or "similar" */
+#define _curl_is_progress_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_progress_callback) || \
+ _curl_callback_compatible((expr), _curl_progress_callback1) || \
+ _curl_callback_compatible((expr), _curl_progress_callback2))
+typedef int (_curl_progress_callback1)(void *,
+ double, double, double, double);
+typedef int (_curl_progress_callback2)(const void *,
+ double, double, double, double);
+
+/* evaluates to true if expr is of type curl_debug_callback or "similar" */
+#define _curl_is_debug_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_debug_callback) || \
+ _curl_callback_compatible((expr), _curl_debug_callback1) || \
+ _curl_callback_compatible((expr), _curl_debug_callback2) || \
+ _curl_callback_compatible((expr), _curl_debug_callback3) || \
+ _curl_callback_compatible((expr), _curl_debug_callback4))
+typedef int (_curl_debug_callback1) (CURL *,
+ curl_infotype, char *, size_t, void *);
+typedef int (_curl_debug_callback2) (CURL *,
+ curl_infotype, char *, size_t, const void *);
+typedef int (_curl_debug_callback3) (CURL *,
+ curl_infotype, const char *, size_t, void *);
+typedef int (_curl_debug_callback4) (CURL *,
+ curl_infotype, const char *, size_t, const void *);
+
+/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */
+/* this is getting even messier... */
+#define _curl_is_ssl_ctx_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_ssl_ctx_callback) || \
+ _curl_callback_compatible((expr), _curl_ssl_ctx_callback1) || \
+ _curl_callback_compatible((expr), _curl_ssl_ctx_callback2) || \
+ _curl_callback_compatible((expr), _curl_ssl_ctx_callback3) || \
+ _curl_callback_compatible((expr), _curl_ssl_ctx_callback4) || \
+ _curl_callback_compatible((expr), _curl_ssl_ctx_callback5) || \
+ _curl_callback_compatible((expr), _curl_ssl_ctx_callback6) || \
+ _curl_callback_compatible((expr), _curl_ssl_ctx_callback7) || \
+ _curl_callback_compatible((expr), _curl_ssl_ctx_callback8))
+typedef CURLcode (_curl_ssl_ctx_callback1)(CURL *, void *, void *);
+typedef CURLcode (_curl_ssl_ctx_callback2)(CURL *, void *, const void *);
+typedef CURLcode (_curl_ssl_ctx_callback3)(CURL *, const void *, void *);
+typedef CURLcode (_curl_ssl_ctx_callback4)(CURL *, const void *, const void *);
+#ifdef HEADER_SSL_H
+/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX
+ * this will of course break if we're included before OpenSSL headers...
+ */
+typedef CURLcode (_curl_ssl_ctx_callback5)(CURL *, SSL_CTX, void *);
+typedef CURLcode (_curl_ssl_ctx_callback6)(CURL *, SSL_CTX, const void *);
+typedef CURLcode (_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX, void *);
+typedef CURLcode (_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX, const void *);
+#else
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8;
+#endif
+
+/* evaluates to true if expr is of type curl_conv_callback or "similar" */
+#define _curl_is_conv_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_conv_callback) || \
+ _curl_callback_compatible((expr), _curl_conv_callback1) || \
+ _curl_callback_compatible((expr), _curl_conv_callback2) || \
+ _curl_callback_compatible((expr), _curl_conv_callback3) || \
+ _curl_callback_compatible((expr), _curl_conv_callback4))
+typedef CURLcode (*_curl_conv_callback1)(char *, size_t length);
+typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length);
+typedef CURLcode (*_curl_conv_callback3)(void *, size_t length);
+typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length);
+
+/* evaluates to true if expr is of type curl_seek_callback or "similar" */
+#define _curl_is_seek_cb(expr) \
+ (_curl_is_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), curl_seek_callback) || \
+ _curl_callback_compatible((expr), _curl_seek_callback1) || \
+ _curl_callback_compatible((expr), _curl_seek_callback2))
+typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int);
+typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int);
+
+
+#endif /* __CURL_TYPECHECK_GCC_H */
diff --git a/plugins/FTPFileYM/curl/types.h b/plugins/FTPFileYM/curl/types.h
new file mode 100644
index 0000000000..d37d6ae9e1
--- /dev/null
+++ b/plugins/FTPFileYM/curl/types.h
@@ -0,0 +1 @@
+/* not used */
diff --git a/plugins/FTPFileYM/dbentry.cpp b/plugins/FTPFileYM/dbentry.cpp
new file mode 100644
index 0000000000..cb11af1944
--- /dev/null
+++ b/plugins/FTPFileYM/dbentry.cpp
@@ -0,0 +1,169 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "dbentry.h"
+#include "options.h"
+
+int DBEntry::entryID;
+Mutex DBEntry::mutexDB;
+
+DBEntry::DBEntry()
+{ }
+
+DBEntry::DBEntry(DBEntry *entry)
+{
+ this->fileID = entry->fileID;
+ this->iFtpNum = entry->iFtpNum;
+ strcpy(this->szFileName, entry->szFileName);
+}
+
+DBEntry *DBEntry::getFirts()
+{
+ entryID = 0;
+ DBEntry *entry = new DBEntry();
+ return getNext(entry);
+}
+
+DBEntry *DBEntry::getNext(DBEntry *entry)
+{
+ char szValue[256];
+ int count = DB::getDword(0, MODULE_FILES, "NextFileID", 0);
+
+ for (; entryID < count; entryID++)
+ {
+ int ftpNum = DB::getByteF(0, MODULE_FILES, "Ftp%d", entryID, -1);
+ if (ftpNum != -1)
+ {
+ if (!DB::getAStringF(0, MODULE_FILES, "Filename%d", entryID, szValue))
+ {
+ entry->fileID = entryID;
+ entry->iFtpNum = ftpNum;
+ strcpy(entry->szFileName, szValue);
+ entry->deleteTS = DB::getDwordF(0, MODULE_FILES, "DeleteTS%d", entryID, 0);
+ entryID++;
+ return entry;
+ }
+ }
+ }
+
+ delete entry;
+ return NULL;
+}
+
+void DBEntry::cleanupDB()
+{
+ int count = 0;
+
+ DBEntry *entry = getFirts();
+ while (entry != NULL)
+ {
+ DB::setByteF(0, MODULE_FILES, "Ftp%d", count, entry->iFtpNum);
+ DB::setAStringF(0, MODULE_FILES, "Filename%d", count, entry->szFileName);
+ if (entry->deleteTS != 0)
+ DB::setDwordF(0, MODULE_FILES, "DeleteTS%d", count, entry->deleteTS);
+
+ count++;
+ entry = getNext(entry);
+ }
+
+ DB::setDword(0, MODULE_FILES, "NextFileID", count);
+}
+
+DBEntry *DBEntry::get(int fileID)
+{
+ char szValue[256];
+ DBEntry *entry = new DBEntry();
+
+ int ftpNum = DB::getByteF(0, MODULE_FILES, "Ftp%d", fileID, -1);
+ if (ftpNum != -1)
+ {
+ if (!DB::getAStringF(0, MODULE_FILES, "Filename%d", fileID, szValue))
+ {
+ entry->fileID = fileID;
+ entry->iFtpNum = ftpNum;
+ strcpy(entry->szFileName, szValue);
+ entry->deleteTS = DB::getDwordF(0, MODULE_FILES, "DeleteTS%d", fileID, 0);
+ return entry;
+ }
+ }
+
+ return NULL;
+}
+
+void DBEntry::remove(int fileID)
+{
+ DB::deleteSettingF(0, MODULE_FILES, "Ftp%d", fileID);
+ DB::deleteSettingF(0, MODULE_FILES, "Filename%d", fileID);
+ DB::deleteSettingF(0, MODULE_FILES, "DeleteTS%d", fileID);
+}
+
+bool DBEntry::entryExists(GenericJob *job)
+{
+ Lock *lock = new Lock(mutexDB);
+
+ DBEntry *entry = getFirts();
+ while (entry != NULL)
+ {
+ if (entry->iFtpNum == job->iFtpNum && !strcmp(entry->szFileName, job->szSafeFileName))
+ {
+ delete lock;
+ return true;
+ }
+ entry = getNext(entry);
+ }
+
+ delete lock;
+ return false;
+}
+
+void DBEntry::add(GenericJob *job)
+{
+ if (entryExists(job))
+ return;
+
+ Lock *lock = new Lock(mutexDB);
+ int id = DB::getDword(0, MODULE_FILES, "NextFileID", 0);
+ DB::setByteF(0, MODULE_FILES, "Ftp%d", id, job->iFtpNum);
+ DB::setAStringF(0, MODULE_FILES, "Filename%d", id, job->szSafeFileName);
+
+ if (job->tab->iOptAutoDelete != -1)
+ {
+ time_t deleteTS = time(NULL);
+ deleteTS += (job->tab->iOptAutoDelete * 60);
+ DB::setDwordF(0, MODULE_FILES, "DeleteTS%d", id, deleteTS);
+ }
+
+ DB::setDword(0, MODULE_FILES, "NextFileID", id + 1);
+ job->fileID = id;
+
+ delete lock;
+}
+
+void DBEntry::setDeleteTS(GenericJob *job)
+{
+ if (job->tab->iOptAutoDelete != -1)
+ {
+ time_t deleteTS = time(NULL);
+ deleteTS += (job->tab->iOptAutoDelete * 60);
+ DB::setDwordF(0, MODULE_FILES, "DeleteTS%d", job->fileID, deleteTS);
+ }
+ else
+ {
+ DB::deleteSettingF(0, MODULE_FILES, "DeleteTS%d", job->fileID);
+ }
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/dbentry.h b/plugins/FTPFileYM/dbentry.h
new file mode 100644
index 0000000000..27ad865559
--- /dev/null
+++ b/plugins/FTPFileYM/dbentry.h
@@ -0,0 +1,51 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+#include "job_upload.h"
+#include "utils.h"
+
+class DBEntry
+{
+private:
+ static int entryID;
+ static bool entryExists(GenericJob *job);
+
+public:
+ int fileID;
+ int iFtpNum;
+ char szFileName[256];
+ DWORD deleteTS;
+
+ static Mutex mutexDB;
+
+ DBEntry();
+ DBEntry(DBEntry *entry);
+
+ static DBEntry *getFirts();
+ static DBEntry *getNext(DBEntry *entry);
+ static void cleanupDB();
+
+ static DBEntry *get(int fileID);
+ static void remove(int fileID);
+
+ static void add(GenericJob *job);
+ static void setDeleteTS(GenericJob *job);
+};
diff --git a/plugins/FTPFileYM/deletetimer.cpp b/plugins/FTPFileYM/deletetimer.cpp
new file mode 100644
index 0000000000..480a0a9c3b
--- /dev/null
+++ b/plugins/FTPFileYM/deletetimer.cpp
@@ -0,0 +1,73 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "deletetimer.h"
+#include "dbentry.h"
+#include "job_delete.h"
+
+DeleteTimer *DeleteTimer::instance = NULL;
+DeleteTimer &deleteTimer = DeleteTimer::getInstance();
+
+extern Options &opt;
+
+void DeleteTimer::init()
+{
+ timerId = 0;
+ if (opt.bAutoDelete)
+ this->start();
+}
+
+void DeleteTimer::deinit()
+{
+ this->stop();
+ delete this;
+}
+
+void DeleteTimer::start()
+{
+ if (!timerId)
+ timerId = SetTimer(NULL, 0, 1000 * 60 * 5, (TIMERPROC)AutoDeleteTimerProc);
+}
+
+void DeleteTimer::stop()
+{
+ if (timerId)
+ {
+ KillTimer(NULL, timerId);
+ timerId = 0;
+ }
+}
+
+void CALLBACK DeleteTimer::AutoDeleteTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
+{
+ Lock *lock = new Lock(DBEntry::mutexDB);
+
+ DBEntry *entry = DBEntry::getFirts();
+ while (entry != NULL)
+ {
+ if (entry->deleteTS > 0 && entry->deleteTS < time(NULL))
+ {
+ DeleteJob *job = new DeleteJob(new DBEntry(entry), NULL);
+ job->start();
+ }
+
+ entry = DBEntry::getNext(entry);
+ }
+
+ delete lock;
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/deletetimer.h b/plugins/FTPFileYM/deletetimer.h
new file mode 100644
index 0000000000..9fbe478c9d
--- /dev/null
+++ b/plugins/FTPFileYM/deletetimer.h
@@ -0,0 +1,47 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+#include "options.h"
+
+class DeleteTimer
+{
+private:
+ static DeleteTimer *instance;
+ UINT timerId;
+
+ DeleteTimer() { };
+ ~DeleteTimer() { instance = NULL; };
+
+ static void CALLBACK AutoDeleteTimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
+
+public:
+ static DeleteTimer &getInstance()
+ {
+ if (!instance)
+ instance = new DeleteTimer();
+ return *instance;
+ };
+
+ void init();
+ void deinit();
+ void start();
+ void stop();
+}; \ No newline at end of file
diff --git a/plugins/FTPFileYM/dialog.cpp b/plugins/FTPFileYM/dialog.cpp
new file mode 100644
index 0000000000..9cef156189
--- /dev/null
+++ b/plugins/FTPFileYM/dialog.cpp
@@ -0,0 +1,456 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "dialog.h"
+#include "dbentry.h"
+#include "options.h"
+#include "job_upload.h"
+#include "job_packer.h"
+
+UploadDialog *UploadDialog::instance = NULL;
+UploadDialog *uDlg = NULL;
+
+Mutex UploadDialog::mutexTabs;
+WNDPROC UploadDialog::oldTabControlProc;
+
+extern Options &opt;
+extern BOOL (WINAPI *MyEnableThemeDialogTexture)(HANDLE, DWORD);
+
+UploadDialog::UploadDialog()
+{
+ this->hwnd = CreateDialog(hInst, MAKEINTRESOURCE(IDD_DLG_UPLOAD), 0, UploadDlgProc);
+ this->hwndTabs = GetDlgItem(this->hwnd, IDC_TAB);
+ MyEnableThemeDialogTexture(this->hwnd, ETDT_ENABLETAB);
+
+ MONITORINFO mi = {0};
+ mi.cbSize = sizeof(mi);
+ HMONITOR hMonitor = MonitorFromWindow(this->hwnd, MONITOR_DEFAULTTONEAREST);
+ GetMonitorInfo(hMonitor, &mi);
+
+ RECT rc;
+ GetWindowRect(this->hwnd, &rc);
+ rc.left = mi.rcWork.left + ((mi.rcWork.right - mi.rcWork.left) - (rc.right-rc.left)) / 2;
+ rc.top = mi.rcWork.top + ((mi.rcWork.bottom - mi.rcWork.top) - (rc.bottom-rc.top)) / 2;
+ SetWindowPos(this->hwnd, 0, rc.left, rc.top, 0, 0, SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOSIZE);
+}
+
+UploadDialog::~UploadDialog()
+{
+ if (this->hwnd)
+ {
+ ShowWindow(this->hwnd, SW_HIDE);
+ SendMessage(this->hwnd, WMU_DESTROY, 0, 0);
+ }
+
+ instance = NULL;
+ uDlg = NULL;
+}
+
+void UploadDialog::selectTab(int index)
+{
+ if (tabs[index] != NULL)
+ tabs[index]->select();
+}
+
+void UploadDialog::show()
+{
+ ShowWindow(this->hwnd, SW_SHOWNORMAL);
+}
+
+UploadDialog::Tab::Tab(GenericJob *Job)
+:job(Job),bOptCloseDlg(opt.bCloseDlg),bOptCopyLink(opt.bCopyLink),bOptAutosend(opt.bAutosend),iOptAutoDelete(-1)
+{
+ if (opt.bAutoDelete)
+ this->iOptAutoDelete = Utils::getDeleteTimeMin();
+
+ this->stzSpeed[0] = 0;
+ this->stzComplet[0] = 0;
+ this->stzRemain[0] = 0;
+
+ TCHAR buff[256];
+ TCITEM tab = {0};
+ tab.mask = TCIF_TEXT;
+ tab.pszText = Utils::getTextFragment(job->stzFileName, 20, buff);
+ TabCtrl_InsertItem(uDlg->hwndTabs, uDlg->tabs.size(), &tab);
+
+ Lock *lock = new Lock(mutexTabs);
+ uDlg->tabs.push_back(this);
+ delete lock;
+
+ this->select();
+}
+
+UploadDialog::Tab::~Tab()
+{
+ Lock *lock = new Lock(mutexTabs);
+ TabCtrl_DeleteItem(uDlg->hwndTabs, this->index());
+ uDlg->tabs.erase(uDlg->tabs.begin() + this->index());
+ delete lock;
+
+ if (this->job->isCompleted())
+ delete this->job;
+
+ if (uDlg->tabs.size() == 0)
+ delete uDlg;
+ else
+ uDlg->selectTab(0);
+}
+
+int UploadDialog::Tab::index()
+{
+ for (UINT i = 0; i < uDlg->tabs.size(); i++)
+ {
+ if (uDlg->tabs[i] == this)
+ return i;
+ }
+
+ return -1;
+}
+
+void UploadDialog::Tab::select()
+{
+ TabCtrl_SetCurSel(uDlg->hwndTabs, this->index());
+
+ Lock *lock = new Lock(mutexTabs);
+ uDlg->activeTab = this->index();
+ delete lock;
+
+ this->job->refreshTab(true);
+ InvalidateRect(uDlg->hwnd, NULL, TRUE);
+}
+
+void UploadDialog::Tab::labelCompleted()
+{
+ TCHAR buff[64], buff2[256];
+ mir_sntprintf(buff2, SIZEOF(buff2), _T("* %s"), Utils::getTextFragment(this->job->stzFileName, 20, buff));
+
+ TCITEM tab = {0};
+ tab.mask = TCIF_TEXT;
+ tab.pszText = buff2;
+ TabCtrl_SetItem(uDlg->hwndTabs, this->index(), &tab);
+}
+
+INT_PTR CALLBACK UploadDialog::TabControlProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch (msg)
+ {
+ case WM_LBUTTONDBLCLK:
+ case WM_MBUTTONDOWN:
+ {
+ POINT pt;
+ GetCursorPos(&pt);
+ ScreenToClient(uDlg->hwndTabs, &pt);
+
+ TCHITTESTINFO tch;
+ tch.pt = pt;
+ tch.flags = 0;
+ int index = TabCtrl_HitTest(uDlg->hwndTabs, &tch);
+
+ if (index != -1)
+ uDlg->tabs[index]->job->closeTab();
+ }
+ break;
+ }
+
+ return CallWindowProc(UploadDialog::oldTabControlProc, hwnd, msg, wParam, lParam);
+}
+
+INT_PTR CALLBACK UploadDialog::UploadDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch (msg)
+ {
+ case WM_INITDIALOG:
+ {
+ TranslateDialogDefault(hwndDlg);
+ SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM)Utils::loadIconEx("main"));
+
+ UploadDialog::oldTabControlProc = (WNDPROC)SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_TAB), GWLP_WNDPROC, (LONG_PTR)TabControlProc);
+
+ LOGFONT logFont = {0};
+ HFONT hFont = (HFONT)SendMessage(GetDlgItem(hwndDlg, IDC_ST_FILE), WM_GETFONT, 0, 0);
+ GetObject(hFont, sizeof(logFont), &logFont);
+ logFont.lfWeight = FW_BOLD;
+ hFont = CreateFontIndirect(&logFont);
+ SendMessage(GetDlgItem(hwndDlg, IDC_ST_CONTACT), WM_SETFONT, (WPARAM)hFont, 0);
+ SendMessage(GetDlgItem(hwndDlg, IDC_ST_FILE), WM_SETFONT, (WPARAM)hFont, 0);
+ SendMessage(GetDlgItem(hwndDlg, IDC_ST_SERVER), WM_SETFONT, (WPARAM)hFont, 0);
+ SendMessage(GetDlgItem(hwndDlg, IDC_ST_SPEED), WM_SETFONT, (WPARAM)hFont, 0);
+ SendMessage(GetDlgItem(hwndDlg, IDC_ST_COMPLETED), WM_SETFONT, (WPARAM)hFont, 0);
+ SendMessage(GetDlgItem(hwndDlg, IDC_ST_REMAIN), WM_SETFONT, (WPARAM)hFont, 0);
+
+ logFont.lfHeight -= 4;
+ hFont = CreateFontIndirect(&logFont);
+ SendMessage(GetDlgItem(hwndDlg, IDC_UP_CONTACT), WM_SETFONT, (WPARAM)hFont, 0);
+
+ SendDlgItemMessage(hwndDlg, IDC_BTN_PROTO, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_PROTO, BUTTONADDTOOLTIP, (WPARAM)TranslateT("User Info"), BATF_TCHAR);
+
+ SendDlgItemMessage(hwndDlg, IDC_BTN_PAUSE, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_PAUSE, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("pause"));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_PAUSE, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Pause"), BATF_TCHAR);
+
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLIPBOARD, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLIPBOARD, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("clipboard"));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLIPBOARD, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Copy Link to Clipboard"), BATF_TCHAR);
+
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DOWNLOAD, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DOWNLOAD, BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadSkinnedIcon(SKINICON_EVENT_URL));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DOWNLOAD, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Open in Browser"), BATF_TCHAR);
+
+ SendDlgItemMessage(hwndDlg, IDC_BTN_FILEMANAGER, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_FILEMANAGER, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("main"));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_FILEMANAGER, BUTTONADDTOOLTIP, (WPARAM)TranslateT("FTP File Manager"), BATF_TCHAR);
+
+ SendDlgItemMessage(hwndDlg, IDC_BTN_OPTIONS, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_OPTIONS, BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadSkinnedIcon(SKINICON_OTHER_OPTIONS));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_OPTIONS, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Options"), BATF_TCHAR);
+
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLOSE, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLOSE, BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadSkinnedIcon(SKINICON_OTHER_DELETE));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLOSE, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Close"), BATF_TCHAR);
+
+ break;
+ }
+ case WM_MEASUREITEM:
+ {
+ return CallService(MS_CLIST_MENUMEASUREITEM, wParam, lParam);
+ }
+ case WM_DRAWITEM:
+ {
+ return CallService(MS_CLIST_MENUDRAWITEM, wParam, lParam);
+ }
+ case WM_COMMAND:
+ {
+ HANDLE hContact = uDlg->tabs[uDlg->activeTab]->job->hContact;
+ if (hContact != NULL)
+ {
+ if (CallService(MS_CLIST_MENUPROCESSCOMMAND, MAKEWPARAM(LOWORD(wParam),MPCF_CONTACTMENU), (LPARAM)hContact))
+ break;
+ }
+
+ if (HIWORD(wParam) == BN_CLICKED)
+ {
+ switch (LOWORD(wParam))
+ {
+ case IDC_BTN_PROTO:
+ {
+ if (hContact != NULL)
+ {
+ RECT rc;
+ HMENU hMenu = (HMENU)CallService(MS_CLIST_MENUBUILDCONTACT, (WPARAM)hContact, 0);
+ GetWindowRect((HWND)lParam, &rc);
+ TrackPopupMenu(hMenu, 0, rc.left, rc.bottom, 0, hwndDlg, NULL);
+ DestroyMenu(hMenu);
+ }
+
+ break;
+ }
+ case IDC_BTN_PAUSE:
+ {
+ uDlg->tabs[uDlg->activeTab]->job->pauseHandler();
+ return TRUE;
+ }
+ case IDC_BTN_CLIPBOARD:
+ {
+ UploadJob *job = (UploadJob *)uDlg->tabs[uDlg->activeTab]->job;
+ Utils::copyToClipboard(job->szFileLink);
+ return TRUE;
+ }
+ case IDC_BTN_DOWNLOAD:
+ {
+ UploadJob *job = (UploadJob *)uDlg->tabs[uDlg->activeTab]->job;
+ ShellExecuteA(NULL, "open", job->szFileLink, NULL, NULL, SW_SHOWNORMAL);
+ return TRUE;
+ }
+ case IDC_BTN_FILEMANAGER:
+ {
+ CallService(MS_FTPFILE_SHOWMANAGER, 0, 0);
+ return TRUE;
+ }
+ case IDC_BTN_OPTIONS:
+ {
+ Tab *tab = uDlg->tabs[uDlg->activeTab];
+
+ POINT pt;
+ GetCursorPos(&pt);
+ SetForegroundWindow(uDlg->hwndTabs);
+
+ HMENU hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_MENU_UPLOAD));
+ if (hMenu)
+ {
+ HMENU hPopupMenu = GetSubMenu(hMenu, 0);
+ CallService(MS_LANGPACK_TRANSLATEMENU, (WPARAM)hPopupMenu, 0);
+ CheckMenuItem(hPopupMenu, IDM_CLOSEDLG, MF_BYCOMMAND | tab->bOptCloseDlg ? MF_CHECKED : 0);
+ CheckMenuItem(hPopupMenu, IDM_COPYLINK, MF_BYCOMMAND | tab->bOptCopyLink ? MF_CHECKED : 0);
+ CheckMenuItem(hPopupMenu, IDM_AUTOSEND, MF_BYCOMMAND | tab->bOptAutosend ? MF_CHECKED : 0);
+
+ HMENU hTimeMenu = GetSubMenu(hPopupMenu, 3);
+ CheckMenuItem(hTimeMenu, IDM_DISABLED, MF_BYCOMMAND | (tab->iOptAutoDelete == -1) ? MF_CHECKED : MF_UNCHECKED);
+
+ int times[10] = {5, 15, 30, 1 * 60, 2 * 60, 5 * 60, 10 * 60, 1 * 24 * 60, 2 * 24 * 60, 7 * 24 * 60};
+ bool bChecked = (tab->iOptAutoDelete == -1) ? true : false;
+ TCHAR buff[256];
+
+ for (int i = 0; i < SIZEOF(times); i++)
+ {
+ if (i == 3 || i == 7)
+ AppendMenu(hTimeMenu, MF_SEPARATOR, 0, 0);
+
+ if (i < 3)
+ mir_sntprintf(buff, SIZEOF(buff), TranslateT("%d minutes"), times[i]);
+ else if (i < 7)
+ mir_sntprintf(buff, SIZEOF(buff), TranslateT("%d hours"), times[i] / 60);
+ else
+ mir_sntprintf(buff, SIZEOF(buff), TranslateT("%d days"), times[i] / 60 / 24);
+
+ UINT check = MF_UNCHECKED;
+ if (!bChecked && tab->iOptAutoDelete == times[i])
+ {
+ check = MF_CHECKED;
+ bChecked = true;
+ }
+
+ AppendMenu(hTimeMenu, MF_STRING | check, times[i], buff);
+ }
+
+ if (opt.bAutoDelete)
+ {
+ switch (opt.timeRange)
+ {
+ case Options::TR_MINUTES: mir_sntprintf(buff, SIZEOF(buff), TranslateT("%d minutes"), opt.iDeleteTime); break;
+ case Options::TR_HOURS: mir_sntprintf(buff, SIZEOF(buff), TranslateT("%d hours"), opt.iDeleteTime); break;
+ case Options::TR_DAYS: mir_sntprintf(buff, SIZEOF(buff), TranslateT("%d days"), opt.iDeleteTime); break;
+ }
+
+ AppendMenu(hTimeMenu, MF_SEPARATOR, 0, 0);
+ AppendMenu(hTimeMenu, MF_STRING | bChecked ? MF_UNCHECKED : MF_CHECKED, IDM_CUSTOM, buff);
+ }
+
+ int command = TrackPopupMenu(hPopupMenu, TPM_LEFTALIGN | TPM_RETURNCMD, pt.x, pt.y, 0, uDlg->hwndTabs, NULL);
+ switch (command)
+ {
+ case IDM_CLOSEDLG:
+ tab->bOptCloseDlg = !tab->bOptCloseDlg; break;
+ case IDM_COPYLINK:
+ tab->bOptCopyLink = !tab->bOptCopyLink; break;
+ case IDM_AUTOSEND:
+ tab->bOptAutosend = !tab->bOptAutosend; break;
+ case IDM_DISABLED:
+ tab->iOptAutoDelete = -1; break;
+ case IDM_CUSTOM:
+ switch (opt.timeRange)
+ {
+ case Options::TR_MINUTES: tab->iOptAutoDelete = opt.iDeleteTime; break;
+ case Options::TR_HOURS: tab->iOptAutoDelete = opt.iDeleteTime * 60; break;
+ case Options::TR_DAYS: tab->iOptAutoDelete = opt.iDeleteTime * 60 * 24; break;
+ }
+ break;
+ default:
+ tab->iOptAutoDelete = command;
+ break;
+ }
+
+ if (command && ((UploadJob *)tab->job)->isCompleted())
+ DBEntry::setDeleteTS(tab->job);
+
+ DestroyMenu(hMenu);
+ }
+ return TRUE;
+ }
+ case IDC_BTN_CLOSE:
+ {
+ uDlg->tabs[uDlg->activeTab]->job->closeTab();
+ return TRUE;
+ }
+ }
+ }
+ break;
+ }
+ case WM_NOTIFY:
+ {
+ switch (((LPNMHDR)lParam)->code)
+ {
+ case TCN_SELCHANGE:
+ {
+ uDlg->selectTab(TabCtrl_GetCurSel(uDlg->hwndTabs));
+ break;
+ }
+ case TTN_GETDISPINFO:
+ {
+ LPNMTTDISPINFO pInfo = (LPNMTTDISPINFO)lParam;
+
+ POINT pt;
+ GetCursorPos(&pt);
+ ScreenToClient(hwndDlg, &pt);
+
+ UINT i; RECT rc;
+ for (i = 0; i < uDlg->tabs.size(); i++)
+ {
+ if (uDlg->tabs[i] != NULL)
+ {
+ TabCtrl_GetItemRect(uDlg->hwndTabs, i, &rc);
+ if (PtInRect(&rc, pt)) break;
+ }
+ }
+
+ if (i < uDlg->tabs.size())
+ {
+ uDlg->tabs[i]->job->createToolTip();
+ HWND hToolTip = TabCtrl_GetToolTips(uDlg->hwndTabs);
+ SendMessage(hToolTip, TTM_SETMAXTIPWIDTH, 0, (LPARAM)500);
+ pInfo->lpszText = uDlg->stzToolTipText;
+ }
+
+ break;
+ }
+ }
+ break;
+ }
+ case WM_CLOSE:
+ {
+ for (UINT i = 0; i < uDlg->tabs.size(); i++)
+ uDlg->tabs[i]->job->pause();
+
+ int result = IDYES;
+ if (!Miranda_Terminated() && UploadJob::iRunningJobCount > 0)
+ result = Utils::msgBox(TranslateT("Do you really want to cancel all running jobs?"), MB_YESNO | MB_ICONQUESTION);
+
+ if (result == IDYES)
+ {
+ SkinPlaySound(SOUND_CANCEL);
+ size_t count = uDlg->tabs.size();
+ for (UINT i = 0; i < count; i++)
+ uDlg->tabs[0]->job->closeAllTabs();
+ }
+ else
+ {
+ for (UINT i = 0; i < uDlg->tabs.size(); i++)
+ uDlg->tabs[i]->job->resume();
+ }
+
+ break;
+ }
+ case WMU_DESTROY:
+ {
+ DestroyWindow(hwndDlg);
+ break;
+ }
+ }
+
+ return FALSE;
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/dialog.h b/plugins/FTPFileYM/dialog.h
new file mode 100644
index 0000000000..1c1cd38ff8
--- /dev/null
+++ b/plugins/FTPFileYM/dialog.h
@@ -0,0 +1,84 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+#include "utils.h"
+
+#define WMU_DESTROY (WM_USER + 1)
+#define IDM_CUSTOM 41000
+
+class UploadDialog
+{
+ friend class GenericJob;
+ friend class UploadJob;
+ friend class PackerJob;
+
+private:
+ static UploadDialog *instance;
+ static Mutex mutexTabs;
+ static WNDPROC oldTabControlProc;
+ TCHAR stzToolTipText[1024];
+
+ UploadDialog();
+
+public:
+ class Tab
+ {
+ public:
+ GenericJob *job;
+
+ bool bOptCloseDlg;
+ bool bOptCopyLink;
+ bool bOptAutosend;
+ int iOptAutoDelete;
+
+ TCHAR stzSpeed[64];
+ TCHAR stzComplet[64];
+ TCHAR stzRemain[64];
+
+ Tab(GenericJob *Job);
+ ~Tab();
+
+ int index();
+ void select();
+ void labelCompleted();
+ };
+
+ HWND hwnd;
+ HWND hwndTabs;
+ int activeTab;
+
+ vector<Tab *> tabs;
+
+ ~UploadDialog();
+
+ static UploadDialog *getInstance()
+ {
+ if (!instance)
+ instance = new UploadDialog();
+ return instance;
+ };
+
+ void selectTab(int index);
+ void show();
+
+ static INT_PTR CALLBACK TabControlProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
+ static INT_PTR CALLBACK UploadDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+}; \ No newline at end of file
diff --git a/plugins/FTPFileYM/docs/ftpfile_licence.txt b/plugins/FTPFileYM/docs/ftpfile_licence.txt
new file mode 100644
index 0000000000..7f1161073d
--- /dev/null
+++ b/plugins/FTPFileYM/docs/ftpfile_licence.txt
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) 19yy <name of author>
+
+ 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.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) 19yy name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/plugins/FTPFileYM/docs/ftpfile_readme.txt b/plugins/FTPFileYM/docs/ftpfile_readme.txt
new file mode 100644
index 0000000000..971d3d18ab
--- /dev/null
+++ b/plugins/FTPFileYM/docs/ftpfile_readme.txt
@@ -0,0 +1,135 @@
+***********
+FTP File YM
+***********
+
+Description
+===========
+Plugin uploads files to the FTP server.
+
+Main features
+=============
+- FTPS (FTP+SSL) and SFTP (FTP via SSH) support
+- support for zipping files before upload
+- support for sending folders
+- tabs support in upload dialog
+- possibility to set 5 different FTP servers
+- simple file manager for deleting uploaded files from FTP
+- added Pause/Resume and Cancel buttons in upload dialog
+- customizable menu entries
+
+!!! Requirements !!!
+====================
+Libcurl.dll has to be in Miranda root folder.
+
+
+Changelog
+=========
+
+--- 0.4.0.3 ---
+* x64 portability changes
+! fixed multiple same files in file manager
+
+--- 0.4.0.2 ---
++ possibility to enter archive file name
++ check if file exists on server
+
+--- 0.4.0.1 ---
+! restored backward compatibility with Send Screenshot
+
+--- 0.4.0.0 ---
++ added zipping support
++ added support for sending folders
+* many other changes and improvements
+* plugin completely rewritted to C++
+
+--- 0.3.0.4 ---
+* redesigned buttons in file manager
+! fixed multiple same files in file manager
+! another fixes for SFTP
+
+--- 0.3.0.3 ---
++ added hidden option ('LocalIP', string format) for set IP address used in PORT command
+! fixed file deleting via SFTP
+! fixed upload dialog refreshing
+
+--- 0.3.0.2 ---
+! some FTP connection fixes
+
+--- 0.3.0.1 ---
+! fixed 100% CPU load in file manager
+! some other minor fixes
+
+--- 0.3.0.0 ---
++ implemented libcurl library
++ added FTPS (FTP+SSL) and SFTP (FTP via SSH) support
+
+--- 0.2.2.1 ---
++ auto deletion function can be adjusted in options menu in upload dialog
+! some fixes for file manager
+
+--- 0.2.2.0 ---
++ automatic deletion of file after defined time
++ added send button to tabsrmm button bar
++ added server info to upload dialog
+! fixed 'Command after upload' function
+
+--- 0.2.1.0 ---
++ simple file manager for deleting uploaded files from FTP
+
+--- 0.2.0.1 ---
++ ability to close tab by double click or middle button click
+* changed upload dialog layout
+! fixed selection of new tab after tab is closed
+
+--- 0.2.0.0 ---
+* plugin was completely rewritten
++ added tabs support
+
+--- 0.1.0.3 ---
+! disabled menu entries for non IM contacts
+
+--- 0.1.0.2 ---
+! fixed possible crash in options
+
+--- 0.1.0.1 ---
++ added options for better customize of contact menu items (original patch by jarvis)
++ added check of minimal Miranda version (0.7+)
+! fixed percentual indicator for large files
+
+--- 0.1.0.0 ---
++ first FL version
+
+--- 0.0.2.5 ---
++ option for remove national characters from filename
++ updater support
+* increased number of FTP servers to 5
+* visual changes in upload dialog
+! fixed 100% CPU load when upload process is paused
+! fixed compatibility with clist_classic and clist_mw
+! fixed compatibility with scriver and srmm
+
+--- 0.0.2.4 ---
++ added Cancel All and Stop/Resume buttons
++ restored service function for other plugins (sendSS) - see m_ftpfile.h
+! fixed some minor bugs
+
+--- 0.0.2.3 ---
++ added Ansi version
+! fixed crash on sending multiple files
+
+--- 0.0.2.2 ---
++ added possibility to set 3 different FTP server
++ full Unicode support
+* menu entry redesigned
+
+Symbols used in changelog: + = new / * = changed / ! = fixed
+
+
+Author
+======
+original plugin by Joel Jonsson (thx!)
+mod by yaho -> YM
+
+ICQ: 356344824
+email: yaho@miranda-easy.net
+www: www.miranda-easy.net \ No newline at end of file
diff --git a/plugins/FTPFileYM/docs/ftpfile_translate.txt b/plugins/FTPFileYM/docs/ftpfile_translate.txt
new file mode 100644
index 0000000000..ee987f182f
--- /dev/null
+++ b/plugins/FTPFileYM/docs/ftpfile_translate.txt
@@ -0,0 +1,103 @@
+;FTP File YM
+;=============
+
+;Main
+;------
+[FTP File]
+
+;Open file dialog
+;------------------
+[FTP File - Select files]
+
+;Error messages
+;----------------
+[FTP File Error]
+[Aborting file upload...]
+[Error occurred when opening local file.\nAborting file upload...]
+[Error occurred when initializing libcurl.\nAborting file upload...]
+[You have to fill FTP server setting before upload file.]
+[FTP error occurred.\n%s]
+
+;Upload dialog
+;---------------
+[Upload manager - %d file(s)]
+[Sending for:]
+[Upload info]
+[File:]
+[Speed:]
+[Completed:]
+[Remaining:]
+[Download url:]
+[Copy link to clipboard]
+[Options]
+[Close]
+[Automatically delete file after...]
+[Disabled]
+
+;File manager
+;---------------
+[FTP File manager]
+[Select all]
+[Deselect all]
+[Delete from FTP]
+[Delete from list]
+[Copy link]
+[Download file]
+
+;Dialogs
+;---------------
+[Enter file name]
+[File exists - %s]
+[File with the same name alredy exists on the server.]
+[How to procced?]
+[Rename]
+[Overwrite]
+[Copy URL]
+[Cancel]
+
+;Sounds
+;--------
+[File upload complete]
+[Upload canceled]
+
+;Icons
+;--------
+[Send file]
+[Clipboard]
+[FTP Server %d]
+
+;Options page - Accounts
+;-----------------------
+[Accounts]
+[FTP account]
+[Account name]
+[Default FTP server]
+[Protocol]
+[FTP (Standard)]
+[FTP+SSL (Explicit)]
+[FTP+SSL (Implicit)]
+[SFTP (Secure FTP ove SSH)]
+[Host name]
+[Port]
+[Use passive mode]
+[User]
+[Password]
+[Command after upload]
+[Directory on server]
+[URL]
+
+;Options page - Advanced
+;-----------------------
+[Advanced]
+[File download link]
+[Copy download link to message log]
+[Autosend download link to contact]
+[Menu items]
+[Use submenu (restart required)]
+[Hide inactive accounts]
+[Other]
+[ZIP support]
+[Enter archive name manually]
+[Compression level:]
+[Close dialog after upload finishes]
+[Automatically delete file from FTP server after (experimental):]
diff --git a/plugins/FTPFileYM/ftpfile.cpp b/plugins/FTPFileYM/ftpfile.cpp
new file mode 100644
index 0000000000..0bcac128cb
--- /dev/null
+++ b/plugins/FTPFileYM/ftpfile.cpp
@@ -0,0 +1,634 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "common.h"
+#include "deletetimer.h"
+#include "dbentry.h"
+#include "dialog.h"
+#include "libcurl.h"
+#include "manager.h"
+#include "options.h"
+#include "job_delete.h"
+#include "job_packer.h"
+#include "job_upload.h"
+#include "version.h"
+
+HINSTANCE hInst;
+PLUGINLINK *pluginLink;
+MM_INTERFACE mmi = {0};
+
+HANDLE hModulesLoaded, hEventPreShutdown, hOptionsInit, hPrebuildContactMenu, hTabsrmmButtonPressed;
+HANDLE hServiceUpload, hServiceShowManager, hServiceContactMenu, hServiceMainMenu, hServiceShareFile;
+HGENMENU hMenu, hMainMenu, hSubMenu[ServerList::FTP_COUNT], hMainSubMenu[ServerList::FTP_COUNT];
+
+extern UploadDialog *uDlg;
+extern Manager *manDlg;
+
+extern DeleteTimer &deleteTimer;
+extern ServerList &ftpList;
+extern Options &opt;
+extern LibCurl &curl;
+
+BOOL (WINAPI *MyEnableThemeDialogTexture)(HANDLE, DWORD) = 0;
+int PrebuildContactMenu(WPARAM wParam, LPARAM lParam);
+void PrebuildMainMenu();
+int TabsrmmButtonPressed(WPARAM wParam, LPARAM lParam);
+int UploadFile(HANDLE hContact, int iFtpNum, UploadJob::EMode mode);
+
+static PLUGININFOEX pluginInfoEx =
+{
+ sizeof(PLUGININFOEX),
+#ifdef _WIN64
+ "FTP File YM x64",
+#else
+ "FTP File YM",
+#endif
+ __VERSION_DWORD,
+ "FTP a file to a server and send the URL to your friend. Supported automatic zipping before upload and encryption via SFTP and FTPS.",
+ "yaho",
+ "yaho@miranda-easy.net",
+ "Copyright � 2007-2010 Jan Holub",
+ "http://miranda-easy.net/mods.php",
+ UNICODE_AWARE,
+ 0,
+ MIID_FTPFILE
+};
+
+//------------ BASIC STAFF ------------//
+
+extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
+{
+ hInst = hinstDLL;
+ return TRUE;
+}
+
+extern "C" __declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
+{
+ if (mirandaVersion < PLUGIN_MAKE_VERSION(0, 8, 0, 0))
+ return NULL;
+
+ return &pluginInfoEx;
+}
+
+static const MUUID interfaces[] = {MIID_FTPFILE, MIID_LAST};
+extern "C" __declspec(dllexport) const MUUID* MirandaPluginInterfaces(void)
+{
+ return interfaces;
+}
+
+//------------ INIT FUNCTIONS ------------//
+
+struct _tag_iconList
+{
+ char *szDescr;
+ char *szName;
+ int defIconID;
+}
+static const iconList[6] =
+{
+ { "Send file", "main", IDI_MENU },
+ { "Clipboard", "clipboard", IDI_CLIPBOARD },
+ { "Pause", "pause", IDI_PAUSE },
+ { "Resume", "resume", IDI_RESUME },
+ { "Delete from list", "clear", IDI_CLEAR },
+ { "Delete from FTP", "delete", IDI_DELETE }
+};
+
+static HANDLE hIconlibItem[ServerList::FTP_COUNT + SIZEOF(iconList)];
+
+static void InitIcolib()
+{
+ TCHAR stzFile[MAX_PATH];
+ char szSettingName[100];
+ char szDesc[100];
+
+ SKINICONDESC sid = {0};
+ sid.cbSize = sizeof(sid);
+ sid.cx = sid.cy = 16;
+ sid.ptszDefaultFile = stzFile;
+ sid.pszSection = MODULE;
+ sid.pszDescription = szDesc;
+ sid.pszName = szSettingName;
+ sid.flags = SIDF_PATH_TCHAR;
+
+ GetModuleFileName(hInst, stzFile, MAX_PATH);
+
+ for (int i = 0; i < ServerList::FTP_COUNT; i++)
+ {
+ mir_snprintf(szDesc, sizeof(szDesc), Translate("FTP Server %d"), i + 1);
+ mir_snprintf(szSettingName, sizeof(szSettingName), "%s_ftp%d", MODULE, i);
+ sid.iDefaultIndex = -(IDI_FTP0 + i);
+ hIconlibItem[i] = (HANDLE)CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
+ }
+
+ for (int i = 0; i < SIZEOF(iconList); i++)
+ {
+ mir_snprintf(szSettingName, sizeof(szSettingName), "%s_%s", MODULE, iconList[i].szName);
+ sid.pszDescription = Translate(iconList[i].szDescr);
+ sid.iDefaultIndex = -(iconList[i].defIconID);
+ hIconlibItem[i + ServerList::FTP_COUNT] = (HANDLE)CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
+ }
+}
+
+void InitMenuItems()
+{
+ CLISTMENUITEM mi = {0};
+ CLISTMENUITEM mi2 = {0};
+ TCHAR stzName[256];
+
+ mi.cbSize = sizeof(mi);
+ mi.flags = CMIF_ROOTPOPUP | CMIF_ICONFROMICOLIB | CMIF_TCHAR;
+ mi.icolibItem = hIconlibItem[ServerList::FTP_COUNT];
+ mi.position = 3000090001;
+ mi.ptszName = LPGENT("FTP File");
+
+ hMainMenu = (HGENMENU)CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM)&mi);
+ if (opt.bUseSubmenu) hMenu = (HGENMENU)CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&mi);
+
+ memset(&mi, 0, sizeof(mi));
+ mi.cbSize = sizeof(mi);
+ mi.ptszName = stzName;
+
+ mi2.cbSize = sizeof(mi2);
+ mi2.flags = CMIF_CHILDPOPUP | CMIF_ROOTHANDLE | CMIF_TCHAR;
+ mi2.pszService = MS_FTPFILE_CONTACTMENU;
+
+ for (int i = 0; i < ServerList::FTP_COUNT; i++)
+ {
+ if (DB::getStringF(0, MODULE, "Name%d", i, stzName))
+ mir_sntprintf(stzName, SIZEOF(stzName), TranslateT("FTP Server %d"), i + 1);
+
+ mi.flags = CMIF_ICONFROMICOLIB | CMIF_TCHAR;
+ mi.hParentMenu = 0;
+ if (opt.bUseSubmenu)
+ {
+ mi.flags |= CMIF_CHILDPOPUP | CMIF_ROOTHANDLE;
+ mi.hParentMenu = hMenu;
+ }
+
+ mi.icolibItem = hIconlibItem[i];
+ mi.popupPosition = i + 1000;
+ hSubMenu[i] = (HGENMENU)CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&mi);
+
+ mi.flags |= CMIF_CHILDPOPUP | CMIF_ROOTHANDLE;
+ mi.hParentMenu = hMainMenu;
+ hMainSubMenu[i] = (HGENMENU)CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM)&mi);
+
+ mi2.hParentMenu = hSubMenu[i];
+ mi2.pszService = MS_FTPFILE_CONTACTMENU;
+ mi2.popupPosition = mi2.position = i + UploadJob::FTP_RAWFILE;
+ mi2.ptszName = TranslateT("Upload file(s)");
+ CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&mi2);
+
+ mi2.pszService = MS_FTPFILE_MAINMENU;
+ mi2.hParentMenu = hMainSubMenu[i];
+ CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM)&mi2);
+
+ mi2.hParentMenu = hSubMenu[i];
+ mi2.pszService = MS_FTPFILE_CONTACTMENU;
+ mi2.popupPosition = i + UploadJob::FTP_ZIPFILE;
+ mi2.ptszName = TranslateT("Zip and upload file(s)");
+ CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&mi2);
+
+ mi2.pszService = MS_FTPFILE_MAINMENU;
+ mi2.hParentMenu = hMainSubMenu[i];
+ CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM)&mi2);
+
+ mi2.hParentMenu = hSubMenu[i];
+ mi2.pszService = MS_FTPFILE_CONTACTMENU;
+ mi2.popupPosition = i + UploadJob::FTP_ZIPFOLDER;
+ mi2.ptszName = TranslateT("Zip and upload folder");
+ CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&mi2);
+
+ mi2.pszService = MS_FTPFILE_MAINMENU;
+ mi2.hParentMenu = hMainSubMenu[i];
+ CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM)&mi2);
+ }
+
+ memset(&mi, 0, sizeof(mi));
+ mi.cbSize = sizeof(mi);
+ mi.flags = CMIF_ICONFROMICOLIB | CMIF_CHILDPOPUP | CMIF_ROOTHANDLE | CMIF_TCHAR;
+ mi.icolibItem = hIconlibItem[ServerList::FTP_COUNT];
+ mi.position = 3000090001;
+ mi.ptszName = LPGENT("FTP File manager");
+ mi.pszService = MS_FTPFILE_SHOWMANAGER;
+ mi.hParentMenu = hMainMenu;
+ CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM)&mi);
+
+ PrebuildMainMenu();
+
+ hPrebuildContactMenu = HookEvent(ME_CLIST_PREBUILDCONTACTMENU, PrebuildContactMenu);
+}
+
+void InitHotkeys()
+{
+ HOTKEYDESC hk = {0};
+ hk.cbSize = sizeof(hk);
+ hk.pszDescription = LPGEN("Show FTPFile manager");
+ hk.pszName = LPGEN("FTP_ShowManager");
+ hk.pszSection = MODULE;
+ hk.pszService = MS_FTPFILE_SHOWMANAGER;
+ CallService(MS_HOTKEY_REGISTER, 0, (LPARAM)&hk);
+}
+
+void InitUpdater()
+{
+#ifndef _WIN64
+ if (ServiceExists(MS_UPDATE_REGISTER))
+ {
+ Update update = {0};
+ char szVersion[16];
+ update.cbSize = sizeof(Update);
+ update.szComponentName = pluginInfoEx.shortName;
+ update.pbVersion = (BYTE *)CreateVersionString(pluginInfoEx.version, szVersion);
+ update.cpbVersion = (int)strlen((char *)update.pbVersion);
+
+#ifdef _UNICODE
+ update.szUpdateURL = "http://miranda-easy.net/addons/updater/ftpfile-ym.zip";
+#else
+ update.szUpdateURL = "http://miranda-easy.net/addons/updater/ftpfile-ym_ansi.zip";
+#endif
+ update.szVersionURL = "http://miranda-easy.net/addons/updater/ftpfile_version.txt";
+ update.pbVersionPrefix = (BYTE *)"FTP File YM ";
+ update.cpbVersionPrefix = (int)strlen((char *)update.pbVersionPrefix);
+ CallService(MS_UPDATE_REGISTER, 0, (WPARAM)&update);
+ }
+#endif
+}
+
+void InitTabsrmmButton()
+{
+ if (ServiceExists(MS_BB_ADDBUTTON))
+ {
+ BBButton btn = {0};
+ btn.cbSize = sizeof(btn);
+ btn.dwButtonID = 1;
+ btn.pszModuleName = MODULE;
+ btn.dwDefPos = 105;
+ btn.hIcon = hIconlibItem[ServerList::FTP_COUNT];
+ btn.bbbFlags = BBBF_ISARROWBUTTON | BBBF_ISIMBUTTON | BBBF_ISLSIDEBUTTON | BBBF_CANBEHIDDEN;
+ btn.ptszTooltip = TranslateT("FTP File");
+ CallService(MS_BB_ADDBUTTON, 0, (LPARAM)&btn);
+ hTabsrmmButtonPressed = HookEvent(ME_MSG_BUTTONPRESSED, TabsrmmButtonPressed);
+ }
+}
+
+//------------ MENU & BUTTON HANDLERS ------------//
+
+int PrebuildContactMenu(WPARAM wParam, LPARAM lParam)
+{
+ bool bIsContact = false;
+
+ char *szProto = DB::getProto((HANDLE)wParam);
+ if (szProto) bIsContact = (CallProtoService(szProto, PS_GETCAPS, PFLAGNUM_1, 0) & PF1_IM) ? true : false;
+
+ bool bHideRoot = opt.bHideInactive;
+ for (int i = 0; i < ServerList::FTP_COUNT; i++)
+ {
+ if (ftpList[i]->bEnabled)
+ bHideRoot = false;
+ }
+
+ CLISTMENUITEM mi = {0};
+ mi.cbSize = sizeof(mi);
+ mi.flags = CMIM_FLAGS;
+
+ if (opt.bUseSubmenu)
+ {
+ if (!bIsContact || bHideRoot) mi.flags |= CMIF_HIDDEN;
+ else mi.flags &= ~CMIF_HIDDEN;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM)hMenu, (LPARAM)&mi);
+ }
+
+ for (int i = 0; i < ServerList::FTP_COUNT; i++)
+ {
+ mi.flags = CMIM_FLAGS;
+ if (!bIsContact)
+ {
+ mi.flags |= CMIF_HIDDEN;
+ }
+ else if (!ftpList[i]->bEnabled)
+ {
+ mi.flags |= opt.bHideInactive ? CMIF_HIDDEN : CMIF_GRAYED;
+ }
+
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM)hSubMenu[i], (LPARAM)&mi);
+ }
+
+ return 0;
+}
+
+void PrebuildMainMenu()
+{
+ CLISTMENUITEM mi = {0};
+ mi.cbSize = sizeof(mi);
+
+ for (int i = 0; i < ServerList::FTP_COUNT; i++)
+ {
+ mi.flags = CMIM_FLAGS;
+ if (!ftpList[i]->bEnabled)
+ mi.flags |= opt.bHideInactive ? CMIF_HIDDEN : CMIF_GRAYED;
+
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM)hMainSubMenu[i], (LPARAM)&mi);
+ }
+}
+
+int TabsrmmButtonPressed(WPARAM wParam, LPARAM lParam)
+{
+ CustomButtonClickData *cbc = (CustomButtonClickData *)lParam;
+ HANDLE hContact = (HANDLE)wParam;
+
+ if (!strcmp(cbc->pszModule, MODULE) && cbc->dwButtonId == 1 && hContact)
+ {
+ if (cbc->flags == BBCF_ARROWCLICKED)
+ {
+ HMENU hMenu = CreatePopupMenu();
+ if (hMenu)
+ {
+ int iCount = 0;
+ for (UINT i = 0; i < ServerList::FTP_COUNT; i++)
+ {
+ if (ftpList[i]->bEnabled)
+ {
+ HMENU hModeMenu = CreatePopupMenu();
+ AppendMenu(hModeMenu, MF_STRING, i + UploadJob::FTP_RAWFILE, TranslateT("Upload file"));
+ AppendMenu(hModeMenu, MF_STRING, i + UploadJob::FTP_ZIPFILE, TranslateT("Zip and upload file"));
+ AppendMenu(hModeMenu, MF_STRING, i + UploadJob::FTP_ZIPFOLDER, TranslateT("Zip and upload folder"));
+ AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT_PTR)hModeMenu, ftpList[i]->stzName);
+ DestroyMenu(hModeMenu);
+ iCount++;
+ }
+ }
+
+ if (iCount != 0)
+ {
+ POINT pt;
+ GetCursorPos(&pt);
+ HWND hwndBtn = WindowFromPoint(pt);
+ if (hwndBtn)
+ {
+ RECT rc;
+ GetWindowRect(hwndBtn, &rc);
+ SetForegroundWindow(cbc->hwndFrom);
+ int selected = TrackPopupMenu(hMenu, TPM_RETURNCMD, rc.left, rc.bottom, 0, cbc->hwndFrom, 0);
+ if (selected != 0)
+ {
+ int ftpNum = selected & (1|2|4);
+ int mode = selected & (UploadJob::FTP_RAWFILE | UploadJob::FTP_ZIPFILE | UploadJob::FTP_ZIPFOLDER);
+ UploadFile(hContact, ftpNum, (UploadJob::EMode)mode);
+ }
+ }
+ }
+
+ DestroyMenu(hMenu);
+ }
+ }
+ else
+ {
+ UploadFile(hContact, 0, UploadJob::FTP_RAWFILE);
+ }
+ }
+
+ return 0;
+}
+
+int UploadFile(HANDLE hContact, int iFtpNum, GenericJob::EMode mode, void **objects, int objCount, DWORD flags)
+{
+ if (!ftpList[iFtpNum]->isValid())
+ {
+ Utils::msgBox(TranslateT("You have to fill FTP server setting before upload a file."), MB_OK | MB_ICONERROR);
+ return 1;
+ }
+
+ GenericJob *job;
+ if (mode == GenericJob::FTP_RAWFILE)
+ job = new UploadJob(hContact, iFtpNum, mode);
+ else
+ job = new PackerJob(hContact, iFtpNum, mode);
+
+ int result;
+ if (objects != NULL)
+ result = job->getFiles(objects, objCount, flags);
+ else
+ result = job->getFiles();
+
+ if (result != 0)
+ {
+ uDlg = UploadDialog::getInstance();
+ if (!uDlg->hwnd || !uDlg->hwndTabs)
+ {
+ Utils::msgBox(TranslateT("Error has occurred while trying to create a dialog!"), MB_OK | MB_ICONERROR);
+ delete uDlg;
+ return 1;
+ }
+
+ job->addToUploadDlg();
+ uDlg->show();
+ }
+ else
+ {
+ delete job;
+ return 1;
+ }
+
+ return 0;
+}
+
+int UploadFile(HANDLE hContact, int iFtpNum, GenericJob::EMode mode)
+{
+ return UploadFile(hContact, iFtpNum, mode, NULL, 0, 0);
+}
+
+//------------ MIRANDA SERVICES ------------//
+
+INT_PTR UploadService(WPARAM wParam, LPARAM lParam)
+{
+ FTPUPLOAD* ftpu = (FTPUPLOAD *)lParam;
+ if (ftpu == NULL || ftpu->cbSize != sizeof(FTPUPLOAD))
+ return 1;
+
+ int ftpNum = (ftpu->ftpNum == FNUM_DEFAULT) ? opt.defaultFTP : ftpu->ftpNum - 1;
+ int mode = (ftpu->mode * GenericJob::FTP_RAWFILE);
+
+ UploadFile(ftpu->hContact, ftpNum, (GenericJob::EMode)mode, (void**)ftpu->pstzObjects, ftpu->objectCount, ftpu->flags);
+ return 0;
+}
+
+INT_PTR ShareFileService(WPARAM wParam, LPARAM lParam)
+{
+ if (!wParam || !lParam)
+ return 1;
+
+ FTPUPLOAD ftpu = {0};
+ ftpu.cbSize = sizeof(ftpu);
+ ftpu.ftpNum = FNUM_DEFAULT;
+ ftpu.mode = FMODE_RAWFILE;
+ ftpu.hContact = (HANDLE)wParam;
+
+ char *szFile = (char *)mir_alloc(1024 * sizeof(char));
+ ZeroMemory(szFile, 1024);
+ strcpy(szFile, (char *)lParam);
+
+ char *ptr, buff[256];
+ if (szFile[strlen(szFile) + 1])
+ {
+ ptr = szFile + strlen(szFile) + 1;
+ while (ptr[0])
+ {
+ ftpu.pszObjects = (char **)mir_realloc(ftpu.pszObjects, (ftpu.objectCount + 1) * sizeof(char *));
+ mir_snprintf(buff, MAX_PATH, "%s\\%s", szFile, ptr);
+ ftpu.pszObjects[ftpu.objectCount++] = mir_strdup(buff);
+ ptr += strlen(ptr) + 1;
+ }
+ }
+ else
+ {
+ ftpu.pszObjects = (char **)mir_alloc(sizeof(char *));
+ ftpu.pszObjects[0] = mir_strdup(szFile);
+ ftpu.objectCount = 1;
+ }
+
+ CallService(MS_FTPFILE_UPLOAD, 0, (LPARAM)&ftpu);
+
+ for (int i = 0; i < ftpu.objectCount; i++)
+ FREE(ftpu.pszObjects[i]);
+
+ FREE(ftpu.pszObjects);
+ FREE(szFile);
+
+ return 0;
+}
+
+INT_PTR ShowManagerService(WPARAM wParam, LPARAM lParam)
+{
+ manDlg = Manager::getInstance();
+ manDlg->init();
+ return 0;
+}
+
+INT_PTR ContactMenuService(WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact = (HANDLE)wParam;
+ int ftpNum = lParam & (1|2|4);
+ int mode = lParam & (UploadJob::FTP_RAWFILE | UploadJob::FTP_ZIPFILE | UploadJob::FTP_ZIPFOLDER);
+ return UploadFile(hContact, ftpNum, (UploadJob::EMode)mode);
+}
+
+INT_PTR MainMenuService(WPARAM wParam, LPARAM lParam)
+{
+ int ftpNum = wParam & (1|2|4);
+ int mode = wParam & (UploadJob::FTP_RAWFILE | UploadJob::FTP_ZIPFILE | UploadJob::FTP_ZIPFOLDER);
+ return UploadFile(0, ftpNum, (UploadJob::EMode)mode);
+}
+
+//------------ START & EXIT STUFF ------------//
+
+int ModulesLoaded(WPARAM wParam, LPARAM lParam)
+{
+ InitIcolib();
+ InitMenuItems();
+ InitHotkeys();
+ InitUpdater();
+ InitTabsrmmButton();
+
+ SkinAddNewSoundEx(SOUND_UPCOMPLETE, Translate("FTP File"), Translate("File upload complete"));
+ SkinAddNewSoundEx(SOUND_CANCEL, Translate("FTP File"), Translate("Upload canceled"));
+
+ curl.global_init(CURL_GLOBAL_ALL);
+
+ return 0;
+}
+
+int Shutdown(WPARAM wParam, LPARAM lParam)
+{
+ deleteTimer.deinit();
+
+ if (manDlg) delete manDlg;
+ if (uDlg) SendMessage(uDlg->hwnd, WM_CLOSE, 0, 0);
+
+ UploadJob::jobDone.release();
+ DeleteJob::jobDone.release();
+ DBEntry::cleanupDB();
+
+ curl.global_cleanup();
+
+ ftpList.deinit();
+ opt.deinit();
+ curl.deinit();
+
+ return 0;
+}
+
+extern "C" int __declspec(dllexport) Load(PLUGINLINK *link)
+{
+ pluginLink = link;
+
+ if (!curl.init())
+ {
+ Utils::msgBox(TranslateT("FTP File YM won't be loaded because libcurl.dll is missing or wrong version!"), MB_OK | MB_ICONERROR);
+ return 1;
+ }
+
+#ifdef _DEBUG
+ _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
+#endif
+
+ mir_getMMI(&mmi);
+
+ CoInitialize(NULL);
+
+ hModulesLoaded = HookEvent(ME_SYSTEM_MODULESLOADED, ModulesLoaded);
+ hEventPreShutdown = HookEvent(ME_SYSTEM_PRESHUTDOWN, Shutdown);
+ hOptionsInit = HookEvent(ME_OPT_INITIALISE, Options::InitOptions);
+
+ hServiceUpload = CreateServiceFunction(MS_FTPFILE_UPLOAD, UploadService);
+ hServiceShowManager = CreateServiceFunction(MS_FTPFILE_SHOWMANAGER, ShowManagerService);
+ hServiceContactMenu = CreateServiceFunction(MS_FTPFILE_CONTACTMENU, ContactMenuService);
+ hServiceMainMenu = CreateServiceFunction(MS_FTPFILE_MAINMENU, MainMenuService);
+ hServiceShareFile = CreateServiceFunction(MS_FTPFILE_SHAREFILE, ShareFileService);
+
+ if (IsWinVerXPPlus())
+ {
+ HMODULE hUxTheme = GetModuleHandle(_T("uxtheme.dll"));
+ if (hUxTheme)
+ MyEnableThemeDialogTexture = (BOOL (WINAPI *)(HANDLE, DWORD))GetProcAddress(hUxTheme, "EnableThemeDialogTexture");
+ }
+
+ opt.loadOptions();
+ deleteTimer.init();
+ ftpList.init();
+
+ return 0;
+}
+
+extern "C" int __declspec(dllexport) Unload(void)
+{
+ UnhookEvent(hModulesLoaded);
+ UnhookEvent(hEventPreShutdown);
+ UnhookEvent(hOptionsInit);
+ UnhookEvent(hPrebuildContactMenu);
+ UnhookEvent(hTabsrmmButtonPressed);
+
+ DestroyServiceFunction(hServiceUpload);
+ DestroyServiceFunction(hServiceShowManager);
+ DestroyServiceFunction(hServiceContactMenu);
+ DestroyServiceFunction(hServiceMainMenu);
+ DestroyServiceFunction(hServiceShareFile);
+
+ return 0;
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/ftpfile.rc b/plugins/FTPFileYM/ftpfile.rc
new file mode 100644
index 0000000000..c1cd9e3a96
--- /dev/null
+++ b/plugins/FTPFileYM/ftpfile.rc
@@ -0,0 +1,317 @@
+// Microsoft Visual C++ generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "afxres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// Neutral resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU)
+#ifdef _WIN32
+LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
+#pragma code_page(1250)
+#endif //_WIN32
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_OPT_FTPFILE DIALOGEX 0, 0, 268, 230
+STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ GROUPBOX "FTP account",IDC_STATIC,7,5,254,220
+ RTEXT "Host name",IDC_STATIC,14,70,89,8
+ RTEXT "User",IDC_STATIC,14,129,89,8
+ RTEXT "Password",IDC_STATIC,14,148,89,8
+ RTEXT "URL",IDC_STATIC,14,207,89,8
+ RTEXT "Directory on server",IDC_STATIC,14,189,89,8
+ EDITTEXT IDC_SERVER,109,68,140,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_USER,109,127,140,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_PASSWORD,109,146,140,12,ES_PASSWORD | ES_AUTOHSCROLL
+ EDITTEXT IDC_DIR,109,186,140,12,ES_AUTOHSCROLL
+ EDITTEXT IDC_URL,109,205,140,12,ES_AUTOHSCROLL
+ RTEXT "Port",IDC_STATIC,14,88,89,8
+ EDITTEXT IDC_PORT,109,86,140,12,ES_AUTOHSCROLL | ES_NUMBER
+ RTEXT "Command after upload",IDC_STATIC,14,172,89,8
+ EDITTEXT IDC_CHMOD,109,170,140,12,ES_AUTOHSCROLL
+ CONTROL "Use passive mode",IDC_PASSIVE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,110,104,142,10
+ COMBOBOX IDC_FTPLIST,109,16,125,28,CBS_DROPDOWN | CBS_AUTOHSCROLL | WS_VSCROLL | WS_TABSTOP
+ RTEXT "Account name",IDC_STATIC,14,18,89,8,0,WS_EX_RIGHT
+ CONTROL "",IDC_ENABLED,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,241,18,11,10
+ COMBOBOX IDC_PROTOLIST,109,50,125,30,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
+ RTEXT "Protocol",IDC_STATIC,14,53,89,8
+ CONTROL "Default FTP server",IDC_DEFAULT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,109,33,140,10
+END
+
+IDD_OPT_ADVANCED DIALOGEX 0, 0, 265, 225
+STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ GROUPBOX "File download link",IDC_STATIC,5,12,254,42
+ CONTROL "Close dialog after upload is completed",IDC_CLOSEDLG,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,163,236,10
+ CONTROL "Copy download link to message log",IDC_URL_COPYTOML,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,38,236,10
+ CONTROL "Autosend download link to contact",IDC_URL_AUTOSEND,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,24,236,10
+ GROUPBOX "Menu items",IDC_STATIC,5,58,254,42
+ CONTROL "Use submenu (restart required)",IDC_USESUBMENU,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,69,236,10
+ CONTROL "Hide inactive accounts",IDC_HIDEINACTIVE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,84,236,10
+ GROUPBOX "Other",IDC_STATIC,5,152,254,60
+ CONTROL "Automatically delete file from FTP server after (experimental):",IDC_AUTODELETE,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,177,237,10
+ EDITTEXT IDC_DELETETIME,27,192,38,12,ES_AUTOHSCROLL | ES_NUMBER
+ CONTROL "",IDC_DELETETIME_SPIN,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS,57,187,11,14
+ COMBOBOX IDC_RANGE,71,192,75,30,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
+ GROUPBOX "ZIP support",IDC_STATIC,5,104,254,44
+ CONTROL "Enter archive name manually",IDC_SETZIPNAME,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,13,115,240,10
+ LTEXT "Compression level:",IDC_STATIC,24,131,82,8
+ EDITTEXT IDC_LEVEL,108,130,38,12,ES_AUTOHSCROLL | ES_NUMBER
+ CONTROL "",IDC_LEVEL_SPIN,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS,135,125,11,14
+END
+
+IDD_DLG_UPLOAD DIALOGEX 0, 0, 285, 148
+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Upload File Manager"
+FONT 8, "Tahoma", 400, 0, 0xEE
+BEGIN
+ CONTROL "",IDC_TAB,"SysTabControl32",TCS_TOOLTIPS | WS_TABSTOP,3,3,279,142
+ LTEXT "",IDC_STATIC,3,134,277,10,SS_SUNKEN
+ LTEXT "File:",IDC_ST_FILE,21,46,55,8
+ LTEXT "Completed:",IDC_ST_COMPLETED,21,85,55,8
+ LTEXT "Speed:",IDC_ST_SPEED,21,72,55,8
+ LTEXT "Remaining:",IDC_ST_REMAIN,21,98,55,8
+ GROUPBOX "Summary",IDC_STATIC,11,35,260,79
+ LTEXT "",IDC_UP_FILE,84,46,180,8
+ CONTROL "",IDC_PB_UPLOAD,"msctls_progress32",PBS_SMOOTH | WS_BORDER,11,119,236,10
+ LTEXT "",IDC_UP_SPEED,84,72,180,8
+ LTEXT "",IDC_UP_COMPLETED,84,85,180,8
+ LTEXT "To:",IDC_ST_CONTACT,17,22,19,8
+ LTEXT "Nick",IDC_UP_CONTACT,55,18,158,17,SS_CENTERIMAGE
+ LTEXT "",IDC_UP_REMAIN,84,98,180,8
+ CONTROL "Close",IDC_BTN_CLOSE,"MButtonClass",WS_TABSTOP,253,20,16,14
+ CONTROL "Clipboard",IDC_BTN_CLIPBOARD,"MButtonClass",NOT WS_VISIBLE | WS_TABSTOP,251,96,16,14
+ EDITTEXT IDC_ED_URL,20,97,210,12,ES_AUTOHSCROLL | ES_READONLY | NOT WS_VISIBLE
+ CONTROL "Options",IDC_BTN_OPTIONS,"MButtonClass",WS_TABSTOP,237,20,16,14
+ CONTROL "Pause",IDC_BTN_PAUSE,"MButtonClass",WS_TABSTOP,253,117,16,14
+ CONTROL "File Manager",IDC_BTN_FILEMANAGER,"MButtonClass",WS_TABSTOP,221,20,16,14
+ LTEXT "Server:",IDC_ST_SERVER,21,59,55,8
+ LTEXT "",IDC_UP_SERVER,84,59,180,8
+ CONTROL "User info",IDC_BTN_PROTO,"MButtonClass",WS_TABSTOP,38,20,16,14
+ LTEXT "UPLOADING...",IDC_STATUSBAR,11,135,267,8
+ CONTROL "Open in Browser",IDC_BTN_DOWNLOAD,"MButtonClass",NOT WS_VISIBLE | WS_TABSTOP,235,96,16,14
+END
+
+IDD_DLG_MANAGER DIALOGEX 0, 0, 214, 215
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "FTP File Manager"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ CONTROL "",IDC_FILELIST,"SysTreeView32",TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT | TVS_DISABLEDRAGDROP | TVS_INFOTIP | WS_BORDER | WS_HSCROLL | WS_TABSTOP,6,6,201,189
+ CONTROL "Select All",IDC_BTN_SELECTALL,"MButtonClass",WS_TABSTOP,6,198,16,14
+ CONTROL "Deselect All",IDC_BTN_DESELECTALL,"MButtonClass",WS_TABSTOP,22,198,16,14
+ CONTROL "Delete from list",IDC_BTN_DELETEFROMLIST,"MButtonClass",WS_TABSTOP,44,198,16,14
+ CONTROL "Delete from FTP",IDC_BTN_DELETE,"MButtonClass",WS_TABSTOP,60,198,16,14
+ CONTROL "Close",IDC_BTN_CLOSE,"MButtonClass",WS_TABSTOP,191,198,16,14
+END
+
+IDD_DLG_NAME DIALOGEX 0, 0, 165, 52
+STYLE DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Enter file name"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ PUSHBUTTON "OK",IDOK,24,31,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,90,31,50,14
+ EDITTEXT IDC_NAME,7,8,151,14,ES_AUTOHSCROLL
+END
+
+IDD_DLG_FILEEXISTS DIALOGEX 0, 0, 220, 76
+STYLE DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION
+CAPTION "File exists"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ DEFPUSHBUTTON "Rename",IDC_RENAME,35,38,65,14
+ PUSHBUTTON "Overwrite",IDC_OVERWRITE,119,38,65,14
+ CTEXT "File with the same name already exists on the server.",IDC_HEADER,4,9,211,8
+ CTEXT "How to proceed?",IDC_STATIC,4,20,211,8
+ PUSHBUTTON "Cancel",IDC_CANCEL,119,56,65,14
+ PUSHBUTTON "Copy URL",IDC_COPYURL,35,56,65,14
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO
+BEGIN
+ IDD_OPT_FTPFILE, DIALOG
+ BEGIN
+ BOTTOMMARGIN, 223
+ END
+
+ IDD_OPT_ADVANCED, DIALOG
+ BEGIN
+ BOTTOMMARGIN, 212
+ END
+
+ IDD_DLG_UPLOAD, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 278
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 141
+ END
+
+ IDD_DLG_MANAGER, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 207
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 194
+ END
+
+ IDD_DLG_NAME, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 158
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 45
+ END
+
+ IDD_DLG_FILEEXISTS, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 213
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 69
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Menu
+//
+
+IDR_MENU_UPLOAD MENU
+BEGIN
+ POPUP ""
+ BEGIN
+ MENUITEM "Autosend download link to contact", IDM_AUTOSEND
+ MENUITEM "Copy download link to message log", IDM_COPYLINK
+ MENUITEM "Close dialog after upload finishes", IDM_CLOSEDLG
+ POPUP "Automatically delete file after..."
+ BEGIN
+ MENUITEM "Disabled", IDM_DISABLED
+ MENUITEM SEPARATOR
+ END
+ END
+END
+
+IDR_MENU_MANAGER MENU
+BEGIN
+ POPUP ""
+ BEGIN
+ MENUITEM "Delete from List", IDM_DELETEFROMLIST
+ MENUITEM "Delete from FTP", IDM_DELETEFROMFTP
+ MENUITEM SEPARATOR
+ MENUITEM "Copy Link", IDM_COPYLINK
+ MENUITEM "Open in Browser", IDM_DOWNLOAD
+ END
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_PAUSE ICON "icons\\pause.ico"
+IDI_FTP0 ICON "icons\\ftp0.ico"
+IDI_FTP1 ICON "icons\\ftp1.ico"
+IDI_FTP2 ICON "icons\\ftp2.ico"
+IDI_FTP3 ICON "icons\\ftp3.ico"
+IDI_FTP4 ICON "icons\\ftp4.ico"
+IDI_MENU ICON "icons\\menu.ico"
+IDI_CLIPBOARD ICON "icons\\clipboard.ico"
+IDI_RESUME ICON "icons\\resume.ico"
+#endif // Neutral resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+/////////////////////////////////////////////////////////////////////////////
+// Czech resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CSY)
+#ifdef _WIN32
+LANGUAGE LANG_CZECH, SUBLANG_DEFAULT
+#pragma code_page(1250)
+#endif //_WIN32
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_CLEAR ICON "icons\\clear.ico"
+IDI_DELETE ICON "icons\\delete.ico"
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+#endif // Czech resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/plugins/FTPFileYM/ftpfile_10.vcxproj b/plugins/FTPFileYM/ftpfile_10.vcxproj
new file mode 100644
index 0000000000..b50cdd5535
--- /dev/null
+++ b/plugins/FTPFileYM/ftpfile_10.vcxproj
@@ -0,0 +1,435 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug Unicode|Win32">
+ <Configuration>Debug Unicode</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug Unicode|x64">
+ <Configuration>Debug Unicode</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug|x64">
+ <Configuration>Debug</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Unicode|Win32">
+ <Configuration>Release Unicode</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Unicode|x64">
+ <Configuration>Release Unicode</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|x64">
+ <Configuration>Release</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectName>ftpfile</ProjectName>
+ <ProjectGuid>{73482497-9F57-4819-A9AB-5D841A9F072D}</ProjectGuid>
+ <RootNamespace>ftpfile</RootNamespace>
+ <Keyword>Win32Proj</Keyword>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>MultiByte</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>MultiByte</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup>
+ <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(Configuration)\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)64\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(Configuration)64\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(Configuration)\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)64\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(Configuration)64\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">$(Configuration)\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">false</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">$(SolutionDir)$(Configuration)64\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">$(Configuration)64\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">false</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">$(Configuration)\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">true</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">$(SolutionDir)$(Configuration)64\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">$(Configuration)64\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">true</LinkIncremental>
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>..\..\include;curl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MinimalRebuild>true</MinimalRebuild>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>common.h</PrecompiledHeaderFile>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>wininet.lib;uxtheme.lib;comctl32.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(ProjectName).dll</OutputFile>
+ <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
+ <Midl>
+ <TargetEnvironment>X64</TargetEnvironment>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>..\..\include;curl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>_WIN64;_DEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MinimalRebuild>true</MinimalRebuild>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>common.h</PrecompiledHeaderFile>
+ <WarningLevel>Level3</WarningLevel>
+ <TreatWarningAsError>false</TreatWarningAsError>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>wininet.lib;uxtheme.lib;comctl32.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(ProjectName).dll</OutputFile>
+ <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <TargetMachine>MachineX64</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <AdditionalIncludeDirectories>..\..\include;curl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>wininet.lib;uxtheme.lib;comctl32.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(ProjectName).dll</OutputFile>
+ <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+ <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <RandomizedBaseAddress>true</RandomizedBaseAddress>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
+ <Midl>
+ <TargetEnvironment>X64</TargetEnvironment>
+ </Midl>
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <AdditionalIncludeDirectories>..\..\include;curl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>_WIN64;NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>wininet.lib;uxtheme.lib;comctl32.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(ProjectName).dll</OutputFile>
+ <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+ <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <RandomizedBaseAddress>true</RandomizedBaseAddress>
+ <TargetMachine>MachineX64</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <AdditionalIncludeDirectories>..\..\include;curl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <TreatWarningAsError>false</TreatWarningAsError>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>wininet.lib;uxtheme.lib;comctl32.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(ProjectName).dll</OutputFile>
+ <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+ <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <RandomizedBaseAddress>true</RandomizedBaseAddress>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">
+ <Midl>
+ <TargetEnvironment>X64</TargetEnvironment>
+ </Midl>
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <AdditionalIncludeDirectories>..\..\include;curl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>_WIN64;NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <TreatWarningAsError>false</TreatWarningAsError>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>wininet.lib;uxtheme.lib;comctl32.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(ProjectName).dll</OutputFile>
+ <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
+ <IgnoreSpecificDefaultLibraries>%(IgnoreSpecificDefaultLibraries)</IgnoreSpecificDefaultLibraries>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <RandomizedBaseAddress>true</RandomizedBaseAddress>
+ <TargetMachine>MachineX64</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>..\..\include;curl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MinimalRebuild>true</MinimalRebuild>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>common.h</PrecompiledHeaderFile>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>wininet.lib;uxtheme.lib;comctl32.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>d:\Development\TEST\miranda-im-v0.9.3-unicode\plugins\ftpfile.dll</OutputFile>
+ <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <DelayLoadDLLs>%(DelayLoadDLLs)</DelayLoadDLLs>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">
+ <Midl>
+ <TargetEnvironment>X64</TargetEnvironment>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>..\..\include;curl;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>_WIN64;_DEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MinimalRebuild>true</MinimalRebuild>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>common.h</PrecompiledHeaderFile>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>wininet.lib;uxtheme.lib;comctl32.lib;zlib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>d:\Development\YMP\4.6\Light\Miranda IM\plugins\ftpfile.dll</OutputFile>
+ <AdditionalLibraryDirectories>lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ <DelayLoadDLLs>%(DelayLoadDLLs)</DelayLoadDLLs>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <TargetMachine>MachineX64</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="dbentry.cpp" />
+ <ClCompile Include="deletetimer.cpp" />
+ <ClCompile Include="dialog.cpp" />
+ <ClCompile Include="ftpfile.cpp" />
+ <ClCompile Include="job_delete.cpp" />
+ <ClCompile Include="job_generic.cpp" />
+ <ClCompile Include="job_packer.cpp" />
+ <ClCompile Include="job_upload.cpp" />
+ <ClCompile Include="libcurl.cpp" />
+ <ClCompile Include="manager.cpp" />
+ <ClCompile Include="mir_db.cpp" />
+ <ClCompile Include="options.cpp" />
+ <ClCompile Include="serverlist.cpp" />
+ <ClCompile Include="utils.cpp" />
+ <ClCompile Include="zip\ioapi.c" />
+ <ClCompile Include="zip\zip.c" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="common.h" />
+ <ClInclude Include="dbentry.h" />
+ <ClInclude Include="deletetimer.h" />
+ <ClInclude Include="dialog.h" />
+ <ClInclude Include="job_delete.h" />
+ <ClInclude Include="job_generic.h" />
+ <ClInclude Include="job_packer.h" />
+ <ClInclude Include="job_upload.h" />
+ <ClInclude Include="libcurl.h" />
+ <ClInclude Include="docs\m_ftpfile.h" />
+ <ClInclude Include="manager.h" />
+ <ClInclude Include="mir_db.h" />
+ <ClInclude Include="options.h" />
+ <ClInclude Include="resource.h" />
+ <ClInclude Include="serverlist.h" />
+ <ClInclude Include="utils.h" />
+ <ClInclude Include="version.h" />
+ <ClInclude Include="zip\ioapi.h" />
+ <ClInclude Include="zip\zip.h" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="icons\clear.ico" />
+ <None Include="icons\clipboard.ico" />
+ <None Include="icons\delete.ico" />
+ <None Include="icons\ftp0.ico" />
+ <None Include="icons\ftp1.ico" />
+ <None Include="icons\ftp2.ico" />
+ <None Include="icons\ftp3.ico" />
+ <None Include="icons\ftp4.ico" />
+ <None Include="icons\menu.ico" />
+ <None Include="icons\pause.ico" />
+ <None Include="icons\resume.ico" />
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="ftpfile.rc" />
+ <ResourceCompile Include="version.rc" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project> \ No newline at end of file
diff --git a/plugins/FTPFileYM/ftpfile_10.vcxproj.filters b/plugins/FTPFileYM/ftpfile_10.vcxproj.filters
new file mode 100644
index 0000000000..7f21cc8ad4
--- /dev/null
+++ b/plugins/FTPFileYM/ftpfile_10.vcxproj.filters
@@ -0,0 +1,175 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup>
+ <Filter Include="Source Files">
+ <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+ <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+ </Filter>
+ <Filter Include="Source Files\zip">
+ <UniqueIdentifier>{b3e7dfba-6dac-490c-b597-8001819c9a39}</UniqueIdentifier>
+ </Filter>
+ <Filter Include="Header Files">
+ <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+ <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+ </Filter>
+ <Filter Include="Header Files\zip">
+ <UniqueIdentifier>{e450d857-86aa-4ad4-b63c-3a21362402c8}</UniqueIdentifier>
+ </Filter>
+ <Filter Include="Resource Files">
+ <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+ <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
+ </Filter>
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="dbentry.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="deletetimer.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="dialog.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ftpfile.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="job_delete.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="job_generic.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="job_packer.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="job_upload.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="libcurl.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="manager.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="mir_db.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="options.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="serverlist.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="utils.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="zip\ioapi.c">
+ <Filter>Source Files\zip</Filter>
+ </ClCompile>
+ <ClCompile Include="zip\zip.c">
+ <Filter>Source Files\zip</Filter>
+ </ClCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="common.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="dbentry.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="deletetimer.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="dialog.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="job_delete.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="job_generic.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="job_packer.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="job_upload.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="libcurl.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="docs\m_ftpfile.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="manager.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="mir_db.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="options.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="resource.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="serverlist.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="utils.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="version.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="zip\ioapi.h">
+ <Filter>Header Files\zip</Filter>
+ </ClInclude>
+ <ClInclude Include="zip\zip.h">
+ <Filter>Header Files\zip</Filter>
+ </ClInclude>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="icons\clear.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\clipboard.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\delete.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\ftp0.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\ftp1.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\ftp2.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\ftp3.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\ftp4.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\menu.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\pause.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ <None Include="icons\resume.ico">
+ <Filter>Resource Files</Filter>
+ </None>
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="ftpfile.rc">
+ <Filter>Resource Files</Filter>
+ </ResourceCompile>
+ <ResourceCompile Include="version.rc">
+ <Filter>Resource Files</Filter>
+ </ResourceCompile>
+ </ItemGroup>
+</Project> \ No newline at end of file
diff --git a/plugins/FTPFileYM/icons/clear.ico b/plugins/FTPFileYM/icons/clear.ico
new file mode 100644
index 0000000000..8fd6c2a936
--- /dev/null
+++ b/plugins/FTPFileYM/icons/clear.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/clipboard.ico b/plugins/FTPFileYM/icons/clipboard.ico
new file mode 100644
index 0000000000..d0e80b0e7e
--- /dev/null
+++ b/plugins/FTPFileYM/icons/clipboard.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/delete.ico b/plugins/FTPFileYM/icons/delete.ico
new file mode 100644
index 0000000000..26058006a0
--- /dev/null
+++ b/plugins/FTPFileYM/icons/delete.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/ftp0.ico b/plugins/FTPFileYM/icons/ftp0.ico
new file mode 100644
index 0000000000..2a10ab1ad9
--- /dev/null
+++ b/plugins/FTPFileYM/icons/ftp0.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/ftp1.ico b/plugins/FTPFileYM/icons/ftp1.ico
new file mode 100644
index 0000000000..6ab8b4a2f3
--- /dev/null
+++ b/plugins/FTPFileYM/icons/ftp1.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/ftp2.ico b/plugins/FTPFileYM/icons/ftp2.ico
new file mode 100644
index 0000000000..cda6827a5e
--- /dev/null
+++ b/plugins/FTPFileYM/icons/ftp2.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/ftp3.ico b/plugins/FTPFileYM/icons/ftp3.ico
new file mode 100644
index 0000000000..ed2eea3582
--- /dev/null
+++ b/plugins/FTPFileYM/icons/ftp3.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/ftp4.ico b/plugins/FTPFileYM/icons/ftp4.ico
new file mode 100644
index 0000000000..69965d998a
--- /dev/null
+++ b/plugins/FTPFileYM/icons/ftp4.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/menu.ico b/plugins/FTPFileYM/icons/menu.ico
new file mode 100644
index 0000000000..ae0e211a7f
--- /dev/null
+++ b/plugins/FTPFileYM/icons/menu.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/pause.ico b/plugins/FTPFileYM/icons/pause.ico
new file mode 100644
index 0000000000..c3ed4fa12b
--- /dev/null
+++ b/plugins/FTPFileYM/icons/pause.ico
Binary files differ
diff --git a/plugins/FTPFileYM/icons/resume.ico b/plugins/FTPFileYM/icons/resume.ico
new file mode 100644
index 0000000000..01451a7319
--- /dev/null
+++ b/plugins/FTPFileYM/icons/resume.ico
Binary files differ
diff --git a/plugins/FTPFileYM/job_delete.cpp b/plugins/FTPFileYM/job_delete.cpp
new file mode 100644
index 0000000000..f7d2c7c64b
--- /dev/null
+++ b/plugins/FTPFileYM/job_delete.cpp
@@ -0,0 +1,124 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "common.h"
+#include "job_delete.h"
+
+Event DeleteJob::jobDone;
+Mutex DeleteJob::mutexJobCount;
+int DeleteJob::iRunningJobCount = 0;
+
+extern ServerList &ftpList;
+extern Manager *manDlg;
+extern LibCurl &curl;
+
+DeleteJob::DeleteJob(DBEntry *_entry, Manager::TreeItem *_item)
+:entry(_entry),treeItem(_item),ftp(ftpList[entry->iFtpNum])
+{ }
+
+DeleteJob::~DeleteJob()
+{
+ delete this->entry;
+}
+
+void DeleteJob::waitingThread(void *arg)
+{
+ DeleteJob *job = (DeleteJob *)arg;
+
+ while(!Miranda_Terminated())
+ {
+ Lock *lock = new Lock(mutexJobCount);
+ if (iRunningJobCount < MAX_RUNNING_JOBS)
+ {
+ iRunningJobCount++;
+ delete lock;
+ job->run();
+ delete job;
+
+ Lock *lock = new Lock(mutexJobCount);
+ iRunningJobCount--;
+ delete lock;
+
+ jobDone.release();
+ return;
+ }
+
+ delete lock;
+ jobDone.wait();
+ }
+
+ delete job;
+}
+
+void DeleteJob::start()
+{
+ mir_forkthread(&DeleteJob::waitingThread, this);
+}
+
+void DeleteJob::run()
+{
+ char szError[1024];
+
+ CURL *hCurl = curl.easy_init();
+ if (hCurl)
+ {
+ struct curl_slist *headerList = NULL;
+ headerList = curl.slist_append(headerList, getDelFileString());
+
+ Utils::curlSetOpt(hCurl, this->ftp, getDelUrlString(), headerList, szError);
+
+ int result = curl.easy_perform(hCurl);
+ if (result == CURLE_OK)
+ {
+ if (manDlg != NULL && this->treeItem)
+ this->treeItem->remove();
+ else
+ DBEntry::remove(entry->fileID);
+ }
+ else if (manDlg != NULL && this->treeItem)
+ {
+ TCHAR *error = mir_a2t(szError);
+ _tcscpy(this->treeItem->stzToolTip, error);
+ this->treeItem->setState(Manager::TreeItem::_ERROR());
+ FREE(error);
+ }
+
+ curl.slist_free_all(headerList);
+ curl.easy_cleanup(hCurl);
+ }
+}
+
+char *DeleteJob::getDelFileString()
+{
+ if (ftp->ftpProto == ServerList::FTP::FT_SSH)
+ mir_snprintf(buff, sizeof(buff), "rm \"%s/%s\"", ftp->szDir, entry->szFileName);
+ else
+ mir_snprintf(buff, sizeof(buff), "DELE %s", entry->szFileName);
+
+ return buff;
+}
+
+char *DeleteJob::getDelUrlString()
+{
+ if (ftp->szDir[0] && ftp->ftpProto != ServerList::FTP::FT_SSH)
+ mir_snprintf(buff, sizeof(buff), "%s%s/%s/", ftp->getProtoString(), ftp->szServer, ftp->szDir);
+ else
+ mir_snprintf(buff, sizeof(buff), "%s%s/", ftp->getProtoString(), ftp->szServer);
+
+ return buff;
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/job_delete.h b/plugins/FTPFileYM/job_delete.h
new file mode 100644
index 0000000000..a2da7c5d24
--- /dev/null
+++ b/plugins/FTPFileYM/job_delete.h
@@ -0,0 +1,50 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "dbentry.h"
+#include "manager.h"
+
+class DeleteJob
+{
+private:
+ static const int MAX_RUNNING_JOBS = 2;
+
+ DBEntry *entry;
+ Manager::TreeItem *treeItem;
+ ServerList::FTP *ftp;
+ char buff[256];
+
+ static Mutex mutexJobCount;
+ static int iRunningJobCount;
+
+ char *getDelFileString();
+ char *getDelUrlString();
+
+ static void waitingThread(void *arg);
+ void run();
+
+public:
+ static Event jobDone;
+
+ DeleteJob(DBEntry *entry, Manager::TreeItem *item);
+ ~DeleteJob();
+
+ void start();
+};
diff --git a/plugins/FTPFileYM/job_generic.cpp b/plugins/FTPFileYM/job_generic.cpp
new file mode 100644
index 0000000000..2a126b2190
--- /dev/null
+++ b/plugins/FTPFileYM/job_generic.cpp
@@ -0,0 +1,255 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "job_generic.h"
+#include "dbentry.h"
+#include "utils.h"
+
+extern UploadDialog *uDlg;
+extern ServerList &ftpList;
+
+GenericJob::GenericJob(HANDLE _hContact, int _iFtpNum, EMode _mode)
+:hContact(_hContact),iFtpNum(_iFtpNum),mode(_mode),status(STATUS_CREATED),ftp(ftpList[iFtpNum])
+{
+ this->stzFilePath[0] = 0;
+ this->stzFileName[0] = 0;
+ this->szSafeFileName[0] = 0;
+}
+
+GenericJob::GenericJob(GenericJob *job)
+:hContact(job->hContact),iFtpNum(job->iFtpNum),mode(job->mode),status(job->status),ftp(job->ftp),tab(job->tab)
+{
+ _tcscpy(this->stzFilePath, job->stzFilePath);
+ _tcscpy(this->stzFileName, job->stzFileName);
+ strcpy(this->szSafeFileName, job->szSafeFileName);
+}
+
+GenericJob::~GenericJob()
+{
+ for (UINT i = 0; i < this->files.size(); i++)
+ mir_free(this->files[i]);
+}
+
+int GenericJob::openFileDialog()
+{
+ OPENFILENAME ofn = {0};
+ ofn.lStructSize = sizeof(ofn);
+ ofn.hwndOwner = 0;
+ ofn.lpstrFilter = _T("All Files (*.*)\0*.*\0");
+ ofn.nFilterIndex = 1;
+ ofn.lpstrFile = this->stzFilePath;
+ ofn.lpstrTitle = TranslateT("FTP File - Select files");
+ ofn.nMaxFile = SIZEOF(this->stzFilePath);
+ ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_ALLOWMULTISELECT | OFN_EXPLORER | OFN_NOCHANGEDIR;
+ return GetOpenFileName(&ofn);
+}
+
+int GenericJob::openFolderDialog()
+{
+ BROWSEINFO bi = {0};
+ bi.lpszTitle = TranslateT("FTP File - Select a folder");
+ bi.ulFlags = BIF_NEWDIALOGSTYLE | BIF_NONEWFOLDERBUTTON | BIF_DONTGOBELOWDOMAIN;
+ LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
+ if (pidl != 0)
+ {
+ SHGetPathFromIDList(pidl, this->stzFilePath);
+ CoTaskMemFree(pidl);
+ return 1;
+ }
+
+ return 0;
+}
+
+void GenericJob::getFilesFromOpenDialog()
+{
+ TCHAR stzFile[MAX_PATH];
+
+ size_t length = _tcslen(this->stzFilePath);
+ if (this->stzFilePath[0] && this->stzFilePath[length+1]) // multiple files
+ {
+ TCHAR *ptr = this->stzFilePath + length + 1;
+ while (ptr[0])
+ {
+ mir_sntprintf(stzFile, MAX_PATH, _T("%s\\%s"), this->stzFilePath, ptr);
+ this->addFile(stzFile);
+ ptr += _tcslen(ptr) + 1;
+ }
+ }
+ else
+ {
+ this->addFile(this->stzFilePath);
+ }
+}
+
+int GenericJob::getFilesFromFolder(TCHAR *stzFolder)
+{
+ TCHAR stzFile[MAX_PATH], stzDirSave[MAX_PATH];
+
+ GetCurrentDirectory(MAX_PATH, stzDirSave);
+ if (!SetCurrentDirectory(stzFolder))
+ {
+ Utils::msgBox(TranslateT("Folder not found!"), MB_OK | MB_ICONERROR);
+ return 0;
+ }
+
+ WIN32_FIND_DATA ffd;
+ HANDLE hFind = FindFirstFile(_T("*.*"), &ffd);
+ while (hFind != INVALID_HANDLE_VALUE)
+ {
+ if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
+ {
+ mir_sntprintf(stzFile, MAX_PATH, _T("%s\\%s"), stzFolder, ffd.cFileName);
+ this->addFile(stzFile);
+ }
+
+ if (!FindNextFile(hFind, &ffd))
+ break;
+ }
+
+ FindClose(hFind);
+ SetCurrentDirectory(stzDirSave);
+
+ if (this->files.size() == 0)
+ {
+ Utils::msgBox(TranslateT("The selected folder does not contain any files.\nFTP File sends files only from the selected folder, not from subfolders."), MB_OK | MB_ICONERROR);
+ return 0;
+ }
+
+ return 1;
+}
+
+int GenericJob::getFiles()
+{
+ if (this->mode == FTP_ZIPFOLDER)
+ {
+ if (!openFolderDialog()) return 0;
+ return getFilesFromFolder(this->stzFilePath);
+ }
+ else
+ {
+ if (!openFileDialog()) return 0;
+ getFilesFromOpenDialog();
+ }
+
+ return 1;
+}
+
+int GenericJob::getFiles(void **objects, int objCount, DWORD flags)
+{
+ if (this->mode == FTP_ZIPFOLDER)
+ {
+ TCHAR *folder;
+ if (flags & FUPL_UNICODE)
+ folder = mir_u2t((wchar_t *)objects[0]);
+ else
+ folder = mir_a2t((char *)objects[0]);
+
+ int result = getFilesFromFolder(folder);
+ FREE(folder);
+ return result;
+ }
+ else
+ {
+ for (int i = 0; i < objCount; i++)
+ {
+ TCHAR *fileName;
+ if (flags & FUPL_UNICODE)
+ fileName = mir_u2t((wchar_t *)objects[i]);
+ else
+ fileName = mir_a2t((char *)objects[i]);
+
+ addFile(fileName);
+ FREE(fileName);
+ }
+ }
+
+ return (this->files.size() == 0) ? 0 : 1;
+}
+
+void GenericJob::addFile(TCHAR *fileName)
+{
+ TCHAR *buff = mir_tstrdup(fileName);
+ this->files.push_back(buff);
+}
+
+void GenericJob::setStatus(EStatus status)
+{
+ this->status = status;
+ this->refreshTab(true);
+}
+
+bool GenericJob::isCompleted()
+{
+ return this->status == STATUS_COMPLETED;
+}
+
+bool GenericJob::isPaused()
+{
+ return this->status == STATUS_PAUSED;
+}
+
+bool GenericJob::isWaitting()
+{
+ return this->status == STATUS_WAITING;
+}
+
+bool GenericJob::isCanceled()
+{
+ return this->status == STATUS_CANCELED;
+}
+
+bool GenericJob::isConnecting()
+{
+ return (this->status == STATUS_CONNECTING || this->status == STATUS_CREATED);
+}
+
+TCHAR *GenericJob::getStatusString()
+{
+ switch (this->status)
+ {
+ case STATUS_CANCELED: return TranslateT("CANCELED");
+ case STATUS_COMPLETED: return TranslateT("COMPLETED");
+ case STATUS_CONNECTING: return TranslateT("CONNECTING...");
+ case STATUS_CREATED: return TranslateT("CREATED");
+ case STATUS_PACKING: return TranslateT("PACKING...");
+ case STATUS_PAUSED: return TranslateT("PAUSED");
+ case STATUS_UPLOADING: return TranslateT("UPLOADING...");
+ case STATUS_WAITING: return TranslateT("WAITING...");
+ default: return TranslateT("UNKNOWN");
+ }
+}
+
+void GenericJob::refreshTab(bool bTabChanged)
+{
+ if (bTabChanged)
+ {
+ if (this->hContact != NULL)
+ {
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PROTO, BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadSkinnedProtoIcon(DB::getProto(this->hContact), ID_STATUS_ONLINE));
+ SetDlgItemText(uDlg->hwnd, IDC_UP_CONTACT, (TCHAR *)CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM)this->hContact, GCDNF_TCHAR));
+ }
+ else
+ {
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PROTO, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("main"));
+ SetDlgItemTextA(uDlg->hwnd, IDC_UP_CONTACT, this->ftp->szServer);
+ }
+
+ SetDlgItemText(uDlg->hwnd, IDC_UP_FILE, this->stzFileName);
+ SetDlgItemTextA(uDlg->hwnd, IDC_UP_SERVER, this->ftp->szServer);
+ }
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/job_generic.h b/plugins/FTPFileYM/job_generic.h
new file mode 100644
index 0000000000..618d891a82
--- /dev/null
+++ b/plugins/FTPFileYM/job_generic.h
@@ -0,0 +1,109 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+#include "dialog.h"
+#include "serverlist.h"
+
+class Event
+{
+private:
+ HANDLE handle;
+
+public:
+ Event() { handle = CreateEvent (0, FALSE, FALSE, 0); }
+ ~Event() { CloseHandle (handle); }
+
+ operator HANDLE () { return handle; }
+
+ void release() { SetEvent(handle); }
+ void wait() { WaitForSingleObject(handle, INFINITE); }
+};
+
+class GenericJob
+{
+private:
+ int openFileDialog();
+ int openFolderDialog();
+ void getFilesFromOpenDialog();
+ int getFilesFromFolder(TCHAR *stzFolder);
+ void addFile(TCHAR *fileName);
+
+public:
+ enum EMode
+ {
+ FTP_RAWFILE = 8,
+ FTP_ZIPFILE = 16,
+ FTP_ZIPFOLDER = 32
+ };
+
+ enum EStatus
+ {
+ STATUS_CREATED = 0,
+ STATUS_WAITING,
+ STATUS_CONNECTING,
+ STATUS_UPLOADING,
+ STATUS_PACKING,
+ STATUS_PAUSED,
+ STATUS_CANCELED,
+ STATUS_COMPLETED
+ };
+
+ HANDLE hContact;
+ int iFtpNum, fileID;
+ ServerList::FTP *ftp;
+ TCHAR stzFilePath[1024];
+ TCHAR stzFileName[64];
+ char szSafeFileName[64];
+ EMode mode;
+ EStatus status;
+
+ UploadDialog::Tab *tab;
+ vector<TCHAR *> files;
+ TCHAR * operator[] (int i) const { return files[i];}
+
+ GenericJob(HANDLE hContact, int iFtpNum, EMode mode);
+ GenericJob(GenericJob *job);
+ virtual ~GenericJob();
+
+ int getFiles();
+ int getFiles(void **objects, int objCount, DWORD flags);
+ void setStatus(EStatus status);
+
+ bool isCompleted();
+ bool isPaused();
+ bool isWaitting();
+ bool isConnecting();
+ bool isCanceled();
+
+ TCHAR *getStatusString();
+
+ virtual void start() = 0;
+ virtual void pause() = 0;
+ virtual void resume() = 0;
+ virtual void cancel() = 0;
+ virtual void addToUploadDlg() = 0;
+ virtual void pauseHandler() = 0;
+
+ virtual void refreshTab(bool bTabChanged);
+ virtual void closeTab() = 0;
+ virtual void closeAllTabs() = 0;
+ virtual void createToolTip() = 0;
+};
diff --git a/plugins/FTPFileYM/job_packer.cpp b/plugins/FTPFileYM/job_packer.cpp
new file mode 100644
index 0000000000..4d5c9ce4d5
--- /dev/null
+++ b/plugins/FTPFileYM/job_packer.cpp
@@ -0,0 +1,354 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "job_packer.h"
+#include "job_upload.h"
+#include "dialog.h"
+#include "options.h"
+#include "utils.h"
+
+Event PackerJob::jobDone;
+Mutex PackerJob::mutexJobCount;
+int PackerJob::iRunningJobCount = 0;
+
+extern UploadDialog *uDlg;
+extern Options &opt;
+
+PackerJob::PackerJob(HANDLE _hContact, int _iFtpNum, EMode _mode)
+:GenericJob(_hContact, _iFtpNum, _mode),uiFileSize(0),uiReaded(0),lastUpdateTick(0)
+{ }
+
+void PackerJob::getZipFilePath()
+{
+ TCHAR buff[256], stzFileName[256] = {0};
+ TCHAR *pch;
+
+ if (this->files.size() == 1)
+ {
+ _tcscpy(stzFileName, Utils::getFileNameFromPath(this->files[0]));
+ pch = _tcsrchr(stzFileName, '.');
+ if (pch) *pch = 0;
+ }
+ else
+ {
+ _tcscpy(buff, this->files[0]);
+ pch = _tcsrchr(buff, '\\');
+ if (pch)
+ {
+ *pch = 0;
+ pch = _tcsrchr(buff, '\\');
+ if (pch) _tcscpy(stzFileName, pch + 1);
+ }
+ }
+
+ if (_tcslen(stzFileName) == 0)
+ _tcscpy(stzFileName, _T("archive"));
+
+ GetTempPath(SIZEOF(buff), buff);
+
+ mir_sntprintf(this->stzFilePath, SIZEOF(this->stzFilePath), _T("%s%s.zip"), buff, stzFileName);
+ _tcscpy(this->stzFileName, Utils::getFileNameFromPath(this->stzFilePath));
+
+ if (opt.bSetZipName)
+ Utils::setFileNameDlg(this->stzFileName);
+}
+
+void PackerJob::addToUploadDlg()
+{
+ this->getZipFilePath();
+
+ UploadDialog::Tab *newTab = new UploadDialog::Tab(this);
+ this->tab = newTab;
+ this->start();
+}
+
+void PackerJob::waitingThread(void *arg)
+{
+ PackerJob *job = (PackerJob *)arg;
+
+ while(!Miranda_Terminated())
+ {
+ Lock *lock = new Lock(mutexJobCount);
+ if (iRunningJobCount < MAX_RUNNING_JOBS)
+ {
+ iRunningJobCount++;
+ delete lock;
+ job->pack();
+ delete job;
+
+ Lock *lock = new Lock(mutexJobCount);
+ iRunningJobCount--;
+ delete lock;
+
+ jobDone.release();
+ return;
+ }
+
+ delete lock;
+ jobDone.wait();
+ job->status = GenericJob::STATUS_WAITING;
+ }
+}
+
+void PackerJob::start()
+{
+ mir_forkthread(&PackerJob::waitingThread, this);
+}
+
+void PackerJob::pack()
+{
+ struct _stat fileInfo;
+ for (UINT i = 0; i < this->files.size(); i++)
+ {
+ if (_tstat(this->files[i], &fileInfo) == 0)
+ this->uiFileSize += (UINT64)fileInfo.st_size;
+ }
+
+ this->setStatus(STATUS_PACKING);
+ this->startTS = time(NULL);
+
+ int res = this->createZipFile();
+ if (res == ZIP_OK)
+ {
+ UploadJob *ujob = new UploadJob(this);
+ ujob->tab->job = ujob;
+ ujob->start();
+ }
+ else
+ {
+ if (res == ZIP_ERRNO)
+ {
+ Utils::msgBox(TranslateT("Error occured when zipping the file(s)."), MB_OK | MB_ICONERROR);
+ delete this->tab;
+ }
+
+ DeleteFile(this->stzFilePath);
+ }
+}
+
+int PackerJob::createZipFile()
+{
+ int result = ZIP_ERRNO;
+
+ char *filePath = mir_t2a(this->stzFilePath);
+ zipFile zf = zipOpen2(filePath, 0, NULL, NULL);
+ FREE(filePath);
+
+ if (zf != NULL)
+ {
+ result = ZIP_OK;
+
+ int size_buf = 65536;
+ void *buff = (void *)mir_alloc(size_buf);
+
+ for (UINT i = 0; i < this->files.size(); i++)
+ {
+ int size_read;
+ zip_fileinfo zi;
+
+ zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = 0;
+ zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
+ zi.dosDate = 0;
+ zi.internal_fa = 0;
+ zi.external_fa = 0;
+
+ getFileTime(this->files[i], &zi.tmz_date, &zi.dosDate);
+
+ char *file = mir_t2a(Utils::getFileNameFromPath(this->files[i]));
+ int err = zipOpenNewFileInZip(zf, file, &zi, NULL, 0, NULL, 0, NULL, Z_DEFLATED, opt.iCompressionLevel);
+ FREE(file);
+
+ if (err == ZIP_OK)
+ {
+ FILE *fin = _tfopen(this->files[i], _T("rb"));
+ if (fin)
+ {
+ do
+ {
+ if (this->isCanceled())
+ {
+ fclose(fin);
+ result = STATUS_CANCELED;
+ goto Cleanup;
+ }
+
+ err = ZIP_OK;
+ size_read = (int)fread(buff, 1, size_buf, fin);
+ if (size_read < size_buf && feof(fin) == 0)
+ {
+ fclose(fin);
+ result = ZIP_ERRNO;
+ goto Cleanup;
+ }
+
+ if (size_read > 0)
+ {
+ err = zipWriteInFileInZip(zf, buff, size_read);
+ this->uiReaded += size_read;
+ }
+
+ this->updateStats();
+ }
+ while ((err == ZIP_OK) && (size_read > 0));
+ fclose(fin);
+ }
+ else
+ {
+ err = ZIP_ERRNO;
+ }
+
+ err = zipCloseFileInZip(zf);
+ if (err < 0)
+ {
+ result = ZIP_ERRNO;
+ goto Cleanup;
+ }
+ }
+ else
+ {
+ result = ZIP_ERRNO;
+ break;
+ }
+ }
+
+Cleanup:
+ zipClose(zf, NULL);
+ FREE(buff);
+ }
+
+ return result;
+}
+
+uLong PackerJob::getFileTime(TCHAR *file, tm_zip *tmzip, uLong *dt)
+{
+ FILETIME ftLocal;
+ HANDLE hFind;
+ WIN32_FIND_DATA ff32;
+
+ hFind = FindFirstFile(file, &ff32);
+ if (hFind != INVALID_HANDLE_VALUE)
+ {
+ FileTimeToLocalFileTime(&(ff32.ftLastWriteTime),&ftLocal);
+ FileTimeToDosDateTime(&ftLocal,((LPWORD)dt)+1,((LPWORD)dt)+0);
+ FindClose(hFind);
+ return 1;
+ }
+
+ return 0;
+}
+
+void PackerJob::updateStats()
+{
+ DWORD dwNewTick = GetTickCount();
+ if (this->uiReaded && (time(NULL) > this->startTS) && (dwNewTick > this->lastUpdateTick + 100))
+ {
+ this->lastUpdateTick = dwNewTick;
+
+ double speed = ((double)this->uiReaded / 1024)/(time(NULL) - this->startTS);
+ mir_sntprintf(this->tab->stzSpeed, SIZEOF(this->tab->stzSpeed), _T("%0.1f kB/s"), speed);
+
+ double perc = this->uiFileSize ? ((double)this->uiReaded / this->uiFileSize) * 100 : 0;
+ mir_sntprintf(this->tab->stzComplet, SIZEOF(this->tab->stzComplet), _T("%0.1f%% (%d kB/%d kB)"), perc, (int)this->uiReaded/1024, (int)this->uiFileSize/1024);
+
+ TCHAR buff[256];
+ long s = (this->uiFileSize - this->uiReaded) / (long)(speed * 1024);
+ int d = (s / 60 / 60 / 24);
+ int h = (s - d * 60 * 60 * 24) / 60 / 60;
+ int m = (s - d * 60 * 60 * 24 - h * 60 * 60) / 60;
+ s = s - (d * 24 * 60 * 60) - (h * 60 * 60) - (m * 60);
+
+ if (d > 0) mir_sntprintf(buff, SIZEOF(buff), _T("%dd %02d:%02d:%02d"), d, h, m, s);
+ else mir_sntprintf(buff, SIZEOF(buff), _T("%02d:%02d:%02d"), h, m, s);
+ mir_sntprintf(this->tab->stzRemain, SIZEOF(this->tab->stzRemain), _T("%s (%d kB/%d kB)"), buff, (this->uiFileSize - this->uiReaded)/1024, this->uiFileSize/1024);
+
+ this->refreshTab(false);
+ }
+}
+
+void PackerJob::refreshTab(bool bTabChanged)
+{
+ if (uDlg->activeTab == this->tab->index())
+ {
+ GenericJob::refreshTab(bTabChanged);
+
+ SetDlgItemText(uDlg->hwnd, IDC_UP_SPEED, this->tab->stzSpeed);
+ SetDlgItemText(uDlg->hwnd, IDC_UP_COMPLETED, this->tab->stzComplet);
+ SetDlgItemText(uDlg->hwnd, IDC_UP_REMAIN, this->tab->stzRemain);
+
+ SendDlgItemMessage(uDlg->hwnd, IDC_PB_UPLOAD, PBM_SETRANGE32, 0, (LPARAM)this->uiFileSize);
+ SendDlgItemMessage(uDlg->hwnd, IDC_PB_UPLOAD, PBM_SETPOS, (WPARAM)this->uiReaded, 0);
+
+ if (bTabChanged)
+ {
+ SetDlgItemText(uDlg->hwnd, IDC_STATUSBAR, TranslateT("PACKING..."));
+ EnableWindow(GetDlgItem(uDlg->hwnd, IDC_BTN_PAUSE), FALSE);
+ }
+ }
+}
+
+bool PackerJob::isCanceled()
+{
+ return this->status == STATUS_CANCELED;
+}
+
+void PackerJob::pauseHandler()
+{
+ /* Not implemented */
+}
+
+void PackerJob::pause()
+{
+ /* Not implemented */
+}
+
+void PackerJob::resume()
+{
+ /* Not implemented */
+}
+
+void PackerJob::cancel()
+{
+ this->setStatus(STATUS_CANCELED);
+}
+
+void PackerJob::closeTab()
+{
+ if (Utils::msgBox(TranslateT("Do you really want to cancel this upload?"), MB_YESNO | MB_ICONQUESTION) == IDYES)
+ {
+ this->cancel();
+ delete this->tab;
+ }
+}
+
+void PackerJob::closeAllTabs()
+{
+ this->cancel();
+ delete this->tab;
+}
+
+void PackerJob::createToolTip()
+{
+ TCHAR *server = mir_a2t(this->ftp->szServer);
+ mir_sntprintf(uDlg->stzToolTipText, SIZEOF(uDlg->stzToolTipText),
+ TranslateT("Status: %s\r\nFile: %s\r\nServer: %s"),
+ this->getStatusString(),
+ this->stzFileName,
+ server);
+
+ FREE(server);
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/job_packer.h b/plugins/FTPFileYM/job_packer.h
new file mode 100644
index 0000000000..5d6857f24b
--- /dev/null
+++ b/plugins/FTPFileYM/job_packer.h
@@ -0,0 +1,63 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+#include "job_generic.h"
+#include "zip/zip.h"
+
+class PackerJob: public GenericJob
+{
+private:
+ static const int MAX_RUNNING_JOBS = 1;
+
+ UINT64 uiFileSize;
+ UINT64 uiReaded;
+ time_t startTS;
+ time_t lastUpdateTick;
+
+ static Event jobDone;
+ static Mutex mutexJobCount;
+ static int iRunningJobCount;
+
+ static void waitingThread(void *arg);
+ static uLong getFileTime(TCHAR *file, tm_zip *tmzip, uLong *dt);
+
+ void pack();
+ void getZipFilePath();
+ int createZipFile();
+ void updateStats();
+ bool isCanceled();
+
+public:
+ PackerJob(HANDLE hContact, int iFtpNum, EMode mode);
+ virtual ~PackerJob() {};
+
+ virtual void start();
+ virtual void pause();
+ virtual void resume();
+ virtual void cancel();
+ virtual void addToUploadDlg();
+ virtual void pauseHandler();
+
+ virtual void refreshTab(bool bTabChanged);
+ virtual void closeTab();
+ virtual void closeAllTabs();
+ virtual void createToolTip();
+}; \ No newline at end of file
diff --git a/plugins/FTPFileYM/job_upload.cpp b/plugins/FTPFileYM/job_upload.cpp
new file mode 100644
index 0000000000..36b4e628b5
--- /dev/null
+++ b/plugins/FTPFileYM/job_upload.cpp
@@ -0,0 +1,551 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "job_upload.h"
+#include "dbentry.h"
+#include "job_packer.h"
+
+Event UploadJob::jobDone;
+Mutex UploadJob::mutexJobCount;
+int UploadJob::iRunningJobCount = 0;
+
+extern UploadDialog *uDlg;
+extern ServerList &ftpList;
+extern LibCurl &curl;
+
+UploadJob::UploadJob(HANDLE _hContact, int _iFtpNum, EMode _mode)
+:GenericJob(_hContact, _iFtpNum, _mode),fp(NULL)
+{
+ this->szFileLink[0] = 0;
+}
+
+UploadJob::UploadJob(UploadJob *job)
+:GenericJob(job),fp(NULL),uiSent(0),uiTotalSent(0),uiFileSize(0)
+{
+ strcpy(this->szFileLink, job->szFileLink);
+ for (int i = 0; i < SIZEOF(this->lastSpeed); i++)
+ this->lastSpeed[i] = 0;
+}
+
+UploadJob::UploadJob(PackerJob *job)
+:GenericJob(job),fp(NULL),uiSent(0),uiTotalSent(0),uiFileSize(0)
+{
+ for (int i = 0; i < SIZEOF(this->lastSpeed); i++)
+ this->lastSpeed[i] = 0;
+
+ Utils::makeSafeString(job->stzFileName, this->szSafeFileName);
+ this->status = STATUS_CREATED;
+}
+
+UploadJob::~UploadJob()
+{
+ if (this->fp)
+ fclose(this->fp);
+
+ if (this->mode != FTP_RAWFILE)
+ DeleteFile(this->stzFilePath);
+}
+
+void UploadJob::addToUploadDlg()
+{
+ for (UINT i = 0; i < this->files.size(); i++)
+ {
+ UploadJob *jobCopy = new UploadJob(this);
+ _tcscpy(jobCopy->stzFilePath, this->files[i]);
+ _tcscpy(jobCopy->stzFileName, Utils::getFileNameFromPath(jobCopy->stzFilePath));
+ Utils::makeSafeString(jobCopy->stzFileName, jobCopy->szSafeFileName);
+
+ UploadDialog::Tab *newTab = new UploadDialog::Tab(jobCopy);
+ jobCopy->tab = newTab;
+ jobCopy->start();
+ }
+
+ delete this;
+}
+
+void UploadJob::autoSend()
+{
+ if (this->hContact != NULL)
+ {
+ char *szProto = DB::getProto(this->hContact);
+ if (szProto)
+ {
+ DBEVENTINFO dbei = {0};
+ dbei.cbSize = sizeof(dbei);
+ dbei.eventType = EVENTTYPE_MESSAGE;
+ dbei.flags = DBEF_SENT;
+ dbei.szModule = szProto;
+ dbei.timestamp = (DWORD)time(NULL);
+ dbei.cbBlob = (DWORD)strlen(this->szFileLink) + 1;
+ dbei.pBlob = (PBYTE)this->szFileLink;
+ CallService(MS_DB_EVENT_ADD, (WPARAM)this->hContact, (LPARAM)&dbei);
+ CallContactService(this->hContact, PSS_MESSAGE, 0, (LPARAM)this->szFileLink);
+ CallServiceSync(MS_MSG_SENDMESSAGE, (WPARAM)this->hContact, 0);
+ }
+ }
+}
+
+void UploadJob::copyLinkToML()
+{
+ if (this->hContact != NULL)
+ {
+ char buff[256];
+ mir_snprintf(buff, sizeof(buff), "%s\r\n", this->szFileLink);
+ CallServiceSync(MS_MSG_SENDMESSAGE, (WPARAM)this->hContact, (LPARAM)buff);
+ }
+}
+
+void UploadJob::pause()
+{
+ if (!isCompleted())
+ {
+ curl.easy_pause(this->hCurl, CURLPAUSE_SEND);
+ this->setStatus(STATUS_PAUSED);
+ }
+}
+
+void UploadJob::pauseHandler()
+{
+ if (this->isPaused())
+ {
+ this->resume();
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PAUSE, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("pause"));
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PAUSE, BUTTONADDTOOLTIP, (WPARAM)Translate("Pause"), 0);
+ }
+ else
+ {
+ this->pause();
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PAUSE, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("resume"));
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PAUSE, BUTTONADDTOOLTIP, (WPARAM)Translate("Resume"), 0);
+ }
+}
+
+void UploadJob::resume()
+{
+ this->uiSent = 0;
+ this->startTS = time(NULL);
+ if (!isCompleted())
+ {
+ curl.easy_pause(this->hCurl, CURLPAUSE_CONT);
+ this->setStatus(STATUS_UPLOADING);
+ }
+}
+
+void UploadJob::cancel()
+{
+ this->setStatus(STATUS_CANCELED);
+ curl.easy_pause(this->hCurl, CURLPAUSE_CONT);
+}
+
+void UploadJob::waitingThread(void *arg)
+{
+ UploadJob *job = (UploadJob *)arg;
+
+ while (!Miranda_Terminated())
+ {
+ Lock *lock = new Lock(mutexJobCount);
+ if (iRunningJobCount < MAX_RUNNING_JOBS)
+ {
+ iRunningJobCount++;
+ delete lock;
+ job->upload();
+
+ if (!job->isCompleted())
+ delete job;
+
+ Lock *lock = new Lock(mutexJobCount);
+ iRunningJobCount--;
+ delete lock;
+
+ jobDone.release();
+ return;
+ }
+
+ delete lock;
+ jobDone.wait();
+ job->status = GenericJob::STATUS_WAITING;
+ }
+
+ delete job;
+}
+
+void UploadJob::start()
+{
+ mir_forkthread(&UploadJob::waitingThread, this);
+}
+
+char *UploadJob::getChmodString()
+{
+ if (ftp->ftpProto == ServerList::FTP::FT_SSH)
+ mir_snprintf(buff, sizeof(buff), "%s \"%s/%s\"", ftp->szChmod, ftp->szDir, this->szSafeFileName);
+ else
+ mir_snprintf(buff, sizeof(buff), "%s %s", ftp->szChmod, this->szSafeFileName);
+
+ return buff;
+}
+
+char *UploadJob::getDelFileString()
+{
+ if (ftp->ftpProto == ServerList::FTP::FT_SSH)
+ mir_snprintf(buff, sizeof(buff), "rm \"%s/%s\"", ftp->szDir, this->szSafeFileName);
+ else
+ mir_snprintf(buff, sizeof(buff), "DELE %s", this->szSafeFileName);
+
+ return buff;
+}
+
+char *UploadJob::getUrlString()
+{
+ if (ftp->szDir[0])
+ mir_snprintf(buff, sizeof(buff), "%s%s/%s/%s", ftp->getProtoString(), ftp->szServer, ftp->szDir, this->szSafeFileName);
+ else
+ mir_snprintf(buff, sizeof(buff), "%s%s/%s", ftp->getProtoString(), ftp->szServer, this->szSafeFileName);
+
+ return buff;
+}
+
+char *UploadJob::getDelUrlString()
+{
+ if (ftp->szDir[0] && ftp->ftpProto != ServerList::FTP::FT_SSH)
+ mir_snprintf(buff, sizeof(buff), "%s%s/%s/", ftp->getProtoString(), ftp->szServer, ftp->szDir);
+ else
+ mir_snprintf(buff, sizeof(buff), "%s%s/", ftp->getProtoString(), ftp->szServer);
+
+ return buff;
+}
+
+CURL *UploadJob::curlInit(char *szUrl, struct curl_slist *headerList)
+{
+ this->hCurl = curl.easy_init();
+ if (!hCurl) return NULL;
+
+ Utils::curlSetOpt(this->hCurl, this->ftp, szUrl, headerList, this->szError);
+
+ curl.easy_setopt(this->hCurl, CURLOPT_INFILESIZE_LARGE, (curl_off_t)this->uiFileSize);
+ curl.easy_setopt(this->hCurl, CURLOPT_READDATA, this);
+ curl.easy_setopt(this->hCurl, CURLOPT_READFUNCTION, &UploadJob::ReadCallback);
+ //curl.easy_setopt(this->hCurl, CURLOPT_UPLOAD, 1L);
+
+ return this->hCurl;
+}
+
+bool UploadJob::fileExistsOnServer()
+{
+ int result = curl.easy_perform(hCurl);
+ return result != CURLE_REMOTE_FILE_NOT_FOUND;
+}
+
+INT_PTR CALLBACK UploadJob::DlgProcFileExists(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch (msg)
+ {
+ case WM_INITDIALOG:
+ {
+ TranslateDialogDefault(hwndDlg);
+
+ TCHAR buff[256];
+ TCHAR *fileName = mir_a2t((char *)lParam);
+ mir_sntprintf(buff, SIZEOF(buff), TranslateT("File exists - %s"), fileName);
+ SetWindowText(hwndDlg, buff);
+ FREE(fileName);
+ return TRUE;
+ }
+ case WM_COMMAND:
+ {
+ if (HIWORD(wParam) == BN_CLICKED)
+ EndDialog(hwndDlg, LOWORD(wParam));
+ break;
+ }
+ }
+
+ return FALSE;
+}
+
+void UploadJob::upload()
+{
+ this->refreshTab(true);
+
+ this->fp = _tfopen(this->stzFilePath, _T("rb"));
+ if (this->fp == NULL)
+ {
+ Utils::msgBox(TranslateT("Error occurred when opening local file.\nAborting file upload..."), MB_OK | MB_ICONERROR);
+ return;
+ }
+
+ struct curl_slist *headerList = NULL;
+ if (this->ftp->szChmod[0])
+ headerList = curl.slist_append(headerList, getChmodString());
+
+ struct _stat fileInfo;
+ _tstat(this->stzFilePath, &fileInfo);
+ this->uiFileSize = (UINT64)fileInfo.st_size;
+
+ CURL *hCurl = this->curlInit(getUrlString(), headerList);
+ if (!hCurl)
+ {
+ Utils::msgBox(TranslateT("Error occurred when initializing libcurl.\nAborting file upload..."), MB_OK | MB_ICONERROR);
+ return;
+ }
+
+ bool uploadFile = true;
+ if (fileExistsOnServer())
+ {
+ int res = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_DLG_FILEEXISTS), 0, DlgProcFileExists, (LPARAM)this->szSafeFileName);
+ if (res == IDC_RENAME)
+ {
+ if (Utils::setFileNameDlgA(this->szSafeFileName) == true)
+ curl.easy_setopt(hCurl, CURLOPT_URL, getUrlString());
+ }
+ else if (res == IDC_COPYURL)
+ {
+ uploadFile = false;
+ }
+ else if (res == IDC_CANCEL)
+ {
+ this->setStatus(STATUS_CANCELED);
+ delete this->tab;
+ return;
+ }
+ }
+
+ if (uploadFile)
+ {
+ curl.easy_setopt(this->hCurl, CURLOPT_UPLOAD, 1L);
+ this->setStatus(STATUS_CONNECTING);
+ this->startTS = time(NULL);
+
+ int result = curl.easy_perform(hCurl);
+ curl.slist_free_all(headerList);
+ curl.easy_cleanup(hCurl);
+
+ if (result != CURLE_OK && result != CURLE_ABORTED_BY_CALLBACK)
+ {
+ char buff[256];
+ mir_snprintf(buff, sizeof(buff), Translate("FTP error occurred.\n%s"), this->szError);
+ Utils::msgBoxA(buff, MB_OK | MB_ICONERROR);
+ }
+
+ if (result > CURLE_OPERATION_TIMEDOUT)
+ {
+ struct curl_slist *headerList = NULL;
+ headerList = curl.slist_append(headerList, getDelFileString());
+
+ CURL *hCurl = curl.easy_init();
+ if (hCurl)
+ {
+ Utils::curlSetOpt(hCurl, this->ftp, getDelUrlString(), headerList, this->szError);
+ curl.easy_perform(hCurl);
+ curl.slist_free_all(headerList);
+ curl.easy_cleanup(hCurl);
+ }
+ }
+
+ if (result != CURLE_OK && result != CURLE_QUOTE_ERROR)
+ {
+ if (!this->isCanceled())
+ {
+ this->setStatus(STATUS_CANCELED);
+ delete this->tab;
+ }
+ return;
+ }
+
+ DBEntry::add(this);
+ SkinPlaySound(SOUND_UPCOMPLETE);
+ }
+
+ this->setStatus(STATUS_COMPLETED);
+
+ Utils::createFileDownloadLink(this->ftp->szUrl, this->szSafeFileName, this->szFileLink, sizeof(this->szFileLink));
+ Utils::copyToClipboard(this->szFileLink);
+
+ if (this->tab->bOptAutosend)
+ this->autoSend();
+ else if (this->tab->bOptCopyLink)
+ this->copyLinkToML();
+
+ if (!this->tab->bOptCloseDlg)
+ {
+ this->tab->labelCompleted();
+ this->tab->select();
+ }
+ else
+ this->closeTab();
+}
+
+size_t UploadJob::ReadCallback(void *ptr, size_t size, size_t nmemb, void *arg)
+{
+ UploadJob *job = (UploadJob *)arg;
+
+ if (job->uiTotalSent == 0)
+ job->status = UploadJob::STATUS_UPLOADING;
+
+ if (job->isCanceled())
+ return CURL_READFUNC_ABORT;
+
+ size_t readed = fread(ptr, size, nmemb, job->fp);
+ job->uiSent += readed;
+ job->uiTotalSent += readed;
+ job->updateStats();
+
+ return readed;
+}
+
+void UploadJob::updateStats()
+{
+ if (this->uiSent && (time(NULL) > this->startTS))
+ {
+ double speed = ((double)this->uiSent / 1024)/(time(NULL) - this->startTS);
+ this->avgSpeed = speed;
+ for (int i = 0; i < SIZEOF(this->lastSpeed); i++)
+ {
+ this->avgSpeed += (this->lastSpeed[i] == 0 ? speed : this->lastSpeed[i]);
+ if (i < SIZEOF(this->lastSpeed) - 1)
+ this->lastSpeed[i + 1] = this->lastSpeed[i];
+ }
+
+ this->avgSpeed /= SIZEOF(this->lastSpeed) + 1;
+ this->lastSpeed[0] = speed;
+
+ mir_sntprintf(this->tab->stzSpeed, SIZEOF(this->tab->stzSpeed), _T("%0.1f kB/s"), this->avgSpeed);
+
+ double perc = this->uiFileSize ? ((double)this->uiTotalSent / this->uiFileSize) * 100 : 0;
+ mir_sntprintf(this->tab->stzComplet, SIZEOF(this->tab->stzComplet), _T("%0.1f%% (%d kB/%d kB)"), perc, (int)this->uiTotalSent/1024, (int)this->uiFileSize/1024);
+
+ long s = (this->uiFileSize - this->uiTotalSent) / (long)(this->avgSpeed * 1024);
+ int d = (s / 60 / 60 / 24);
+ int h = (s - d * 60 * 60 * 24) / 60 / 60;
+ int m = (s - d * 60 * 60 * 24 - h * 60 * 60) / 60;
+ s = s - (d * 24 * 60 * 60) - (h * 60 * 60) - (m * 60);
+
+ TCHAR buff[256];
+ if (d > 0) mir_sntprintf(buff, SIZEOF(buff), _T("%dd %02d:%02d:%02d"), d, h, m, s);
+ else mir_sntprintf(buff, SIZEOF(buff), _T("%02d:%02d:%02d"), h, m, s);
+ mir_sntprintf(this->tab->stzRemain, SIZEOF(this->tab->stzRemain), _T("%s (%d kB/%d kB)"), buff, (this->uiFileSize - this->uiTotalSent)/1024, this->uiFileSize/1024);
+
+ this->refreshTab(false);
+ }
+}
+
+void UploadJob::refreshTab(bool bTabChanged)
+{
+ if (uDlg->activeTab == this->tab->index())
+ {
+ GenericJob::refreshTab(bTabChanged);
+
+ ShowWindow(GetDlgItem(uDlg->hwnd, IDC_BTN_CLIPBOARD), this->isCompleted() ? SW_SHOW : SW_HIDE);
+ ShowWindow(GetDlgItem(uDlg->hwnd, IDC_BTN_DOWNLOAD), this->isCompleted() ? SW_SHOW : SW_HIDE);
+ EnableWindow(GetDlgItem(uDlg->hwnd, IDC_BTN_PAUSE), !this->isCompleted() && !this->isConnecting());
+
+ if (this->isCompleted())
+ SetDlgItemText(uDlg->hwnd, IDC_STATUSBAR, TranslateT("COMPLETED"));
+ else if (this->isConnecting())
+ SetDlgItemText(uDlg->hwnd, IDC_STATUSBAR, TranslateT("CONNECTING..."));
+ else if (this->isPaused())
+ SetDlgItemText(uDlg->hwnd, IDC_STATUSBAR, TranslateT("PAUSED"));
+ else if (this->isWaitting())
+ SetDlgItemText(uDlg->hwnd, IDC_STATUSBAR, TranslateT("WAITTING..."));
+ else
+ SetDlgItemText(uDlg->hwnd, IDC_STATUSBAR, TranslateT("UPLOADING..."));
+
+ if (bTabChanged)
+ {
+ if (this->isPaused())
+ {
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PAUSE, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("resume"));
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PAUSE, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Resume"), BATF_TCHAR);
+ }
+ else
+ {
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PAUSE, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("pause"));
+ SendDlgItemMessage(uDlg->hwnd, IDC_BTN_PAUSE, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Pause"), BATF_TCHAR);
+ }
+
+ ShowWindow(GetDlgItem(uDlg->hwnd, IDC_ST_REMAIN), !this->isCompleted() ? SW_SHOW : SW_HIDE);
+ ShowWindow(GetDlgItem(uDlg->hwnd, IDC_UP_COMPLETED), !this->isCompleted() ? SW_SHOW : SW_HIDE);
+ ShowWindow(GetDlgItem(uDlg->hwnd, IDC_UP_REMAIN), !this->isCompleted() ? SW_SHOW : SW_HIDE);
+ ShowWindow(GetDlgItem(uDlg->hwnd, IDC_ED_URL), this->isCompleted() ? SW_SHOW : SW_HIDE);
+ SetDlgItemText(uDlg->hwnd, IDC_ST_COMPLETED, this->isCompleted() ? TranslateT("Download link:") : TranslateT("Completed:"));
+ }
+
+ if (this->isCompleted())
+ {
+ SetDlgItemText(uDlg->hwnd, IDC_UP_SPEED, _T(""));
+ SetDlgItemText(uDlg->hwnd, IDC_UP_COMPLETED, _T(""));
+ SetDlgItemText(uDlg->hwnd, IDC_UP_REMAIN, _T(""));
+
+ SetDlgItemTextA(uDlg->hwnd, IDC_ED_URL, this->szFileLink);
+ SendDlgItemMessage(uDlg->hwnd, IDC_PB_UPLOAD, PBM_SETRANGE32, 0, (LPARAM)100);
+ SendDlgItemMessage(uDlg->hwnd, IDC_PB_UPLOAD, PBM_SETPOS, (WPARAM)100, 0);
+ }
+ else
+ {
+ SetDlgItemText(uDlg->hwnd, IDC_UP_SPEED, this->tab->stzSpeed);
+ SetDlgItemText(uDlg->hwnd, IDC_UP_COMPLETED, this->tab->stzComplet);
+ SetDlgItemText(uDlg->hwnd, IDC_UP_REMAIN, this->tab->stzRemain);
+
+ SendDlgItemMessage(uDlg->hwnd, IDC_PB_UPLOAD, PBM_SETRANGE32, 0, (LPARAM)this->uiFileSize);
+ SendDlgItemMessage(uDlg->hwnd, IDC_PB_UPLOAD, PBM_SETPOS, (WPARAM)this->uiTotalSent, 0);
+ }
+ }
+}
+
+void UploadJob::closeTab()
+{
+ if (!this->isCompleted())
+ {
+ this->pause();
+ if (Utils::msgBox(TranslateT("Do you really want to cancel running upload?"), MB_YESNO | MB_ICONQUESTION) == IDNO)
+ {
+ this->resume();
+ return;
+ }
+
+ this->cancel();
+ }
+
+ delete this->tab;
+}
+
+void UploadJob::closeAllTabs()
+{
+ if (!this->isCompleted())
+ this->cancel();
+
+ delete this->tab;
+}
+
+void UploadJob::createToolTip()
+{
+ TCHAR *server = mir_a2t(this->ftp->szServer);
+ mir_sntprintf(uDlg->stzToolTipText, SIZEOF(uDlg->stzToolTipText),
+ TranslateT("Status: %s\r\nFile: %s\r\nServer: %s"),
+ this->getStatusString(),
+ this->stzFileName,
+ server);
+
+ if (this->tab->stzSpeed[0] && this->tab->stzComplet[0] && this->tab->stzRemain[0])
+ mir_sntprintf(uDlg->stzToolTipText, SIZEOF(uDlg->stzToolTipText),
+ TranslateT("%s\r\nSpeed: %s\r\nCompleted: %s\r\nRemaining: %s"),
+ uDlg->stzToolTipText,
+ this->tab->stzSpeed,
+ this->tab->stzComplet,
+ this->tab->stzRemain);
+
+ FREE(server);
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/job_upload.h b/plugins/FTPFileYM/job_upload.h
new file mode 100644
index 0000000000..fa29e3c640
--- /dev/null
+++ b/plugins/FTPFileYM/job_upload.h
@@ -0,0 +1,84 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+#include "job_generic.h"
+#include "utils.h"
+
+class UploadJob: public GenericJob
+{
+ friend class UploadDialog;
+
+private:
+ static const int MAX_RUNNING_JOBS = 4;
+
+ FILE *fp;
+ CURL *hCurl;
+ char szError[CURL_ERROR_SIZE];
+ char buff[256];
+
+ UINT64 uiFileSize;
+ UINT64 uiTotalSent;
+ UINT64 uiSent;
+ time_t startTS;
+ double lastSpeed[10];
+ double avgSpeed;
+
+ static Mutex mutexJobCount;
+ static int iRunningJobCount;
+
+ char *getChmodString();
+ char *getDelFileString();
+ char *getUrlString();
+ char *getDelUrlString();
+ void copyLinkToML();
+ void autoSend();
+
+ CURL *curlInit(char *szUrl, struct curl_slist *headerList);
+
+ static void waitingThread(void *arg);
+ static size_t ReadCallback(void *ptr, size_t size, size_t nmemb, void *arg);
+ static INT_PTR CALLBACK DlgProcFileExists(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+ bool fileExistsOnServer();
+ void upload();
+ void updateStats();
+
+public:
+ char szFileLink[256];
+ static Event jobDone;
+
+ UploadJob(HANDLE _hContact, int _iFtpNum, EMode _mode);
+ UploadJob(UploadJob *job);
+ UploadJob(PackerJob *job);
+ virtual ~UploadJob();
+
+ virtual void start();
+ virtual void pause();
+ virtual void resume();
+ virtual void cancel();
+ virtual void addToUploadDlg();
+ virtual void pauseHandler();
+
+ virtual void refreshTab(bool bTabChanged);
+ virtual void closeTab();
+ virtual void closeAllTabs();
+ virtual void createToolTip();
+}; \ No newline at end of file
diff --git a/plugins/FTPFileYM/lib/libcurl.dll b/plugins/FTPFileYM/lib/libcurl.dll
new file mode 100644
index 0000000000..0980b9a3e4
--- /dev/null
+++ b/plugins/FTPFileYM/lib/libcurl.dll
Binary files differ
diff --git a/plugins/FTPFileYM/lib/libcurl64.dll b/plugins/FTPFileYM/lib/libcurl64.dll
new file mode 100644
index 0000000000..4efba6f35f
--- /dev/null
+++ b/plugins/FTPFileYM/lib/libcurl64.dll
Binary files differ
diff --git a/plugins/FTPFileYM/libcurl.cpp b/plugins/FTPFileYM/libcurl.cpp
new file mode 100644
index 0000000000..59f95b6de6
--- /dev/null
+++ b/plugins/FTPFileYM/libcurl.cpp
@@ -0,0 +1,73 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "libcurl.h"
+
+LibCurl *LibCurl::instance = NULL;
+LibCurl &curl = LibCurl::getInstance();
+
+BOOL LibCurl::init()
+{
+ HMODULE h = LoadLibrary(_T("libcurl.dll"));
+ if (h == NULL)
+ {
+ h = LoadLibrary(_T("plugins\\libcurl.dll"));
+ if (h == NULL) return FALSE;
+ }
+
+ version_info = (_curl_version_info)GetProcAddress(h, "curl_version_info");
+ if (version_info == NULL)
+ return FALSE;
+
+ PVERSION_INFO info = version_info(CURLVERSION_NOW);
+ if (info == NULL)
+ return FALSE;
+
+ if (info->version_num < PLUGIN_MAKE_VERSION(0, 7, 10, 0))
+ return FALSE;
+
+ if ((info->features & CURL_VERSION_SSL) == 0)
+ return FALSE;
+
+ bool found = false;
+ for (int i = 0; info->protocols[i]; i++)
+ {
+ if (strcmp(info->protocols[i], "ftp") == 0)
+ found = true;
+ }
+
+ if (!found)
+ return FALSE;
+
+ global_init = (_curl_global_init) GetProcAddress(h, "curl_global_init");
+ global_cleanup = (_curl_global_cleanup) GetProcAddress(h, "curl_global_cleanup");
+ easy_init = (_curl_easy_init) GetProcAddress(h, "curl_easy_init");
+ easy_cleanup = (_curl_easy_cleanup) GetProcAddress(h, "curl_easy_cleanup");
+ easy_perform = (_curl_easy_perform) GetProcAddress(h, "curl_easy_perform");
+ easy_pause = (_curl_easy_pause) GetProcAddress(h, "curl_easy_pause");
+ easy_setopt = (_curl_easy_setopt) GetProcAddress(h, "curl_easy_setopt");
+ slist_append = (_curl_slist_append) GetProcAddress(h, "curl_slist_append");
+ slist_free_all = (_curl_slist_free_all) GetProcAddress(h, "curl_slist_free_all");
+
+ return TRUE;
+}
+
+void LibCurl::deinit()
+{
+ delete this;
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/libcurl.h b/plugins/FTPFileYM/libcurl.h
new file mode 100644
index 0000000000..4a8ba6b253
--- /dev/null
+++ b/plugins/FTPFileYM/libcurl.h
@@ -0,0 +1,69 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+
+class LibCurl
+{
+private:
+ typedef CURL *PCURL;
+ typedef struct curl_slist *PCURL_SLIST;
+ typedef curl_version_info_data *PVERSION_INFO;
+
+ typedef CURLcode (__cdecl * _curl_global_init) (long);
+ typedef void (__cdecl * _curl_global_cleanup) (void);
+
+ typedef PCURL (__cdecl * _curl_easy_init) (void);
+ typedef void (__cdecl * _curl_easy_cleanup) (PCURL);
+ typedef CURLcode (__cdecl * _curl_easy_perform) (PCURL);
+ typedef CURLcode (__cdecl * _curl_easy_pause) (PCURL,int);
+ typedef CURLcode (__cdecl * _curl_easy_setopt) (PCURL,CURLoption,...);
+
+ typedef PCURL_SLIST (__cdecl * _curl_slist_append) (PCURL_SLIST,LPCSTR);
+ typedef void (__cdecl * _curl_slist_free_all) (PCURL_SLIST);
+
+ typedef PVERSION_INFO (__cdecl * _curl_version_info) (CURLversion);
+
+ static LibCurl *instance;
+ LibCurl() { };
+ ~LibCurl() { instance = NULL; };
+
+public:
+ _curl_global_init global_init;
+ _curl_global_cleanup global_cleanup;
+ _curl_easy_init easy_init;
+ _curl_easy_cleanup easy_cleanup;
+ _curl_easy_perform easy_perform;
+ _curl_easy_pause easy_pause;
+ _curl_easy_setopt easy_setopt;
+ _curl_slist_append slist_append;
+ _curl_slist_free_all slist_free_all;
+ _curl_version_info version_info;
+
+ static LibCurl &getInstance()
+ {
+ if (!instance)
+ instance = new LibCurl();
+ return *instance;
+ };
+
+ BOOL init();
+ void deinit();
+}; \ No newline at end of file
diff --git a/plugins/FTPFileYM/manager.cpp b/plugins/FTPFileYM/manager.cpp
new file mode 100644
index 0000000000..abf1ec3f0a
--- /dev/null
+++ b/plugins/FTPFileYM/manager.cpp
@@ -0,0 +1,449 @@
+/*
+FTP File plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "common.h"
+#include "job_delete.h"
+#include "manager.h"
+#include "dbentry.h"
+#include "options.h"
+#include "utils.h"
+
+Manager *manDlg = NULL;
+Manager *Manager::instance = NULL;
+
+extern Options &opt;
+extern ServerList &ftpList;
+
+Manager::Manager()
+{ }
+
+Manager::~Manager()
+{
+ for (UINT i = 0; i < this->rootItems.size(); i++)
+ delete this->rootItems[i];
+
+ for (UINT i = 0; i < this->items.size(); i++)
+ delete this->items[i];
+
+ ImageList_Destroy(this->himlStates);
+ DBEntry::cleanupDB();
+
+ instance = NULL;
+ manDlg = NULL;
+}
+
+void Manager::init()
+{
+ if (opt.enabled != 0)
+ {
+ this->hwnd = CreateDialog(hInst, MAKEINTRESOURCE(IDD_DLG_MANAGER), NULL, Manager::ManagerDlgProc);
+ this->hwndFileTree = GetDlgItem(this->hwnd, IDC_FILELIST);
+ this->initImageList();
+ this->fillTree();
+ this->show();
+ }
+ else
+ {
+ Utils::msgBox(TranslateT("You have to fill and enable at least one FTP server in setting."), MB_OK);
+ delete this;
+ }
+}
+
+void Manager::show()
+{
+ ShowWindow(this->hwnd, SW_SHOWNORMAL);
+ BringWindowToTop(this->hwnd);
+}
+
+void Manager::initImageList()
+{
+ char buff[256];
+
+ this->himlStates = ImageList_Create(16, 16, IsWinVerXPPlus() ? ILC_COLOR32 | ILC_MASK : ILC_COLOR8 | ILC_MASK, ServerList::FTP_COUNT + 4, 0);
+ ImageList_AddIcon(himlStates, LoadSkinnedIcon(SKINICON_OTHER_DELETE)); // image index 0 is useless for INDEXTOSTATEIMAGEMASK
+ ImageList_AddIcon(himlStates, LoadSkinnedIcon(SKINICON_OTHER_DELETE));
+ ImageList_AddIcon(himlStates, LoadSkinnedIcon(SKINICON_OTHER_NOTICK));
+ ImageList_AddIcon(himlStates, LoadSkinnedIcon(SKINICON_OTHER_TICK));
+
+ for (int i = 0; i < ServerList::FTP_COUNT; i++)
+ {
+ mir_snprintf(buff, sizeof(buff), "ftp%d", i);
+ ImageList_AddIcon(himlStates, Utils::loadIconEx(buff));
+ }
+
+ TreeView_SetImageList(this->hwndFileTree, himlStates, TVSIL_STATE);
+ TreeView_SetItemHeight(this->hwndFileTree, 18);
+}
+
+void Manager::initRootItems()
+{
+ TVINSERTSTRUCT tvi = {0};
+ tvi.hInsertAfter = TVI_LAST;
+ tvi.item.mask = TVIF_TEXT | TVIF_STATE;
+ tvi.item.stateMask = TVIS_STATEIMAGEMASK | TVIS_EXPANDED | TVIS_BOLD;
+
+ for (UINT i = 0; i < ServerList::FTP_COUNT; i++)
+ {
+ if (ftpList[i]->bEnabled)
+ {
+ tvi.item.pszText = ftpList[i]->stzName;
+ tvi.item.state = INDEXTOSTATEIMAGEMASK(i + 4) | TVIS_EXPANDED | TVIS_BOLD;
+ HTREEITEM hItem = TreeView_InsertItem(this->hwndFileTree, &tvi);
+ this->AddRoot(hItem);
+ }
+ }
+}
+
+void Manager::fillTree()
+{
+ initRootItems();
+
+ TVINSERTSTRUCT tvi = {0};
+ tvi.hInsertAfter = TVI_LAST;
+ tvi.item.mask = TVIF_TEXT | TVIF_STATE;
+ tvi.item.stateMask = TVIS_STATEIMAGEMASK;
+ tvi.item.state = TreeItem::_UNCHECKED();
+
+ Lock *lock = new Lock(DBEntry::mutexDB);
+
+ DBEntry *entry = DBEntry::getFirts();
+ while (entry != NULL)
+ {
+ if ((UINT)entry->iFtpNum < this->rootItems.size())
+ {
+ tvi.item.pszText = mir_a2t(entry->szFileName);
+ tvi.hParent = this->rootItems[entry->iFtpNum]->handle;
+ HTREEITEM hItem = TreeView_InsertItem(this->hwndFileTree, &tvi);
+ this->AddLeaf(hItem, tvi.hParent, entry->fileID);
+ FREE(tvi.item.pszText);
+ }
+
+ entry = DBEntry::getNext(entry);
+ }
+
+ delete lock;
+}
+
+int Manager::indexOf(HTREEITEM handle)
+{
+ for (UINT i = 0; i < this->rootItems.size(); i++)
+ {
+ if (this->rootItems[i]->handle == handle)
+ return i;
+ }
+
+ return -1;
+}
+
+Manager::TreeItem *Manager::getItem(HTREEITEM handle)
+{
+ for (UINT i = 0; i < this->rootItems.size(); i++)
+ {
+ if (this->rootItems[i]->handle == handle)
+ return this->rootItems[i];
+ }
+
+ for (UINT i = 0; i < this->items.size(); i++)
+ {
+ if (this->items[i]->handle == handle)
+ return this->items[i];
+ }
+
+ return NULL;
+}
+
+Manager::TreeItem::TreeItem(HTREEITEM _handle, HTREEITEM _parent, int _id)
+:handle(_handle),parent(_parent),fileID(_id)
+{
+ stzToolTip[0] = 0;
+}
+
+void Manager::TreeItem::setState(UINT state)
+{
+ TVITEM item = {0};
+ item.mask = TVIF_HANDLE | TVIF_STATE;
+ item.stateMask = TVIS_STATEIMAGEMASK;
+ item.hItem = this->handle;
+ TreeView_GetItem(manDlg->hwndFileTree, &item);
+
+ if (TreeItem::_GETSTATE(item.state) != 0)
+ {
+ item.state = state;
+ TreeView_SetItem(manDlg->hwndFileTree, &item);
+ }
+}
+
+UINT Manager::TreeItem::getState()
+{
+ TVITEM item = {0};
+ item.mask = TVIF_HANDLE | TVIF_STATE;
+ item.stateMask = TVIS_STATEIMAGEMASK;
+ item.hItem = this->handle;
+ TreeView_GetItem(manDlg->hwndFileTree, &item);
+ return TreeItem::_GETSTATE(item.state);
+}
+
+void Manager::TreeItem::toggleState()
+{
+ TVITEM item = {0};
+ item.mask = TVIF_HANDLE | TVIF_STATE;
+ item.stateMask = TVIS_STATEIMAGEMASK;
+ item.hItem = this->handle;
+ TreeView_GetItem(manDlg->hwndFileTree, &item);
+
+ UINT state = TreeItem::_GETSTATE(item.state);
+ if (state == STATE_UNCHECKED)
+ item.state = TreeItem::_CHECKED();
+ else if (state == STATE_CHECKED || state == STATE_ERROR)
+ item.state = TreeItem::_UNCHECKED();
+
+ TreeView_SetItem(manDlg->hwndFileTree, &item);
+}
+
+void Manager::TreeItem::remove()
+{
+ TreeView_DeleteItem(manDlg->hwndFileTree, this->handle);
+ DBEntry::remove(this->fileID);
+}
+
+bool Manager::TreeItem::isRoot()
+{
+ return (this->parent != NULL) ? false : true;
+}
+
+
+INT_PTR CALLBACK Manager::ManagerDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch (msg)
+ {
+ case WM_INITDIALOG:
+ {
+ TranslateDialogDefault(hwndDlg);
+
+ SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM)Utils::loadIconEx("main"));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_SELECTALL, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_SELECTALL, BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadSkinnedIcon(SKINICON_OTHER_TICK));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_SELECTALL, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Select All"), BATF_TCHAR);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DESELECTALL, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DESELECTALL, BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadSkinnedIcon(SKINICON_OTHER_NOTICK));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DESELECTALL, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Clear All"), BATF_TCHAR);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DELETEFROMLIST, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DELETEFROMLIST, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("clear"));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DELETEFROMLIST, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Delete from List"), BATF_TCHAR);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DELETE, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DELETE, BM_SETIMAGE, IMAGE_ICON, (LPARAM)Utils::loadIconEx("delete"));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_DELETE, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Delete from FTP"), BATF_TCHAR);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLOSE, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLOSE, BM_SETIMAGE, IMAGE_ICON, (LPARAM)LoadSkinnedIcon(SKINICON_OTHER_EXIT));
+ SendDlgItemMessage(hwndDlg, IDC_BTN_CLOSE, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Close"), BATF_TCHAR);
+
+ return TRUE;
+ }
+ case WM_COMMAND:
+ {
+ if (HIWORD(wParam) == BN_CLICKED)
+ {
+ switch (LOWORD(wParam))
+ {
+ case IDC_BTN_DELETE:
+ {
+ for (UINT i = 0; i < manDlg->items.size(); i++)
+ {
+ TreeItem *item = manDlg->items[i];
+ if (item->getState() == STATE_CHECKED)
+ {
+ DeleteJob *job = new DeleteJob(DBEntry::get(item->fileID), item);
+ job->start();
+ }
+ }
+ break;
+ }
+ case IDC_BTN_DELETEFROMLIST:
+ {
+ for (UINT i = 0; i < manDlg->items.size(); i++)
+ {
+ TreeItem *item = manDlg->items[i];
+ if (item->getState() == STATE_CHECKED)
+ item->remove();
+ }
+ break;
+ }
+ case IDC_BTN_SELECTALL:
+ case IDC_BTN_DESELECTALL:
+ {
+ UINT newState = (LOWORD(wParam) == IDC_BTN_SELECTALL) ?
+ TreeItem::_CHECKED() : TreeItem::_UNCHECKED();
+
+ for (UINT i = 0; i < manDlg->items.size(); i++)
+ manDlg->items[i]->setState(newState);
+
+ break;
+ }
+ case IDC_BTN_CLOSE:
+ {
+ DestroyWindow(hwndDlg);
+ break;
+ }
+ }
+ }
+
+ break;
+ }
+ case WM_NOTIFY:
+ {
+ if (((LPNMHDR)lParam)->idFrom == IDC_FILELIST)
+ {
+ switch(((LPNMHDR)lParam)->code)
+ {
+ case TVN_KEYDOWN:
+ if (((LPNMTVKEYDOWN)lParam)->wVKey != VK_SPACE)
+ break;
+ case NM_CLICK:
+ {
+ HTREEITEM hItem;
+ TVHITTESTINFO hti = {0};
+ hti.pt.x = (short)LOWORD(GetMessagePos());
+ hti.pt.y = (short)HIWORD(GetMessagePos());
+ ScreenToClient(((LPNMHDR)lParam)->hwndFrom, &hti.pt);
+ if (TreeView_HitTest(((LPNMHDR)lParam)->hwndFrom, &hti) || ((LPNMHDR)lParam)->code == TVN_KEYDOWN)
+ {
+ if (((LPNMHDR)lParam)->code == TVN_KEYDOWN)
+ {
+ hti.flags |= TVHT_ONITEMSTATEICON;
+ hItem = TreeView_GetSelection(((LPNMHDR)lParam)->hwndFrom);
+ }
+ else
+ {
+ hItem = hti.hItem;
+ }
+
+ TreeItem *item = manDlg->getItem(hItem);
+ if (item && (hti.flags & TVHT_ONITEMSTATEICON))
+ {
+ if (item->isRoot())
+ {
+ for (UINT i = 0; i < manDlg->items.size(); i++)
+ {
+ if (manDlg->items[i]->parent == item->handle)
+ manDlg->items[i]->toggleState();
+ }
+ }
+ else
+ {
+ item->toggleState();
+ }
+ }
+ }
+ return TRUE;
+ }
+ case NM_RCLICK:
+ {
+ TVHITTESTINFO hti;
+ hti.pt.x = (short)LOWORD(GetMessagePos());
+ hti.pt.y = (short)HIWORD(GetMessagePos());
+ ScreenToClient(manDlg->hwndFileTree, &hti.pt);
+ if (TreeView_HitTest(manDlg->hwndFileTree, &hti))
+ {
+ HTREEITEM hItem = hti.hItem;
+ TreeItem *item = manDlg->getItem(hItem);
+ if (item && !item->isRoot())
+ {
+ POINT pt;
+ GetCursorPos(&pt);
+ SetForegroundWindow(hwndDlg);
+ HMENU hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_MENU_MANAGER));
+ if (hMenu)
+ {
+ HMENU hPopupMenu = GetSubMenu(hMenu, 0);
+ CallService(MS_LANGPACK_TRANSLATEMENU, (WPARAM)hPopupMenu, 0);
+ int command = TrackPopupMenu(hPopupMenu, TPM_LEFTALIGN | TPM_RETURNCMD, pt.x, pt.y, 0, hwndDlg, NULL);
+ switch (command)
+ {
+
+ case IDM_DELETEFROMLIST:
+ {
+ item->remove();
+ break;
+ }
+ case IDM_DELETEFROMFTP:
+ {
+ DeleteJob *job = new DeleteJob(DBEntry::get(item->fileID), item);
+ job->start();
+ break;
+ }
+ case IDM_COPYLINK:
+ case IDM_DOWNLOAD:
+ {
+ int ftpNum = manDlg->indexOf(item->parent);
+ if (ftpNum != -1)
+ {
+ char buff[256];
+
+ DBEntry *entry = DBEntry::get(item->fileID);
+ Utils::createFileDownloadLink(ftpList[ftpNum]->szUrl, entry->szFileName, buff, sizeof(buff));
+ delete entry;
+
+ if (command == IDM_COPYLINK)
+ Utils::copyToClipboard(buff);
+ else
+ ShellExecuteA(NULL, "open", buff, NULL, NULL, SW_SHOWNORMAL);
+ }
+ break;
+ }
+ }
+ DestroyMenu(hMenu);
+ }
+ }
+ }
+ return TRUE;
+ }
+ case TVN_GETINFOTIP:
+ {
+ NMTVGETINFOTIP *tvInfoTip = (NMTVGETINFOTIP *)lParam;
+ TreeItem *item = manDlg->getItem(tvInfoTip->hItem);
+
+ if (item)
+ {
+ if (item->stzToolTip[0])
+ {
+ _tcsncpy(tvInfoTip->pszText, item->stzToolTip, tvInfoTip->cchTextMax - 1);
+ tvInfoTip->pszText[tvInfoTip->cchTextMax - 1] = 0;
+ }
+ }
+
+ return TRUE;
+ }
+ }
+ }
+
+ break;
+ }
+ case WM_CLOSE:
+ {
+ DestroyWindow(hwndDlg);
+ return TRUE;
+ }
+ case WM_DESTROY:
+ {
+ delete manDlg;
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/manager.h b/plugins/FTPFileYM/manager.h
new file mode 100644
index 0000000000..ef5ba0ddb3
--- /dev/null
+++ b/plugins/FTPFileYM/manager.h
@@ -0,0 +1,88 @@
+/*
+FTP File plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+
+class Manager
+{
+private:
+ enum EState
+ {
+ STATE_ERROR = 1,
+ STATE_UNCHECKED,
+ STATE_CHECKED
+ };
+
+ static Manager *instance;
+
+ HWND hwnd;
+ HWND hwndFileTree;
+ HIMAGELIST himlStates;
+
+ Manager();
+
+ void show();
+ void initRootItems();
+ void initImageList();
+ void fillTree();
+
+public:
+ class TreeItem
+ {
+ public:
+ HTREEITEM handle;
+ HTREEITEM parent;
+ TCHAR stzToolTip[256];
+ int fileID;
+
+ TreeItem(HTREEITEM _handle, HTREEITEM _parent, int _id);
+ void setState(UINT state);
+ UINT getState();
+ void toggleState();
+ void remove();
+ bool isRoot();
+
+ static UINT _GETSTATE(UINT s) { return ((s & TVIS_STATEIMAGEMASK) >> 12); }
+ static UINT _ERROR() { return INDEXTOSTATEIMAGEMASK(STATE_ERROR); }
+ static UINT _UNCHECKED() { return INDEXTOSTATEIMAGEMASK(STATE_UNCHECKED); }
+ static UINT _CHECKED() { return INDEXTOSTATEIMAGEMASK(STATE_CHECKED); }
+ };
+
+ vector<TreeItem *> rootItems;
+ vector<TreeItem *> items;
+
+ ~Manager();
+
+ void AddRoot(HTREEITEM h) { rootItems.push_back(new TreeItem(h,NULL,0)); }
+ void AddLeaf(HTREEITEM h, HTREEITEM p, int id) { items.push_back(new TreeItem(h,p,id)); }
+
+ static Manager *getInstance()
+ {
+ if (!instance)
+ instance = new Manager();
+ return instance;
+ };
+
+ void init();
+ int indexOf(HTREEITEM handle);
+ TreeItem *getItem(HTREEITEM handle);
+
+ static INT_PTR CALLBACK ManagerDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+};
diff --git a/plugins/FTPFileYM/mir_db.cpp b/plugins/FTPFileYM/mir_db.cpp
new file mode 100644
index 0000000000..1a466f7863
--- /dev/null
+++ b/plugins/FTPFileYM/mir_db.cpp
@@ -0,0 +1,198 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "mir_db.h"
+
+int DB::setByte(HANDLE hContact, char *szModule, char *szSetting, int iValue)
+{
+ return DBWriteContactSettingByte(hContact, szModule, szSetting, iValue);
+}
+
+int DB::setByteF(HANDLE hContact, char *szModule, char *szSetting, int id, int iValue)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return setByte(hContact, szModule, formSet, iValue);
+}
+
+int DB::setWord(HANDLE hContact, char *szModule, char *szSetting, int iValue)
+{
+ return DBWriteContactSettingWord(hContact, szModule, szSetting, iValue);
+}
+
+int DB::setWordF(HANDLE hContact, char *szModule, char *szSetting, int id, int iValue)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return setWord(hContact, szModule, formSet, iValue);
+}
+
+int DB::setDword(HANDLE hContact, char *szModule, char *szSetting, int iValue)
+{
+ return DBWriteContactSettingDword(hContact, szModule, szSetting, iValue);
+}
+
+int DB::setDwordF(HANDLE hContact, char *szModule, char *szSetting, int id, int iValue)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return setDword(hContact, szModule, formSet, iValue);
+}
+
+int DB::setAString(HANDLE hContact, char *szModule, char *szSetting, char *szValue)
+{
+ return DBWriteContactSettingString(hContact, szModule, szSetting, szValue);
+}
+
+int DB::setAStringF(HANDLE hContact, char *szModule, char *szSetting, int id, char *szValue)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return setAString(hContact, szModule, formSet, szValue);
+}
+
+int DB::setString(HANDLE hContact, char *szModule, char *szSetting, TCHAR *stzValue)
+{
+ return DBWriteContactSettingTString(hContact, szModule, szSetting, stzValue);
+}
+
+int DB::setStringF(HANDLE hContact, char *szModule, char *szSetting, int id, TCHAR *stzValue)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return setString(hContact, szModule, formSet, stzValue);
+}
+
+int DB::setCryptedString(HANDLE hContact, char *szModule, char *szSetting, char *szValue)
+{
+ char buff[256];
+ strcpy(buff, szValue);
+ CallService(MS_DB_CRYPT_ENCODESTRING, (WPARAM)sizeof(buff), (LPARAM)buff);
+ return setAString(hContact, szModule, szSetting, buff);
+}
+
+int DB::getByte(HANDLE hContact, char *szModule, char *szSetting, int iErrorValue)
+{
+ return DBGetContactSettingByte(hContact, szModule, szSetting, iErrorValue);
+}
+
+int DB::getByteF(HANDLE hContact, char *szModule, char *szSetting, int id, int iErrorValue)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return getByte(hContact, szModule, formSet, iErrorValue);
+}
+
+int DB::getWord(HANDLE hContact, char *szModule, char *szSetting, int iErrorValue)
+{
+ return DBGetContactSettingWord(hContact, szModule, szSetting, iErrorValue);
+}
+
+int DB::getWordF(HANDLE hContact, char *szModule, char *szSetting, int id, int iErrorValue)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return getWord(hContact, szModule, formSet, iErrorValue);
+}
+
+int DB::getDword(HANDLE hContact, char *szModule, char *szSetting, int iErrorValue)
+{
+ return DBGetContactSettingDword(hContact, szModule, szSetting, iErrorValue);
+}
+
+int DB::getDwordF(HANDLE hContact, char *szModule, char *szSetting, int id, int iErrorValue)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return getDword(hContact, szModule, formSet, iErrorValue);
+}
+
+int DB::getAString(HANDLE hContact, char *szModule, char *szSetting, char *buff)
+{
+ DBVARIANT dbv;
+ if (!DBGetContactSettingString(hContact, szModule, szSetting, &dbv))
+ {
+ strcpy(buff, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ return 0;
+ }
+
+ buff[0] = 0;
+ return 1;
+}
+
+int DB::getAStringF(HANDLE hContact, char *szModule, char *szSetting, int id, char *buff)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return getAString(hContact, szModule, formSet, buff);
+}
+
+int DB::getString(HANDLE hContact, char *szModule, char *szSetting, TCHAR *buff)
+{
+ DBVARIANT dbv;
+ if (!DBGetContactSettingTString(hContact, szModule, szSetting, &dbv))
+ {
+ _tcscpy(buff, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ return 0;
+ }
+
+ buff[0] = 0;
+ return 1;
+}
+
+int DB::getStringF(HANDLE hContact, char *szModule, char *szSetting, int id, TCHAR *buff)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return getString(hContact, szModule, formSet, buff);
+}
+
+int DB::getCryptedString(HANDLE hContact, char *szModule, char *szSetting, char *szValue)
+{
+ char buff[256];
+ if (!getAString(hContact, szModule, szSetting, buff))
+ {
+ CallService(MS_DB_CRYPT_DECODESTRING, (WPARAM)sizeof(buff), (LPARAM)buff);
+ strcpy(szValue, buff);
+ return 0;
+ }
+
+ szValue[0] = 0;
+ return 1;
+}
+
+int DB::deleteSetting(HANDLE hContact, char *szModule, char *szSetting)
+{
+ return DBDeleteContactSetting(hContact, szModule, szSetting);
+}
+
+int DB::deleteSettingF(HANDLE hContact, char *szModule, char *szSetting, int id)
+{
+ char formSet[256];
+ mir_snprintf(formSet, sizeof(formSet), szSetting, id);
+ return deleteSetting(hContact, szModule, formSet);
+}
+
+char *DB::getProto(HANDLE hContact)
+{
+ char *szProto = (char *)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0);
+ return ((INT_PTR)szProto != CALLSERVICE_NOTFOUND) ? szProto : NULL;
+}
+
diff --git a/plugins/FTPFileYM/mir_db.h b/plugins/FTPFileYM/mir_db.h
new file mode 100644
index 0000000000..df2004c86d
--- /dev/null
+++ b/plugins/FTPFileYM/mir_db.h
@@ -0,0 +1,57 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+
+class DB
+{
+public:
+ static int setByte(HANDLE hContact, char *szModule, char *szSetting, int iValue);
+ static int setByteF(HANDLE hContact, char *szModule, char *szSetting, int id, int iValue);
+ static int setWord(HANDLE hContact, char *szModule, char *szSetting, int iValue);
+ static int setWordF(HANDLE hContact, char *szModule, char *szSetting, int id, int iValue);
+ static int setDword(HANDLE hContact, char *szModule, char *szSetting, int iValue);
+ static int setDwordF(HANDLE hContact, char *szModule, char *szSetting, int id, int iValue);
+
+ static int setAString(HANDLE hContact, char *szModule, char *szSetting, char *szValue);
+ static int setAStringF(HANDLE hContact, char *szModule, char *szSetting, int id, char *szValue);
+ static int setString(HANDLE hContact, char *szModule, char *szSetting, TCHAR *stzValue);
+ static int setStringF(HANDLE hContact, char *szModule, char *szSetting, int id, TCHAR *stzValue);
+
+ static int getByte(HANDLE hContact, char *szModule, char *szSetting, int iErrorValue);
+ static int getByteF(HANDLE hContact, char *szModule, char *szSetting, int id, int iErrorValue = -1);
+ static int getWord(HANDLE hContact, char *szModule, char *szSetting, int iErrorValue = -1);
+ static int getWordF(HANDLE hContact, char *szModule, char *szSetting, int id, int iErrorValue = -1);
+ static int getDword(HANDLE hContact, char *szModule, char *szSetting, int iErrorValue = -1);
+ static int getDwordF(HANDLE hContact, char *szModule, char *szSetting, int id, int iErrorValue = -1);
+
+ static int getAString(HANDLE hContact, char *szModule, char *szSetting, char *buff);
+ static int getAStringF(HANDLE hContact, char *szModule, char *szSetting, int id, char *buff);
+ static int getString(HANDLE hContact, char *szModule, char *szSetting, TCHAR *buff);
+ static int getStringF(HANDLE hContact, char *szModule, char *szSetting, int id, TCHAR *buff);
+
+ static int setCryptedString(HANDLE hContact, char *szModule, char *szSetting, char *szValue);
+ static int getCryptedString(HANDLE hContact, char *szModule, char *szSetting, char *szValue);
+
+ static int deleteSetting(HANDLE hContact, char *szModule, char *szSetting);
+ static int deleteSettingF(HANDLE hContact, char *szModule, char *szSetting, int id);
+
+ static char *getProto(HANDLE hContact);
+}; \ No newline at end of file
diff --git a/plugins/FTPFileYM/options.cpp b/plugins/FTPFileYM/options.cpp
new file mode 100644
index 0000000000..65700e1744
--- /dev/null
+++ b/plugins/FTPFileYM/options.cpp
@@ -0,0 +1,310 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "deletetimer.h"
+#include "options.h"
+
+Options *Options::instance = NULL;
+Options &opt = Options::getInstance();
+
+extern DeleteTimer &deleteTimer;
+extern ServerList &ftpList;
+
+extern void PrebuildMainMenu();
+
+void Options::deinit()
+{
+ delete this;
+}
+
+void Options::loadOptions()
+{
+ enabled = DB::getByte(0, MODULE, "Enabled", 0);
+ selected = DB::getByte(0, MODULE, "Selected", 0);
+ defaultFTP = DB::getByte(0, MODULE, "Default", 0);
+ bAutosend = DB::getByte(0, MODULE, "Autosend", 0) ? true : false;
+ bCloseDlg = DB::getByte(0, MODULE, "CloseDlg", 0) ? true : false;
+ bCopyLink = DB::getByte(0, MODULE, "CopyLink", 1) ? true : false;
+ bUseSubmenu = DB::getByte(0, MODULE, "UseSubmenu", 1) ? true : false;
+ bHideInactive = DB::getByte(0, MODULE, "HideInactive", 1) ? true : false;
+ bAutoDelete = DB::getByte(0, MODULE, "DeleteTimer", 0) ? true : false;
+ iDeleteTime = DB::getDword(0, MODULE, "AutoDeleteTime", 60);
+ timeRange = (ETimeRange)DB::getByte(0, MODULE, "TimeRange", TR_MINUTES);
+ iCompressionLevel = DB::getByte(0, MODULE, "CompressionLevel", 6);
+ bSetZipName = DB::getByte(0, MODULE, "SetZipName", 0) ? true : false;
+}
+
+void Options::saveOptions() const
+{
+ DB::setByte(0, MODULE, "Autosend", bAutosend ? 1 : 0);
+ DB::setByte(0, MODULE, "CopyLink", bCopyLink ? 1 : 0);
+ DB::setByte(0, MODULE, "UseSubmenu", bUseSubmenu ? 1 : 0);
+ DB::setByte(0, MODULE, "HideInactive", bHideInactive ? 1 : 0);
+ DB::setByte(0, MODULE, "CloseDlg", bCloseDlg ? 1 : 0);
+ DB::setByte(0, MODULE, "DeleteTimer", bAutoDelete ? 1 : 0);
+ DB::setDword(0, MODULE, "AutoDeleteTime", iDeleteTime);
+ DB::setByte(0, MODULE, "TimeRange", (int)timeRange);
+ DB::setByte(0, MODULE, "CompressionLevel", iCompressionLevel);
+ DB::setByte(0, MODULE, "SetZipName", bSetZipName ? 1 : 0);
+}
+
+void Options::enableItems(HWND hwndDlg, bool state)
+{
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DEFAULT), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_PROTOLIST), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_SERVER), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_USER), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_PASSWORD), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DIR), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_URL), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_PORT), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_CHMOD), state);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_PASSIVE), state);
+}
+
+INT_PTR CALLBACK Options::DlgProcOptsAccounts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch(msg)
+ {
+ case WM_INITDIALOG:
+ {
+ TranslateDialogDefault(hwndDlg);
+
+ for (int i = 0; i < ServerList::FTP_COUNT; i++)
+ ComboBox_AddString(GetDlgItem(hwndDlg, IDC_FTPLIST), ftpList[i]->stzName);
+
+ ComboBox_SetCurSel(GetDlgItem(hwndDlg, IDC_FTPLIST), opt.selected);
+ CheckDlgButton(hwndDlg, IDC_DEFAULT, opt.selected == opt.defaultFTP);
+
+ ServerList::FTP *ftp = ftpList.getSelected();
+ ComboBox_AddString(GetDlgItem(hwndDlg, IDC_PROTOLIST), TranslateT("FTP (Standard)"));
+ ComboBox_AddString(GetDlgItem(hwndDlg, IDC_PROTOLIST), TranslateT("FTP+SSL (Explicit)"));
+ ComboBox_AddString(GetDlgItem(hwndDlg, IDC_PROTOLIST), TranslateT("FTP+SSL (Implicit)"));
+ ComboBox_AddString(GetDlgItem(hwndDlg, IDC_PROTOLIST), TranslateT("SFTP (Secure FTP over SSH)"));
+ ComboBox_SetCurSel(GetDlgItem(hwndDlg, IDC_PROTOLIST), ftp->ftpProto);
+
+ SetDlgItemTextA(hwndDlg, IDC_SERVER, ftp->szServer);
+ SetDlgItemTextA(hwndDlg, IDC_USER, ftp->szUser);
+ SetDlgItemTextA(hwndDlg, IDC_PASSWORD, ftp->szPass);
+ SetDlgItemTextA(hwndDlg, IDC_DIR, ftp->szDir);
+ SetDlgItemTextA(hwndDlg, IDC_URL, ftp->szUrl);
+ SetDlgItemTextA(hwndDlg, IDC_CHMOD, ftp->szChmod);
+ SetDlgItemInt (hwndDlg, IDC_PORT, ftp->iPort, FALSE);
+ CheckDlgButton(hwndDlg, IDC_PASSIVE, ftp->bPassive);
+
+ if (ftpList.getSelected()->bEnabled)
+ {
+ CheckDlgButton(hwndDlg, IDC_ENABLED, 1);
+ }
+ else
+ {
+ CheckDlgButton(hwndDlg, IDC_ENABLED, 0);
+ enableItems(hwndDlg, false);
+ }
+
+ return TRUE;
+ }
+ case WM_COMMAND:
+ {
+ if (HIWORD(wParam) == BN_CLICKED)
+ {
+ if (LOWORD(wParam) == IDC_ENABLED)
+ enableItems(hwndDlg, IsDlgButtonChecked(hwndDlg, IDC_ENABLED) == BST_CHECKED ? true : false);
+ }
+ else if (HIWORD(wParam) == CBN_SELCHANGE)
+ {
+ if (LOWORD(wParam) == IDC_FTPLIST)
+ {
+ opt.selected = (BYTE)ComboBox_GetCurSel(GetDlgItem(hwndDlg, IDC_FTPLIST));
+ CheckDlgButton(hwndDlg, IDC_DEFAULT, opt.selected == opt.defaultFTP);
+
+ ServerList::FTP *ftp = ftpList.getSelected();
+ SendDlgItemMessage(hwndDlg, IDC_PROTOLIST, CB_SETCURSEL, ftp->ftpProto, 0);
+ SetDlgItemTextA(hwndDlg, IDC_SERVER, ftp->szServer);
+ SetDlgItemTextA(hwndDlg, IDC_USER, ftp->szUser);
+ SetDlgItemTextA(hwndDlg, IDC_PASSWORD, ftp->szPass);
+ SetDlgItemTextA(hwndDlg, IDC_DIR, ftp->szDir);
+ SetDlgItemTextA(hwndDlg, IDC_URL, ftp->szUrl);
+ SetDlgItemTextA(hwndDlg, IDC_CHMOD, ftp->szChmod);
+ SetDlgItemInt (hwndDlg, IDC_PORT, ftp->iPort, FALSE);
+ CheckDlgButton(hwndDlg, IDC_PASSIVE, ftp->bPassive);
+
+ if (ftpList.getSelected()->bEnabled)
+ {
+ CheckDlgButton(hwndDlg, IDC_ENABLED, 1);
+ enableItems(hwndDlg, true);
+ }
+ else
+ {
+ CheckDlgButton(hwndDlg, IDC_ENABLED, 0);
+ enableItems(hwndDlg, false);
+ }
+ }
+ else if (LOWORD(wParam) == IDC_PROTOLIST)
+ {
+ int sel = ComboBox_GetCurSel(GetDlgItem(hwndDlg, IDC_PROTOLIST));
+ switch (sel)
+ {
+ case ServerList::FTP::FT_STANDARD:
+ case ServerList::FTP::FT_SSL_EXPLICIT: SetDlgItemInt(hwndDlg, IDC_PORT, 21, FALSE); break;
+ case ServerList::FTP::FT_SSL_IMPLICIT: SetDlgItemInt(hwndDlg, IDC_PORT, 990, FALSE); break;
+ case ServerList::FTP::FT_SSH: SetDlgItemInt(hwndDlg, IDC_PORT, 22, FALSE); break;
+ }
+ }
+ }
+
+ if (HIWORD(wParam)==BN_CLICKED || HIWORD(wParam)==EN_CHANGE || HIWORD(wParam)==CBN_SELCHANGE || HIWORD(wParam)==CBN_EDITCHANGE)
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+
+ return TRUE;
+ }
+ case WM_NOTIFY:
+ {
+ if (((LPNMHDR)lParam)->code == PSN_APPLY)
+ {
+ if (IsDlgButtonChecked(hwndDlg, IDC_ENABLED))
+ opt.enabled |= (1 << opt.selected);
+ else
+ opt.enabled &= ~(1 << opt.selected);
+
+ if (IsDlgButtonChecked(hwndDlg, IDC_DEFAULT))
+ opt.defaultFTP = opt.selected;
+
+ ServerList::FTP *ftp = ftpList.getSelected();
+ GetDlgItemText(hwndDlg, IDC_FTPLIST, ftp->stzName, SIZEOF(ftp->stzName));
+ GetDlgItemTextA(hwndDlg, IDC_SERVER, ftp->szServer, SIZEOF(ftp->szServer));
+ GetDlgItemTextA(hwndDlg, IDC_USER, ftp->szUser, SIZEOF(ftp->szUser));
+ GetDlgItemTextA(hwndDlg, IDC_PASSWORD, ftp->szPass, SIZEOF(ftp->szPass));
+ GetDlgItemTextA(hwndDlg, IDC_DIR, ftp->szDir, SIZEOF(ftp->szDir));
+ GetDlgItemTextA(hwndDlg, IDC_URL, ftp->szUrl, SIZEOF(ftp->szUrl));
+ GetDlgItemTextA(hwndDlg, IDC_CHMOD, ftp->szChmod, SIZEOF(ftp->szChmod));
+
+ ftp->ftpProto = (ServerList::FTP::EProtoType)ComboBox_GetCurSel(GetDlgItem(hwndDlg, IDC_PROTOLIST));
+ ftp->iPort = GetDlgItemInt(hwndDlg, IDC_PORT, 0, 0);
+ ftp->bPassive = IsDlgButtonChecked(hwndDlg, IDC_PASSIVE) ? true : false;
+
+ ComboBox_DeleteString(GetDlgItem(hwndDlg, IDC_FTPLIST), opt.selected);
+ ComboBox_InsertString(GetDlgItem(hwndDlg, IDC_FTPLIST), opt.selected, ftp->stzName);
+ ComboBox_SetCurSel(GetDlgItem(hwndDlg, IDC_FTPLIST), opt.selected);
+
+ ftpList.saveToDb();
+ PrebuildMainMenu();
+ }
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+INT_PTR CALLBACK Options::DlgProcOptsAdvanced(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch(msg)
+ {
+ case WM_INITDIALOG:
+ {
+ TranslateDialogDefault(hwndDlg);
+
+ CheckDlgButton(hwndDlg, IDC_URL_AUTOSEND, opt.bAutosend ? 1 : 0);
+ CheckDlgButton(hwndDlg, IDC_URL_COPYTOML, opt.bCopyLink ? 1 : 0);
+ CheckDlgButton(hwndDlg, IDC_USESUBMENU, opt.bUseSubmenu ? 1 : 0);
+ CheckDlgButton(hwndDlg, IDC_HIDEINACTIVE, opt.bHideInactive ? 1 : 0);
+ CheckDlgButton(hwndDlg, IDC_CLOSEDLG, opt.bCloseDlg ? 1 : 0);
+ CheckDlgButton(hwndDlg, IDC_AUTODELETE, opt.bAutoDelete ? 1 : 0);
+
+ SendDlgItemMessage(hwndDlg, IDC_LEVEL_SPIN, UDM_SETRANGE, 0, (LPARAM)MAKELONG(9, 0));
+ SetDlgItemInt(hwndDlg, IDC_LEVEL, opt.iCompressionLevel, FALSE);
+ CheckDlgButton(hwndDlg, IDC_SETZIPNAME, opt.bSetZipName ? 1 : 0);
+
+ SendDlgItemMessage(hwndDlg, IDC_DELETETIME_SPIN, UDM_SETRANGE, 0, (LPARAM)MAKELONG(UD_MAXVAL, 1));
+ SetDlgItemInt(hwndDlg, IDC_DELETETIME, opt.iDeleteTime, FALSE);
+
+ SendDlgItemMessage(hwndDlg, IDC_RANGE, CB_ADDSTRING, 0, (LPARAM)TranslateT("minutes"));
+ SendDlgItemMessage(hwndDlg, IDC_RANGE, CB_ADDSTRING, 0, (LPARAM)TranslateT("hours"));
+ SendDlgItemMessage(hwndDlg, IDC_RANGE, CB_ADDSTRING, 0, (LPARAM)TranslateT("days"));
+ SendDlgItemMessage(hwndDlg, IDC_RANGE, CB_SETCURSEL, (int)opt.timeRange, 0);
+
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DELETETIME), opt.bAutoDelete);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_RANGE), opt.bAutoDelete);
+
+ return TRUE;
+ }
+ case WM_COMMAND:
+ {
+ if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) == IDC_AUTODELETE)
+ {
+ EnableWindow(GetDlgItem(hwndDlg, IDC_DELETETIME), IsDlgButtonChecked(hwndDlg, IDC_AUTODELETE));
+ EnableWindow(GetDlgItem(hwndDlg, IDC_RANGE), IsDlgButtonChecked(hwndDlg, IDC_AUTODELETE));
+ }
+
+ if (HIWORD(wParam) == BN_CLICKED || HIWORD(wParam) == EN_CHANGE)
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+
+ return TRUE;
+ }
+ case WM_NOTIFY:
+ {
+ if(((LPNMHDR)lParam)->code == PSN_APPLY)
+ {
+ opt.bAutosend = IsDlgButtonChecked(hwndDlg, IDC_URL_AUTOSEND) ? true : false;
+ opt.bCopyLink = IsDlgButtonChecked(hwndDlg, IDC_URL_COPYTOML) ? true : false;
+ opt.bUseSubmenu = IsDlgButtonChecked(hwndDlg, IDC_USESUBMENU) ? true : false;
+ opt.bHideInactive = IsDlgButtonChecked(hwndDlg, IDC_HIDEINACTIVE) ? true : false;
+ opt.bCloseDlg = IsDlgButtonChecked(hwndDlg, IDC_CLOSEDLG) ? true : false;
+ opt.bAutoDelete = IsDlgButtonChecked(hwndDlg, IDC_AUTODELETE) ? true : false;
+ opt.iCompressionLevel = GetDlgItemInt(hwndDlg, IDC_LEVEL, 0, FALSE);
+ opt.bSetZipName = IsDlgButtonChecked(hwndDlg, IDC_SETZIPNAME) ? true : false;
+ opt.iDeleteTime = GetDlgItemInt(hwndDlg, IDC_DELETETIME, 0, FALSE);
+ opt.timeRange = (Options::ETimeRange)SendDlgItemMessage(hwndDlg, IDC_RANGE, CB_GETCURSEL, 0, 0);
+ opt.saveOptions();
+
+ if (opt.bAutoDelete) deleteTimer.start();
+ else deleteTimer.stop();
+
+ PrebuildMainMenu();
+ }
+ return TRUE;
+ }
+ }
+
+ return FALSE;
+}
+
+int Options::InitOptions(WPARAM wParam, LPARAM lParam)
+{
+ OPTIONSDIALOGPAGE odp = {0};
+
+ odp.cbSize = sizeof(odp);
+ odp.position = 100000000;
+ odp.hInstance = hInst;
+ odp.flags = ODPF_BOLDGROUPS | ODPF_TCHAR;
+ odp.ptszTitle = LPGENT("FTP File");
+ odp.ptszGroup = LPGENT("Services");
+
+ odp.ptszTab = LPGENT("Accounts");
+ odp.pszTemplate = MAKEINTRESOURCEA(IDD_OPT_FTPFILE);
+ odp.pfnDlgProc = Options::DlgProcOptsAccounts;
+ CallService(MS_OPT_ADDPAGE, wParam, (LPARAM)&odp);
+
+ odp.ptszTab = LPGENT("Advanced");
+ odp.pszTemplate = MAKEINTRESOURCEA(IDD_OPT_ADVANCED);
+ odp.pfnDlgProc = Options::DlgProcOptsAdvanced;
+ CallService(MS_OPT_ADDPAGE, wParam, (LPARAM)&odp);
+
+ return 0;
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/options.h b/plugins/FTPFileYM/options.h
new file mode 100644
index 0000000000..5def96e1e5
--- /dev/null
+++ b/plugins/FTPFileYM/options.h
@@ -0,0 +1,69 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+#include "serverlist.h"
+
+class Options
+{
+private:
+ static Options *instance;
+
+ Options() { };
+ ~Options() { instance = NULL; };
+
+public:
+ enum ETimeRange
+ {
+ TR_MINUTES= 0,
+ TR_HOURS,
+ TR_DAYS
+ };
+
+ BYTE enabled;
+ BYTE selected;
+ BYTE defaultFTP;
+ bool bCloseDlg;
+ bool bCopyLink;
+ bool bAutosend;
+ bool bUseSubmenu;
+ bool bHideInactive;
+ bool bAutoDelete;
+ int iCompressionLevel;
+ bool bSetZipName;
+ int iDeleteTime;
+ ETimeRange timeRange;
+
+ static Options &getInstance()
+ {
+ if (!instance)
+ instance = new Options();
+ return *instance;
+ };
+
+ static void enableItems(HWND hwndDlg, bool state);
+ static int InitOptions(WPARAM wParam, LPARAM lParam);
+ static INT_PTR CALLBACK DlgProcOptsAccounts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+ static INT_PTR CALLBACK DlgProcOptsAdvanced(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+ void deinit();
+ void loadOptions();
+ void saveOptions() const;
+}; \ No newline at end of file
diff --git a/plugins/FTPFileYM/resource.h b/plugins/FTPFileYM/resource.h
new file mode 100644
index 0000000000..17a227010b
--- /dev/null
+++ b/plugins/FTPFileYM/resource.h
@@ -0,0 +1,101 @@
+//{{NO_DEPENDENCIES}}
+// Microsoft Visual C++ generated include file.
+// Used by ftpfile.rc
+//
+#define IDD_DLG_UPLOAD 101
+#define IDD_OPT_FTPFILE 103
+#define IDD_OPT_ADVANCED 104
+#define IDR_MENU_UPLOAD 106
+#define IDI_PAUSE 110
+#define IDI_RESUME 111
+#define IDD_DLG_MANAGER 113
+#define IDR_MENU_MANAGER 115
+#define IDI_CLEAR 116
+#define IDI_DELETE 117
+#define IDD_DLG_NAME 118
+#define IDD_DLG_FILEEXISTS 119
+#define IDC_TAB 1001
+#define IDC_PB_UPLOAD 1002
+#define IDC_ST_FILE 1003
+#define IDC_ST_SPEED 1004
+#define IDC_ST_COMPLETED 1005
+#define IDC_ST_REMAIN 1006
+#define IDC_UP_FILE 1007
+#define IDC_UP_COMPLETED 1008
+#define IDC_UP_SPEED 1009
+#define IDC_UP_REMAIN 1010
+#define IDC_ST_CONTACT 1011
+#define IDC_BTN_CLOSE 1012
+#define IDC_BTN_CLIPBOARD 1013
+#define IDC_BTN_OPTIONS 1014
+#define IDC_UP_CONTACT 1015
+#define IDC_ED_URL 1016
+#define IDC_BTN_FILEMANAGER 1017
+#define IDC_BTN_PAUSE 1018
+#define IDC_ST_SERVER 1019
+#define IDC_UP_SERVER 1020
+#define IDC_SERVER 1021
+#define IDC_BTN_PROTO 1021
+#define IDC_USER 1022
+#define IDC_BTN_DOWNLOAD 1022
+#define IDC_PASSWORD 1023
+#define IDC_DIR 1024
+#define IDC_URL 1025
+#define IDC_PORT 1026
+#define IDC_CHMOD 1027
+#define IDC_URL_CLOSEDLG 1028
+#define IDC_CLOSEDLG 1028
+#define IDC_URL_COPYTOML 1029
+#define IDC_URL_AUTOSEND 1030
+#define IDC_FTPLIST 1031
+#define IDC_AUTODELETE 1031
+#define IDC_ENABLED 1032
+#define IDC_PASSIVE 1033
+#define IDC_USESUBMENU 1034
+#define IDC_HIDEINACTIVE 1035
+#define IDC_FILELIST 1040
+#define IDC_BTN_SELECTALL 1041
+#define IDC_BTN_DESELECTALL 1042
+#define IDC_BTN_DELETE 1043
+#define IDC_DELETETIME 1043
+#define IDC_BTN_DELETEFROMLIST 1044
+#define IDC_LEVEL 1044
+#define IDC_DELETETIME_SPIN 1045
+#define IDC_RANGE 1046
+#define IDC_PROTOLIST 1047
+#define IDC_LEVEL_SPIN 1047
+#define IDC_SETZIPNAME 1048
+#define IDC_NAME 1049
+#define IDC_STATUSBAR 1050
+#define IDC_DEFAULT 1052
+#define IDC_RENAME 1054
+#define IDC_OVERWRITE 1055
+#define IDC_CANCEL 1056
+#define IDC_HEADER 1057
+#define IDC_CANCEL2 1058
+#define IDC_COPYURL 1058
+#define IDI_FTP0 20000
+#define IDI_FTP1 20001
+#define IDI_FTP2 20002
+#define IDI_FTP3 20003
+#define IDI_FTP4 20004
+#define IDI_MENU 20010
+#define IDI_CLIPBOARD 20011
+#define IDM_COPYLINK 40001
+#define IDM_CLOSEDLG 40002
+#define IDM_AUTOSEND 40003
+#define IDM_DELETEFROMLIST 40016
+#define IDM_DELETEFROMFTP 40017
+#define IDM_DOWNLOAD 40019
+#define IDM_DISABLED 40043
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NEXT_RESOURCE_VALUE 119
+#define _APS_NEXT_COMMAND_VALUE 40044
+#define _APS_NEXT_CONTROL_VALUE 1058
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/plugins/FTPFileYM/serverlist.cpp b/plugins/FTPFileYM/serverlist.cpp
new file mode 100644
index 0000000000..9d94c33b7c
--- /dev/null
+++ b/plugins/FTPFileYM/serverlist.cpp
@@ -0,0 +1,113 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "serverlist.h"
+#include "options.h"
+
+ServerList *ServerList::instance = NULL;
+ServerList &ftpList = ServerList::getInstance();
+
+extern Options &opt;
+
+void ServerList::init()
+{
+ for (int i = 0; i < FTP_COUNT; i++)
+ {
+ ServerList::FTP *ftp = new ServerList::FTP(i);
+ ftpList.add(ftp);
+ }
+}
+
+void ServerList::deinit()
+{
+ for (UINT i = 0; i < ftpList.size(); i++)
+ delete ftpList[i];
+
+ delete this;
+}
+
+void ServerList::saveToDb() const
+{
+ ServerList::FTP *ftp = ftpList.getSelected();
+ char buff[256];
+
+ mir_snprintf(buff, sizeof(buff), "Password%d", opt.selected);
+ DB::setCryptedString(0, MODULE, buff, ftp->szPass);
+
+ DB::setStringF(0, MODULE, "Name%d", opt.selected, ftp->stzName);
+ DB::setAStringF(0, MODULE, "Server%d", opt.selected, ftp->szServer);
+ DB::setAStringF(0, MODULE, "User%d", opt.selected, ftp->szUser);
+ DB::setAStringF(0, MODULE, "Url%d", opt.selected, ftp->szUrl);
+ DB::setAStringF(0, MODULE, "Dir%d", opt.selected, ftp->szDir);
+ DB::setAStringF(0, MODULE, "Chmod%d", opt.selected, ftp->szChmod);
+ DB::setWordF(0, MODULE, "FtpProto%d", opt.selected, ftp->ftpProto);
+ DB::setWordF(0, MODULE, "Port%d", opt.selected, ftp->iPort);
+ DB::setByteF(0, MODULE, "Passive%d", opt.selected, ftp->bPassive);
+ DB::setByte(0, MODULE, "Selected", opt.selected);
+ DB::setByte(0, MODULE, "Enabled", opt.enabled);
+ DB::setByte(0, MODULE, "Default", opt.defaultFTP);
+}
+
+ServerList::FTP::FTP(int index)
+{
+ char buff[256];
+
+ this->bEnabled = ((opt.enabled >> index) & 1);
+
+ if (DB::getStringF(0, MODULE, "Name%d", index, this->stzName))
+ mir_sntprintf(this->stzName, SIZEOF(this->stzName), TranslateT("FTP Server %d"), index + 1);
+
+ mir_snprintf(buff, sizeof(buff), "Password%d", index);
+ DB::getCryptedString(0, MODULE, buff, this->szPass);
+
+ DB::getAStringF(0, MODULE, "Server%d", index, this->szServer);
+ DB::getAStringF(0, MODULE, "User%d", index, this->szUser);
+ DB::getAStringF(0, MODULE, "Url%d", index, this->szUrl);
+ DB::getAStringF(0, MODULE, "Dir%d", index, this->szDir);
+ DB::getAStringF(0, MODULE, "Chmod%d", index, this->szChmod);
+ this->ftpProto = (FTP::EProtoType)DB::getWordF(0, MODULE, "FtpProto%d", index, FTP::FT_STANDARD);
+ this->iPort = DB::getWordF(0, MODULE, "Port%d", index, 21);
+ this->bPassive = DB::getByteF(0, MODULE, "Passive%d", index, 0) ? true : false;
+}
+
+ServerList::FTP *ServerList::getSelected() const
+{
+ return ftpList[opt.selected];
+}
+
+bool ServerList::FTP::isValid() const
+{
+ return (this->bEnabled &&
+ this->szServer[0] &&
+ this->szUser[0] &&
+ this->szPass[0] &&
+ this->szUrl[0]) ? true : false;
+}
+
+char *ServerList::FTP::getProtoString() const
+{
+ switch (this->ftpProto)
+ {
+ case FT_STANDARD:
+ case FT_SSL_EXPLICIT: return "ftp://";
+ case FT_SSL_IMPLICIT: return "ftps://";
+ case FT_SSH: return "sftp://";
+ }
+
+ return NULL;
+}
diff --git a/plugins/FTPFileYM/serverlist.h b/plugins/FTPFileYM/serverlist.h
new file mode 100644
index 0000000000..8a1a540172
--- /dev/null
+++ b/plugins/FTPFileYM/serverlist.h
@@ -0,0 +1,79 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+
+class ServerList
+{
+private:
+ static ServerList *instance;
+ ServerList() { };
+ ~ServerList() { instance = NULL; };
+
+public:
+ class FTP
+ {
+ public:
+ enum EProtoType
+ {
+ FT_STANDARD = 0,
+ FT_SSL_EXPLICIT,
+ FT_SSL_IMPLICIT,
+ FT_SSH
+ };
+
+ bool bEnabled;
+ TCHAR stzName[64];
+ char szServer[256];
+ char szUser[64];
+ char szPass[64];
+ char szDir[64];
+ char szChmod[256];
+ char szUrl[256];
+ EProtoType ftpProto;
+ int iPort;
+ bool bPassive;
+
+ FTP(int index);
+
+ bool isValid() const;
+ char *getProtoString() const;
+ };
+
+ static const int FTP_COUNT = 5;
+
+ vector<FTP *> items;
+
+ FTP *operator[] (int i) const { return items[i]; };
+ void add(FTP *newItem) { items.push_back(newItem); }
+ size_t size() { return items.size(); }
+
+ static ServerList &getInstance()
+ {
+ if (!instance)
+ instance = new ServerList();
+ return *instance;
+ };
+
+ void init();
+ void deinit();
+ void saveToDb() const;
+ FTP *getSelected() const;
+}; \ No newline at end of file
diff --git a/plugins/FTPFileYM/utils.cpp b/plugins/FTPFileYM/utils.cpp
new file mode 100644
index 0000000000..8b0acd14da
--- /dev/null
+++ b/plugins/FTPFileYM/utils.cpp
@@ -0,0 +1,237 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "utils.h"
+#include "dialog.h"
+#include "options.h"
+
+extern Options &opt;
+extern UploadDialog *uDlg;
+extern LibCurl &curl;
+
+int Utils::getDeleteTimeMin()
+{
+ switch (opt.timeRange)
+ {
+ case (Options::TR_MINUTES): return (opt.iDeleteTime);
+ case (Options::TR_HOURS): return (opt.iDeleteTime * 60);
+ case (Options::TR_DAYS): return (opt.iDeleteTime * 60 * 24);
+ }
+
+ return -1;
+}
+
+int Utils::msgBox(TCHAR *stzMsg, UINT uType)
+{
+ HWND hwnd = (uDlg != NULL) ? uDlg->hwnd : 0;
+ return MessageBox(hwnd, stzMsg, TranslateT("FTP File"), uType);
+}
+
+int Utils::msgBoxA(char *szMsg, UINT uType)
+{
+ HWND hwnd = (uDlg != NULL) ? uDlg->hwnd : 0;
+ return MessageBoxA(hwnd, szMsg, Translate("FTP File"), uType);
+}
+
+HICON Utils::loadIconEx(char *szName)
+{
+ char buff[100];
+ mir_snprintf(buff, sizeof(buff), "%s_%s", MODULE, szName);
+ return (HICON)CallService(MS_SKIN2_GETICON, 0, (LPARAM)buff);
+}
+
+TCHAR *Utils::getFileNameFromPath(TCHAR *stzPath)
+{
+ TCHAR *pch = _tcsrchr(stzPath, '\\');
+ if (pch) return pch + 1;
+ else return _T("file.zip");
+}
+
+TCHAR *Utils::getTextFragment(TCHAR *stzText, size_t length, TCHAR *buff)
+{
+ if (_tcslen(stzText) > length)
+ {
+ _tcscpy(buff, stzText);
+ buff[length - 1] = 0;
+ _tcscat(buff, _T("..."));
+ return buff;
+ }
+
+ return stzText;
+}
+
+void Utils::copyToClipboard(char *szText)
+{
+ if (szText)
+ {
+ if (OpenClipboard(NULL))
+ {
+ EmptyClipboard();
+ HGLOBAL hClipboardData = GlobalAlloc(GMEM_DDESHARE, 1024);
+ char *pchData = (char *)GlobalLock(hClipboardData);
+ strcpy(pchData, szText);
+ GlobalUnlock(hClipboardData);
+ SetClipboardData(CF_TEXT, hClipboardData);
+ CloseClipboard();
+ }
+ }
+}
+
+const char from_chars[] = "������Ɋ�؎ύ��������������� #{}^~[];,";
+const char to_chars[] = "AEIOUYESCRZDTNaeeiouuyscrzdtn__________";
+
+char* Utils::makeSafeString(TCHAR *input, char *output)
+{
+ char *buff = mir_t2a(input);
+ size_t length = strlen(buff);
+
+ for (UINT i = 0; i < length; i++)
+ {
+ for (int j = 0; from_chars[j] != 0; j++)
+ {
+ if (buff[i] == from_chars[j])
+ {
+ buff[i] = to_chars[j];
+ break;
+ }
+ }
+ }
+
+ strcpy(output, buff);
+ FREE(buff);
+
+ return output;
+}
+
+void Utils::curlSetOpt(CURL *hCurl, ServerList::FTP *ftp, char *url, struct curl_slist *headerList, char *errorBuff)
+{
+ char buff[256];
+
+ curl.easy_setopt(hCurl, CURLOPT_ERRORBUFFER, errorBuff);
+
+ curl.easy_setopt(hCurl, CURLOPT_POSTQUOTE, headerList);
+ curl.easy_setopt(hCurl, CURLOPT_NOPROGRESS, 1);
+
+ curl.easy_setopt(hCurl, CURLOPT_URL, url);
+ curl.easy_setopt(hCurl, CURLOPT_PORT, ftp->iPort);
+ curl.easy_setopt(hCurl, CURLOPT_CONNECTTIMEOUT, 30);
+ curl.easy_setopt(hCurl, CURLOPT_FTP_RESPONSE_TIMEOUT, 20);
+
+ curl.easy_setopt(hCurl, CURLOPT_FTP_USE_EPRT, 0);
+ curl.easy_setopt(hCurl, CURLOPT_FTP_USE_EPSV, 0);
+
+ if (ftp->bPassive)
+ curl.easy_setopt(hCurl, CURLOPT_FTPPORT, 0);
+ else if (!DB::getAString(0, MODULE, "LocalIP", buff))
+ curl.easy_setopt(hCurl, CURLOPT_FTPPORT, buff);
+ else
+ curl.easy_setopt(hCurl, CURLOPT_FTPPORT, "-");
+
+ mir_snprintf(buff, sizeof(buff), "%s:%s", ftp->szUser, ftp->szPass);
+ curl.easy_setopt(hCurl, CURLOPT_USERPWD, buff);
+
+ if (ftp->ftpProto == ServerList::FTP::FT_SSL_EXPLICIT || ftp->ftpProto == ServerList::FTP::FT_SSL_IMPLICIT)
+ {
+ curl.easy_setopt(hCurl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
+ curl.easy_setopt(hCurl, CURLOPT_FTPSSLAUTH, CURLFTPAUTH_DEFAULT);
+ curl.easy_setopt(hCurl, CURLOPT_SSL_VERIFYPEER, 0);
+ curl.easy_setopt(hCurl, CURLOPT_SSL_VERIFYHOST, 2);
+ }
+ else if (ftp->ftpProto == ServerList::FTP::FT_SSH)
+ {
+ curl.easy_setopt(hCurl, CURLOPT_SSH_AUTH_TYPES, CURLSSH_AUTH_PASSWORD);
+ }
+}
+
+INT_PTR CALLBACK Utils::DlgProcSetFileName(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ TCHAR *fileName = (TCHAR *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+
+ switch (msg)
+ {
+ case WM_INITDIALOG:
+ {
+ TranslateDialogDefault(hwndDlg);
+ fileName = (TCHAR *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)fileName);
+ SetDlgItemText(hwndDlg, IDC_NAME, fileName);
+
+ if (GetDlgCtrlID((HWND)wParam) != IDC_NAME)
+ {
+ SetFocus(GetDlgItem(hwndDlg, IDC_NAME));
+ SendDlgItemMessage(hwndDlg, IDC_NAME, EM_SETSEL, 0, _tcslen(fileName) - 4);
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+ case WM_COMMAND:
+ {
+ if (HIWORD(wParam) == BN_CLICKED)
+ {
+ if (LOWORD(wParam) == IDOK)
+ {
+ GetDlgItemText(hwndDlg, IDC_NAME, fileName, 64);
+ EndDialog(hwndDlg, IDOK);
+ }
+ else if (LOWORD(wParam) == IDCANCEL)
+ {
+ EndDialog(hwndDlg, IDCANCEL);
+ }
+ }
+
+ break;
+ }
+ }
+
+ return FALSE;
+}
+
+bool Utils::setFileNameDlg(TCHAR *nameBuff)
+{
+ if (DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_DLG_NAME), 0, DlgProcSetFileName, (LPARAM)nameBuff) == IDOK)
+ return true;
+ else
+ return false;
+}
+
+bool Utils::setFileNameDlgA(char *nameBuff)
+{
+ TCHAR buff[64];
+ TCHAR *tmp = mir_a2t(nameBuff);
+ _tcscpy(buff, tmp);
+ FREE(tmp);
+
+ bool res = setFileNameDlg(buff);
+ if (res)
+ {
+ char *p = mir_t2a(buff);
+ strcpy(nameBuff, p);
+ FREE(p);
+ }
+
+ return res;
+}
+
+void Utils::createFileDownloadLink(char *szUrl, char *fileName, char *buff, int buffSize)
+{
+ if (szUrl[strlen(szUrl) - 1] == '/')
+ mir_snprintf(buff, buffSize, "%s%s", szUrl, fileName);
+ else
+ mir_snprintf(buff, buffSize, "%s/%s", szUrl, fileName);
+} \ No newline at end of file
diff --git a/plugins/FTPFileYM/utils.h b/plugins/FTPFileYM/utils.h
new file mode 100644
index 0000000000..3b22ccc7d6
--- /dev/null
+++ b/plugins/FTPFileYM/utils.h
@@ -0,0 +1,71 @@
+/*
+FTP File YM plugin
+Copyright (C) 2007-2010 Jan Holub
+
+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 version 2
+of the License.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "common.h"
+#include "serverlist.h"
+
+class Utils
+{
+private:
+ static INT_PTR CALLBACK DlgProcSetFileName(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+public:
+ static int msgBox(TCHAR *szMsg, UINT uType);
+ static int msgBoxA(char *szMsg, UINT uType);
+ static int getDeleteTimeMin();
+ static HICON loadIconEx(char *szName);
+
+ static TCHAR *getFileNameFromPath(TCHAR *stzPath);
+ static TCHAR *getTextFragment(TCHAR *stzText, size_t length, TCHAR *buff);
+ static char *makeSafeString(TCHAR *input, char *output);
+
+ static void createFileDownloadLink(char *szUrl, char *fileName, char *buff, int buffSize);
+ static void copyToClipboard(char *szText);
+ static void curlSetOpt(CURL *hCurl, ServerList::FTP *ftp, char *url, struct curl_slist *headerList, char *errorBuff);
+
+ static bool setFileNameDlg(TCHAR *nameBuff);
+ static bool setFileNameDlgA(char *nameBuff);
+};
+
+class Mutex
+{
+ friend class Lock;
+
+private:
+ void Acquire() { EnterCriticalSection (&_critSection); }
+ void Release() { LeaveCriticalSection (&_critSection); }
+
+ CRITICAL_SECTION _critSection;
+
+public:
+ Mutex() { InitializeCriticalSection (&_critSection); }
+ ~Mutex() { DeleteCriticalSection (&_critSection); }
+};
+
+class Lock
+{
+private:
+ Mutex &_mutex;
+
+public:
+ Lock (Mutex &mutex): _mutex(mutex) { _mutex.Acquire(); }
+ ~Lock () {_mutex.Release(); }
+};
+
diff --git a/plugins/FTPFileYM/version.h b/plugins/FTPFileYM/version.h
new file mode 100644
index 0000000000..ca7d1ef7cd
--- /dev/null
+++ b/plugins/FTPFileYM/version.h
@@ -0,0 +1,4 @@
+#define __FILEVERSION_STRING 0,5,0,0
+#define __VERSION_STRING "0.5.0.0"
+#define __VERSION_DWORD PLUGIN_MAKE_VERSION(0, 5, 0, 0)
+
diff --git a/plugins/FTPFileYM/version.rc b/plugins/FTPFileYM/version.rc
new file mode 100644
index 0000000000..e436e54e03
--- /dev/null
+++ b/plugins/FTPFileYM/version.rc
@@ -0,0 +1,37 @@
+
+#include <windows.h>
+#include "version.h"
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION __FILEVERSION_STRING
+ PRODUCTVERSION __FILEVERSION_STRING
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE 0x1L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "000004b0"
+ BEGIN
+ VALUE "Author", "Jan Holub"
+ VALUE "CompanyName", "yaho"
+ VALUE "FileDescription", "FTP a file to a server and send the URL to your friend"
+ VALUE "FileVersion", __VERSION_STRING
+ VALUE "InternalName", "FTP File YM"
+ VALUE "LegalCopyright", "Copyright (c) 2007-2010 Jan Holub"
+ VALUE "OriginalFilename", "ftpfile.dll"
+ VALUE "ProductName", "FTP File YM"
+ VALUE "ProductVersion", __VERSION_STRING
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x0, 1200
+ END
+END
diff --git a/plugins/FTPFileYM/zip/crypt.h b/plugins/FTPFileYM/zip/crypt.h
new file mode 100644
index 0000000000..a01d08d932
--- /dev/null
+++ b/plugins/FTPFileYM/zip/crypt.h
@@ -0,0 +1,131 @@
+/* crypt.h -- base code for crypt/uncrypt ZIPfile
+
+
+ Version 1.01e, February 12th, 2005
+
+ Copyright (C) 1998-2005 Gilles Vollant
+
+ This code is a modified version of crypting code in Infozip distribution
+
+ The encryption/decryption parts of this source code (as opposed to the
+ non-echoing password parts) were originally written in Europe. The
+ whole source package can be freely distributed, including from the USA.
+ (Prior to January 2000, re-export from the US was a violation of US law.)
+
+ This encryption code is a direct transcription of the algorithm from
+ Roger Schlafly, described by Phil Katz in the file appnote.txt. This
+ file (appnote.txt) is distributed with the PKZIP program (even in the
+ version without encryption capabilities).
+
+ If you don't need crypting in your application, just define symbols
+ NOCRYPT and NOUNCRYPT.
+
+ This code support the "Traditional PKWARE Encryption".
+
+ The new AES encryption added on Zip format by Winzip (see the page
+ http://www.winzip.com/aes_info.htm ) and PKWare PKZip 5.x Strong
+ Encryption is not supported.
+*/
+
+#define CRC32(c, b) ((*(pcrc_32_tab+(((int)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
+
+/***********************************************************************
+ * Return the next byte in the pseudo-random sequence
+ */
+static int decrypt_byte(unsigned long* pkeys, const unsigned long* pcrc_32_tab)
+{
+ unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an
+ * unpredictable manner on 16-bit systems; not a problem
+ * with any known compiler so far, though */
+
+ temp = ((unsigned)(*(pkeys+2)) & 0xffff) | 2;
+ return (int)(((temp * (temp ^ 1)) >> 8) & 0xff);
+}
+
+/***********************************************************************
+ * Update the encryption keys with the next byte of plain text
+ */
+static int update_keys(unsigned long* pkeys,const unsigned long* pcrc_32_tab,int c)
+{
+ (*(pkeys+0)) = CRC32((*(pkeys+0)), c);
+ (*(pkeys+1)) += (*(pkeys+0)) & 0xff;
+ (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
+ {
+ register int keyshift = (int)((*(pkeys+1)) >> 24);
+ (*(pkeys+2)) = CRC32((*(pkeys+2)), keyshift);
+ }
+ return c;
+}
+
+
+/***********************************************************************
+ * Initialize the encryption keys and the random header according to
+ * the given password.
+ */
+static void init_keys(const char* passwd,unsigned long* pkeys,const unsigned long* pcrc_32_tab)
+{
+ *(pkeys+0) = 305419896L;
+ *(pkeys+1) = 591751049L;
+ *(pkeys+2) = 878082192L;
+ while (*passwd != '\0') {
+ update_keys(pkeys,pcrc_32_tab,(int)*passwd);
+ passwd++;
+ }
+}
+
+#define zdecode(pkeys,pcrc_32_tab,c) \
+ (update_keys(pkeys,pcrc_32_tab,c ^= decrypt_byte(pkeys,pcrc_32_tab)))
+
+#define zencode(pkeys,pcrc_32_tab,c,t) \
+ (t=decrypt_byte(pkeys,pcrc_32_tab), update_keys(pkeys,pcrc_32_tab,c), t^(c))
+
+#ifdef INCLUDECRYPTINGCODE_IFCRYPTALLOWED
+
+#define RAND_HEAD_LEN 12
+ /* "last resort" source for second part of crypt seed pattern */
+# ifndef ZCR_SEED2
+# define ZCR_SEED2 3141592654UL /* use PI as default pattern */
+# endif
+
+static int crypthead(const char* passwd, /* password string */
+ unsigned char* buf, /* where to write header */
+ int bufSize,
+ unsigned long* pkeys,
+ const unsigned long* pcrc_32_tab,
+ unsigned long crcForCrypting)
+{
+ int n; /* index in random header */
+ int t; /* temporary */
+ int c; /* random byte */
+ unsigned char header[RAND_HEAD_LEN-2]; /* random header */
+ static unsigned calls = 0; /* ensure different random header each time */
+
+ if (bufSize<RAND_HEAD_LEN)
+ return 0;
+
+ /* First generate RAND_HEAD_LEN-2 random bytes. We encrypt the
+ * output of rand() to get less predictability, since rand() is
+ * often poorly implemented.
+ */
+ if (++calls == 1)
+ {
+ srand((unsigned)(time(NULL) ^ ZCR_SEED2));
+ }
+ init_keys(passwd, pkeys, pcrc_32_tab);
+ for (n = 0; n < RAND_HEAD_LEN-2; n++)
+ {
+ c = (rand() >> 7) & 0xff;
+ header[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, c, t);
+ }
+ /* Encrypt random header (last two bytes is high word of crc) */
+ init_keys(passwd, pkeys, pcrc_32_tab);
+ for (n = 0; n < RAND_HEAD_LEN-2; n++)
+ {
+ buf[n] = (unsigned char)zencode(pkeys, pcrc_32_tab, header[n], t);
+ }
+ buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 16) & 0xff, t);
+ buf[n++] = (unsigned char)zencode(pkeys, pcrc_32_tab, (int)(crcForCrypting >> 24) & 0xff, t);
+ return n;
+}
+
+#endif
diff --git a/plugins/FTPFileYM/zip/ioapi.c b/plugins/FTPFileYM/zip/ioapi.c
new file mode 100644
index 0000000000..49958f61ff
--- /dev/null
+++ b/plugins/FTPFileYM/zip/ioapi.c
@@ -0,0 +1,235 @@
+/* ioapi.h -- IO base function header for compress/uncompress .zip
+ part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications for Zip64 support
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+ For more info read MiniZip_info.txt
+
+*/
+
+#if (defined(_WIN32))
+ #define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include "ioapi.h"
+
+voidpf call_zopen64 (const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode)
+{
+ if (pfilefunc->zfile_func64.zopen64_file != NULL)
+ return (*(pfilefunc->zfile_func64.zopen64_file)) (pfilefunc->zfile_func64.opaque,filename,mode);
+ else
+ {
+ return (*(pfilefunc->zopen32_file))(pfilefunc->zfile_func64.opaque,(const char*)filename,mode);
+ }
+}
+
+long call_zseek64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin)
+{
+ if (pfilefunc->zfile_func64.zseek64_file != NULL)
+ return (*(pfilefunc->zfile_func64.zseek64_file)) (pfilefunc->zfile_func64.opaque,filestream,offset,origin);
+ else
+ {
+ uLong offsetTruncated = (uLong)offset;
+ if (offsetTruncated != offset)
+ return -1;
+ else
+ return (*(pfilefunc->zseek32_file))(pfilefunc->zfile_func64.opaque,filestream,offsetTruncated,origin);
+ }
+}
+
+ZPOS64_T call_ztell64 (const zlib_filefunc64_32_def* pfilefunc,voidpf filestream)
+{
+ if (pfilefunc->zfile_func64.zseek64_file != NULL)
+ return (*(pfilefunc->zfile_func64.ztell64_file)) (pfilefunc->zfile_func64.opaque,filestream);
+ else
+ {
+ uLong tell_uLong = (*(pfilefunc->ztell32_file))(pfilefunc->zfile_func64.opaque,filestream);
+ if ((tell_uLong) == ((uLong)-1))
+ return (ZPOS64_T)-1;
+ else
+ return tell_uLong;
+ }
+}
+
+void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32)
+{
+ p_filefunc64_32->zfile_func64.zopen64_file = NULL;
+ p_filefunc64_32->zopen32_file = p_filefunc32->zopen_file;
+ p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
+ p_filefunc64_32->zfile_func64.zread_file = p_filefunc32->zread_file;
+ p_filefunc64_32->zfile_func64.zwrite_file = p_filefunc32->zwrite_file;
+ p_filefunc64_32->zfile_func64.ztell64_file = NULL;
+ p_filefunc64_32->zfile_func64.zseek64_file = NULL;
+ p_filefunc64_32->zfile_func64.zclose_file = p_filefunc32->zclose_file;
+ p_filefunc64_32->zfile_func64.zerror_file = p_filefunc32->zerror_file;
+ p_filefunc64_32->zfile_func64.opaque = p_filefunc32->opaque;
+ p_filefunc64_32->zseek32_file = p_filefunc32->zseek_file;
+ p_filefunc64_32->ztell32_file = p_filefunc32->ztell_file;
+}
+
+
+
+static voidpf ZCALLBACK fopen_file_func OF((voidpf opaque, const char* filename, int mode));
+static uLong ZCALLBACK fread_file_func OF((voidpf opaque, voidpf stream, void* buf, uLong size));
+static uLong ZCALLBACK fwrite_file_func OF((voidpf opaque, voidpf stream, const void* buf,uLong size));
+static ZPOS64_T ZCALLBACK ftell64_file_func OF((voidpf opaque, voidpf stream));
+static long ZCALLBACK fseek64_file_func OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
+static int ZCALLBACK fclose_file_func OF((voidpf opaque, voidpf stream));
+static int ZCALLBACK ferror_file_func OF((voidpf opaque, voidpf stream));
+
+static voidpf ZCALLBACK fopen_file_func (voidpf opaque, const char* filename, int mode)
+{
+ FILE* file = NULL;
+ const char* mode_fopen = NULL;
+ if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
+ mode_fopen = "rb";
+ else
+ if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
+ mode_fopen = "r+b";
+ else
+ if (mode & ZLIB_FILEFUNC_MODE_CREATE)
+ mode_fopen = "wb";
+
+ if ((filename!=NULL) && (mode_fopen != NULL))
+ file = fopen(filename, mode_fopen);
+ return file;
+}
+
+static voidpf ZCALLBACK fopen64_file_func (voidpf opaque, const void* filename, int mode)
+{
+ FILE* file = NULL;
+ const char* mode_fopen = NULL;
+ if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER)==ZLIB_FILEFUNC_MODE_READ)
+ mode_fopen = "rb";
+ else
+ if (mode & ZLIB_FILEFUNC_MODE_EXISTING)
+ mode_fopen = "r+b";
+ else
+ if (mode & ZLIB_FILEFUNC_MODE_CREATE)
+ mode_fopen = "wb";
+
+ if ((filename!=NULL) && (mode_fopen != NULL))
+ file = fopen64((const char*)filename, mode_fopen);
+ return file;
+}
+
+
+static uLong ZCALLBACK fread_file_func (voidpf opaque, voidpf stream, void* buf, uLong size)
+{
+ uLong ret;
+ ret = (uLong)fread(buf, 1, (size_t)size, (FILE *)stream);
+ return ret;
+}
+
+static uLong ZCALLBACK fwrite_file_func (voidpf opaque, voidpf stream, const void* buf, uLong size)
+{
+ uLong ret;
+ ret = (uLong)fwrite(buf, 1, (size_t)size, (FILE *)stream);
+ return ret;
+}
+
+static long ZCALLBACK ftell_file_func (voidpf opaque, voidpf stream)
+{
+ long ret;
+ ret = ftell((FILE *)stream);
+ return ret;
+}
+
+
+static ZPOS64_T ZCALLBACK ftell64_file_func (voidpf opaque, voidpf stream)
+{
+ ZPOS64_T ret;
+ ret = ftello64((FILE *)stream);
+ return ret;
+}
+
+static long ZCALLBACK fseek_file_func (voidpf opaque, voidpf stream, uLong offset, int origin)
+{
+ int fseek_origin=0;
+ long ret;
+ switch (origin)
+ {
+ case ZLIB_FILEFUNC_SEEK_CUR :
+ fseek_origin = SEEK_CUR;
+ break;
+ case ZLIB_FILEFUNC_SEEK_END :
+ fseek_origin = SEEK_END;
+ break;
+ case ZLIB_FILEFUNC_SEEK_SET :
+ fseek_origin = SEEK_SET;
+ break;
+ default: return -1;
+ }
+ ret = 0;
+ if (fseek((FILE *)stream, offset, fseek_origin) != 0)
+ ret = -1;
+ return ret;
+}
+
+static long ZCALLBACK fseek64_file_func (voidpf opaque, voidpf stream, ZPOS64_T offset, int origin)
+{
+ int fseek_origin=0;
+ long ret;
+ switch (origin)
+ {
+ case ZLIB_FILEFUNC_SEEK_CUR :
+ fseek_origin = SEEK_CUR;
+ break;
+ case ZLIB_FILEFUNC_SEEK_END :
+ fseek_origin = SEEK_END;
+ break;
+ case ZLIB_FILEFUNC_SEEK_SET :
+ fseek_origin = SEEK_SET;
+ break;
+ default: return -1;
+ }
+ ret = 0;
+
+ if(fseeko64((FILE *)stream, offset, fseek_origin) != 0)
+ ret = -1;
+
+ return ret;
+}
+
+
+static int ZCALLBACK fclose_file_func (voidpf opaque, voidpf stream)
+{
+ int ret;
+ ret = fclose((FILE *)stream);
+ return ret;
+}
+
+static int ZCALLBACK ferror_file_func (voidpf opaque, voidpf stream)
+{
+ int ret;
+ ret = ferror((FILE *)stream);
+ return ret;
+}
+
+void fill_fopen_filefunc (pzlib_filefunc_def)
+ zlib_filefunc_def* pzlib_filefunc_def;
+{
+ pzlib_filefunc_def->zopen_file = fopen_file_func;
+ pzlib_filefunc_def->zread_file = fread_file_func;
+ pzlib_filefunc_def->zwrite_file = fwrite_file_func;
+ pzlib_filefunc_def->ztell_file = ftell_file_func;
+ pzlib_filefunc_def->zseek_file = fseek_file_func;
+ pzlib_filefunc_def->zclose_file = fclose_file_func;
+ pzlib_filefunc_def->zerror_file = ferror_file_func;
+ pzlib_filefunc_def->opaque = NULL;
+}
+
+void fill_fopen64_filefunc (zlib_filefunc64_def* pzlib_filefunc_def)
+{
+ pzlib_filefunc_def->zopen64_file = fopen64_file_func;
+ pzlib_filefunc_def->zread_file = fread_file_func;
+ pzlib_filefunc_def->zwrite_file = fwrite_file_func;
+ pzlib_filefunc_def->ztell64_file = ftell64_file_func;
+ pzlib_filefunc_def->zseek64_file = fseek64_file_func;
+ pzlib_filefunc_def->zclose_file = fclose_file_func;
+ pzlib_filefunc_def->zerror_file = ferror_file_func;
+ pzlib_filefunc_def->opaque = NULL;
+}
diff --git a/plugins/FTPFileYM/zip/ioapi.h b/plugins/FTPFileYM/zip/ioapi.h
new file mode 100644
index 0000000000..8309c4cf8f
--- /dev/null
+++ b/plugins/FTPFileYM/zip/ioapi.h
@@ -0,0 +1,200 @@
+/* ioapi.h -- IO base function header for compress/uncompress .zip
+ part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications for Zip64 support
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+ For more info read MiniZip_info.txt
+
+ Changes
+
+ Oct-2009 - Defined ZPOS64_T to fpos_t on windows and u_int64_t on linux. (might need to find a better why for this)
+ Oct-2009 - Change to fseeko64, ftello64 and fopen64 so large files would work on linux.
+ More if/def section may be needed to support other platforms
+ Oct-2009 - Defined fxxxx64 calls to normal fopen/ftell/fseek so they would compile on windows.
+ (but you should use iowin32.c for windows instead)
+
+*/
+
+#ifndef _ZLIBIOAPI64_H
+#define _ZLIBIOAPI64_H
+
+#if (!defined(_WIN32)) && (!defined(WIN32))
+
+ // Linux needs this to support file operation on files larger then 4+GB
+ // But might need better if/def to select just the platforms that needs them.
+
+ #ifndef __USE_FILE_OFFSET64
+ #define __USE_FILE_OFFSET64
+ #endif
+ #ifndef __USE_LARGEFILE64
+ #define __USE_LARGEFILE64
+ #endif
+ #ifndef _LARGEFILE64_SOURCE
+ #define _LARGEFILE64_SOURCE
+ #endif
+ #ifndef _FILE_OFFSET_BIT
+ #define _FILE_OFFSET_BIT 64
+ #endif
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include "zlib.h"
+
+#if defined(USE_FILE32API)
+#define fopen64 fopen
+#define ftello64 ftell
+#define fseeko64 fseek
+#else
+#ifdef _MSC_VER
+ #define fopen64 fopen
+ #if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
+ #define ftello64 _ftelli64
+ #define fseeko64 _fseeki64
+ #else // old MSC
+ #define ftello64 ftell
+ #define fseeko64 fseek
+ #endif
+#endif
+#endif
+
+/*
+#ifndef ZPOS64_T
+ #ifdef _WIN32
+ #define ZPOS64_T fpos_t
+ #else
+ #include <stdint.h>
+ #define ZPOS64_T uint64_t
+ #endif
+#endif
+*/
+
+#ifdef HAVE_MINIZIP64_CONF_H
+#include "mz64conf.h"
+#endif
+
+/* a type choosen by DEFINE */
+#ifdef HAVE_64BIT_INT_CUSTOM
+typedef 64BIT_INT_CUSTOM_TYPE ZPOS64_T;
+#else
+#ifdef HAS_STDINT_H
+#include "stdint.h"
+typedef uint64_t ZPOS64_T;
+#else
+
+
+#if defined(_MSC_VER) || defined(__BORLANDC__)
+typedef unsigned __int64 ZPOS64_T;
+#else
+typedef unsigned long long int ZPOS64_T;
+#endif
+#endif
+#endif
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+#define ZLIB_FILEFUNC_SEEK_CUR (1)
+#define ZLIB_FILEFUNC_SEEK_END (2)
+#define ZLIB_FILEFUNC_SEEK_SET (0)
+
+#define ZLIB_FILEFUNC_MODE_READ (1)
+#define ZLIB_FILEFUNC_MODE_WRITE (2)
+#define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
+
+#define ZLIB_FILEFUNC_MODE_EXISTING (4)
+#define ZLIB_FILEFUNC_MODE_CREATE (8)
+
+
+#ifndef ZCALLBACK
+ #if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
+ #define ZCALLBACK CALLBACK
+ #else
+ #define ZCALLBACK
+ #endif
+#endif
+
+
+
+
+typedef voidpf (ZCALLBACK *open_file_func) OF((voidpf opaque, const char* filename, int mode));
+typedef uLong (ZCALLBACK *read_file_func) OF((voidpf opaque, voidpf stream, void* buf, uLong size));
+typedef uLong (ZCALLBACK *write_file_func) OF((voidpf opaque, voidpf stream, const void* buf, uLong size));
+typedef int (ZCALLBACK *close_file_func) OF((voidpf opaque, voidpf stream));
+typedef int (ZCALLBACK *testerror_file_func) OF((voidpf opaque, voidpf stream));
+
+typedef long (ZCALLBACK *tell_file_func) OF((voidpf opaque, voidpf stream));
+typedef long (ZCALLBACK *seek_file_func) OF((voidpf opaque, voidpf stream, uLong offset, int origin));
+
+
+/* here is the "old" 32 bits structure structure */
+typedef struct zlib_filefunc_def_s
+{
+ open_file_func zopen_file;
+ read_file_func zread_file;
+ write_file_func zwrite_file;
+ tell_file_func ztell_file;
+ seek_file_func zseek_file;
+ close_file_func zclose_file;
+ testerror_file_func zerror_file;
+ voidpf opaque;
+} zlib_filefunc_def;
+
+typedef ZPOS64_T (ZCALLBACK *tell64_file_func) OF((voidpf opaque, voidpf stream));
+typedef long (ZCALLBACK *seek64_file_func) OF((voidpf opaque, voidpf stream, ZPOS64_T offset, int origin));
+typedef voidpf (ZCALLBACK *open64_file_func) OF((voidpf opaque, const void* filename, int mode));
+
+typedef struct zlib_filefunc64_def_s
+{
+ open64_file_func zopen64_file;
+ read_file_func zread_file;
+ write_file_func zwrite_file;
+ tell64_file_func ztell64_file;
+ seek64_file_func zseek64_file;
+ close_file_func zclose_file;
+ testerror_file_func zerror_file;
+ voidpf opaque;
+} zlib_filefunc64_def;
+
+void fill_fopen64_filefunc OF((zlib_filefunc64_def* pzlib_filefunc_def));
+void fill_fopen_filefunc OF((zlib_filefunc_def* pzlib_filefunc_def));
+
+/* now internal definition, only for zip.c and unzip.h */
+typedef struct zlib_filefunc64_32_def_s
+{
+ zlib_filefunc64_def zfile_func64;
+ open_file_func zopen32_file;
+ tell_file_func ztell32_file;
+ seek_file_func zseek32_file;
+} zlib_filefunc64_32_def;
+
+
+#define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
+#define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
+//#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))
+//#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))
+#define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream))
+#define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream))
+
+voidpf call_zopen64 OF((const zlib_filefunc64_32_def* pfilefunc,const void*filename,int mode));
+long call_zseek64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream, ZPOS64_T offset, int origin));
+ZPOS64_T call_ztell64 OF((const zlib_filefunc64_32_def* pfilefunc,voidpf filestream));
+
+void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def* p_filefunc64_32,const zlib_filefunc_def* p_filefunc32);
+
+#define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode)))
+#define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream)))
+#define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/plugins/FTPFileYM/zip/zconf.h b/plugins/FTPFileYM/zip/zconf.h
new file mode 100644
index 0000000000..58880245c1
--- /dev/null
+++ b/plugins/FTPFileYM/zip/zconf.h
@@ -0,0 +1,416 @@
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2010 Jean-loup Gailly.
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZCONF_H
+#define ZCONF_H
+
+/*
+ * If you *really* need a unique prefix for all types and library functions,
+ * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
+ */
+#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */
+
+/* all linked symbols */
+# define _dist_code z__dist_code
+# define _length_code z__length_code
+# define _tr_align z__tr_align
+# define _tr_flush_block z__tr_flush_block
+# define _tr_init z__tr_init
+# define _tr_stored_block z__tr_stored_block
+# define _tr_tally z__tr_tally
+# define adler32 z_adler32
+# define adler32_combine z_adler32_combine
+# define adler32_combine64 z_adler32_combine64
+# define compress z_compress
+# define compress2 z_compress2
+# define compressBound z_compressBound
+# define crc32 z_crc32
+# define crc32_combine z_crc32_combine
+# define crc32_combine64 z_crc32_combine64
+# define deflate z_deflate
+# define deflateBound z_deflateBound
+# define deflateCopy z_deflateCopy
+# define deflateEnd z_deflateEnd
+# define deflateInit2_ z_deflateInit2_
+# define deflateInit_ z_deflateInit_
+# define deflateParams z_deflateParams
+# define deflatePrime z_deflatePrime
+# define deflateReset z_deflateReset
+# define deflateSetDictionary z_deflateSetDictionary
+# define deflateSetHeader z_deflateSetHeader
+# define deflateTune z_deflateTune
+# define deflate_copyright z_deflate_copyright
+# define get_crc_table z_get_crc_table
+# define gz_error z_gz_error
+# define gz_intmax z_gz_intmax
+# define gz_strwinerror z_gz_strwinerror
+# define gzbuffer z_gzbuffer
+# define gzclearerr z_gzclearerr
+# define gzclose z_gzclose
+# define gzclose_r z_gzclose_r
+# define gzclose_w z_gzclose_w
+# define gzdirect z_gzdirect
+# define gzdopen z_gzdopen
+# define gzeof z_gzeof
+# define gzerror z_gzerror
+# define gzflush z_gzflush
+# define gzgetc z_gzgetc
+# define gzgets z_gzgets
+# define gzoffset z_gzoffset
+# define gzoffset64 z_gzoffset64
+# define gzopen z_gzopen
+# define gzopen64 z_gzopen64
+# define gzprintf z_gzprintf
+# define gzputc z_gzputc
+# define gzputs z_gzputs
+# define gzread z_gzread
+# define gzrewind z_gzrewind
+# define gzseek z_gzseek
+# define gzseek64 z_gzseek64
+# define gzsetparams z_gzsetparams
+# define gztell z_gztell
+# define gztell64 z_gztell64
+# define gzungetc z_gzungetc
+# define gzwrite z_gzwrite
+# define inflate z_inflate
+# define inflateBack z_inflateBack
+# define inflateBackEnd z_inflateBackEnd
+# define inflateBackInit_ z_inflateBackInit_
+# define inflateCopy z_inflateCopy
+# define inflateEnd z_inflateEnd
+# define inflateGetHeader z_inflateGetHeader
+# define inflateInit2_ z_inflateInit2_
+# define inflateInit_ z_inflateInit_
+# define inflateMark z_inflateMark
+# define inflatePrime z_inflatePrime
+# define inflateReset z_inflateReset
+# define inflateReset2 z_inflateReset2
+# define inflateSetDictionary z_inflateSetDictionary
+# define inflateSync z_inflateSync
+# define inflateSyncPoint z_inflateSyncPoint
+# define inflateUndermine z_inflateUndermine
+# define inflate_copyright z_inflate_copyright
+# define inflate_fast z_inflate_fast
+# define inflate_table z_inflate_table
+# define uncompress z_uncompress
+# define zError z_zError
+# define zcalloc z_zcalloc
+# define zcfree z_zcfree
+# define zlibCompileFlags z_zlibCompileFlags
+# define zlibVersion z_zlibVersion
+
+/* all zlib typedefs in zlib.h and zconf.h */
+# define Byte z_Byte
+# define Bytef z_Bytef
+# define alloc_func z_alloc_func
+# define charf z_charf
+# define free_func z_free_func
+# define gzFile z_gzFile
+# define gz_header z_gz_header
+# define gz_headerp z_gz_headerp
+# define in_func z_in_func
+# define intf z_intf
+# define out_func z_out_func
+# define uInt z_uInt
+# define uIntf z_uIntf
+# define uLong z_uLong
+# define uLongf z_uLongf
+# define voidp z_voidp
+# define voidpc z_voidpc
+# define voidpf z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+# define gz_header_s z_gz_header_s
+# define internal_state z_internal_state
+
+#endif
+
+#if defined(__MSDOS__) && !defined(MSDOS)
+# define MSDOS
+#endif
+#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
+# define OS2
+#endif
+#if defined(_WINDOWS) && !defined(WINDOWS)
+# define WINDOWS
+#endif
+#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
+# ifndef WIN32
+# define WIN32
+# endif
+#endif
+#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
+# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
+# ifndef SYS16BIT
+# define SYS16BIT
+# endif
+# endif
+#endif
+
+/*
+ * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
+ * than 64k bytes at a time (needed on systems with 16-bit int).
+ */
+#ifdef SYS16BIT
+# define MAXSEG_64K
+#endif
+#ifdef MSDOS
+# define UNALIGNED_OK
+#endif
+
+#ifdef __STDC_VERSION__
+# ifndef STDC
+# define STDC
+# endif
+# if __STDC_VERSION__ >= 199901L
+# ifndef STDC99
+# define STDC99
+# endif
+# endif
+#endif
+#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
+# define STDC
+#endif
+#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
+# define STDC
+#endif
+#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
+# define STDC
+#endif
+#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
+# define STDC
+#endif
+
+#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
+# define STDC
+#endif
+
+#ifndef STDC
+# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
+# define const /* note: need a more gentle solution here */
+# endif
+#endif
+
+/* Some Mac compilers merge all .h files incorrectly: */
+#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
+# define NO_DUMMY_DECL
+#endif
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+# ifdef MAXSEG_64K
+# define MAX_MEM_LEVEL 8
+# else
+# define MAX_MEM_LEVEL 9
+# endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+# define MAX_WBITS 15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+ (1 << (windowBits+2)) + (1 << (memLevel+9))
+ that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+ make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+ The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus a few kilobytes
+ for small objects.
+*/
+
+ /* Type declarations */
+
+#ifndef OF /* function prototypes */
+# ifdef STDC
+# define OF(args) args
+# else
+# define OF(args) ()
+# endif
+#endif
+
+/* The following definitions for FAR are needed only for MSDOS mixed
+ * model programming (small or medium model with some far allocations).
+ * This was tested only with MSC; for other MSDOS compilers you may have
+ * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
+ * just define FAR to be empty.
+ */
+#ifdef SYS16BIT
+# if defined(M_I86SM) || defined(M_I86MM)
+ /* MSC small or medium model */
+# define SMALL_MEDIUM
+# ifdef _MSC_VER
+# define FAR _far
+# else
+# define FAR far
+# endif
+# endif
+# if (defined(__SMALL__) || defined(__MEDIUM__))
+ /* Turbo C small or medium model */
+# define SMALL_MEDIUM
+# ifdef __BORLANDC__
+# define FAR _far
+# else
+# define FAR far
+# endif
+# endif
+#endif
+
+#if defined(WINDOWS) || defined(WIN32)
+ /* If building or using zlib as a DLL, define ZLIB_DLL.
+ * This is not mandatory, but it offers a little performance increase.
+ */
+# ifdef ZLIB_DLL
+# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
+# ifdef ZLIB_INTERNAL
+# define ZEXTERN extern __declspec(dllexport)
+# else
+# define ZEXTERN extern __declspec(dllimport)
+# endif
+# endif
+# endif /* ZLIB_DLL */
+ /* If building or using zlib with the WINAPI/WINAPIV calling convention,
+ * define ZLIB_WINAPI.
+ * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
+ */
+# ifdef ZLIB_WINAPI
+# ifdef FAR
+# undef FAR
+# endif
+# include <windows.h>
+ /* No need for _export, use ZLIB.DEF instead. */
+ /* For complete Windows compatibility, use WINAPI, not __stdcall. */
+# define ZEXPORT WINAPI
+# ifdef WIN32
+# define ZEXPORTVA WINAPIV
+# else
+# define ZEXPORTVA FAR CDECL
+# endif
+# endif
+#endif
+
+#if defined (__BEOS__)
+# ifdef ZLIB_DLL
+# ifdef ZLIB_INTERNAL
+# define ZEXPORT __declspec(dllexport)
+# define ZEXPORTVA __declspec(dllexport)
+# else
+# define ZEXPORT __declspec(dllimport)
+# define ZEXPORTVA __declspec(dllimport)
+# endif
+# endif
+#endif
+
+#ifdef HAVE_VISIBILITY_PRAGMA
+# define ZEXTERN __attribute__((visibility ("default"))) extern
+#endif
+
+#ifndef ZEXTERN
+# define ZEXTERN extern
+#endif
+#ifndef ZEXPORT
+# define ZEXPORT
+#endif
+#ifndef ZEXPORTVA
+# define ZEXPORTVA
+#endif
+
+#ifndef FAR
+# define FAR
+#endif
+
+#if !defined(__MACTYPES__)
+typedef unsigned char Byte; /* 8 bits */
+#endif
+typedef unsigned int uInt; /* 16 bits or more */
+typedef unsigned long uLong; /* 32 bits or more */
+
+#ifdef SMALL_MEDIUM
+ /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
+# define Bytef Byte FAR
+#else
+ typedef Byte FAR Bytef;
+#endif
+typedef char FAR charf;
+typedef int FAR intf;
+typedef uInt FAR uIntf;
+typedef uLong FAR uLongf;
+
+#ifdef STDC
+ typedef void const *voidpc;
+ typedef void FAR *voidpf;
+ typedef void *voidp;
+#else
+ typedef Byte const *voidpc;
+ typedef Byte FAR *voidpf;
+ typedef Byte *voidp;
+#endif
+
+#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */
+# define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef Z_HAVE_UNISTD_H
+# include <sys/types.h> /* for off_t */
+# include <unistd.h> /* for SEEK_* and off_t */
+# ifdef VMS
+# include <unixio.h> /* for off_t */
+# endif
+# ifndef z_off_t
+# define z_off_t off_t
+# endif
+#endif
+
+#ifdef _LARGEFILE64_SOURCE
+# include <sys/types.h>
+#endif
+
+#ifndef SEEK_SET
+# define SEEK_SET 0 /* Seek from beginning of file. */
+# define SEEK_CUR 1 /* Seek from current position. */
+# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
+#endif
+#ifndef z_off_t
+# define z_off_t long
+#endif
+
+#if defined(__OS400__)
+# define NO_vsnprintf
+#endif
+
+#if defined(__MVS__)
+# define NO_vsnprintf
+#endif
+
+/* MVS linker does not support external names larger than 8 bytes */
+#if defined(__MVS__)
+ #pragma map(deflateInit_,"DEIN")
+ #pragma map(deflateInit2_,"DEIN2")
+ #pragma map(deflateEnd,"DEEND")
+ #pragma map(deflateBound,"DEBND")
+ #pragma map(inflateInit_,"ININ")
+ #pragma map(inflateInit2_,"ININ2")
+ #pragma map(inflateEnd,"INEND")
+ #pragma map(inflateSync,"INSY")
+ #pragma map(inflateSetDictionary,"INSEDI")
+ #pragma map(compressBound,"CMBND")
+ #pragma map(inflate_table,"INTABL")
+ #pragma map(inflate_fast,"INFA")
+ #pragma map(inflate_copyright,"INCOPY")
+#endif
+
+#endif /* ZCONF_H */
diff --git a/plugins/FTPFileYM/zip/zip.c b/plugins/FTPFileYM/zip/zip.c
new file mode 100644
index 0000000000..3c34fc8bd4
--- /dev/null
+++ b/plugins/FTPFileYM/zip/zip.c
@@ -0,0 +1,2004 @@
+/* zip.c -- IO on .zip files using zlib
+ Version 1.1, February 14h, 2010
+ part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications for Zip64 support
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+ For more info read MiniZip_info.txt
+
+ Changes
+ Oct-2009 - Mathias Svensson - Remove old C style function prototypes
+ Oct-2009 - Mathias Svensson - Added Zip64 Support when creating new file archives
+ Oct-2009 - Mathias Svensson - Did some code cleanup and refactoring to get better overview of some functions.
+ Oct-2009 - Mathias Svensson - Added zipRemoveExtraInfoBlock to strip extra field data from its ZIP64 data
+ It is used when recreting zip archive with RAW when deleting items from a zip.
+ ZIP64 data is automaticly added to items that needs it, and existing ZIP64 data need to be removed.
+ Oct-2009 - Mathias Svensson - Added support for BZIP2 as compression mode (bzip2 lib is required)
+ Jan-2010 - back to unzip and minizip 1.0 name scheme, with compatibility layer
+
+*/
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include "zlib.h"
+#include "zip.h"
+
+#ifdef STDC
+# include <stddef.h>
+# include <string.h>
+# include <stdlib.h>
+#endif
+#ifdef NO_ERRNO_H
+ extern int errno;
+#else
+# include <errno.h>
+#endif
+
+
+#ifndef local
+# define local static
+#endif
+/* compile with -Dlocal if your debugger can't find static symbols */
+
+#ifndef VERSIONMADEBY
+# define VERSIONMADEBY (0x0) /* platform depedent */
+#endif
+
+#ifndef Z_BUFSIZE
+#define Z_BUFSIZE (64*1024) //(16384)
+#endif
+
+#ifndef Z_MAXFILENAMEINZIP
+#define Z_MAXFILENAMEINZIP (256)
+#endif
+
+#ifndef ALLOC
+# define ALLOC(size) (malloc(size))
+#endif
+#ifndef TRYFREE
+# define TRYFREE(p) {if (p) free(p);}
+#endif
+
+/*
+#define SIZECENTRALDIRITEM (0x2e)
+#define SIZEZIPLOCALHEADER (0x1e)
+*/
+
+/* I've found an old Unix (a SunOS 4.1.3_U1) without all SEEK_* defined.... */
+
+
+// NOT sure that this work on ALL platform
+#define MAKEULONG64(a, b) ((ZPOS64_T)(((unsigned long)(a)) | ((ZPOS64_T)((unsigned long)(b))) << 32))
+
+#ifndef SEEK_CUR
+#define SEEK_CUR 1
+#endif
+
+#ifndef SEEK_END
+#define SEEK_END 2
+#endif
+
+#ifndef SEEK_SET
+#define SEEK_SET 0
+#endif
+
+#ifndef DEF_MEM_LEVEL
+#if MAX_MEM_LEVEL >= 8
+# define DEF_MEM_LEVEL 8
+#else
+# define DEF_MEM_LEVEL MAX_MEM_LEVEL
+#endif
+#endif
+const char zip_copyright[] =" zip 1.01 Copyright 1998-2004 Gilles Vollant - http://www.winimage.com/zLibDll";
+
+
+#define SIZEDATA_INDATABLOCK (4096-(4*4))
+
+#define LOCALHEADERMAGIC (0x04034b50)
+#define CENTRALHEADERMAGIC (0x02014b50)
+#define ENDHEADERMAGIC (0x06054b50)
+#define ZIP64ENDHEADERMAGIC (0x6064b50)
+#define ZIP64ENDLOCHEADERMAGIC (0x7064b50)
+
+#define FLAG_LOCALHEADER_OFFSET (0x06)
+#define CRC_LOCALHEADER_OFFSET (0x0e)
+
+#define SIZECENTRALHEADER (0x2e) /* 46 */
+
+typedef struct linkedlist_datablock_internal_s
+{
+ struct linkedlist_datablock_internal_s* next_datablock;
+ uLong avail_in_this_block;
+ uLong filled_in_this_block;
+ uLong unused; /* for future use and alignement */
+ unsigned char data[SIZEDATA_INDATABLOCK];
+} linkedlist_datablock_internal;
+
+typedef struct linkedlist_data_s
+{
+ linkedlist_datablock_internal* first_block;
+ linkedlist_datablock_internal* last_block;
+} linkedlist_data;
+
+
+typedef struct
+{
+ z_stream stream; /* zLib stream structure for inflate */
+#ifdef HAVE_BZIP2
+ bz_stream bstream; /* bzLib stream structure for bziped */
+#endif
+
+ int stream_initialised; /* 1 is stream is initialised */
+ uInt pos_in_buffered_data; /* last written byte in buffered_data */
+
+ ZPOS64_T pos_local_header; /* offset of the local header of the file
+ currenty writing */
+ char* central_header; /* central header data for the current file */
+ uLong size_centralExtra;
+ uLong size_centralheader; /* size of the central header for cur file */
+ uLong size_centralExtraFree; /* Extra bytes allocated to the centralheader but that are not used */
+ uLong flag; /* flag of the file currently writing */
+
+ int method; /* compression method of file currenty wr.*/
+ int raw; /* 1 for directly writing raw data */
+ Byte buffered_data[Z_BUFSIZE];/* buffer contain compressed data to be writ*/
+ uLong dosDate;
+ uLong crc32;
+ int encrypt;
+ int zip64; /* Add ZIP64 extened information in the extra field */
+ ZPOS64_T pos_zip64extrainfo;
+ ZPOS64_T totalCompressedData;
+ ZPOS64_T totalUncompressedData;
+#ifndef NOCRYPT
+ unsigned long keys[3]; /* keys defining the pseudo-random sequence */
+ const unsigned long* pcrc_32_tab;
+ int crypt_header_size;
+#endif
+} curfile64_info;
+
+typedef struct
+{
+ zlib_filefunc64_32_def z_filefunc;
+ voidpf filestream; /* io structore of the zipfile */
+ linkedlist_data central_dir;/* datablock with central dir in construction*/
+ int in_opened_file_inzip; /* 1 if a file in the zip is currently writ.*/
+ curfile64_info ci; /* info on the file curretly writing */
+
+ ZPOS64_T begin_pos; /* position of the beginning of the zipfile */
+ ZPOS64_T add_position_when_writting_offset;
+ ZPOS64_T number_entry;
+
+#ifndef NO_ADDFILEINEXISTINGZIP
+ char *globalcomment;
+#endif
+
+} zip64_internal;
+
+
+#ifndef NOCRYPT
+#define INCLUDECRYPTINGCODE_IFCRYPTALLOWED
+#include "crypt.h"
+#endif
+
+local linkedlist_datablock_internal* allocate_new_datablock()
+{
+ linkedlist_datablock_internal* ldi;
+ ldi = (linkedlist_datablock_internal*)
+ ALLOC(sizeof(linkedlist_datablock_internal));
+ if (ldi!=NULL)
+ {
+ ldi->next_datablock = NULL ;
+ ldi->filled_in_this_block = 0 ;
+ ldi->avail_in_this_block = SIZEDATA_INDATABLOCK ;
+ }
+ return ldi;
+}
+
+local void free_datablock(linkedlist_datablock_internal* ldi)
+{
+ while (ldi!=NULL)
+ {
+ linkedlist_datablock_internal* ldinext = ldi->next_datablock;
+ TRYFREE(ldi);
+ ldi = ldinext;
+ }
+}
+
+local void init_linkedlist(linkedlist_data* ll)
+{
+ ll->first_block = ll->last_block = NULL;
+}
+
+local void free_linkedlist(linkedlist_data* ll)
+{
+ free_datablock(ll->first_block);
+ ll->first_block = ll->last_block = NULL;
+}
+
+
+local int add_data_in_datablock(linkedlist_data* ll, const void* buf, uLong len)
+{
+ linkedlist_datablock_internal* ldi;
+ const unsigned char* from_copy;
+
+ if (ll==NULL)
+ return ZIP_INTERNALERROR;
+
+ if (ll->last_block == NULL)
+ {
+ ll->first_block = ll->last_block = allocate_new_datablock();
+ if (ll->first_block == NULL)
+ return ZIP_INTERNALERROR;
+ }
+
+ ldi = ll->last_block;
+ from_copy = (unsigned char*)buf;
+
+ while (len>0)
+ {
+ uInt copy_this;
+ uInt i;
+ unsigned char* to_copy;
+
+ if (ldi->avail_in_this_block==0)
+ {
+ ldi->next_datablock = allocate_new_datablock();
+ if (ldi->next_datablock == NULL)
+ return ZIP_INTERNALERROR;
+ ldi = ldi->next_datablock ;
+ ll->last_block = ldi;
+ }
+
+ if (ldi->avail_in_this_block < len)
+ copy_this = (uInt)ldi->avail_in_this_block;
+ else
+ copy_this = (uInt)len;
+
+ to_copy = &(ldi->data[ldi->filled_in_this_block]);
+
+ for (i=0;i<copy_this;i++)
+ *(to_copy+i)=*(from_copy+i);
+
+ ldi->filled_in_this_block += copy_this;
+ ldi->avail_in_this_block -= copy_this;
+ from_copy += copy_this ;
+ len -= copy_this;
+ }
+ return ZIP_OK;
+}
+
+
+
+/****************************************************************************/
+
+#ifndef NO_ADDFILEINEXISTINGZIP
+/* ===========================================================================
+ Inputs a long in LSB order to the given file
+ nbByte == 1, 2 ,4 or 8 (byte, short or long, ZPOS64_T)
+*/
+
+local int zip64local_putValue OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte));
+local int zip64local_putValue (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T x, int nbByte)
+{
+ unsigned char buf[8];
+ int n;
+ for (n = 0; n < nbByte; n++)
+ {
+ buf[n] = (unsigned char)(x & 0xff);
+ x >>= 8;
+ }
+ if (x != 0)
+ { /* data overflow - hack for ZIP64 (X Roche) */
+ for (n = 0; n < nbByte; n++)
+ {
+ buf[n] = 0xff;
+ }
+ }
+
+ if (ZWRITE64(*pzlib_filefunc_def,filestream,buf,nbByte)!=(uLong)nbByte)
+ return ZIP_ERRNO;
+ else
+ return ZIP_OK;
+}
+
+local void zip64local_putValue_inmemory OF((void* dest, ZPOS64_T x, int nbByte));
+local void zip64local_putValue_inmemory (void* dest, ZPOS64_T x, int nbByte)
+{
+ unsigned char* buf=(unsigned char*)dest;
+ int n;
+ for (n = 0; n < nbByte; n++) {
+ buf[n] = (unsigned char)(x & 0xff);
+ x >>= 8;
+ }
+
+ if (x != 0)
+ { /* data overflow - hack for ZIP64 */
+ for (n = 0; n < nbByte; n++)
+ {
+ buf[n] = 0xff;
+ }
+ }
+}
+
+/****************************************************************************/
+
+
+local uLong zip64local_TmzDateToDosDate(const tm_zip* ptm)
+{
+ uLong year = (uLong)ptm->tm_year;
+ if (year>=1980)
+ year-=1980;
+ else if (year>=80)
+ year-=80;
+ return
+ (uLong) (((ptm->tm_mday) + (32 * (ptm->tm_mon+1)) + (512 * year)) << 16) |
+ ((ptm->tm_sec/2) + (32* ptm->tm_min) + (2048 * (uLong)ptm->tm_hour));
+}
+
+
+/****************************************************************************/
+
+local int zip64local_getByte OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, int *pi));
+
+local int zip64local_getByte(const zlib_filefunc64_32_def* pzlib_filefunc_def,voidpf filestream,int* pi)
+{
+ unsigned char c;
+ int err = (int)ZREAD64(*pzlib_filefunc_def,filestream,&c,1);
+ if (err==1)
+ {
+ *pi = (int)c;
+ return ZIP_OK;
+ }
+ else
+ {
+ if (ZERROR64(*pzlib_filefunc_def,filestream))
+ return ZIP_ERRNO;
+ else
+ return ZIP_EOF;
+ }
+}
+
+
+/* ===========================================================================
+ Reads a long in LSB order from the given gz_stream. Sets
+*/
+local int zip64local_getShort OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX));
+
+local int zip64local_getShort (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX)
+{
+ uLong x ;
+ int i = 0;
+ int err;
+
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x = (uLong)i;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((uLong)i)<<8;
+
+ if (err==ZIP_OK)
+ *pX = x;
+ else
+ *pX = 0;
+ return err;
+}
+
+local int zip64local_getLong OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX));
+
+local int zip64local_getLong (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong* pX)
+{
+ uLong x ;
+ int i = 0;
+ int err;
+
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x = (uLong)i;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((uLong)i)<<8;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((uLong)i)<<16;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((uLong)i)<<24;
+
+ if (err==ZIP_OK)
+ *pX = x;
+ else
+ *pX = 0;
+ return err;
+}
+
+local int zip64local_getLong64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX));
+
+
+local int zip64local_getLong64 (const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, ZPOS64_T *pX)
+{
+ ZPOS64_T x;
+ int i = 0;
+ int err;
+
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x = (ZPOS64_T)i;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((ZPOS64_T)i)<<8;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((ZPOS64_T)i)<<16;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((ZPOS64_T)i)<<24;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((ZPOS64_T)i)<<32;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((ZPOS64_T)i)<<40;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((ZPOS64_T)i)<<48;
+
+ if (err==ZIP_OK)
+ err = zip64local_getByte(pzlib_filefunc_def,filestream,&i);
+ x += ((ZPOS64_T)i)<<56;
+
+ if (err==ZIP_OK)
+ *pX = x;
+ else
+ *pX = 0;
+
+ return err;
+}
+
+#ifndef BUFREADCOMMENT
+#define BUFREADCOMMENT (0x400)
+#endif
+/*
+ Locate the Central directory of a zipfile (at the end, just before
+ the global comment)
+*/
+local ZPOS64_T zip64local_SearchCentralDir OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
+
+local ZPOS64_T zip64local_SearchCentralDir(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
+{
+ unsigned char* buf;
+ ZPOS64_T uSizeFile;
+ ZPOS64_T uBackRead;
+ ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
+ ZPOS64_T uPosFound=0;
+
+ if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
+ return 0;
+
+
+ uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
+
+ if (uMaxBack>uSizeFile)
+ uMaxBack = uSizeFile;
+
+ buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
+ if (buf==NULL)
+ return 0;
+
+ uBackRead = 4;
+ while (uBackRead<uMaxBack)
+ {
+ uLong uReadSize;
+ ZPOS64_T uReadPos ;
+ int i;
+ if (uBackRead+BUFREADCOMMENT>uMaxBack)
+ uBackRead = uMaxBack;
+ else
+ uBackRead+=BUFREADCOMMENT;
+ uReadPos = uSizeFile-uBackRead ;
+
+ uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
+ (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
+ if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+ break;
+
+ if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
+ break;
+
+ for (i=(int)uReadSize-3; (i--)>0;)
+ if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) &&
+ ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
+ {
+ uPosFound = uReadPos+i;
+ break;
+ }
+
+ if (uPosFound!=0)
+ break;
+ }
+ TRYFREE(buf);
+ return uPosFound;
+}
+
+/*
+Locate the End of Zip64 Central directory locator and from there find the CD of a zipfile (at the end, just before
+the global comment)
+*/
+local ZPOS64_T zip64local_SearchCentralDir64 OF((const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream));
+
+local ZPOS64_T zip64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream)
+{
+ unsigned char* buf;
+ ZPOS64_T uSizeFile;
+ ZPOS64_T uBackRead;
+ ZPOS64_T uMaxBack=0xffff; /* maximum size of global comment */
+ ZPOS64_T uPosFound=0;
+ uLong uL;
+ ZPOS64_T relativeOffset;
+
+ if (ZSEEK64(*pzlib_filefunc_def,filestream,0,ZLIB_FILEFUNC_SEEK_END) != 0)
+ return 0;
+
+ uSizeFile = ZTELL64(*pzlib_filefunc_def,filestream);
+
+ if (uMaxBack>uSizeFile)
+ uMaxBack = uSizeFile;
+
+ buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
+ if (buf==NULL)
+ return 0;
+
+ uBackRead = 4;
+ while (uBackRead<uMaxBack)
+ {
+ uLong uReadSize;
+ ZPOS64_T uReadPos;
+ int i;
+ if (uBackRead+BUFREADCOMMENT>uMaxBack)
+ uBackRead = uMaxBack;
+ else
+ uBackRead+=BUFREADCOMMENT;
+ uReadPos = uSizeFile-uBackRead ;
+
+ uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ?
+ (BUFREADCOMMENT+4) : (uLong)(uSizeFile-uReadPos);
+ if (ZSEEK64(*pzlib_filefunc_def,filestream,uReadPos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+ break;
+
+ if (ZREAD64(*pzlib_filefunc_def,filestream,buf,uReadSize)!=uReadSize)
+ break;
+
+ for (i=(int)uReadSize-3; (i--)>0;)
+ {
+ // Signature "0x07064b50" Zip64 end of central directory locater
+ if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && ((*(buf+i+2))==0x06) && ((*(buf+i+3))==0x07))
+ {
+ uPosFound = uReadPos+i;
+ break;
+ }
+ }
+
+ if (uPosFound!=0)
+ break;
+ }
+
+ TRYFREE(buf);
+ if (uPosFound == 0)
+ return 0;
+
+ /* Zip64 end of central directory locator */
+ if (ZSEEK64(*pzlib_filefunc_def,filestream, uPosFound,ZLIB_FILEFUNC_SEEK_SET)!=0)
+ return 0;
+
+ /* the signature, already checked */
+ if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
+ return 0;
+
+ /* number of the disk with the start of the zip64 end of central directory */
+ if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
+ return 0;
+ if (uL != 0)
+ return 0;
+
+ /* relative offset of the zip64 end of central directory record */
+ if (zip64local_getLong64(pzlib_filefunc_def,filestream,&relativeOffset)!=ZIP_OK)
+ return 0;
+
+ /* total number of disks */
+ if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
+ return 0;
+ if (uL != 1)
+ return 0;
+
+ /* Goto Zip64 end of central directory record */
+ if (ZSEEK64(*pzlib_filefunc_def,filestream, relativeOffset,ZLIB_FILEFUNC_SEEK_SET)!=0)
+ return 0;
+
+ /* the signature */
+ if (zip64local_getLong(pzlib_filefunc_def,filestream,&uL)!=ZIP_OK)
+ return 0;
+
+ if (uL != 0x06064b50) // signature of 'Zip64 end of central directory'
+ return 0;
+
+ return relativeOffset;
+}
+
+int LoadCentralDirectoryRecord(zip64_internal* pziinit)
+{
+ int err=ZIP_OK;
+ ZPOS64_T byte_before_the_zipfile;/* byte before the zipfile, (>0 for sfx)*/
+
+ ZPOS64_T size_central_dir; /* size of the central directory */
+ ZPOS64_T offset_central_dir; /* offset of start of central directory */
+ ZPOS64_T central_pos;
+ uLong uL;
+
+ uLong number_disk; /* number of the current dist, used for
+ spaning ZIP, unsupported, always 0*/
+ uLong number_disk_with_CD; /* number the the disk with central dir, used
+ for spaning ZIP, unsupported, always 0*/
+ ZPOS64_T number_entry;
+ ZPOS64_T number_entry_CD; /* total number of entries in
+ the central dir
+ (same than number_entry on nospan) */
+ uLong VersionMadeBy;
+ uLong VersionNeeded;
+ uLong size_comment;
+
+ int hasZIP64Record = 0;
+
+ // check first if we find a ZIP64 record
+ central_pos = zip64local_SearchCentralDir64(&pziinit->z_filefunc,pziinit->filestream);
+ if(central_pos > 0)
+ {
+ hasZIP64Record = 1;
+ }
+ else if(central_pos == 0)
+ {
+ central_pos = zip64local_SearchCentralDir(&pziinit->z_filefunc,pziinit->filestream);
+ }
+
+/* disable to allow appending to empty ZIP archive
+ if (central_pos==0)
+ err=ZIP_ERRNO;
+*/
+
+ if(hasZIP64Record)
+ {
+ ZPOS64_T sizeEndOfCentralDirectory;
+ if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos, ZLIB_FILEFUNC_SEEK_SET) != 0)
+ err=ZIP_ERRNO;
+
+ /* the signature, already checked */
+ if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* size of zip64 end of central directory record */
+ if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &sizeEndOfCentralDirectory)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* version made by */
+ if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionMadeBy)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* version needed to extract */
+ if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &VersionNeeded)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* number of this disk */
+ if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* number of the disk with the start of the central directory */
+ if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* total number of entries in the central directory on this disk */
+ if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream, &number_entry)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* total number of entries in the central directory */
+ if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&number_entry_CD)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0))
+ err=ZIP_BADZIPFILE;
+
+ /* size of the central directory */
+ if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&size_central_dir)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* offset of start of central directory with respect to the
+ starting disk number */
+ if (zip64local_getLong64(&pziinit->z_filefunc, pziinit->filestream,&offset_central_dir)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ // TODO..
+ // read the comment from the standard central header.
+ size_comment = 0;
+ }
+ else
+ {
+ // Read End of central Directory info
+ if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, central_pos,ZLIB_FILEFUNC_SEEK_SET)!=0)
+ err=ZIP_ERRNO;
+
+ /* the signature, already checked */
+ if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream,&uL)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* number of this disk */
+ if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* number of the disk with the start of the central directory */
+ if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream,&number_disk_with_CD)!=ZIP_OK)
+ err=ZIP_ERRNO;
+
+ /* total number of entries in the central dir on this disk */
+ number_entry = 0;
+ if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
+ err=ZIP_ERRNO;
+ else
+ number_entry = uL;
+
+ /* total number of entries in the central dir */
+ number_entry_CD = 0;
+ if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
+ err=ZIP_ERRNO;
+ else
+ number_entry_CD = uL;
+
+ if ((number_entry_CD!=number_entry) || (number_disk_with_CD!=0) || (number_disk!=0))
+ err=ZIP_BADZIPFILE;
+
+ /* size of the central directory */
+ size_central_dir = 0;
+ if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
+ err=ZIP_ERRNO;
+ else
+ size_central_dir = uL;
+
+ /* offset of start of central directory with respect to the starting disk number */
+ offset_central_dir = 0;
+ if (zip64local_getLong(&pziinit->z_filefunc, pziinit->filestream, &uL)!=ZIP_OK)
+ err=ZIP_ERRNO;
+ else
+ offset_central_dir = uL;
+
+
+ /* zipfile global comment length */
+ if (zip64local_getShort(&pziinit->z_filefunc, pziinit->filestream, &size_comment)!=ZIP_OK)
+ err=ZIP_ERRNO;
+ }
+
+ if ((central_pos<offset_central_dir+size_central_dir) &&
+ (err==ZIP_OK))
+ err=ZIP_BADZIPFILE;
+
+ if (err!=ZIP_OK)
+ {
+ ZCLOSE64(pziinit->z_filefunc, pziinit->filestream);
+ return ZIP_ERRNO;
+ }
+
+ if (size_comment>0)
+ {
+ pziinit->globalcomment = (char*)ALLOC(size_comment+1);
+ if (pziinit->globalcomment)
+ {
+ size_comment = ZREAD64(pziinit->z_filefunc, pziinit->filestream, pziinit->globalcomment,size_comment);
+ pziinit->globalcomment[size_comment]=0;
+ }
+ }
+
+ byte_before_the_zipfile = central_pos - (offset_central_dir+size_central_dir);
+ pziinit->add_position_when_writting_offset = byte_before_the_zipfile;
+
+ {
+ ZPOS64_T size_central_dir_to_read = size_central_dir;
+ size_t buf_size = SIZEDATA_INDATABLOCK;
+ void* buf_read = (void*)ALLOC(buf_size);
+ if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir + byte_before_the_zipfile, ZLIB_FILEFUNC_SEEK_SET) != 0)
+ err=ZIP_ERRNO;
+
+ while ((size_central_dir_to_read>0) && (err==ZIP_OK))
+ {
+ ZPOS64_T read_this = SIZEDATA_INDATABLOCK;
+ if (read_this > size_central_dir_to_read)
+ read_this = size_central_dir_to_read;
+
+ if (ZREAD64(pziinit->z_filefunc, pziinit->filestream,buf_read,(uLong)read_this) != read_this)
+ err=ZIP_ERRNO;
+
+ if (err==ZIP_OK)
+ err = add_data_in_datablock(&pziinit->central_dir,buf_read, (uLong)read_this);
+
+ size_central_dir_to_read-=read_this;
+ }
+ TRYFREE(buf_read);
+ }
+ pziinit->begin_pos = byte_before_the_zipfile;
+ pziinit->number_entry = number_entry_CD;
+
+ if (ZSEEK64(pziinit->z_filefunc, pziinit->filestream, offset_central_dir+byte_before_the_zipfile,ZLIB_FILEFUNC_SEEK_SET) != 0)
+ err=ZIP_ERRNO;
+
+ return err;
+}
+
+
+#endif /* !NO_ADDFILEINEXISTINGZIP*/
+
+
+/************************************************************/
+extern zipFile ZEXPORT zipOpen3 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_32_def* pzlib_filefunc64_32_def)
+{
+ zip64_internal ziinit;
+ zip64_internal* zi;
+ int err=ZIP_OK;
+
+ ziinit.z_filefunc.zseek32_file = NULL;
+ ziinit.z_filefunc.ztell32_file = NULL;
+ if (pzlib_filefunc64_32_def==NULL)
+ fill_fopen64_filefunc(&ziinit.z_filefunc.zfile_func64);
+ else
+ ziinit.z_filefunc = *pzlib_filefunc64_32_def;
+
+ ziinit.filestream = ZOPEN64(ziinit.z_filefunc,
+ pathname,
+ (append == APPEND_STATUS_CREATE) ?
+ (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_CREATE) :
+ (ZLIB_FILEFUNC_MODE_READ | ZLIB_FILEFUNC_MODE_WRITE | ZLIB_FILEFUNC_MODE_EXISTING));
+
+ if (ziinit.filestream == NULL)
+ return NULL;
+
+ if (append == APPEND_STATUS_CREATEAFTER)
+ ZSEEK64(ziinit.z_filefunc,ziinit.filestream,0,SEEK_END);
+
+ ziinit.begin_pos = ZTELL64(ziinit.z_filefunc,ziinit.filestream);
+ ziinit.in_opened_file_inzip = 0;
+ ziinit.ci.stream_initialised = 0;
+ ziinit.number_entry = 0;
+ ziinit.add_position_when_writting_offset = 0;
+ init_linkedlist(&(ziinit.central_dir));
+
+
+
+ zi = (zip64_internal*)ALLOC(sizeof(zip64_internal));
+ if (zi==NULL)
+ {
+ ZCLOSE64(ziinit.z_filefunc,ziinit.filestream);
+ return NULL;
+ }
+
+ /* now we add file in a zipfile */
+# ifndef NO_ADDFILEINEXISTINGZIP
+ ziinit.globalcomment = NULL;
+ if (append == APPEND_STATUS_ADDINZIP)
+ {
+ // Read and Cache Central Directory Records
+ err = LoadCentralDirectoryRecord(&ziinit);
+ }
+
+ if (globalcomment)
+ {
+ *globalcomment = ziinit.globalcomment;
+ }
+# endif /* !NO_ADDFILEINEXISTINGZIP*/
+
+ if (err != ZIP_OK)
+ {
+# ifndef NO_ADDFILEINEXISTINGZIP
+ TRYFREE(ziinit.globalcomment);
+# endif /* !NO_ADDFILEINEXISTINGZIP*/
+ TRYFREE(zi);
+ return NULL;
+ }
+ else
+ {
+ *zi = ziinit;
+ return (zipFile)zi;
+ }
+}
+
+extern zipFile ZEXPORT zipOpen2 (const char *pathname, int append, zipcharpc* globalcomment, zlib_filefunc_def* pzlib_filefunc32_def)
+{
+ if (pzlib_filefunc32_def != NULL)
+ {
+ zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
+ fill_zlib_filefunc64_32_def_from_filefunc32(&zlib_filefunc64_32_def_fill,pzlib_filefunc32_def);
+ return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill);
+ }
+ else
+ return zipOpen3(pathname, append, globalcomment, NULL);
+}
+
+extern zipFile ZEXPORT zipOpen2_64 (const void *pathname, int append, zipcharpc* globalcomment, zlib_filefunc64_def* pzlib_filefunc_def)
+{
+ if (pzlib_filefunc_def != NULL)
+ {
+ zlib_filefunc64_32_def zlib_filefunc64_32_def_fill;
+ zlib_filefunc64_32_def_fill.zfile_func64 = *pzlib_filefunc_def;
+ zlib_filefunc64_32_def_fill.ztell32_file = NULL;
+ zlib_filefunc64_32_def_fill.zseek32_file = NULL;
+ return zipOpen3(pathname, append, globalcomment, &zlib_filefunc64_32_def_fill);
+ }
+ else
+ return zipOpen3(pathname, append, globalcomment, NULL);
+}
+
+
+
+extern zipFile ZEXPORT zipOpen (const char* pathname, int append)
+{
+ return zipOpen3((const void*)pathname,append,NULL,NULL);
+}
+
+extern zipFile ZEXPORT zipOpen64 (const void* pathname, int append)
+{
+ return zipOpen3(pathname,append,NULL,NULL);
+}
+
+int Write_LocalFileHeader(zip64_internal* zi, const char* filename, uInt size_extrafield_local, const void* extrafield_local)
+{
+ /* write the local header */
+ int err;
+ uInt size_filename = (uInt)strlen(filename);
+ uInt size_extrafield = size_extrafield_local;
+
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)LOCALHEADERMAGIC, 4);
+
+ if (err==ZIP_OK)
+ {
+ if(zi->ci.zip64)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);/* version needed to extract */
+ else
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)20,2);/* version needed to extract */
+ }
+
+ if (err==ZIP_OK)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.flag,2);
+
+ if (err==ZIP_OK)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.method,2);
+
+ if (err==ZIP_OK)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->ci.dosDate,4);
+
+ // CRC / Compressed size / Uncompressed size will be filled in later and rewritten later
+ if (err==ZIP_OK)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* crc 32, unknown */
+ if (err==ZIP_OK)
+ {
+ if(zi->ci.zip64)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* compressed size, unknown */
+ else
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* compressed size, unknown */
+ }
+ if (err==ZIP_OK)
+ {
+ if(zi->ci.zip64)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xFFFFFFFF,4); /* uncompressed size, unknown */
+ else
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4); /* uncompressed size, unknown */
+ }
+
+ if (err==ZIP_OK)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_filename,2);
+
+ if(zi->ci.zip64)
+ {
+ size_extrafield += 20;
+ }
+
+ if (err==ZIP_OK)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_extrafield,2);
+
+ if ((err==ZIP_OK) && (size_filename > 0))
+ {
+ if (ZWRITE64(zi->z_filefunc,zi->filestream,filename,size_filename)!=size_filename)
+ err = ZIP_ERRNO;
+ }
+
+ if ((err==ZIP_OK) && (size_extrafield_local > 0))
+ {
+ if (ZWRITE64(zi->z_filefunc, zi->filestream, extrafield_local, size_extrafield_local) != size_extrafield_local)
+ err = ZIP_ERRNO;
+ }
+
+
+ if ((err==ZIP_OK) && (zi->ci.zip64))
+ {
+ // write the Zip64 extended info
+ short HeaderID = 1;
+ short DataSize = 16;
+ ZPOS64_T CompressedSize = 0;
+ ZPOS64_T UncompressedSize = 0;
+
+ // Remember position of Zip64 extended info for the local file header. (needed when we update size after done with file)
+ zi->ci.pos_zip64extrainfo = ZTELL64(zi->z_filefunc,zi->filestream);
+
+ err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)HeaderID,2);
+ err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (short)DataSize,2);
+
+ err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)UncompressedSize,8);
+ err = zip64local_putValue(&zi->z_filefunc, zi->filestream, (ZPOS64_T)CompressedSize,8);
+ }
+
+ return err;
+}
+
+/*
+ NOTE.
+ When writing RAW the ZIP64 extended information in extrafield_local and extrafield_global needs to be stripped
+ before calling this function it can be done with zipRemoveExtraInfoBlock
+
+ It is not done here because then we need to realloc a new buffer since parameters are 'const' and I want to minimize
+ unnecessary allocations.
+ */
+extern int ZEXPORT zipOpenNewFileInZip4_64 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+ const void* extrafield_local, uInt size_extrafield_local,
+ const void* extrafield_global, uInt size_extrafield_global,
+ const char* comment, int method, int level, int raw,
+ int windowBits,int memLevel, int strategy,
+ const char* password, uLong crcForCrypting,
+ uLong versionMadeBy, uLong flagBase, int zip64)
+{
+ zip64_internal* zi;
+ uInt size_filename;
+ uInt size_comment;
+ uInt i;
+ int err = ZIP_OK;
+
+# ifdef NOCRYPT
+ if (password != NULL)
+ return ZIP_PARAMERROR;
+# endif
+
+ if (file == NULL)
+ return ZIP_PARAMERROR;
+
+#ifdef HAVE_BZIP2
+ if ((method!=0) && (method!=Z_DEFLATED) && (method!=Z_BZIP2ED))
+ return ZIP_PARAMERROR;
+#else
+ if ((method!=0) && (method!=Z_DEFLATED))
+ return ZIP_PARAMERROR;
+#endif
+
+ zi = (zip64_internal*)file;
+
+ if (zi->in_opened_file_inzip == 1)
+ {
+ err = zipCloseFileInZip (file);
+ if (err != ZIP_OK)
+ return err;
+ }
+
+ if (filename==NULL)
+ filename="-";
+
+ if (comment==NULL)
+ size_comment = 0;
+ else
+ size_comment = (uInt)strlen(comment);
+
+ size_filename = (uInt)strlen(filename);
+
+ if (zipfi == NULL)
+ zi->ci.dosDate = 0;
+ else
+ {
+ if (zipfi->dosDate != 0)
+ zi->ci.dosDate = zipfi->dosDate;
+ else
+ zi->ci.dosDate = zip64local_TmzDateToDosDate(&zipfi->tmz_date);
+ }
+
+ zi->ci.flag = flagBase;
+ if ((level==8) || (level==9))
+ zi->ci.flag |= 2;
+ if ((level==2))
+ zi->ci.flag |= 4;
+ if ((level==1))
+ zi->ci.flag |= 6;
+ if (password != NULL)
+ zi->ci.flag |= 1;
+
+ zi->ci.crc32 = 0;
+ zi->ci.method = method;
+ zi->ci.encrypt = 0;
+ zi->ci.stream_initialised = 0;
+ zi->ci.pos_in_buffered_data = 0;
+ zi->ci.raw = raw;
+ zi->ci.pos_local_header = ZTELL64(zi->z_filefunc,zi->filestream);
+
+ zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + size_extrafield_global + size_comment;
+ zi->ci.size_centralExtraFree = 32; // Extra space we have reserved in case we need to add ZIP64 extra info data
+
+ zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader + zi->ci.size_centralExtraFree);
+
+ zi->ci.size_centralExtra = size_extrafield_global;
+ zip64local_putValue_inmemory(zi->ci.central_header,(uLong)CENTRALHEADERMAGIC,4);
+ /* version info */
+ zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)versionMadeBy,2);
+ zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)20,2);
+ zip64local_putValue_inmemory(zi->ci.central_header+8,(uLong)zi->ci.flag,2);
+ zip64local_putValue_inmemory(zi->ci.central_header+10,(uLong)zi->ci.method,2);
+ zip64local_putValue_inmemory(zi->ci.central_header+12,(uLong)zi->ci.dosDate,4);
+ zip64local_putValue_inmemory(zi->ci.central_header+16,(uLong)0,4); /*crc*/
+ zip64local_putValue_inmemory(zi->ci.central_header+20,(uLong)0,4); /*compr size*/
+ zip64local_putValue_inmemory(zi->ci.central_header+24,(uLong)0,4); /*uncompr size*/
+ zip64local_putValue_inmemory(zi->ci.central_header+28,(uLong)size_filename,2);
+ zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)size_extrafield_global,2);
+ zip64local_putValue_inmemory(zi->ci.central_header+32,(uLong)size_comment,2);
+ zip64local_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/
+
+ if (zipfi==NULL)
+ zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2);
+ else
+ zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2);
+
+ if (zipfi==NULL)
+ zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4);
+ else
+ zip64local_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4);
+
+ if(zi->ci.pos_local_header >= 0xffffffff)
+ zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)0xffffffff,4);
+ else
+ zip64local_putValue_inmemory(zi->ci.central_header+42,(uLong)zi->ci.pos_local_header - zi->add_position_when_writting_offset,4);
+
+ for (i=0;i<size_filename;i++)
+ *(zi->ci.central_header+SIZECENTRALHEADER+i) = *(filename+i);
+
+ for (i=0;i<size_extrafield_global;i++)
+ *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+i) =
+ *(((const char*)extrafield_global)+i);
+
+ for (i=0;i<size_comment;i++)
+ *(zi->ci.central_header+SIZECENTRALHEADER+size_filename+
+ size_extrafield_global+i) = *(comment+i);
+ if (zi->ci.central_header == NULL)
+ return ZIP_INTERNALERROR;
+
+ zi->ci.zip64 = zip64;
+ zi->ci.totalCompressedData = 0;
+ zi->ci.totalUncompressedData = 0;
+ zi->ci.pos_zip64extrainfo = 0;
+
+ err = Write_LocalFileHeader(zi, filename, size_extrafield_local, extrafield_local);
+
+#ifdef HAVE_BZIP2
+ zi->ci.bstream.avail_in = (uInt)0;
+ zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
+ zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
+ zi->ci.bstream.total_in_hi32 = 0;
+ zi->ci.bstream.total_in_lo32 = 0;
+ zi->ci.bstream.total_out_hi32 = 0;
+ zi->ci.bstream.total_out_lo32 = 0;
+#endif
+
+ zi->ci.stream.avail_in = (uInt)0;
+ zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
+ zi->ci.stream.next_out = zi->ci.buffered_data;
+ zi->ci.stream.total_in = 0;
+ zi->ci.stream.total_out = 0;
+ zi->ci.stream.data_type = Z_BINARY;
+
+#ifdef HAVE_BZIP2
+ if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED || zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
+#else
+ if ((err==ZIP_OK) && (zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
+#endif
+ {
+ if(zi->ci.method == Z_DEFLATED)
+ {
+ zi->ci.stream.zalloc = (alloc_func)0;
+ zi->ci.stream.zfree = (free_func)0;
+ zi->ci.stream.opaque = (voidpf)0;
+
+ if (windowBits>0)
+ windowBits = -windowBits;
+
+ err = deflateInit2(&zi->ci.stream, level, Z_DEFLATED, windowBits, memLevel, strategy);
+
+ if (err==Z_OK)
+ zi->ci.stream_initialised = Z_DEFLATED;
+ }
+ else if(zi->ci.method == Z_BZIP2ED)
+ {
+#ifdef HAVE_BZIP2
+ // Init BZip stuff here
+ zi->ci.bstream.bzalloc = 0;
+ zi->ci.bstream.bzfree = 0;
+ zi->ci.bstream.opaque = (voidpf)0;
+
+ err = BZ2_bzCompressInit(&zi->ci.bstream, level, 0,35);
+ if(err == BZ_OK)
+ zi->ci.stream_initialised = Z_BZIP2ED;
+#endif
+ }
+
+ }
+
+# ifndef NOCRYPT
+ zi->ci.crypt_header_size = 0;
+ if ((err==Z_OK) && (password != NULL))
+ {
+ unsigned char bufHead[RAND_HEAD_LEN];
+ unsigned int sizeHead;
+ zi->ci.encrypt = 1;
+ zi->ci.pcrc_32_tab = get_crc_table();
+ /*init_keys(password,zi->ci.keys,zi->ci.pcrc_32_tab);*/
+
+ sizeHead=crypthead(password,bufHead,RAND_HEAD_LEN,zi->ci.keys,zi->ci.pcrc_32_tab,crcForCrypting);
+ zi->ci.crypt_header_size = sizeHead;
+
+ if (ZWRITE64(zi->z_filefunc,zi->filestream,bufHead,sizeHead) != sizeHead)
+ err = ZIP_ERRNO;
+ }
+# endif
+
+ if (err==Z_OK)
+ zi->in_opened_file_inzip = 1;
+ return err;
+}
+
+extern int ZEXPORT zipOpenNewFileInZip4 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+ const void* extrafield_local, uInt size_extrafield_local,
+ const void* extrafield_global, uInt size_extrafield_global,
+ const char* comment, int method, int level, int raw,
+ int windowBits,int memLevel, int strategy,
+ const char* password, uLong crcForCrypting,
+ uLong versionMadeBy, uLong flagBase)
+{
+ return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+ extrafield_local, size_extrafield_local,
+ extrafield_global, size_extrafield_global,
+ comment, method, level, raw,
+ windowBits, memLevel, strategy,
+ password, crcForCrypting, versionMadeBy, flagBase, 0);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip3 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+ const void* extrafield_local, uInt size_extrafield_local,
+ const void* extrafield_global, uInt size_extrafield_global,
+ const char* comment, int method, int level, int raw,
+ int windowBits,int memLevel, int strategy,
+ const char* password, uLong crcForCrypting)
+{
+ return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+ extrafield_local, size_extrafield_local,
+ extrafield_global, size_extrafield_global,
+ comment, method, level, raw,
+ windowBits, memLevel, strategy,
+ password, crcForCrypting, VERSIONMADEBY, 0, 0);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip3_64(zipFile file, const char* filename, const zip_fileinfo* zipfi,
+ const void* extrafield_local, uInt size_extrafield_local,
+ const void* extrafield_global, uInt size_extrafield_global,
+ const char* comment, int method, int level, int raw,
+ int windowBits,int memLevel, int strategy,
+ const char* password, uLong crcForCrypting, int zip64)
+{
+ return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+ extrafield_local, size_extrafield_local,
+ extrafield_global, size_extrafield_global,
+ comment, method, level, raw,
+ windowBits, memLevel, strategy,
+ password, crcForCrypting, VERSIONMADEBY, 0, zip64);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip2(zipFile file, const char* filename, const zip_fileinfo* zipfi,
+ const void* extrafield_local, uInt size_extrafield_local,
+ const void* extrafield_global, uInt size_extrafield_global,
+ const char* comment, int method, int level, int raw)
+{
+ return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+ extrafield_local, size_extrafield_local,
+ extrafield_global, size_extrafield_global,
+ comment, method, level, raw,
+ -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+ NULL, 0, VERSIONMADEBY, 0, 0);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip2_64(zipFile file, const char* filename, const zip_fileinfo* zipfi,
+ const void* extrafield_local, uInt size_extrafield_local,
+ const void* extrafield_global, uInt size_extrafield_global,
+ const char* comment, int method, int level, int raw, int zip64)
+{
+ return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+ extrafield_local, size_extrafield_local,
+ extrafield_global, size_extrafield_global,
+ comment, method, level, raw,
+ -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+ NULL, 0, VERSIONMADEBY, 0, zip64);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip64 (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+ const void* extrafield_local, uInt size_extrafield_local,
+ const void*extrafield_global, uInt size_extrafield_global,
+ const char* comment, int method, int level, int zip64)
+{
+ return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+ extrafield_local, size_extrafield_local,
+ extrafield_global, size_extrafield_global,
+ comment, method, level, 0,
+ -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+ NULL, 0, VERSIONMADEBY, 0, zip64);
+}
+
+extern int ZEXPORT zipOpenNewFileInZip (zipFile file, const char* filename, const zip_fileinfo* zipfi,
+ const void* extrafield_local, uInt size_extrafield_local,
+ const void*extrafield_global, uInt size_extrafield_global,
+ const char* comment, int method, int level)
+{
+ return zipOpenNewFileInZip4_64 (file, filename, zipfi,
+ extrafield_local, size_extrafield_local,
+ extrafield_global, size_extrafield_global,
+ comment, method, level, 0,
+ -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY,
+ NULL, 0, VERSIONMADEBY, 0, 0);
+}
+
+local int zip64FlushWriteBuffer(zip64_internal* zi)
+{
+ int err=ZIP_OK;
+
+ if (zi->ci.encrypt != 0)
+ {
+#ifndef NOCRYPT
+ uInt i;
+ int t;
+ for (i=0;i<zi->ci.pos_in_buffered_data;i++)
+ zi->ci.buffered_data[i] = zencode(zi->ci.keys, zi->ci.pcrc_32_tab, zi->ci.buffered_data[i],t);
+#endif
+ }
+
+ if (ZWRITE64(zi->z_filefunc,zi->filestream,zi->ci.buffered_data,zi->ci.pos_in_buffered_data) != zi->ci.pos_in_buffered_data)
+ err = ZIP_ERRNO;
+
+ zi->ci.totalCompressedData += zi->ci.pos_in_buffered_data;
+
+#ifdef HAVE_BZIP2
+ if(zi->ci.method == Z_BZIP2ED)
+ {
+ zi->ci.totalUncompressedData += zi->ci.bstream.total_in_lo32;
+ zi->ci.bstream.total_in_lo32 = 0;
+ zi->ci.bstream.total_in_hi32 = 0;
+ }
+ else
+#endif
+ {
+ zi->ci.totalUncompressedData += zi->ci.stream.total_in;
+ zi->ci.stream.total_in = 0;
+ }
+
+
+ zi->ci.pos_in_buffered_data = 0;
+
+ return err;
+}
+
+extern int ZEXPORT zipWriteInFileInZip (zipFile file,const void* buf,unsigned int len)
+{
+ zip64_internal* zi;
+ int err=ZIP_OK;
+
+ if (file == NULL)
+ return ZIP_PARAMERROR;
+ zi = (zip64_internal*)file;
+
+ if (zi->in_opened_file_inzip == 0)
+ return ZIP_PARAMERROR;
+
+ zi->ci.crc32 = crc32(zi->ci.crc32,buf,(uInt)len);
+
+#ifdef HAVE_BZIP2
+ if(zi->ci.method == Z_BZIP2ED && (!zi->ci.raw))
+ {
+ zi->ci.bstream.next_in = (void*)buf;
+ zi->ci.bstream.avail_in = len;
+ err = BZ_RUN_OK;
+
+ while ((err==BZ_RUN_OK) && (zi->ci.bstream.avail_in>0))
+ {
+ if (zi->ci.bstream.avail_out == 0)
+ {
+ if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
+ err = ZIP_ERRNO;
+ zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
+ zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
+ }
+
+
+ if(err != BZ_RUN_OK)
+ break;
+
+ if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
+ {
+ uLong uTotalOutBefore_lo = zi->ci.bstream.total_out_lo32;
+// uLong uTotalOutBefore_hi = zi->ci.bstream.total_out_hi32;
+ err=BZ2_bzCompress(&zi->ci.bstream, BZ_RUN);
+
+ zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore_lo) ;
+ }
+ }
+
+ if(err == BZ_RUN_OK)
+ err = ZIP_OK;
+ }
+ else
+#endif
+ {
+ zi->ci.stream.next_in = (Bytef*)buf;
+ zi->ci.stream.avail_in = len;
+
+ while ((err==ZIP_OK) && (zi->ci.stream.avail_in>0))
+ {
+ if (zi->ci.stream.avail_out == 0)
+ {
+ if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
+ err = ZIP_ERRNO;
+ zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
+ zi->ci.stream.next_out = zi->ci.buffered_data;
+ }
+
+
+ if(err != ZIP_OK)
+ break;
+
+ if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
+ {
+ uLong uTotalOutBefore = zi->ci.stream.total_out;
+ err=deflate(&zi->ci.stream, Z_NO_FLUSH);
+ if(uTotalOutBefore > zi->ci.stream.total_out)
+ {
+ int bBreak = 0;
+ bBreak++;
+ }
+
+ zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ;
+ }
+ else
+ {
+ uInt copy_this,i;
+ if (zi->ci.stream.avail_in < zi->ci.stream.avail_out)
+ copy_this = zi->ci.stream.avail_in;
+ else
+ copy_this = zi->ci.stream.avail_out;
+
+ for (i = 0; i < copy_this; i++)
+ *(((char*)zi->ci.stream.next_out)+i) =
+ *(((const char*)zi->ci.stream.next_in)+i);
+ {
+ zi->ci.stream.avail_in -= copy_this;
+ zi->ci.stream.avail_out-= copy_this;
+ zi->ci.stream.next_in+= copy_this;
+ zi->ci.stream.next_out+= copy_this;
+ zi->ci.stream.total_in+= copy_this;
+ zi->ci.stream.total_out+= copy_this;
+ zi->ci.pos_in_buffered_data += copy_this;
+ }
+ }
+ }// while(...)
+ }
+
+ return err;
+}
+
+extern int ZEXPORT zipCloseFileInZipRaw (zipFile file, uLong uncompressed_size, uLong crc32)
+{
+ return zipCloseFileInZipRaw64 (file, uncompressed_size, crc32);
+}
+
+extern int ZEXPORT zipCloseFileInZipRaw64 (zipFile file, ZPOS64_T uncompressed_size, uLong crc32)
+{
+ zip64_internal* zi;
+ ZPOS64_T compressed_size;
+ uLong invalidValue = 0xffffffff;
+ short datasize = 0;
+ int err=ZIP_OK;
+
+ if (file == NULL)
+ return ZIP_PARAMERROR;
+ zi = (zip64_internal*)file;
+
+ if (zi->in_opened_file_inzip == 0)
+ return ZIP_PARAMERROR;
+ zi->ci.stream.avail_in = 0;
+
+ if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
+ {
+ while (err==ZIP_OK)
+ {
+ uLong uTotalOutBefore;
+ if (zi->ci.stream.avail_out == 0)
+ {
+ if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
+ err = ZIP_ERRNO;
+ zi->ci.stream.avail_out = (uInt)Z_BUFSIZE;
+ zi->ci.stream.next_out = zi->ci.buffered_data;
+ }
+ uTotalOutBefore = zi->ci.stream.total_out;
+ err=deflate(&zi->ci.stream, Z_FINISH);
+ zi->ci.pos_in_buffered_data += (uInt)(zi->ci.stream.total_out - uTotalOutBefore) ;
+ }
+ }
+ else if ((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
+ {
+#ifdef HAVE_BZIP2
+ err = BZ_FINISH_OK;
+ while (err==BZ_FINISH_OK)
+ {
+ uLong uTotalOutBefore;
+ if (zi->ci.bstream.avail_out == 0)
+ {
+ if (zip64FlushWriteBuffer(zi) == ZIP_ERRNO)
+ err = ZIP_ERRNO;
+ zi->ci.bstream.avail_out = (uInt)Z_BUFSIZE;
+ zi->ci.bstream.next_out = (char*)zi->ci.buffered_data;
+ }
+ uTotalOutBefore = zi->ci.bstream.total_out_lo32;
+ err=BZ2_bzCompress(&zi->ci.bstream, BZ_FINISH);
+ if(err == BZ_STREAM_END)
+ err = Z_STREAM_END;
+
+ zi->ci.pos_in_buffered_data += (uInt)(zi->ci.bstream.total_out_lo32 - uTotalOutBefore);
+ }
+
+ if(err == BZ_FINISH_OK)
+ err = ZIP_OK;
+#endif
+ }
+
+ if (err==Z_STREAM_END)
+ err=ZIP_OK; /* this is normal */
+
+ if ((zi->ci.pos_in_buffered_data>0) && (err==ZIP_OK))
+ {
+ if (zip64FlushWriteBuffer(zi)==ZIP_ERRNO)
+ err = ZIP_ERRNO;
+ }
+
+ if ((zi->ci.method == Z_DEFLATED) && (!zi->ci.raw))
+ {
+ int tmp_err = deflateEnd(&zi->ci.stream);
+ if (err == ZIP_OK)
+ err = tmp_err;
+ zi->ci.stream_initialised = 0;
+ }
+#ifdef HAVE_BZIP2
+ else if((zi->ci.method == Z_BZIP2ED) && (!zi->ci.raw))
+ {
+ int tmperr = BZ2_bzCompressEnd(&zi->ci.bstream);
+ if (err==ZIP_OK)
+ err = tmperr;
+ zi->ci.stream_initialised = 0;
+ }
+#endif
+
+ if (!zi->ci.raw)
+ {
+ crc32 = (uLong)zi->ci.crc32;
+ uncompressed_size = zi->ci.totalUncompressedData;
+ }
+ compressed_size = zi->ci.totalCompressedData;
+
+# ifndef NOCRYPT
+ compressed_size += zi->ci.crypt_header_size;
+# endif
+
+ // update Current Item crc and sizes,
+ if(compressed_size >= 0xffffffff || uncompressed_size >= 0xffffffff || zi->ci.pos_local_header >= 0xffffffff)
+ {
+ /*version Made by*/
+ zip64local_putValue_inmemory(zi->ci.central_header+4,(uLong)45,2);
+ /*version needed*/
+ zip64local_putValue_inmemory(zi->ci.central_header+6,(uLong)45,2);
+
+ }
+
+ zip64local_putValue_inmemory(zi->ci.central_header+16,crc32,4); /*crc*/
+
+
+ if(compressed_size >= 0xffffffff)
+ zip64local_putValue_inmemory(zi->ci.central_header+20, invalidValue,4); /*compr size*/
+ else
+ zip64local_putValue_inmemory(zi->ci.central_header+20, compressed_size,4); /*compr size*/
+
+ /// set internal file attributes field
+ if (zi->ci.stream.data_type == Z_ASCII)
+ zip64local_putValue_inmemory(zi->ci.central_header+36,(uLong)Z_ASCII,2);
+
+ if(uncompressed_size >= 0xffffffff)
+ zip64local_putValue_inmemory(zi->ci.central_header+24, invalidValue,4); /*uncompr size*/
+ else
+ zip64local_putValue_inmemory(zi->ci.central_header+24, uncompressed_size,4); /*uncompr size*/
+
+ // Add ZIP64 extra info field for uncompressed size
+ if(uncompressed_size >= 0xffffffff)
+ datasize += 8;
+
+ // Add ZIP64 extra info field for compressed size
+ if(compressed_size >= 0xffffffff)
+ datasize += 8;
+
+ // Add ZIP64 extra info field for relative offset to local file header of current file
+ if(zi->ci.pos_local_header >= 0xffffffff)
+ datasize += 8;
+
+ if(datasize > 0)
+ {
+ char* p = NULL;
+
+ if((uLong)(datasize + 4) > zi->ci.size_centralExtraFree)
+ {
+ // we can not write more data to the buffer that we have room for.
+ return ZIP_BADZIPFILE;
+ }
+
+ p = zi->ci.central_header + zi->ci.size_centralheader;
+
+ // Add Extra Information Header for 'ZIP64 information'
+ zip64local_putValue_inmemory(p, 0x0001, 2); // HeaderID
+ p += 2;
+ zip64local_putValue_inmemory(p, datasize, 2); // DataSize
+ p += 2;
+
+ if(uncompressed_size >= 0xffffffff)
+ {
+ zip64local_putValue_inmemory(p, uncompressed_size, 8);
+ p += 8;
+ }
+
+ if(compressed_size >= 0xffffffff)
+ {
+ zip64local_putValue_inmemory(p, compressed_size, 8);
+ p += 8;
+ }
+
+ if(zi->ci.pos_local_header >= 0xffffffff)
+ {
+ zip64local_putValue_inmemory(p, zi->ci.pos_local_header, 8);
+ p += 8;
+ }
+
+ // Update how much extra free space we got in the memory buffer
+ // and increase the centralheader size so the new ZIP64 fields are included
+ // ( 4 below is the size of HeaderID and DataSize field )
+ zi->ci.size_centralExtraFree -= datasize + 4;
+ zi->ci.size_centralheader += datasize + 4;
+
+ // Update the extra info size field
+ zi->ci.size_centralExtra += datasize + 4;
+ zip64local_putValue_inmemory(zi->ci.central_header+30,(uLong)zi->ci.size_centralExtra,2);
+ }
+
+ if (err==ZIP_OK)
+ err = add_data_in_datablock(&zi->central_dir, zi->ci.central_header, (uLong)zi->ci.size_centralheader);
+
+ free(zi->ci.central_header);
+
+ if (err==ZIP_OK)
+ {
+ // Update the LocalFileHeader with the new values.
+
+ ZPOS64_T cur_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream);
+
+ if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_local_header + 14,ZLIB_FILEFUNC_SEEK_SET)!=0)
+ err = ZIP_ERRNO;
+
+ if (err==ZIP_OK)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,crc32,4); /* crc 32, unknown */
+
+ if(uncompressed_size >= 0xffffffff)
+ {
+ if(zi->ci.pos_zip64extrainfo > 0)
+ {
+ // Update the size in the ZIP64 extended field.
+ if (ZSEEK64(zi->z_filefunc,zi->filestream, zi->ci.pos_zip64extrainfo + 4,ZLIB_FILEFUNC_SEEK_SET)!=0)
+ err = ZIP_ERRNO;
+
+ if (err==ZIP_OK) /* compressed size, unknown */
+ err = zip64local_putValue(&zi->z_filefunc, zi->filestream, uncompressed_size, 8);
+
+ if (err==ZIP_OK) /* uncompressed size, unknown */
+ err = zip64local_putValue(&zi->z_filefunc, zi->filestream, compressed_size, 8);
+ }
+ }
+ else
+ {
+ if (err==ZIP_OK) /* compressed size, unknown */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,compressed_size,4);
+
+ if (err==ZIP_OK) /* uncompressed size, unknown */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,uncompressed_size,4);
+ }
+
+ if (ZSEEK64(zi->z_filefunc,zi->filestream, cur_pos_inzip,ZLIB_FILEFUNC_SEEK_SET)!=0)
+ err = ZIP_ERRNO;
+ }
+
+ zi->number_entry ++;
+ zi->in_opened_file_inzip = 0;
+
+ return err;
+}
+
+extern int ZEXPORT zipCloseFileInZip (zipFile file)
+{
+ return zipCloseFileInZipRaw (file,0,0);
+}
+
+int Write_Zip64EndOfCentralDirectoryLocator(zip64_internal* zi, ZPOS64_T zip64eocd_pos_inzip)
+{
+ int err = ZIP_OK;
+ ZPOS64_T pos = zip64eocd_pos_inzip - zi->add_position_when_writting_offset;
+
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDLOCHEADERMAGIC,4);
+
+ /*num disks*/
+ if (err==ZIP_OK) /* number of the disk with the start of the central directory */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
+
+ /*relative offset*/
+ if (err==ZIP_OK) /* Relative offset to the Zip64EndOfCentralDirectory */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream, pos,8);
+
+ /*total disks*/ /* Do not support spawning of disk so always say 1 here*/
+ if (err==ZIP_OK) /* number of the disk with the start of the central directory */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)1,4);
+
+ return err;
+}
+
+int Write_Zip64EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip)
+{
+ int err = ZIP_OK;
+
+ uLong Zip64DataSize = 44;
+
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ZIP64ENDHEADERMAGIC,4);
+
+ if (err==ZIP_OK) /* size of this 'zip64 end of central directory' */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)Zip64DataSize,8); // why ZPOS64_T of this ?
+
+ if (err==ZIP_OK) /* version made by */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);
+
+ if (err==ZIP_OK) /* version needed */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)45,2);
+
+ if (err==ZIP_OK) /* number of this disk */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
+
+ if (err==ZIP_OK) /* number of the disk with the start of the central directory */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,4);
+
+ if (err==ZIP_OK) /* total number of entries in the central dir on this disk */
+ err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8);
+
+ if (err==ZIP_OK) /* total number of entries in the central dir */
+ err = zip64local_putValue(&zi->z_filefunc, zi->filestream, zi->number_entry, 8);
+
+ if (err==ZIP_OK) /* size of the central directory */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(ZPOS64_T)size_centraldir,8);
+
+ if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */
+ {
+ ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (ZPOS64_T)pos,8);
+ }
+ return err;
+}
+int Write_EndOfCentralDirectoryRecord(zip64_internal* zi, uLong size_centraldir, ZPOS64_T centraldir_pos_inzip)
+{
+ int err = ZIP_OK;
+
+ /*signature*/
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)ENDHEADERMAGIC,4);
+
+ if (err==ZIP_OK) /* number of this disk */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2);
+
+ if (err==ZIP_OK) /* number of the disk with the start of the central directory */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0,2);
+
+ if (err==ZIP_OK) /* total number of entries in the central dir on this disk */
+ {
+ {
+ if(zi->number_entry >= 0xFFFF)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record
+ else
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2);
+ }
+ }
+
+ if (err==ZIP_OK) /* total number of entries in the central dir */
+ {
+ if(zi->number_entry >= 0xFFFF)
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)0xffff,2); // use value in ZIP64 record
+ else
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)zi->number_entry,2);
+ }
+
+ if (err==ZIP_OK) /* size of the central directory */
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_centraldir,4);
+
+ if (err==ZIP_OK) /* offset of start of central directory with respect to the starting disk number */
+ {
+ ZPOS64_T pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
+ if(pos >= 0xffffffff)
+ {
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)0xffffffff,4);
+ }
+ else
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream, (uLong)(centraldir_pos_inzip - zi->add_position_when_writting_offset),4);
+ }
+
+ return err;
+}
+
+int Write_GlobalComment(zip64_internal* zi, const char* global_comment)
+{
+ int err = ZIP_OK;
+ uInt size_global_comment = 0;
+
+ if(global_comment != NULL)
+ size_global_comment = (uInt)strlen(global_comment);
+
+ err = zip64local_putValue(&zi->z_filefunc,zi->filestream,(uLong)size_global_comment,2);
+
+ if (err == ZIP_OK && size_global_comment > 0)
+ {
+ if (ZWRITE64(zi->z_filefunc,zi->filestream, global_comment, size_global_comment) != size_global_comment)
+ err = ZIP_ERRNO;
+ }
+ return err;
+}
+
+extern int ZEXPORT zipClose (zipFile file, const char* global_comment)
+{
+ zip64_internal* zi;
+ int err = 0;
+ uLong size_centraldir = 0;
+ ZPOS64_T centraldir_pos_inzip;
+ ZPOS64_T pos;
+
+ if (file == NULL)
+ return ZIP_PARAMERROR;
+
+ zi = (zip64_internal*)file;
+
+ if (zi->in_opened_file_inzip == 1)
+ {
+ err = zipCloseFileInZip (file);
+ }
+
+#ifndef NO_ADDFILEINEXISTINGZIP
+ if (global_comment==NULL)
+ global_comment = zi->globalcomment;
+#endif
+
+ centraldir_pos_inzip = ZTELL64(zi->z_filefunc,zi->filestream);
+
+ if (err==ZIP_OK)
+ {
+ linkedlist_datablock_internal* ldi = zi->central_dir.first_block;
+ while (ldi!=NULL)
+ {
+ if ((err==ZIP_OK) && (ldi->filled_in_this_block>0))
+ {
+ if (ZWRITE64(zi->z_filefunc,zi->filestream, ldi->data, ldi->filled_in_this_block) != ldi->filled_in_this_block)
+ err = ZIP_ERRNO;
+ }
+
+ size_centraldir += ldi->filled_in_this_block;
+ ldi = ldi->next_datablock;
+ }
+ }
+ free_linkedlist(&(zi->central_dir));
+
+ pos = centraldir_pos_inzip - zi->add_position_when_writting_offset;
+ if(pos >= 0xffffffff)
+ {
+ ZPOS64_T Zip64EOCDpos = ZTELL64(zi->z_filefunc,zi->filestream);
+ Write_Zip64EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip);
+
+ Write_Zip64EndOfCentralDirectoryLocator(zi, Zip64EOCDpos);
+ }
+
+ if (err==ZIP_OK)
+ err = Write_EndOfCentralDirectoryRecord(zi, size_centraldir, centraldir_pos_inzip);
+
+ if(err == ZIP_OK)
+ err = Write_GlobalComment(zi, global_comment);
+
+ if (ZCLOSE64(zi->z_filefunc,zi->filestream) != 0)
+ if (err == ZIP_OK)
+ err = ZIP_ERRNO;
+
+#ifndef NO_ADDFILEINEXISTINGZIP
+ TRYFREE(zi->globalcomment);
+#endif
+ TRYFREE(zi);
+
+ return err;
+}
+
+extern int ZEXPORT zipRemoveExtraInfoBlock (char* pData, int* dataLen, short sHeader)
+{
+ char* p = pData;
+ int size = 0;
+ char* pNewHeader;
+ char* pTmp;
+ short header;
+ short dataSize;
+
+ int retVal = ZIP_OK;
+
+ if(pData == NULL || *dataLen < 4)
+ return ZIP_PARAMERROR;
+
+ pNewHeader = (char*)ALLOC(*dataLen);
+ pTmp = pNewHeader;
+
+ while(p < (pData + *dataLen))
+ {
+ header = *(short*)p;
+ dataSize = *(((short*)p)+1);
+
+ if( header == sHeader ) // Header found.
+ {
+ p += dataSize + 4; // skip it. do not copy to temp buffer
+ }
+ else
+ {
+ // Extra Info block should not be removed, So copy it to the temp buffer.
+ memcpy(pTmp, p, dataSize + 4);
+ p += dataSize + 4;
+ size += dataSize + 4;
+ }
+
+ }
+
+ if(size < *dataLen)
+ {
+ // clean old extra info block.
+ memset(pData,0, *dataLen);
+
+ // copy the new extra info block over the old
+ if(size > 0)
+ memcpy(pData, pNewHeader, size);
+
+ // set the new extra info size
+ *dataLen = size;
+
+ retVal = ZIP_OK;
+ }
+ else
+ retVal = ZIP_ERRNO;
+
+ TRYFREE(pNewHeader);
+
+ return retVal;
+}
diff --git a/plugins/FTPFileYM/zip/zip.h b/plugins/FTPFileYM/zip/zip.h
new file mode 100644
index 0000000000..8aaebb6234
--- /dev/null
+++ b/plugins/FTPFileYM/zip/zip.h
@@ -0,0 +1,362 @@
+/* zip.h -- IO on .zip files using zlib
+ Version 1.1, February 14h, 2010
+ part of the MiniZip project - ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Copyright (C) 1998-2010 Gilles Vollant (minizip) ( http://www.winimage.com/zLibDll/minizip.html )
+
+ Modifications for Zip64 support
+ Copyright (C) 2009-2010 Mathias Svensson ( http://result42.com )
+
+ For more info read MiniZip_info.txt
+
+ ---------------------------------------------------------------------------
+
+ Condition of use and distribution are the same than zlib :
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ ---------------------------------------------------------------------------
+
+ Changes
+
+ See header of zip.h
+
+*/
+
+#ifndef _zip12_H
+#define _zip12_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//#define HAVE_BZIP2
+
+#ifndef _ZLIB_H
+#include "zlib.h"
+#endif
+
+#ifndef _ZLIBIOAPI_H
+#include "ioapi.h"
+#endif
+
+#ifdef HAVE_BZIP2
+#include "bzlib.h"
+#endif
+
+#define Z_BZIP2ED 12
+
+#if defined(STRICTZIP) || defined(STRICTZIPUNZIP)
+/* like the STRICT of WIN32, we define a pointer that cannot be converted
+ from (void*) without cast */
+typedef struct TagzipFile__ { int unused; } zipFile__;
+typedef zipFile__ *zipFile;
+#else
+typedef voidp zipFile;
+#endif
+
+#define ZIP_OK (0)
+#define ZIP_EOF (0)
+#define ZIP_ERRNO (Z_ERRNO)
+#define ZIP_PARAMERROR (-102)
+#define ZIP_BADZIPFILE (-103)
+#define ZIP_INTERNALERROR (-104)
+
+#ifndef DEF_MEM_LEVEL
+# if MAX_MEM_LEVEL >= 8
+# define DEF_MEM_LEVEL 8
+# else
+# define DEF_MEM_LEVEL MAX_MEM_LEVEL
+# endif
+#endif
+/* default memLevel */
+
+/* tm_zip contain date/time info */
+typedef struct tm_zip_s
+{
+ uInt tm_sec; /* seconds after the minute - [0,59] */
+ uInt tm_min; /* minutes after the hour - [0,59] */
+ uInt tm_hour; /* hours since midnight - [0,23] */
+ uInt tm_mday; /* day of the month - [1,31] */
+ uInt tm_mon; /* months since January - [0,11] */
+ uInt tm_year; /* years - [1980..2044] */
+} tm_zip;
+
+typedef struct
+{
+ tm_zip tmz_date; /* date in understandable format */
+ uLong dosDate; /* if dos_date == 0, tmu_date is used */
+/* uLong flag; */ /* general purpose bit flag 2 bytes */
+
+ uLong internal_fa; /* internal file attributes 2 bytes */
+ uLong external_fa; /* external file attributes 4 bytes */
+} zip_fileinfo;
+
+typedef const char* zipcharpc;
+
+
+#define APPEND_STATUS_CREATE (0)
+#define APPEND_STATUS_CREATEAFTER (1)
+#define APPEND_STATUS_ADDINZIP (2)
+
+extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append));
+extern zipFile ZEXPORT zipOpen64 OF((const void *pathname, int append));
+/*
+ Create a zipfile.
+ pathname contain on Windows XP a filename like "c:\\zlib\\zlib113.zip" or on
+ an Unix computer "zlib/zlib113.zip".
+ if the file pathname exist and append==APPEND_STATUS_CREATEAFTER, the zip
+ will be created at the end of the file.
+ (useful if the file contain a self extractor code)
+ if the file pathname exist and append==APPEND_STATUS_ADDINZIP, we will
+ add files in existing zip (be sure you don't add file that doesn't exist)
+ If the zipfile cannot be opened, the return value is NULL.
+ Else, the return value is a zipFile Handle, usable with other function
+ of this zip package.
+*/
+
+/* Note : there is no delete function into a zipfile.
+ If you want delete file into a zipfile, you must open a zipfile, and create another
+ Of couse, you can use RAW reading and writing to copy the file you did not want delte
+*/
+
+extern zipFile ZEXPORT zipOpen2 OF((const char *pathname,
+ int append,
+ zipcharpc* globalcomment,
+ zlib_filefunc_def* pzlib_filefunc_def));
+
+extern zipFile ZEXPORT zipOpen2_64 OF((const void *pathname,
+ int append,
+ zipcharpc* globalcomment,
+ zlib_filefunc64_def* pzlib_filefunc_def));
+
+extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
+ const char* filename,
+ const zip_fileinfo* zipfi,
+ const void* extrafield_local,
+ uInt size_extrafield_local,
+ const void* extrafield_global,
+ uInt size_extrafield_global,
+ const char* comment,
+ int method,
+ int level));
+
+extern int ZEXPORT zipOpenNewFileInZip64 OF((zipFile file,
+ const char* filename,
+ const zip_fileinfo* zipfi,
+ const void* extrafield_local,
+ uInt size_extrafield_local,
+ const void* extrafield_global,
+ uInt size_extrafield_global,
+ const char* comment,
+ int method,
+ int level,
+ int zip64));
+
+/*
+ Open a file in the ZIP for writing.
+ filename : the filename in zip (if NULL, '-' without quote will be used
+ *zipfi contain supplemental information
+ if extrafield_local!=NULL and size_extrafield_local>0, extrafield_local
+ contains the extrafield data the the local header
+ if extrafield_global!=NULL and size_extrafield_global>0, extrafield_global
+ contains the extrafield data the the local header
+ if comment != NULL, comment contain the comment string
+ method contain the compression method (0 for store, Z_DEFLATED for deflate)
+ level contain the level of compression (can be Z_DEFAULT_COMPRESSION)
+ zip64 is set to 1 if a zip64 extended information block should be added to the local file header.
+ this MUST be '1' if the uncompressed size is >= 0xffffffff.
+
+*/
+
+
+extern int ZEXPORT zipOpenNewFileInZip2 OF((zipFile file,
+ const char* filename,
+ const zip_fileinfo* zipfi,
+ const void* extrafield_local,
+ uInt size_extrafield_local,
+ const void* extrafield_global,
+ uInt size_extrafield_global,
+ const char* comment,
+ int method,
+ int level,
+ int raw));
+
+
+extern int ZEXPORT zipOpenNewFileInZip2_64 OF((zipFile file,
+ const char* filename,
+ const zip_fileinfo* zipfi,
+ const void* extrafield_local,
+ uInt size_extrafield_local,
+ const void* extrafield_global,
+ uInt size_extrafield_global,
+ const char* comment,
+ int method,
+ int level,
+ int raw,
+ int zip64));
+/*
+ Same than zipOpenNewFileInZip, except if raw=1, we write raw file
+ */
+
+extern int ZEXPORT zipOpenNewFileInZip3 OF((zipFile file,
+ const char* filename,
+ const zip_fileinfo* zipfi,
+ const void* extrafield_local,
+ uInt size_extrafield_local,
+ const void* extrafield_global,
+ uInt size_extrafield_global,
+ const char* comment,
+ int method,
+ int level,
+ int raw,
+ int windowBits,
+ int memLevel,
+ int strategy,
+ const char* password,
+ uLong crcForCrypting));
+
+extern int ZEXPORT zipOpenNewFileInZip3_64 OF((zipFile file,
+ const char* filename,
+ const zip_fileinfo* zipfi,
+ const void* extrafield_local,
+ uInt size_extrafield_local,
+ const void* extrafield_global,
+ uInt size_extrafield_global,
+ const char* comment,
+ int method,
+ int level,
+ int raw,
+ int windowBits,
+ int memLevel,
+ int strategy,
+ const char* password,
+ uLong crcForCrypting,
+ int zip64
+ ));
+
+/*
+ Same than zipOpenNewFileInZip2, except
+ windowBits,memLevel,,strategy : see parameter strategy in deflateInit2
+ password : crypting password (NULL for no crypting)
+ crcForCrypting : crc of file to compress (needed for crypting)
+ */
+
+extern int ZEXPORT zipOpenNewFileInZip4 OF((zipFile file,
+ const char* filename,
+ const zip_fileinfo* zipfi,
+ const void* extrafield_local,
+ uInt size_extrafield_local,
+ const void* extrafield_global,
+ uInt size_extrafield_global,
+ const char* comment,
+ int method,
+ int level,
+ int raw,
+ int windowBits,
+ int memLevel,
+ int strategy,
+ const char* password,
+ uLong crcForCrypting,
+ uLong versionMadeBy,
+ uLong flagBase
+ ));
+
+
+extern int ZEXPORT zipOpenNewFileInZip4_64 OF((zipFile file,
+ const char* filename,
+ const zip_fileinfo* zipfi,
+ const void* extrafield_local,
+ uInt size_extrafield_local,
+ const void* extrafield_global,
+ uInt size_extrafield_global,
+ const char* comment,
+ int method,
+ int level,
+ int raw,
+ int windowBits,
+ int memLevel,
+ int strategy,
+ const char* password,
+ uLong crcForCrypting,
+ uLong versionMadeBy,
+ uLong flagBase,
+ int zip64
+ ));
+/*
+ Same than zipOpenNewFileInZip4, except
+ versionMadeBy : value for Version made by field
+ flag : value for flag field (compression level info will be added)
+ */
+
+
+extern int ZEXPORT zipWriteInFileInZip OF((zipFile file,
+ const void* buf,
+ unsigned len));
+/*
+ Write data in the zipfile
+*/
+
+extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
+/*
+ Close the current file in the zipfile
+*/
+
+extern int ZEXPORT zipCloseFileInZipRaw OF((zipFile file,
+ uLong uncompressed_size,
+ uLong crc32));
+
+extern int ZEXPORT zipCloseFileInZipRaw64 OF((zipFile file,
+ ZPOS64_T uncompressed_size,
+ uLong crc32));
+
+/*
+ Close the current file in the zipfile, for file opened with
+ parameter raw=1 in zipOpenNewFileInZip2
+ uncompressed_size and crc32 are value for the uncompressed size
+*/
+
+extern int ZEXPORT zipClose OF((zipFile file,
+ const char* global_comment));
+/*
+ Close the zipfile
+*/
+
+
+extern int ZEXPORT zipRemoveExtraInfoBlock OF((char* pData, int* dataLen, short sHeader));
+/*
+ zipRemoveExtraInfoBlock - Added by Mathias Svensson
+
+ Remove extra information block from a extra information data for the local file header or central directory header
+
+ It is needed to remove ZIP64 extra information blocks when before data is written if using RAW mode.
+
+ 0x0001 is the signature header for the ZIP64 extra information blocks
+
+ usage.
+ Remove ZIP64 Extra information from a central director extra field data
+ zipRemoveExtraInfoBlock(pCenDirExtraFieldData, &nCenDirExtraFieldDataLen, 0x0001);
+
+ Remove ZIP64 Extra information from a Local File Header extra field data
+ zipRemoveExtraInfoBlock(pLocalHeaderExtraFieldData, &nLocalHeaderExtraFieldDataLen, 0x0001);
+*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _zip64_H */
diff --git a/plugins/FTPFileYM/zip/zlib.h b/plugins/FTPFileYM/zip/zlib.h
new file mode 100644
index 0000000000..f5785be7e0
--- /dev/null
+++ b/plugins/FTPFileYM/zip/zlib.h
@@ -0,0 +1,1605 @@
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+ version 1.2.4, Mar 14th, 2010
+
+ Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+ jloup@gzip.org madler@alumni.caltech.edu
+
+
+ The data format used by the zlib library is described by RFCs (Request for
+ Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt
+ (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
+*/
+
+#ifndef ZLIB_H
+#define ZLIB_H
+
+#include "zconf.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ZLIB_VERSION "1.2.4"
+#define ZLIB_VERNUM 0x1240
+#define ZLIB_VER_MAJOR 1
+#define ZLIB_VER_MINOR 2
+#define ZLIB_VER_REVISION 4
+#define ZLIB_VER_SUBREVISION 0
+
+/*
+ The 'zlib' compression library provides in-memory compression and
+ decompression functions, including integrity checks of the uncompressed data.
+ This version of the library supports only one compression method (deflation)
+ but other algorithms will be added later and will have the same stream
+ interface.
+
+ Compression can be done in a single step if the buffers are large enough,
+ or can be done by repeated calls of the compression function. In the latter
+ case, the application must provide more input and/or consume the output
+ (providing more output space) before each call.
+
+ The compressed data format used by default by the in-memory functions is
+ the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
+ around a deflate stream, which is itself documented in RFC 1951.
+
+ The library also supports reading and writing files in gzip (.gz) format
+ with an interface similar to that of stdio using the functions that start
+ with "gz". The gzip format is different from the zlib format. gzip is a
+ gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
+
+ This library can optionally read and write gzip streams in memory as well.
+
+ The zlib format was designed to be compact and fast for use in memory
+ and on communications channels. The gzip format was designed for single-
+ file compression on file systems, has a larger header than zlib to maintain
+ directory information, and uses a different, slower check method than zlib.
+
+ The library does not install any signal handler. The decoder checks
+ the consistency of the compressed data, so the library should never crash
+ even in case of corrupted input.
+*/
+
+typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
+typedef void (*free_func) OF((voidpf opaque, voidpf address));
+
+struct internal_state;
+
+typedef struct z_stream_s {
+ Bytef *next_in; /* next input byte */
+ uInt avail_in; /* number of bytes available at next_in */
+ uLong total_in; /* total nb of input bytes read so far */
+
+ Bytef *next_out; /* next output byte should be put there */
+ uInt avail_out; /* remaining free space at next_out */
+ uLong total_out; /* total nb of bytes output so far */
+
+ char *msg; /* last error message, NULL if no error */
+ struct internal_state FAR *state; /* not visible by applications */
+
+ alloc_func zalloc; /* used to allocate the internal state */
+ free_func zfree; /* used to free the internal state */
+ voidpf opaque; /* private data object passed to zalloc and zfree */
+
+ int data_type; /* best guess about the data type: binary or text */
+ uLong adler; /* adler32 value of the uncompressed data */
+ uLong reserved; /* reserved for future use */
+} z_stream;
+
+typedef z_stream FAR *z_streamp;
+
+/*
+ gzip header information passed to and from zlib routines. See RFC 1952
+ for more details on the meanings of these fields.
+*/
+typedef struct gz_header_s {
+ int text; /* true if compressed data believed to be text */
+ uLong time; /* modification time */
+ int xflags; /* extra flags (not used when writing a gzip file) */
+ int os; /* operating system */
+ Bytef *extra; /* pointer to extra field or Z_NULL if none */
+ uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
+ uInt extra_max; /* space at extra (only when reading header) */
+ Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
+ uInt name_max; /* space at name (only when reading header) */
+ Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
+ uInt comm_max; /* space at comment (only when reading header) */
+ int hcrc; /* true if there was or will be a header crc */
+ int done; /* true when done reading gzip header (not used
+ when writing a gzip file) */
+} gz_header;
+
+typedef gz_header FAR *gz_headerp;
+
+/*
+ The application must update next_in and avail_in when avail_in has dropped
+ to zero. It must update next_out and avail_out when avail_out has dropped
+ to zero. The application must initialize zalloc, zfree and opaque before
+ calling the init function. All other fields are set by the compression
+ library and must not be updated by the application.
+
+ The opaque value provided by the application will be passed as the first
+ parameter for calls of zalloc and zfree. This can be useful for custom
+ memory management. The compression library attaches no meaning to the
+ opaque value.
+
+ zalloc must return Z_NULL if there is not enough memory for the object.
+ If zlib is used in a multi-threaded application, zalloc and zfree must be
+ thread safe.
+
+ On 16-bit systems, the functions zalloc and zfree must be able to allocate
+ exactly 65536 bytes, but will not be required to allocate more than this if
+ the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers
+ returned by zalloc for objects of exactly 65536 bytes *must* have their
+ offset normalized to zero. The default allocation function provided by this
+ library ensures this (see zutil.c). To reduce memory requirements and avoid
+ any allocation of 64K objects, at the expense of compression ratio, compile
+ the library with -DMAX_WBITS=14 (see zconf.h).
+
+ The fields total_in and total_out can be used for statistics or progress
+ reports. After compression, total_in holds the total size of the
+ uncompressed data and may be saved for use in the decompressor (particularly
+ if the decompressor wants to decompress everything in a single step).
+*/
+
+ /* constants */
+
+#define Z_NO_FLUSH 0
+#define Z_PARTIAL_FLUSH 1
+#define Z_SYNC_FLUSH 2
+#define Z_FULL_FLUSH 3
+#define Z_FINISH 4
+#define Z_BLOCK 5
+#define Z_TREES 6
+/* Allowed flush values; see deflate() and inflate() below for details */
+
+#define Z_OK 0
+#define Z_STREAM_END 1
+#define Z_NEED_DICT 2
+#define Z_ERRNO (-1)
+#define Z_STREAM_ERROR (-2)
+#define Z_DATA_ERROR (-3)
+#define Z_MEM_ERROR (-4)
+#define Z_BUF_ERROR (-5)
+#define Z_VERSION_ERROR (-6)
+/* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
+ */
+
+#define Z_NO_COMPRESSION 0
+#define Z_BEST_SPEED 1
+#define Z_BEST_COMPRESSION 9
+#define Z_DEFAULT_COMPRESSION (-1)
+/* compression levels */
+
+#define Z_FILTERED 1
+#define Z_HUFFMAN_ONLY 2
+#define Z_RLE 3
+#define Z_FIXED 4
+#define Z_DEFAULT_STRATEGY 0
+/* compression strategy; see deflateInit2() below for details */
+
+#define Z_BINARY 0
+#define Z_TEXT 1
+#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
+#define Z_UNKNOWN 2
+/* Possible values of the data_type field (though see inflate()) */
+
+#define Z_DEFLATED 8
+/* The deflate compression method (the only one supported in this version) */
+
+#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
+
+#define zlib_version zlibVersion()
+/* for compatibility with versions < 1.0.2 */
+
+
+ /* basic functions */
+
+ZEXTERN const char * ZEXPORT zlibVersion OF((void));
+/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
+ If the first character differs, the library code actually used is not
+ compatible with the zlib.h header file used by the application. This check
+ is automatically made by deflateInit and inflateInit.
+ */
+
+/*
+ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
+
+ Initializes the internal stream state for compression. The fields
+ zalloc, zfree and opaque must be initialized before by the caller. If
+ zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
+ allocation functions.
+
+ The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
+ 1 gives best speed, 9 gives best compression, 0 gives no compression at all
+ (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION
+ requests a default compromise between speed and compression (currently
+ equivalent to level 6).
+
+ deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_STREAM_ERROR if level is not a valid compression level, or
+ Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
+ with the version assumed by the caller (ZLIB_VERSION). msg is set to null
+ if there is no error message. deflateInit does not perform any compression:
+ this will be done by deflate().
+*/
+
+
+ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
+/*
+ deflate compresses as much data as possible, and stops when the input
+ buffer becomes empty or the output buffer becomes full. It may introduce
+ some output latency (reading input without producing any output) except when
+ forced to flush.
+
+ The detailed semantics are as follows. deflate performs one or both of the
+ following actions:
+
+ - Compress more input starting at next_in and update next_in and avail_in
+ accordingly. If not all input can be processed (because there is not
+ enough room in the output buffer), next_in and avail_in are updated and
+ processing will resume at this point for the next call of deflate().
+
+ - Provide more output starting at next_out and update next_out and avail_out
+ accordingly. This action is forced if the parameter flush is non zero.
+ Forcing flush frequently degrades the compression ratio, so this parameter
+ should be set only when necessary (in interactive applications). Some
+ output may be provided even if flush is not set.
+
+ Before the call of deflate(), the application should ensure that at least
+ one of the actions is possible, by providing more input and/or consuming more
+ output, and updating avail_in or avail_out accordingly; avail_out should
+ never be zero before the call. The application can consume the compressed
+ output when it wants, for example when the output buffer is full (avail_out
+ == 0), or after each call of deflate(). If deflate returns Z_OK and with
+ zero avail_out, it must be called again after making room in the output
+ buffer because there might be more output pending.
+
+ Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
+ decide how much data to accumulate before producing output, in order to
+ maximize compression.
+
+ If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
+ flushed to the output buffer and the output is aligned on a byte boundary, so
+ that the decompressor can get all input data available so far. (In
+ particular avail_in is zero after the call if enough output space has been
+ provided before the call.) Flushing may degrade compression for some
+ compression algorithms and so it should be used only when necessary. This
+ completes the current deflate block and follows it with an empty stored block
+ that is three bits plus filler bits to the next byte, followed by four bytes
+ (00 00 ff ff).
+
+ If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
+ output buffer, but the output is not aligned to a byte boundary. All of the
+ input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
+ This completes the current deflate block and follows it with an empty fixed
+ codes block that is 10 bits long. This assures that enough bytes are output
+ in order for the decompressor to finish the block before the empty fixed code
+ block.
+
+ If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
+ for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
+ seven bits of the current block are held to be written as the next byte after
+ the next deflate block is completed. In this case, the decompressor may not
+ be provided enough bits at this point in order to complete decompression of
+ the data provided so far to the compressor. It may need to wait for the next
+ block to be emitted. This is for advanced applications that need to control
+ the emission of deflate blocks.
+
+ If flush is set to Z_FULL_FLUSH, all output is flushed as with
+ Z_SYNC_FLUSH, and the compression state is reset so that decompression can
+ restart from this point if previous compressed data has been damaged or if
+ random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
+ compression.
+
+ If deflate returns with avail_out == 0, this function must be called again
+ with the same value of the flush parameter and more output space (updated
+ avail_out), until the flush is complete (deflate returns with non-zero
+ avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
+ avail_out is greater than six to avoid repeated flush markers due to
+ avail_out == 0 on return.
+
+ If the parameter flush is set to Z_FINISH, pending input is processed,
+ pending output is flushed and deflate returns with Z_STREAM_END if there was
+ enough output space; if deflate returns with Z_OK, this function must be
+ called again with Z_FINISH and more output space (updated avail_out) but no
+ more input data, until it returns with Z_STREAM_END or an error. After
+ deflate has returned Z_STREAM_END, the only possible operations on the stream
+ are deflateReset or deflateEnd.
+
+ Z_FINISH can be used immediately after deflateInit if all the compression
+ is to be done in a single step. In this case, avail_out must be at least the
+ value returned by deflateBound (see below). If deflate does not return
+ Z_STREAM_END, then it must be called again as described above.
+
+ deflate() sets strm->adler to the adler32 checksum of all input read
+ so far (that is, total_in bytes).
+
+ deflate() may update strm->data_type if it can make a good guess about
+ the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
+ binary. This field is only for information purposes and does not affect the
+ compression algorithm in any manner.
+
+ deflate() returns Z_OK if some progress has been made (more input
+ processed or more output produced), Z_STREAM_END if all input has been
+ consumed and all output has been produced (only when flush is set to
+ Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
+ if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible
+ (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
+ fatal, and deflate() can be called again with more input and more output
+ space to continue compressing.
+*/
+
+
+ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
+/*
+ All dynamically allocated data structures for this stream are freed.
+ This function discards any unprocessed input and does not flush any pending
+ output.
+
+ deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
+ stream state was inconsistent, Z_DATA_ERROR if the stream was freed
+ prematurely (some input or output was discarded). In the error case, msg
+ may be set but then points to a static string (which must not be
+ deallocated).
+*/
+
+
+/*
+ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
+
+ Initializes the internal stream state for decompression. The fields
+ next_in, avail_in, zalloc, zfree and opaque must be initialized before by
+ the caller. If next_in is not Z_NULL and avail_in is large enough (the
+ exact value depends on the compression method), inflateInit determines the
+ compression method from the zlib header and allocates all data structures
+ accordingly; otherwise the allocation will be deferred to the first call of
+ inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
+ use default allocation functions.
+
+ inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+ version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+ invalid, such as a null pointer to the structure. msg is set to null if
+ there is no error message. inflateInit does not perform any decompression
+ apart from possibly reading the zlib header if present: actual decompression
+ will be done by inflate(). (So next_in and avail_in may be modified, but
+ next_out and avail_out are unused and unchanged.) The current implementation
+ of inflateInit() does not process any header information -- that is deferred
+ until inflate() is called.
+*/
+
+
+ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
+/*
+ inflate decompresses as much data as possible, and stops when the input
+ buffer becomes empty or the output buffer becomes full. It may introduce
+ some output latency (reading input without producing any output) except when
+ forced to flush.
+
+ The detailed semantics are as follows. inflate performs one or both of the
+ following actions:
+
+ - Decompress more input starting at next_in and update next_in and avail_in
+ accordingly. If not all input can be processed (because there is not
+ enough room in the output buffer), next_in is updated and processing will
+ resume at this point for the next call of inflate().
+
+ - Provide more output starting at next_out and update next_out and avail_out
+ accordingly. inflate() provides as much output as possible, until there is
+ no more input data or no more space in the output buffer (see below about
+ the flush parameter).
+
+ Before the call of inflate(), the application should ensure that at least
+ one of the actions is possible, by providing more input and/or consuming more
+ output, and updating the next_* and avail_* values accordingly. The
+ application can consume the uncompressed output when it wants, for example
+ when the output buffer is full (avail_out == 0), or after each call of
+ inflate(). If inflate returns Z_OK and with zero avail_out, it must be
+ called again after making room in the output buffer because there might be
+ more output pending.
+
+ The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
+ Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much
+ output as possible to the output buffer. Z_BLOCK requests that inflate()
+ stop if and when it gets to the next deflate block boundary. When decoding
+ the zlib or gzip format, this will cause inflate() to return immediately
+ after the header and before the first block. When doing a raw inflate,
+ inflate() will go ahead and process the first block, and will return when it
+ gets to the end of that block, or when it runs out of data.
+
+ The Z_BLOCK option assists in appending to or combining deflate streams.
+ Also to assist in this, on return inflate() will set strm->data_type to the
+ number of unused bits in the last byte taken from strm->next_in, plus 64 if
+ inflate() is currently decoding the last block in the deflate stream, plus
+ 128 if inflate() returned immediately after decoding an end-of-block code or
+ decoding the complete header up to just before the first byte of the deflate
+ stream. The end-of-block will not be indicated until all of the uncompressed
+ data from that block has been written to strm->next_out. The number of
+ unused bits may in general be greater than seven, except when bit 7 of
+ data_type is set, in which case the number of unused bits will be less than
+ eight. data_type is set as noted here every time inflate() returns for all
+ flush options, and so can be used to determine the amount of currently
+ consumed input in bits.
+
+ The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
+ end of each deflate block header is reached, before any actual data in that
+ block is decoded. This allows the caller to determine the length of the
+ deflate block header for later use in random access within a deflate block.
+ 256 is added to the value of strm->data_type when inflate() returns
+ immediately after reaching the end of the deflate block header.
+
+ inflate() should normally be called until it returns Z_STREAM_END or an
+ error. However if all decompression is to be performed in a single step (a
+ single call of inflate), the parameter flush should be set to Z_FINISH. In
+ this case all pending input is processed and all pending output is flushed;
+ avail_out must be large enough to hold all the uncompressed data. (The size
+ of the uncompressed data may have been saved by the compressor for this
+ purpose.) The next operation on this stream must be inflateEnd to deallocate
+ the decompression state. The use of Z_FINISH is never required, but can be
+ used to inform inflate that a faster approach may be used for the single
+ inflate() call.
+
+ In this implementation, inflate() always flushes as much output as
+ possible to the output buffer, and always uses the faster approach on the
+ first call. So the only effect of the flush parameter in this implementation
+ is on the return value of inflate(), as noted below, or when it returns early
+ because Z_BLOCK or Z_TREES is used.
+
+ If a preset dictionary is needed after this call (see inflateSetDictionary
+ below), inflate sets strm->adler to the adler32 checksum of the dictionary
+ chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
+ strm->adler to the adler32 checksum of all output produced so far (that is,
+ total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
+ below. At the end of the stream, inflate() checks that its computed adler32
+ checksum is equal to that saved by the compressor and returns Z_STREAM_END
+ only if the checksum is correct.
+
+ inflate() can decompress and check either zlib-wrapped or gzip-wrapped
+ deflate data. The header type is detected automatically, if requested when
+ initializing with inflateInit2(). Any information contained in the gzip
+ header is not retained, so applications that need that information should
+ instead use raw inflate, see inflateInit2() below, or inflateBack() and
+ perform their own processing of the gzip header and trailer.
+
+ inflate() returns Z_OK if some progress has been made (more input processed
+ or more output produced), Z_STREAM_END if the end of the compressed data has
+ been reached and all uncompressed output has been produced, Z_NEED_DICT if a
+ preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
+ corrupted (input stream not conforming to the zlib format or incorrect check
+ value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
+ next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory,
+ Z_BUF_ERROR if no progress is possible or if there was not enough room in the
+ output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
+ inflate() can be called again with more input and more output space to
+ continue decompressing. If Z_DATA_ERROR is returned, the application may
+ then call inflateSync() to look for a good compression block if a partial
+ recovery of the data is desired.
+*/
+
+
+ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
+/*
+ All dynamically allocated data structures for this stream are freed.
+ This function discards any unprocessed input and does not flush any pending
+ output.
+
+ inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
+ was inconsistent. In the error case, msg may be set but then points to a
+ static string (which must not be deallocated).
+*/
+
+
+ /* Advanced functions */
+
+/*
+ The following functions are needed only in some special applications.
+*/
+
+/*
+ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
+ int level,
+ int method,
+ int windowBits,
+ int memLevel,
+ int strategy));
+
+ This is another version of deflateInit with more compression options. The
+ fields next_in, zalloc, zfree and opaque must be initialized before by the
+ caller.
+
+ The method parameter is the compression method. It must be Z_DEFLATED in
+ this version of the library.
+
+ The windowBits parameter is the base two logarithm of the window size
+ (the size of the history buffer). It should be in the range 8..15 for this
+ version of the library. Larger values of this parameter result in better
+ compression at the expense of memory usage. The default value is 15 if
+ deflateInit is used instead.
+
+ windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
+ determines the window size. deflate() will then generate raw deflate data
+ with no zlib header or trailer, and will not compute an adler32 check value.
+
+ windowBits can also be greater than 15 for optional gzip encoding. Add
+ 16 to windowBits to write a simple gzip header and trailer around the
+ compressed data instead of a zlib wrapper. The gzip header will have no
+ file name, no extra data, no comment, no modification time (set to zero), no
+ header crc, and the operating system will be set to 255 (unknown). If a
+ gzip stream is being written, strm->adler is a crc32 instead of an adler32.
+
+ The memLevel parameter specifies how much memory should be allocated
+ for the internal compression state. memLevel=1 uses minimum memory but is
+ slow and reduces compression ratio; memLevel=9 uses maximum memory for
+ optimal speed. The default value is 8. See zconf.h for total memory usage
+ as a function of windowBits and memLevel.
+
+ The strategy parameter is used to tune the compression algorithm. Use the
+ value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
+ filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
+ string match), or Z_RLE to limit match distances to one (run-length
+ encoding). Filtered data consists mostly of small values with a somewhat
+ random distribution. In this case, the compression algorithm is tuned to
+ compress them better. The effect of Z_FILTERED is to force more Huffman
+ coding and less string matching; it is somewhat intermediate between
+ Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as
+ fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The
+ strategy parameter only affects the compression ratio but not the
+ correctness of the compressed output even if it is not set appropriately.
+ Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
+ decoder for special applications.
+
+ deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
+ method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
+ incompatible with the version assumed by the caller (ZLIB_VERSION). msg is
+ set to null if there is no error message. deflateInit2 does not perform any
+ compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
+ const Bytef *dictionary,
+ uInt dictLength));
+/*
+ Initializes the compression dictionary from the given byte sequence
+ without producing any compressed output. This function must be called
+ immediately after deflateInit, deflateInit2 or deflateReset, before any call
+ of deflate. The compressor and decompressor must use exactly the same
+ dictionary (see inflateSetDictionary).
+
+ The dictionary should consist of strings (byte sequences) that are likely
+ to be encountered later in the data to be compressed, with the most commonly
+ used strings preferably put towards the end of the dictionary. Using a
+ dictionary is most useful when the data to be compressed is short and can be
+ predicted with good accuracy; the data can then be compressed better than
+ with the default empty dictionary.
+
+ Depending on the size of the compression data structures selected by
+ deflateInit or deflateInit2, a part of the dictionary may in effect be
+ discarded, for example if the dictionary is larger than the window size
+ provided in deflateInit or deflateInit2. Thus the strings most likely to be
+ useful should be put at the end of the dictionary, not at the front. In
+ addition, the current implementation of deflate will use at most the window
+ size minus 262 bytes of the provided dictionary.
+
+ Upon return of this function, strm->adler is set to the adler32 value
+ of the dictionary; the decompressor may later use this value to determine
+ which dictionary has been used by the compressor. (The adler32 value
+ applies to the whole dictionary even if only a subset of the dictionary is
+ actually used by the compressor.) If a raw deflate was requested, then the
+ adler32 value is not computed and strm->adler is not set.
+
+ deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
+ parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
+ inconsistent (for example if deflate has already been called for this stream
+ or if the compression method is bsort). deflateSetDictionary does not
+ perform any compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
+ z_streamp source));
+/*
+ Sets the destination stream as a complete copy of the source stream.
+
+ This function can be useful when several compression strategies will be
+ tried, for example when there are several ways of pre-processing the input
+ data with a filter. The streams that will be discarded should then be freed
+ by calling deflateEnd. Note that deflateCopy duplicates the internal
+ compression state which can be quite large, so this strategy is slow and can
+ consume lots of memory.
+
+ deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+ (such as zalloc being Z_NULL). msg is left unchanged in both source and
+ destination.
+*/
+
+ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
+/*
+ This function is equivalent to deflateEnd followed by deflateInit,
+ but does not free and reallocate all the internal compression state. The
+ stream will keep the same compression level and any other attributes that
+ may have been set by deflateInit2.
+
+ deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
+ int level,
+ int strategy));
+/*
+ Dynamically update the compression level and compression strategy. The
+ interpretation of level and strategy is as in deflateInit2. This can be
+ used to switch between compression and straight copy of the input data, or
+ to switch to a different kind of input data requiring a different strategy.
+ If the compression level is changed, the input available so far is
+ compressed with the old level (and may be flushed); the new level will take
+ effect only at the next call of deflate().
+
+ Before the call of deflateParams, the stream state must be set as for
+ a call of deflate(), since the currently available input may have to be
+ compressed and flushed. In particular, strm->avail_out must be non-zero.
+
+ deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
+ stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if
+ strm->avail_out was zero.
+*/
+
+ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
+ int good_length,
+ int max_lazy,
+ int nice_length,
+ int max_chain));
+/*
+ Fine tune deflate's internal compression parameters. This should only be
+ used by someone who understands the algorithm used by zlib's deflate for
+ searching for the best matching string, and even then only by the most
+ fanatic optimizer trying to squeeze out the last compressed bit for their
+ specific input data. Read the deflate.c source code for the meaning of the
+ max_lazy, good_length, nice_length, and max_chain parameters.
+
+ deflateTune() can be called after deflateInit() or deflateInit2(), and
+ returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
+ */
+
+ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
+ uLong sourceLen));
+/*
+ deflateBound() returns an upper bound on the compressed size after
+ deflation of sourceLen bytes. It must be called after deflateInit() or
+ deflateInit2(), and after deflateSetHeader(), if used. This would be used
+ to allocate an output buffer for deflation in a single pass, and so would be
+ called before deflate().
+*/
+
+ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
+ int bits,
+ int value));
+/*
+ deflatePrime() inserts bits in the deflate output stream. The intent
+ is that this function is used to start off the deflate output with the bits
+ leftover from a previous deflate stream when appending to it. As such, this
+ function can only be used for raw deflate, and must be used before the first
+ deflate() call after a deflateInit2() or deflateReset(). bits must be less
+ than or equal to 16, and that many of the least significant bits of value
+ will be inserted in the output.
+
+ deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
+ gz_headerp head));
+/*
+ deflateSetHeader() provides gzip header information for when a gzip
+ stream is requested by deflateInit2(). deflateSetHeader() may be called
+ after deflateInit2() or deflateReset() and before the first call of
+ deflate(). The text, time, os, extra field, name, and comment information
+ in the provided gz_header structure are written to the gzip header (xflag is
+ ignored -- the extra flags are set according to the compression level). The
+ caller must assure that, if not Z_NULL, name and comment are terminated with
+ a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
+ available there. If hcrc is true, a gzip header crc is included. Note that
+ the current versions of the command-line version of gzip (up through version
+ 1.3.x) do not support header crc's, and will report that it is a "multi-part
+ gzip file" and give up.
+
+ If deflateSetHeader is not used, the default gzip header has text false,
+ the time set to zero, and os set to 255, with no extra, name, or comment
+ fields. The gzip header is returned to the default state by deflateReset().
+
+ deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
+ int windowBits));
+
+ This is another version of inflateInit with an extra parameter. The
+ fields next_in, avail_in, zalloc, zfree and opaque must be initialized
+ before by the caller.
+
+ The windowBits parameter is the base two logarithm of the maximum window
+ size (the size of the history buffer). It should be in the range 8..15 for
+ this version of the library. The default value is 15 if inflateInit is used
+ instead. windowBits must be greater than or equal to the windowBits value
+ provided to deflateInit2() while compressing, or it must be equal to 15 if
+ deflateInit2() was not used. If a compressed stream with a larger window
+ size is given as input, inflate() will return with the error code
+ Z_DATA_ERROR instead of trying to allocate a larger window.
+
+ windowBits can also be zero to request that inflate use the window size in
+ the zlib header of the compressed stream.
+
+ windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
+ determines the window size. inflate() will then process raw deflate data,
+ not looking for a zlib or gzip header, not generating a check value, and not
+ looking for any check values for comparison at the end of the stream. This
+ is for use with other formats that use the deflate compressed data format
+ such as zip. Those formats provide their own check values. If a custom
+ format is developed using the raw deflate format for compressed data, it is
+ recommended that a check value such as an adler32 or a crc32 be applied to
+ the uncompressed data as is done in the zlib, gzip, and zip formats. For
+ most applications, the zlib format should be used as is. Note that comments
+ above on the use in deflateInit2() applies to the magnitude of windowBits.
+
+ windowBits can also be greater than 15 for optional gzip decoding. Add
+ 32 to windowBits to enable zlib and gzip decoding with automatic header
+ detection, or add 16 to decode only the gzip format (the zlib format will
+ return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a
+ crc32 instead of an adler32.
+
+ inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+ version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+ invalid, such as a null pointer to the structure. msg is set to null if
+ there is no error message. inflateInit2 does not perform any decompression
+ apart from possibly reading the zlib header if present: actual decompression
+ will be done by inflate(). (So next_in and avail_in may be modified, but
+ next_out and avail_out are unused and unchanged.) The current implementation
+ of inflateInit2() does not process any header information -- that is
+ deferred until inflate() is called.
+*/
+
+ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
+ const Bytef *dictionary,
+ uInt dictLength));
+/*
+ Initializes the decompression dictionary from the given uncompressed byte
+ sequence. This function must be called immediately after a call of inflate,
+ if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
+ can be determined from the adler32 value returned by that call of inflate.
+ The compressor and decompressor must use exactly the same dictionary (see
+ deflateSetDictionary). For raw inflate, this function can be called
+ immediately after inflateInit2() or inflateReset() and before any call of
+ inflate() to set the dictionary. The application must insure that the
+ dictionary that was used for compression is provided.
+
+ inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
+ parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
+ inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+ expected one (incorrect adler32 value). inflateSetDictionary does not
+ perform any decompression: this will be done by subsequent calls of
+ inflate().
+*/
+
+ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
+/*
+ Skips invalid compressed data until a full flush point (see above the
+ description of deflate with Z_FULL_FLUSH) can be found, or until all
+ available input is skipped. No output is provided.
+
+ inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
+ if no more input was provided, Z_DATA_ERROR if no flush point has been
+ found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the
+ success case, the application may save the current current value of total_in
+ which indicates where valid compressed data was found. In the error case,
+ the application may repeatedly call inflateSync, providing more input each
+ time, until success or end of the input data.
+*/
+
+ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
+ z_streamp source));
+/*
+ Sets the destination stream as a complete copy of the source stream.
+
+ This function can be useful when randomly accessing a large stream. The
+ first pass through the stream can periodically record the inflate state,
+ allowing restarting inflate at those points when randomly accessing the
+ stream.
+
+ inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+ (such as zalloc being Z_NULL). msg is left unchanged in both source and
+ destination.
+*/
+
+ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
+/*
+ This function is equivalent to inflateEnd followed by inflateInit,
+ but does not free and reallocate all the internal decompression state. The
+ stream will keep attributes that may have been set by inflateInit2.
+
+ inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
+ int windowBits));
+/*
+ This function is the same as inflateReset, but it also permits changing
+ the wrap and window size requests. The windowBits parameter is interpreted
+ the same as it is for inflateInit2.
+
+ inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent (such as zalloc or state being Z_NULL), or if
+ the windowBits parameter is invalid.
+*/
+
+ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
+ int bits,
+ int value));
+/*
+ This function inserts bits in the inflate input stream. The intent is
+ that this function is used to start inflating at a bit position in the
+ middle of a byte. The provided bits will be used before any bytes are used
+ from next_in. This function should only be used with raw inflate, and
+ should be used before the first inflate() call after inflateInit2() or
+ inflateReset(). bits must be less than or equal to 16, and that many of the
+ least significant bits of value will be inserted in the input.
+
+ If bits is negative, then the input stream bit buffer is emptied. Then
+ inflatePrime() can be called again to put bits in the buffer. This is used
+ to clear out bits leftover after feeding inflate a block description prior
+ to feeding inflate codes.
+
+ inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent.
+*/
+
+ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
+/*
+ This function returns two values, one in the lower 16 bits of the return
+ value, and the other in the remaining upper bits, obtained by shifting the
+ return value down 16 bits. If the upper value is -1 and the lower value is
+ zero, then inflate() is currently decoding information outside of a block.
+ If the upper value is -1 and the lower value is non-zero, then inflate is in
+ the middle of a stored block, with the lower value equaling the number of
+ bytes from the input remaining to copy. If the upper value is not -1, then
+ it is the number of bits back from the current bit position in the input of
+ the code (literal or length/distance pair) currently being processed. In
+ that case the lower value is the number of bytes already emitted for that
+ code.
+
+ A code is being processed if inflate is waiting for more input to complete
+ decoding of the code, or if it has completed decoding but is waiting for
+ more output space to write the literal or match data.
+
+ inflateMark() is used to mark locations in the input data for random
+ access, which may be at bit positions, and to note those cases where the
+ output of a code may span boundaries of random access blocks. The current
+ location in the input stream can be determined from avail_in and data_type
+ as noted in the description for the Z_BLOCK flush parameter for inflate.
+
+ inflateMark returns the value noted above or -1 << 16 if the provided
+ source stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
+ gz_headerp head));
+/*
+ inflateGetHeader() requests that gzip header information be stored in the
+ provided gz_header structure. inflateGetHeader() may be called after
+ inflateInit2() or inflateReset(), and before the first call of inflate().
+ As inflate() processes the gzip stream, head->done is zero until the header
+ is completed, at which time head->done is set to one. If a zlib stream is
+ being decoded, then head->done is set to -1 to indicate that there will be
+ no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be
+ used to force inflate() to return immediately after header processing is
+ complete and before any actual data is decompressed.
+
+ The text, time, xflags, and os fields are filled in with the gzip header
+ contents. hcrc is set to true if there is a header CRC. (The header CRC
+ was valid if done is set to one.) If extra is not Z_NULL, then extra_max
+ contains the maximum number of bytes to write to extra. Once done is true,
+ extra_len contains the actual extra field length, and extra contains the
+ extra field, or that field truncated if extra_max is less than extra_len.
+ If name is not Z_NULL, then up to name_max characters are written there,
+ terminated with a zero unless the length is greater than name_max. If
+ comment is not Z_NULL, then up to comm_max characters are written there,
+ terminated with a zero unless the length is greater than comm_max. When any
+ of extra, name, or comment are not Z_NULL and the respective field is not
+ present in the header, then that field is set to Z_NULL to signal its
+ absence. This allows the use of deflateSetHeader() with the returned
+ structure to duplicate the header. However if those fields are set to
+ allocated memory, then the application will need to save those pointers
+ elsewhere so that they can be eventually freed.
+
+ If inflateGetHeader is not used, then the header information is simply
+ discarded. The header is always checked for validity, including the header
+ CRC if present. inflateReset() will reset the process to discard the header
+ information. The application would need to call inflateGetHeader() again to
+ retrieve the header from the next gzip stream.
+
+ inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+ stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
+ unsigned char FAR *window));
+
+ Initialize the internal stream state for decompression using inflateBack()
+ calls. The fields zalloc, zfree and opaque in strm must be initialized
+ before the call. If zalloc and zfree are Z_NULL, then the default library-
+ derived memory allocation routines are used. windowBits is the base two
+ logarithm of the window size, in the range 8..15. window is a caller
+ supplied buffer of that size. Except for special applications where it is
+ assured that deflate was used with small window sizes, windowBits must be 15
+ and a 32K byte window must be supplied to be able to decompress general
+ deflate streams.
+
+ See inflateBack() for the usage of these routines.
+
+ inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
+ the paramaters are invalid, Z_MEM_ERROR if the internal state could not be
+ allocated, or Z_VERSION_ERROR if the version of the library does not match
+ the version of the header file.
+*/
+
+typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
+typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
+
+ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
+ in_func in, void FAR *in_desc,
+ out_func out, void FAR *out_desc));
+/*
+ inflateBack() does a raw inflate with a single call using a call-back
+ interface for input and output. This is more efficient than inflate() for
+ file i/o applications in that it avoids copying between the output and the
+ sliding window by simply making the window itself the output buffer. This
+ function trusts the application to not change the output buffer passed by
+ the output function, at least until inflateBack() returns.
+
+ inflateBackInit() must be called first to allocate the internal state
+ and to initialize the state with the user-provided window buffer.
+ inflateBack() may then be used multiple times to inflate a complete, raw
+ deflate stream with each call. inflateBackEnd() is then called to free the
+ allocated state.
+
+ A raw deflate stream is one with no zlib or gzip header or trailer.
+ This routine would normally be used in a utility that reads zip or gzip
+ files and writes out uncompressed files. The utility would decode the
+ header and process the trailer on its own, hence this routine expects only
+ the raw deflate stream to decompress. This is different from the normal
+ behavior of inflate(), which expects either a zlib or gzip header and
+ trailer around the deflate stream.
+
+ inflateBack() uses two subroutines supplied by the caller that are then
+ called by inflateBack() for input and output. inflateBack() calls those
+ routines until it reads a complete deflate stream and writes out all of the
+ uncompressed data, or until it encounters an error. The function's
+ parameters and return types are defined above in the in_func and out_func
+ typedefs. inflateBack() will call in(in_desc, &buf) which should return the
+ number of bytes of provided input, and a pointer to that input in buf. If
+ there is no input available, in() must return zero--buf is ignored in that
+ case--and inflateBack() will return a buffer error. inflateBack() will call
+ out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
+ should return zero on success, or non-zero on failure. If out() returns
+ non-zero, inflateBack() will return with an error. Neither in() nor out()
+ are permitted to change the contents of the window provided to
+ inflateBackInit(), which is also the buffer that out() uses to write from.
+ The length written by out() will be at most the window size. Any non-zero
+ amount of input may be provided by in().
+
+ For convenience, inflateBack() can be provided input on the first call by
+ setting strm->next_in and strm->avail_in. If that input is exhausted, then
+ in() will be called. Therefore strm->next_in must be initialized before
+ calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
+ immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
+ must also be initialized, and then if strm->avail_in is not zero, input will
+ initially be taken from strm->next_in[0 .. strm->avail_in - 1].
+
+ The in_desc and out_desc parameters of inflateBack() is passed as the
+ first parameter of in() and out() respectively when they are called. These
+ descriptors can be optionally used to pass any information that the caller-
+ supplied in() and out() functions need to do their job.
+
+ On return, inflateBack() will set strm->next_in and strm->avail_in to
+ pass back any unused input that was provided by the last in() call. The
+ return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
+ if in() or out() returned an error, Z_DATA_ERROR if there was a format error
+ in the deflate stream (in which case strm->msg is set to indicate the nature
+ of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
+ In the case of Z_BUF_ERROR, an input or output error can be distinguished
+ using strm->next_in which will be Z_NULL only if in() returned an error. If
+ strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
+ non-zero. (in() will always be called before out(), so strm->next_in is
+ assured to be defined if out() returns non-zero.) Note that inflateBack()
+ cannot return Z_OK.
+*/
+
+ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
+/*
+ All memory allocated by inflateBackInit() is freed.
+
+ inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
+ state was inconsistent.
+*/
+
+ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
+/* Return flags indicating compile-time options.
+
+ Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
+ 1.0: size of uInt
+ 3.2: size of uLong
+ 5.4: size of voidpf (pointer)
+ 7.6: size of z_off_t
+
+ Compiler, assembler, and debug options:
+ 8: DEBUG
+ 9: ASMV or ASMINF -- use ASM code
+ 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
+ 11: 0 (reserved)
+
+ One-time table building (smaller code, but not thread-safe if true):
+ 12: BUILDFIXED -- build static block decoding tables when needed
+ 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
+ 14,15: 0 (reserved)
+
+ Library content (indicates missing functionality):
+ 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
+ deflate code when not needed)
+ 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
+ and decode gzip streams (to avoid linking crc code)
+ 18-19: 0 (reserved)
+
+ Operation variations (changes in library functionality):
+ 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
+ 21: FASTEST -- deflate algorithm with only one, lowest compression level
+ 22,23: 0 (reserved)
+
+ The sprintf variant used by gzprintf (zero is best):
+ 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
+ 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
+ 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
+
+ Remainder:
+ 27-31: 0 (reserved)
+ */
+
+
+ /* utility functions */
+
+/*
+ The following utility functions are implemented on top of the basic
+ stream-oriented functions. To simplify the interface, some default options
+ are assumed (compression level and memory usage, standard memory allocation
+ functions). The source code of these utility functions can be modified if
+ you need special options.
+*/
+
+ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen));
+/*
+ Compresses the source buffer into the destination buffer. sourceLen is
+ the byte length of the source buffer. Upon entry, destLen is the total size
+ of the destination buffer, which must be at least the value returned by
+ compressBound(sourceLen). Upon exit, destLen is the actual size of the
+ compressed buffer.
+
+ compress returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_BUF_ERROR if there was not enough room in the output
+ buffer.
+*/
+
+ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen,
+ int level));
+/*
+ Compresses the source buffer into the destination buffer. The level
+ parameter has the same meaning as in deflateInit. sourceLen is the byte
+ length of the source buffer. Upon entry, destLen is the total size of the
+ destination buffer, which must be at least the value returned by
+ compressBound(sourceLen). Upon exit, destLen is the actual size of the
+ compressed buffer.
+
+ compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+ memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+ Z_STREAM_ERROR if the level parameter is invalid.
+*/
+
+ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
+/*
+ compressBound() returns an upper bound on the compressed size after
+ compress() or compress2() on sourceLen bytes. It would be used before a
+ compress() or compress2() call to allocate the destination buffer.
+*/
+
+ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen));
+/*
+ Decompresses the source buffer into the destination buffer. sourceLen is
+ the byte length of the source buffer. Upon entry, destLen is the total size
+ of the destination buffer, which must be large enough to hold the entire
+ uncompressed data. (The size of the uncompressed data must have been saved
+ previously by the compressor and transmitted to the decompressor by some
+ mechanism outside the scope of this compression library.) Upon exit, destLen
+ is the actual size of the uncompressed buffer.
+
+ uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+ enough memory, Z_BUF_ERROR if there was not enough room in the output
+ buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
+*/
+
+
+ /* gzip file access functions */
+
+/*
+ This library supports reading and writing files in gzip (.gz) format with
+ an interface similar to that of stdio, using the functions that start with
+ "gz". The gzip format is different from the zlib format. gzip is a gzip
+ wrapper, documented in RFC 1952, wrapped around a deflate stream.
+*/
+
+typedef voidp gzFile; /* opaque gzip file descriptor */
+
+/*
+ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
+
+ Opens a gzip (.gz) file for reading or writing. The mode parameter is as
+ in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
+ a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
+ compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
+ for fixed code compression as in "wb9F". (See the description of
+ deflateInit2 for more information about the strategy parameter.) Also "a"
+ can be used instead of "w" to request that the gzip stream that will be
+ written be appended to the file. "+" will result in an error, since reading
+ and writing to the same gzip file is not supported.
+
+ gzopen can be used to read a file which is not in gzip format; in this
+ case gzread will directly read from the file without decompression.
+
+ gzopen returns NULL if the file could not be opened, if there was
+ insufficient memory to allocate the gzFile state, or if an invalid mode was
+ specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
+ errno can be checked to determine if the reason gzopen failed was that the
+ file could not be opened.
+*/
+
+ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
+/*
+ gzdopen associates a gzFile with the file descriptor fd. File descriptors
+ are obtained from calls like open, dup, creat, pipe or fileno (if the file
+ has been previously opened with fopen). The mode parameter is as in gzopen.
+
+ The next call of gzclose on the returned gzFile will also close the file
+ descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
+ fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
+ mode);. The duplicated descriptor should be saved to avoid a leak, since
+ gzdopen does not close fd if it fails.
+
+ gzdopen returns NULL if there was insufficient memory to allocate the
+ gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
+ provided, or '+' was provided), or if fd is -1. The file descriptor is not
+ used until the next gz* read, write, seek, or close operation, so gzdopen
+ will not detect if fd is invalid (unless fd is -1).
+*/
+
+ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
+/*
+ Set the internal buffer size used by this library's functions. The
+ default buffer size is 8192 bytes. This function must be called after
+ gzopen() or gzdopen(), and before any other calls that read or write the
+ file. The buffer memory allocation is always deferred to the first read or
+ write. Two buffers are allocated, either both of the specified size when
+ writing, or one of the specified size and the other twice that size when
+ reading. A larger buffer size of, for example, 64K or 128K bytes will
+ noticeably increase the speed of decompression (reading).
+
+ The new buffer size also affects the maximum length for gzprintf().
+
+ gzbuffer() returns 0 on success, or -1 on failure, such as being called
+ too late.
+*/
+
+ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
+/*
+ Dynamically update the compression level or strategy. See the description
+ of deflateInit2 for the meaning of these parameters.
+
+ gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
+ opened for writing.
+*/
+
+ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
+/*
+ Reads the given number of uncompressed bytes from the compressed file. If
+ the input file was not in gzip format, gzread copies the given number of
+ bytes into the buffer.
+
+ After reaching the end of a gzip stream in the input, gzread will continue
+ to read, looking for another gzip stream, or failing that, reading the rest
+ of the input file directly without decompression. The entire input file
+ will be read if gzread is called until it returns less than the requested
+ len.
+
+ gzread returns the number of uncompressed bytes actually read, less than
+ len for end of file, or -1 for error.
+*/
+
+ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
+ voidpc buf, unsigned len));
+/*
+ Writes the given number of uncompressed bytes into the compressed file.
+ gzwrite returns the number of uncompressed bytes written or 0 in case of
+ error.
+*/
+
+ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
+/*
+ Converts, formats, and writes the arguments to the compressed file under
+ control of the format string, as in fprintf. gzprintf returns the number of
+ uncompressed bytes actually written, or 0 in case of error. The number of
+ uncompressed bytes written is limited to 8191, or one less than the buffer
+ size given to gzbuffer(). The caller should assure that this limit is not
+ exceeded. If it is exceeded, then gzprintf() will return an error (0) with
+ nothing written. In this case, there may also be a buffer overflow with
+ unpredictable consequences, which is possible only if zlib was compiled with
+ the insecure functions sprintf() or vsprintf() because the secure snprintf()
+ or vsnprintf() functions were not available. This can be determined using
+ zlibCompileFlags().
+*/
+
+ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
+/*
+ Writes the given null-terminated string to the compressed file, excluding
+ the terminating null character.
+
+ gzputs returns the number of characters written, or -1 in case of error.
+*/
+
+ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
+/*
+ Reads bytes from the compressed file until len-1 characters are read, or a
+ newline character is read and transferred to buf, or an end-of-file
+ condition is encountered. If any characters are read or if len == 1, the
+ string is terminated with a null character. If no characters are read due
+ to an end-of-file or len < 1, then the buffer is left untouched.
+
+ gzgets returns buf which is a null-terminated string, or it returns NULL
+ for end-of-file or in case of error. If there was an error, the contents at
+ buf are indeterminate.
+*/
+
+ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
+/*
+ Writes c, converted to an unsigned char, into the compressed file. gzputc
+ returns the value that was written, or -1 in case of error.
+*/
+
+ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
+/*
+ Reads one byte from the compressed file. gzgetc returns this byte or -1
+ in case of end of file or error.
+*/
+
+ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
+/*
+ Push one character back onto the stream to be read as the first character
+ on the next read. At least one character of push-back is allowed.
+ gzungetc() returns the character pushed, or -1 on failure. gzungetc() will
+ fail if c is -1, and may fail if a character has been pushed but not read
+ yet. If gzungetc is used immediately after gzopen or gzdopen, at least the
+ output buffer size of pushed characters is allowed. (See gzbuffer above.)
+ The pushed character will be discarded if the stream is repositioned with
+ gzseek() or gzrewind().
+*/
+
+ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
+/*
+ Flushes all pending output into the compressed file. The parameter flush
+ is as in the deflate() function. The return value is the zlib error number
+ (see function gzerror below). gzflush is only permitted when writing.
+
+ If the flush parameter is Z_FINISH, the remaining data is written and the
+ gzip stream is completed in the output. If gzwrite() is called again, a new
+ gzip stream will be started in the output. gzread() is able to read such
+ concatented gzip streams.
+
+ gzflush should be called only when strictly necessary because it will
+ degrade compression if called too often.
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
+ z_off_t offset, int whence));
+
+ Sets the starting position for the next gzread or gzwrite on the given
+ compressed file. The offset represents a number of bytes in the
+ uncompressed data stream. The whence parameter is defined as in lseek(2);
+ the value SEEK_END is not supported.
+
+ If the file is opened for reading, this function is emulated but can be
+ extremely slow. If the file is opened for writing, only forward seeks are
+ supported; gzseek then compresses a sequence of zeroes up to the new
+ starting position.
+
+ gzseek returns the resulting offset location as measured in bytes from
+ the beginning of the uncompressed stream, or -1 in case of error, in
+ particular if the file is opened for writing and the new starting position
+ would be before the current position.
+*/
+
+ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
+/*
+ Rewinds the given file. This function is supported only for reading.
+
+ gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
+
+ Returns the starting position for the next gzread or gzwrite on the given
+ compressed file. This position represents a number of bytes in the
+ uncompressed data stream, and is zero when starting, even if appending or
+ reading a gzip stream from the middle of a file using gzdopen().
+
+ gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
+
+ Returns the current offset in the file being read or written. This offset
+ includes the count of bytes that precede the gzip stream, for example when
+ appending or when using gzdopen() for reading. When reading, the offset
+ does not include as yet unused buffered input. This information can be used
+ for a progress indicator. On error, gzoffset() returns -1.
+*/
+
+ZEXTERN int ZEXPORT gzeof OF((gzFile file));
+/*
+ Returns true (1) if the end-of-file indicator has been set while reading,
+ false (0) otherwise. Note that the end-of-file indicator is set only if the
+ read tried to go past the end of the input, but came up short. Therefore,
+ just like feof(), gzeof() may return false even if there is no more data to
+ read, in the event that the last read request was for the exact number of
+ bytes remaining in the input file. This will happen if the input file size
+ is an exact multiple of the buffer size.
+
+ If gzeof() returns true, then the read functions will return no more data,
+ unless the end-of-file indicator is reset by gzclearerr() and the input file
+ has grown since the previous end of file was detected.
+*/
+
+ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
+/*
+ Returns true (1) if file is being copied directly while reading, or false
+ (0) if file is a gzip stream being decompressed. This state can change from
+ false to true while reading the input file if the end of a gzip stream is
+ reached, but is followed by data that is not another gzip stream.
+
+ If the input file is empty, gzdirect() will return true, since the input
+ does not contain a gzip stream.
+
+ If gzdirect() is used immediately after gzopen() or gzdopen() it will
+ cause buffers to be allocated to allow reading the file to determine if it
+ is a gzip file. Therefore if gzbuffer() is used, it should be called before
+ gzdirect().
+*/
+
+ZEXTERN int ZEXPORT gzclose OF((gzFile file));
+/*
+ Flushes all pending output if necessary, closes the compressed file and
+ deallocates the (de)compression state. Note that once file is closed, you
+ cannot call gzerror with file, since its structures have been deallocated.
+ gzclose must not be called more than once on the same file, just as free
+ must not be called more than once on the same allocation.
+
+ gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
+ file operation error, or Z_OK on success.
+*/
+
+ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
+ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
+/*
+ Same as gzclose(), but gzclose_r() is only for use when reading, and
+ gzclose_w() is only for use when writing or appending. The advantage to
+ using these instead of gzclose() is that they avoid linking in zlib
+ compression or decompression code that is not used when only reading or only
+ writing respectively. If gzclose() is used, then both compression and
+ decompression code will be included the application when linking to a static
+ zlib library.
+*/
+
+ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
+/*
+ Returns the error message for the last error which occurred on the given
+ compressed file. errnum is set to zlib error number. If an error occurred
+ in the file system and not in the compression library, errnum is set to
+ Z_ERRNO and the application may consult errno to get the exact error code.
+
+ The application must not modify the returned string. Future calls to
+ this function may invalidate the previously returned string. If file is
+ closed, then the string previously returned by gzerror will no longer be
+ available.
+
+ gzerror() should be used to distinguish errors from end-of-file for those
+ functions above that do not distinguish those cases in their return values.
+*/
+
+ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
+/*
+ Clears the error and end-of-file flags for file. This is analogous to the
+ clearerr() function in stdio. This is useful for continuing to read a gzip
+ file that is being written concurrently.
+*/
+
+
+ /* checksum functions */
+
+/*
+ These functions are not related to compression but are exported
+ anyway because they might be useful in applications using the compression
+ library.
+*/
+
+ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
+/*
+ Update a running Adler-32 checksum with the bytes buf[0..len-1] and
+ return the updated checksum. If buf is Z_NULL, this function returns the
+ required initial value for the checksum.
+
+ An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
+ much faster.
+
+ Usage example:
+
+ uLong adler = adler32(0L, Z_NULL, 0);
+
+ while (read_buffer(buffer, length) != EOF) {
+ adler = adler32(adler, buffer, length);
+ }
+ if (adler != original_adler) error();
+*/
+
+/*
+ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
+ z_off_t len2));
+
+ Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
+ and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
+ each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
+ seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
+*/
+
+ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
+/*
+ Update a running CRC-32 with the bytes buf[0..len-1] and return the
+ updated CRC-32. If buf is Z_NULL, this function returns the required
+ initial value for the for the crc. Pre- and post-conditioning (one's
+ complement) is performed within this function so it shouldn't be done by the
+ application.
+
+ Usage example:
+
+ uLong crc = crc32(0L, Z_NULL, 0);
+
+ while (read_buffer(buffer, length) != EOF) {
+ crc = crc32(crc, buffer, length);
+ }
+ if (crc != original_crc) error();
+*/
+
+/*
+ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
+
+ Combine two CRC-32 check values into one. For two sequences of bytes,
+ seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
+ calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
+ check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
+ len2.
+*/
+
+
+ /* various hacks, don't look :) */
+
+/* deflateInit and inflateInit are macros to allow checking the zlib version
+ * and the compiler's view of z_stream:
+ */
+ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
+ const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
+ const char *version, int stream_size));
+ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
+ int windowBits, int memLevel,
+ int strategy, const char *version,
+ int stream_size));
+ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
+ const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
+ unsigned char FAR *window,
+ const char *version,
+ int stream_size));
+#define deflateInit(strm, level) \
+ deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit(strm) \
+ inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
+#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+ (strategy), ZLIB_VERSION, sizeof(z_stream))
+#define inflateInit2(strm, windowBits) \
+ inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
+#define inflateBackInit(strm, windowBits, window) \
+ inflateBackInit_((strm), (windowBits), (window), \
+ ZLIB_VERSION, sizeof(z_stream))
+
+#ifdef _LARGEFILE64_SOURCE
+ ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+ ZEXTERN off64_t ZEXPORT gzseek64 OF((gzFile, off64_t, int));
+ ZEXTERN off64_t ZEXPORT gztell64 OF((gzFile));
+ ZEXTERN off64_t ZEXPORT gzoffset64 OF((gzFile));
+ ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, off64_t));
+ ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, off64_t));
+#endif
+
+#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS == 64
+# define gzopen gzopen64
+# define gzseek gzseek64
+# define gztell gztell64
+# define gzoffset gzoffset64
+# define adler32_combine adler32_combine64
+# define crc32_combine crc32_combine64
+# ifndef _LARGEFILE64_SOURCE
+ ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+ ZEXTERN off_t ZEXPORT gzseek64 OF((gzFile, off_t, int));
+ ZEXTERN off_t ZEXPORT gztell64 OF((gzFile));
+ ZEXTERN off_t ZEXPORT gzoffset64 OF((gzFile));
+ ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, off_t));
+ ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, off_t));
+# endif
+#else
+ ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
+ ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
+ ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
+ ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
+ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+ ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+#endif
+
+#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
+ struct internal_state {int dummy;}; /* hack for buggy compilers */
+#endif
+
+ZEXTERN const char * ZEXPORT zError OF((int));
+ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp));
+ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
+ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int));
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ZLIB_H */
diff --git a/plugins/SendScreenshotPlus/CSend.cpp b/plugins/SendScreenshotPlus/CSend.cpp
new file mode 100644
index 0000000000..4e48ecb2b4
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSend.cpp
@@ -0,0 +1,416 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSend.cpp $
+Revision : $Revision: 19 $
+Last change on : $Date: 2010-04-09 03:24:04 +0400 (Пт, 09 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#include "CSend.h"
+
+//---------------------------------------------------------------------------
+CSend::CSend(HWND Owner, HANDLE hContact, bool bFreeOnExit) {
+ m_hWndO = Owner;
+ m_bFreeOnExit = bFreeOnExit;
+ m_pszFile = NULL;
+ m_pszFileDesc = NULL;
+ m_pszProto = NULL;
+ m_ChatRoom = NULL;
+ m_PFflag = NULL;
+ m_hContact = NULL;
+ if (hContact) SetContact(hContact);
+ m_hOnSend = NULL;
+ m_szEventMsg = NULL;
+ m_szEventMsgT = NULL;
+ m_pszSendTyp = NULL;
+
+ m_ErrorMsg = NULL;
+ m_ErrorTitle = NULL;
+}
+
+CSend::~CSend(){
+ mir_free(m_pszFile);
+ mir_free(m_pszFileDesc);
+ mir_free(m_szEventMsg);
+ mir_free(m_szEventMsgT);
+ mir_free(m_ErrorMsg);
+ mir_free(m_ErrorTitle);
+ if (m_hOnSend) UnhookEvent(m_hOnSend);
+}
+
+//---------------------------------------------------------------------------
+void CSend::SetContact(HANDLE hContact) {
+ m_hContact = hContact;
+ m_pszProto = (char*)CallService(MS_PROTO_GETCONTACTBASEPROTO,(WPARAM)hContact,0);
+ m_ChatRoom = DBGetContactSettingByte(hContact, m_pszProto, "ChatRoom", 0);
+ m_PFflag = hasCap(PF1_URLSEND);
+ m_PFflag = hasCap(PF1_CHAT);
+ m_PFflag = hasCap(PF1_IMSEND);
+}
+
+//---------------------------------------------------------------------------
+bool CSend::hasCap(unsigned int Flag) {
+ return (Flag & CallContactService(m_hContact, PS_GETCAPS, (WPARAM)PFLAGNUM_1, NULL)) == Flag;
+}
+
+//---------------------------------------------------------------------------
+void CSend::svcSendMsg(const char* szMessage) {
+ mir_freeAndNil(m_szEventMsg);
+ m_cbEventMsg=lstrlenA(szMessage)+1;
+ m_szEventMsg=(char*)mir_realloc(m_szEventMsg, sizeof(char)*m_cbEventMsg);
+ ZeroMemory(m_szEventMsg, m_cbEventMsg);
+ lstrcpyA(m_szEventMsg,szMessage);
+ if (m_pszFileDesc && m_pszFileDesc[0] != NULL) {
+ char *temp = mir_t2a(m_pszFileDesc);
+ mir_stradd(m_szEventMsg, "\r\n");
+ mir_stradd(m_szEventMsg, temp);
+ m_cbEventMsg = lstrlenA(m_szEventMsg)+1;
+ mir_free(temp);
+ }
+ //create a HookEventObj on ME_PROTO_ACK
+ if (!m_hOnSend) {
+ int (__cdecl CSend::*hookProc)(WPARAM, LPARAM);
+ hookProc = &CSend::OnSend;
+ m_hOnSend = HookEventObj(ME_PROTO_ACK, (MIRANDAHOOKOBJ)*(void **)&hookProc, this);
+ }
+ //start PSS_MESSAGE service
+ m_hSend = (HANDLE)CallContactService(m_hContact, PSS_MESSAGE, NULL, (LPARAM)m_szEventMsg);
+ // check we actually got an ft handle back from the protocol
+ if (!m_hSend) {
+ Unhook();
+ Error(SS_ERR_INIT, m_pszSendTyp);
+ Exit(ACKRESULT_FAILED);
+ }
+}
+
+void CSend::svcSendUrl(const char* url) {
+//szMessage should be encoded as the URL followed by the description, the
+//separator being a single nul (\0). If there is no description, do not forget
+//to end the URL with two nuls.
+ mir_freeAndNil(m_szEventMsg)
+ m_cbEventMsg=lstrlenA(url)+2;
+ m_szEventMsg=(char*)mir_realloc(m_szEventMsg, m_cbEventMsg);
+ ZeroMemory(m_szEventMsg, m_cbEventMsg);
+ lstrcpyA(m_szEventMsg,url);
+ if (m_pszFileDesc && m_pszFileDesc[0] != NULL) {
+ char *temp = mir_t2a(m_pszFileDesc);
+ m_cbEventMsg += lstrlenA(temp);
+ m_szEventMsg=(char*)mir_realloc(m_szEventMsg, sizeof(char)*m_cbEventMsg);
+ lstrcpyA(m_szEventMsg+lstrlenA(url)+1,temp);
+ m_szEventMsg[m_cbEventMsg-1] = 0;
+ mir_free(temp);
+ }
+ //create a HookEventObj on ME_PROTO_ACK
+ if (!m_hOnSend) {
+ int (__cdecl CSend::*hookProc)(WPARAM, LPARAM);
+ hookProc = &CSend::OnSend;
+ m_hOnSend = HookEventObj(ME_PROTO_ACK, (MIRANDAHOOKOBJ)*(void **)&hookProc, this);
+ }
+ //start PSS_URL service
+ m_hSend = (HANDLE)CallContactService(m_hContact, PSS_URL, NULL, (LPARAM)m_szEventMsg);
+ // check we actually got an ft handle back from the protocol
+ if (!m_hSend) {
+ //SetFtStatus(hwndDlg, LPGENT("Unable to initiate transfer."), FTS_TEXT);
+ //dat->waitingForAcceptance=0;
+ Unhook();
+ }
+}
+
+void CSend::svcSendChat() {
+ LPTSTR dirtyFix = NULL;
+ GC_INFO gci = {0};
+ GCDEST gcd = {0};
+ GCEVENT gce = {0};
+ int res = GC_RESULT_NOSESSION;
+ int cnt = (int)CallService(MS_GC_GETSESSIONCOUNT, 0, (LPARAM)m_pszProto);
+
+ //loop on all gc session to get the right (save) ptszID for the chatroom from m_hContact
+ gci.pszModule = m_pszProto;
+ for (int i = 0; i < cnt ; i++ ) {
+ gci.iItem = i;
+ gci.Flags = BYINDEX | HCONTACT | ID; //need dirty fix
+ CallService(MS_GC_GETINFO, 0, (LPARAM)(GC_INFO *) &gci);
+ if (gci.hContact == m_hContact) {
+ gcd.pszModule = m_pszProto;
+ gcd.iType = GC_EVENT_SENDMESSAGE; //GC_EVENT_MESSAGE ???;
+#ifdef _UNICODE
+ gcd.ptszID = gci.pszID;
+#else //dirty fix coz MS_GC_GETINFO dont know if caller is ansi or unicode.
+ //result from MS_GC_GETINFO only depend on type of chat.dll and not of caller type
+ if (mir_is_unicode()) {
+ dirtyFix = mir_u2t((wchar_t*)gci.pszID);
+ }
+ else {
+ dirtyFix = mir_tstrdup(gci.pszID);
+ }
+ gcd.ptszID = dirtyFix; //fixed gci.pszID;
+#endif
+ gce.cbSize = sizeof(GCEVENT);
+ gce.pDest = &gcd;
+ gce.bIsMe = TRUE;
+ gce.dwFlags = GC_TCHAR|GCEF_ADDTOLOG;
+ gce.ptszText = m_szEventMsgT;
+ gce.time = time(NULL);
+
+ //* returns 0 on success or error code on failure
+ res = 200 + (int)CallService(MS_GC_EVENT, 0, (LPARAM)(GCEVENT *) &gce);
+ mir_freeAndNil(dirtyFix);
+ break;
+ }
+ }
+ Exit(res);
+}
+
+void CSend::svcSendChat(const char* szMessage) {
+ if (!m_ChatRoom) {
+ svcSendMsg(szMessage);
+ return;
+ }
+ mir_freeAndNil(m_szEventMsgT);
+ m_szEventMsgT = mir_a2t(szMessage);
+ if (m_pszFileDesc) {
+ mir_tcsadd(m_szEventMsgT, _T("\r\n"));
+ mir_tcsadd(m_szEventMsgT, m_pszFileDesc);
+ }
+ svcSendChat();
+}
+
+void CSend::svcSendFile() {
+//szMessage should be encoded as the File followed by the description, the
+//separator being a single nul (\0). If there is no description, do not forget
+//to end the File with two nuls.
+ mir_freeAndNil(m_szEventMsg)
+ char *szFile = mir_t2a(m_pszFile);
+ m_cbEventMsg=lstrlenA(szFile)+2;
+ m_szEventMsg=(char*)mir_realloc(m_szEventMsg, sizeof(char)*m_cbEventMsg);
+ ZeroMemory(m_szEventMsg, m_cbEventMsg);
+ lstrcpyA(m_szEventMsg,szFile);
+ if (m_pszFileDesc && m_pszFileDesc[0] != NULL) {
+ char* temp = mir_t2a(m_pszFileDesc);
+ m_cbEventMsg += lstrlenA(temp);
+ m_szEventMsg=(char*)mir_realloc(m_szEventMsg, sizeof(char)*m_cbEventMsg);
+ lstrcpyA(m_szEventMsg+lstrlenA(szFile)+1,temp);
+ m_szEventMsg[m_cbEventMsg-1] = 0;
+ mir_freeAndNil(temp);
+ }
+ mir_freeAndNil(szFile);
+
+ //create a HookEventObj on ME_PROTO_ACK
+ if (!m_hOnSend) {
+ int (__cdecl CSend::*hookProc)(WPARAM, LPARAM);
+ hookProc = &CSend::OnSend;
+ m_hOnSend = HookEventObj(ME_PROTO_ACK, (MIRANDAHOOKOBJ)*(void **)&hookProc, this);
+ }
+ // Start miranda PSS_FILE based on mir ver (T)
+ if ((CallService(MS_SYSTEM_GETVERSION,0,0) >= 0x090000) && mir_is_unicode()) {
+ TCHAR *ppFile[2]={0,0};
+ TCHAR *pDesc = mir_tstrdup(m_pszFileDesc);
+ ppFile[0] = mir_tstrdup (m_pszFile);
+/* #if defined( _UNICODE )
+ TCHAR *ppFile[2]={0,0};
+ TCHAR *pDesc = mir_tstrdup(m_pszFileDesc);
+ ppFile[0] = mir_tstrdup (m_pszFile);
+ #else
+ wchar_t *ppFile[2]={0,0};
+ wchar_t *pDesc = mir_t2u (m_pszFileDesc);
+ ppFile[0] = mir_t2u (m_pszFile);
+ #endif */
+ ppFile[1] = NULL;
+ m_hSend = (HANDLE)CallContactService(m_hContact, PSS_FILET, (WPARAM)pDesc, (LPARAM)ppFile);
+ mir_free(pDesc);
+ mir_free(ppFile[0]);
+ }
+ else {
+ char *pDesc = mir_t2a(m_pszFileDesc);
+ char *ppFile[2]={0};
+ ppFile[0] = mir_t2a(m_pszFile);
+ ppFile[1] = NULL;
+ m_hSend = (HANDLE)CallContactService(m_hContact, PSS_FILE, (WPARAM)pDesc, (LPARAM)ppFile);
+ mir_free(pDesc);
+ mir_free(ppFile[0]);
+ }
+ // check we actually got an ft handle back from the protocol
+ if (!m_hSend) {
+ Unhook();
+ Error(SS_ERR_INIT, m_pszSendTyp);
+ Exit(ACKRESULT_FAILED);
+ }
+}
+
+//---------------------------------------------------------------------------
+int __cdecl CSend::OnSend(WPARAM wParam, LPARAM lParam){
+ ACKDATA *ack=(ACKDATA*)lParam;
+ if(ack->hProcess!= m_hSend) return 0;
+ /* if(dat->waitingForAcceptance) {
+ SetTimer(hwndDlg,1,1000,NULL);
+ dat->waitingForAcceptance=0;
+ }
+ */
+
+ switch(ack->result) {
+ case ACKRESULT_INITIALISING: //SetFtStatus(hwndDlg, LPGENT("Initialising..."), FTS_TEXT); break;
+ case ACKRESULT_CONNECTING: //SetFtStatus(hwndDlg, LPGENT("Connecting..."), FTS_TEXT); break;
+ case ACKRESULT_CONNECTPROXY: //SetFtStatus(hwndDlg, LPGENT("Connecting to proxy..."), FTS_TEXT); break;
+ case ACKRESULT_LISTENING: //SetFtStatus(hwndDlg, LPGENT("Waiting for connection..."), FTS_TEXT); break;
+ case ACKRESULT_CONNECTED: //SetFtStatus(hwndDlg, LPGENT("Connected"), FTS_TEXT); break;
+ case ACKRESULT_SENTREQUEST: //SetFtStatus(hwndDlg, LPGENT("Decision sent"), FTS_TEXT); break;
+ case ACKRESULT_NEXTFILE: //SetFtStatus(hwndDlg, LPGENT("Moving to next file..."), FTS_TEXT);
+ case ACKRESULT_FILERESUME: //
+ case ACKRESULT_DATA: //transfer is on progress
+ break;
+ case ACKRESULT_DENIED:
+ Unhook();
+ Exit(ack->result);
+ break;
+ case ACKRESULT_FAILED:
+ Unhook();
+ Exit(ack->result);
+ //type=ACKTYPE_MESSAGE, result=success/failure, (char*)lParam=error message or NULL.
+ //type=ACKTYPE_URL, result=success/failure, (char*)lParam=error message or NULL.
+ //type=ACKTYPE_FILE, result=ACKRESULT_FAILED then lParam=(LPARAM)(const char*)szReason
+ break;
+ case ACKRESULT_SUCCESS:
+ Unhook();
+ switch(ack->type) {
+ case ACKTYPE_CHAT:
+ break;
+ case ACKTYPE_MESSAGE:
+ DB_EventAdd((WORD)EVENTTYPE_MESSAGE);
+ break;
+ case ACKTYPE_URL:
+ DB_EventAdd((WORD)EVENTTYPE_URL);
+ break;
+ case ACKTYPE_FILE:
+ //MS_DB_EVENT_ADD need 4byte extra at the beginning of m_szEventMsg for ACKTYPE_FILE
+ m_szEventMsg = (char*) mir_realloc(m_szEventMsg, sizeof(DWORD) + m_cbEventMsg);
+ //memmove_s(m_szEventMsg+sizeof(DWORD), m_cbEventMsg, m_szEventMsg, m_cbEventMsg);
+ memmove(m_szEventMsg+sizeof(DWORD), m_szEventMsg, m_cbEventMsg);
+ m_cbEventMsg += sizeof(DWORD);
+ DB_EventAdd((WORD)EVENTTYPE_FILE);
+ break;
+ default:
+ break;
+ }
+ Exit(ack->result);
+ break;
+ default:
+ return 0;
+ break;
+ }
+ return 0;
+}
+
+void CSend::DB_EventAdd(WORD EventType) {
+ DBEVENTINFO dbei={0};
+ dbei.cbSize = sizeof(dbei);
+ dbei.szModule = m_pszProto;
+ dbei.eventType = EventType;
+ dbei.flags = DBEF_SENT;
+ dbei.timestamp = time(NULL);
+ #if defined( _UNICODE )
+ dbei.flags |= DBEF_UTF;
+ #endif
+ dbei.cbBlob= m_cbEventMsg;
+ dbei.pBlob=(PBYTE)m_szEventMsg;
+
+ CallService(MS_DB_EVENT_ADD,(WPARAM)m_hContact,(LPARAM)&dbei);
+}
+
+//---------------------------------------------------------------------------
+void CSend::AfterSendDelete() {
+ if (m_pszFile && m_bDeleteAfterSend && (m_EnableItem & SS_DLG_DELETEAFTERSSEND) == SS_DLG_DELETEAFTERSSEND) {
+ DeleteFile(m_pszFile);
+ }
+}
+
+//---------------------------------------------------------------------------
+void CSend::Exit(unsigned int Result) {
+ bool err = true;
+ if (m_hWndO && IsWindow(m_hWndO)){
+ ;
+ }
+ switch(Result) {
+ case ACKRESULT_SUCCESS:
+ case GC_RESULT_SUCCESS:
+ SkinPlaySound("FileDone");
+ err = false;
+ break;
+ case ACKRESULT_DENIED:
+ SkinPlaySound("FileDenied");
+ Error(_T("%s (%i):\nFile transfer denied."),TranslateTS(m_pszSendTyp),Result);
+ MsgBoxService(NULL, (LPARAM)&m_box);
+ err = false;
+ break;
+ case GC_RESULT_WRONGVER: //.You appear to be using the wrong version of GC API.
+ Error(_T("%s (%i):\nYou appear to be using the wrong version of GC API"),TranslateT("GCHAT error"),Result);
+ break;
+ case GC_RESULT_ERROR: // An internal GC error occurred.
+ Error(_T("%s (%i):\nAn internal GC error occurred."),TranslateT("GCHAT error"),Result);
+ break;
+ case GC_RESULT_NOSESSION: // contact has no open GC session
+ Error(_T("%s (%i):\nContact has no open GC session."),TranslateT("GCHAT error"),Result);
+ break;
+ case ACKRESULT_FAILED:
+ default:
+ break;
+ }
+ if (err){
+ SkinPlaySound("FileFailed");
+ if(m_ErrorMsg && m_ErrorMsg[0] != 0) MsgBoxService(NULL, (LPARAM)&m_box);
+ else MsgErr(NULL, LPGENT("An unknown error has occured."));
+ }
+
+ AfterSendDelete();
+ if(m_bFreeOnExit) delete this;
+}
+
+void CSend::Error(LPCTSTR pszFormat, ...) {
+ if(!pszFormat) return;
+
+ TCHAR tszTemp[MAX_SECONDLINE];
+ va_list vl;
+
+ mir_sntprintf(tszTemp, SIZEOF(tszTemp),_T("%s - %s") ,_T(MODNAME), TranslateT("Error"));
+ mir_freeAndNil(m_ErrorTitle);
+ m_ErrorTitle = mir_tstrdup(tszTemp);
+
+ va_start(vl, pszFormat);
+ mir_vsntprintf(tszTemp, SIZEOF(tszTemp), TranslateTS(pszFormat), vl);
+ va_end(vl);
+ mir_freeAndNil(m_ErrorMsg);
+ m_ErrorMsg = mir_tstrdup(tszTemp);
+
+ ZeroMemory(&m_box, sizeof(m_box));
+ m_box.cbSize = sizeof(MSGBOX);
+ m_box.hParent = NULL;
+ m_box.hiLogo = IcoLib_GetIcon(ICO_PLUG_SSWINDOW1);
+ m_box.hiMsg = NULL;
+ m_box.ptszTitle = m_ErrorTitle;
+ m_box.ptszMsg = m_ErrorMsg;
+ m_box.uType = MB_OK|MB_ICON_ERROR;
+}
+
diff --git a/plugins/SendScreenshotPlus/CSend.h b/plugins/SendScreenshotPlus/CSend.h
new file mode 100644
index 0000000000..082f3e961a
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSend.h
@@ -0,0 +1,113 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSend.h $
+Revision : $Revision: 17 $
+Last change on : $Date: 2010-04-03 18:01:11 +0400 (Сб, 03 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _CSEND_H
+#define _CSEND_H
+
+//---------------------------------------------------------------------------
+#include "global.h"
+#include "Utils.h"
+#include "dlg_msgbox.h"
+
+
+//---------------------------------------------------------------------------
+#define SS_AUTOSEND 1
+#define SS_DELETEAFTERSSEND 2
+
+#define SS_DLG_AUTOSEND 1 //Button_Enable(GetDlgItem(Owner, ID_chkEmulateClick), TRUE);
+#define SS_DLG_DELETEAFTERSSEND 2 //Button_Enable(GetDlgItem(Owner, ID_btnDeleteAfterSend), TRUE);
+#define SS_DLG_DESCRIPTION 4 //Button_Enable(GetDlgItem(Owner, ID_btnDesc), TRUE);
+
+#define GC_RESULT_SUCCESS 200
+#define GC_RESULT_WRONGVER 201
+#define GC_RESULT_ERROR 202
+#define GC_RESULT_NOSESSION 209
+
+#define SS_ERR_INIT _T("Unable to initiate %s.")
+#define SS_ERR_MAPI _T("MAPI error (%i):\n%s.")
+
+//---------------------------------------------------------------------------
+class CSend {
+ public:
+ CSend(HWND Owner, HANDLE hContact, bool bFreeOnExit); // oder (TfrmMain & Owner)
+ virtual ~CSend();
+
+ virtual void Send() = 0;
+ void SendSync(bool Sync) {m_SendSync = Sync;};
+ bool m_bFreeOnExit; // need to "delete object;" on exit ?
+ void SetContact(HANDLE hContact);
+ BYTE GetEnableItem() {return m_EnableItem;};
+ LPTSTR GetErrorMsg() {return m_ErrorMsg;};
+
+ LPTSTR m_pszFile;
+ LPTSTR m_pszFileDesc;
+
+ BOOL m_bDeleteAfterSend;
+
+ private:
+
+ protected:
+ LPTSTR m_pszSendTyp; //hold string for error mess
+ HWND m_hWndO; //window handle of caller
+ HANDLE m_hContact; //Contact handle
+ char* m_pszProto; //Contact Proto Modul
+ BYTE m_EnableItem; //hold flag for send type
+ void AfterSendDelete();
+ BYTE m_ChatRoom; //is Contact chatroom
+ bool m_SendSync; //send sync / async
+
+ bool hasCap(unsigned int Flag);
+ unsigned int m_PFflag;
+
+ void svcSendFile();
+ void svcSendUrl (const char* url);
+ void svcSendMsg (const char* szMessage);
+ void svcSendChat(); //main GC service
+ void svcSendChat(const char* szMessage); //GC ansi wrapper
+
+ DWORD m_cbEventMsg; //sizeof EventMsg(T) buffer
+ char* m_szEventMsg; //EventMsg char*
+ LPTSTR m_szEventMsgT; //EventMsg TCHAR*
+ HANDLE m_hSend; //protocol send handle
+ HANDLE m_hOnSend; //HookEventObj on ME_PROTO_ACK
+ int __cdecl OnSend(WPARAM wParam, LPARAM lParam);
+ void Unhook(){if(m_hOnSend) {UnhookEvent(m_hOnSend);m_hOnSend = NULL;}}
+ void DB_EventAdd(WORD EventType);
+ void Exit(unsigned int Result);
+
+ MSGBOX m_box;
+ LPTSTR m_ErrorMsg;
+ LPTSTR m_ErrorTitle;
+ void Error(LPCTSTR pszFormat, ...);
+};
+
+#endif
diff --git a/plugins/SendScreenshotPlus/CSendEmail.cpp b/plugins/SendScreenshotPlus/CSendEmail.cpp
new file mode 100644
index 0000000000..14e539ea0d
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendEmail.cpp
@@ -0,0 +1,221 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendEmail.cpp $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+//---------------------------------------------------------------------------
+#include "CSendEmail.h"
+
+//---------------------------------------------------------------------------
+CSendEmail::CSendEmail(HWND Owner, HANDLE hContact, bool bFreeOnExit)
+: CSend(Owner, hContact, bFreeOnExit){
+ m_EnableItem = SS_DLG_DELETEAFTERSSEND | SS_DLG_DESCRIPTION; // SS_DLG_AUTOSEND | ;
+ m_pszSendTyp = _T("Email transfer");
+ m_pszFileA = NULL;
+ m_pszFileName = NULL;
+ m_Email = NULL;
+ m_FriendlyName = NULL;
+ m_Subject = NULL;
+}
+
+CSendEmail::~CSendEmail(){
+ mir_free(m_pszFileA);
+ mir_free(m_pszFileName);
+ mir_free(m_Email);
+ mir_free(m_FriendlyName);
+ mir_free(m_Subject);
+}
+
+//---------------------------------------------------------------------------
+void CSendEmail::Send() {
+
+ mir_freeAndNil(m_pszFileName);
+ m_pszFileName = (LPSTR)GetFileName(m_pszFile, DBVT_ASCIIZ);
+
+ mir_freeAndNil(m_pszFileA);
+ m_pszFileA = mir_t2a(m_pszFile);
+
+
+// AnsiString Email, Subject, FriendlyName;
+ CONTACTINFO ci={0};
+ ci.cbSize = sizeof(ci);
+ ci.hContact = m_hContact;
+ ci.szProto = m_pszProto;
+ //ci.dwFlag = CNF_TCHAR;
+
+ ci.dwFlag = CNF_EMAIL | CNF_TCHAR;
+ CallService(MS_CONTACT_GETCONTACTINFO,(WPARAM)0,(LPARAM)&ci);
+ m_Email = mir_t2a(ci.pszVal);
+
+ ci.dwFlag = CNF_DISPLAY | CNF_TCHAR;
+ CallService(MS_CONTACT_GETCONTACTINFO,(WPARAM)0,(LPARAM)&ci);
+ m_FriendlyName = mir_t2a(ci.pszVal);
+
+ mir_free(ci.pszVal);
+
+ m_Subject = mir_t2a(m_pszFileDesc);
+
+ //SendByEmail(m_pszFileA, "", m_FriendlyName, m_Email, m_Subject);
+
+ //start Send thread
+ m_bFreeOnExit = TRUE;
+ mir_forkthread(&CSendEmail::SendThreadWrapper, this);
+}
+
+void CSendEmail::SendThread() {
+ //This code based on SentTo.exe application.
+ //The default mail client for Simple MAPI or MAPI calls is defined by the
+ //HKLM\Software\Clients\Mail::(default) registry value.
+
+ LPTSTR err = NULL;
+ MapiFileDesc arrfileDesc[1];
+
+ typedef ULONG (FAR PASCAL *MAPIFUNC)(LHANDLE,ULONG,lpMapiMessage,FLAGS,ULONG);
+ MapiMessage Msg;
+ MAPIFUNC lpMAPISendMail;
+
+ HINSTANCE hMAPILib = ::LoadLibrary(_T("MAPI32.DLL"));
+ if (hMAPILib == NULL) {
+ //return -1;
+ Error(SS_ERR_INIT, m_pszSendTyp);
+ Exit(ACKRESULT_FAILED);
+ }
+
+ lpMAPISendMail = (MAPIFUNC)GetProcAddress(hMAPILib, "MAPISendMail");
+ if (lpMAPISendMail == NULL) {
+ ::FreeLibrary(hMAPILib);
+ //return -2;
+ Error(SS_ERR_INIT, m_pszSendTyp);
+ Exit(ACKRESULT_FAILED);
+ }
+
+ memset(&Msg, 0, sizeof(Msg));
+
+ arrfileDesc[0].ulReserved = 0;
+ arrfileDesc[0].flFlags = 0;
+ arrfileDesc[0].lpFileType = NULL;
+ arrfileDesc[0].nPosition = -1;
+ arrfileDesc[0].lpszPathName = m_pszFileA;
+ arrfileDesc[0].lpszFileName = NULL;
+
+ Msg.nFileCount = 1;
+ Msg.lpFiles = arrfileDesc;
+ Msg.lpszNoteText = ""; //body
+ Msg.lpszSubject = m_Subject; //subject
+
+ Msg.nRecipCount = 1;
+ MapiRecipDesc recip;
+ recip.ulReserved = 0;
+ recip.ulRecipClass = MAPI_TO;
+
+ if (m_FriendlyName && m_FriendlyName[0]!= NULL) {
+ recip.lpszName = m_FriendlyName; //friendly name set to contact's name
+ }
+ else {
+ recip.lpszName = m_Email; //friendly name set to contact's email
+ }
+
+ recip.lpszAddress = m_Email; //email
+ recip.ulEIDSize = 0;
+ recip.lpEntryID = NULL;
+ Msg.lpRecips = &recip;
+
+ try {
+ int res = lpMAPISendMail(NULL, NULL, &Msg, MAPI_LOGON_UI|MAPI_DIALOG, 0);
+ ::FreeLibrary(hMAPILib);
+
+ switch (res) {
+ case SUCCESS_SUCCESS:
+ //The call succeeded and the message was sent.
+ Exit(ACKRESULT_SUCCESS);
+ return;
+
+ // No message was sent
+ case MAPI_E_AMBIGUOUS_RECIPIENT:
+ err = _T("A recipient matched more than one of the recipient descriptor structures and MAPI_DIALOG was not set");
+ break;
+ case MAPI_E_ATTACHMENT_NOT_FOUND:
+ err = _T("The specified attachment was not found");
+ break;
+ case MAPI_E_ATTACHMENT_OPEN_FAILURE:
+ err = _T("The specified attachment could not be opened");
+ break;
+ case MAPI_E_BAD_RECIPTYPE:
+ err = _T("The type of a recipient was not MAPI_TO, MAPI_CC, or MAPI_BCC");
+ break;
+ case MAPI_E_FAILURE:
+ err = _T("One or more unspecified errors occurred");
+ break;
+ case MAPI_E_INSUFFICIENT_MEMORY:
+ err = _T("There was insufficient memory to proceed");
+ break;
+ case MAPI_E_INVALID_RECIPS:
+ err = _T("One or more recipients were invalid or did not resolve to any address");
+ break;
+ case MAPI_E_LOGIN_FAILURE:
+ err = _T("There was no default logon, and the user failed to log on successfully when the logon dialog box was displayed");
+ break;
+ case MAPI_E_TEXT_TOO_LARGE:
+ err = _T("The text in the message was too large");
+ break;
+ case MAPI_E_TOO_MANY_FILES:
+ err = _T("There were too many file attachments");
+ break;
+ case MAPI_E_TOO_MANY_RECIPIENTS:
+ err = _T("There were too many recipients");
+ break;
+ case MAPI_E_UNKNOWN_RECIPIENT:
+ err = _T("A recipient did not appear in the address list");
+ break;
+ case MAPI_E_USER_ABORT:
+ err = _T("The user canceled one of the dialog boxes");
+ break;
+ default:
+ err = _T("Unknown Error");
+ break;
+ }
+ Error(SS_ERR_MAPI, res, err);
+ Exit(ACKRESULT_FAILED);
+
+ } catch (...) {
+ ::FreeLibrary(hMAPILib);
+ Error(SS_ERR_INIT, m_pszSendTyp);
+ Exit(ACKRESULT_FAILED);
+ //return -3;
+ return;
+ }
+}
+
+void CSendEmail::SendThreadWrapper(void * Obj) {
+ reinterpret_cast<CSendEmail*>(Obj)->SendThread();
+}
+
+//---------------------------------------------------------------------------
+
diff --git a/plugins/SendScreenshotPlus/CSendEmail.h b/plugins/SendScreenshotPlus/CSendEmail.h
new file mode 100644
index 0000000000..940558b0d6
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendEmail.h
@@ -0,0 +1,63 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendEmail.h $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _CSEND_EMAIL_H
+#define _CSEND_EMAIL_H
+
+//---------------------------------------------------------------------------
+#include "global.h"
+#include "CSend.h"
+#include <mapi.h>
+
+//---------------------------------------------------------------------------
+class CSendEmail : public CSend {
+ public:
+ // Deklaration Standardkonstruktor/Standarddestructor
+ CSendEmail(HWND Owner, HANDLE hContact, bool bFreeOnExit);
+ ~CSendEmail();
+
+ void Send();
+
+ protected:
+ LPSTR m_pszFileA;
+ LPSTR m_pszFileName;
+ LPSTR m_Email;
+ LPSTR m_FriendlyName;
+ LPSTR m_Subject;
+ void SendThread();
+ static void SendThreadWrapper(void * Obj);
+
+};
+
+//---------------------------------------------------------------------------
+
+#endif
diff --git a/plugins/SendScreenshotPlus/CSendFTPFile.cpp b/plugins/SendScreenshotPlus/CSendFTPFile.cpp
new file mode 100644
index 0000000000..d7512d2fe6
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendFTPFile.cpp
@@ -0,0 +1,99 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendFTPFile.cpp $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+//---------------------------------------------------------------------------
+#include "CSendFTPFile.h"
+
+
+//---------------------------------------------------------------------------
+CSendFTPFile::CSendFTPFile(HWND Owner, HANDLE hContact, bool bFreeOnExit)
+: CSend(Owner, hContact, bFreeOnExit){
+ m_EnableItem = NULL ; //SS_DLG_DESCRIPTION| SS_DLG_AUTOSEND | SS_DLG_DELETEAFTERSSEND;
+ m_pszSendTyp = _T("FTPFile transfer");
+ m_pszFileName = NULL;
+ m_URL = NULL;
+}
+
+CSendFTPFile::~CSendFTPFile(){
+ mir_free(m_pszFileName);
+ mir_free(m_URL);
+}
+
+//---------------------------------------------------------------------------
+void CSendFTPFile::Send() {
+
+ /*********************************************************************************************
+ * Send file (files) to the FTP server and copy file URL
+ * to message log or clipboard (according to plugin setting)
+ * wParam = (HANDLE)hContact
+ * lParam = (char *)filename
+ * Filename format is same as GetOpenFileName (OPENFILENAME.lpstrFile) returns,
+ * see http://msdn2.microsoft.com/en-us/library/ms646839.aspx
+ * Returns 0 on success or nonzero on failure
+ * if (!wParam || !lParam) return 1
+ ********************************************************************************************/
+ mir_freeAndNil(m_pszFileName);
+ m_pszFileName = (LPSTR)GetFileName(m_pszFile, DBVT_ASCIIZ);
+ size_t size = sizeof(char)*(strlen(m_pszFileName)+2);
+ m_pszFileName = (LPSTR) mir_realloc(m_pszFileName, size);
+ m_pszFileName[size-1] = NULL;
+
+ //start Send thread
+ m_bFreeOnExit = TRUE;
+ mir_forkthread(&CSendFTPFile::SendThreadWrapper, this);
+}
+
+void CSendFTPFile::SendThread() {
+ int ret;
+ mir_freeAndNil(m_URL);
+
+ ret = (int)CallService(MS_FTPFILE_SHAREFILE, (WPARAM)m_hContact, (LPARAM)m_pszFileName);
+ if (ret != 0) {
+ Error(_T("%s (%i):\nCould not add a share to the FTP File plugin."),TranslateTS(m_pszSendTyp),ret);
+ Exit(ret);
+ }
+
+ //Can't delete the file since FTP File plugin will use it
+ m_bDeleteAfterSend = false;
+
+ if (m_URL && m_URL[0]!= NULL) {
+ m_ChatRoom ? svcSendChat(m_URL) : svcSendMsg(m_URL);
+ return;
+ }
+}
+
+void CSendFTPFile::SendThreadWrapper(void * Obj) {
+ reinterpret_cast<CSendFTPFile*>(Obj)->SendThread();
+}
+
+//---------------------------------------------------------------------------
+
diff --git a/plugins/SendScreenshotPlus/CSendFTPFile.h b/plugins/SendScreenshotPlus/CSendFTPFile.h
new file mode 100644
index 0000000000..6012f76232
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendFTPFile.h
@@ -0,0 +1,59 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendFTPFile.h $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _CSEND_FTP_FILE_H
+#define _CSEND_FTP_FILE_H
+
+//---------------------------------------------------------------------------
+#include "global.h"
+#include "CSend.h"
+
+//---------------------------------------------------------------------------
+class CSendFTPFile : public CSend {
+ public:
+ // Deklaration Standardkonstruktor/Standarddestructor
+ CSendFTPFile(HWND Owner, HANDLE hContact, bool bFreeOnExit);
+ ~CSendFTPFile();
+
+ void Send();
+
+ protected:
+ LPSTR m_pszFileName;
+ LPSTR m_URL;
+ void SendThread();
+ static void SendThreadWrapper(void * Obj);
+
+};
+
+//---------------------------------------------------------------------------
+
+#endif
diff --git a/plugins/SendScreenshotPlus/CSendFile.cpp b/plugins/SendScreenshotPlus/CSendFile.cpp
new file mode 100644
index 0000000000..1884c8307f
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendFile.cpp
@@ -0,0 +1,53 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendFile.cpp $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+//---------------------------------------------------------------------------
+#include "CSendFile.h"
+
+//---------------------------------------------------------------------------
+CSendFile::CSendFile(HWND Owner, HANDLE hContact, bool bFreeOnExit)
+: CSend(Owner, hContact, bFreeOnExit){
+ m_EnableItem = SS_DLG_AUTOSEND | SS_DLG_DELETEAFTERSSEND | SS_DLG_DESCRIPTION;
+ m_pszSendTyp = _T("File transfer");
+}
+
+CSendFile::~CSendFile(){
+ ;
+}
+
+//---------------------------------------------------------------------------
+void CSendFile::Send() {
+ m_bFreeOnExit = TRUE;
+ svcSendFile();
+}
+
+//---------------------------------------------------------------------------
diff --git a/plugins/SendScreenshotPlus/CSendFile.h b/plugins/SendScreenshotPlus/CSendFile.h
new file mode 100644
index 0000000000..edbb49822d
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendFile.h
@@ -0,0 +1,55 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendFile.h $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _CSEND_FILE_H
+#define _CSEND_FILE_H
+
+//---------------------------------------------------------------------------
+#include "global.h"
+#include "CSend.h"
+
+//---------------------------------------------------------------------------
+class CSendFile : public CSend {
+ public:
+ // Deklaration Standardkonstruktor/Standarddestructor
+ CSendFile(HWND Owner, HANDLE hContact, bool bFreeOnExit);
+ ~CSendFile();
+
+ void Send();
+
+ protected:
+
+};
+
+//---------------------------------------------------------------------------*/
+
+#endif
diff --git a/plugins/SendScreenshotPlus/CSendHTTPServer.cpp b/plugins/SendScreenshotPlus/CSendHTTPServer.cpp
new file mode 100644
index 0000000000..27eb42d9b4
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendHTTPServer.cpp
@@ -0,0 +1,143 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendHTTPServer.cpp $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+//---------------------------------------------------------------------------
+#include "CSendHTTPServer.h"
+INT_PTR (*g_MirCallService)(const char *, WPARAM, LPARAM)=NULL;
+//INT_PTR (*CallService)(const char *,WPARAM,LPARAM);
+
+
+//---------------------------------------------------------------------------
+CSendHTTPServer::CSendHTTPServer(HWND Owner, HANDLE hContact, bool bFreeOnExit)
+: CSend(Owner, hContact, bFreeOnExit){
+ m_EnableItem = SS_DLG_DESCRIPTION ; //| SS_DLG_AUTOSEND | SS_DLG_DELETEAFTERSSEND;
+ m_pszSendTyp = _T("HTTPServer transfer");
+ m_pszFileName = NULL;
+ m_URL = NULL;
+ m_fsi_pszSrvPath = NULL;
+ m_fsi_pszRealPath = NULL;
+}
+
+CSendHTTPServer::~CSendHTTPServer(){
+ mir_free(m_pszFileName);
+ mir_free(m_URL);
+ mir_free(m_fsi_pszSrvPath);
+ mir_free(m_fsi_pszRealPath);
+}
+
+//---------------------------------------------------------------------------
+void CSendHTTPServer::Send() {
+
+ if (CallService(MS_HTTP_ACCEPT_CONNECTIONS, (WPARAM)true, (LPARAM)0) != 0) {
+ Error(NULL, _T("Could not start the HTTP Server plugin."));
+ return;
+ }
+
+ if (!m_pszFileName) {
+ m_pszFileName = (LPSTR)GetFileName(m_pszFile, DBVT_ASCIIZ);
+ }
+ mir_freeAndNil(m_fsi_pszSrvPath);
+ mir_stradd(m_fsi_pszSrvPath, "/");
+ mir_stradd(m_fsi_pszSrvPath, m_pszFileName);
+
+ mir_freeAndNil(m_fsi_pszRealPath);
+ m_fsi_pszRealPath = mir_t2a(m_pszFile);
+
+ ZeroMemory(&m_fsi, sizeof(m_fsi));
+ m_fsi.lStructSize = sizeof(STFileShareInfo);
+ m_fsi.pszSrvPath = m_fsi_pszSrvPath;
+ m_fsi.nMaxDownloads = -1; // -1 = infinite
+ m_fsi.pszRealPath = m_fsi_pszRealPath;
+ //m_fsi.dwOptions = NULL; //OPT_SEND_LINK only work on single chat;
+
+ //start Send thread
+ m_bFreeOnExit = TRUE;
+ mir_forkthread(&CSendHTTPServer::SendThreadWrapper, this);
+}
+
+void CSendHTTPServer::SendThread() {
+ int ret;
+ mir_freeAndNil(m_URL);
+
+ if (ServiceExists(MS_HTTP_GET_LINK)) {
+ //patched plugin version
+ ret = (int)CallService(MS_HTTP_ADD_CHANGE_REMOVE, (WPARAM)m_hContact, (LPARAM)&m_fsi);
+ if (!ret) {
+ m_URL = (LPSTR)CallService(MS_HTTP_GET_LINK, (WPARAM)m_fsi.pszSrvPath, NULL);
+ }
+ }
+ else {
+ //original plugin
+ m_fsi.dwOptions = OPT_SEND_LINK;
+ g_MirCallService = pluginLink->CallService; //backup Miranda CallService
+ pluginLink->CallService = MyCallService; //Hack on Miranda CallService
+
+ //send DATA and wait for reply
+ ret = (int)CallService(MS_HTTP_ADD_CHANGE_REMOVE, (WPARAM)m_hContact, (LPARAM)&m_fsi);
+ pluginLink->CallService = g_MirCallService; //restore Miranda CallService
+ }
+
+ if (ret != 0) {
+ Error(_T("%s (%i):\nCould not add a share to the HTTP Server plugin."),TranslateTS(m_pszSendTyp),ret);
+ Exit(ret);
+ }
+
+ //Share the file by HTTP Server plugin, SendSS does not own the file anymore = auto-delete won't work
+ m_bDeleteAfterSend = false;
+
+ if (m_URL && m_URL[0]!= NULL) {
+ m_ChatRoom ? svcSendChat(m_URL) : svcSendMsg(m_URL);
+ return;
+ }
+ Exit(ACKRESULT_FAILED);
+}
+
+void CSendHTTPServer::SendThreadWrapper(void * Obj) {
+ reinterpret_cast<CSendHTTPServer*>(Obj)->SendThread();
+}
+
+//---------------------------------------------------------------------------
+CSendHTTPServer::CContactMapping CSendHTTPServer::_CContactMapping;
+
+INT_PTR CSendHTTPServer::MyCallService(const char *name, WPARAM wParam, LPARAM lParam) {
+ CContactMapping::iterator Contact(_CContactMapping.end());
+/*
+ if ( wParam == m_hContact && (
+ (strcmp(name, MS_MSG_SENDMESSAGE)== 0) ||
+ (strcmp(name, "SRMsg/LaunchMessageWindow")== 0) ))
+ {
+ m_URL= mir_strdup((char*)lParam);
+ return 0;
+ }*/
+ return g_MirCallService(name, wParam, lParam);
+}
+
diff --git a/plugins/SendScreenshotPlus/CSendHTTPServer.h b/plugins/SendScreenshotPlus/CSendHTTPServer.h
new file mode 100644
index 0000000000..129153e0c6
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendHTTPServer.h
@@ -0,0 +1,67 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendHTTPServer.h $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _CSEND_HTTP_SERVER_H
+#define _CSEND_HTTP_SERVER_H
+
+//---------------------------------------------------------------------------
+#include "global.h"
+#include "CSend.h"
+
+//---------------------------------------------------------------------------
+class CSendHTTPServer : public CSend {
+ public:
+ // Deklaration Standardkonstruktor/Standarddestructor
+ CSendHTTPServer(HWND Owner, HANDLE hContact, bool bFreeOnExit);
+ ~CSendHTTPServer();
+
+ void Send();
+
+ protected:
+ LPSTR m_pszFileName;
+ LPSTR m_URL;
+ STFileShareInfo m_fsi;
+ LPSTR m_fsi_pszSrvPath;
+ LPSTR m_fsi_pszRealPath;
+ void SendThread();
+ static void SendThreadWrapper(void * Obj);
+
+ typedef std::map<HANDLE, CSendHTTPServer *> CContactMapping;
+ static CContactMapping _CContactMapping;
+
+ static INT_PTR MyCallService(const char *name, WPARAM wParam, LPARAM lParam);
+
+};
+
+//---------------------------------------------------------------------------
+
+#endif
diff --git a/plugins/SendScreenshotPlus/CSendImageShack.cpp b/plugins/SendScreenshotPlus/CSendImageShack.cpp
new file mode 100644
index 0000000000..a27b4f5273
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendImageShack.cpp
@@ -0,0 +1,299 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendImageShack.cpp $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+//---------------------------------------------------------------------------
+#include <fcntl.h>
+#include <io.h>
+#include <sys/stat.h>
+
+#include "CSendImageShack.h"
+#include "DevKey.h"
+
+//---------------------------------------------------------------------------
+CSendImageShack::CSendImageShack(HWND Owner, HANDLE hContact, bool bFreeOnExit)
+: CSend(Owner, hContact, bFreeOnExit) {
+ m_EnableItem = SS_DLG_AUTOSEND | SS_DLG_DELETEAFTERSSEND | SS_DLG_DESCRIPTION;
+ m_pszSendTyp = _T("Image upload");
+ m_pszFileName = NULL;
+ m_pszContentType = NULL;
+ m_MFDRboundary = NULL;
+ m_nlreply = NULL;
+ m_SendSync = false;
+ m_Url = NULL;
+}
+
+CSendImageShack::~CSendImageShack(){
+ mir_free(m_pszFileName);
+ mir_free(m_MFDRboundary);
+ // FREEHTTPREQUESTSTRUCT*
+ if (m_nlreply) CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM) m_nlreply);
+ mir_free(m_Url);
+};
+
+//---------------------------------------------------------------------------
+void CSendImageShack::Send() {
+ // check Netlib
+ if( !hNetlibUser ) {
+ //PrintError(1,TRUE);
+ return;
+ }
+ if (!m_pszFileName) {
+ m_pszFileName = (LPSTR)GetFileName(m_pszFile, DBVT_ASCIIZ);
+ }
+ if (!m_pszContentType) GetContentType();
+
+ // create new boundary
+ MFDR_Reset();
+
+ // initialize the netlib request
+ ZeroMemory(&m_nlhr, sizeof(m_nlhr));
+ m_nlhr.cbSize = sizeof(m_nlhr);
+ m_nlhr.requestType = REQUEST_POST;
+ m_nlhr.flags = NLHRF_HTTP11; //NLHRF_DUMPASTEXT;
+ m_nlhr.szUrl = "http://www.imageshack.us/upload_api.php";
+ m_nlhr.headersCount = 6;
+ { //NETLIBHTTPHEADER start
+ m_nlhr.headers=(NETLIBHTTPHEADER*)mir_alloc(sizeof(NETLIBHTTPHEADER)*m_nlhr.headersCount);
+ m_nlhr.headers[0].szName = "Referer";
+ m_nlhr.headers[0].szValue = "http://www.imageshack.us/upload_api.php";
+ m_nlhr.headers[1].szName = "Connection";
+ m_nlhr.headers[1].szValue = "Keep-alive";
+ m_nlhr.headers[2].szName = "AcceptLanguage";
+ m_nlhr.headers[2].szValue = "en-us, pt-br";
+ m_nlhr.headers[3].szName = "Host";
+ m_nlhr.headers[3].szValue = "imageshack.us";
+ m_nlhr.headers[4].szName = "User-Agent";
+ m_nlhr.headers[4].szValue = __USER_AGENT_STRING; //szAgent; /;
+ //nlhr.headers[x].szName = "Authorization";
+ //nlhr.headers[x].szValue = auth; //Basic base-64-authorization
+
+ //$header .= "Content-type: multipart/form-data; boundary=" . part::getBoundary() . "\r\n";
+ sprintf(m_nlheader_ContentType, "multipart/form-data; boundary=%s", m_MFDRboundary);
+ m_nlhr.headers[m_nlhr.headersCount-1].szName = "Content-Type";
+ m_nlhr.headers[m_nlhr.headersCount-1].szValue = m_nlheader_ContentType;
+ } //NETLIBHTTPHEADER end
+
+//POST DATA file-header, init DATA with MultipartFormDataRequest
+ //$params[] = new filepart('fileupload', $file, basename($file), $contentType, 'iso-8859-1');
+ //($this->sendStart($h);)
+ AppendToData("--");
+ AppendToData(m_MFDRboundary);
+ AppendToData("\r\n");
+ //($this->sendDispositionHeader($h);)
+ AppendToData("Content-Disposition: form-data; name=\"");
+ AppendToData("fileupload");
+ AppendToData("\"; filename=\"");
+ AppendToData(m_pszFileName);
+ AppendToData("\"");
+ AppendToData("\r\n");
+ //($this->sendContentTypeHeader($h);)
+ AppendToData("Content-Type: ");
+ AppendToData(m_pszContentType);
+ AppendToData("; charset=");
+ AppendToData("iso-8859-1");
+ //($this->sendEndOfHeader($h);)
+ AppendToData("\r\n");
+ AppendToData("\r\n");
+ //Now we add the file binary ($this->sendData($h))
+ FILE * fileId = _tfsopen(m_pszFile, _T("rb"), _SH_DENYWR );
+ if( !fileId) {
+ //PrintError(1,TRUE);
+ return;
+ }
+ fseek(fileId, NULL, SEEK_END);
+ size_t lenFile = ftell(fileId);
+ size_t sizeDest = sizeof(char)*(m_nlhr.dataLength + lenFile + 1);
+ m_nlhr.pData = (char *) mir_realloc(m_nlhr.pData, sizeDest);
+ fseek(fileId, NULL, SEEK_SET );
+ int i;
+ int ch = fgetc( fileId );
+ for( i=0; (i < (int)lenFile ) && ( feof( fileId ) == 0 ); i++ ) {
+ m_nlhr.pData[m_nlhr.dataLength+i] = (char)ch;
+ ch = fgetc( fileId );
+ }
+ m_nlhr.pData[sizeDest-1] = 0; //NULL Termination for binary data
+ m_nlhr.dataLength = (int)sizeDest - 1;
+ fclose(fileId);
+ //($this->sendEnd($h);)
+ AppendToData("\r\n");
+
+//POST DATA footer (for "optimage", 1)
+//POST DATA footer (for "optsize", optsize)
+
+//POST DATA footer (for "tags", tags)
+//POST DATA footer (for "rembar", "yes" : "no")
+//POST DATA footer (for "public", "yes" : "no")
+//POST DATA footer (for "cookie", cookie)
+
+//POST DATA footer (for "key", DEVKEY_IMAGESHACK)
+ //($this->sendStart($h);)
+ AppendToData("--");
+ AppendToData(m_MFDRboundary);
+ AppendToData("\r\n");
+ //($this->sendDispositionHeader($h);)
+ AppendToData("Content-Disposition: form-data; name=\"");
+ AppendToData("key");
+ AppendToData("\"");
+ //($this->sendTransferEncodingHeader($h); )
+ AppendToData("\r\n");
+ AppendToData("Content-Transfer-Encoding: ");
+ AppendToData("8bit"); //??"binary"
+ //($this->sendEndOfHeader($h);)
+ AppendToData("\r\n");
+ AppendToData("\r\n");
+ //($this->sendData($h);)
+ AppendToData(DEVKEY_IMAGESHACK);
+ //($this->sendEnd($h);)
+ AppendToData("\r\n");
+
+//POST DATA Exit
+ //$postdata = "--" . part::getBoundary() . "--\r\n";
+ AppendToData("--");
+ AppendToData(m_MFDRboundary);
+ AppendToData("--\r\n");
+
+//start upload thread
+ if (m_SendSync) {
+ m_bFreeOnExit = FALSE;
+ SendThread();
+ return;
+ }
+ m_bFreeOnExit = TRUE;
+ mir_forkthread(&CSendImageShack::SendThreadWrapper, this);
+}
+
+void CSendImageShack::SendThread() {
+ //send DATA and wait for m_nlreply
+ m_nlreply = (NETLIBHTTPREQUEST *) CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM) hNetlibUser, (LPARAM) &m_nlhr);
+ mir_freeAndNil(m_nlhr.pData);
+ mir_freeAndNil(m_nlhr.headers);
+ if(m_nlreply){
+ if( m_nlreply->resultCode >= 200 && m_nlreply->resultCode < 300 ){
+ m_nlreply->pData[m_nlreply->dataLength] = 0;// make sure its null terminated
+ const char* URL = NULL;
+ LPTSTR err = NULL;
+ URL = GetTagContent(m_nlreply->pData, "<image_link>", "</image_link>");
+ if (URL && URL[0]!= NULL) {
+ m_Url = mir_strdup(URL);
+ if(m_SendSync) {
+ Exit(ACKRESULT_SUCCESS);
+ return;
+ }
+ m_ChatRoom ? svcSendChat(URL) : svcSendMsg(URL);
+ return;
+ }
+ else{ //check error mess from server
+ err = mir_a2t(GetTagContent(m_nlreply->pData, "<error ", "</error>"));
+ if (err && err[0]!= NULL) { //parsed err messege
+ Error(NULL, err);
+ }
+ else{ //fallback to server response mess
+ mir_freeAndNil(err);
+ err = mir_a2t(m_nlreply->pData);
+ }
+ mir_free(err);
+ }
+ }
+ else {
+ Error(NULL, _T("Upload server did not respond timely."));
+ }
+ CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM) m_nlreply);
+ m_nlreply = NULL;
+ }
+ else {
+ Error(SS_ERR_INIT, m_pszSendTyp);
+ }
+ Exit(ACKRESULT_FAILED);
+}
+
+void CSendImageShack::SendThreadWrapper(void * Obj) {
+ reinterpret_cast<CSendImageShack*>(Obj)->SendThread();
+}
+
+//---------------------------------------------------------------------------
+void CSendImageShack::MFDR_Reset() {
+ char Temp[64];
+ DWORD dwBoundaryRand1 = GetTickCount();
+ DWORD dwBoundaryRand2 = rand();
+
+ mir_freeAndNil(m_MFDRboundary);
+ sprintf(Temp, "B-O-U-N-D-A-R-Y%u%u", dwBoundaryRand1, dwBoundaryRand2);
+ mir_stradd(m_MFDRboundary,Temp);
+}
+
+void CSendImageShack::GetContentType() {
+ if (m_pszContentType) mir_freeAndNil(m_pszContentType);
+ LPSTR FileExtension = (LPSTR)GetFileExt(m_pszFile, DBVT_ASCIIZ);
+
+ if ((strcmp(FileExtension, ".jpeg")==0) || (strcmp(FileExtension, ".jpe")==0) || (strcmp(FileExtension ,".jpg")==0))
+ m_pszContentType="image/jpeg";
+ else if (strcmp(FileExtension, ".bmp")==0)
+ m_pszContentType="image/bmp";
+ else if (strcmp(FileExtension, ".png")==0)
+ m_pszContentType="image/png";
+ else if (strcmp(FileExtension, ".gif")==0)
+ m_pszContentType="image/gif";
+ else if ((strcmp(FileExtension, ".tif")==0) || (strcmp(FileExtension, ".tiff")==0))
+ m_pszContentType="image/tiff";
+ else
+ m_pszContentType="application/octet-stream";
+
+ mir_free(FileExtension);
+ return;
+}
+
+void CSendImageShack::AppendToData(const char *pszVal) {
+ if (!m_nlhr.pData) {
+ m_nlhr.pData = mir_strdup(pszVal);
+ m_nlhr.dataLength = (int)strlen(pszVal);
+ }
+ else {
+ size_t lenVal = strlen(pszVal);
+ size_t sizeNew = sizeof(char)*(m_nlhr.dataLength + lenVal + 1);
+ m_nlhr.pData = (char*) mir_realloc(m_nlhr.pData, sizeNew);
+
+ strcpy(m_nlhr.pData + sizeof(char)*m_nlhr.dataLength, pszVal);
+ m_nlhr.pData[sizeNew-1] = 0;
+ m_nlhr.dataLength = (int)sizeNew -1;
+ }
+}
+
+//---------------------------------------------------------------------------
+const char * CSendImageShack::GetTagContent(char * pszSource, const char * pszTagStart, const char * pszTagEnd) {
+ char * b = strstr(pszSource, pszTagStart);
+ if (!b) return NULL;
+ b += strlen(pszTagStart);
+ char * e = strstr(b, pszTagEnd);
+ if (e) *e = 0;
+ return b;
+}
+
diff --git a/plugins/SendScreenshotPlus/CSendImageShack.h b/plugins/SendScreenshotPlus/CSendImageShack.h
new file mode 100644
index 0000000000..eae406aca9
--- /dev/null
+++ b/plugins/SendScreenshotPlus/CSendImageShack.h
@@ -0,0 +1,77 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/CSendImageShack.h $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _CSEND_IMAGESHACK_H
+#define _CSEND_IMAGESHACK_H
+
+//---------------------------------------------------------------------------
+#include "global.h"
+#include "Utils.h"
+#include "CSend.h"
+
+//---------------------------------------------------------------------------
+class CSendImageShack : public CSend {
+ public:
+ // Deklaration Standardkonstruktor/Standarddestructor
+ CSendImageShack(HWND Owner, HANDLE hContact, bool bFreeOnExit);
+ ~CSendImageShack();
+
+ void Send();
+ void SendSync(bool Sync) {m_SendSync = Sync;};
+ LPSTR GetURL(){return m_Url;};
+ LPSTR GetError(){return mir_t2a(m_ErrorMsg);};
+
+ protected:
+ LPSTR m_pszFileName;
+ NETLIBHTTPREQUEST m_nlhr;
+ NETLIBHTTPREQUEST* m_nlreply;
+ NETLIBHTTPHEADER* m_nlheader;
+ char m_nlheader_ContentType[64];
+ LPSTR m_Url;
+
+ void AppendToData(const char *pszVal); //append to netlib DATA
+ LPSTR m_pszContentType; //hold mimeType (does not need free)
+ void GetContentType(); //get mimeType
+ const char * GetTagContent(char * pszSource, const char * pszTagStart, const char * pszTagEnd);
+
+ char* m_MFDRboundary;
+ void MFDR_Reset();
+
+ bool m_SendSync;
+ void SendThread();
+ static void SendThreadWrapper(void * Obj);
+
+};
+
+//---------------------------------------------------------------------------
+
+#endif
diff --git a/plugins/SendScreenshotPlus/Main.cpp b/plugins/SendScreenshotPlus/Main.cpp
new file mode 100644
index 0000000000..f2a355a524
--- /dev/null
+++ b/plugins/SendScreenshotPlus/Main.cpp
@@ -0,0 +1,406 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/Main.cpp $
+Revision : $Revision: 22 $
+Last change on : $Date: 2010-05-02 21:25:02 +0400 (Вс, 02 май 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+//---------------------------------------------------------------------------
+#include "main.h"
+
+// Prototypes ///////////////////////////////////////////////////////////////////////////
+MM_INTERFACE mmi;
+UTF8_INTERFACE utfi;
+//LIST_INTERFACE li;
+FI_INTERFACE *FIP = 0;
+HINSTANCE hInst; //!< Global reference to the application
+MGLOBAL myGlobals;
+
+
+PLUGINLINK *pluginLink; //!< Link between Miranda and this plugin
+//Information gathered by Miranda, displayed in the plugin pane of the Option Dialog
+PLUGININFOEX pluginInfo={
+ sizeof(PLUGININFOEX),
+ __PLUGIN_NAME, // altered here and on file listing, so as not to match original
+ PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM),
+ __DESC,
+ __AUTHOR,
+ __AUTHOREMAIL,
+ __COPYRIGHT,
+ __AUTHORWEB,
+ UNICODE_AWARE,
+ 0, //doesn't replace anything built-in
+ MIID_PLUGIN
+};
+
+//static char szSendSS[]=SZ_SENDSS;
+
+HANDLE hsvc_SendScreenshot=0;
+HANDLE hsvc_SendDesktop=0;
+HANDLE hsvc_EditBitmap=0;
+HANDLE hsvc_Send2ImageShack=0;
+
+HANDLE hNetlibUser = 0; //!< Netlib Register User
+HANDLE hFolderScreenshot=0;
+
+HANDLE hhook_ModulesLoad=0;
+HANDLE hhook_SystemPShutdown=0;
+
+
+// Functions ////////////////////////////////////////////////////////////////////////////
+
+/*---------------------------------------------------------------------------
+* DLL entry point - Required to store the instance handle
+*/
+extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
+ hInst = hinstDLL;
+ // Freeing some unneeded resources
+ DisableThreadLibraryCalls(GetModuleHandle(_T("sendss.dll")));
+
+ return TRUE;
+}
+
+/*---------------------------------------------------------------------------
+* Called by Miranda to get the information associated to this plugin.
+* It only returns the PLUGININFO structure, without any test on the version
+* @param mirandaVersion The version of the application calling this function
+*/
+extern "C" __declspec(dllexport) PLUGININFO* MirandaPluginInfo(DWORD mirandaVersion) {
+ pluginInfo.cbSize = sizeof(PLUGININFO);
+ return (PLUGININFO*) &pluginInfo;
+}
+
+extern "C" __declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion) {
+ pluginInfo.cbSize = sizeof(PLUGININFOEX);
+ myGlobals.mirandaVersion = mirandaVersion;
+ return &pluginInfo;
+}
+
+static const MUUID interfaces[] = { MIID_PLUGIN, MIID_LAST };
+extern "C" __declspec(dllexport) const MUUID* MirandaPluginInterfaces(void) {
+ return interfaces;
+}
+
+/*---------------------------------------------------------------------------
+* Initializes the services provided and the link to those needed
+* Called when the plugin is loaded into Miranda
+*/
+extern "C" int __declspec(dllexport) Load(PLUGINLINK *link) {
+ pluginLink = link;
+ INT_PTR result = CALLSERVICE_NOTFOUND;
+
+ if(ServiceExists(MS_IMG_GETINTERFACE))
+ result = CallService(MS_IMG_GETINTERFACE, FI_IF_VERSION, (LPARAM)&FIP);
+
+ if(FIP == NULL || result != S_OK) {
+ MessageBoxEx(NULL, TranslateT("Fatal error, image services not found. Send Screenshot will be disabled."), _T("Error"), MB_OK | MB_ICONERROR | MB_APPLMODAL, 0);
+ return 1;
+ }
+
+ mmi.cbSize = sizeof(mmi);
+ mir_getMMI(&mmi);
+ utfi.cbSize = sizeof(utfi);
+ mir_getUTFI(&utfi);
+
+ // load icon library (use UserInfoEx icon Pack)
+ IcoLib_LoadModule();
+
+ hhook_ModulesLoad = HookEvent(ME_SYSTEM_MODULESLOADED, hook_ModulesLoaded);
+ //hhook_options_init = HookEvent(ME_OPT_INITIALISE, hook_options_init);
+ //hhook_OkToExit = HookEvent(ME_SYSTEM_OKTOEXIT, hook_OkToExit);
+ hhook_SystemPShutdown = HookEvent(ME_SYSTEM_PRESHUTDOWN, hook_SystemPShutdown);
+
+ AddMenuItems();
+ RegisterServices();
+
+ return 0;
+}
+
+int hook_ModulesLoaded(WPARAM, LPARAM) {
+
+ myGlobals.PopUpExist = ServiceExists(MS_POPUP_ADDPOPUP);
+ myGlobals.PopUpActionsExist = ServiceExists(MS_POPUP_REGISTERACTIONS);
+ myGlobals.PluginHTTPExist = ServiceExists(MS_HTTP_ACCEPT_CONNECTIONS);
+ myGlobals.PluginFTPExist = ServiceExists(MS_FTPFILE_SHAREFILE);
+// myGlobals.PluginUserinfoEx = ServiceExists(MS_USERINFO_VCARD_EXPORT);
+
+ // Netlib register
+ if (!NetlibInit()){
+ ;
+ }
+
+ // load my button class
+ if(!ServiceExists("UserInfo/vCard/Export")) {
+ CtrlButtonLoadModule();
+ }
+
+ // Folders plugin support
+ if (ServiceExists(MS_FOLDERS_REGISTER_PATH)) {
+ hFolderScreenshot = (HANDLE) FoldersRegisterCustomPathT("SendSS", "Screenshots",
+ _T(PROFILE_PATH)_T("\\")_T(CURRENT_PROFILE)_T("\\Screenshots"));
+ }
+ // updater plugin support
+ if(ServiceExists(MS_UPDATE_REGISTER)) {
+ Update update = {0};
+ char szVersion[16];
+ update.cbSize = sizeof(Update);
+ update.szComponentName = pluginInfo.shortName;
+ update.pbVersion = (BYTE *)CreateVersionStringPluginEx(&pluginInfo, szVersion);
+ update.cpbVersion = (int)strlen((char *)update.pbVersion);
+
+ update.szVersionURL = __FLVersionURL;
+ update.pbVersionPrefix = (BYTE *)__FLVersionPrefix;
+ update.cpbVersionPrefix = (int)strlen((char *)update.pbVersionPrefix);
+ update.szUpdateURL = __FLUpdateURL;
+ // update.szUpdateURL = UPDATER_AUTOREGISTER;
+
+ update.szBetaVersionURL = __BetaVersionURL;
+ // bytes occuring in VersionURL before the version, used to locate the version information within the URL data
+ update.pbBetaVersionPrefix = (BYTE *)__BetaVersionPrefix;
+ update.cpbBetaVersionPrefix = (int)strlen((char *)update.pbBetaVersionPrefix);
+ update.szBetaUpdateURL = __BetaUpdateURL;
+
+ // url for displaying changelog for beta versions
+ update.szBetaChangelogURL = __BetaChangelogURL;
+
+ CallService(MS_UPDATE_REGISTER, 0, (WPARAM)&update);
+ }
+
+ return 0;
+}
+
+/*---------------------------------------------------------------------------
+* Prepare the plugin to stop
+* Called by Miranda when it will exit or when the plugin gets deselected
+*/
+extern "C" int __declspec(dllexport) Unload(void) {
+ UnhookEvent(hhook_SystemPShutdown);
+
+ DestroyServiceFunction(MS_SENDSS_OPENDIALOG);
+ DestroyServiceFunction(MS_SENDSS_EDITBITMAP);
+ DestroyServiceFunction(MS_SENDSS_SENDDESKTOP);
+ DestroyServiceFunction(MS_SENDSS_SEND2IMAGESHACK);
+ return 0;
+}
+
+int hook_SystemPShutdown(WPARAM wParam, LPARAM lParam) {
+ UnhookEvent(hhook_ModulesLoad);
+
+ // Netlib unregister
+ NetlibClose();
+
+ // uninitialize classes
+ CtrlButtonUnloadModule();
+
+ return 0;
+}
+
+//---------------------------------------------------------------------------
+// Netlib
+HANDLE NetlibInit(void) {
+ NETLIBUSER nlu = {0};
+ nlu.cbSize = sizeof(nlu);
+ nlu.szSettingsModule = (char*)PLUGNAME;
+ nlu.szDescriptiveName = Translate("SendSS HTTP connections");
+ nlu.flags = NUF_OUTGOING|NUF_HTTPCONNS; //|NUF_NOHTTPSOPTION;
+ hNetlibUser = (HANDLE)CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM)&nlu);
+ return hNetlibUser;
+}
+
+void NetlibClose(void) {
+ Netlib_CloseHandle(hNetlibUser);
+}
+
+
+//---------------------------------------------------------------------------
+// Callback function of service
+// 1. Send a screenshot of the desktop to the selected contact
+// wParam = contact handle
+// lParam = 0
+// 2. Open the capture dialog in take screenshot only mode (it will not be sent)
+// wParam = 0
+// lParam = anything but 0
+INT_PTR service_CaptureAndSendDesktop(WPARAM wParam, LPARAM lParam) {
+ LPTSTR pszPath = NULL;
+ LPSTR pszProto = NULL;
+ bool bChatRoom;
+
+ TfrmMain *frmMain=new TfrmMain();
+ if (!frmMain) {
+ MessageBoxEx(NULL, TranslateT("Could not create main dialog."), TranslateT("Error"), MB_OK | MB_ICONERROR | MB_APPLMODAL, 0);
+ return -1;
+ }
+ pszPath = GetCustomPath();
+
+ pszProto = (LPSTR)CallService(MS_PROTO_GETCONTACTBASEPROTO,wParam,0);
+ bChatRoom = DBGetContactSettingByte((HANDLE)wParam, pszProto, "ChatRoom", 0) != 0;
+ frmMain->m_opt_chkTimed = false;
+ frmMain->m_opt_tabCapture = 1;
+ frmMain->m_opt_cboxDesktop = 0;
+ frmMain->m_opt_chkEditor = false;
+ frmMain->m_opt_cboxSendBy = bChatRoom ? SS_IMAGESHACK:SS_FILESEND;
+ frmMain->Init(pszPath, (HANDLE)wParam); // this method create the window hidden.
+ frmMain->btnCaptureClick(); // this method will call Close()
+ mir_free(pszPath);
+ return 0;
+}
+
+//---------------------------------------------------------------------------
+// Callback function of service for contact menu and main menu
+// wParam = contact handle
+// lParam = 0
+INT_PTR service_OpenCaptureDialog(WPARAM wParam, LPARAM lParam) {
+ LPTSTR pszPath = NULL;
+
+ TfrmMain *frmMain=new TfrmMain();
+ if (!frmMain) {
+ MessageBoxEx(NULL, TranslateT("Could not create main dialog."), TranslateT("Error"), MB_OK | MB_ICONERROR | MB_APPLMODAL, 0);
+ return -1;
+ }
+
+ pszPath = GetCustomPath();
+ frmMain->Init(pszPath, (HANDLE)wParam);
+ mir_free(pszPath);
+ frmMain->Show();
+ return 0;
+}
+
+//---------------------------------------------------------------------------
+// Edit a in-memory bitmap on the edit window
+// wParam = (SENDSSCB) callback function address to call when editing is done
+// lParam = (HBITMAP) bitmap handle, a copy is made so the calling function can free this handle after the service function returns
+// Returns:
+INT_PTR service_EditBitmap(WPARAM wParam, LPARAM lParam) {
+/* TfrmEdit *frmEdit=new TfrmEdit(NULL);
+ if (!frmEdit)
+ return -1;
+
+ Graphics::TBitmap *bitmap=new Graphics::TBitmap();
+ if (!bitmap)
+ return -2;
+
+ bitmap->Handle = (void*)lParam;
+ frmEdit->InitEditor(bitmap); // a copy of the bitmap is made inside this function
+ frmEdit->Show();
+ delete bitmap;
+*/
+ return 0;
+}
+
+//---------------------------------------------------------------------------
+// Callback function of service for sending image to imageshack.us
+// wParam = (char*)filename
+// lParam = (HANDLE)contact (can be null)
+INT_PTR service_Send2ImageShack(WPARAM wParam, LPARAM lParam) {
+ LPSTR result = NULL;
+ CSendImageShack* cSend = new CSendImageShack(NULL, (HANDLE)lParam, false);
+ cSend->m_pszFile = mir_a2t((char*)wParam);
+ cSend->m_bDeleteAfterSend = FALSE;
+ if (lParam != NULL) {
+ cSend->Send();
+ return 0;
+ }
+ cSend->SendSync(TRUE);
+ cSend->Send();
+ if (cSend->GetURL()) {
+ result = mir_strdup(cSend->GetURL());
+ }
+ else {
+ result = cSend->GetError();
+ }
+ delete cSend;
+ return (INT_PTR)result;
+}
+
+//---------------------------------------------------------------------------
+// Add SendSS menu item in contact menu
+void AddMenuItems(void) {
+ CLISTMENUITEM mi={0};
+
+ // Common
+ mi.cbSize = sizeof(mi);
+ // support new genmenu style
+ mi.flags = CMIF_ROOTHANDLE|CMIF_UNICODE;
+ mi.hParentMenu = HGENMENU_ROOT;
+
+ // Add item to contact menu
+ mi.position = 1000000;
+ mi.ptszName = LPGENT("Send Screenshot");
+ mi.hIcon = IcoLib_GetIcon(ICO_PLUG_SSWINDOW2);
+ mi.pszService = MS_SENDSS_OPENDIALOG;
+ CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&mi);
+
+ // Add item to contact menu
+ mi.position = 1000001;
+ mi.ptszName = LPGENT("Send desktop screenshot");
+ mi.hIcon = IcoLib_GetIcon(ICO_PLUG_SSWINDOW2);
+ mi.pszService = MS_SENDSS_SENDDESKTOP;
+ CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&mi);
+
+ // Add item to main menu
+ mi.position = 1000001;
+ mi.ptszName = LPGENT("Take a screenshot");
+ mi.hIcon = IcoLib_GetIcon(ICO_PLUG_SSWINDOW2);
+ mi.pszService = MS_SENDSS_OPENDIALOG;
+ CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM)&mi);
+}
+
+//---------------------------------------------------------------------------
+// Register Send screenshot services
+int RegisterServices(void) {
+ hsvc_SendScreenshot = CreateServiceFunction(MS_SENDSS_OPENDIALOG, service_OpenCaptureDialog);
+ if (!hsvc_SendScreenshot)
+ MessageBoxEx(NULL, TranslateT("Could not register miranda service."), _T("MS_SENDSS_OPENDIALOG"), MB_OK | MB_ICONERROR | MB_APPLMODAL, 0);
+
+ hsvc_SendDesktop = CreateServiceFunction(MS_SENDSS_SENDDESKTOP, service_CaptureAndSendDesktop);
+ if (!hsvc_SendDesktop)
+ MessageBoxEx(NULL, TranslateT("Could not register miranda service."), _T("MS_SENDSS_SENDDESKTOP"), MB_OK | MB_ICONERROR | MB_APPLMODAL, 0);
+
+ hsvc_EditBitmap = CreateServiceFunction(MS_SENDSS_EDITBITMAP, service_EditBitmap);
+ if (!hsvc_EditBitmap)
+ MessageBoxEx(NULL, TranslateT("Could not register miranda service."), _T("MS_SENDSS_EDITBITMAP"), MB_OK | MB_ICONERROR | MB_APPLMODAL, 0);
+
+ hsvc_Send2ImageShack = CreateServiceFunction(MS_SENDSS_SEND2IMAGESHACK, service_Send2ImageShack);
+ if (!hsvc_Send2ImageShack)
+ MessageBoxEx(NULL, TranslateT("Could not register miranda service."), _T("MS_SENDSS_SEND2IMAGESHACK"), MB_OK | MB_ICONERROR | MB_APPLMODAL, 0);
+
+ return 0;
+}
+
+//---------------------------------------------------------------------------
+LPTSTR GetCustomPath() {
+ LPTSTR pszPath = NULL;
+ pszPath = Utils_ReplaceVarsT(_T("%miranda_userdata%\\Screenshots"));
+ if (hFolderScreenshot) {
+ TCHAR szPath[1024] = {'\0'};
+ FoldersGetCustomPathT(hFolderScreenshot, szPath, 1024, pszPath);
+ mir_freeAndNil(pszPath);
+ pszPath = mir_tstrdup(szPath);
+ }
+ return pszPath;
+}
diff --git a/plugins/SendScreenshotPlus/Main.h b/plugins/SendScreenshotPlus/Main.h
new file mode 100644
index 0000000000..67059fb73c
--- /dev/null
+++ b/plugins/SendScreenshotPlus/Main.h
@@ -0,0 +1,65 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/Main.h $
+Revision : $Revision: 22 $
+Last change on : $Date: 2010-05-02 21:25:02 +0400 (Вс, 02 май 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef MainH
+#define MainH
+
+//---------------------------------------------------------------------------
+#include "global.h"
+#include "UMainForm.h"
+//#include "UEditForm.h"
+
+extern HANDLE hNetlibUser;
+
+//---------------------------------------------------------------------------
+
+HANDLE NetlibInit(void);
+void NetlibClose(void);
+
+void IcoLib_LoadModule(void);
+void AddMenuItems(void);
+int RegisterServices(void);
+
+int hook_ModulesLoaded(WPARAM, LPARAM);
+int hook_SystemPShutdown(WPARAM wParam, LPARAM lParam);
+
+INT_PTR service_CaptureAndSendDesktop(WPARAM wParam, LPARAM lParam);
+INT_PTR service_OpenCaptureDialog(WPARAM wParam, LPARAM lParam);
+INT_PTR service_EditBitmap(WPARAM wParam, LPARAM lParam);
+INT_PTR service_Send2ImageShack(WPARAM wParam, LPARAM lParam);
+
+int OnSendScreenShot(WPARAM wParam, LPARAM lParam);
+
+LPTSTR GetCustomPath();
+
+//---------------------------------------------------------------------------
+#endif
diff --git a/plugins/SendScreenshotPlus/SendSS_9.vcproj b/plugins/SendScreenshotPlus/SendSS_9.vcproj
new file mode 100644
index 0000000000..25fc100659
--- /dev/null
+++ b/plugins/SendScreenshotPlus/SendSS_9.vcproj
@@ -0,0 +1,621 @@
+<?xml version="1.0" encoding="Windows-1252"?>
+<VisualStudioProject
+ ProjectType="Visual C++"
+ Version="9,00"
+ Name="SendSS_Plus"
+ ProjectGUID="{CEAD8BCF-1F22-4E00-9F6D-E33405B00552}"
+ RootNamespace="SendSS"
+ Keyword="ManagedCProj"
+ TargetFrameworkVersion="196613"
+ >
+ <Platforms>
+ <Platform
+ Name="Win32"
+ />
+ </Platforms>
+ <ToolFiles>
+ </ToolFiles>
+ <Configurations>
+ <Configuration
+ Name="Debug|Win32"
+ OutputDirectory="$(SolutionDir)$(ConfigurationName)/Plugins"
+ IntermediateDirectory="$(SolutionDir)$(ConfigurationName)/Obj/$(ProjectName)"
+ ConfigurationType="2"
+ CharacterSet="2"
+ ManagedExtensions="0"
+ DeleteExtensionsOnClean="*.obj;*.ilk;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pch;*.pgc;*.pgd;*.meta;$(TargetPath);$(TargetDir)$(ProjectName).*;$(TargetDir)$(RootNamespace).*"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="../../include;../../include_API;./sdk"
+ PreprocessorDefinitions="WIN32;_DEBUG;_USRDLL"
+ RuntimeLibrary="3"
+ WarningLevel="3"
+ DebugInformationFormat="3"
+ DisableSpecificWarnings="4996"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="gdiplus.lib msimg32.lib shlwapi.lib comctl32.lib"
+ OutputFile="$(OutDir)\$(RootNamespace).dll"
+ LinkIncremental="1"
+ GenerateDebugInformation="true"
+ ProgramDatabaseFile="$(OutDir)\$(RootNamespace).pdb"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ ImportLibrary="$(IntDir)/$(TargetName).lib"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release|Win32"
+ OutputDirectory="$(SolutionDir)$(ConfigurationName)/Plugins"
+ IntermediateDirectory="$(SolutionDir)$(ConfigurationName)/Obj/$(ProjectName)"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ CharacterSet="2"
+ ManagedExtensions="0"
+ DeleteExtensionsOnClean="*.obj;*.ilk;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pch;*.pgc;*.pgd;*.meta;$(TargetPath);$(TargetDir)$(ProjectName).*;$(TargetDir)$(RootNamespace).*"
+ WholeProgramOptimization="1"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories="../../include;../../include_API;./sdk"
+ PreprocessorDefinitions="WIN32;NDEBUG;_USRDLL"
+ RuntimeLibrary="2"
+ WarningLevel="3"
+ DebugInformationFormat="3"
+ DisableSpecificWarnings="4996"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="gdiplus.lib msimg32.lib shlwapi.lib comctl32.lib"
+ OutputFile="$(OutDir)\$(RootNamespace).dll"
+ LinkIncremental="1"
+ GenerateDebugInformation="true"
+ ProgramDatabaseFile="$(OutDir)\$(RootNamespace).pdb"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ ImportLibrary="$(IntDir)/$(TargetName).lib"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Release Unicode|Win32"
+ OutputDirectory="$(SolutionDir)$(ConfigurationName)/Plugins"
+ IntermediateDirectory="$(SolutionDir)$(ConfigurationName)/Obj/$(ProjectName)"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ CharacterSet="1"
+ ManagedExtensions="0"
+ DeleteExtensionsOnClean="*.obj;*.ilk;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pch;*.pgc;*.pgd;*.meta;$(TargetPath);$(TargetDir)$(ProjectName).*;$(TargetDir)$(RootNamespace).*"
+ WholeProgramOptimization="1"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ AdditionalIncludeDirectories="../../include;../../include_API;./sdk"
+ PreprocessorDefinitions="WIN32;NDEBUG;_USRDLL"
+ RuntimeLibrary="2"
+ WarningLevel="3"
+ DebugInformationFormat="3"
+ DisableSpecificWarnings="4996"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="gdiplus.lib msimg32.lib shlwapi.lib comctl32.lib"
+ OutputFile="$(OutDir)\$(RootNamespace).dll"
+ LinkIncremental="1"
+ GenerateDebugInformation="true"
+ ProgramDatabaseFile="$(OutDir)\$(RootNamespace).pdb"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ ImportLibrary="$(IntDir)/$(TargetName).lib"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ <Configuration
+ Name="Debug Unicode|Win32"
+ OutputDirectory="$(SolutionDir)$(ConfigurationName)/Plugins"
+ IntermediateDirectory="$(SolutionDir)$(ConfigurationName)/Obj/$(ProjectName)"
+ ConfigurationType="2"
+ UseOfMFC="0"
+ CharacterSet="1"
+ ManagedExtensions="0"
+ DeleteExtensionsOnClean="*.obj;*.ilk;*.tlb;*.tli;*.tlh;*.tmp;*.rsp;*.pch;*.pgc;*.pgd;*.meta;$(TargetPath);$(TargetDir)$(ProjectName).*;$(TargetDir)$(RootNamespace).*"
+ >
+ <Tool
+ Name="VCPreBuildEventTool"
+ />
+ <Tool
+ Name="VCCustomBuildTool"
+ />
+ <Tool
+ Name="VCXMLDataGeneratorTool"
+ />
+ <Tool
+ Name="VCWebServiceProxyGeneratorTool"
+ />
+ <Tool
+ Name="VCMIDLTool"
+ />
+ <Tool
+ Name="VCCLCompilerTool"
+ Optimization="0"
+ AdditionalIncludeDirectories="../../include;../../include_API;./sdk"
+ PreprocessorDefinitions="WIN32;_DEBUG;_USRDLL;_UNICODE;UNICODE"
+ RuntimeLibrary="3"
+ PrecompiledHeaderThrough="global.h"
+ WarningLevel="3"
+ DebugInformationFormat="3"
+ DisableSpecificWarnings="4996"
+ />
+ <Tool
+ Name="VCManagedResourceCompilerTool"
+ />
+ <Tool
+ Name="VCResourceCompilerTool"
+ />
+ <Tool
+ Name="VCPreLinkEventTool"
+ />
+ <Tool
+ Name="VCLinkerTool"
+ AdditionalDependencies="gdiplus.lib msimg32.lib shlwapi.lib comctl32.lib"
+ OutputFile="$(OutDir)\$(RootNamespace).dll"
+ LinkIncremental="1"
+ GenerateDebugInformation="true"
+ ProgramDatabaseFile="$(OutDir)\$(RootNamespace).pdb"
+ RandomizedBaseAddress="1"
+ DataExecutionPrevention="0"
+ ImportLibrary="$(IntDir)/$(TargetName).lib"
+ TargetMachine="1"
+ />
+ <Tool
+ Name="VCALinkTool"
+ />
+ <Tool
+ Name="VCManifestTool"
+ />
+ <Tool
+ Name="VCXDCMakeTool"
+ />
+ <Tool
+ Name="VCBscMakeTool"
+ />
+ <Tool
+ Name="VCFxCopTool"
+ />
+ <Tool
+ Name="VCAppVerifierTool"
+ />
+ <Tool
+ Name="VCPostBuildEventTool"
+ />
+ </Configuration>
+ </Configurations>
+ <References>
+ <AssemblyReference
+ RelativePath="System.dll"
+ AssemblyName="System, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"
+ MinFrameworkVersion="131072"
+ />
+ <AssemblyReference
+ RelativePath="System.Data.dll"
+ AssemblyName="System.Data, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86"
+ MinFrameworkVersion="131072"
+ />
+ <AssemblyReference
+ RelativePath="System.Drawing.dll"
+ AssemblyName="System.Drawing, Version=2.0.0.0, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
+ MinFrameworkVersion="131072"
+ />
+ <AssemblyReference
+ RelativePath="System.Windows.Forms.dll"
+ AssemblyName="System.Windows.Forms, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"
+ MinFrameworkVersion="131072"
+ />
+ <AssemblyReference
+ RelativePath="System.XML.dll"
+ AssemblyName="System.Xml, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"
+ MinFrameworkVersion="131072"
+ />
+ </References>
+ <Files>
+ <Filter
+ Name="Class Form"
+ Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+ UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+ >
+ <File
+ RelativePath=".\UAboutForm.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\UAboutForm.h"
+ >
+ </File>
+ <File
+ RelativePath=".\UMainForm.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\UMainForm.h"
+ >
+ </File>
+ </Filter>
+ <Filter
+ Name="Helper"
+ Filter="h;hpp;hxx;hm;inl;inc;xsd"
+ UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+ >
+ <File
+ RelativePath=".\ctrl_button.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\ctrl_button.h"
+ >
+ </File>
+ <File
+ RelativePath=".\dlg_msgbox.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\dlg_msgbox.h"
+ >
+ </File>
+ <File
+ RelativePath=".\mir_icolib.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\mir_icolib.h"
+ >
+ </File>
+ <File
+ RelativePath=".\mir_string.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\mir_string.h"
+ >
+ </File>
+ <File
+ RelativePath=".\Utils.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\Utils.h"
+ >
+ </File>
+ </Filter>
+ <Filter
+ Name="Resource Files"
+ Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
+ UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"
+ >
+ <File
+ RelativePath=".\res\009_avatar.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\credits.txt"
+ >
+ </File>
+ <File
+ RelativePath=".\res\default.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\icon1.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\license.txt"
+ >
+ </File>
+ <File
+ RelativePath=".\res\overlay_disabled.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\overlay_enabled.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\resource.h"
+ >
+ </File>
+ <File
+ RelativePath=".\resource.rc"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssArrow_Left.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssArrow_Right.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssCamera.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssCamera_1.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssCamera_2.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssDefault.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssDelOff.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssDelOn.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssDeskOff.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssDeskOn.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\sshelp.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssMonitor.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssOpen.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\ssTarget.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\treePhoto.ico"
+ >
+ </File>
+ <File
+ RelativePath=".\res\UEditForm_nvr_1.bmp"
+ >
+ </File>
+ <File
+ RelativePath=".\res\UEditForm_nvr_2.bmp"
+ >
+ </File>
+ <File
+ RelativePath=".\version.rc"
+ >
+ </File>
+ </Filter>
+ <Filter
+ Name="Class Send"
+ >
+ <File
+ RelativePath=".\CSend.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\CSend.h"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendEmail.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendEmail.h"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendFile.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendFile.h"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendFTPFile.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendFTPFile.h"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendHTTPServer.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendHTTPServer.h"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendImageShack.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\CSendImageShack.h"
+ >
+ </File>
+ </Filter>
+ <File
+ RelativePath=".\global.h"
+ >
+ </File>
+ <File
+ RelativePath=".\sdk\m_sendss.h"
+ >
+ </File>
+ <File
+ RelativePath=".\Main.cpp"
+ >
+ </File>
+ <File
+ RelativePath=".\Main.h"
+ >
+ </File>
+ <File
+ RelativePath=".\version.h"
+ >
+ </File>
+ </Files>
+ <Globals>
+ <Global
+ Name="RESOURCE_FILE"
+ Value="resource.rc"
+ />
+ </Globals>
+</VisualStudioProject>
diff --git a/plugins/SendScreenshotPlus/UAboutForm.cpp b/plugins/SendScreenshotPlus/UAboutForm.cpp
new file mode 100644
index 0000000000..f4ea2b6bc2
--- /dev/null
+++ b/plugins/SendScreenshotPlus/UAboutForm.cpp
@@ -0,0 +1,212 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/UAboutForm.cpp $
+Revision : $Revision: 22 $
+Last change on : $Date: 2010-05-02 21:25:02 +0400 (Вс, 02 май 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#include "UAboutForm.h"
+
+//---------------------------------------------------------------------------
+TfrmAbout::CHandleMapping TfrmAbout::_HandleMapping;
+
+LRESULT CALLBACK TfrmAbout::DlgTfrmAbout(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ if (msg == WM_CTLCOLOREDIT || msg == WM_CTLCOLORSTATIC) {
+ switch ( GetWindowLongPtr(( HWND )lParam, GWL_ID )) {
+ case IDC_WHITERECT:
+ case IDC_BUILDTIME:
+ case IDC_CREDIT:
+ case IDC_LICENSE:
+ SetTextColor((HDC)wParam,GetSysColor(COLOR_WINDOWTEXT));
+ break;
+ default:
+ return FALSE;
+ }
+ SetBkColor((HDC)wParam, GetSysColor(COLOR_WINDOW));
+ return (LRESULT)GetStockObject(WHITE_BRUSH); //GetSysColorBrush(COLOR_WINDOW);
+ }
+
+ CHandleMapping::iterator wnd(_HandleMapping.end());
+ if (msg == WM_INITDIALOG) {
+ wnd = _HandleMapping.insert(CHandleMapping::value_type(hWnd, reinterpret_cast<TfrmAbout*>(lParam))).first;
+ reinterpret_cast<TfrmAbout*>(lParam)->m_hWnd = hWnd;
+ return wnd->second->wmInitdialog(wParam, lParam);
+ }
+ else {
+ wnd = _HandleMapping.find(hWnd);
+ }
+ if (wnd == _HandleMapping.end()) { // something screwed up
+ return FALSE; //dialog! do not use ::DefWindowProc(hWnd, msg, wParam, lParam);
+ }
+
+ switch (msg)
+ {
+ // case WM_INITDIALOG: done on top
+ case WM_COMMAND:
+ return wnd->second->wmCommand(wParam, lParam);
+ break;
+ case WM_CLOSE:
+ return wnd->second->wmClose(wParam, lParam);
+ break;
+ case WM_DESTROY:
+ delete wnd->second;
+ break;
+ }
+ return FALSE;
+}
+
+//---------------------------------------------------------------------------
+//WM_INITDIALOG:
+LRESULT TfrmAbout::wmInitdialog(WPARAM wParam, LPARAM lParam) {
+ char* pszMsg = NULL;
+ HRSRC hResInfo;
+ DWORD ResSize;
+ TCHAR oldTitle[256], newTitle[256];
+ LPTSTR temp = NULL;
+ LPTSTR pszTitle = NULL;
+ // Headerbar
+ LPTSTR pszPlug = mir_a2t(__PLUGIN_NAME);
+ LPTSTR pszVer = mir_a2t(__VERSION_STRING_DOT);
+ GetDlgItemText( m_hWnd, IDC_HEADERBAR, oldTitle, SIZEOF( oldTitle ));
+ mir_sntprintf( newTitle, SIZEOF(newTitle), oldTitle, pszPlug, pszVer );
+ mir_freeAndNil(pszPlug);
+ mir_freeAndNil(pszVer);
+ SetDlgItemText( m_hWnd, IDC_HEADERBAR, newTitle );
+ SendMessage(GetDlgItem(m_hWnd, IDC_HEADERBAR), WM_SETICON, 0, (WPARAM)IcoLib_GetIcon(ICO_PLUG_SSWINDOW1, true));
+
+ //Buildtime
+ mir_sntprintf(newTitle,SIZEOF(newTitle),TranslateT("Built %s %s"),_T(__DATE__),_T(__TIME__));
+ SetDlgItemText(m_hWnd,IDC_BUILDTIME,newTitle);
+
+ //License
+ { mir_tcsadd(pszTitle ,_T(__COPYRIGHT));
+ mir_tcsadd(pszTitle ,_T("\r\n\r\n"));
+
+ hResInfo = FindResource(hInst,MAKEINTRESOURCE(IDR_LICENSE),_T("TEXT"));
+ ResSize = SizeofResource(hInst,hResInfo);
+ pszMsg = (char*)LockResource(LoadResource(hInst,hResInfo));
+ temp = mir_a2t(pszMsg);
+ temp [ResSize] = 0; //LockResource is not NULL terminatet !!
+ mir_tcsadd(pszTitle ,temp);
+ mir_freeAndNil(temp);
+ SetDlgItemText(m_hWnd,IDC_LICENSE, pszTitle);
+ mir_freeAndNil(pszTitle);
+ }
+
+ //Credit
+ {
+ hResInfo = FindResource(hInst,MAKEINTRESOURCE(IDR_CREDIT),_T("TEXT"));
+ ResSize = SizeofResource(hInst,hResInfo);
+ pszMsg = (char*)LockResource(LoadResource(hInst,hResInfo));
+ temp = mir_a2t(pszMsg);
+ temp [ResSize] = 0; //LockResource is not NULL terminatet !!
+ mir_tcsadd(pszTitle ,temp);
+ mir_freeAndNil(temp);
+ SetDlgItemText(m_hWnd,IDC_CREDIT, pszTitle);
+ mir_freeAndNil(pszTitle);
+ }
+
+ SendMessage(m_hWnd, WM_SETICON, ICON_BIG, (LPARAM)IcoLib_GetIcon(ICO_PLUG_SSWINDOW1, true));
+ SendMessage(m_hWnd, WM_SETICON, ICON_SMALL, (LPARAM)IcoLib_GetIcon(ICO_PLUG_SSWINDOW2));
+
+ //init controls
+ btnPageClick();
+ SendMessage(GetDlgItem(m_hWnd, IDA_CONTRIBLINK), BUTTONSETDEFAULT, (WPARAM)1, NULL);
+
+ TranslateDialogDefault(m_hWnd);
+ return FALSE;
+}
+
+//WM_COMMAND:
+LRESULT TfrmAbout::wmCommand(WPARAM wParam, LPARAM lParam) {
+ //---------------------------------------------------------------------------
+ if (HIWORD(wParam) == BN_CLICKED) {
+ int IDControl = LOWORD(wParam);
+ HWND hCtrl = (HWND)lParam;
+ switch(IDControl) {
+ case IDCANCEL:
+ case IDCLOSE:
+ break;
+ case IDA_btnClose:
+ Close();
+ break;
+ case IDA_CONTRIBLINK:
+ m_Page = m_Page ? 0 : 1;
+ btnPageClick();
+ break;
+ default:
+ break;
+ }
+ }
+ return FALSE;
+}
+
+//WM_CLOSE:
+LRESULT TfrmAbout::wmClose(WPARAM wParam, LPARAM lParam) {
+ SendMessage(m_hWndOwner,UM_CLOSING, (WPARAM)m_hWnd, (LPARAM)IDD_UAboutForm);
+ DestroyWindow(m_hWnd);
+ return FALSE;
+}
+
+//---------------------------------------------------------------------------
+// Standard konstruktor/destruktor
+TfrmAbout::TfrmAbout(HWND Owner) {
+ m_hWndOwner = Owner;
+ // create window
+ m_hWnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_UAboutForm),0, (DLGPROC)DlgTfrmAbout,(LPARAM)this);
+ //register object
+ _HandleMapping.insert(CHandleMapping::value_type(m_hWnd, this));
+ //init page
+ m_Page = 1;
+}
+
+TfrmAbout::~TfrmAbout() {
+ _HandleMapping.erase(m_hWnd);
+}
+
+//---------------------------------------------------------------------------
+void TfrmAbout::btnPageClick() {
+ HWND hCtrl = GetDlgItem(m_hWnd, IDA_CONTRIBLINK);
+ if(!m_Page) {
+ ShowWindow(GetDlgItem(m_hWnd, IDC_CREDIT), SW_HIDE);
+ ShowWindow(GetDlgItem(m_hWnd, IDC_LICENSE), SW_SHOW);
+ SendDlgItemMessage(m_hWnd, IDA_CONTRIBLINK, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Credits >"), MBF_TCHAR);
+ HICON hIcon = IcoLib_GetIcon(ICO_PLUG_ARROWR);
+ SendMessage(hCtrl, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ SetWindowText(hCtrl, hIcon ? TranslateT("Credits") : TranslateT("Credits >"));
+ }
+ else {
+ ShowWindow(GetDlgItem(m_hWnd, IDC_CREDIT), SW_SHOW);
+ ShowWindow(GetDlgItem(m_hWnd, IDC_LICENSE), SW_HIDE);
+ SendDlgItemMessage(m_hWnd, IDA_CONTRIBLINK, BUTTONADDTOOLTIP, (WPARAM)TranslateT("< Copyright"), MBF_TCHAR);
+ HICON hIcon = IcoLib_GetIcon(ICO_PLUG_ARROWL);
+ SendMessage(hCtrl, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ SetWindowText(hCtrl, hIcon ? TranslateT("Copyright") : TranslateT("< Copyright"));
+ }
+}
diff --git a/plugins/SendScreenshotPlus/UAboutForm.h b/plugins/SendScreenshotPlus/UAboutForm.h
new file mode 100644
index 0000000000..d9d598aeb6
--- /dev/null
+++ b/plugins/SendScreenshotPlus/UAboutForm.h
@@ -0,0 +1,69 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/UAboutForm.h $
+Revision : $Revision: 19 $
+Last change on : $Date: 2010-04-09 03:24:04 +0400 (Пт, 09 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef UAboutFormH
+#define UAboutFormH
+//---------------------------------------------------------------------------
+#include "global.h"
+
+//---------------------------------------------------------------------------
+class TfrmAbout{
+
+ public:
+ // Deklaration Standardkonstruktor/Standarddestructor
+ TfrmAbout(HWND Owner);
+ ~TfrmAbout();
+
+ HWND m_hWndOwner;
+ void Show(){ShowWindow(m_hWnd,SW_SHOW);}
+ void Hide(){ShowWindow(m_hWnd,SW_HIDE);}
+ void Close(){SendMessage(m_hWnd,WM_CLOSE,0,0);}
+
+ private:
+ HWND m_hWnd;
+
+ protected:
+ UINT m_Page;
+ typedef std::map<HWND, TfrmAbout *> CHandleMapping;
+ static CHandleMapping _HandleMapping;
+ static LRESULT CALLBACK DlgTfrmAbout(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+
+ LRESULT wmInitdialog(WPARAM wParam, LPARAM lParam);
+ LRESULT wmCommand(WPARAM wParam, LPARAM lParam);
+ LRESULT wmClose(WPARAM wParam, LPARAM lParam);
+
+ void btnPageClick();
+
+};
+
+//---------------------------------------------------------------------------
+#endif
diff --git a/plugins/SendScreenshotPlus/UMainForm.cpp b/plugins/SendScreenshotPlus/UMainForm.cpp
new file mode 100644
index 0000000000..2061f80d83
--- /dev/null
+++ b/plugins/SendScreenshotPlus/UMainForm.cpp
@@ -0,0 +1,1180 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/UMainForm.cpp $
+Revision : $Revision: 22 $
+Last change on : $Date: 2010-05-02 21:25:02 +0400 (Вс, 02 май 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#include "UMainForm.h"
+#include "UAboutForm.h"
+//#include "UEditForm.h"
+
+//---------------------------------------------------------------------------
+INT_PTR CALLBACK TfrmMain::DlgProc_CaptureWindow(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
+// main message handling is done inside TfrmMain::DlgTfrmMain
+ switch (uMsg) {
+ case WM_INITDIALOG:
+ Static_SetIcon(GetDlgItem(hDlg, ID_imgTarget), IcoLib_GetIcon(ICO_PLUG_SSTARGET));
+ SetDlgItemText(hDlg, ID_edtCaption, _T("Drag&&Drop the target on the desired window."));
+ TranslateDialogDefault(hDlg);
+ break;
+ case WM_CTLCOLOREDIT: //ctrl is NOT read-only or disabled
+ case WM_CTLCOLORSTATIC: //ctrl is read-only or disabled
+ // make the rectangle on the top white
+ switch (GetWindowLongPtr((HWND)lParam, GWL_ID)) {
+ case IDC_WHITERECT:
+ case ID_chkClientArea:
+ case ID_lblDropInfo:
+ case ID_edtCaption:
+ case ID_edtCaptionLabel:
+ case ID_edtSize:
+ case ID_edtSizeLabel:
+ case ID_bvlTarget:
+ case ID_imgTarget:
+ SetBkColor((HDC)wParam,GetSysColor(COLOR_WINDOW));
+ SetTextColor((HDC)wParam,GetSysColor(COLOR_WINDOWTEXT));
+
+ //SetBkMode((HDC)wParam,OPAQUE);
+ //return (INT_PTR)GetSysColorBrush(COLOR_WINDOW);
+ return (LRESULT)GetStockObject(WHITE_BRUSH);
+ break;
+ default:
+ SetBkMode((HDC)wParam, TRANSPARENT);
+ return (LRESULT)GetStockObject(NULL_BRUSH);
+ break;
+ }
+ break; //this return false
+ case WM_COMMAND:
+ SendMessage(GetParent(hDlg), uMsg, wParam, lParam);
+ break;
+ case WM_MOUSEMOVE:
+ SendMessage(GetParent(hDlg), UM_TAB1, uMsg, 0);
+ break;
+ case WM_NOTIFY:
+ SendMessage(GetParent(hDlg), uMsg, wParam, lParam);
+ break;
+ case WM_DESTROY:
+ break;
+ }
+ return FALSE;
+}
+
+//---------------------------------------------------------------------------
+INT_PTR CALLBACK TfrmMain::DlgProc_CaptureDesktop(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
+// main message handling is done inside TfrmMain::DlgTfrmMain
+ switch (uMsg) {
+ case WM_INITDIALOG:
+ Static_SetIcon(GetDlgItem(hDlg, ID_imgTarget), IcoLib_GetIcon(ICO_PLUG_SSMONITOR));
+ break;
+ case WM_CTLCOLOREDIT:
+ case WM_CTLCOLORSTATIC:
+ // make the rectangle on the top white
+ switch (GetWindowLongPtr((HWND)lParam, GWL_ID)) {
+ case IDC_WHITERECT:
+ case ID_lblDropInfo:
+ case ID_edtCaption:
+ case ID_edtCaptionLabel:
+ case ID_edtSize:
+ case ID_edtSizeLabel:
+ case ID_bvlTarget:
+ case ID_imgTarget:
+ SetBkColor((HDC)wParam,GetSysColor(COLOR_WINDOW));
+ SetTextColor((HDC)wParam,GetSysColor(COLOR_WINDOWTEXT));
+ return (LRESULT)GetStockObject(WHITE_BRUSH);
+ break;
+ default:
+ SetBkMode((HDC)wParam, TRANSPARENT);
+ return (LRESULT)GetStockObject(NULL_BRUSH);
+ break;
+ }
+ break;
+ case WM_COMMAND:
+ SendMessage(GetParent(hDlg), uMsg, wParam, lParam);
+ break;
+ case WM_NOTIFY:
+ SendMessage(GetParent(hDlg), uMsg, wParam, lParam);
+ break;
+ case WM_DESTROY:
+ break;
+ }
+ return FALSE;
+}
+
+//---------------------------------------------------------------------------
+
+TfrmMain::CHandleMapping TfrmMain::_HandleMapping;
+
+LRESULT CALLBACK TfrmMain::DlgTfrmMain(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ if (msg == WM_CTLCOLOREDIT || msg == WM_CTLCOLORSTATIC) {
+ switch ( GetWindowLongPtr(( HWND )lParam, GWL_ID )) {
+ /* case IDC_WHITERECT:*/
+ case IDC_HEADERBAR:
+ SetTextColor((HDC)wParam,GetSysColor(COLOR_WINDOWTEXT));
+ break;
+ default:
+ return FALSE;
+ }
+ SetBkColor((HDC)wParam, GetSysColor(COLOR_WINDOW));
+ return (LRESULT)GetStockObject(WHITE_BRUSH); //GetSysColorBrush(COLOR_WINDOW);
+ }
+
+ CHandleMapping::iterator wnd(_HandleMapping.end());
+ if (msg == WM_INITDIALOG) {
+ wnd = _HandleMapping.insert(CHandleMapping::value_type(hWnd, reinterpret_cast<TfrmMain*>(lParam))).first;
+ reinterpret_cast<TfrmMain*>(lParam)->m_hWnd = hWnd;
+ return wnd->second->wmInitdialog(wParam, lParam);
+ }
+ else {
+ wnd = _HandleMapping.find(hWnd);
+ }
+ if (wnd == _HandleMapping.end()) { // something screwed up
+ return FALSE; //dialog! do not use ::DefWindowProc(hWnd, msg, wParam, lParam);
+ }
+
+ switch (msg)
+ {
+ // case WM_INITDIALOG: done on top
+ case WM_COMMAND:
+ return wnd->second->wmCommand(wParam, lParam);
+ break;
+ case WM_CLOSE:
+ return wnd->second->wmClose(wParam, lParam);
+ break;
+ case WM_DESTROY:
+ delete wnd->second;
+ break;
+ case UM_TAB1:
+ return wnd->second->UMTab1(wParam, lParam);
+ break;
+ case WM_NOTIFY:
+ return wnd->second->wmNotify(wParam, lParam);
+ break;
+ case WM_TIMER:
+ return wnd->second->wmTimer(wParam, lParam);
+ break;
+ case UM_CLOSING:
+ return wnd->second->UMClosing(wParam, lParam);
+ break;
+ case UM_EVENT:
+ return wnd->second->UMevent(wParam, lParam);
+ break;
+ }
+ return FALSE;
+}
+
+//---------------------------------------------------------------------------
+//WM_INITDIALOG:
+LRESULT TfrmMain::wmInitdialog(WPARAM wParam, LPARAM lParam) {
+ HWND hCtrl;
+ //Taskbar and Window icon
+ SendMessage(m_hWnd, WM_SETICON, ICON_BIG, (LPARAM)IcoLib_GetIcon(ICO_PLUG_SSWINDOW1, true));
+ SendMessage(m_hWnd, WM_SETICON, ICON_SMALL, (LPARAM)IcoLib_GetIcon(ICO_PLUG_SSWINDOW2));
+ LPTSTR pt = mir_a2t(__PLUGIN_NAME);
+ SetWindowText(m_hWnd, pt);
+ mir_freeAndNil(pt);
+
+ // Headerbar
+ pt = mir_tstrdup((LPTSTR)CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM)m_hContact, (LPARAM)GCDNF_TCHAR));
+ if (pt && (m_hContact != 0)) {
+ LPTSTR lptString = NULL;
+ mir_tcsadd(lptString , TranslateT("Send screenshot to\n"));
+ mir_tcsadd(lptString , pt);
+ SetDlgItemText(m_hWnd, IDC_HEADERBAR, lptString);
+ mir_free(lptString);
+ }
+ mir_freeAndNil(pt);
+
+ SendMessage(GetDlgItem(m_hWnd, IDC_HEADERBAR), WM_SETICON, 0, (WPARAM)IcoLib_GetIcon(ICO_PLUG_SSWINDOW1, true));
+
+ //Timed controls
+ CheckDlgButton(m_hWnd,ID_chkTimed, m_opt_chkTimed ? BST_CHECKED : BST_UNCHECKED);
+ SetDlgItemInt (m_hWnd,ID_edtTimed, (UINT)m_opt_edtTimed, FALSE);
+ SendDlgItemMessage(m_hWnd, ID_upTimed, UDM_SETRANGE, 0, (LPARAM)MAKELONG(250, 1));
+ chkTimedClick(); //enable disable Timed controls
+
+ //create Image list for tab control
+ if(m_himlTab == 0){
+ //m_himlTab = ImageList_Create(16, 16, PluginConfig.m_bIsXP ? ILC_COLOR32 | ILC_MASK : ILC_COLOR8 | ILC_MASK, 2, 0);
+ m_himlTab = ImageList_Create(16, 16, ILC_COLOR32 | ILC_MASK, 2, 0);
+ ImageList_AddIcon(m_himlTab, IcoLib_GetIcon(ICO_PLUG_SSWINDOW2));
+ ImageList_AddIcon(m_himlTab, IcoLib_GetIcon(ICO_PLUG_SSWINDOW2));
+ }
+
+ //create the tab control.
+ {
+ TAB_INFO itab;
+ RECT rcClient, rcTab;
+ m_hwndTab = GetDlgItem(m_hWnd, IDC_CAPTURETAB);
+ TabCtrl_SetItemExtra(m_hwndTab, sizeof(TAB_INFO) - sizeof(TCITEMHEADER));
+
+ ZeroMemory(&itab, sizeof(itab));
+ itab.hwndMain = m_hWnd;
+ itab.hwndTab = m_hwndTab;
+
+ GetWindowRect(m_hwndTab, &rcTab);
+ GetWindowRect(m_hWnd, &rcClient);
+
+ TabCtrl_SetImageList(m_hwndTab, m_himlTab);
+
+ // Add a tab for each of the three child dialog boxes.
+ itab.tcih.mask = TCIF_PARAM|TCIF_TEXT|TCIF_IMAGE;
+
+ itab.tcih.pszText = TranslateT("Window");
+ itab.tcih.iImage = 0;
+ itab.hwndTabPage = CreateDialog(hInst,MAKEINTRESOURCE(IDD_UMain_CaptureWindow), m_hWnd,(DLGPROC)DlgProc_CaptureWindow);
+ TabCtrl_InsertItem(m_hwndTab, 0, &itab);
+ MoveWindow(itab.hwndTabPage, (rcTab.left - rcClient.left)+2, (rcTab.top - rcClient.top), (rcTab.right - rcTab.left) - 2*5, (rcTab.bottom - rcTab.top) - 2*20, TRUE);
+ ShowWindow(itab.hwndTabPage, SW_HIDE);
+ CheckDlgButton(itab.hwndTabPage, ID_chkClientArea, m_opt_chkClientArea ? BST_CHECKED : BST_UNCHECKED);
+
+ itab.tcih.pszText = TranslateT("Desktop");
+ itab.tcih.iImage = 1;
+ itab.hwndTabPage = CreateDialog(hInst,MAKEINTRESOURCE(IDD_UMain_CaptureDesktop), m_hWnd, DlgProc_CaptureDesktop);
+ TabCtrl_InsertItem(m_hwndTab, 1, &itab);
+ MoveWindow(itab.hwndTabPage, (rcTab.left - rcClient.left)+2, (rcTab.top - rcClient.top), (rcTab.right - rcTab.left) - 2*5, (rcTab.bottom - rcTab.top) - 2*20, TRUE);
+ ShowWindow(itab.hwndTabPage, SW_HIDE);
+
+ hCtrl = GetDlgItem(itab.hwndTabPage, ID_edtCaption);
+ ComboBox_ResetContent(hCtrl);
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, TranslateT("<entire desktop>")) ,(DWORD)0);
+ ComboBox_SetCurSel (hCtrl,0);
+ if(m_MonitorCount >1) {
+ TCHAR tszTemp[120];
+ for (size_t i = 0; i < m_MonitorCount; ++i) {
+ mir_sntprintf(tszTemp, SIZEOF(tszTemp),_T("%i. %s%s"),
+ i+1,
+ TranslateT("Monitor"),
+ (m_Monitors[i].dwFlags & MONITORINFOF_PRIMARY) ? TranslateT(" (primary)") : _T("")
+ );
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, (LPCTSTR)tszTemp) , i+1);
+ }
+ ComboBox_SelectItemData (hCtrl, -1, m_opt_cboxDesktop); //use Workaround for MS bug ComboBox_SelectItemData
+ }
+ PostMessage(m_hWnd, WM_COMMAND, MAKEWPARAM(ID_edtCaption, CBN_SELCHANGE),(LPARAM)hCtrl);
+
+ //select tab and set m_hwndTabPage
+ TabCtrl_SetCurSel(m_hwndTab, m_opt_tabCapture);
+ ZeroMemory(&itab, sizeof(itab));
+ itab.tcih.mask = TCIF_PARAM;
+ TabCtrl_GetItem(m_hwndTab,TabCtrl_GetCurSel(m_hwndTab),&itab);
+ ShowWindow(itab.hwndTabPage,SW_SHOW);
+ m_hwndTabPage = itab.hwndTabPage;
+ }
+ //init Format combo box
+ {
+ hCtrl = GetDlgItem(m_hWnd, ID_cboxFormat);
+ ComboBox_ResetContent(hCtrl);
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, _T("PNG")),0);
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, _T("JPG")),1);
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, _T("BMP")),2);
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, _T("TIF")),3);
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, _T("GIF")),4);
+ ComboBox_SelectItemData (hCtrl, -1, m_opt_cboxFormat); //use Workaround for MS bug ComboBox_SelectItemData
+ }
+ //init SendBy combo box
+ {
+ hCtrl = GetDlgItem(m_hWnd, ID_cboxSendBy);
+ ComboBox_ResetContent(hCtrl);
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, TranslateT("<Only save>")) ,SS_JUSTSAVE);
+ if (m_hContact) {
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, TranslateT("File Transfer")),SS_FILESEND);
+ }
+ else if(m_opt_cboxSendBy == SS_FILESEND) {
+ m_opt_cboxSendBy = SS_IMAGESHACK;
+ }
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, TranslateT("E-mail")) ,SS_EMAIL);
+ if (myGlobals.PluginHTTPExist) {
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, _T("HTTP Server")) ,SS_HTTPSERVER);
+ }
+ else if(m_opt_cboxSendBy == SS_HTTPSERVER) {
+ m_opt_cboxSendBy = SS_IMAGESHACK;
+ }
+ if (myGlobals.PluginFTPExist) {
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, TranslateT("FTP File")) ,SS_FTPFILE);
+ }
+ else if(m_opt_cboxSendBy == SS_FTPFILE) {
+ m_opt_cboxSendBy = SS_IMAGESHACK;
+ }
+ ComboBox_SetItemData(hCtrl, ComboBox_AddString(hCtrl, TranslateT("ImageShack")) ,(BYTE)SS_IMAGESHACK);
+ ComboBox_SelectItemData (hCtrl, -1, m_opt_cboxSendBy); //use Workaround for MS bug ComboBox_SelectItemData
+ cboxSendByChange(); //enable disable controls
+ }
+ //init footer options
+ CheckDlgButton(m_hWnd,ID_chkOpenAgain, m_opt_chkOpenAgain ? BST_CHECKED : BST_UNCHECKED);
+
+ if (hCtrl = GetDlgItem(m_hWnd, ID_btnAbout)) {
+ SendDlgItemMessage(m_hWnd, ID_btnAbout, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Information"), MBF_TCHAR);
+ HICON hIcon = IcoLib_GetIcon(ICO_PLUG_SSHELP);
+ SendMessage(hCtrl, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ SetWindowText(hCtrl, hIcon ? _T("") : _T("?"));
+ }
+
+ if (hCtrl = GetDlgItem(m_hWnd, ID_btnExplore)) {
+ SendDlgItemMessage(m_hWnd, ID_btnExplore, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Open Folder"), MBF_TCHAR);
+ HICON hIcon = IcoLib_GetIcon(ICO_PLUG_SSFOLDERO);
+ SendMessage(hCtrl, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ SetWindowText(hCtrl, hIcon ? _T("") : _T("..."));
+ }
+
+ if (hCtrl = GetDlgItem(m_hWnd, ID_btnDesc)) {
+ SendDlgItemMessage(m_hWnd, ID_btnDesc, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Fill description textbox."), MBF_TCHAR);
+ HICON hIcon = IcoLib_GetIcon(m_opt_btnDesc ? ICO_PLUG_SSDESKON : ICO_PLUG_SSDESKOFF);
+ SendMessage(hCtrl, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ SetWindowText(hCtrl, hIcon ? _T("") : _T("D"));
+ SendMessage(hCtrl, BM_SETCHECK, m_opt_btnDesc ? BST_CHECKED : BST_UNCHECKED, NULL);
+ }
+
+ if (hCtrl = GetDlgItem(m_hWnd, ID_btnDeleteAfterSend)) {
+ SendDlgItemMessage(m_hWnd, ID_btnDeleteAfterSend, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Delete after send"), MBF_TCHAR);
+ HICON hIcon = IcoLib_GetIcon(m_opt_btnDeleteAfterSend ? ICO_PLUG_SSDELON : ICO_PLUG_SSDELOFF);
+ SendMessage(hCtrl, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ SetWindowText(hCtrl, hIcon ? _T("") : _T("X"));
+ SendMessage(hCtrl, BM_SETCHECK, m_opt_btnDeleteAfterSend ? BST_CHECKED : BST_UNCHECKED, NULL);
+ }
+
+ if (hCtrl = GetDlgItem(m_hWnd, ID_btnCapture)) {
+ SendDlgItemMessage(m_hWnd, ID_btnCapture, BUTTONADDTOOLTIP, (WPARAM)TranslateT("Capture"), MBF_TCHAR);
+ HICON hIcon = IcoLib_GetIcon(ICO_BTN_OK);
+ SendMessage(hCtrl, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ SetWindowText(hCtrl, TranslateT("&Capture"));
+ SendMessage(hCtrl, BUTTONSETDEFAULT, (WPARAM)1, NULL);
+ }
+
+// CheckDlgButton(m_hWnd,ID_chkEditor, m_opt_chkEditor ? BST_CHECKED : BST_UNCHECKED);
+ TranslateDialogDefault(m_hWnd);
+ return FALSE;
+}
+
+//WM_COMMAND:
+LRESULT TfrmMain::wmCommand(WPARAM wParam, LPARAM lParam) {
+ //---------------------------------------------------------------------------
+ int IDControl = LOWORD(wParam);
+ switch (HIWORD(wParam)) {
+ case BN_CLICKED: //Button controls
+ switch(IDControl) {
+ case IDCANCEL:
+ case IDCLOSE:
+ break;
+
+ case ID_chkTimed:
+ m_opt_chkTimed = (BYTE)Button_GetCheck((HWND)lParam);
+ TfrmMain::chkTimedClick();
+ break;
+ case ID_chkClientArea:
+ m_opt_chkClientArea = (BYTE)Button_GetCheck((HWND)lParam);
+ if(m_hTargetWindow)
+ edtSizeUpdate(m_hTargetWindow, m_opt_chkClientArea, GetParent((HWND)lParam), ID_edtSize);
+ break;
+ case ID_chkOpenAgain:
+ m_opt_chkOpenAgain = (BYTE)Button_GetCheck((HWND)lParam);
+ break;
+ case ID_chkEditor:
+ m_opt_chkEditor = (BYTE)Button_GetCheck((HWND)lParam);
+ break;
+
+ case ID_btnAbout:
+ TfrmMain::btnAboutClick();
+ break;
+ case ID_btnExplore:
+ TfrmMain::btnExploreClick();
+ break;
+ case ID_btnDesc:
+ {
+ m_opt_btnDesc = (m_opt_btnDesc == 0);
+ HICON hIcon = IcoLib_GetIcon(m_opt_btnDesc ? ICO_PLUG_SSDESKON : ICO_PLUG_SSDESKOFF);
+ SendMessage((HWND)lParam, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ }
+ break;
+ case ID_btnDeleteAfterSend:
+ {
+ m_opt_btnDeleteAfterSend = (m_opt_btnDeleteAfterSend == 0);
+ HICON hIcon = IcoLib_GetIcon(m_opt_btnDeleteAfterSend ? ICO_PLUG_SSDELON : ICO_PLUG_SSDELOFF);
+ SendMessage((HWND)lParam, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ if(m_cSend) m_cSend->m_bDeleteAfterSend = m_opt_btnDeleteAfterSend;
+ }
+ break;
+ case ID_btnCapture:
+ TfrmMain::btnCaptureClick();
+ break;
+ default:
+ break;
+ }
+ break;
+ case CBN_SELCHANGE: //ComboBox controls
+ switch(IDControl) {
+ //lParam = Handle to the control
+ case ID_cboxFormat: //not finish
+ m_opt_cboxFormat = (BYTE)ComboBox_GetItemData((HWND)lParam, ComboBox_GetCurSel((HWND)lParam));
+ break;
+ case ID_cboxSendBy:
+ m_opt_cboxSendBy = (BYTE)ComboBox_GetItemData((HWND)lParam, ComboBox_GetCurSel((HWND)lParam));
+ cboxSendByChange();
+ break;
+ case ID_edtCaption: //cboxDesktopChange
+ m_opt_cboxDesktop = (BYTE)ComboBox_GetItemData((HWND)lParam, ComboBox_GetCurSel((HWND)lParam));
+ m_hTargetWindow = 0;
+ if (m_opt_cboxDesktop > 0) {
+ edtSizeUpdate(m_Monitors[m_opt_cboxDesktop-1].rcMonitor, GetParent((HWND)lParam), ID_edtSize);
+ }
+ else {
+ edtSizeUpdate(m_VirtualScreen, GetParent((HWND)lParam), ID_edtSize);
+ }
+ break;
+ default:
+ break;
+ }
+ break;
+ case EN_CHANGE: //Edit controls
+ switch(IDControl) {
+ //lParam = Handle to the control
+ case ID_edtQuality:
+ m_opt_edtQuality = (BYTE)GetDlgItemInt(m_hWnd, ID_edtQuality, NULL, FALSE);
+ break;
+ case ID_edtTimed:
+ m_opt_edtTimed = (BYTE)GetDlgItemInt(m_hWnd, ID_edtTimed, NULL, FALSE);
+ break;
+ default:
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+ return FALSE;
+}
+
+//WM_CLOSE:
+LRESULT TfrmMain::wmClose(WPARAM wParam, LPARAM lParam) {
+ DestroyWindow(m_hWnd);
+ return FALSE;
+}
+
+//WM_TIMER:
+LRESULT TfrmMain::wmTimer(WPARAM wParam, LPARAM lParam) {
+ if (wParam == ID_bvlTarget) { // Timer for Target selector
+ if (m_hCursor) { //imgTarget is activ
+ //LmouseButton = false
+ if (!GetLmouse()) {
+ TfrmMain::imgTargetMouseUp();
+ return FALSE;
+ }
+ //Timer action if LmouseButton = true
+ m_hLastWin = m_hTargetWindow;
+ POINT point={0};
+ GetCursorPos(&point);
+ HWND hCurrentWin = WindowFromPoint(point);
+ while (GetParent(hCurrentWin)) {
+ hCurrentWin = GetParent(hCurrentWin);
+ }
+ if (m_hLastWin != hCurrentWin) {
+ LPTSTR lpTitle = NULL;
+ if (m_hLastWin) {
+ DrawBorderInverted(m_hLastWin);
+ }
+ int Count = GetWindowTextLength(hCurrentWin)+1;
+ if(Count > 1){
+ lpTitle = (LPTSTR)mir_alloc(Count*sizeof(TCHAR));
+ GetWindowText(hCurrentWin, lpTitle, Count);
+ }
+ else {
+ //no WindowText present, use WindowClass
+ lpTitle = (LPTSTR)mir_alloc(MAX_PATH*sizeof(TCHAR));
+ RealGetWindowClass(hCurrentWin, lpTitle, MAX_PATH);
+ }
+ SetDlgItemText(m_hwndTabPage, ID_edtCaption, lpTitle);
+ mir_free(lpTitle);
+ edtSizeUpdate(hCurrentWin, m_opt_chkClientArea, m_hwndTabPage, ID_edtSize);
+ DrawBorderInverted(hCurrentWin);
+ m_hTargetWindow = hCurrentWin;
+ }
+ return FALSE;
+ }
+ //imgTarget is not activ (check if cursor is over ID_bvlTarget control)
+ RECT rc;
+ POINT pt;
+ GetWindowRect(GetDlgItem(m_hwndTabPage, wParam),&rc);
+ GetCursorPos(&pt);
+ //check Mouse cursor
+ if(!PtInRect(&rc,pt)) { // mouse must be gone, trigger mouse leave
+ //PostMessage(m_hWnd,WM_MOUSELEAVE,wParam,lParam);
+ KillTimer(m_hWnd,wParam);
+ }
+ else if (GetLmouse() && !m_hCursor) { //mouse hover + LButton
+ TfrmMain::imgTargetMouseDown();
+ }
+ }
+ if (wParam == ID_chkTimed) { // Timer for Screenshot
+ #ifdef _DEBUG
+ OutputDebugStringA("SS Bitmap Timer Start\r\n" );
+ #endif
+ if(!m_bCapture) { //only start once
+ if (m_Screenshot) {
+ FIP->FI_Unload(m_Screenshot);
+ m_Screenshot = NULL;
+ }
+ m_bCapture = true;
+ switch (m_opt_tabCapture) {
+ case 0:
+ m_Screenshot = CaptureWindow(m_hTargetWindow, (BOOL)m_opt_chkClientArea);
+ break;
+ case 1:
+ m_Screenshot = CaptureMonitor((m_opt_cboxDesktop > 0) ? m_Monitors[m_opt_cboxDesktop-1].szDevice : NULL);
+ break;
+ default:
+ KillTimer(m_hWnd,wParam);
+ m_bCapture = false;
+ #ifdef _DEBUG
+ OutputDebugStringA("SS Bitmap Timer Stop (no tabCapture)\r\n" );
+ #endif
+ return FALSE;
+ }
+ if (!m_Screenshot) m_bCapture = false;
+ }
+ if (m_Screenshot) {
+ KillTimer(m_hWnd,wParam);
+ m_bCapture = false;
+ #ifdef _DEBUG
+ OutputDebugStringA("SS Bitmap Timer Stop (CaptureDone)\r\n" );
+ #endif
+ SendMessage(m_hWnd,UM_EVENT, (WPARAM)0, (LPARAM)EVT_CaptureDone);
+ }
+ }
+ return FALSE;
+}
+
+//WM_NOTIFY:
+LRESULT TfrmMain::wmNotify(WPARAM wParam, LPARAM lParam) {
+ switch(((LPNMHDR)lParam)->idFrom) {
+ case IDC_CAPTURETAB: //TabControl IDC_CAPTURETAB
+ switch (((LPNMHDR)lParam)->code) {
+ // HWND hwndFrom; = member is handle to the tab control
+ // UINT_PTR idFrom; = member is the child window identifier of the tab control.
+ // UINT code; = member is TCN_SELCHANGE
+ case TCN_SELCHANGING:
+ {
+ TAB_INFO itab;
+ ZeroMemory(&itab, sizeof(itab));
+ itab.tcih.mask = TCIF_PARAM;
+ TabCtrl_GetItem(m_hwndTab,TabCtrl_GetCurSel(m_hwndTab),&itab);
+ ShowWindow(itab.hwndTabPage,SW_HIDE);
+ m_hwndTabPage = NULL;
+ }
+ break;
+
+ case TCN_SELCHANGE:
+ {
+ TAB_INFO itab;
+ ZeroMemory(&itab, sizeof(itab));
+ itab.tcih.mask = TCIF_PARAM;
+ m_opt_tabCapture = TabCtrl_GetCurSel(m_hwndTab);
+ TabCtrl_GetItem(m_hwndTab, m_opt_tabCapture, &itab);
+ ShowWindow(itab.hwndTabPage, SW_SHOW);
+ m_hwndTabPage = itab.hwndTabPage;
+ }
+ break;
+ default:
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+ return FALSE;
+}
+
+//UM_CLOSING:
+LRESULT TfrmMain::UMClosing(WPARAM wParam, LPARAM lParam) {
+ HWND hWnd = (HWND)wParam;
+ switch (lParam) {
+ case IDD_UAboutForm:
+ btnAboutOnCloseWindow(hWnd);
+ break;
+ case IDD_UEditForm:
+ ;
+ break;
+ default:
+ break;
+ }
+ return FALSE;
+}
+
+//UM_TAB1:
+LRESULT TfrmMain::UMTab1(WPARAM wParam, LPARAM lParam) {
+ switch (wParam) {
+ case WM_MOUSEMOVE:
+ if (m_opt_tabCapture == 0) {
+ // Call timer, used to start cheesy TrackMouseEvent faker
+ SetTimer(m_hWnd,ID_bvlTarget,BUTTON_POLLDELAY,NULL);
+ }
+ break;
+ default:
+ break;
+ }
+ return FALSE;
+}
+
+//UM_EVENT:
+LRESULT TfrmMain::UMevent(WPARAM wParam, LPARAM lParam) {
+ //HWND hWnd = (HWND)wParam;
+ switch (lParam) {
+ case EVT_CaptureDone:
+ if (!m_Screenshot) {
+ TCHAR *err = TranslateT("Cant create a Screenshot");
+ MessageBox(m_hWnd,err,ERROR_TITLE,MB_OK|MB_ICONWARNING);
+ Show();
+ return FALSE;
+ }
+ if (m_opt_chkEditor) {
+ /* TfrmEdit *frmEdit=new TfrmEdit(this);
+ m_bFormEdit = true;
+
+ frmEdit->mniClose->Enabled = !chkJustSaveIt->Checked;
+ frmEdit->mniCloseSend->Enabled = frmEdit->mniClose->Enabled;
+ frmEdit->OnClose = OnCloseEditWindow;
+ frmEdit->InitEditor(Screenshot); // Screenshot is copied to another in-memory bitmap inside this method
+ frmEdit->Show();
+ delete Screenshot; // This way we can delete it after the method returns
+ Screenshot = NULL;
+ */
+ return FALSE;
+ }
+ else {
+ FormClose();
+ }
+ break;
+ case EVT_SendFileDone:
+ break;
+ case EVT_CheckOpenAgain:
+ if (m_opt_chkOpenAgain) {
+ if (m_Screenshot) {
+ FIP->FI_Unload(m_Screenshot);
+ m_Screenshot = NULL;
+ }
+ m_hTargetWindow = m_hLastWin = NULL;
+ Show();
+ }
+ else {
+ // Saving Options and close
+ SaveOptions();
+ Close();
+ }
+ break;
+ default:
+ break;
+ }
+ return FALSE;
+}
+
+//---------------------------------------------------------------------------
+// Standard konstruktor/destruktor
+TfrmMain::TfrmMain() {
+ m_hWnd = NULL;
+ m_hContact = NULL;
+ m_hTargetWindow = NULL;
+ m_hCursor = NULL;
+ m_Screenshot = NULL;
+ m_pszFile = m_pszFileDesc = m_FDestFolder = NULL;
+ m_bFormAbout = m_bFormEdit = m_bDeleteAfterSend = m_bSelectingWindow = false;
+ m_cSend = NULL;
+ m_bOnExitSave = TRUE;
+ LoadOptions();
+ m_bCapture = false;
+ m_himlTab = NULL;
+ m_Monitors = NULL;
+ m_MonitorCount = MonitorInfoEnum(m_Monitors, m_VirtualScreen);
+
+}
+
+TfrmMain::~TfrmMain() {
+ _HandleMapping.erase(m_hWnd);
+ mir_free(m_pszFile);
+ mir_free(m_FDestFolder);
+ mir_free(m_pszFileDesc);
+ mir_free(m_Monitors);
+ if (m_Screenshot) FIP->FI_Unload(m_Screenshot);
+ if (m_cSend) delete m_cSend;
+}
+
+//---------------------------------------------------------------------------
+// Load / Saving options from miranda's database
+void TfrmMain::LoadOptions(void) {
+ DWORD rgb = DBGetContactSettingDword(NULL, SZ_SENDSS, "AlphaColor", 16777215);
+ m_AlphaColor.rgbRed = GetRValue(rgb);
+ m_AlphaColor.rgbGreen = GetGValue(rgb);
+ m_AlphaColor.rgbBlue = GetBValue(rgb);
+ m_AlphaColor.rgbReserved = 0;
+
+// m_opt_chkEmulateClick = DBGetContactSettingByte(NULL, SZ_SENDSS, "AutoSend", 1);
+ m_opt_edtQuality = DBGetContactSettingByte(NULL, SZ_SENDSS, "JpegQuality", 75);
+
+ m_opt_tabCapture = DBGetContactSettingByte(NULL, SZ_SENDSS, "Capture", 0);
+ m_opt_chkClientArea = DBGetContactSettingByte(NULL, SZ_SENDSS, "ClientArea", 0);
+ m_opt_cboxDesktop = DBGetContactSettingByte(NULL, SZ_SENDSS, "Desktop", 0);
+
+ m_opt_chkTimed = DBGetContactSettingByte(NULL, SZ_SENDSS, "TimedCap", 0);
+ m_opt_edtTimed = DBGetContactSettingByte(NULL, SZ_SENDSS, "CapTime", 3);
+ m_opt_cboxFormat = DBGetContactSettingByte(NULL, SZ_SENDSS, "OutputFormat", 3);
+ m_opt_cboxSendBy = DBGetContactSettingByte(NULL, SZ_SENDSS, "SendBy", 0);
+
+ m_opt_chkEditor = DBGetContactSettingByte(NULL, SZ_SENDSS, "Preview", 0);
+ m_opt_btnDesc = DBGetContactSettingByte(NULL, SZ_SENDSS, "AutoDescription", 1);
+ m_opt_btnDeleteAfterSend = DBGetContactSettingByte(NULL, SZ_SENDSS, "DelAfterSend", 1);
+ m_opt_chkOpenAgain = DBGetContactSettingByte(NULL, SZ_SENDSS, "OpenAgain", 0);
+}
+
+void TfrmMain::SaveOptions(void) {
+ if(m_bOnExitSave) {
+ DBWriteContactSettingDword(NULL, SZ_SENDSS, "AlphaColor",
+ (DWORD)RGB(m_AlphaColor.rgbRed, m_AlphaColor.rgbGreen, m_AlphaColor.rgbBlue));
+
+// DBWriteContactSettingByte(NULL, SZ_SENDSS, "AutoSend", m_opt_chkEmulateClick);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "JpegQuality", m_opt_edtQuality);
+
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "Capture", m_opt_tabCapture);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "ClientArea", m_opt_chkClientArea);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "Desktop", m_opt_cboxDesktop);
+
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "TimedCap", m_opt_chkTimed);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "CapTime", m_opt_edtTimed);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "OutputFormat", m_opt_cboxFormat);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "SendBy", m_opt_cboxSendBy);
+
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "AutoDescription", m_opt_btnDesc);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "DelAfterSend", m_opt_btnDeleteAfterSend);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "OpenAgain", m_opt_chkOpenAgain);
+ DBWriteContactSettingByte(NULL, SZ_SENDSS, "Preview", m_opt_chkEditor);
+ }
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::Init(LPTSTR DestFolder, HANDLE Contact) {
+ m_FDestFolder = mir_tstrdup(DestFolder);
+ m_hContact = Contact;
+ if(!m_hContact) m_opt_cboxSendBy = SS_JUSTSAVE;
+
+ // create window
+ m_hWnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_UMainForm),0, (DLGPROC)DlgTfrmMain,(LPARAM)this);
+ //register object
+ _HandleMapping.insert(CHandleMapping::value_type(m_hWnd, this));
+
+ //check Contact
+ if(m_cSend) m_cSend->SetContact(Contact);
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::btnCaptureClick() {
+ m_bFormEdit = false; //until UEditForm is includet
+
+ if (m_opt_tabCapture == 0 && m_hTargetWindow == 0) {
+ TCHAR *err = TranslateT("Select a target window.");
+ MessageBox(m_hWnd,err,ERROR_TITLE,MB_OK|MB_ICONWARNING);
+ return;
+ }
+ TfrmMain::Hide();
+
+ if (!m_hTargetWindow) m_hTargetWindow = GetDesktopWindow();
+
+ if (m_opt_chkTimed) {
+ SetTimer(m_hWnd, ID_chkTimed, m_opt_edtTimed ? m_opt_edtTimed*1000 : 500, NULL);
+ }
+ else if (m_opt_tabCapture == 1){
+ //desktop need always time to update from TfrmMain::Hide()
+ SetTimer(m_hWnd, ID_chkTimed, 500, NULL);
+ }
+ else {
+ m_Screenshot = CaptureWindow(m_hTargetWindow, (BOOL)(m_opt_chkClientArea));
+ SendMessage(m_hWnd,UM_EVENT, (WPARAM)0, (LPARAM)EVT_CaptureDone);
+ }
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::chkTimedClick() {
+ Button_Enable(GetDlgItem(m_hWnd, ID_edtTimedLabel), (BOOL)m_opt_chkTimed);
+ Button_Enable(GetDlgItem(m_hWnd, ID_edtTimed), (BOOL)m_opt_chkTimed);
+ Button_Enable(GetDlgItem(m_hWnd, ID_upTimed), (BOOL)m_opt_chkTimed);
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::imgTargetMouseDown() {
+ //if (Button != mbLeft) return;
+ m_hCursor = CopyCursor(GetCursor()); //backup cursor
+ //SetSystemCursor need a copy coz it destroy the handle
+ SetSystemCursor(CopyCursor(IcoLib_GetIcon(ICO_PLUG_SSTARGET)),OCR_NORMAL);
+ m_bSelectingWindow = true;
+ m_hTargetWindow = NULL;
+ Hide();
+ SetCapture(m_hWnd);
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::imgTargetMouseUp() {
+ //if (Button == mbLeft && m_bSelectingWindow && TimerCheckFocus->Enabled)
+ if (m_bSelectingWindow && m_hCursor) {
+ Show();
+ ReleaseCapture();
+ SetSystemCursor(m_hCursor, OCR_NORMAL);
+ m_hCursor = NULL;
+ if (m_hTargetWindow){
+ DrawBorderInverted(m_hTargetWindow);
+ }
+ m_bSelectingWindow = false;
+ }
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::cboxSendByChange() {
+ BOOL bState;
+ HICON hIcon;
+ BYTE itemFlag = SS_DLG_DESCRIPTION; //SS_DLG_AUTOSEND | SS_DLG_DELETEAFTERSSEND |
+ if (m_cSend && !m_cSend->m_bFreeOnExit) {
+ delete m_cSend;
+ m_cSend = NULL;
+ }
+ switch(m_opt_cboxSendBy) {
+ case SS_FILESEND: //"File Transfer"
+ m_cSend = new CSendFile(m_hWnd, m_hContact, false);
+ break;
+ case SS_EMAIL: //"E-mail"
+ m_cSend = new CSendEmail(m_hWnd, m_hContact, false);
+ break;
+ case SS_HTTPSERVER: //"HTTP Server"
+ m_cSend = new CSendHTTPServer(m_hWnd, m_hContact, false);
+ break;
+ case SS_FTPFILE: //"FTP File"
+ m_cSend = new CSendFTPFile(m_hWnd, m_hContact, false);
+ break;
+ case SS_IMAGESHACK: //"ImageShack"
+ m_cSend = new CSendImageShack(m_hWnd, m_hContact, false);
+ break;
+ default: //SS_JUSTSAVE - "Just save it "
+ m_cSend = NULL;
+ break;
+ }
+ if(m_cSend){
+ itemFlag = m_cSend->GetEnableItem();
+ m_cSend->m_bDeleteAfterSend = m_opt_btnDeleteAfterSend;
+ }
+ bState = ((itemFlag & SS_DLG_DELETEAFTERSSEND) == SS_DLG_DELETEAFTERSSEND);
+ hIcon = IcoLib_GetIcon(m_opt_btnDeleteAfterSend ? ICO_PLUG_SSDELON : ICO_PLUG_SSDELOFF);
+ SendMessage(GetDlgItem(m_hWnd, ID_btnDeleteAfterSend), BM_SETIMAGE, IMAGE_ICON, (LPARAM)(bState ? hIcon : 0));
+ Button_Enable(GetDlgItem(m_hWnd, ID_btnDeleteAfterSend), bState);
+
+ bState = ((itemFlag & SS_DLG_DESCRIPTION) == SS_DLG_DESCRIPTION);
+ hIcon = IcoLib_GetIcon(m_opt_btnDesc ? ICO_PLUG_SSDESKON : ICO_PLUG_SSDESKOFF);
+ SendMessage(GetDlgItem(m_hWnd, ID_btnDesc), BM_SETIMAGE, IMAGE_ICON, (LPARAM)(bState ? hIcon : 0));
+ Button_Enable(GetDlgItem(m_hWnd, ID_btnDesc), bState);
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::btnAboutClick() {
+ if (m_bFormAbout) return;
+
+ TfrmAbout *frmAbout=new TfrmAbout(m_hWnd);
+ frmAbout->Show();
+ m_bFormAbout = true;
+}
+
+// Edit window call this event before it closes
+void TfrmMain::btnAboutOnCloseWindow(HWND hWnd) {
+ m_bFormAbout = false;
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::btnExploreClick() {
+ if (m_FDestFolder)
+ ShellExecute(NULL, _T("explore"), m_FDestFolder, NULL, NULL, SW_SHOW);
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::edtSizeUpdate(HWND hWnd, BOOL ClientArea, HWND hTarget, UINT Ctrl) {
+ // get window dimensions
+ RECT rect = {0};
+ RECT cliRect = {0};
+ TCHAR B[33], H[16];
+ GetWindowRect(hWnd, &rect);
+ if (ClientArea) {
+ POINT pt = {0};
+ GetClientRect(hWnd, &cliRect);
+ pt.x = cliRect.left;
+ pt.y = cliRect.top;
+ ClientToScreen(hWnd, &pt);
+ pt.x = pt.x - rect.left; //offset x for client area
+ pt.y = pt.y - rect.top; //offset y for client area
+ rect = cliRect;
+ }
+// _itot_s(rect.right - rect.left, B, 33, 10);
+ _itot(rect.right - rect.left, B, 10);
+// _itot_s(rect.bottom - rect.top, H, 16, 10);
+ _itot(rect.bottom - rect.top, H, 10);
+ mir_tcsncat(B, _T("x"), 33);
+ mir_tcsncat(B, H, 33);
+ SetDlgItemText(hTarget, Ctrl, B);
+}
+
+void TfrmMain::edtSizeUpdate(RECT rect, HWND hTarget, UINT Ctrl) {
+ TCHAR B[33], H[16];
+// _itot_s(ABS(rect.right - rect.left), B, 33, 10);
+ _itot(ABS(rect.right - rect.left), B, 10);
+// _itot_s(ABS(rect.bottom - rect.top), H, 16, 10);
+ _itot(ABS(rect.bottom - rect.top), H, 10);
+ mir_tcsncat(B, _T("x"), 33);
+ mir_tcsncat(B, H, 33);
+ SetDlgItemText(hTarget, Ctrl, B);
+}
+
+//---------------------------------------------------------------------------
+INT_PTR TfrmMain::SaveScreenshot(FIBITMAP* dib) {
+ //generate File name
+ FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
+ LPTSTR ret = NULL;
+ LPTSTR path = NULL;
+ LPTSTR pszFilename = NULL;
+ LPTSTR pszFileDesc = NULL;
+ if (!dib) return 1; //error
+
+ //Generate FileName
+ mir_tcsadd(path, m_FDestFolder);
+ if (path[_tcslen(path)-1] != _T('\\')) mir_tcsadd(path, _T("\\"));
+ mir_tcsadd(path, _T("shot%.5ld"));
+ int FileNumber=DBGetContactSettingDword(NULL, SZ_SENDSS, "FileNumber", 0) + 1;
+ // '00000'-'%.5ld'=0 (add more or less len if differ from 5
+ size_t len = (_tcslen(path)+0+1);
+ pszFilename = (LPTSTR)mir_alloc(sizeof(TCHAR)*(len));
+ mir_sntprintf(pszFilename, len, path, FileNumber);
+ mir_free(path);
+
+ //Generate a description according to the screenshot
+ TCHAR winText[1024];
+ mir_tcsadd(pszFileDesc, _T("Screenshot "));
+ if (m_opt_tabCapture == 0 && m_opt_chkClientArea) {
+ mir_tcsadd(pszFileDesc, _T("for Client area "));
+ }
+ mir_tcsadd(pszFileDesc, _T("of \""));
+ GetDlgItemText(m_hwndTabPage, ID_edtCaption, winText, 1024);
+ mir_tcsadd(pszFileDesc, winText);
+ mir_tcsadd(pszFileDesc, _T("\" Window"));
+
+ // convert to 32Bits (make shure it is 32bit)
+ FIBITMAP *dib_new = FIP->FI_ConvertTo32Bits(dib);
+ //RGBQUAD appColor = { 245, 0, 254, 0 }; //bgr0 schwarz
+ //FIP->FI_SetBackgroundColor(dib_new, &appColor);
+ FIP->FI_SetTransparent(dib_new,TRUE);
+
+ // Investigates the color type of the bitmap (test for RGB or CMYK colour space)
+ switch (FREE_IMAGE_COLOR_TYPE ColTye=FIP->FI_GetColorType(dib_new)) {
+ case FIC_MINISBLACK:
+ //Monochrome bitmap (1-bit) : first palette entry is black.
+ //Palletised bitmap (4 or 8-bit) and single channel non standard bitmap: the bitmap has a greyscale palette
+ case FIC_MINISWHITE:
+ //Monochrome bitmap (1-bit) : first palette entry is white.
+ //Palletised bitmap (4 or 8-bit) : the bitmap has an inverted greyscale palette
+ case FIC_PALETTE:
+ //Palettized bitmap (1, 4 or 8 bit)
+ case FIC_RGB:
+ //High-color bitmap (16, 24 or 32 bit), RGB16 or RGBF
+ case FIC_RGBALPHA:
+ //High-color bitmap with an alpha channel (32 bit bitmap, RGBA16 or RGBAF)
+ case FIC_CMYK:
+ //CMYK bitmap (32 bit only)
+ default:
+ break;
+ }
+
+
+ if ((FIP->FI_GetICCProfile(dib_new)->flags & FIICC_COLOR_IS_CMYK) == FIICC_COLOR_IS_CMYK) {
+ // we are in CMYK colour space
+ bool bDummy = false;
+ }
+ else {
+ // we are in RGB colour space
+ bool bDummy = true;
+ }
+
+ FIBITMAP *dib32 = NULL;
+ FIBITMAP *dib24 = NULL;
+ HWND hwndCombo = GetDlgItem(m_hWnd, ID_cboxFormat);
+ switch (ComboBox_GetItemData(hwndCombo, ComboBox_GetCurSel(hwndCombo))) {
+ case 0: //PNG
+ ret = SaveImage(fif,dib_new, pszFilename, _T("png"));
+ break;
+
+ case 1: //JPG
+ /*
+ #define JPEG_QUALITYSUPERB 0x80 // save with superb quality (100:1)
+ #define JPEG_QUALITYGOOD 0x0100 // save with good quality (75:1)
+ #define JPEG_QUALITYNORMAL 0x0200 // save with normal quality (50:1)
+ #define JPEG_QUALITYAVERAGE 0x0400 // save with average quality (25:1)
+ #define JPEG_QUALITYBAD 0x0800 // save with bad quality (10:1)
+ #define JPEG_PROGRESSIVE 0x2000 // save as a progressive-JPEG (use | to combine with other save flags)
+ */
+ dib32 = FIP->FI_Composite(dib_new,FALSE,&m_AlphaColor,NULL);
+ dib24 = FIP->FI_ConvertTo24Bits(dib32);
+ FIP->FI_Unload(dib32); dib32 = NULL;
+ ret = SaveImage(fif,dib24, pszFilename, _T("jpg"));
+ FIP->FI_Unload(dib24); dib24 = NULL;
+ break;
+
+ case 2: //BMP
+ // ret = SaveImage(FIF_BMP,dib_new, pszFilename, _T("bmp")); //32bit alpha BMP
+ dib32 = FIP->FI_Composite(dib_new,FALSE,&m_AlphaColor,NULL);
+ dib24 = FIP->FI_ConvertTo24Bits(dib32);
+ FIP->FI_Unload(dib32); dib32 = NULL;
+ ret = SaveImage(FIF_BMP,dib24, pszFilename, _T("bmp"));
+ FIP->FI_Unload(dib24); dib24 = NULL;
+ break;
+
+ case 3: //TIFF (miranda freeimage interface do not support save tiff, we udse GDI+)
+ {
+ LPTSTR pszFile = NULL;
+ mir_tcsadd(pszFile, pszFilename);
+ mir_tcsadd(pszFile, _T(".tif"));
+
+ dib32 = FIP->FI_Composite(dib_new,FALSE,&m_AlphaColor,NULL);
+ dib24 = FIP->FI_ConvertTo24Bits(dib32);
+ FIP->FI_Unload(dib32); dib32 = NULL;
+
+ HBITMAP hBmp = FIP->FI_CreateHBITMAPFromDIB(dib24);
+ FIP->FI_Unload(dib24); dib24 = NULL;
+ ret = SaveTIF(hBmp, pszFile) ? NULL : pszFile;
+ DeleteObject(hBmp);
+ }
+ break;
+
+ case 4: //GIF
+ {
+ //dib24 = FIP->FI_ConvertTo8Bits(dib_new);
+ //ret = SaveImage(FIF_GIF,dib24, pszFilename, _T("gif"));
+ //FIP->FI_Unload(dib24); dib24 = NULL;
+ LPTSTR pszFile = NULL;
+ mir_tcsadd(pszFile, pszFilename);
+ mir_tcsadd(pszFile, _T(".gif"));
+ HBITMAP hBmp = FIP->FI_CreateHBITMAPFromDIB(dib_new);
+ SaveGIF(hBmp, pszFile);
+ ret = pszFile;
+ DeleteObject(hBmp);
+ }
+ break;
+
+ default:
+ break;
+ }
+/* //load PNG and save file in user format (if differ)
+ //this get better result for transparent aereas
+ //LPTSTR pszFormat = (LPTSTR)ComboBox_GetItemData(hwndCombo, ComboBox_GetCurSel(hwndCombo));
+ TCHAR pszFormat[6];
+ ComboBox_GetText(hwndCombo, pszFormat, 6);
+ if(ret && (_tcsicmp (pszFormat,_T("png")) != 0)) {
+ #if defined(_UNICODE)
+ fif = FIP->FI_GetFIFFromFilenameU(ret);
+ dib_new = FIP->FI_LoadU(fif, ret,0);
+ #else
+ fif = FIP->FI_GetFIFFromFilenameU(ret);
+ dib_new = FIP->FI_Load(fif, ret,0);
+ #endif
+
+ if(dib_new) {
+ DeleteFile(ret);
+ mir_freeAndNil(ret);
+ FIBITMAP *dib_save = FIP->FI_ConvertTo24Bits(dib_new);
+ ret = SaveImage(FIF_UNKNOWN,dib_save, pszFilename, pszFormat);
+ FIP->FI_Unload(dib_new); dib_new = NULL;
+ FIP->FI_Unload(dib_save); dib_save = NULL;
+ }
+ }*/
+ FIP->FI_Unload(dib_new); dib_new = NULL;
+ mir_freeAndNil(pszFilename);
+
+ if (ret) {
+ DBWriteContactSettingDword(NULL, SZ_SENDSS, "FileNumber", (DWORD)FileNumber);
+ mir_freeAndNil(m_pszFile);
+ mir_freeAndNil(m_pszFileDesc);
+ m_pszFile = ret;
+ if (IsWindowEnabled(GetDlgItem(m_hWnd, ID_btnDesc)) && m_opt_btnDesc) {
+ m_pszFileDesc = pszFileDesc;
+ }
+ else {
+ mir_tcsadd(m_pszFileDesc, _T(""));
+ }
+
+ if(m_cSend) {
+ mir_freeAndNil(m_cSend->m_pszFile);
+ mir_freeAndNil(m_cSend->m_pszFileDesc);
+ m_cSend->m_pszFile = mir_tstrdup(m_pszFile);
+ m_cSend->m_pszFileDesc = mir_tstrdup(m_pszFileDesc);
+ }
+ return 0; //OK
+ }
+ mir_freeAndNil(ret);
+ mir_freeAndNil(pszFileDesc);
+ return 1; //error
+}
+
+//---------------------------------------------------------------------------
+void TfrmMain::FormClose() {
+
+ // Saving the screenshot
+ if (SaveScreenshot(m_Screenshot)) {
+ Show(); // Error from SaveScreenshot
+ return;
+ }
+
+ if (m_cSend && m_pszFile && m_hContact && !m_bFormEdit) {
+ m_cSend->Send();
+ if (m_cSend->m_bFreeOnExit) cboxSendByChange();
+// Not finish delete this if events from m_opt_cboxSendBy implementet
+ SendMessage(m_hWnd,UM_EVENT, (WPARAM)0, (LPARAM)EVT_CheckOpenAgain);
+ }
+ else {
+ SendMessage(m_hWnd,UM_EVENT, (WPARAM)0, (LPARAM)EVT_CheckOpenAgain);
+ }
+}
+
+//---------------------------------------------------------------------------
+/*/ Edit window call this event before it closes
+void TfrmMain::OnCloseEditWindow(TObject *Sender, TCloseAction &Action) {
+ TfrmEdit *form=dynamic_cast<TfrmEdit*>(Sender);
+ form->Hide();
+
+ // delete the form automatically,after this event returns
+ Action = caFree;
+
+ // This will saves settings, free resources, ...
+ form->CallBeforeClose(Action);
+
+ // User selected "Capture" on action menu of edit window
+ if (form->ModalResult == mrCancel) {
+ this->Show();
+ } else {
+ Screenshot = form->Screen;
+ bFormEdit = form->DontSend;
+ this->Close();
+ }
+}*/
+
+//---------------------------------------------------------------------------
diff --git a/plugins/SendScreenshotPlus/UMainForm.h b/plugins/SendScreenshotPlus/UMainForm.h
new file mode 100644
index 0000000000..a7fdcdc643
--- /dev/null
+++ b/plugins/SendScreenshotPlus/UMainForm.h
@@ -0,0 +1,157 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/UMainForm.h $
+Revision : $Revision: 22 $
+Last change on : $Date: 2010-05-02 21:25:02 +0400 (Вс, 02 май 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef UMainFormH
+#define UMainFormH
+//---------------------------------------------------------------------------
+#include "global.h"
+#include "Utils.h"
+#include "CSend.h"
+#include "CSendFile.h"
+#include "CSendImageShack.h"
+#include "CSendHTTPServer.h"
+#include "CSendFTPFile.h"
+#include "CSendEmail.h"
+
+#define SS_JUSTSAVE 0
+#define SS_FILESEND 1
+#define SS_EMAIL 2
+#define SS_HTTPSERVER 3
+#define SS_FTPFILE 4
+#define SS_IMAGESHACK 5
+
+// Used for our own cheap TrackMouseEvent
+#define BUTTON_POLLDELAY 50
+
+// User Events
+#define EVT_CaptureDone 1
+#define EVT_SendFileDone 2
+#define EVT_CheckOpenAgain 3
+
+extern FI_INTERFACE *FIP;
+
+typedef struct MyTabData {
+ TCITEMHEADER tcih;
+ HWND hwndMain; //main window
+ HWND hwndTab; //tab control
+ HWND hwndTabPage; //current child dialog box
+}TAB_INFO;
+
+//---------------------------------------------------------------------------
+class TfrmMain{
+
+ public:
+ // Deklaration Standardkonstruktor/Standarddestructor
+ TfrmMain();
+ ~TfrmMain();
+
+ BYTE m_opt_tabCapture; //capure tab page
+ BYTE m_opt_btnDesc; //TCheckBox *chkDesc;
+ BYTE m_opt_cboxDesktop; //TRadioButton *rbtnDesktop;
+ BYTE m_opt_chkEditor; //TCheckBox *chkEditor;
+ BYTE m_opt_chkTimed; //TCheckBox *chkTimed;
+ BYTE m_opt_cboxSendBy; //TComboBox *cboxSendBy;
+ bool m_bOnExitSave;
+
+ void Show(){ShowWindow(m_hWnd,SW_SHOW);}
+ void Hide(){ShowWindow(m_hWnd,SW_HIDE);}
+ void Close(){SendMessage(m_hWnd,WM_CLOSE,0,0);}
+ void Init(LPTSTR DestFolder, HANDLE Contact);
+ void btnCaptureClick();
+ void cboxSendByChange();
+
+ private:
+ HWND m_hWnd;
+ HANDLE m_hContact;
+ bool m_bSelectingWindow, m_bDeleteAfterSend;
+ bool m_bFormAbout, m_bFormEdit;
+ HWND m_hTargetWindow, m_hLastWin;
+ LPTSTR m_FDestFolder;
+ LPTSTR m_pszFile;
+ LPTSTR m_pszFileDesc;
+ FIBITMAP* m_Screenshot; //Graphics::TBitmap *Screenshot;
+ RGBQUAD m_AlphaColor; //
+ HCURSOR m_hCursor;
+ CSend* m_cSend;
+
+ void chkTimedClick();
+ void imgTargetMouseDown();
+ void imgTargetMouseUp();
+ void btnAboutClick();
+ void btnAboutOnCloseWindow(HWND hWnd);
+ void btnExploreClick();
+ void LoadOptions(void);
+ void SaveOptions(void);
+ INT_PTR SaveScreenshot(FIBITMAP* dib);
+ void FormClose();
+ static void edtSizeUpdate(HWND hWnd, BOOL ClientArea, HWND hTarget, UINT Ctrl);
+ static void edtSizeUpdate(RECT rect, HWND hTarget, UINT Ctrl);
+
+ protected:
+ size_t m_MonitorCount;
+ MONITORINFOEX* m_Monitors;
+ RECT m_VirtualScreen;
+
+ BYTE m_opt_chkOpenAgain; //TCheckBox *chkOpenAgain;
+ BYTE m_opt_chkClientArea; //TCheckBox *chkClientArea;
+ BYTE m_opt_edtQuality; //TLabeledEdit *edtQuality;
+ BYTE m_opt_btnDeleteAfterSend; //TCheckBox *chkDeleteAfterSend;
+ BYTE m_opt_cboxFormat; //TComboBox *cboxFormat;
+ BYTE m_opt_edtTimed; //TLabeledEdit *edtTimed;
+ bool m_bCapture; //is capture activ
+
+ typedef std::map<HWND, TfrmMain *> CHandleMapping;
+ static CHandleMapping _HandleMapping;
+ static LRESULT CALLBACK DlgTfrmMain(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+
+ LRESULT wmInitdialog(WPARAM wParam, LPARAM lParam);
+ LRESULT wmCommand(WPARAM wParam, LPARAM lParam);
+ LRESULT wmClose(WPARAM wParam, LPARAM lParam);
+ LRESULT wmNotify(WPARAM wParam, LPARAM lParam);
+ LRESULT wmTimer(WPARAM wParam, LPARAM lParam);
+
+ LRESULT UMevent(WPARAM wParam, LPARAM lParam);
+ LRESULT UMClosing(WPARAM wParam, LPARAM lParam);
+ LRESULT UMTab1(WPARAM wParam, LPARAM lParam);
+
+ HWND m_hwndTab; //TabControl handle
+ HWND m_hwndTabPage; //TabControl activ page handle
+ HIMAGELIST m_himlTab; //TabControl imagelist
+ static INT_PTR CALLBACK DlgProc_CaptureWindow (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+ static INT_PTR CALLBACK DlgProc_CaptureDesktop(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+// LRESULT CALLBACK DlgProc_UseLastFile (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
+
+};
+
+//---------------------------------------------------------------------------
+
+#endif
diff --git a/plugins/SendScreenshotPlus/Utils.cpp b/plugins/SendScreenshotPlus/Utils.cpp
new file mode 100644
index 0000000000..f1b7251fd7
--- /dev/null
+++ b/plugins/SendScreenshotPlus/Utils.cpp
@@ -0,0 +1,579 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/Utils.cpp $
+Revision : $Revision: 22 $
+Last change on : $Date: 2010-05-02 21:25:02 +0400 (Вс, 02 май 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#include "Utils.h"
+
+//---------------------------------------------------------------------------
+extern HINSTANCE hInst;
+
+//---------------------------------------------------------------------------
+//Workaround for MS bug ComboBox_SelectItemData
+int ComboBox_SelectItemData(HWND hwndCtl, int indexStart, LPARAM data) {
+ int i = 0;
+ for ( i ; i < ComboBox_GetCount(hwndCtl); i++) {
+ if(data == ComboBox_GetItemData(hwndCtl, i)) {
+ ComboBox_SetCurSel (hwndCtl,i);
+ return i;
+ }
+ }
+ return CB_ERR;
+}
+
+//---------------------------------------------------------------------------
+// MonitorInfoEnum
+size_t MonitorInfoEnum(MONITORINFOEX* & myMonitors, RECT & virtualScreen) {
+ MONITORS tmp = {0,0};
+ if (EnumDisplayMonitors(NULL, NULL, MonitorInfoEnumProc, (LPARAM)&tmp)){
+ myMonitors = tmp.info;
+ memset(&virtualScreen, 0, sizeof(virtualScreen));
+ for (size_t i = 0; i < tmp.count; ++i) {
+ UnionRect(&virtualScreen, &virtualScreen, &tmp.info[i].rcMonitor);
+ }
+ return tmp.count;
+ }
+ else {
+ if (tmp.info) mir_free(tmp.info);
+ }
+ return 0;
+}
+
+// MonitorInfoEnumProc - CALLBACK for MonitorInfoEnum
+BOOL CALLBACK MonitorInfoEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) {
+ MONITORS* monitors = (MONITORS*)dwData;
+ monitors->count++;
+ monitors->info = (MONITORINFOEX*)mir_realloc(monitors->info, sizeof(MONITORINFOEX)*monitors->count);
+ monitors->info[monitors->count-1].cbSize = sizeof(MONITORINFOEX);
+ if(!GetMonitorInfo(hMonitor, (LPMONITORINFO)(monitors->info + monitors->count-1))) {
+ return FALSE; // stop enumeration if error
+ }
+ return TRUE;
+}
+
+//---------------------------------------------------------------------------
+// capture window as FIBITMAP - caller must FIP->FI_Unload(dib)
+FIBITMAP* CaptureWindow (HWND hCapture, BOOL ClientArea) {
+ FIBITMAP *dib = NULL;
+ HWND hForegroundWin = NULL;
+ HDC hScrDC; // screen DC
+ RECT rect= {0}; // screen RECT
+ SIZE size; // DIB width and height = window resolution
+
+ if (!hCapture || !IsWindow(hCapture)) return 0;
+ hForegroundWin = GetForegroundWindow(); //Saving foreground window
+ BringWindowToTop(hCapture); // This window bring the target window to the top of all others
+ SetForegroundWindow(hCapture); // Make sure the target window is the foreground one
+ // redraw window to prevent runtime artefact in picture
+ UpdateWindow(hCapture);
+
+ hScrDC = GetWindowDC(hCapture);
+
+ // get window resolution
+ GetWindowRect(hCapture, &rect);
+ size.cx = ABS(rect.right - rect.left);
+ size.cy = ABS(rect.bottom - rect.top);
+
+ //capture window and get FIBITMAP
+ dib = CaptureScreen(hScrDC, size, hCapture);
+
+ if(ClientArea) {
+ RECT rectCA = {0};
+ POINT pt = {0};
+ GetClientRect (hCapture, &rectCA);
+ ClientToScreen(hCapture, &pt);
+ //crop the window to ClientArea
+ FIBITMAP* dibClient = FIP->FI_Copy(dib,
+ pt.x - rect.left,
+ pt.y - rect.top,
+ pt.x - rect.left + rectCA.right -1,
+ pt.y - rect.top + rectCA.bottom -1);
+ FIP->FI_Unload(dib);
+ dib = dibClient;
+ }
+
+ ReleaseDC(NULL, hScrDC);
+
+ // Restoring foreground window
+ if (hForegroundWin) {
+ SetForegroundWindow(hForegroundWin);
+ }
+
+ return dib;
+}
+
+FIBITMAP* CaptureMonitor (LPTSTR szDevice) {
+ SIZE size;
+ HDC hScrDC;
+ FIBITMAP *dib = NULL;
+ // get screen resolution
+ if(!szDevice) {
+ hScrDC = GetDC(NULL); /*Get full virtualscreen*/
+ size.cx = GetSystemMetrics(SM_CXVIRTUALSCREEN);
+ size.cy = GetSystemMetrics(SM_CYVIRTUALSCREEN);
+ }
+ else {
+ hScrDC = CreateDC(szDevice, NULL, NULL, NULL);
+ size.cx = GetDeviceCaps(hScrDC, HORZRES);
+ size.cy = GetDeviceCaps(hScrDC, VERTRES);
+ }
+ dib = CaptureScreen (hScrDC, size);
+ ReleaseDC(NULL, hScrDC);
+ return dib;
+}
+
+FIBITMAP* CaptureScreen (HDC hDC, SIZE size, HWND hCapture) {
+//HDC GetDC (NULL) entire desktp
+//HDC GetDC (HWND hWnd) client area of the specified window.
+//HDC GetWindowDC (HWND hWnd) entire window.
+ FIBITMAP *dib = NULL;
+ HBITMAP hBitmap; // handles to device-dependent bitmaps
+ HDC hScrDC, hMemDC; // screen DC and memory DC
+
+ // create a DC for the screen and create
+ // a memory DC compatible to screen DC
+ hScrDC = hDC ? hDC : GetDC(NULL/*Get full screen*/);
+ hMemDC = CreateCompatibleDC(hScrDC);
+ // create a bitmap compatible with the screen DC
+ hBitmap = CreateCompatibleBitmap(hScrDC, size.cx, size.cy);
+
+ // select new bitmap into memory DC
+ HBITMAP hOld = (HBITMAP) SelectObject(hMemDC, hBitmap);
+
+ if(hCapture) {
+ PrintWindow(hCapture, hMemDC, 0/*PW_CLIENTONLY is buggy*/);
+ }
+ else {
+ // bitblt screen DC to memory DC
+ BitBlt(hMemDC, 0, 0, size.cx, size.cy, hScrDC, 0, 0, CAPTUREBLT|SRCCOPY);
+ }
+
+ dib = FIP->FI_CreateDIBFromHBITMAP(hBitmap);
+
+ //alpha channel from window is always wrong,
+ //coz GDI do not draw all in alpha mode.
+ //we have to create our own new alpha channel.
+ bool bFixAlpha = true;
+ bool bInvert = false;
+
+ // Create monochrome (1 bit) B+W mask bitmap.
+ HBITMAP hMask = CreateBitmap(size.cx,size.cy, 1, 1, NULL);
+ HDC hMaskDC = CreateCompatibleDC(0);
+ SelectBitmap(hMaskDC, hMask);
+
+ //Create a SolidBrush object for non transparent area
+ HBRUSH hBr = CreateSolidBrush(RGB(255,255,255));
+
+ HRGN hrgn = NULL;
+ int regionType;
+ if(hCapture) {
+ hrgn = CreateRectRgn(0,0,0,0);
+ regionType = GetWindowRgn(hCapture, hrgn);
+ if (regionType != ERROR) {
+ // not layerd - fill the window region
+ FillRgn(hMaskDC, hrgn, hBr);
+ }
+ else { //layerd window (WS_EX_LAYERED)
+ BYTE bAlpha= 0;
+ COLORREF crKey=0; //0x00bbggrr
+ DWORD dwFlags=0;
+ if(GetLayeredWindowAttributes(hCapture,&crKey,&bAlpha,&dwFlags)) {
+ //per window transparency (like fading in a whole window).
+ if((dwFlags & LWA_ALPHA) == LWA_ALPHA) {
+ //Use bAlpha to determine the opacity of the layered window.
+ bFixAlpha = false;
+ }
+ if((dwFlags & LWA_COLORKEY) == LWA_COLORKEY) {
+ //Use crKey as the transparency color.
+ SetBkColor(hMemDC, crKey);
+ BitBlt(hMaskDC, 0, 0, size.cx, size.cy, hMemDC, 0, 0, SRCCOPY);
+ bInvert = true;
+ bFixAlpha = true;
+ }
+ }
+ else {
+ //per-pixel transparency (won't use the WM_PAINT )
+ bFixAlpha = false;
+ }
+ }
+ }
+ else { //fill the desktop region
+ hrgn = CreateRectRgn(0,0,size.cx,size.cy);
+ FillRgn(hMaskDC, hrgn, hBr);
+ }
+
+ if(bFixAlpha) {
+ FIBITMAP* dibMask = FIP->FI_CreateDIBFromHBITMAP(hMask);
+ if(bInvert) FIP->FI_Invert(dibMask);
+ FIBITMAP* dib8 = FIP->FI_ConvertTo8Bits(dibMask);
+
+ //copy the dib8 alpha mask to dib32 main bitmap
+ FIP->FI_SetChannel(dib,dib8,FICC_ALPHA);
+ FIP->FI_Unload(dibMask);
+ FIP->FI_Unload(dib8);
+ }
+
+ //clean up
+ DeleteObject(hBr);
+ if(hrgn) DeleteObject(hrgn);
+ DeleteDC(hMaskDC);
+ DeleteObject(hMask);
+ SelectObject(hMemDC, hOld);
+ DeleteDC(hMemDC);
+ if(!hDC) ReleaseDC(NULL, hScrDC);
+ DeleteObject(hBitmap);
+
+ #ifdef _DEBUG
+ switch (FIP->FI_GetImageType(dib)){
+ case FIT_UNKNOWN:
+ OutputDebugStringA("FIBITMAP Typ: FIT_UNKNOWN\r\n" );
+ break;
+ case FIT_BITMAP:
+ OutputDebugStringA("FIBITMAP Typ: FIT_BITMAP\r\n" );
+ break;
+ case FIT_UINT16:
+ OutputDebugStringA("FIBITMAP Typ: FIT_UINT16\r\n" );
+ break;
+ case FIT_INT16:
+ OutputDebugStringA("FIBITMAP Typ: FIT_INT16\r\n" );
+ break;
+ case FIT_UINT32:
+ OutputDebugStringA("FIBITMAP Typ: FIT_UINT32\r\n" );
+ break;
+ case FIT_INT32:
+ OutputDebugStringA("FIBITMAP Typ: FIT_INT32\r\n" );
+ break;
+ case FIT_FLOAT:
+ OutputDebugStringA("FIBITMAP Typ: FIT_FLOAT\r\n" );
+ break;
+ case FIT_DOUBLE:
+ OutputDebugStringA("FIBITMAP Typ: FIT_DOUBLE\r\n" );
+ break;
+ case FIT_COMPLEX:
+ OutputDebugStringA("FIBITMAP Typ: FIT_COMPLEX\r\n" );
+ break;
+ case FIT_RGB16:
+ OutputDebugStringA("FIBITMAP Typ: FIT_RGB16\r\n" );
+ break;
+ case FIT_RGBA16:
+ OutputDebugStringA("FIBITMAP Typ: FIT_RGBA16\r\n" );
+ break;
+ case FIT_RGBF:
+ OutputDebugStringA("FIBITMAP Typ: FIT_RGBF\r\n" );
+ break;
+ case FIT_RGBAF:
+ OutputDebugStringA("FIBITMAP Typ: FIT_RGBAF\r\n" );
+ break;
+ default:
+ OutputDebugStringA("FIBITMAP Typ: nicht feststellbar\r\n" );
+ break;
+ }
+ BOOL inf = FIP->FI_IsTransparent(dib);
+ OutputDebugStringA(inf ? "FIBITMAP Transparent: true\r\n" : "FIBITMAP Transparent: fase\r\n");
+ #endif
+
+ return dib;
+}
+
+FIBITMAP* CaptureDesktop/*emulate print screen*/() {
+ FIBITMAP *dib = NULL;
+ HBITMAP hBitmap; // handles to device-dependent bitmaps
+ BOOL bBitmap = false;
+ int i = 0;
+ keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY, 0);
+ keybd_event(VK_SNAPSHOT, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
+ do {//Clipboard need time to get bitmap from keybd_event,
+ i++; //we use a counter to get this time.
+ bBitmap = IsClipboardFormatAvailable(CF_BITMAP);
+ if(i == 500) return (FIBITMAP*)0; //emergency exit if something go wrong
+ } while (!bBitmap);
+ #ifdef _DEBUG
+ char mess[120] = {0};
+ LPSTR pszMess = mess;
+ mir_snprintf(pszMess,120,"SS Bitmap counter: %i\r\n",i);
+ OutputDebugStringA( pszMess );
+ #endif
+ //get clipboard data
+ OpenClipboard(NULL);
+ hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP);
+
+ //create FIBITMAP * from HBITMAP
+ FIP->FI_CorrectBitmap32Alpha(hBitmap, FALSE);
+ dib = FIP->FI_CreateDIBFromHBITMAP(hBitmap);
+ CloseClipboard();
+
+ return dib;
+}
+
+LPTSTR SaveImage(FREE_IMAGE_FORMAT fif, FIBITMAP* dib, LPTSTR pszFilename, LPTSTR pszExt, int flag) {
+ int ret=0;
+ LPTSTR pszFile = NULL;
+ LPTSTR FileExt = (LPTSTR)GetFileExt (pszFilename, DBVT_TCHAR);
+ if(!FileExt) {
+ if(!pszExt) return NULL;
+ mir_tcsadd(pszFile, pszFilename);
+ mir_tcsadd(pszFile, _T("."));
+ mir_tcsadd(pszFile, pszExt);
+ }
+ else {
+ mir_tcsadd(pszFile, pszFilename);
+ }
+
+ if(fif==FIF_UNKNOWN) {
+ #if defined(_UNICODE)
+ fif = FIP->FI_GetFIFFromFilenameU(pszFile);
+ #else
+ fif = FIP->FI_GetFIFFromFilename(pszFile);
+ #endif
+ }
+ if(FIP->FI_FIFSupportsICCProfiles(fif)) {
+ bool bDummy = true;
+ }
+
+ #if defined(_UNICODE)
+ ret = FIP->FI_SaveU(fif, dib, pszFile, flag);
+ #else
+ ret = FIP->FI_Save(fif, dib, pszFile, flag);
+ #endif
+
+ mir_free(FileExt);
+
+ if(ret) return pszFile;
+ mir_free(pszFile);
+ return NULL;
+}
+
+//---------------------------------------------------------------------------
+//Draws a selection border on the window under cursor
+void DrawBorderInverted(HWND hWindow) {
+ if (!hWindow){
+ return;
+ }
+ HDC hDC=GetWindowDC(hWindow);
+ RECT rect={0};
+ GetWindowRect(hWindow, &rect);
+
+ int dcSave = SaveDC(hDC);
+
+ SetROP2(hDC, R2_NOT);
+
+ HPEN hPen=0;
+ hPen = CreatePen(PS_SOLID, 10, RGB(0, 0, 0));
+
+ SelectObject(hDC, &hPen);
+ SelectObject(hDC, GetStockObject(NULL_BRUSH));
+
+ Rectangle(hDC, 0, 0, rect.right-rect.left, rect.bottom-rect.top);
+ Rectangle(hDC, 1, 1, rect.right-rect.left-1, rect.bottom-rect.top-1);
+ Rectangle(hDC, 2, 2, rect.right-rect.left-2, rect.bottom-rect.top-2);
+
+ RestoreDC(hDC, dcSave);
+}
+
+//---------------------------------------------------------------------------
+//is left mouse button down
+BOOL GetLmouse() {
+ SHORT temp = GetAsyncKeyState((GetSystemMetrics(SM_SWAPBUTTON)) ? VK_RBUTTON : VK_LBUTTON);
+ if ((temp & 0x8000) == 0x8000) { // LBUTTON down
+ return TRUE;
+ }
+ return FALSE;
+}
+
+//---------------------------------------------------------------------------
+//is miranda unicode
+BOOL mir_is_unicode() {
+ char ver[1024];
+ CallService(MS_SYSTEM_GETVERSIONTEXT, (WPARAM) sizeof(ver), (LPARAM) ver);
+ return strstr(ver, "Unicode") != NULL;
+}
+
+//---------------------------------------------------------------------------
+INT_PTR GetFileName(LPTSTR pszPath, UINT typ) {
+ /*DBVT_ASCIIZ, DBVT_WCHAR, DBVT_TCHAR*/
+ LPTSTR slash = _tcsrchr(pszPath,_T('\\'));
+ if (slash) {
+ switch (typ) {
+ case DBVT_ASCIIZ:
+ return (INT_PTR)mir_t2a(slash+1);
+ case DBVT_WCHAR:
+ return (INT_PTR)mir_t2u(slash+1);
+ default:
+ return 0;
+ }
+ }
+ else {
+ switch (typ) {
+ case DBVT_ASCIIZ:
+ return (INT_PTR)mir_t2a(pszPath);
+ case DBVT_WCHAR:
+ return (INT_PTR)mir_t2u(pszPath);
+ default:
+ return 0;
+ }
+ }
+}
+
+INT_PTR GetFileExt (LPTSTR pszPath, UINT typ) {
+ /*DBVT_ASCIIZ, DBVT_WCHAR, DBVT_TCHAR*/
+ LPTSTR slash = _tcsrchr(pszPath,_T('.'));
+ if (slash) {
+ switch (typ) {
+ case DBVT_ASCIIZ:
+ return (INT_PTR)mir_t2a(slash);
+ case DBVT_WCHAR:
+ return (INT_PTR)mir_t2u(slash);
+ default:
+ return 0;
+ }
+ }
+ else {
+ return NULL;
+ }
+}
+
+//---------------------------------------------------------------------------
+BOOL GetEncoderClsid(wchar_t *wchMimeType, CLSID& clsidEncoder) {
+ UINT uiNum = 0;
+ UINT uiSize = 0;
+ BOOL bOk = FALSE;
+ Gdiplus::ImageCodecInfo* pImageCodecInfo = NULL;
+ Gdiplus::GetImageEncodersSize(&uiNum, &uiSize);
+ if( uiSize > 0 ) {
+ pImageCodecInfo = (Gdiplus::ImageCodecInfo *)new char[uiSize];
+ if( pImageCodecInfo ) {
+ Gdiplus::GetImageEncoders(uiNum, uiSize, pImageCodecInfo);
+ for( UINT i = 0; i < uiNum; i++ ) {
+ if( wcscmp(pImageCodecInfo[i].MimeType, wchMimeType) == 0 ) {
+ clsidEncoder = pImageCodecInfo[i].Clsid;
+ bOk = TRUE;
+ }
+ }
+ }
+ delete pImageCodecInfo;
+ }
+ return bOk;
+}
+
+INT_PTR SavePNG(HBITMAP hBmp, LPTSTR szFilename) {
+ Gdiplus::GdiplusStartupInput gdiplusStartupInput;
+ ULONG_PTR gdiplusToken;
+ Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
+
+ Gdiplus::Bitmap *pBitmap = Gdiplus::Bitmap::FromHBITMAP(hBmp, (HPALETTE)GetStockObject(DEFAULT_PALETTE) );
+ if( pBitmap ) {
+ // Get the CLSID of the PNG encoder.
+ CLSID clsidEncoder;
+ if( GetEncoderClsid(L"image/png", clsidEncoder)) {
+ LPWSTR pswFile = mir_t2u(szFilename);
+ pBitmap->Save((const WCHAR*)pswFile, &clsidEncoder, NULL);
+ mir_free(pswFile);
+ }
+ delete pBitmap;
+ }
+ Gdiplus::GdiplusShutdown(gdiplusToken);
+ return 0;
+}
+
+INT_PTR SaveGIF(HBITMAP hBmp, LPTSTR szFilename) {
+ Gdiplus::GdiplusStartupInput gdiplusStartupInput;
+ ULONG_PTR gdiplusToken;
+ Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
+
+ Gdiplus::Bitmap *pBitmap = Gdiplus::Bitmap::FromHBITMAP(hBmp, (HPALETTE)GetStockObject(DEFAULT_PALETTE) );
+ if( pBitmap ) {
+ // Get the CLSID of the GIF encoder.
+ CLSID clsidEncoder;
+ if( GetEncoderClsid(L"image/gif", clsidEncoder)) {
+ LPWSTR pswFile = mir_t2u(szFilename);
+ pBitmap->Save((const WCHAR*)pswFile, &clsidEncoder, NULL);
+ mir_free(pswFile);
+ }
+ delete pBitmap;
+ }
+ Gdiplus::GdiplusShutdown(gdiplusToken);
+ return 0;
+}
+
+INT_PTR SaveTIF(HBITMAP hBmp, LPTSTR szFilename) {
+//http://www.codeproject.com/Messages/1406708/How-to-reduce-the-size-of-an-Image-using-GDIplus.aspx
+ ULONG_PTR gdiplusToken;
+ Gdiplus::GdiplusStartupInput gdiplusStartupInput;
+ Gdiplus::Status stat;
+ Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
+
+ Gdiplus::Bitmap *pBitmap = Gdiplus::Bitmap::FromHBITMAP(hBmp, (HPALETTE)GetStockObject(DEFAULT_PALETTE) );
+ if( pBitmap ) {
+ // Get the CLSID of the GIF encoder.
+ CLSID EncCLSID;
+ if( GetEncoderClsid(L"image/tiff", EncCLSID)) {
+ //--- Create a 2-parameter array, for Compression and for Color Bit depth
+ Gdiplus::EncoderParameters* EncParams = (Gdiplus::EncoderParameters*) malloc(sizeof(Gdiplus::EncoderParameters) + 1 * sizeof(Gdiplus::EncoderParameter));
+ // Gdiplus::EncoderParameters pEncoderParameters;
+ //--- Use LZW Compression instead of Group 4, since it works for color and G4 doesn't
+ ULONG ulCompression = Gdiplus::EncoderValueCompressionLZW ;
+ ULONG ulColorDepth = 24L ;
+
+ EncParams->Count = 2 ;
+ EncParams->Parameter[0].Guid = Gdiplus::EncoderCompression ;
+ EncParams->Parameter[0].Type = Gdiplus::EncoderParameterValueTypeLong ;
+ EncParams->Parameter[0].NumberOfValues = 1 ;
+ EncParams->Parameter[0].Value = &ulCompression ;
+ EncParams->Parameter[1].Guid = Gdiplus::EncoderColorDepth ;
+ EncParams->Parameter[1].Type = Gdiplus::EncoderParameterValueTypeLong ;
+ EncParams->Parameter[1].NumberOfValues = 1 ;
+ EncParams->Parameter[1].Value = &ulColorDepth ;
+
+ LPWSTR pswFile = mir_t2u(szFilename);
+ stat = pBitmap->Save((const WCHAR*)pswFile, &EncCLSID, EncParams);
+ mir_free(pswFile);
+ free(EncParams);
+ }
+ delete pBitmap;
+ }
+ Gdiplus::GdiplusShutdown(gdiplusToken);
+ return 0;
+}
+
+//---------------------------------------------------------------------------
+/* Old stuff from Borland C++ */
+//---------------------------------------------------------------------------
+/*/Popup
+void ShowPopUp(char *title, char *text) {
+ POPUPDATAEX pude={0};
+
+ strcpy(pude.lpzText, text);
+ strcpy(pude.lpzContactName, title);
+ pude.lchIcon = LoadIcon(g_hAppInstance, MAKEINTRESOURCE(MAIN));
+ pude.colorBack = POPUP_USE_SKINNED_BG;
+
+ CallService(MS_POPUP_ADDPOPUP, (WPARAM)&pude, 0);
+}*/
+
diff --git a/plugins/SendScreenshotPlus/Utils.h b/plugins/SendScreenshotPlus/Utils.h
new file mode 100644
index 0000000000..2934391a8b
--- /dev/null
+++ b/plugins/SendScreenshotPlus/Utils.h
@@ -0,0 +1,81 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/Utils.h $
+Revision : $Revision: 22 $
+Last change on : $Date: 2010-05-02 21:25:02 +0400 (Вс, 02 май 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef UTILSH
+#define UTILSH
+
+#include "global.h"
+//#include <uxtheme.h>
+//#include <tmschema.h>
+#define SPP_USERPANE 1
+
+extern FI_INTERFACE *FIP;
+
+#define ABS(x) ((x)<0?-(x):(x))
+
+typedef struct TEnumDataTemp {
+size_t count;
+MONITORINFOEX* info;
+}MONITORS;
+
+extern HWND g_hCapture;
+extern HBITMAP g_hBitmap, g_hbmMask;
+
+//---------------------------------------------------------------------------
+int ComboBox_SelectItemData(HWND hwndCtl, int indexStart, LPARAM data);
+
+size_t MonitorInfoEnum(MONITORINFOEX* & myMonitors, RECT & virtualScreen);
+BOOL CALLBACK MonitorInfoEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData);
+
+FIBITMAP* CaptureWindow(HWND hCapture, BOOL ClientArea);
+FIBITMAP* CaptureMonitor(LPTSTR szDevice);
+FIBITMAP* CaptureScreen(HDC hDC, SIZE size, HWND hCapture=0);
+FIBITMAP* CaptureDesktop(); /*emulate print screen (not used)*/
+LPTSTR SaveImage(FREE_IMAGE_FORMAT fif, FIBITMAP* dib, LPTSTR pszFilename, LPTSTR pszExt, int flag=0);
+
+void DrawBorderInverted(HWND hWindow);
+BOOL GetLmouse();
+BOOL mir_is_unicode();
+INT_PTR GetFileName(LPTSTR pszPath, UINT typ);
+INT_PTR GetFileExt (LPTSTR pszPath, UINT typ);
+
+BOOL GetEncoderClsid(wchar_t *wchMimeType, CLSID& clsidEncoder);
+INT_PTR SavePNG(HBITMAP hBmp, LPTSTR szFilename);
+INT_PTR SaveGIF(HBITMAP hBmp, LPTSTR szFilename);
+INT_PTR SaveTIF(HBITMAP hBmp, LPTSTR szFilename);
+
+//---------------------------------------------------------------------------
+/* Old stuff from Borland C++
+//void ShowPopUp(char *title, char *text);
+
+*/
+#endif
diff --git a/plugins/SendScreenshotPlus/ctrl_button.cpp b/plugins/SendScreenshotPlus/ctrl_button.cpp
new file mode 100644
index 0000000000..ad8e542fa3
--- /dev/null
+++ b/plugins/SendScreenshotPlus/ctrl_button.cpp
@@ -0,0 +1,699 @@
+/*
+Miranda IM
+Copyright (C) 2002 Robert Rainwater
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+*/
+#include "global.h"
+
+// Used for our own cheap TrackMouseEvent
+#define BUTTON_POLLID 100
+#define BUTTON_POLLDELAY 50
+
+#define MGPROC(x) GetProcAddress(themeAPIHandle,x)
+
+typedef struct TMBCtrl{
+ HWND hwnd;
+ HANDLE hThemeButton;
+ HANDLE hThemeToolbar;
+
+ HICON hIcon;
+ HICON arrow; // uses down arrow
+ HBITMAP hBitmap;
+ HFONT hFont; // font
+
+ DWORD dwStyle;
+ BOOLEAN bFocus;
+
+ INT stateId; // button state
+ INT defbutton; // default button
+ INT pbState;
+ TCHAR cHot;
+} BTNCTRL, *LPBTNCTRL;
+
+// External theme methods and properties
+CRITICAL_SECTION csTips;
+HWND hwndToolTips = NULL;
+HMODULE themeAPIHandle = NULL;
+
+// theme procedures
+HANDLE (WINAPI *OpenThemeData)(HWND,LPCWSTR);
+HRESULT (WINAPI *CloseThemeData)(HANDLE);
+BOOL (WINAPI *IsThemeBackgroundPartiallyTransparent)(HANDLE,INT,INT);
+HRESULT (WINAPI *DrawThemeParentBackground)(HWND,HDC,RECT *);
+HRESULT (WINAPI *DrawThemeBackground)(HANDLE,HDC,INT,INT,const RECT *,const RECT *);
+HRESULT (WINAPI *DrawThemeText)(HANDLE,HDC,INT,INT,LPCWSTR,INT,DWORD,DWORD,const RECT *);
+HRESULT (WINAPI *GetThemeTextExtent)(HANDLE,HDC,INT,INT,LPCWSTR,INT,DWORD,OPTIONAL const RECT*, RECT *);
+HRESULT (WINAPI *GetThemeBackgroundRegion)(HANDLE,HDC,INT,INT,const RECT *,HRGN *);
+
+/**
+ * name: ThemeSupport
+ * desc: Loads the uxtheme functions, if supported by the os
+ * param: none
+ * return: TRUE if themes are supported, FALSE if not
+ **/
+BOOLEAN __fastcall ThemeSupport() {
+ if (IsWinVerXPPlus()) {
+ if (!themeAPIHandle) {
+ themeAPIHandle = GetModuleHandleA("uxtheme");
+ if (themeAPIHandle) {
+ OpenThemeData = (HANDLE (WINAPI *)(HWND,LPCWSTR))MGPROC("OpenThemeData");
+ CloseThemeData = (HRESULT (WINAPI *)(HANDLE))MGPROC("CloseThemeData");
+ IsThemeBackgroundPartiallyTransparent = (BOOL (WINAPI *)(HANDLE,INT,INT))MGPROC("IsThemeBackgroundPartiallyTransparent");
+ DrawThemeParentBackground = (HRESULT (WINAPI *)(HWND,HDC,RECT *))MGPROC("DrawThemeParentBackground");
+ DrawThemeBackground = (HRESULT (WINAPI *)(HANDLE,HDC,INT,INT,const RECT *,const RECT *))MGPROC("DrawThemeBackground");
+ DrawThemeText = (HRESULT (WINAPI *)(HANDLE,HDC,INT,INT,LPCWSTR,INT,DWORD,DWORD,const RECT *))MGPROC("DrawThemeText");
+ GetThemeTextExtent = (HRESULT (WINAPI *)(HANDLE,HDC,INT,INT,LPCWSTR,INT,DWORD,OPTIONAL const RECT*, RECT *))MGPROC("GetThemeTextExtent");
+ GetThemeBackgroundRegion = (HRESULT (WINAPI *)(HANDLE,HDC,INT,INT,const RECT *,HRGN *))MGPROC("GetThemeBackgroundRegion");
+ }
+ }
+ // Make sure all of these methods are valid (i would hope either all or none work)
+ if (OpenThemeData
+ && CloseThemeData
+ && IsThemeBackgroundPartiallyTransparent
+ && DrawThemeParentBackground
+ && DrawThemeBackground
+ && DrawThemeText
+ && GetThemeTextExtent)
+ {
+ return TRUE;
+ }
+ }
+ return FALSE;
+}
+
+/**
+ * name: DestroyTheme
+ * desc: destroys theme data for buttons
+ * param: ctl - BTNCTRL structure with the information about the theme to close
+ * return: nothing
+ **/
+static VOID __fastcall DestroyTheme(BTNCTRL *ctl) {
+ if (ctl->hThemeButton) {
+ CloseThemeData(ctl->hThemeButton);
+ ctl->hThemeButton = NULL;
+ }
+ if (ctl->hThemeToolbar) {
+ CloseThemeData(ctl->hThemeToolbar);
+ ctl->hThemeToolbar = NULL;
+ }
+}
+
+/**
+ * name: LoadTheme
+ * desc: load theme data for buttons if supported by os
+ * param: ctl - BTNCTRL structure with the information about the theme to load
+ * return: nothing
+ **/
+static VOID __fastcall LoadTheme(BTNCTRL *ctl) {
+ if (ThemeSupport()) {
+ DestroyTheme(ctl);
+ ctl->hThemeButton = OpenThemeData(ctl->hwnd,L"BUTTON");
+ ctl->hThemeToolbar = OpenThemeData(ctl->hwnd,L"TOOLBAR");
+ }
+}
+
+/**
+ * name: TBStateConvert2Flat
+ * desc: convert button stateIDs
+ * param: state - state id for the normal theme button
+ * return: stateID for the flat theme button
+ **/
+static INT __fastcall TBStateConvert2Flat(INT state) {
+ switch (state) {
+ case PBS_NORMAL: return TS_NORMAL;
+ case PBS_HOT: return TS_HOT;
+ case PBS_PRESSED: return TS_PRESSED;
+ case PBS_DISABLED: return TS_DISABLED;
+ case PBS_DEFAULTED: return TS_NORMAL;
+ }
+ return TS_NORMAL;
+}
+
+/**
+ * name: PaintIcon
+ * desc: Draws the Icon of the button
+ * param: ctl - BTNCTRL structure for the button
+ * hdcMem - device context to draw to
+ * ccText - character count of the text of the button
+ * rcClient - rectangle of the whole button
+ * rcText - rectangle of the text to draw later on
+ * return: nothing
+ **/
+static VOID __fastcall PaintIcon(BTNCTRL *ctl, HDC hdcMem, LPWORD ccText, LPRECT rcClient, LPRECT rcText)
+{
+ RECT rcImage;
+
+ // draw icon on the left of the button
+ if (ctl->hIcon) {
+ rcImage.right = GetSystemMetrics(SM_CXSMICON);
+ rcImage.bottom = GetSystemMetrics(SM_CYSMICON);
+ rcImage.left = (rcClient->right - rcClient->left) / 2 - ((rcImage.right + rcText->right + (*ccText > 0 ? 4 : 0) + (ctl->arrow ? rcImage.right : 0)) / 2);
+ rcImage.top = (rcClient->bottom - rcClient->top - rcImage.bottom) / 2;
+ rcImage.right += rcImage.left;
+ rcImage.bottom += rcImage.top;
+
+ OffsetRect(rcText, rcImage.right + 4, 0);
+ if (ctl->stateId == PBS_PRESSED) OffsetRect(&rcImage, 1, 1);
+
+ DrawState(hdcMem, NULL, NULL, (LPARAM)ctl->hIcon, 0,
+ rcImage.left, rcImage.top,
+ rcImage.right - rcImage.left, rcImage.bottom - rcImage.top,
+ IsWindowEnabled(ctl->hwnd) ? DST_ICON | DSS_NORMAL : DST_ICON | DSS_DISABLED);
+ }
+
+ // draw arrow on the right of the button
+ if (ctl->arrow) {
+ rcImage.right = GetSystemMetrics(SM_CXSMICON);
+ rcImage.left = (*ccText > 0 || ctl->hIcon)
+ ? rcClient->right - GetSystemMetrics(SM_CXSMICON)
+ : (rcClient->right - rcClient->left - rcImage.right) / 2;
+ rcImage.right += rcImage.left;
+ rcImage.bottom = GetSystemMetrics(SM_CYSMICON);
+ rcImage.top = (rcClient->bottom - rcClient->top - rcImage.bottom) / 2;
+ if (ctl->stateId == PBS_PRESSED) OffsetRect(&rcImage, 1, 1);
+
+ DrawState(hdcMem, NULL, NULL, (LPARAM)ctl->arrow, 0,
+ rcImage.left, rcImage.top,
+ rcImage.right - rcImage.left, rcImage.bottom - rcImage.top,
+ IsWindowEnabled(ctl->hwnd) ? DST_ICON | DSS_NORMAL : DST_ICON | DSS_DISABLED);
+ }
+}
+
+/**
+ * name: PaintThemeButton
+ * desc: Draws the themed button
+ * param: ctl - BTNCTRL structure for the button
+ * hdcMem - device context to draw to
+ * rcClient - rectangle of the whole button
+ * return: nothing
+ **/
+static VOID __fastcall PaintThemeButton(BTNCTRL *ctl, HDC hdcMem, LPRECT rcClient)
+{
+ RECT rcText = { 0, 0, 0, 0 };
+ WCHAR wszText[MAX_PATH] = { 0 };
+ WORD ccText;
+
+ // Draw the flat button
+ if ((ctl->dwStyle & MBS_FLAT) && ctl->hThemeToolbar) {
+ INT state = IsWindowEnabled(ctl->hwnd)
+ ? (ctl->stateId == PBS_NORMAL && ctl->defbutton
+ ? PBS_DEFAULTED
+ : ctl->stateId)
+ : PBS_DISABLED;
+ if (IsThemeBackgroundPartiallyTransparent(ctl->hThemeToolbar, TP_BUTTON, TBStateConvert2Flat(state))) {
+ if (SUCCEEDED(DrawThemeParentBackground(ctl->hwnd, hdcMem, rcClient)))
+ DrawThemeParentBackground(GetParent(ctl->hwnd), hdcMem, rcClient);
+ }
+ DrawThemeBackground(ctl->hThemeToolbar, hdcMem, TP_BUTTON, TBStateConvert2Flat(state), rcClient, rcClient);
+ }
+ else {
+ // draw themed button background
+ if (ctl->hThemeButton) {
+ INT state = IsWindowEnabled(ctl->hwnd)
+ ? (ctl->stateId == PBS_NORMAL && ctl->defbutton
+ ? PBS_DEFAULTED
+ : ctl->stateId)
+ : PBS_DISABLED;
+ if (IsThemeBackgroundPartiallyTransparent(ctl->hThemeButton, BP_PUSHBUTTON, state)) {
+ if (SUCCEEDED(DrawThemeParentBackground(ctl->hwnd, hdcMem, rcClient)))
+ DrawThemeParentBackground(GetParent(ctl->hwnd), hdcMem, rcClient);
+ }
+ DrawThemeBackground(ctl->hThemeButton, hdcMem, BP_PUSHBUTTON, state, rcClient, rcClient);
+ }
+ }
+
+ // calculate text rect
+ {
+ RECT sizeText;
+ HFONT hOldFont;
+
+ ccText = GetWindowTextW(ctl->hwnd, wszText, sizeof(wszText) / sizeof(WCHAR));
+
+ if (ccText > 0) {
+ hOldFont = (HFONT)SelectObject(hdcMem, ctl->hFont);
+
+ GetThemeTextExtent(
+ ctl->hThemeButton,
+ hdcMem,
+ BP_PUSHBUTTON,
+ IsWindowEnabled(ctl->hwnd) ? ctl->stateId : PBS_DISABLED,
+ wszText,
+ ccText,
+ DST_PREFIXTEXT,
+ NULL,
+ &sizeText);
+
+ if (ctl->cHot) {
+ RECT rcHot;
+
+ GetThemeTextExtent(ctl->hThemeButton,
+ hdcMem,
+ BP_PUSHBUTTON,
+ IsWindowEnabled(ctl->hwnd) ? ctl->stateId : PBS_DISABLED,
+ L"&",
+ 1,
+ DST_PREFIXTEXT,
+ NULL,
+ &rcHot);
+
+ sizeText.right -= (rcHot.right - rcHot.left);
+ }
+ SelectObject(hdcMem, hOldFont);
+
+ rcText.left = (ctl->hIcon) ? 0 : (rcClient->right - rcClient->left - (sizeText.right - sizeText.left)) / 2;
+ rcText.top = (rcClient->bottom - rcClient->top - (sizeText.bottom - sizeText.top)) / 2;
+ rcText.right = rcText.left + (sizeText.right - sizeText.left);
+ rcText.bottom = rcText.top + (sizeText.bottom - sizeText.top);
+ if (ctl->stateId == PBS_PRESSED) {
+ OffsetRect(&rcText, 1, 1);
+ }
+ }
+ }
+ PaintIcon(ctl, hdcMem, &ccText, rcClient, &rcText);
+ // draw text
+ if (ccText > 0 && ctl->hThemeButton) {
+ HFONT hOldFont = (HFONT)SelectObject(hdcMem, ctl->hFont);
+ DrawThemeText(ctl->hThemeButton, hdcMem, BP_PUSHBUTTON, IsWindowEnabled(ctl->hwnd) ? ctl->stateId : PBS_DISABLED, wszText, ccText, DST_PREFIXTEXT, 0, &rcText);
+ SelectObject(hdcMem, hOldFont);
+ }
+}
+
+/**
+ * name: PaintThemeButton
+ * desc: Draws the none themed button
+ * param: ctl - BTNCTRL structure for the button
+ * hdcMem - device context to draw to
+ * rcClient - rectangle of the whole button
+ * return: nothing
+ **/
+static VOID __fastcall PaintButton(BTNCTRL *ctl, HDC hdcMem, LPRECT rcClient)
+{
+ RECT rcText = { 0, 0, 0, 0 };
+ TCHAR szText[MAX_PATH] = { 0 };
+ WORD ccText;
+
+ // Draw the flat button
+ if (ctl->dwStyle & MBS_FLAT) {
+ HBRUSH hbr = NULL;
+
+ if (ctl->stateId == PBS_PRESSED || ctl->stateId == PBS_HOT)
+ hbr = GetSysColorBrush(COLOR_3DLIGHT);
+ else {
+ HDC dc;
+ HWND hwndParent;
+
+ hwndParent = GetParent(ctl->hwnd);
+ if (dc = GetDC(hwndParent)) {
+ hbr = (HBRUSH)SendMessage(hwndParent, WM_CTLCOLORDLG, (WPARAM)dc, (LPARAM)hwndParent);
+ ReleaseDC(hwndParent, dc);
+ }
+ }
+ if (hbr) {
+ FillRect(hdcMem, rcClient, hbr);
+ DeleteObject(hbr);
+ }
+ if (ctl->stateId == PBS_HOT || ctl->bFocus) {
+ if (ctl->pbState) DrawEdge(hdcMem, rcClient, EDGE_ETCHED, BF_RECT|BF_SOFT);
+ else DrawEdge(hdcMem, rcClient, BDR_RAISEDOUTER, BF_RECT|BF_SOFT|BF_FLAT);
+ }
+ else
+ if (ctl->stateId == PBS_PRESSED)
+ DrawEdge(hdcMem, rcClient, BDR_SUNKENOUTER, BF_RECT|BF_SOFT);
+ }
+ else {
+ UINT uState = DFCS_BUTTONPUSH|((ctl->stateId == PBS_HOT) ? DFCS_HOT : 0)|((ctl->stateId == PBS_PRESSED) ? DFCS_PUSHED : 0);
+ if (ctl->defbutton&&ctl->stateId==PBS_NORMAL) uState |= DLGC_DEFPUSHBUTTON;
+ DrawFrameControl(hdcMem, rcClient, DFC_BUTTON, uState);
+ // Draw focus rectangle if button has focus
+ if (ctl->bFocus) {
+ RECT focusRect = *rcClient;
+ InflateRect(&focusRect, -3, -3);
+ DrawFocusRect(hdcMem, &focusRect);
+ }
+ }
+ // calculate text rect
+ {
+ SIZE sizeText;
+ HFONT hOldFont;
+
+ ccText = GetWindowText(ctl->hwnd, szText, SIZEOF(szText));
+
+ if (ccText > 0) {
+ hOldFont = (HFONT)SelectObject(hdcMem, ctl->hFont);
+ GetTextExtentPoint32(hdcMem, szText, ccText, &sizeText);
+ if (ctl->cHot) {
+ SIZE sizeHot;
+
+ GetTextExtentPoint32A(hdcMem, "&", 1, &sizeHot);
+ sizeText.cx -= sizeHot.cx;
+ }
+ SelectObject(hdcMem, hOldFont);
+
+ rcText.left = (ctl->hIcon) ? 0 : (rcClient->right - rcClient->left - sizeText.cx) / 2;
+ rcText.top = (rcClient->bottom - rcClient->top - sizeText.cy) / 2;
+ rcText.right = rcText.left + sizeText.cx;
+ rcText.bottom = rcText.top + sizeText.cy;
+ if (ctl->stateId == PBS_PRESSED)
+ OffsetRect(&rcText, 1, 1);
+ }
+ }
+ PaintIcon(ctl, hdcMem, &ccText, rcClient, &rcText);
+
+ // draw text
+ if (ccText > 0) {
+ HFONT hOldFont;
+
+ hOldFont = (HFONT)SelectObject(hdcMem, ctl->hFont);
+
+ SetBkMode(hdcMem, TRANSPARENT);
+ SetTextColor(hdcMem,
+ IsWindowEnabled(ctl->hwnd) || !ctl->hThemeButton
+ ? ctl->stateId == PBS_HOT
+ ? GetSysColor(COLOR_HOTLIGHT)
+ : GetSysColor(COLOR_BTNTEXT)
+ : GetSysColor(COLOR_GRAYTEXT));
+
+ DrawState(hdcMem, NULL, NULL, (LPARAM)szText, 0,
+ rcText.left, rcText.top, rcText.right - rcText.left, rcText.bottom - rcText.top,
+ IsWindowEnabled(ctl->hwnd) || ctl->hThemeButton ? DST_PREFIXTEXT | DSS_NORMAL : DST_PREFIXTEXT | DSS_DISABLED);
+ SelectObject(hdcMem, hOldFont);
+ }
+}
+
+/**
+ * name: Button_WndProc
+ * desc: window procedure for the button class
+ * param: hwndBtn - window handle to the button
+ * uMsg - message to handle
+ * wParam - message specific parameter
+ * lParam - message specific parameter
+ * return: message specific
+ **/
+static LRESULT CALLBACK Button_WndProc(HWND hwndBtn, UINT uMsg, WPARAM wParam, LPARAM lParam) {
+ LPBTNCTRL bct = (LPBTNCTRL)GetWindowLongPtr(hwndBtn, 0);
+
+ switch (uMsg) {
+ case WM_NCCREATE:
+ {
+ LPCREATESTRUCT cs = (LPCREATESTRUCT)lParam;
+
+ cs->style |= BS_OWNERDRAW;
+ if (!(bct = (LPBTNCTRL)malloc(sizeof(BTNCTRL))))
+ return FALSE;
+ ZeroMemory(bct, sizeof(BTNCTRL));
+ bct->hwnd = hwndBtn;
+ bct->stateId = PBS_NORMAL;
+ bct->hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
+ bct->dwStyle = cs->style;
+ if (cs->style & MBS_DOWNARROW)
+ bct->arrow = IcoLib_GetIcon(ICO_BTN_DOWNARROW);
+ LoadTheme(bct);
+ SetWindowLongPtr(hwndBtn, 0, (LONG_PTR)bct);
+ if (cs->lpszName) SetWindowText(hwndBtn, cs->lpszName);
+ return TRUE;
+ }
+ case WM_DESTROY:
+ if (bct) {
+ EnterCriticalSection(&csTips);
+ if (hwndToolTips) {
+ TOOLINFO ti;
+
+ ZeroMemory(&ti, sizeof(ti));
+ ti.cbSize = sizeof(ti);
+ ti.uFlags = TTF_IDISHWND;
+ ti.hwnd = bct->hwnd;
+ ti.uId = (UINT)bct->hwnd;
+ if (SendMessage(hwndToolTips, TTM_GETTOOLINFO, 0, (LPARAM)&ti)) {
+ SendMessage(hwndToolTips, TTM_DELTOOL, 0, (LPARAM)&ti);
+ }
+ if (SendMessage(hwndToolTips, TTM_GETTOOLCOUNT, 0, (LPARAM)&ti) == 0) {
+ DestroyWindow(hwndToolTips);
+ hwndToolTips = NULL;
+ }
+ }
+ LeaveCriticalSection(&csTips);
+ DestroyTheme(bct);
+ free(bct);
+ }
+ SetWindowLongPtr(hwndBtn, 0, NULL);
+ break;
+ case WM_SETTEXT:
+ bct->cHot = 0;
+ if ((LPTSTR)lParam) {
+ LPTSTR tmp = (LPTSTR)lParam;
+
+ while (*tmp) {
+ if (*tmp=='&' && *(tmp+1)) {
+ bct->cHot = _totlower(*(tmp+1));
+ break;
+ }
+ tmp++;
+ }
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ break;
+ case WM_SYSKEYUP:
+ if (bct->stateId != PBS_DISABLED && bct->cHot && bct->cHot == _totlower((TCHAR)wParam)) {
+ if (bct->dwStyle & MBS_PUSHBUTTON) {
+ if (bct->pbState) bct->pbState = 0;
+ else bct->pbState = 1;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ else
+ SetFocus(hwndBtn);
+ SendMessage(GetParent(hwndBtn), WM_COMMAND, MAKELONG(GetDlgCtrlID(hwndBtn), BN_CLICKED), (LPARAM)hwndBtn);
+ return 0;
+ }
+ break;
+ case WM_THEMECHANGED:
+ {
+ // themed changed, reload theme object
+ LoadTheme(bct);
+ InvalidateRect(bct->hwnd, NULL, TRUE); // repaint it
+ break;
+ }
+ case WM_SETFONT: // remember the font so we can use it later
+ bct->hFont = (HFONT)wParam; // maybe we should redraw?
+ break;
+ case WM_NCPAINT:
+ case WM_PAINT:
+ {
+ PAINTSTRUCT ps;
+ HDC hdcPaint;
+ HDC hdcMem;
+ HBITMAP hbmMem;
+ HDC hOld;
+ RECT rcClient;
+
+ if (hdcPaint = BeginPaint(hwndBtn, &ps)) {
+ GetClientRect(bct->hwnd, &rcClient);
+ hdcMem = CreateCompatibleDC(hdcPaint);
+ hbmMem = CreateCompatibleBitmap(hdcPaint, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top);
+ hOld = (HDC)SelectObject(hdcMem, hbmMem);
+
+ // If its a push button, check to see if it should stay pressed
+ if ((bct->dwStyle & MBS_PUSHBUTTON) && bct->pbState) bct->stateId = PBS_PRESSED;
+
+ if ((bct->dwStyle & MBS_FLAT) && bct->hThemeToolbar || bct->hThemeButton)
+ PaintThemeButton(bct, hdcMem, &rcClient);
+ else
+ PaintButton(bct, hdcMem, &rcClient);
+
+ BitBlt(hdcPaint, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, hdcMem, 0, 0, SRCCOPY);
+ SelectObject(hdcMem, hOld);
+ DeleteObject(hbmMem);
+ DeleteDC(hdcMem);
+ EndPaint(hwndBtn, &ps);
+ }
+ return 0;
+ }
+ case BM_SETIMAGE:
+ if (wParam == IMAGE_ICON) {
+ bct->hIcon = (HICON)lParam;
+ bct->hBitmap = NULL;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ else if (wParam == IMAGE_BITMAP) {
+ bct->hIcon = NULL;
+ bct->hBitmap = (HBITMAP)lParam;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ else if (wParam == NULL && lParam == NULL) {
+ bct->hIcon = NULL;
+ bct->hBitmap = NULL;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ break;
+ case BM_SETCHECK:
+ if (!(bct->dwStyle & MBS_PUSHBUTTON)) break;
+ if (wParam == BST_CHECKED) {
+ bct->pbState = 1;
+ bct->stateId = PBS_PRESSED;
+ }
+ else if (wParam == BST_UNCHECKED) {
+ bct->pbState = 0;
+ bct->stateId = PBS_NORMAL;
+ }
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ break;
+ case BM_GETCHECK:
+ if (bct->dwStyle & MBS_PUSHBUTTON) return bct->pbState ? BST_CHECKED : BST_UNCHECKED;
+ return 0;
+ case BUTTONSETDEFAULT:
+ bct->defbutton = wParam ? 1 : 0;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ break;
+ case BUTTONADDTOOLTIP:
+ {
+ if (!wParam) break;
+ EnterCriticalSection(&csTips);
+ if (!hwndToolTips) {
+ hwndToolTips = CreateWindowEx(WS_EX_TOPMOST, TOOLTIPS_CLASS, NULL, WS_POPUP, 0, 0, 0, 0, NULL, NULL, GetModuleHandle(NULL), NULL);
+ }
+
+ if (lParam == MBF_UNICODE) {
+ TOOLINFOW ti;
+
+ ZeroMemory(&ti, sizeof(TOOLINFOW));
+ ti.cbSize = sizeof(TOOLINFOW);
+ ti.uFlags = TTF_IDISHWND;
+ ti.hwnd = bct->hwnd;
+ ti.uId = (UINT)bct->hwnd;
+ if (SendMessage(hwndToolTips, TTM_GETTOOLINFOW, 0, (LPARAM)&ti)) {
+ SendMessage(hwndToolTips, TTM_DELTOOLW, 0, (LPARAM)&ti);
+ }
+ ti.uFlags = TTF_IDISHWND|TTF_SUBCLASS;
+ ti.uId = (UINT)bct->hwnd;
+ ti.lpszText=(LPWSTR)wParam;
+ SendMessage(hwndToolTips, TTM_ADDTOOLW, 0, (LPARAM)&ti);
+ }
+ else {
+ TOOLINFOA ti;
+
+ ZeroMemory(&ti, sizeof(TOOLINFOA));
+ ti.cbSize = sizeof(TOOLINFOA);
+ ti.uFlags = TTF_IDISHWND;
+ ti.hwnd = bct->hwnd;
+ ti.uId = (UINT)bct->hwnd;
+ if (SendMessage(hwndToolTips, TTM_GETTOOLINFOA, 0, (LPARAM)&ti)) {
+ SendMessage(hwndToolTips, TTM_DELTOOLA, 0, (LPARAM)&ti);
+ }
+ ti.uFlags = TTF_IDISHWND|TTF_SUBCLASS;
+ ti.uId = (UINT)bct->hwnd;
+ ti.lpszText=(LPSTR)wParam;
+ SendMessage(hwndToolTips, TTM_ADDTOOLA, 0, (LPARAM)&ti);
+ }
+ LeaveCriticalSection(&csTips);
+ break;
+ }
+ case BUTTONTRANSLATE:
+ {
+ TCHAR szButton[MAX_PATH];
+ GetWindowText(bct->hwnd, szButton, MAX_PATH);
+ SetWindowText(bct->hwnd, TranslateTS(szButton));
+ break;
+ }
+ case WM_SETFOCUS: // set keybord bFocus and redraw
+ bct->bFocus = 1;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ break;
+ case WM_KILLFOCUS: // kill bFocus and redraw
+ bct->bFocus = 0;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ break;
+ case WM_WINDOWPOSCHANGED:
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ break;
+ case WM_ENABLE: // windows tells us to enable/disable
+ bct->stateId = wParam ? PBS_NORMAL : PBS_DISABLED;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ break;
+ case WM_MOUSELEAVE: // faked by the WM_TIMER
+ if (bct->stateId != PBS_DISABLED) { // don't change states if disabled
+ bct->stateId = PBS_NORMAL;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ if (bct->stateId != PBS_DISABLED) { // don't change states if disabled
+ bct->stateId = PBS_PRESSED;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ break;
+ case WM_LBUTTONUP:
+ if (bct->stateId != PBS_DISABLED) { // don't change states if disabled
+ BOOLEAN bPressed = bct->stateId == PBS_PRESSED;
+
+ if (bct->dwStyle & MBS_PUSHBUTTON) {
+ if (bct->pbState) bct->pbState = 0;
+ else bct->pbState = 1;
+ }
+ bct->stateId = PBS_HOT;
+
+ // Tell your daddy you got clicked, if mouse is still over the button.
+ if ((bct->dwStyle & MBS_PUSHBUTTON) || bPressed)
+ SendMessage(GetParent(hwndBtn), WM_COMMAND, MAKELONG(GetDlgCtrlID(hwndBtn), BN_CLICKED), (LPARAM)hwndBtn);
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ break;
+ case WM_MOUSEMOVE:
+ if (bct->stateId == PBS_NORMAL) {
+ bct->stateId = PBS_HOT;
+ InvalidateRect(bct->hwnd, NULL, TRUE);
+ }
+ // Call timer, used to start cheesy TrackMouseEvent faker
+ SetTimer(hwndBtn, BUTTON_POLLID, BUTTON_POLLDELAY, NULL);
+ break;
+ case WM_TIMER: // use a timer to check if they have did a mouseout
+ if (wParam == BUTTON_POLLID) {
+ RECT rc;
+ POINT pt;
+
+ GetWindowRect(hwndBtn, &rc);
+ GetCursorPos(&pt);
+ if (!PtInRect(&rc, pt)) { // mouse must be gone, trigger mouse leave
+ PostMessage(hwndBtn, WM_MOUSELEAVE, 0, 0L);
+ KillTimer(hwndBtn, BUTTON_POLLID);
+ }
+ }
+ break;
+ case WM_ERASEBKGND:
+ return 1;
+ }
+ return DefWindowProc(hwndBtn, uMsg, wParam, lParam);
+}
+
+VOID CtrlButtonUnloadModule()
+{
+ DeleteCriticalSection(&csTips);
+ UnregisterClass(UINFOBUTTONCLASS, hInst);
+}
+
+VOID CtrlButtonLoadModule()
+{
+ WNDCLASSEX wc;
+
+ ZeroMemory(&wc, sizeof(wc));
+ wc.cbSize = sizeof(wc);
+ wc.lpszClassName = UINFOBUTTONCLASS;
+ wc.lpfnWndProc = Button_WndProc;
+ wc.hCursor = LoadCursor(NULL, IDC_ARROW);
+ wc.cbWndExtra = sizeof(LPBTNCTRL);
+ wc.style = CS_GLOBALCLASS;
+ RegisterClassEx(&wc);
+ InitializeCriticalSection(&csTips);
+}
+
diff --git a/plugins/SendScreenshotPlus/ctrl_button.h b/plugins/SendScreenshotPlus/ctrl_button.h
new file mode 100644
index 0000000000..dc77334b05
--- /dev/null
+++ b/plugins/SendScreenshotPlus/ctrl_button.h
@@ -0,0 +1,43 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2009 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+aLONG with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef _UINFOEX_BOTTONS_H_INCLUDED_
+#define _UINFOEX_BOTTONS_H_INCLUDED_ 1
+
+// theme procedures
+extern HANDLE (WINAPI *OpenThemeData)(HWND,LPCWSTR);
+extern HRESULT (WINAPI *CloseThemeData)(HANDLE);
+extern BOOL (WINAPI *IsThemeBackgroundPartiallyTransparent)(HANDLE,INT,INT);
+extern HRESULT (WINAPI *DrawThemeParentBackground)(HWND,HDC,RECT *);
+extern HRESULT (WINAPI *DrawThemeBackground)(HANDLE,HDC,INT,INT,const RECT *,const RECT *);
+extern HRESULT (WINAPI *DrawThemeText)(HANDLE,HDC,INT,INT,LPCWSTR,INT,DWORD,DWORD,const RECT *);
+extern HRESULT (WINAPI *GetThemeTextExtent)(HANDLE,HDC,INT,INT,LPCWSTR,INT,DWORD,OPTIONAL const RECT*, RECT *);
+extern HRESULT (WINAPI *GetThemeBackgroundRegion)(HANDLE,HDC,INT,INT,const RECT *,HRGN *);
+
+
+VOID CtrlButtonLoadModule();
+VOID CtrlButtonUnloadModule();
+
+BOOLEAN __fastcall ThemeSupport();
+
+#endif /* _UINFOEX_BOTTONS_H_INCLUDED_ */ \ No newline at end of file
diff --git a/plugins/SendScreenshotPlus/dlg_msgbox.cpp b/plugins/SendScreenshotPlus/dlg_msgbox.cpp
new file mode 100644
index 0000000000..86fa25cbae
--- /dev/null
+++ b/plugins/SendScreenshotPlus/dlg_msgbox.cpp
@@ -0,0 +1,854 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2009 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+aLONG with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: https://userinfoex.googlecode.com/svn/trunk/dlg_msgbox.cpp $
+Revision : $Revision: 164 $
+Last change on : $Date: 2009-12-02 21:24:35 +0100 (Mi, 02. Dez 2009) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#include "dlg_msgbox.h"
+
+typedef struct _MSGPOPUPDATA
+{
+ POPUPACTION pa[3];
+ HWND hDialog;
+}
+MSGPOPUPDATA, *LPMSGPOPUPDATA;
+
+/**
+ * This helper function moves and resizes a dialog box's control element.
+ *
+ * @param hDlg - the dialog box's window handle
+ * @param idCtrl - the identication number of the control to move
+ * @param dx -�number of pixels to horizontal move the control
+ * @param dy - number of pixels to vertical move the control
+ * @param dw - number of pixels to horizontal resize the control
+ * @param dh - number of pixels to vertical resize the control
+ *
+ * @return nothing
+ **/
+static FORCEINLINE VOID MoveCtrl(HWND hDlg, INT idCtrl, INT dx, INT dy, INT dw, INT dh)
+{
+ RECT ws;
+ HWND hCtrl = GetDlgItem(hDlg, idCtrl);
+ GetWindowRect(hCtrl, &ws);
+ OffsetRect(&ws, dx, dy);
+ MoveWindow(hCtrl, ws.left, ws.top, ws.right - ws.left + dw, ws.bottom - ws.top + dh, FALSE);
+}
+
+/**
+ * This function loads the icon to display for the current message.
+ *
+ * @param pMsgBox - pointer to a MSGBOX structure, with information about the message to display.
+ *
+ * @retval HICON - The function returns an icon to display with the message.
+ * @retval NULL - There is no icon for the message.
+ **/
+HICON MsgLoadIcon(LPMSGBOX pMsgBox)
+{
+ HICON hIcon;
+
+ // load the desired status icon
+ switch (pMsgBox->uType & MB_ICONMASK)
+ {
+
+ // custom icon defined by caller function
+ case MB_ICON_OTHER:
+ {
+ hIcon = pMsgBox->hiMsg;
+ }
+ break;
+
+ // default windows icons
+ case MB_ICON_ERROR:
+ case MB_ICON_QUESTION:
+ case MB_ICON_WARNING:
+ case MB_ICON_INFO:
+ {
+ LPCTSTR ico[] = { 0, IDI_ERROR, IDI_QUESTION, IDI_WARNING, IDI_INFORMATION };
+ hIcon = LoadIcon(NULL, ico[MB_ICON_INDEX(pMsgBox->uType)]);
+ }
+ break;
+
+ // no icon
+ default:
+ {
+ hIcon = NULL;
+ }
+ }
+ return hIcon;
+}
+
+/**
+ * This function fills a given POPUPACTION structure with the data of a given message id,
+ * which is normally used by the message box. This is required to let the user interact
+ * with a popup in the same way as with a normal message dialog box.
+ *
+ * @param pa - reference to a POPUPACTION structure to fill
+ * @param id - the message id
+ * @param result - This parameter is passed to the POPUPACTION structure as is.
+ *
+ * @return nothing
+ **/
+void MakePopupAction(POPUPACTION &pa, INT id)
+{
+ pa.cbSize = sizeof(POPUPACTION);
+ pa.flags = PAF_ENABLED;
+ pa.wParam = MAKEWORD(id, BN_CLICKED);
+ pa.lParam = 0;
+
+ switch (id)
+ {
+ case IDOK:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_OK);
+ mir_strcpy(pa.lpzTitle, MODNAME"/Ok");
+ }
+ break;
+
+ case IDCLOSE:
+ case IDCANCEL:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_CANCEL);
+ mir_strcpy(pa.lpzTitle, MODNAME"/Cancel");
+ }
+ break;
+
+ case IDABORT:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_CANCEL);
+ mir_strcpy(pa.lpzTitle, MODNAME"/Abort");
+ }
+ break;
+
+ case IDRETRY:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_UPDATE);
+ mir_strcpy(pa.lpzTitle, MODNAME"/Retry");
+ }
+ break;
+
+ case IDIGNORE:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_OK);
+ mir_strcpy(pa.lpzTitle, MODNAME"/Ignore");
+ }
+ break;
+
+ case IDYES:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_OK);
+ mir_strcpy(pa.lpzTitle, MODNAME"/Yes");
+ }
+ break;
+
+ case IDNO:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_CANCEL);
+ mir_strcpy(pa.lpzTitle, MODNAME"/No");
+ }
+ break;
+
+ case IDHELP:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_CANCEL);
+ mir_strcpy(pa.lpzTitle, MODNAME"/Help");
+ }
+ break;
+
+ case IDALL:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_OK);
+ mir_strcpy(pa.lpzTitle, MODNAME"/All");
+ }
+ break;
+
+ case IDNONE:
+ {
+ pa.lchIcon = IcoLib_GetIcon(ICO_BTN_CANCEL);
+ mir_strcpy(pa.lpzTitle, MODNAME"/None");
+ }
+ }
+}
+
+/**
+ * This is the message procedure for my nice looking message box
+ *
+ * @param hDlg - window handle
+ * @param uMsg - message to handle
+ * @param wParam - message specific parameter
+ * @param lParam - message specific parameter
+ *
+ * @return TRUE, FALSE, IDOK, IDYES, IDALL, IDNO or IDCANCEL
+ **/
+INT_PTR CALLBACK MsgBoxProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ static INT retOk = IDOK;
+ static INT retAll = IDALL;
+ static INT retNon = IDNONE;
+ static INT retCancel = IDCANCEL;
+
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ {
+ LPMSGBOX pMsgBox = (LPMSGBOX)lParam;
+
+ if (PtrIsValid(pMsgBox))
+ {
+ INT icoWidth = 0;
+ INT InfoBarHeight = 0;
+ HFONT hNormalFont;
+
+ hNormalFont = (HFONT)SendDlgItemMessage(hDlg, TXT_NAME, WM_GETFONT, 0, 0);
+ if (pMsgBox->uType & MB_INFOBAR)
+ {
+ LOGFONT lf;
+
+ // set bold font for name in description area
+ GetObject(hNormalFont, sizeof(lf), &lf);
+ lf.lfWeight = FW_BOLD;
+ hNormalFont = CreateFontIndirect(&lf);
+
+ // set infobar's textfont
+ SendDlgItemMessage(hDlg, TXT_NAME, WM_SETFONT, (WPARAM)hNormalFont, 0);
+
+ // set infobar's logo icon
+ SendDlgItemMessage(hDlg, ICO_DLGLOGO, STM_SETIMAGE, IMAGE_ICON,
+ (LPARAM)((pMsgBox->hiLogo) ? pMsgBox->hiLogo : IcoLib_GetIcon(ICO_DLG_DETAILS)));
+
+ // anable headerbar
+ ShowWindow(GetDlgItem(hDlg, TXT_NAME), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, ICO_DLGLOGO), SW_SHOW);
+ }
+ else
+ {
+ RECT rc;
+ GetClientRect(GetDlgItem(hDlg, TXT_NAME), &rc);
+ InfoBarHeight = rc.bottom;
+
+ if (pMsgBox->hiLogo)
+ {
+ SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)pMsgBox->hiLogo);
+ }
+ }
+
+ // draw the desired status icon
+ HICON hIcon = MsgLoadIcon(pMsgBox);
+ if (hIcon)
+ {
+ SendDlgItemMessage(hDlg, ICO_MSGDLG, STM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ }
+ else
+ {
+ RECT ws;
+ GetWindowRect(GetDlgItem(hDlg, ICO_MSGDLG), &ws);
+ icoWidth = ws.right - ws.left;
+ ShowWindow(GetDlgItem(hDlg, ICO_MSGDLG), SW_HIDE);
+ }
+
+ // resize the messagebox and reorganize the buttons
+ if (HDC hDC = GetDC(hDlg))
+ {
+ POINT mpt = {0,0};
+ RECT ws = {0,0,0,0};
+ INT txtWidth,
+ txtHeight,
+ needX, needY;
+ RECT rcDlg;
+ SIZE ts;
+ LPTSTR h, rs;
+
+ SelectObject(hDC, hNormalFont);
+
+ for (rs = h = pMsgBox->ptszMsg, txtHeight = 0, txtWidth = 0; h; h++)
+ {
+ if (*h == '\n' || *h == '\0')
+ {
+ GetTextExtentPoint32(hDC, rs, h - rs, &ts);
+ if (ts.cx > txtWidth)
+ {
+ txtWidth = ts.cx;
+ }
+ txtHeight += ts.cy;
+ if (*h == '\0')
+ {
+ break;
+ }
+ rs = h + 1;
+ }
+ }
+ ReleaseDC(hDlg, hDC);
+
+ // calc new dialog size
+ GetWindowRect(hDlg, &rcDlg);
+ GetWindowRect(GetDlgItem(hDlg, TXT_MESSAGE), &ws);
+ needX = txtWidth - (ws.right - ws.left) - icoWidth;
+ needY = max(0, txtHeight - (ws.bottom - ws.top) + 5);
+ rcDlg.left -= needX/2; rcDlg.right += needX/2;
+ rcDlg.top -= (needY-InfoBarHeight)/2; rcDlg.bottom += (needY-InfoBarHeight)/2;
+
+ // resize dialog window
+ MoveWindow(hDlg,
+ rcDlg.left, rcDlg.top,
+ rcDlg.right - rcDlg.left,
+ rcDlg.bottom - rcDlg.top,
+ FALSE);
+ ClientToScreen(hDlg, &mpt);
+
+ MoveCtrl(hDlg, STATIC_WHITERECT, -mpt.x, -mpt.y, needX, needY - InfoBarHeight);
+ MoveCtrl(hDlg, TXT_NAME, -mpt.x, -mpt.y, needX, 0);
+ MoveCtrl(hDlg, ICO_DLGLOGO, -mpt.x + needX, -mpt.y, 0, 0);
+ MoveCtrl(hDlg, ICO_MSGDLG, -mpt.x, -mpt.y - InfoBarHeight, 0, 0);
+ MoveCtrl(hDlg, TXT_MESSAGE, -mpt.x - icoWidth, -mpt.y - InfoBarHeight, needX, needY);
+ MoveCtrl(hDlg, STATIC_LINE2, -mpt.x, -mpt.y + needY - InfoBarHeight, needX, 0);
+
+ //
+ // Do pushbutton positioning
+ //
+ {
+ RECT rcOk, rcAll, rcNone, rcCancel;
+ LONG okWidth, caWidth, allWidth, noneWidth, dlgMid;
+
+ // get button rectangles
+ GetWindowRect(GetDlgItem(hDlg, IDOK), &rcOk);
+ OffsetRect(&rcOk, -mpt.x, -mpt.y + needY - InfoBarHeight);
+
+ GetWindowRect(GetDlgItem(hDlg, IDALL), &rcAll);
+ OffsetRect(&rcAll, -mpt.x, -mpt.y + needY - InfoBarHeight);
+
+ GetWindowRect(GetDlgItem(hDlg, IDNONE), &rcNone);
+ OffsetRect(&rcNone, -mpt.x, -mpt.y + needY - InfoBarHeight);
+
+ GetWindowRect(GetDlgItem(hDlg, IDCANCEL), &rcCancel);
+ OffsetRect(&rcCancel, -mpt.x, -mpt.y + needY - InfoBarHeight);
+
+ okWidth = rcOk.right - rcOk.left;
+ allWidth = rcAll.right - rcAll.left;
+ noneWidth = rcNone.right - rcNone.left;
+ caWidth = rcCancel.right - rcCancel.left;
+ dlgMid = (rcDlg.right - rcDlg.left) / 2;
+
+ // load button configuration
+ switch (MB_TYPE(pMsgBox->uType))
+ {
+
+ case MB_OK:
+ {
+ rcOk.left = dlgMid - (okWidth / 2);
+ rcOk.right = rcOk.left + okWidth;
+ ShowWindow(GetDlgItem(hDlg, IDOK), SW_SHOW);
+ }
+ break;
+
+ case MB_OKCANCEL:
+ {
+ retOk = IDRETRY;
+ SetDlgItemText(hDlg, IDOK, LPGENT("OK"));
+ retCancel = IDCANCEL;
+ SetDlgItemText(hDlg, IDCANCEL, LPGENT("Cancel"));
+ rcOk.left = dlgMid - okWidth - 10;
+ rcOk.right = rcOk.left + okWidth;
+ rcCancel.left = dlgMid + 10;
+ rcCancel.right = rcCancel.left + caWidth;
+ ShowWindow(GetDlgItem(hDlg, IDOK), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDCANCEL), SW_SHOW);
+ }
+ break;
+
+ case MB_RETRYCANCEL:
+ {
+ retOk = IDRETRY;
+ SetDlgItemText(hDlg, IDOK, LPGENT("Retry"));
+ retCancel = IDCANCEL;
+ SetDlgItemText(hDlg, IDCANCEL, LPGENT("Cancel"));
+ rcOk.left = dlgMid - okWidth - 10;
+ rcOk.right = rcOk.left + okWidth;
+ rcCancel.left = dlgMid + 10;
+ rcCancel.right = rcCancel.left + caWidth;
+ ShowWindow(GetDlgItem(hDlg, IDOK), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDCANCEL), SW_SHOW);
+ }
+ break;
+
+ case MB_YESNO:
+ {
+ retOk = IDYES;
+ SetDlgItemText(hDlg, IDOK, LPGENT("Yes"));
+ retCancel = IDNO;
+ SetDlgItemText(hDlg, IDCANCEL, LPGENT("No"));
+ rcOk.left = dlgMid - okWidth - 10;
+ rcOk.right = rcOk.left + okWidth;
+ rcCancel.left = dlgMid + 10;
+ rcCancel.right = rcCancel.left + caWidth;
+ ShowWindow(GetDlgItem(hDlg, IDOK), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDCANCEL), SW_SHOW);
+ }
+ break;
+
+ case MB_ABORTRETRYIGNORE:
+ {
+ retOk = IDABORT;
+ SetDlgItemText(hDlg, IDOK, LPGENT("Abord"));
+ retAll = IDABORT;
+ SetDlgItemText(hDlg, IDALL, LPGENT("Retry"));
+ retCancel = IDCANCEL;
+ SetDlgItemText(hDlg, IDCANCEL, LPGENT("Ignore"));
+ rcAll.left = dlgMid - (allWidth / 2);
+ rcAll.right = rcAll.left + allWidth;
+ rcOk.left = rcAll.left - okWidth - 5;
+ rcOk.right = rcOk.left + okWidth;
+ rcCancel.left = rcAll.right + 5;
+ rcCancel.right = rcCancel.left + caWidth;
+ ShowWindow(GetDlgItem(hDlg, IDOK), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDALL), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDCANCEL), SW_SHOW);
+ }
+ break;
+
+ case MB_YESNOCANCEL:
+ {
+ retOk = IDYES;
+ SetDlgItemText(hDlg, IDOK, LPGENT("Yes"));
+ retAll = IDNO;
+ SetDlgItemText(hDlg, IDALL, LPGENT("No"));
+ retCancel = IDCANCEL;
+ SetDlgItemText(hDlg, IDCANCEL, LPGENT("Cancel"));
+ rcAll.left = dlgMid - (allWidth / 2);
+ rcAll.right = rcAll.left + allWidth;
+ rcOk.left = rcAll.left - okWidth - 5;
+ rcOk.right = rcOk.left + okWidth;
+ rcCancel.left = rcAll.right + 5;
+ rcCancel.right = rcCancel.left + caWidth;
+ ShowWindow(GetDlgItem(hDlg, IDOK), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDALL), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDCANCEL), SW_SHOW);
+ }
+ break;
+
+ case MB_YESALLNO:
+ {
+ retOk = IDYES;
+ SetDlgItemText(hDlg, IDOK, LPGENT("Yes"));
+ retAll = IDALL;
+ SetDlgItemText(hDlg, IDALL, LPGENT("All"));
+ //retNon = IDNONE;
+ SetDlgItemText(hDlg, IDNONE, LPGENT("None"));
+ retCancel = IDNO;
+ SetDlgItemText(hDlg, IDCANCEL, LPGENT("No"));
+ rcCancel.right = rcDlg.right - rcDlg.left - 10;
+ rcCancel.left = rcCancel.right - caWidth;
+ rcNone.right = rcCancel.left - 5;
+ rcNone.left = rcNone.right - noneWidth;
+ rcAll.right = rcNone.left - 5;
+ rcAll.left = rcAll.right - allWidth;
+ rcOk.right = rcAll.left - 5;
+ rcOk.left = rcOk.right - okWidth;
+ // show buttons
+ ShowWindow(GetDlgItem(hDlg, IDOK), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDALL), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDNONE), SW_SHOW);
+ ShowWindow(GetDlgItem(hDlg, IDCANCEL), SW_SHOW);
+ }
+ break;
+
+ default:
+ {
+ rcOk.left = dlgMid - (okWidth / 2);
+ rcOk.right = rcOk.left + okWidth;
+ }
+ }
+ // move ok button
+ MoveWindow(GetDlgItem(hDlg, IDOK),
+ rcOk.left, rcOk.top,
+ rcOk.right - rcOk.left, rcOk.bottom - rcOk.top,
+ FALSE);
+ // move all button
+ MoveWindow(GetDlgItem(hDlg, IDALL),
+ rcAll.left, rcAll.top,
+ rcAll.right - rcAll.left, rcAll.bottom - rcAll.top,
+ FALSE);
+ // move none button
+ MoveWindow(GetDlgItem(hDlg, IDNONE),
+ rcNone.left, rcNone.top,
+ rcNone.right - rcNone.left, rcNone.bottom - rcNone.top,
+ FALSE);
+ // move cancel button
+ MoveWindow(GetDlgItem(hDlg, IDCANCEL),
+ rcCancel.left, rcCancel.top,
+ rcCancel.right - rcCancel.left, rcCancel.bottom - rcCancel.top,
+ FALSE);
+ } // end* Do pushbutton positioning
+ } // end* resize the messagebox and reorganize the buttons
+
+ TranslateDialogDefault(hDlg);
+
+ // set text's
+ SetWindowText(hDlg, pMsgBox->ptszTitle);
+ SetDlgItemText(hDlg, TXT_NAME, pMsgBox->ptszInfoText);
+ SetDlgItemText(hDlg, TXT_MESSAGE, pMsgBox->ptszMsg);
+
+ return TRUE;
+ } // end* PtrIsValid(pMsgBox)
+ } // end* WM_INITDIALOG:
+ break;
+
+ case WM_CTLCOLORSTATIC:
+ {
+ switch (GetWindowLong((HWND)lParam, GWL_ID))
+ {
+ case STATIC_WHITERECT:
+ case ICO_DLGLOGO:
+ case ICO_MSGDLG:
+ case TXT_MESSAGE:
+ case TXT_NAME:
+ {
+ SetTextColor((HDC)wParam, GetSysColor(COLOR_WINDOWTEXT));
+ return GetSysColor(COLOR_WINDOW);
+ }
+ }
+ }
+ break;
+
+ case WM_COMMAND:
+ {
+ switch (LOWORD(wParam))
+ {
+ case IDOK:
+ EndDialog(hDlg, retOk);
+ break;
+ case IDCANCEL:
+ EndDialog(hDlg, retCancel);
+ break;
+ case IDALL:
+ EndDialog(hDlg, retAll);
+ break;
+ case IDNONE:
+ EndDialog(hDlg, retNon);
+ }
+ }
+ break;
+
+ case WM_DESTROY:
+ {
+ DeleteObject((HFONT)SendDlgItemMessage(hDlg, TXT_NAME, WM_GETFONT, 0, 0));
+ }
+ break;
+ }
+ return FALSE;
+}
+
+
+/**
+ * Dummi modal MsgBox for popup,
+ * this set call function in wait stait and do not freece miranda main thread
+ * the window is outside the desktop
+ */
+INT_PTR CALLBACK MsgBoxPop(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ switch (uMsg)
+ {
+ case WM_INITDIALOG:
+ {
+ POPUPDATAT pd;
+ LPMSGPOPUPDATA pmpd;
+ LPMSGBOX pMsgBox = (LPMSGBOX)lParam;
+
+ MoveWindow(hDlg,-10,-10,0,0,FALSE);
+ pmpd = (LPMSGPOPUPDATA)mir_alloc(sizeof(MSGPOPUPDATA));
+ if (pmpd)
+ {
+ ZeroMemory(&pd, sizeof(pd));
+ pd.cbSize = sizeof(POPUPDATAT);
+ pd.lchContact = NULL; //(HANDLE)wParam;
+ // icon
+ pd.lchIcon = MsgLoadIcon(pMsgBox);
+ mir_tcsncpy(pd.lptzContactName, pMsgBox->ptszTitle, SIZEOF(pd.lptzContactName));
+ mir_tcsncpy(pd.lptzText, pMsgBox->ptszMsg, SIZEOF(pd.lptzText));
+
+ // CALLBAC Proc
+ pd.PluginWindowProc = (WNDPROC)PopupProc;
+ //
+ pd.PluginData = pmpd;
+
+ pd.iSeconds = -1;
+
+ pd.hNotification = NULL;
+ pd.lpActions = pmpd->pa;
+
+ // set color of popup
+ switch (pMsgBox->uType & MB_ICONMASK)
+ {
+ case MB_ICON_ERROR:
+ {
+ pd.colorBack = RGB(200, 10, 0);
+ pd.colorText = RGB(255, 255, 255);
+ }
+ break;
+
+ case MB_ICON_WARNING:
+ {
+ pd.colorBack = RGB(200, 100, 0);
+ pd.colorText = RGB(255, 255, 255);
+ }
+ break;
+
+ default:
+ {
+ if (pMsgBox->uType & MB_CUSTOMCOLOR)
+ {
+ pd.colorBack = pMsgBox->colorBack;
+ pd.colorText = pMsgBox->colorText;
+ }
+ }
+ }
+
+ // handle for MakePopupAction
+ pmpd->hDialog = hDlg;
+
+ // active buttons
+ switch (MB_TYPE(pMsgBox->uType))
+ {
+ case MB_OK:
+ {
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDOK);
+ }
+ break;
+
+ case MB_OKCANCEL:
+ {
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDOK);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDCANCEL);
+ }
+ break;
+
+ case MB_RETRYCANCEL:
+ {
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDRETRY);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDCANCEL);
+ }
+ break;
+
+ case MB_YESNO:
+ {
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDYES);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDNO);
+ }
+ break;
+
+ case MB_ABORTRETRYIGNORE:
+ {
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDABORT);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDRETRY);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDIGNORE);
+ }
+ break;
+
+ case MB_YESNOCANCEL:
+ {
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDYES);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDNO);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDCANCEL);
+ }
+ break;
+
+ case MB_YESALLNO:
+ {
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDYES);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDALL);
+ MakePopupAction(pmpd->pa[pd.actionCount++], IDNO);
+ }
+ break;
+
+ } // end* switch
+
+ // create popup
+ CallService(MS_POPUP_ADDPOPUPT, (WPARAM) &pd, APF_NEWDATA);
+ if (MB_TYPE(pMsgBox->uType) == MB_OK)
+ {
+ EndDialog(hDlg, IDOK);
+ }
+ } // end*if (pmpd)
+ break;
+ } // end* WM_INITDIALOG:
+ } // end* switch (uMsg)
+ return FALSE;
+}
+
+/**
+ * This is the message procedure for popup
+ *
+ * @param hDlg - window handle
+ * @param uMsg - message to handle
+ * @param wParam - message specific parameter
+ * @param lParam - message specific parameter
+ *
+ * @return TRUE, FALSE, IDOK, IDYES, IDALL, IDNO or IDCANCEL
+ **/
+INT_PTR CALLBACK PopupProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
+{
+ switch (uMsg)
+ {
+ case UM_POPUPACTION:
+ {
+ if (HIWORD(wParam) == BN_CLICKED)
+ {
+ LPMSGPOPUPDATA pmpd = (LPMSGPOPUPDATA)PUGetPluginData(hDlg);
+
+ if (pmpd)
+ {
+ switch (LOWORD(wParam))
+ {
+ case IDOK:
+ case IDCANCEL:
+ case IDABORT:
+ case IDRETRY:
+ case IDIGNORE:
+ case IDYES:
+ case IDNO:
+ case IDALL:
+ case IDNONE:
+ {
+ if (IsWindow(pmpd->hDialog))
+ EndDialog(pmpd->hDialog, LOWORD(wParam));
+ }
+ break;
+
+ default:
+ {
+ if (IsWindow(pmpd->hDialog))
+ EndDialog(pmpd->hDialog, IDCANCEL);
+ }
+ }
+ }
+ PUDeletePopUp(hDlg);
+ }
+ }
+ break;
+
+ case UM_FREEPLUGINDATA:
+ {
+ LPMSGPOPUPDATA pmpd = (LPMSGPOPUPDATA)PUGetPluginData(hDlg);
+ if (pmpd > 0) {
+ mir_freeAndNil(pmpd);
+ }
+ return TRUE; //TRUE or FALSE is the same, it gets ignored.
+ }
+ break;
+
+ default:
+ break;
+ }
+ return DefWindowProc(hDlg, uMsg, wParam, lParam);
+}
+
+/**
+ * This is the service function for external plugins to use the nice messagebox
+ *
+ * @param wParam - HANDLE hContact which can display an avatar for popups
+ * @param lParam - MSGBOX structure holding parameters
+ *
+ * @return The function returns the ID of the clicked button (IDOK, IDCANCEL, ...)
+ * or -1 on error.
+ **/
+INT_PTR MsgBoxService(WPARAM wParam, LPARAM lParam)
+{
+ INT rc = -1;
+ LPMSGBOX pMsgBox = (LPMSGBOX)lParam;
+
+ // check input
+ if (PtrIsValid(pMsgBox) && pMsgBox->cbSize == sizeof(MSGBOX))
+ {
+ // Shall the MessageBox displayed as popup?
+ if (!(pMsgBox->uType & (MB_INFOBAR|MB_NOPOPUP)) && // message box can be a popup?
+ ServiceExists(MS_POPUP_ADDPOPUPT) && // popups exist?
+ myGlobals.PopUpActionsExist == 1 && // popup support ext stuct?
+ (DBGetContactSettingDword(NULL, "PopUp","Actions", 0) & 1) && // popup++ actions on?
+ DBGetContactSettingByte(NULL, MODNAME, SET_POPUPMSGBOX, DEFVAL_POPUPMSGBOX) // user likes popups?
+ )
+ {
+ rc = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_MSGBOXDUMMI), pMsgBox->hParent, (DLGPROC)MsgBoxPop, lParam);
+ }
+ else
+ {
+ rc = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_MSGBOX), pMsgBox->hParent, (DLGPROC)MsgBoxProc, lParam);
+ }
+ }
+ return rc;
+}
+
+/**
+ * name: MsgBox
+ * desc: calls a messagebox
+ * param:
+ **/
+INT_PTR MsgBox(HWND hParent, UINT uType, LPTSTR pszTitle, LPTSTR pszInfo, LPTSTR pszFormat, ...)
+{
+ MSGBOX mb = {0};
+ TCHAR tszMsg[MAX_SECONDLINE];
+ va_list vl;
+
+ va_start(vl, pszFormat);
+ mir_vsntprintf(tszMsg, SIZEOF(tszMsg), TranslateTS(pszFormat), vl);
+ va_end(vl);
+
+ mb.cbSize = sizeof(MSGBOX);
+ mb.hParent = hParent;
+ mb.hiLogo = LoadIcon(hInst, MAKEINTRESOURCE(IDI_PLUG_MAIN));
+ mb.hiMsg = NULL;
+ mb.ptszTitle = TranslateTS(pszTitle);
+ mb.ptszInfoText = TranslateTS(pszInfo);
+ mb.ptszMsg = tszMsg;
+ mb.uType = uType;
+ return MsgBoxService(NULL, (LPARAM)&mb);
+}
+
+/**
+ * name: MsgErr
+ * desc: calls a messagebox
+ * param:
+ **/
+INT_PTR MsgErr(HWND hParent, LPCTSTR pszFormat, ...)
+{
+ if(!pszFormat) return -1;
+ MSGBOX mb = {0};
+ TCHAR tszTitle[MAX_SECONDLINE];
+ TCHAR tszMsg[MAX_SECONDLINE];
+ va_list vl;
+
+ mir_sntprintf(tszTitle, SIZEOF(tszMsg),_T("%s - %s") ,_T(MODNAME), TranslateT("Error"));
+
+ va_start(vl, pszFormat);
+ mir_vsntprintf(tszMsg, SIZEOF(tszMsg), TranslateTS(pszFormat), vl);
+ va_end(vl);
+
+ mb.cbSize = sizeof(MSGBOX);
+ mb.hParent = hParent;
+ mb.hiLogo = LoadIcon(hInst, MAKEINTRESOURCE(IDI_PLUG_MAIN));
+ mb.hiMsg = NULL;
+ mb.ptszTitle = tszTitle;
+ mb.ptszMsg = tszMsg;
+ mb.uType = MB_OK|MB_ICON_ERROR;
+ return MsgBoxService(NULL, (LPARAM)&mb);
+}
diff --git a/plugins/SendScreenshotPlus/dlg_msgbox.h b/plugins/SendScreenshotPlus/dlg_msgbox.h
new file mode 100644
index 0000000000..a6cd04c6b7
--- /dev/null
+++ b/plugins/SendScreenshotPlus/dlg_msgbox.h
@@ -0,0 +1,108 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2009 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+aLONG with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: https://userinfoex.googlecode.com/svn/trunk/dlg_msgbox.h $
+Revision : $Revision: 164 $
+Last change on : $Date: 2009-12-02 21:24:35 +0100 (Mi, 02. Dez 2009) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _DLG_MSGBOX
+#define _DLG_MSGBOX 1
+
+//---------------------------------------------------------------------------
+#include "global.h"
+
+//---------------------------------------------------------------------------
+#define SET_POPUPMSGBOX "PopupMsgBox"
+#define DEFVAL_POPUPMSGBOX TRUE //FALSE
+
+/* UserInfo/MsgBox v0.1.0.3+
+Some little changed message box for nicer look of miranda's messages or questions :-)
+wParam=hContact - can be null
+lParam=(_MSGBOX*)pMsg - structure that holds information about the look of the message dialog
+uType member of _MSGBOX can be a combination of the following values, where most of them are defined in winuser.h:
+MB_OK
+MB_OKCANCEL
+MB_YESALLNO
+MB_YESNO
+For valid icon values use one of the following MB_ICON_...
+Funktion returns: IDOK, IDYES, IDALL, IDNO or IDCANCEL
+*/
+
+/*
+ Defined in winuser.h
+ ********************
+
+#define MB_OK 0x00000000L
+#define MB_OKCANCEL 0x00000001L
+#define MB_ABORTRETRYIGNORE 0x00000002L
+#define MB_YESNOCANCEL 0x00000003L
+#define MB_YESNO 0x00000004L
+#define MB_RETRYCANCEL 0x00000005L
+*/
+#define MB_YESALLNO 0x00000007L
+#define MB_TYPE(p) ((p)&MB_TYPEMASK)
+
+/*
+valid predefined icon values
+*/
+#define MB_ICON_NONE 0x00000000L // 0 - no icon
+#define MB_ICON_ERROR 0x00000010L // 16 - error icon
+#define MB_ICON_QUESTION 0x00000020L // 32 - question mark
+#define MB_ICON_WARNING 0x00000030L // 48 - warning
+#define MB_ICON_INFO 0x00000040L // 64 - info
+#define MB_ICON_OTHER 0x00000080L // 240 - use icon _MSGBOX->hiMsg
+#define MB_ICON_INDEX(p) (((p)&MB_ICONMASK)>>4)
+
+/*
+flags
+*/
+#define MB_INFOBAR 0x00000100L
+#define MB_NOPOPUP 0x00000200L
+#define MB_CUSTOMCOLOR 0x00000300L
+
+typedef struct _MSGBOX
+{
+ UINT cbSize; // size of this structure
+ UINT uType; // parameters
+ HICON hiLogo; // right upper icon of the info bar
+ HICON hiMsg; // icon left next to the message text
+ LPTSTR ptszTitle;
+ LPTSTR ptszInfoText;
+ LPTSTR ptszMsg;
+ HWND hParent; // parent window for the messagebox
+ COLORREF colorBack; // valid if MB_CUSTOMCOLOR is set
+ COLORREF colorText; // valid if MB_CUSTOMCOLOR is set
+} MSGBOX, *LPMSGBOX;
+
+
+INT_PTR CALLBACK MsgBoxProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
+INT_PTR CALLBACK MsgBoxPop (HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
+INT_PTR CALLBACK PopupProc (HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
+
+INT_PTR MsgBoxService(WPARAM wParam, LPARAM lParam);
+INT_PTR MsgBox(HWND hParent, UINT uType, LPTSTR pszTitle, LPTSTR pszInfo, LPTSTR pszFormat, ...);
+INT_PTR MsgErr(HWND hParent, LPCTSTR pszFormat, ...);
+
+#endif /* _DLG_MSGBOX */ \ No newline at end of file
diff --git a/plugins/SendScreenshotPlus/global.h b/plugins/SendScreenshotPlus/global.h
new file mode 100644
index 0000000000..0320949957
--- /dev/null
+++ b/plugins/SendScreenshotPlus/global.h
@@ -0,0 +1,196 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+(c) 2004-2006 S�rgio Vieira Rolanski (portet from Borland C++)
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/global.h $
+Revision : $Revision: 22 $
+Last change on : $Date: 2010-05-02 21:25:02 +0400 (Вс, 02 май 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _GLOBAL_H_
+#define _GLOBAL_H_
+
+#define WINVER 0x0700
+#define _WIN32_WINNT 0x0700
+#define _WIN32_IE 0x0601
+
+#define OEMRESOURCE
+
+#define MIRANDA_VER 0x0800
+
+#ifdef _WIN32
+ #pragma warning(disable:4786)
+#endif
+
+// Windows includes
+#include <windows.h>
+#include <Windowsx.h>
+
+// Standard includes
+#include <shlobj.h>
+//#include <uxtheme.h>
+#include <commctrl.h>
+#include <stdio.h>
+#include <share.h>
+#include <time.h>
+#include <process.h>
+#include <map>
+#include <string>
+#include <Shlwapi.h>
+#include <Wingdi.h>
+#include <gdiplus.h>
+using namespace std;
+
+// Miranda IM SDK includes
+#include <win2k.h>
+#include <msapi/vsstyle.h>
+#include <msapi/vssym32.h>
+#include <newpluginapi.h> // This must be included first
+#include <m_utils.h>
+#include <m_button.h>
+#include <m_chat.h>
+#include <m_clist.h>
+#include <m_contacts.h>
+#include <m_database.h>
+#include <m_file.h>
+#include <m_imgsrvc.h>
+#include <m_langpack.h>
+#include <m_message.h>
+#include <m_netlib.h>
+#include <m_options.h>
+#include <m_png.h>
+#include <m_protosvc.h>
+#include <m_protoint.h>
+#include <m_skin.h>
+#include <m_system.h>
+
+// plugins SDK
+#include <m_folders.h>
+#include <m_updater.h>
+#include <m_HTTPServer.h>
+#include <m_ftpfile.h>
+#include "sdk/m_popup.h" //<m_popup.h>
+#include "sdk/icons.h" //from uiex icon pack
+
+// Project resources
+#include "sdk/m_sendss.h"
+#include "mir_string.h"
+#include "mir_icolib.h"
+#include "ctrl_button.h"
+#include "dlg_msgbox.h"
+#include "resource.h"
+#include "version.h"
+
+#ifdef ComboBox_SelectItemData
+ // use Workaround for MS bug ComboBox_SelectItemData;
+ #undef ComboBox_SelectItemData
+#endif
+
+#define UM_CLOSING WM_USER+1
+#define UM_EVENT WM_USER+2
+#define UM_TAB1 WM_USER+11
+
+// Generic Message Box for Errors
+#define MSGERROR(text) MessageBox(NULL, text, _T("SendSS"), MB_OK | MB_ICONERROR)
+#define MSGINFO (text) MessageBox(NULL, text, _T("SendSS"), MB_OK | MB_ICONINFORMATION)
+
+typedef struct _MGLOBAL {
+ DWORD mirandaVersion; // mirandaVersion
+ BOOLEAN PopUpExist : 1; // Popup or MS_POPUP_ADDPOPUP exist
+ BOOLEAN PopUpActionsExist : 1; // Popup++ or MS_POPUP_REGISTERACTIONS exist
+ BOOLEAN PluginHTTPExist : 1; // HTTPServer or MS_HTTP_ACCEPT_CONNECTIONS exist
+ BOOLEAN PluginFTPExist : 1; // FTPFile or MS_FTPFILE_SHAREFILE exist
+
+} MGLOBAL, *LPMGLOBAL;
+
+//---------------------------------------------------------------------------
+#define ERROR_TITLE _T("SendScreenshot - Error")
+
+// Miranda Database Key
+#define SZ_SENDSS "SendSS"
+#define MODNAME "SendSS"
+
+extern HINSTANCE hInst;
+extern MGLOBAL myGlobals;
+extern MM_INTERFACE mmi;
+extern UTF8_INTERFACE utfi;
+extern HANDLE hNetlibUser;
+
+#define PtrIsValid(p) (((p)!=0)&&(((HANDLE)(p))!=INVALID_HANDLE_VALUE))
+
+template<class _Elem>
+std::basic_string<_Elem> replace(const std::basic_string<_Elem> & Origninal, const std::basic_string<_Elem> & What, const std::basic_string<_Elem> & With)
+{
+ std::basic_string<_Elem> res;
+ size_t l = 0;
+ size_t p = 0;
+
+ for (size_t p = Origninal.find(What.c_str(), 0); p != std::basic_string<_Elem>::npos; p = Origninal.find(What.c_str(), l))
+ {
+ if (l != p)
+ res.append(Origninal.c_str() + l, p - l);
+ res.append(With);
+ l = p + What.length();
+ }
+ if (l < Origninal.length())
+ res.append(Origninal.c_str() + l);
+
+ return res;
+}
+
+#endif
+
+/*************************************************************
+ * Uinfobuttonclass module
+ */
+
+// button styles
+#define MBS_DEFBUTTON 0x00001000L // default button
+#define MBS_PUSHBUTTON 0x00002000L // toggle button
+#define MBS_FLAT 0x00004000L // flat button
+#define MBS_DOWNARROW 0x00008000L // has arrow on the right
+
+#define MBF_UNICODE 1
+#ifdef _UNICODE
+ #define MBF_TCHAR MBF_UNICODE
+#else
+ #define MBF_TCHAR 0
+#endif
+
+// BUTTONADDTOOLTIP
+// use lParam=MBF_UNICODE to set unicode tooltips
+// for lParam=0 the string is interpreted as ansi
+
+// message to explicitly translate the buttons text,
+// as it is not done by default translation routine
+// wParam=lParam=NULL
+#define BUTTONTRANSLATE (WM_USER+6)
+
+/* UserInfo/MsgBox v0.1.0.4+
+Slightly modified version of MButtonClass, to draw both text and icon in a button control
+*/
+#define UINFOBUTTONCLASS _T("UInfoButtonClass")
+
diff --git a/plugins/SendScreenshotPlus/mir_icolib.cpp b/plugins/SendScreenshotPlus/mir_icolib.cpp
new file mode 100644
index 0000000000..dc9a7ad02f
--- /dev/null
+++ b/plugins/SendScreenshotPlus/mir_icolib.cpp
@@ -0,0 +1,382 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2009 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+aLONG with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+this file is taken from UserinfoEx plugin and support UserinfoEx icon pack !!!!
+
+*/
+
+#include "global.h"
+
+
+typedef struct _ICODESC
+{
+ LPSTR pszName;
+ LPSTR pszDesc;
+ LPSTR pszSection;
+ BOOL bfromIconPack;
+ WORD idResource;
+ BYTE size;
+} ICODESC;
+
+HICON ghDefIcon = NULL;
+
+//IDI_PLUG_MAIN must be the first icon from Plugin.dll, all other icon must be IDI_PLUG_MAIN+n
+static ICODESC icoDesc[] =
+{
+ // common
+ { ICO_PLUG_SSWINDOW1, "Screenshot Icon1", SECT_COMMON, 0, IDI_PLUG_MAIN, -1 },
+ { ICO_PLUG_SSWINDOW2, "Screenshot Icon2", SECT_COMMON, 0, IDI_PLUG_ICON1, 0 },
+ { ICO_PLUG_SSTARGET, "Target Cursor", SECT_COMMON, 0, IDI_PLUG_ICON2, 1 },
+ { ICO_PLUG_SSMONITOR, "Target Desktop", SECT_COMMON, 0, IDI_PLUG_ICON3, 1 },
+ { ICO_PLUG_SSDEFAULT, "Default", SECT_COMMON, 0, IDI_PLUG_DEFAULT, 0 },
+
+ // overlays
+ { ICO_PLUG_OVERLAYON, "overlay on", SECT_OVERLAY, 0, IDI_PLUG_OVERLAYON, 0 },
+ { ICO_PLUG_OVERLAYOFF, "overlay off", SECT_OVERLAY, 0, IDI_PLUG_OVERLAYOFF,0 },
+
+ // dialogs
+// { ICO_DLG_DETAILS, "Details Infobar", SECT_DLG, 1, IDI_DLG_DETAILS, 48 },
+// { ICO_DLG_PHONE, "Phone Infobar", SECT_DLG, 1, IDI_DLG_PHONE, 1 },
+// { ICO_DLG_EMAIL, "E-Mail Infobar", SECT_DLG, 1, IDI_DLG_EMAIL, 1 },
+
+ // button icons
+ { ICO_PLUG_SSHELP, "Help", SECT_BUTTONS, 0, IDI_PLUG_HELP, 0 },
+ { ICO_PLUG_SSFOLDERO, "Open Folder", SECT_BUTTONS, 0, IDI_PLUG_FOLDERO, 0 },
+ { ICO_PLUG_SSDESKOFF, "description off", SECT_BUTTONS, 0, IDI_PLUG_DESKOFF, 0 },
+ { ICO_PLUG_SSDESKON, "description on", SECT_BUTTONS, 0, IDI_PLUG_DESKON, 0 },
+ { ICO_PLUG_SSDELOFF, "delete off", SECT_BUTTONS, 0, IDI_PLUG_DELOFF, 0 },
+ { ICO_PLUG_SSDELON, "delete on", SECT_BUTTONS, 0, IDI_PLUG_DELON, 0 },
+ { ICO_PLUG_ARROWL, "Prev", SECT_BUTTONS, 0, IDI_PLUG_ARROWL, 0 },
+ { ICO_PLUG_ARROWR, "Next", SECT_BUTTONS, 0, IDI_PLUG_ARROWR, 0 },
+
+ { ICO_BTN_UPDATE, "Update", SECT_BUTTONS, 1, IDI_BTN_UPDATE, 0 },
+ { ICO_BTN_OK, "Ok", SECT_BUTTONS, 1, IDI_BTN_OK, 0 },
+ { ICO_BTN_CANCEL, "Cancel", SECT_BUTTONS, 1, IDI_BTN_CLOSE, 0 },
+ { ICO_BTN_APPLY, "Apply", SECT_BUTTONS, 1, IDI_BTN_APPLY, 0 },
+// { ICO_BTN_GOTO, "Goto", SECT_BUTTONS, 1, IDI_BTN_GOTO, 0 },
+// { ICO_BTN_EMAIL, "e-mail", SECT_BUTTONS, 1, IDI_BTN_EMAIL, 0 },
+// { ICO_BTN_DOWNARROW, "Down arrow", SECT_BUTTONS, 1, IDI_BTN_DOWNARROW, 0 },
+// { ICO_BTN_ADD, "Add", SECT_BUTTONS, 1, IDI_BTN_ADD, 0 },
+ { ICO_BTN_EDIT, "Edit", SECT_BUTTONS, 1, IDI_BTN_EDIT, 0 },
+// { ICO_BTN_DELETE, "Delete", SECT_BUTTONS, 1, IDI_BTN_DELETE, 0 },
+// { ICO_BTN_SEARCH, "Search", SECT_BUTTONS, 1, IDI_SEARCH, 0 },
+// { ICO_BTN_YES, "Yes", SECT_BUTTONS, 1, IDI_BTN_YES, 0 },
+// { ICO_BTN_NO, "No", SECT_BUTTONS, 1, IDI_BTN_NO, 0 },
+// { ICO_BTN_IGNORE, "Ignore", SECT_BUTTONS, 1, IDI_BTN_IGNORE, 0 },
+
+};
+
+/**
+ * This function finds the default iconpack file and return its path.
+ *
+ * @param - none
+ *
+ * @return This function returns the relative path to an existing icon pack.
+ **/
+LPTSTR IcoLib_GetDefaultIconFileName()
+{
+ static LPTSTR path[] = {
+ _T("Icons\\uinfoex_icons.dll"),
+ _T("Plugins\\uinfoex_icons.dll"),
+ _T("Customize\\Icons\\uinfoex_icons.dll")
+ };
+ TCHAR absolute[MAX_PATH];
+
+ for (INT i = 0; i < SIZEOF(path); i++)
+ {
+ CallService(MS_UTILS_PATHTOABSOLUTET, (WPARAM)path[i], (LPARAM)absolute);
+ if (PathFileExists(absolute))
+ {
+ return path[i];
+ }
+ }
+ return NULL;
+}
+
+/**
+ * This function checks the version of an iconpack.
+ * If the icon pack's version differs from the desired one,
+ * dialog with a warning is displayed.
+ *
+ * @param szIconPack - This is the path to the icon pack.
+ * It can be absolute or relative.
+ *
+ * @return nothing
+ **/
+static VOID IcoLib_CheckIconPackVersion(LPTSTR szIconPack)
+{
+ //if (DB::Setting::GetByte(SET_ICONS_CHECKFILEVERSION, TRUE))
+ if (DBGetContactSettingByte(NULL,MODNAME,SET_ICONS_CHECKFILEVERSION, TRUE))
+ {
+ if (szIconPack)
+ {
+ TCHAR szAbsolutePath[MAX_PATH];
+ HMODULE hIconDll;
+
+ CallService(MS_UTILS_PATHTOABSOLUTET, (WPARAM)szIconPack, (LPARAM)szAbsolutePath);
+
+ hIconDll = LoadLibrary(szAbsolutePath);
+ if (hIconDll)
+ {
+ CHAR szFileVersion[64];
+
+ if (!LoadStringA(hIconDll, IDS_ICOPACKVERSION, szFileVersion, sizeof(szFileVersion)) ||
+ mir_strcmp(szFileVersion, "__UserInfoEx_IconPack_1.2__"))
+ {
+ MsgErr(NULL, LPGENT("Warning: Your current IconPack's version differs from the one UserInfoEx is designed for.\nSome icons may not be displayed correctly"));
+ }
+ FreeLibrary(hIconDll);
+ }
+ }
+ else
+ {
+ MsgErr(NULL, LPGENT("Warning: No IconPack found in one of the following directories: 'customize\\icons', 'icons' or 'plugins'!"));
+ }
+ }
+}
+
+/**
+ * Returns a icon, identified by a name
+ *
+ * @param pszIcon - name of the icon
+ *
+ * @return: HICON if the icon is loaded, NULL otherwise
+ **/
+HICON IcoLib_GetIcon(LPCSTR pszIcon, bool big)
+{
+ return (pszIcon) ? (HICON)CallService(MS_SKIN2_GETICON, (WPARAM)big, (LPARAM) pszIcon) : NULL;
+}
+
+/**
+ * Returns a icon, identified by a name
+ *
+ * @param hIconItem - this is the pointer to an IconItem structure in icolib.
+ *
+ * @return: HICON if the icon is loaded, NULL otherwise
+ **/
+HICON IcoLib_GetIconByHandle(HANDLE hIconItem, bool big)
+{
+ return (HICON)CallService(MS_SKIN2_GETICONBYHANDLE, (WPARAM)big, (LPARAM) hIconItem);
+}
+
+/**
+ * Set the icon of each control in the list
+ *
+ * @param hDlg - handle to the dialog control, that owns the controls
+ * @param pCtrl - list to all controls and its icon names
+ * @param numCtrls - number of elements in the pCtrl list
+ *
+ * @return nothing
+ **/
+VOID IcoLib_SetCtrlIcons(HWND hDlg, const ICONCTRL* pCtrl, BYTE numCtrls)
+{
+ HICON hIcon;
+ BYTE i;
+ HWND hCtrl;
+
+ for (i = 0; i < numCtrls; i++)
+ {
+ hIcon = IcoLib_GetIcon(pCtrl[i].pszIcon);
+ if (pCtrl[i].idCtrl)
+ {
+ hCtrl = GetDlgItem(hDlg, pCtrl[i].idCtrl);
+ switch (pCtrl[i].Message)
+ {
+ case STM_SETICON:
+ case STM_SETIMAGE:
+ {
+ ShowWindow(hCtrl, hIcon ? SW_SHOW : SW_HIDE);
+ }
+ case BM_SETIMAGE:
+ {
+ SendMessage(hCtrl, pCtrl[i].Message, IMAGE_ICON, (LPARAM) hIcon);
+ }
+ }
+ }
+ else
+ {
+ SendMessage(hDlg, pCtrl[i].Message, ICON_BIG, (LPARAM) hIcon);
+ }
+ }
+}
+
+/**
+ * This function manually registers a single icon from the default icon library.
+ *
+ * @param szIconID - This is the uniquely identifying string for an icon.
+ * This string is the setting name in the database and should
+ * only use ASCII characters.
+ * @param szDescription - This is the description displayed in the options dialog.
+ * @param szSection - This is the subsection, where the icon is organized in the options dialog.
+ * @param szDefaultFile - This is the validated path to the default icon file.
+ * @param idIcon - This is the ResourceID of the icon in the default file.
+ * @param Size - This is the desired size of the icon to load.
+ * 0: default size for small icons (16x16)
+ * 1: default size for normal icons (32x32)
+ * @param hDefIcon - This is the default icon to use if the default icon
+ * file does not exist and no custom icon is set up in the config.
+ *
+ * @return This function returns the HANDLE of the icon item.
+ **/
+static HANDLE IcoLib_RegisterIconHandleEx(LPSTR szIconID, LPSTR szDescription, LPSTR szSection, LPTSTR szDefaultFile, INT idIcon, INT Size, HICON hDefIcon)
+{
+ HANDLE hIconHandle = NULL;
+
+ if (szIconID && szDescription && szSection)
+ {
+ SKINICONDESC sid;
+
+ ZeroMemory(&sid, sizeof(sid));
+ sid.cbSize = sizeof(sid);
+ sid.flags = SIDF_ALL_TCHAR;
+ sid.pszName = szIconID;
+ sid.ptszDescription = mir_a2t(szDescription);
+ sid.ptszSection = mir_a2t(szSection);
+
+ if (sid.ptszDescription && sid.ptszSection)
+ {
+ switch (Size)
+ {
+ // small and big icons
+ case -1:
+ {
+ sid.cx = sid.cy = 0;
+ break;
+ }
+ // small icons (16x16)
+ case 0:
+ {
+ sid.cx = GetSystemMetrics(SM_CXSMICON);
+ sid.cy = GetSystemMetrics(SM_CYSMICON);
+ break;
+ }
+ // normal icons (32x32)
+ case 1:
+ {
+ sid.cx = GetSystemMetrics(SM_CXICON);
+ sid.cy = GetSystemMetrics(SM_CYICON);
+ break;
+ }
+ // custom icon size
+ default:
+ {
+ sid.cx = sid.cy = Size;
+ break;
+ }
+ }
+
+ sid.ptszDefaultFile = szDefaultFile;
+ if (sid.ptszDefaultFile && sid.ptszDefaultFile[0])
+ {
+ if(idIcon < IDI_FIRST_ICON || idIcon > IDI_LASTICON) {
+ // Icon from Plugin.dll
+ sid.iDefaultIndex = idIcon - IDI_PLUG_MAIN;
+ }
+ else{
+ //UserinfoEx Icon pack
+ sid.iDefaultIndex = ICONINDEX(idIcon);
+ }
+ }
+ else
+ {
+ sid.hDefaultIcon = hDefIcon;
+ sid.iDefaultIndex = -1;
+ }
+ hIconHandle = (HANDLE) CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
+ }
+ mir_freeAndNil(sid.ptszDescription);
+ mir_freeAndNil(sid.ptszSection);
+ }
+ return hIconHandle;
+}
+
+/**
+ * This function manually registers a single icon from the default icon library.
+ *
+ * @param szIconID - This is the uniquely identifying string for an icon.
+ * This string is the setting name in the database and should
+ * only use ASCII characters.
+ * @param szDescription - This is the description displayed in the options dialog.
+ * @param szSection - This is the subsection, where the icon is organized in the options dialog.
+ * @param idIcon - This is the ResourceID of the icon in the default file
+ * @param Size - This is the desired size of the icon to load.
+ * 0: default size for small icons (16x16)
+ * 1: default size for normal icons (32x32)
+ *
+ * @return This function returns the HANDLE of the icon item.
+ **/
+HANDLE IcoLib_RegisterIconHandle(LPSTR szIconID, LPSTR szDescription, LPSTR szSection, INT idIcon, INT Size)
+{
+ return IcoLib_RegisterIconHandleEx(szIconID, szDescription, szSection, IcoLib_GetDefaultIconFileName(), idIcon, Size, ghDefIcon);
+}
+
+/**
+ * This function manually registers a single icon from the default icon library.
+ *
+ * @param szIconID - This is the uniquely identifying string for an icon.
+ * This string is the setting name in the database and should
+ * only use ASCII characters.
+ * @param szDescription - This is the description displayed in the options dialog.
+ * @param szSection - This is the subsection, where the icon is organized in the options dialog.
+ * @param idIcon - This is the ResourceID of the icon in the default file
+ * @param Size - This is the desired size of the icon to load.
+ * 0: default size for small icons (16x16)
+ * 1: default size for normal icons (32x32)
+ *
+ * @return This function returns the HICON of the icon itself.
+ **/
+HICON IcoLib_RegisterIcon(LPSTR szIconID, LPSTR szDescription, LPSTR szSection, INT idIcon, INT Size)
+{
+ return IcoLib_GetIconByHandle(IcoLib_RegisterIconHandle(szIconID, szDescription, szSection, idIcon, Size));
+}
+
+/**
+ * Add default icons to the skin library or load customized icons
+ *
+ * @param none
+ *
+ * @return nothing
+ **/
+VOID IcoLib_LoadModule()
+{
+ LPTSTR szDefaultFile;
+ LPTSTR szPluginFile;
+ INT_PTR i;
+
+ // search for default icon file
+ szDefaultFile = IcoLib_GetDefaultIconFileName();
+ IcoLib_CheckIconPackVersion(szDefaultFile);
+
+ szPluginFile = _T("Plugins\\")_T(__FILENAME);
+
+ // load default icon if required
+ ghDefIcon = (HICON)LoadImage(hInst, MAKEINTRESOURCE(IDI_PLUG_DEFAULT), IMAGE_ICON,
+ GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
+
+ for (i = 0; i < SIZEOF(icoDesc); i++)
+ {
+ IcoLib_RegisterIconHandleEx(
+ icoDesc[i].pszName, icoDesc[i].pszDesc, icoDesc[i].pszSection,
+ icoDesc[i].bfromIconPack ? szDefaultFile : szPluginFile, icoDesc[i].idResource, icoDesc[i].size, ghDefIcon);
+ }
+}
+
diff --git a/plugins/SendScreenshotPlus/mir_icolib.h b/plugins/SendScreenshotPlus/mir_icolib.h
new file mode 100644
index 0000000000..b80c014a07
--- /dev/null
+++ b/plugins/SendScreenshotPlus/mir_icolib.h
@@ -0,0 +1,139 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2009 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+aLONG with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef _UINFOEX_ICONS_H_INCLUDED_
+#define _UINFOEX_ICONS_H_INCLUDED_ 1
+
+#include "m_icolib.h"
+
+// sections
+#define SECT_COMMON MODNAME
+#define SECT_DLG MODNAME"/Dialogs"
+#define SECT_BUTTONS MODNAME"/Buttons"
+#define SECT_OVERLAY MODNAME"/overlays"
+#define SECT_TOOLBAR "ToolBar" // global toolbar section as used by modern clist
+
+// icons
+#define ICO_PLUG_SSWINDOW1 MODNAME"_plug_SSwindow1"
+#define ICO_PLUG_SSWINDOW2 MODNAME"_plug_SSwindow2"
+#define ICO_PLUG_SSMONITOR MODNAME"_plug_SSmonitor"
+#define ICO_PLUG_SSDEFAULT MODNAME"_plug_SSdefault"
+#define ICO_PLUG_SSTARGET MODNAME"_plug_SSTarget"
+#define ICO_PLUG_SSHELP MODNAME"_plug_SSHelp"
+#define ICO_PLUG_SSFOLDERO MODNAME"_plug_SSFolderOpen"
+#define ICO_PLUG_ARROWL MODNAME"_plug_SSArrowL"
+#define ICO_PLUG_ARROWR MODNAME"_plug_SSArrowR"
+#define ICO_PLUG_SSDESKOFF MODNAME"_plug_SSDeskOff"
+#define ICO_PLUG_SSDESKON MODNAME"_plug_SSDeskOn"
+#define ICO_PLUG_SSDELOFF MODNAME"_plug_SSDelOff"
+#define ICO_PLUG_SSDELON MODNAME"_plug_SSDelOn"
+
+#define ICO_PLUG_OVERLAYOFF MODNAME"_plug_SSOverlayOff"
+#define ICO_PLUG_OVERLAYON MODNAME"_plug_SSOverlayOn"
+
+#define ICO_COMMON_IM MODNAME"_common_im"
+#define ICO_COMMON_FEMALE MODNAME"_common_female"
+#define ICO_COMMON_MALE MODNAME"_common_male"
+#define ICO_COMMON_CLOCK MODNAME"_common_clock"
+#define ICO_COMMON_MARITAL MODNAME"_common_marital"
+#define ICO_COMMON_PASSWORD MODNAME"_common_password"
+#define ICO_COMMON_ADDRESS MODNAME"_common_address"
+#define ICO_TREE_DEFAULT MODNAME"_tree_default"
+#define ICO_DLG_DETAILS MODNAME"_dlg_details"
+#define ICO_DLG_PHONE MODNAME"_dlg_phone"
+#define ICO_DLG_EMAIL MODNAME"_dlg_email"
+#define ICO_DLG_EXPORT MODNAME"_dlg_export"
+#define ICO_DLG_IMPORT MODNAME"_dlg_import"
+#define ICO_DLG_SEARCH MODNAME"_dlg_search"
+#define ICO_LST_MODULES MODNAME"_lst_modules"
+#define ICO_LST_FOLDER MODNAME"_lst_folder"
+#define ICO_BTN_UPDATE MODNAME"_btn_update"
+#define ICO_BTN_OK MODNAME"_btn_ok"
+#define ICO_BTN_CANCEL MODNAME"_btn_cancel"
+#define ICO_BTN_APPLY MODNAME"_btn_apply"
+#define ICO_BTN_GOTO MODNAME"_btn_goto"
+#define ICO_BTN_ADD MODNAME"_btn_add"
+#define ICO_BTN_EDIT MODNAME"_btn_edit"
+#define ICO_BTN_DELETE MODNAME"_btn_delete"
+#define ICO_BTN_IMPORT MODNAME"_btn_import"
+#define ICO_BTN_EXPORT MODNAME"_btn_export"
+#define ICO_BTN_NOTES MODNAME"_btn_notes"
+#define ICO_BTN_ABOUT MODNAME"_btn_about"
+#define ICO_BTN_PROFILE MODNAME"_btn_profile"
+#define ICO_BTN_DOWNARROW MODNAME"_btn_downarrow"
+#define ICO_BTN_PHONE MODNAME"_btn_phone"
+#define ICO_BTN_FAX MODNAME"_btn_fax"
+#define ICO_BTN_CELLULAR MODNAME"_btn_cellular"
+#define ICO_BTN_EMAIL MODNAME"_btn_email"
+#define ICO_BTN_SEARCH MODNAME"_btn_search"
+#define ICO_BTN_YES MODNAME"_btn_yes"
+#define ICO_BTN_NO MODNAME"_btn_no"
+#define ICO_BTN_IGNORE MODNAME"_btn_ignore"
+
+#define ICO_RMD_DTB0 MODNAME"_rmd_dtb0"
+#define ICO_RMD_DTB1 MODNAME"_rmd_dtb1"
+#define ICO_RMD_DTB2 MODNAME"_rmd_dtb2"
+#define ICO_RMD_DTB3 MODNAME"_rmd_dtb3"
+#define ICO_RMD_DTB4 MODNAME"_rmd_dtb4"
+#define ICO_RMD_DTB5 MODNAME"_rmd_dtb5"
+#define ICO_RMD_DTB6 MODNAME"_rmd_dtb6"
+#define ICO_RMD_DTB7 MODNAME"_rmd_dtb7"
+#define ICO_RMD_DTB8 MODNAME"_rmd_dtb8"
+#define ICO_RMD_DTB9 MODNAME"_rmd_dtb9"
+#define ICO_RMD_DTBX MODNAME"_rmd_dtbx"
+
+#define ICO_RMD_DTA0 MODNAME"_rmd_dta0"
+#define ICO_RMD_DTA1 MODNAME"_rmd_dta1"
+#define ICO_RMD_DTA2 MODNAME"_rmd_dta2"
+#define ICO_RMD_DTA3 MODNAME"_rmd_dta3"
+#define ICO_RMD_DTA4 MODNAME"_rmd_dta4"
+#define ICO_RMD_DTA5 MODNAME"_rmd_dta5"
+#define ICO_RMD_DTA6 MODNAME"_rmd_dta6"
+#define ICO_RMD_DTA7 MODNAME"_rmd_dta7"
+#define ICO_RMD_DTA8 MODNAME"_rmd_dta8"
+#define ICO_RMD_DTA9 MODNAME"_rmd_dta9"
+#define ICO_RMD_DTAX MODNAME"_rmd_dtax"
+
+#define SET_ICONS_CHECKFILEVERSION "CheckIconPackVersion"
+#define SET_ICONS_BUTTONS "ButtonIcons"
+
+#define ICONINDEX(id) max((min((id), IDI_LASTICON)) - IDI_FIRST_ICON, 0)
+
+typedef struct TIconCtrl
+{
+ LPCSTR pszIcon;
+ UINT Message;
+ WORD idCtrl;
+} ICONCTRL, *LPICONCTRL;
+
+LPTSTR IcoLib_GetDefaultIconFileName();
+VOID IcoLib_SetCtrlIcons(HWND hDlg, const ICONCTRL* pCtrl, BYTE numCtrls);
+
+HANDLE IcoLib_RegisterIconHandle(LPSTR szName, LPSTR szDescription, LPSTR szSection, INT idIcon, INT Size);
+HICON IcoLib_RegisterIcon(LPSTR szName, LPSTR szDescription, LPSTR szSection, INT idIcon, INT Size);
+HICON IcoLib_GetIcon(LPCSTR pszIcon, bool big = false);
+HICON IcoLib_GetIconByHandle(HANDLE hIconItem, bool big = false);
+
+VOID IcoLib_LoadModule();
+
+#endif /* _UINFOEX_ICONS_H_INCLUDED_ */
diff --git a/plugins/SendScreenshotPlus/mir_string.cpp b/plugins/SendScreenshotPlus/mir_string.cpp
new file mode 100644
index 0000000000..0ee154b7b9
--- /dev/null
+++ b/plugins/SendScreenshotPlus/mir_string.cpp
@@ -0,0 +1,179 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+from UserInfoEx Plugin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/mir_string.cpp $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#include "global.h"
+#include "mir_string.h"
+
+char *mir_strncpy(char *pszDest, const char *pszSrc, const size_t cchDest)
+{
+ if (!pszDest || !pszSrc || !cchDest)
+ return NULL;
+ pszDest = strncpy(pszDest, pszSrc, cchDest-1);
+ pszDest[cchDest-1] = 0;
+ return pszDest;
+}
+
+wchar_t *mir_wcsncpy(wchar_t *pszDest, const wchar_t *pszSrc, const size_t cchDest)
+{
+ if (!pszDest || !pszSrc || !cchDest)
+ return NULL;
+ pszDest = wcsncpy(pszDest, pszSrc, cchDest-1);
+ pszDest[cchDest-1] = 0;
+ return pszDest;
+}
+
+char *mir_strncat(char *pszDest, const char *pszSrc, const size_t cchDest)
+{
+ if (!pszDest || !pszSrc || !cchDest)
+ return NULL;
+ strncat(pszDest, pszSrc, cchDest-1);
+ pszDest[cchDest-1] = 0;
+ return pszDest;
+}
+
+wchar_t *mir_wcsncat(wchar_t *pszDest, const wchar_t *pszSrc, const size_t cchDest)
+{
+ if (!pszDest || !pszSrc || !cchDest)
+ return NULL;
+ pszDest = wcsncat(pszDest, pszSrc, cchDest-1);
+ pszDest[cchDest-1] = 0;
+ return pszDest;
+}
+
+char *mir_strncat_c(char *pszDest, const char cSrc) {
+ size_t lenNew = strlen(pszDest) + 2;
+ if (!pszDest)
+ pszDest = (char *) mir_alloc(sizeof(char) * lenNew);
+ else
+ pszDest = (char *) mir_realloc(pszDest, sizeof(char) * lenNew);
+ pszDest[lenNew-2] = cSrc;
+ pszDest[lenNew-1] = 0;
+ return pszDest;
+}
+
+wchar_t *mir_wcsncat_c(wchar_t *pwszDest, const wchar_t wcSrc) {
+ size_t lenNew = wcslen(pwszDest) + 2;
+ if (!pwszDest)
+ pwszDest = (wchar_t *) mir_alloc(sizeof(wchar_t) * lenNew);
+ else
+ pwszDest = (wchar_t *) mir_realloc(pwszDest, sizeof(wchar_t) * lenNew);
+ pwszDest[lenNew-2] = wcSrc;
+ pwszDest[lenNew-1] = 0;
+ return pwszDest;
+}
+
+char *mir_strnerase(char *pszDest, size_t sizeFrom, size_t sizeTo) {
+ char *pszReturn = NULL;
+ size_t sizeNew, sizeLen = strlen(pszDest);
+ if (sizeFrom >= 0 && sizeFrom < sizeLen && sizeTo >= 0 && sizeTo <= sizeLen && sizeFrom < sizeTo) {
+ sizeNew = sizeLen - (sizeTo - sizeFrom);
+ size_t sizeCopy = sizeNew - sizeFrom;
+ pszReturn = (char *) mir_alloc(sizeNew + 1);
+ memcpy(pszReturn, pszDest, sizeFrom);
+ memcpy(pszReturn + sizeFrom, pszDest + sizeTo, sizeCopy);
+ pszReturn[sizeNew] = 0;
+ }
+
+ pszDest = (char *) mir_realloc(pszDest, sizeNew + 1);
+ pszDest = mir_strcpy(pszDest, pszReturn);
+ mir_free(pszReturn);
+ return pszDest;
+}
+
+size_t mir_vsnwprintf(wchar_t *pszDest, const size_t cchDest, const wchar_t *pszFormat, va_list& argList)
+{
+ size_t iRet, cchMax;
+
+ if (!pszDest || !pszFormat || !*pszFormat)
+ return -1;
+
+ cchMax = cchDest - 1;
+ iRet = _vsnwprintf(pszDest, cchMax, pszFormat, argList);
+ if (iRet < 0) pszDest[0] = 0;
+ else if (iRet >= cchMax) {
+ pszDest[cchMax] = 0;
+ iRet = cchMax;
+ }
+ return iRet;
+}
+
+size_t mir_snwprintf(wchar_t *pszDest, const size_t cchDest, const wchar_t *pszFormat, ...)
+{
+ size_t iRet;
+ va_list argList;
+
+ va_start(argList, pszFormat);
+ iRet = mir_vsnwprintf(pszDest, cchDest, pszFormat, argList);
+ va_end(argList);
+ return iRet;
+}
+
+//---------------------------------------------------------------------------
+void mir_stradd(char* &pszDest, const char *pszSrc)
+{
+ if(!pszSrc) {
+ return;
+ }
+ else if(!pszDest) {
+ pszDest = mir_strdup(pszSrc);
+ }
+ else {
+ size_t lenDest = strlen(pszDest);
+ size_t lenSrc = strlen(pszSrc);
+ size_t lenNew = lenDest + lenSrc + 1;
+ pszDest = (char *) mir_realloc(pszDest, sizeof(char)* lenNew);
+
+ strcpy(pszDest + lenDest, pszSrc);
+ pszDest[lenNew-1] = 0;
+ }
+}
+
+void mir_wcsadd(wchar_t* &pszDest, const wchar_t *pszSrc)
+{
+ if(!pszSrc) {
+ return;
+ }
+ else if(!pszDest) {
+ pszDest = mir_wstrdup(pszSrc);
+ }
+ else {
+ size_t lenDest = wcslen(pszDest);
+ size_t lenSrc = wcslen(pszSrc);
+ size_t lenNew = lenDest + lenSrc + 1;
+ pszDest = (wchar_t *) mir_realloc(pszDest, sizeof(wchar_t)*lenNew);
+
+ wcscpy(pszDest + lenDest, pszSrc);
+ pszDest[lenNew-1] = 0;
+ }
+}
+
diff --git a/plugins/SendScreenshotPlus/mir_string.h b/plugins/SendScreenshotPlus/mir_string.h
new file mode 100644
index 0000000000..11f8276d1b
--- /dev/null
+++ b/plugins/SendScreenshotPlus/mir_string.h
@@ -0,0 +1,129 @@
+/*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+Copyright 2000-2009 Miranda ICQ/IM project,
+
+This file is part of Send Screenshot Plus, a Miranda IM plugin.
+Copyright (c) 2010 Ing.U.Horn
+
+Parts of this file based on original sorce code
+from UserInfoEx Plugin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+File name : $HeadURL: http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSSPlus/mir_string.h $
+Revision : $Revision: 13 $
+Last change on : $Date: 2010-04-02 02:54:30 +0400 (Пт, 02 апр 2010) $
+Last change by : $Author: ing.u.horn $
+
+*/
+
+#ifndef _MIR_STRING_H_INCLUDED_
+#define _MIR_STRING_H_INCLUDED_
+
+class _A2T
+{
+ public:
+ _A2T(const char* s) :
+ buf(mir_a2t(s))
+ {}
+
+ _A2T(const char* s, int cp) :
+ buf(mir_a2t_cp(s, cp))
+ {}
+
+ ~_A2T()
+ { mir_free(buf);
+ }
+
+ __inline operator TCHAR*() const
+ { return buf;
+ }
+
+ private: TCHAR* buf;
+};
+
+#define mir_wcsdup mir_wstrdup
+
+#ifdef _UNICODE
+ #define mir_tcslen mir_wcslen
+ #define mir_tcscpy mir_wcscpy
+ #define mir_tcsncpy mir_wcsncpy
+ #define mir_tcsncat mir_wcsncat
+ #define mir_tcsdup mir_wcsdup
+ #define mir_tcscmp mir_wcscmp
+ #define mir_tcsncmp mir_wcsncmp
+ #define mir_tcsicmp mir_wcsicmp
+ #define mir_tcsnicmp mir_wcsnicmp
+ #define mir_tcschr mir_wcschr
+ #define mir_tcsrchr mir_wcsrchr
+ #define mir_tcsncat_c mir_wcsncat_c
+ #define mir_tcsadd mir_wcsadd
+#else
+ #define mir_tcslen mir_strlen
+ #define mir_tcscpy mir_strcpy
+ #define mir_tcsncpy mir_strncpy
+ #define mir_tcsncat mir_strncat
+ #define mir_tcsdup mir_strdup
+ #define mir_tcscmp mir_strcmp
+ #define mir_tcsncmp mir_strncmp
+ #define mir_tcsicmp mir_stricmp
+ #define mir_tcsnicmp mir_strnicmp
+ #define mir_tcschr mir_strchr
+ #define mir_tcsrchr mir_strrchr
+ #define mir_tcsncat_c mir_strncat_c
+ #define mir_tcsadd mir_stradd
+#endif
+
+
+#define mir_strlen(s) (((s)!=0)?strlen(s):0)
+#define mir_strcpy(d,s) (((s)!=0&&(d)!=0)?strcpy(d,s):0)
+#define mir_strcmp(s1,s2) ((s1)==0||(s2)==0||strcmp((s1),(s2)))
+#define mir_strncmp(s1,s2,n) ((s1)==0||(s2)==0||strncmp((s1),(s2),(n)))
+#define mir_stricmp(s1,s2) ((s1)==0||(s2)==0||_stricmp((s1),(s2)))
+#define mir_strnicmp(s1,s2,n) ((s1)==0||(s2)==0||_strnicmp((s1),(s2),(n)))
+#define mir_strchr(s,c) (((s)!=0)?strchr((s),(c)):0)
+#define mir_strrchr(s,c) (((s)!=0)?strrchr((s),(c)):0)
+
+#define mir_wcslen(s) (((s)!=0)?wcslen(s):0)
+#define mir_wcscpy(d,s) (((s)!=0&&(d)!=0)?wcscpy(d,s):0)
+#define mir_wcscmp(s1,s2) ((s1)==0||(s2)==0||wcscmp((s1),(s2)))
+#define mir_wcsncmp(s1,s2,n) ((s1)==0||(s2)==0||wcsncmp((s1),(s2),(n)))
+#define mir_wcsicmp(s1,s2) ((s1)==0||(s2)==0||_wcsicmp((s1),(s2)))
+#define mir_wcsnicmp(s1,s2,n) ((s1)==0||(s2)==0||_wcsnicmp((s1),(s2),(n)))
+#define mir_wcschr(s,c) (((s)!=0)?wcschr((s),(c)):0)
+#define mir_wcsrchr(s,c) (((s)!=0)?wcsrchr((s),(c)):0)
+
+//#define mir_free(ptr) (if (x) mmi.free(x); *(&(x)) = 0;}
+#define mir_freeAndNil(ptr) {if(ptr) mir_free(ptr); ptr = NULL;}
+
+char * mir_strncpy(char *pszDest, const char *pszSrc, const size_t cchDest);
+wchar_t * mir_wcsncpy(wchar_t *pszDest, const wchar_t *pszSrc, const size_t cchDest);
+
+char * mir_strncat(char *pszDest, const char *pszSrc, const size_t cchDest);
+wchar_t * mir_wcsncat(wchar_t *pszDest, const wchar_t *pszSrc, const size_t cchDest);
+
+char * mir_strncat_c(char *pszDest, const char cSrc);
+char * mir_wcsncat_c(char *pszDest, const char cSrc);
+
+size_t mir_vsnwprintf(wchar_t *pszDest, const size_t cchDest, const wchar_t *pszFormat, va_list& argList);
+size_t mir_snwprintf(wchar_t *pszDest, const size_t cchDest, const wchar_t *pszFormat, ...);
+
+char * mir_strnerase(char *pszDest, size_t sizeFrom, size_t sizeTo);
+
+void mir_stradd(char * &pszDest, const char *pszSrc);
+void mir_wcsadd(wchar_t * &pszDest, const wchar_t *pszSrc);
+
+#endif /* _MIR_STRING_H_INCLUDED_ */ \ No newline at end of file
diff --git a/plugins/SendScreenshotPlus/res/UEditForm_nvr_1.bmp b/plugins/SendScreenshotPlus/res/UEditForm_nvr_1.bmp
new file mode 100644
index 0000000000..d25117bb9b
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/UEditForm_nvr_1.bmp
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/UEditForm_nvr_2.bmp b/plugins/SendScreenshotPlus/res/UEditForm_nvr_2.bmp
new file mode 100644
index 0000000000..3427b7875f
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/UEditForm_nvr_2.bmp
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/credits.txt b/plugins/SendScreenshotPlus/res/credits.txt
new file mode 100644
index 0000000000..122042be3b
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/credits.txt
@@ -0,0 +1,10 @@
+Special thanks to Michael Kunz aka "Protogenes"
+for helping me with 1001 tips and suggestions
+to design the program code.
+http://www-user.tu-chemnitz.de/~kunmi/?dbx_tree&lang=de
+
+Thanks to the "UserinfoEx" programmers group
+for the nice button class code.
+http://code.google.com/p/userinfoex/
+
+and special thanks to all beta-testers...
diff --git a/plugins/SendScreenshotPlus/res/license.txt b/plugins/SendScreenshotPlus/res/license.txt
new file mode 100644
index 0000000000..c5ebcce31f
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/license.txt
@@ -0,0 +1,15 @@
+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.
+
+You should have received a copy of the GNU General
+Public License along with this program; if not, write to the
+Free Software Foundation, Inc.,
+675 Mass Ave, Cambridge, MA 02139, USA.
diff --git a/plugins/SendScreenshotPlus/res/overlay_disabled.ico b/plugins/SendScreenshotPlus/res/overlay_disabled.ico
new file mode 100644
index 0000000000..69ba107250
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/overlay_disabled.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/overlay_enabled.ico b/plugins/SendScreenshotPlus/res/overlay_enabled.ico
new file mode 100644
index 0000000000..389f1c4945
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/overlay_enabled.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssArrow_Left.ico b/plugins/SendScreenshotPlus/res/ssArrow_Left.ico
new file mode 100644
index 0000000000..917ac2734d
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssArrow_Left.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssArrow_Right.ico b/plugins/SendScreenshotPlus/res/ssArrow_Right.ico
new file mode 100644
index 0000000000..53f65a295f
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssArrow_Right.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssCamera_1.ico b/plugins/SendScreenshotPlus/res/ssCamera_1.ico
new file mode 100644
index 0000000000..908327790e
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssCamera_1.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssCamera_2.ico b/plugins/SendScreenshotPlus/res/ssCamera_2.ico
new file mode 100644
index 0000000000..c480cfebc2
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssCamera_2.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssDefault.ico b/plugins/SendScreenshotPlus/res/ssDefault.ico
new file mode 100644
index 0000000000..8b3af75f05
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssDefault.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssDelOff.ico b/plugins/SendScreenshotPlus/res/ssDelOff.ico
new file mode 100644
index 0000000000..12816c8966
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssDelOff.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssDelOn.ico b/plugins/SendScreenshotPlus/res/ssDelOn.ico
new file mode 100644
index 0000000000..4aeb63226f
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssDelOn.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssDeskOff.ico b/plugins/SendScreenshotPlus/res/ssDeskOff.ico
new file mode 100644
index 0000000000..b3dcb08226
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssDeskOff.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssDeskOn.ico b/plugins/SendScreenshotPlus/res/ssDeskOn.ico
new file mode 100644
index 0000000000..aa853d0b2f
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssDeskOn.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssMonitor.ico b/plugins/SendScreenshotPlus/res/ssMonitor.ico
new file mode 100644
index 0000000000..93c9150e47
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssMonitor.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssOpen.ico b/plugins/SendScreenshotPlus/res/ssOpen.ico
new file mode 100644
index 0000000000..735bf034b3
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssOpen.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/ssTarget.ico b/plugins/SendScreenshotPlus/res/ssTarget.ico
new file mode 100644
index 0000000000..d69801cd5b
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/ssTarget.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/res/sshelp.ico b/plugins/SendScreenshotPlus/res/sshelp.ico
new file mode 100644
index 0000000000..63161b4c2b
--- /dev/null
+++ b/plugins/SendScreenshotPlus/res/sshelp.ico
Binary files differ
diff --git a/plugins/SendScreenshotPlus/resource.h b/plugins/SendScreenshotPlus/resource.h
new file mode 100644
index 0000000000..6818f5b23f
--- /dev/null
+++ b/plugins/SendScreenshotPlus/resource.h
@@ -0,0 +1,102 @@
+//{{NO_DEPENDENCIES}}
+// Microsoft Visual C++ generated include file.
+// Used by resource.rc
+//
+#define IDOK 1
+#define IDA_btnClose 1
+#define IDCANCEL 2
+#define IDB_Bmp1 2
+#define IDABORT 3
+#define IDB_Bmp2 3
+#define IDRETRY 4
+#define IDIGNORE 5
+#define IDYES 6
+#define IDNO 7
+#define IDCLOSE 8
+#define IDHELP 9
+#define IDTRYAGAIN 10
+#define IDCONTINUE 11
+#define IDALL 21
+#define IDD_UMainForm 101
+#define MAIN 102
+#define IDR_LICENSE 103
+#define IDD_UMain_CaptureWindow 107
+#define IDD_CAPTURE 111
+#define IDR_CREDIT 116
+#define IDI_PLUG_MAIN 190
+#define IDI_PLUG_DEFAULT 191
+#define IDI_PLUG_ICON1 192
+#define IDI_PLUG_ICON2 193
+#define IDI_PLUG_ICON3 194
+#define IDI_PLUG_HELP 195
+#define IDI_PLUG_FOLDERO 196
+#define IDI_PLUG_ARROWL 197
+#define IDI_PLUG_ARROWR 198
+#define IDI_PLUG_OVERLAYON 199
+#define IDI_PLUG_OVERLAYOFF 200
+#define IDD_UAboutForm 201
+#define IDI_PLUG_DESKOFF 201
+#define IDI_PLUG_DESKON 202
+#define IDI_PLUG_DELOFF 203
+#define IDI_PLUG_DELON 204
+#define IDD_UEditForm 301
+#define IDC_CAPTURETAB 1005
+#define IDD_MSGBOX 1008
+#define IDC_CREDIT 1009
+#define IDD_MSGBOXDUMMI 1024
+#define IDD_UMain_CaptureDesktop 1025
+#define STATIC_WHITERECT 1100
+#define STATIC_LINE2 1103
+#define ICO_DLGLOGO 1105
+#define ICO_MSGDLG 1106
+#define IDC_BUILDTIME 1108
+#define TXT_NAME 1114
+#define TXT_MESSAGE 1126
+#define ID_edtCaption 1201
+#define ID_edtSize 1202
+#define ID_edtQuality 1203
+#define ID_upQuality 1204
+#define ID_edtTimed 1205
+#define ID_upTimed 1206
+#define IDC_WHITERECT 1221
+#define ID_cboxFormat 1301
+#define ID_cboxSendBy 1302
+#define ID_lblFmtInfo 1501
+#define IDE_Image 1501
+#define ID_lblSendBy 1502
+#define IDE_imgSelection 1502
+#define ID_bvlTarget 1503
+#define IDC_COPYRIGHT 1503
+#define ID_lblDropInfo 1504
+#define ID_imgTarget 1505
+#define ID_edtCaptionLabel 1506
+#define ID_edtSizeLabel 1507
+#define ID_edtQualityLabel 1508
+#define ID_edtTimedLabel 1509
+#define IDNONE 1565
+#define IDA_CONTRIBLINK 1586
+#define IDC_LICENSE 1589
+#define ID_gboxAreaToTake 1602
+#define ID_gboxOptions 1603
+#define ID_chkEditor 1701
+#define ID_chkClientArea 1704
+#define ID_chkTimed 1708
+#define ID_chkOpenAgain 1710
+#define IDC_HEADERBAR 1734
+#define ID_btnAbout 2001
+#define ID_btnExplore 2002
+#define ID_btnDesc 2003
+#define ID_btnDeleteAfterSend 2004
+#define ID_btnCapture 2005
+#define IDE_StatusBar 2501
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NEXT_RESOURCE_VALUE 123
+#define _APS_NEXT_COMMAND_VALUE 40002
+#define _APS_NEXT_CONTROL_VALUE 1011
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/plugins/SendScreenshotPlus/resource.rc b/plugins/SendScreenshotPlus/resource.rc
new file mode 100644
index 0000000000..8e24cc0204
--- /dev/null
+++ b/plugins/SendScreenshotPlus/resource.rc
@@ -0,0 +1,274 @@
+// Microsoft Visual C++ generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "afxres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// Deutsch (Deutschland) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU)
+#ifdef _WIN32
+LANGUAGE LANG_GERMAN, SUBLANG_GERMAN
+#pragma code_page(1252)
+#endif //_WIN32
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_MSGBOX DIALOGEX 0, 0, 219, 97
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Dialog"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ LTEXT "",STATIC_WHITERECT,0,0,219,72
+ LTEXT "",TXT_NAME,11,3,173,20,SS_ENDELLIPSIS | NOT WS_VISIBLE,WS_EX_TRANSPARENT
+ ICON "",ICO_DLGLOGO,191,3,21,20,NOT WS_VISIBLE
+ ICON "",ICO_MSGDLG,7,29,21,20
+ LTEXT "",TXT_MESSAGE,34,37,180,35
+ CONTROL "",STATIC_LINE2,"Static",SS_ETCHEDHORZ,0,71,219,1
+ DEFPUSHBUTTON "OK",IDOK,6,78,50,14
+ PUSHBUTTON "All",IDALL,58,78,50,14,NOT WS_VISIBLE
+ PUSHBUTTON "None",IDNONE,110,78,50,14,NOT WS_VISIBLE
+ PUSHBUTTON "Cancel",IDCANCEL,162,78,50,14,NOT WS_VISIBLE
+END
+
+IDD_MSGBOXDUMMI DIALOGEX 65526, 65526, 1, 1
+STYLE DS_ABSALIGN | DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_SYSMENU
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+END
+
+IDD_UMainForm DIALOGEX 0, 0, 231, 164
+STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
+EXSTYLE WS_EX_CONTROLPARENT
+CAPTION "Send screenshot"
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ CONTROL "Send screenshot to\n<unknown>",IDC_HEADERBAR,
+ "MHeaderbarCtrl",0x0,0,0,231,25
+ CONTROL "",IDC_CAPTURETAB,"SysTabControl32",TCS_RAGGEDRIGHT | WS_TABSTOP,8,36,218,68,WS_EX_TRANSPARENT
+ CONTROL "Ti&med capture",ID_chkTimed,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,8,106,85,10
+ RTEXT "Time (secs) :",ID_edtTimedLabel,9,119,49,8
+ EDITTEXT ID_edtTimed,62,117,31,13,ES_AUTOHSCROLL | ES_NUMBER
+ CONTROL "",ID_upTimed,"msctls_updown32",UDS_SETBUDDYINT | UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS | UDS_NOTHOUSANDS,81,117,11,13
+ LTEXT "&Format :",ID_lblFmtInfo,100,107,41,8
+ COMBOBOX ID_cboxFormat,100,117,41,84,CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | CBS_HASSTRINGS | CBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+ LTEXT "Send B&y :",ID_lblSendBy,148,107,75,8
+ COMBOBOX ID_cboxSendBy,148,117,75,84,CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | CBS_HASSTRINGS | CBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+ CONTROL "?",ID_btnAbout,"UInfoButtonClass",WS_TABSTOP | 0x4000,3,145,16,14,WS_EX_NOACTIVATE | 0x10000000L
+ CONTROL "E&xplore",ID_btnExplore,"UInfoButtonClass",WS_TABSTOP | 0x4000,21,145,16,14,WS_EX_NOACTIVATE | 0x10000000L
+ CONTROL "&Fill description textbox.",ID_btnDesc,"UInfoButtonClass",WS_TABSTOP | 0x6000,39,145,16,14,WS_EX_NOACTIVATE | 0x10000000L
+ CONTROL "Delete &after send",ID_btnDeleteAfterSend,
+ "UInfoButtonClass",WS_TABSTOP | 0x6000,57,145,16,14,WS_EX_NOACTIVATE | 0x10000000L
+ CONTROL "Open again",ID_chkOpenAgain,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,100,147,57,9
+ CONTROL "&Capture",ID_btnCapture,"UInfoButtonClass",WS_GROUP | WS_TABSTOP | 0x1000,169,145,54,14,WS_EX_NOACTIVATE | 0x10000000L
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,0,139,231,1
+END
+
+IDD_UAboutForm DIALOGEX 0, 0, 214, 185
+STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
+EXSTYLE WS_EX_TOPMOST
+CAPTION "About"
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ CONTROL "%s\nv%s",IDC_HEADERBAR,"MHeaderbarCtrl",0x0,0,0,214,25
+ CONTROL "Credits >",IDA_CONTRIBLINK,"UInfoButtonClass",WS_GROUP | WS_TABSTOP,5,166,61,14,WS_EX_NOACTIVATE | 0x10000000L
+ PUSHBUTTON "&Close",IDA_btnClose,149,166,60,14
+ LTEXT "",IDC_WHITERECT,0,25,213,135,NOT WS_GROUP
+ EDITTEXT IDC_LICENSE,5,37,204,95,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_READONLY | NOT WS_BORDER | WS_VSCROLL
+ EDITTEXT IDC_CREDIT,5,37,204,95,ES_MULTILINE | ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_READONLY | NOT WS_BORDER | WS_VSCROLL
+ EDITTEXT IDC_BUILDTIME,5,147,146,12,ES_AUTOHSCROLL | ES_READONLY | NOT WS_BORDER | NOT WS_TABSTOP
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,0,160,213,1
+END
+
+IDD_UEditForm DIALOGEX 217, 152, 329, 285
+STYLE DS_SETFONT | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
+EXSTYLE WS_EX_WINDOWEDGE | WS_EX_CONTROLPARENT
+CAPTION "Edit"
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ CONTROL "",IDE_Image,"Static",SS_BITMAP | WS_GROUP,0,0,265,194
+ CONTROL "",IDE_imgSelection,"Static",SS_BITMAP | WS_GROUP,195,133,100,76
+ CONTROL "",IDE_StatusBar,"msctls_statusbar32",WS_CLIPSIBLINGS | 0x100,0,272,323,12
+END
+
+IDD_UMain_CaptureWindow DIALOGEX 0, 0, 214, 48
+STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD | WS_VISIBLE
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ LTEXT "",IDC_WHITERECT,0,0,214,48
+ CONTROL "C&lient Area",ID_chkClientArea,"Button",BS_AUTOCHECKBOX | BS_LEFTTEXT | WS_TABSTOP,100,30,62,8,WS_EX_RIGHT
+ LTEXT "Caption :",ID_edtCaptionLabel,4,1,158,8
+ EDITTEXT ID_edtCaption,4,12,158,13,ES_AUTOHSCROLL | ES_READONLY
+ RTEXT "Size (HxW) :",ID_edtSizeLabel,0,30,50,8
+ EDITTEXT ID_edtSize,52,28,43,13,ES_CENTER | ES_AUTOHSCROLL | ES_READONLY
+ CTEXT "Target Tool",ID_lblDropInfo,162,1,51,8
+ LTEXT "",ID_bvlTarget,174,12,29,29,SS_NOTIFY | SS_SUNKEN
+ ICON IDI_PLUG_ICON2,ID_imgTarget,178,16,20,20,SS_NOTIFY | SS_CENTERIMAGE | WS_GROUP
+END
+
+IDD_UMain_CaptureDesktop DIALOGEX 0, 0, 214, 48
+STYLE DS_SETFONT | DS_FIXEDSYS | DS_CONTROL | WS_CHILD | WS_VISIBLE
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ LTEXT "",IDC_WHITERECT,0,0,214,48
+ LTEXT "Caption :",ID_edtCaptionLabel,4,1,158,8
+ RTEXT "Size (HxW) :",ID_edtSizeLabel,0,30,50,8
+ EDITTEXT ID_edtSize,52,28,43,13,ES_AUTOHSCROLL | ES_READONLY
+ LTEXT "",ID_bvlTarget,174,12,29,29,SS_NOTIFY | SS_SUNKEN
+ ICON "",ID_imgTarget,178,16,20,20,SS_NOTIFY | SS_CENTERIMAGE | WS_GROUP
+ COMBOBOX ID_edtCaption,4,12,158,30,CBS_DROPDOWNLIST | CBS_AUTOHSCROLL | WS_TABSTOP
+END
+
+IDD_CAPTURE DIALOGEX 0, 0, 316, 180
+STYLE DS_SYSMODAL | DS_SETFONT | DS_FIXEDSYS | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME
+CAPTION "Dialog"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_PLUG_MAIN ICON "res\\ssCamera_1.ico"
+IDI_PLUG_ICON1 ICON "res\\ssCamera_2.ico"
+IDI_PLUG_DEFAULT ICON "res\\ssDefault.ico"
+IDI_PLUG_ICON2 ICON "res\\ssTarget.ico"
+IDI_PLUG_ICON3 ICON "res\\ssMonitor.ico"
+IDI_PLUG_HELP ICON "res\\sshelp.ico"
+IDI_PLUG_FOLDERO ICON "res\\ssOpen.ico"
+IDI_PLUG_ARROWL ICON "res\\ssArrow_Left.ico"
+IDI_PLUG_ARROWR ICON "res\\ssArrow_Right.ico"
+IDI_PLUG_OVERLAYOFF ICON "res\\overlay_disabled.ico"
+IDI_PLUG_OVERLAYON ICON "res\\overlay_enabled.ico"
+IDI_PLUG_DESKOFF ICON "res\\ssDeskOff.ico"
+IDI_PLUG_DESKON ICON "res\\ssDeskOn.ico"
+IDI_PLUG_DELOFF ICON "res\\ssDelOff.ico"
+IDI_PLUG_DELON ICON "res\\ssDelOn.ico"
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Bitmap
+//
+
+IDB_Bmp1 BITMAP "res\\UEditForm_nvr_1.bmp"
+IDB_Bmp2 BITMAP "res\\UEditForm_nvr_2.bmp"
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXT
+//
+
+IDR_CREDIT TEXT "./res/credits.txt"
+IDR_LICENSE TEXT "./res/license.txt"
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO
+BEGIN
+ IDD_MSGBOX, DIALOG
+ BEGIN
+ HORZGUIDE, 23
+ HORZGUIDE, 29
+ HORZGUIDE, 72
+ END
+
+ IDD_UMainForm, DIALOG
+ BEGIN
+ HORZGUIDE, 159
+ END
+
+ IDD_UAboutForm, DIALOG
+ BEGIN
+ LEFTMARGIN, 5
+ RIGHTMARGIN, 209
+ BOTTOMMARGIN, 180
+ END
+
+ IDD_UEditForm, DIALOG
+ BEGIN
+ RIGHTMARGIN, 230
+ END
+
+ IDD_UMain_CaptureWindow, DIALOG
+ BEGIN
+ RIGHTMARGIN, 213
+ VERTGUIDE, 162
+ END
+
+ IDD_UMain_CaptureDesktop, DIALOG
+ BEGIN
+ VERTGUIDE, 162
+ END
+
+ IDD_CAPTURE, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 309
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 173
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+#endif // Deutsch (Deutschland) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/plugins/SendScreenshotPlus/resource_6.rc b/plugins/SendScreenshotPlus/resource_6.rc
new file mode 100644
index 0000000000..7989eaa16b
--- /dev/null
+++ b/plugins/SendScreenshotPlus/resource_6.rc
@@ -0,0 +1,2 @@
+#include "resource.rc"
+#include "version.rc"
diff --git a/plugins/SendScreenshotPlus/sdk/DevKey.h b/plugins/SendScreenshotPlus/sdk/DevKey.h
new file mode 100644
index 0000000000..2999f74466
--- /dev/null
+++ b/plugins/SendScreenshotPlus/sdk/DevKey.h
@@ -0,0 +1,3 @@
+#ifndef DEVKEY_IMAGESHACK
+#define DEVKEY_IMAGESHACK "IA5ZRTV6fb6256ccbc3c38650bdce6e6dcfc9e55" /*Test DevKey*/
+#endif
diff --git a/plugins/SendScreenshotPlus/sdk/icons.h b/plugins/SendScreenshotPlus/sdk/icons.h
new file mode 100644
index 0000000000..46871836bd
--- /dev/null
+++ b/plugins/SendScreenshotPlus/sdk/icons.h
@@ -0,0 +1,112 @@
+//{{NO_DEPENDENCIES}}
+// Microsoft Visual C++ generated include file.
+// Used by uinfoex_icons.rc
+//
+#define IDI_FIRST_ICON 101
+
+// dialog inforbar
+#define IDI_DLG_DETAILS 101
+#define IDI_DLG_PHONE 102
+#define IDI_DLG_EMAIL 103
+
+// dialog infobar & buttons
+#define IDI_ANNIVERSARY 104
+#define IDI_EXPORT 105
+#define IDI_IMPORT 106
+#define IDI_SEARCH 107
+
+// common icons of details dialog pages
+#define IDI_MIRANDA 108
+#define IDI_PASSWORD 109
+#define IDI_FEMALE 110
+#define IDI_MALE 111
+#define IDI_CLOCK 112
+#define IDI_MARITAL 113
+
+// commonly used buttons
+#define IDI_BTN_UPDATE 114
+#define IDI_BTN_OK 115
+#define IDI_BTN_CLOSE 116
+#define IDI_BTN_APPLY 117
+#define IDI_BTN_GOTO 118
+#define IDI_BTN_PHONE 119
+#define IDI_BTN_FAX 120
+#define IDI_BTN_CELLULAR 121
+#define IDI_BTN_CUSTOMPHONE 122
+#define IDI_BTN_EMAIL 123
+#define IDI_BTN_DOWNARROW 124
+#define IDI_BTN_ADD 125
+#define IDI_BTN_EDIT 126
+#define IDI_BTN_DELETE 127
+#define IDI_BTN_EXIMPORT 128
+#define IDI_BTN_BIRTHDAY_BACKUP 129
+
+// details treeview icons
+#define IDI_TREE_GENERAL 130
+#define IDI_TREE_ADVANCED 131
+#define IDI_TREE_COMPANY 132
+#define IDI_TREE_CONTACT 133
+#define IDI_TREE_ABOUT 134
+#define IDI_TREE_PHOTO 135
+#define IDI_TREE_ADDRESS 136
+#define IDI_TREE_NOTES 137
+#define IDI_TREE_PROFILE 138
+
+// export: choose modules
+#define IDI_LST_MODULES 139
+#define IDI_LST_FOLDER 140
+
+// zodiac icons
+#define IDI_ZOD_AQUARIUS 141
+#define IDI_ZOD_ARIES 142
+#define IDI_ZOD_CANCER 143
+#define IDI_ZOD_CAPRICORN 144
+#define IDI_ZOD_GEMINI 145
+#define IDI_ZOD_LEO 146
+#define IDI_ZOD_LIBRA 147
+#define IDI_ZOD_PISCES 148
+#define IDI_ZOD_SAGITTARIUS 149
+#define IDI_ZOD_SCORPIO 150
+#define IDI_ZOD_TAURUS 151
+#define IDI_ZOD_VIRGO 152
+
+// reminder
+#define IDI_BIRTHDAY 153
+#define IDI_RMD_DTB0 154
+#define IDI_RMD_DTB1 155
+#define IDI_RMD_DTB2 156
+#define IDI_RMD_DTB3 157
+#define IDI_RMD_DTB4 158
+#define IDI_RMD_DTB5 159
+#define IDI_RMD_DTB6 160
+#define IDI_RMD_DTB7 161
+#define IDI_RMD_DTB8 162
+#define IDI_RMD_DTB9 163
+#define IDI_RMD_DTBX 164
+#define IDI_RMD_DTA0 165
+#define IDI_RMD_DTA1 166
+#define IDI_RMD_DTA2 167
+#define IDI_RMD_DTA3 168
+#define IDI_RMD_DTA4 169
+#define IDI_RMD_DTA5 170
+#define IDI_RMD_DTA6 171
+#define IDI_RMD_DTA7 172
+#define IDI_RMD_DTA8 173
+#define IDI_RMD_DTA9 174
+#define IDI_RMD_DTAX 175
+
+#define IDI_LASTICON 175
+
+// version text
+#define IDS_ICOPACKVERSION 1001
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NEXT_RESOURCE_VALUE 1002
+#define _APS_NEXT_COMMAND_VALUE 40001
+#define _APS_NEXT_CONTROL_VALUE 1000
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/plugins/SendScreenshotPlus/version.h b/plugins/SendScreenshotPlus/version.h
new file mode 100644
index 0000000000..b4fe6f1849
--- /dev/null
+++ b/plugins/SendScreenshotPlus/version.h
@@ -0,0 +1,45 @@
+#define PLUGNAME "Send Screenshot+"
+#define __MAJOR_VERSION 0
+#define __MINOR_VERSION 8
+#define __RELEASE_NUM 0
+#define __BUILD_NUM 0
+
+#define __STRINGIFY(x) #x
+#define __STRINGIFY2(x) __STRINGIFY(x)
+#define __FILEVERSION_STRING __MAJOR_VERSION,__MINOR_VERSION,__RELEASE_NUM,__BUILD_NUM
+#define __FILEVERSION_STRING_DOTS __MAJOR_VERSION.__MINOR_VERSION.__RELEASE_NUM.__BUILD_NUM
+
+#define __VERSION_STRING __STRINGIFY2(__FILEVERSION_STRING)
+#define __VERSION_STRING_DOT __STRINGIFY2(__FILEVERSION_STRING_DOTS)
+
+#define __FILENAME "SendSS.dll"
+#define __DESC "Take a screenshot and send it to a contact."
+#define __AUTHOR "Merlin"
+#define __AUTHOREMAIL "ing.u.horn@googlemail.com"
+#define __COPYRIGHT "� 2010 Merlin, � 2004-2006 Sergio Vieira Rolanski"
+#define __AUTHORWEB "http://code.google.com/p/merlins-miranda"
+
+#ifndef MIID_PLUGIN // {ED39AF7C-BECD-404e-9499-4D04F711B9CB}
+#define MIID_PLUGIN { 0xed39af7c, 0xbecd, 0x404e, { 0x94, 0x99, 0x4d, 0x04, 0xf7, 0x11, 0xb9, 0xcb } }
+#endif
+
+#ifdef _UNICODE
+#define __PLUGIN_NAME "Send Screenshot+ (Unicode)"
+#define __FLVersionURL "http://addons.miranda-im.org/details.php?action=viewfile&id=1428"
+#define __FLVersionPrefix "<span class=\"fileNameHeader\">SendSS (Unicode) "
+#define __FLUpdateURL "http://addons.miranda-im.org/feed.php?dlfile=1428"
+#define __BetaUpdateURL "http://merlins-miranda.googlecode.com/files/SendSSW.zip"
+#else
+#define __PLUGIN_NAME "Send Screenshot+ (2in1)"
+#define __FLVersionURL "http://addons.miranda-im.org/details.php?action=viewfile&id=1428"
+#define __FLVersionPrefix "<span class=\"fileNameHeader\">SendSS (2in1) "
+#define __FLUpdateURL "http://addons.miranda-im.org/feed.php?dlfile=1428"
+#define __BetaUpdateURL "http://merlins-miranda.googlecode.com/files/SendSS.zip"
+#endif
+
+#define __BetaVersionURL "http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSS/changelog.txt"
+#define __BetaVersionPrefix "SendSS Plus: "
+#define __BetaChangelogURL "http://merlins-miranda.googlecode.com/svn/trunk/miranda/plugins/SendSS/changelog.txt"
+
+#define __USER_AGENT_STRING __PLUGIN_NAME##" v"##__VERSION_STRING_DOT
+
diff --git a/plugins/SendScreenshotPlus/version.rc b/plugins/SendScreenshotPlus/version.rc
new file mode 100644
index 0000000000..16f5845ed6
--- /dev/null
+++ b/plugins/SendScreenshotPlus/version.rc
@@ -0,0 +1,38 @@
+#include <windows.h> // include for version info constants
+#include "version.h"
+
+//
+// TO CHANGE VERSION INFORMATION, EDIT PROJECT OPTIONS...
+//
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION __MAJOR_VERSION,__MINOR_VERSION,__RELEASE_NUM,__BUILD_NUM
+ PRODUCTVERSION __MAJOR_VERSION,__MINOR_VERSION,__RELEASE_NUM,__BUILD_NUM
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE 0x1L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "040904E4"
+ BEGIN
+ VALUE "CompanyName", ""
+ VALUE "FileVersion", __VERSION_STRING_DOT
+ VALUE "FileDescription", __DESC
+ VALUE "InternalName", __PLUGIN_NAME
+ VALUE "LegalCopyright", __COPYRIGHT
+ VALUE "OriginalFilename", __FILENAME
+ VALUE "ProductName", __PLUGIN_NAME
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x0409, 1252
+ END
+END
+
diff --git a/plugins/ShlExt/clean.bat b/plugins/ShlExt/clean.bat
new file mode 100644
index 0000000000..575eed729c
--- /dev/null
+++ b/plugins/ShlExt/clean.bat
@@ -0,0 +1 @@
+del *.o *.ppu *.dll *.a fpc-res.res *.or \ No newline at end of file
diff --git a/plugins/ShlExt/docs/HowToBuild.txt b/plugins/ShlExt/docs/HowToBuild.txt
new file mode 100644
index 0000000000..53b6738616
--- /dev/null
+++ b/plugins/ShlExt/docs/HowToBuild.txt
@@ -0,0 +1,22 @@
+shlext 2.0.0.9
+
+Info
+=======================
+
+This source code is based on shlext 1.0.6.6 with minor changes so that it works
+with FreePascal 2.2.2.
+
+The included headers (inc dir) are from Miranda 0.3.3.1 SDK and so if you want newer APIs
+then get the API headers from the latest SVN tree.
+
+Note: I have included v0.8.xx API changes for GUIDs within a new file (m_v8.inc)
+
+
+How to build
+=======================
+
+Make sure you have installed the FreePascal compiler ( http://freepascal.org )
+the latest version is 2.2.2 at the time of writing.
+
+Run "make.bat" in this directory, this contains all the command line switches
+for the newer version should produce shlext.dll
diff --git a/plugins/ShlExt/docs/shlext release notes.txt b/plugins/ShlExt/docs/shlext release notes.txt
new file mode 100644
index 0000000000..0e58edf9ff
--- /dev/null
+++ b/plugins/ShlExt/docs/shlext release notes.txt
@@ -0,0 +1,344 @@
+shlext 2.0.1.2
+
+Contents:
+
+ Introduction ``What is shlext?``
+ Why so long?
+ What you need
+ New features
+ Features
+ Quirks
+ Important changes
+ But Miranda has drag'n'drop!
+ Installation
+ Upgrading/Removing
+ Translation
+ License
+ Contact/Bug reporting
+ Credits
+
+
+
+ ---Introduction ``What is shlext?``
+
+ shlext is a Miranda and Explorer shell plugin, it allows you to use your
+ contact list under any file/directory from Windows.
+
+ This means that you can right click on a file/folder, see "Miranda" and then
+ see your entire contact list! this is a feature that ICQ has built in.
+
+ shlext is better of course.
+
+ ---Why so long?
+
+ A few people contacted me aeons ago about implementing a better file scanner
+ so that they could recreate directories whilst sending, etc, I said I would do
+ this as soon as I had time, that was several months ago.
+
+ I had made several changes/bugfixes when I had time, because I'm a Miranda
+ dev too, I don't usually have lots of time for this plugin, however lately I needed
+ shlext to run again, since I was sending lots of docs/logs around with Miranda.
+
+ So I fixed several things and improved lots of other stuff so that other users
+ could use shlext again (the XP bug was really annoying as soon as I got XP myself ;)
+
+
+ ---What you need
+
+ (2008) You will need 0.7.xx or 0.8.x -- older versions will not work.
+
+ shlext should work on all Window Explorer versions that support it,
+ certain features will not work on older Explorers, i.e. icons, but you will
+ still be able to use the main function of shlext, selection 'n' transfer.
+
+ ---New Features (2.0.1.2)
+
+ * shlext is now compiled with Free Pascal 2.2.4
+
+ * shlext now works with Windows Vista:
+
+ 1. shlext cannot automatically register itself with Windows Explorer due to permissions issues in Vista,
+ therefore you will be UAC prompted if shlext detects you are running Vista and that shlext isn't registered
+ with Explorer.
+
+ This is almost automatic, and you just have to press "OK".
+
+ 2. The entire menu drawing was overhauled and now looks much better, new APIs are used so that Vista draws the menus
+ (with theme) but the status icons are still present.
+
+ * added UAC button for "Remove" from the options dialog.
+
+ * Removed GetMenuItemInfo() debug message box.
+
+ * Note: Miranda is a 32bit application, 64bit editions of Windows require a 64bit extension DLL, this is not possible at present.
+
+ ---New features (2.0.0.9+)
+
+ * shlext is now compiled with Free Pascal 2.2.2 which is a newer compiler with better
+ optimisations so shlext should be faster. (2002 v.s. 2008)
+
+ * shlext now works with Miranda 0.8.x UUID typing system and 0.8.xx plugin loading APIs,
+ 0.7.xx still works too however.
+
+ * shlext now keeps track of recently used contacts and builds a "MRU" menu for quick
+ access within the menu system. This cannot be disabled, if you hate this feature,
+ please stick pins into a voodoo doll named "Christian", that is all.
+
+ * The menu strings "Recently" and "Clear entries" are translate()able but MRU is not.
+
+ ---New features (1.0.6.6+)
+
+ * shlext will now use all your icons per protocol, **not** just the first iconset
+ it finds, it will also use everything properly (because it doesn't do the icon
+ extraction, it just asks Miranda [don't ask why it didn't do this before :P])
+
+ * shlext will now use a Translate()'d version of "Miranda" so that each menu
+ shown for a profile can be given a custom user string
+
+ * reimplemented file/folder selection, finally! a work-as-expected version, it will
+ scan and add all files and folders you give it, producing a file list in the background
+ (scanning your drive) and then send the list to Miranda to send to your selected contact.
+
+ * Added option for disabling status icons in menus, which means that you can use shlext
+ with shell variants/file managers that invoke the shlext interface, such as FAR, but
+ don't need/use the icons.
+
+ * Added option about hiding offline users from the context menu, if this option is off
+ it will fall back onto syncing with your contact list's "hide offline users"
+
+ * Added proper thread safety because Miranda 0.3 now has it.
+
+ * Completely reimplemented group parsing, which means that all the old group bugs
+ can be expected to be gone, note that shlext will now even create menus for
+ subgroups of the same name, e.g. "Miranda\Miranda".
+
+ * shlext will now not show a menu for a running Miranda fails the following checks:
+
+ * not running shlext (duh)
+ * no non-offline contacts (or you have the setting 'hide offline users')
+ * and so on
+
+ * shlext will now also completely ignore contacts on protocols who have no file transfer support
+
+
+ ---Features
+
+ shlext can:
+
+ * allow you to refer to your entire contact list from a file/folder context
+ menu, this includes multiple profiles! if you have Miranda running
+ different profiles, you'll see all your profiles as menu items as long
+ as you're running shlext as a Miranda plugin in that profile.
+
+ * Group ability, see a faithful menu rendition of your group hierarchy.
+ This means you can go something like File->My Profile->Work->Friends->Dude...
+
+ This feature can also be turned off, or enabled in sync with your contact
+ list option to "Disable groups", this is a per profile setting, i.e. setting
+ disable groups on one profile won't affect other profiles running shlext.
+
+ * Multi protocol aware, shlext can send to anyone on your contact list
+ not just ICQ!
+
+ * Each contact will be shown next to their status icon, as selected in your
+ profile(s) which means that you'll easily feel at home with the icons,
+ because they will be used as how they are set in each profile.
+
+ * lots of files, shlext will now, if given a directory/folder go into that
+ folder and scan for files and sub directories/folders til it's added
+ everything.
+
+ This means if you send c:\foobar, it will search c:\foobar\*.* for more
+ files to add, it will also add c:\foobar as a directory space to send.
+ Which means that if the other side hasn't got a 'foobar' directory, it will
+ be created! (Note: recreating directory trees depends on the protocol being used to send)
+
+
+ --Quirks
+
+ * shlext displays all your users by default, if your contact list is set to
+ NOT show offline users, then shlext will not show them.
+
+ * shlext doesn't use all your group settings, it will not ad here to
+ "hide offline users in here", however if a group has got offline users
+ it won't show them (per setting option!)
+
+
+
+ ---Important changes
+
+ Older versions of shlext did not go into folders more than one level, i.e.
+ if you added c:\foobar it would scan for c:\foobar\*.* and add all the files
+ but not go into each directory\folder deeper than that!
+
+ shlext also now does background selection scanning, which means when you select
+ a group of files/folders/directories, it will let you get on with chating
+ until it's made a file list which you can send to the person you've selected.
+
+ shlext will NOT send any file/folder/directory that is marked "hidden"
+
+ Also, sometimes you will see "n files, 1 directory" when you say select something
+ e.g. c:\foobar, this is because shlext now also includes the top level directory so that the
+ remote side will know to create it, as well as sub directories.
+
+
+
+ ---But Miranda has drag'n'drop!
+
+ Yeah, that's okay when you can reach Miranda, but I have multiple profiles and
+ the "hide after NN seconds" option enabled, also I have groups!
+
+ Miranda doesn't auto expand a group when someone is online unless you do that
+ yourself, which means drag 'n' drop has failed. Also, when you've selected a
+ large amount of files, Miranda will *freeze* completely whilst
+ it 1) scans all those files, 2) builds a copy of the given send list
+
+ Whilst shlext only freezes Miranda for the latter, and that is seldom a "complete freeze".
+
+ And of course, shlext uses Miranda 0.3's advanced threading services, which means
+ if you've asked shlext to build a massive send list, you can still exit Miranda safely
+ which you can't with drag 'n' drop!
+
+
+
+ ---Installation
+
+ If you've never installed shlext before, all you have to do is install it like
+ any other Miranda plugin, i.e. copy it to your plugins directory.
+
+ That's it! you should goto Miranda->Options->Plugins->Shell Context Menus
+ to see if you'd like to set any of the options, however shlext works straight
+ out of the box and you don't really need to set anything up after that.
+
+ If you want to use shlext with multiple profiles, you don't have to do any
+ special setting up either, just make sure that shlext is running with each Miranda
+ you want shlext to show a menu contact list for.
+
+ Make sure ALL copies of shlext.dll are the same, i.e. 1.0.6.6, if they're not
+ then shlext will fail (this doesn't mean 'crash').
+
+
+ ---Upgrading/Removing
+
+ Upgrading shlext has always been a pain for users (and me!) this is because
+ shlext.dll runs in Windows and in Miranda (at the same time).
+
+ So when you've shutdown Miranda, shlext.dll maybe kept in memory by Windows
+ to make things worse, clicking any file/folder will result in shlext.dll being
+ reloaded, so if you do shlext.dll->Delete, Windows will ask shlext.dll if
+ it wants to show any menus, nevermind the fact delete was selected!
+
+ This happens also if you just press 'delete' whilst shlext.dll is selected.
+
+ However! All is not lost, this is what you do:
+
+ * goto M->Options->Plugins and disable shlext.dll as a Miranda plugin
+ * goto M->Options->Plugins->Shell context menus and click 'Remove'.
+ * Shutdown Miranda IM
+
+ Advanced users only: ----------------------------------------------------
+
+ * Do all the above and then open a console window (Command prompt, etc)
+ * Make sure all applications have been shutdown
+ * Goto the directory where Miranda is, e.g. c:\, cd Miranda
+ * Goto Start->Shutdown, let the dialog come up and hold CTRL+ALT+SHIFT
+ and press cancel.
+
+ This will shutdown Explorer but not Windows, you can now do: del shlext.dll
+
+ * now run Explorer.exe usually in C:\Windows, shlext.dll will be removed.
+
+ ----------------------------------------------------------------------------
+
+ The remove button will ask Windows not to load it anymore, by removing
+ all shlext registry entries, the button will also remove any settings from your
+ profile settings database that it may of made.
+
+ You should now be able to delete shlext.dll! however if you still are unable
+ to, you may need to log out (if you're using XP/2000/NT) if you're using
+ 9x then you may have to restart Windows (pain I know, sorry!)
+
+ You should now be free of old shlext copies and you can refer to "Installation"
+ above.
+
+ If you were using shlext.dll with multiple profiles, the remove shlext
+ from each profile as stated above and then copy the newer shlext.dll to
+ your plugins folder.
+
+ ---Translation
+
+ I haven't been nice about translation strings in the past, but you
+ can pretty much translate everything shlext uses a string, even
+ "Miranda" which is shown in the menu.
+
+ Note that some strings can't be translated, this is because some parts
+ of the plugin run within Explorer and that doesn't have access to Miranda's
+ langpacks, the "Miranda" string that appears in menus is a special exception
+
+ ;
+ ; Translate()'able strings for shlext/2.0.0.9
+ ;
+
+ ;"Miranda" limited to 63characters! (exceed and it's chopped)
+ ;[Miranda]
+ ;[Problem, registration missing/deleted.]
+ ;[Successfully created shell registration.]
+ ;[Not Approved]
+ ;[Approved]
+ ;[Are you sure? this will remove all the settings stored in your database and all registry entries created for shlext to work with Explorer]
+ ;[Disable/Remove shlext]
+ ;[Shell context menus]
+
+ ; new in 2.0.0.9, both these strings cannot be longer than 63 chracters
+ ;[Clear entries]
+ ;[Recently]
+
+ ;IDD_SHLOPTS
+ ;[Menus]
+ ;[Display contacts in their assigned groups (if any)]
+ ;[Only if/when the contact list is using them]
+ ;[Display hidden, ignored or temporary contacts]
+ ;[Shell Status]
+ ;[Do not display the profile name in use]
+ ;[Contact Status]
+ ;[Show contacts that you have set privacy rules for]
+ ;[Remove]
+ ;[Do not show status icons in menus]
+ ;[Do not show contacts that are offline, even if my contact list does]
+
+
+
+
+ ---License
+
+ Like Miranda, shlext is released under the GPL, you may find the full
+ FreePascal source-code on the CVS in plugins module 'shlext'
+
+ You will need at least FreePascal/2.2.2, GNU make (if you want to use the makefile)
+
+ Follow the CVS links from http://sf.net/projects/miranda-icq/
+
+ Note: All the tools used to build shlext are also under the GPL!
+
+
+ ---Contact/Bug reporting
+
+ In the past shlext hasn't been as stable as it could be, but this was mainly
+ due to the problems of 0.2.0.0 and early 0.3.0.0 Miranda builds, I've taken
+ care to make sure things are stable as can be.
+
+ If you have any problems/crashes, please contact me at: egodust at users.sf.net.
+
+ Please include the following information: Windows version, service packs installed,
+ build version of Explorer, Miranda version, shlext version, a list of plugins
+ that you think maybe involved in crashes, steps to reproduce errors and so on.
+
+ Note that shlext has been blamed for several bugs that were not shlext's fault,
+ for example the file xfer cancel bug was in ICQ and Miranda but not shlext ;)
+
+
+ ---Credits
+
+ Tig-crash\d - Thanks for beta testing every version before this one ;)
+ Erik?, DD Of Borg - Thanks for beta testing 0.0.2.2/1.0.6.6 -- ideas and suggestions
+ as well what to exactly steal from ShellFileSend, heh.. \ No newline at end of file
diff --git a/plugins/ShlExt/inc/README.txt b/plugins/ShlExt/inc/README.txt
new file mode 100644
index 0000000000..4c0ab5f0cf
--- /dev/null
+++ b/plugins/ShlExt/inc/README.txt
@@ -0,0 +1,92 @@
+
+ - Miranda Module API for Borland Delphi, FreePascal -
+
+ These include files allow you to write modules to extend Miranda
+ Older versions of these files
+ limited support for FPC, versions & compilers are :
+
+ Borland Delphi 2.0 thru 6.0
+ FreePascal 1.0.4, 1.0.6
+
+ You can now create modules for Miranda (v0.1.2.2) and use
+ new stuff like Netlib! though you can still write for
+ the current stable release (v0.1.2.1) but you'll have to
+ be aware of version dependant things.
+
+ Worry not though, every service/event is marked with a version
+ code if it's not present in older Miranda versions.
+
+ Be warned, this is a brand new porting though it has borrowed
+ from older ports (see CVS, oh this is viewCVS? mmm, cheese.)
+ Things are presented in a more Delphi esque than a C esque manner
+ so if you feel confused refer to the C header.
+
+ A word of warning, don't try to compile /delphiplugins examples
+ with these include files and expect it to work,
+
+
+ Include files use the {$include } syntax and will never work
+ as units.
+
+ -- FPC support? --
+
+ FPC is now properly supported, but you may need to use -SD -S2
+ command line switches (for Delphi, BP7 mode) remember to use -Fi
+ and -Fu to give the path to these files or use {$UNITPATH} and {$INCLUDEPATH}
+
+ These include files don't any FPC stuff like macros
+ and inlined functions.
+
+ -- Things to be aware of --
+
+ This version is not yet directly supported, if you want to learn
+ the API look at the CVS tree for documentation on plugins, as well
+ as guidelines and examples of the general structure of Miranda.
+
+ This is my cop out for now, I'll try to write a more general 'guide' later
+ on.
+
+ -
+
+ Miranda uses a manifest to allow COMCTRL v6 to be loaded on XP,
+ This causes problems with image lists with Delphi (there are work arounds)
+ see borland.com for the article.
+
+ You may want to refuse to load on XP or try to use Miranda's API to work with
+ imagelists and load images from resource as bitmaps (ugh)
+
+ - lstrcat, lstrcpy
+
+ I've used the Windows API calls to these C functions over Delphi's RTL
+ because SysUtils.pas just adds a bloat.
+
+ - *If* you use SysUtils.pas
+
+ Delphi loads OLE for variant support, it maybe advisable to unload
+ the DLL as soon as you start, this maybe a problem though, since Miranda
+ also uses OLE for extended image support, it doesn't however keep
+ it loaded all the time.
+
+ There should be no problem in just decrementing the reference count
+ to the DLL and it'll unload if you were the only reference.
+
+ if however you're using variants in your code, blergh.
+
+ -- How you get it to work --
+
+ see testdll.dpr, it won't do much but it'll show a pretty description in the
+ options dialog (oh impressive!)
+
+ To bring in new files, just use {$include that_file_you_want.inc}
+ If other include files are needed by the include file you bring in,
+ it'll try to include it itself.
+
+ Of course you need to add the path to where the .inc files are to the project's
+ search path, or if you compile via the command line, use -U and -I
+ -U is needed because m_globaldefs.pas is a unit.
+
+ Each header file is marked with "UNITDEP" which will tell you which units
+ it requires.
+
+ All files that require the PLUGINLINK structure require m_globaldefs.pas
+ (this is all the C header files that use such macros!)
diff --git a/plugins/ShlExt/inc/m_addcontact.inc b/plugins/ShlExt/inc/m_addcontact.inc
new file mode 100644
index 0000000000..2e74ad1279
--- /dev/null
+++ b/plugins/ShlExt/inc/m_addcontact.inc
@@ -0,0 +1,54 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_ADDCONTACT}
+{$DEFINE M_ADDCONTACT}
+
+const
+
+ HANDLE_SEARCHRESULT = 0;
+ HANDLE_EVENT = 1;
+ HANDLE_CONTACT = 2;
+
+type
+
+ PADDCONTACTSTRUCT = ^TADDCONTACTSTRUCT;
+ TADDCONTACTSTRUCT = record
+ handleType: Integer;
+ handle: THandle; // HDBEVENT, HCONTACT, SearchResult
+ szProto: PChar; // used by search result only
+ psr: Pointer; // @PROTOSEARCHRESULT
+ end;
+
+const
+
+ {
+ wParam : (HWND) Parent window of the dialog that will be presented
+ lParam : Pointer to an initialised TADDCONTACTSTRUCT
+ Affect : Open's the add contact dialog
+ Version: 0.1.2.2+
+ }
+ MS_ADDCONTACT_SHOW = 'AddContact/Show';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_api.pas b/plugins/ShlExt/inc/m_api.pas
new file mode 100644
index 0000000000..78fda24976
--- /dev/null
+++ b/plugins/ShlExt/inc/m_api.pas
@@ -0,0 +1,75 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFDEF FPC}
+ {$PACKRECORDS C}
+ {$MODE Delphi}
+{$ENDIF}
+
+unit m_api;
+
+interface
+
+uses
+
+ m_globaldefs, windows;
+
+ {$include m_plugins.inc}
+ {$include m_system.inc}
+ {$include m_database.inc}
+ {$include m_findadd.inc}
+ {$include m_awaymsg.inc}
+ {$include m_email.inc}
+ {$include m_history.inc}
+ {$include m_message.inc}
+ {$include m_url.inc}
+ {$include newpluginapi.inc}
+ {$include m_clui.inc}
+ {$include m_ignore.inc}
+ {$include m_skin.inc}
+ {$include m_file.inc}
+ {$include m_netlib.inc}
+ {$include m_langpack.inc}
+ {$include m_clist.inc}
+ {$include m_clc.inc}
+ {$include m_userinfo.inc}
+ {$include m_protosvc.inc}
+ {$include m_options.inc}
+ {$include m_icq.inc}
+ {$include m_protocols.inc}
+ {$include m_protomod.inc}
+ {$include m_utils.inc}
+ {$include m_addcontact.inc}
+ {$include statusmodes.inc}
+ {$include m_contacts.inc}
+ {$define M_API_UNIT}
+ {$include m_helpers.inc}
+
+implementation
+
+ {$undef M_API_UNIT}
+ {$include m_helpers.inc}
+
+end.
+
diff --git a/plugins/ShlExt/inc/m_awaymsg.inc b/plugins/ShlExt/inc/m_awaymsg.inc
new file mode 100644
index 0000000000..2ad330f9de
--- /dev/null
+++ b/plugins/ShlExt/inc/m_awaymsg.inc
@@ -0,0 +1,40 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_AWAYMSG}
+{$DEFINE M_AWAYMSG}
+
+const
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Show the away/na/etc message for a contact
+ Returns: 0 on success, non zero on failure, see notes
+ notes : returns without waiting for the message to be shown.
+ version: v0.1.0.1+
+ }
+ MS_AWAYMSG_SHOWAWAYMSG = 'SRAway/GetMessage';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_clc.inc b/plugins/ShlExt/inc/m_clc.inc
new file mode 100644
index 0000000000..d55ecc7438
--- /dev/null
+++ b/plugins/ShlExt/inc/m_clc.inc
@@ -0,0 +1,284 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_CLC}
+{$DEFINE M_CLC}
+
+const
+
+ CLISTCONTROL_CLASS = 'CListControl';
+
+ // styles
+
+ CLS_MANUALUPDATE = $0001; // todo
+ CLS_SHOWHIDDEN = $0002;
+ CLS_HIDEOFFLINE = $0004; // hides all offline users
+ CLS_CHECKBOXES = $0008;
+ CLS_MULTICOLUMN = $0010; // not true multi-column, just for ignore/vis options
+ CLS_HIDEEMPTYGROUPS = $0020; // note: this flag will be spontaneously removed if the 'new subgroup' menu item is clicked, for obvious reasons
+ CLS_USEGROUPS = $0040;
+ CLS_NOHIDEOFFLINE = $0080; // overrides CLS_HIDEOFFLINE and the per-group hideoffline setting
+ CLS_GREYALTERNATE = $0100; // make every other line slightly grey
+ CLS_GROUPCHECKBOXES = $0200; // put checkboxes on groups too (managed by CLC)
+
+ CLS_EX_DISABLEDRAGDROP = $00000001;
+ CLS_EX_EDITLABELS = $00000002;
+ CLS_EX_SHOWSELALWAYS = $00000004;
+ CLS_EX_TRACKSELECT = $00000008;
+ CLS_EX_SHOWGROUPCOUNTS = $00000010;
+ CLS_EX_DIVIDERONOFF = $00000020;
+ CLS_EX_HIDECOUNTSWHENEMPTY = $00000040;
+ CLS_EX_NOTRANSLUCENTSEL = $00000080;
+ CLS_EX_LINEWITHGROUPS = $00000100;
+ CLS_EX_QUICKSEARCHVISONLY = $00000200;
+ CLS_EX_SORTGROUPSALPHA = $00000400;
+ CLS_EX_NOSMOOTHSCROLLING = $00000800;
+
+ CLM_FIRST = $1000; // this is the same as LVM_FIRST
+ CLM_LAST = $1100;
+
+// messages, compare with equivalent TVM_* in the WINAPI
+
+ CLM_ADDCONTACT = (CLM_FIRST+0); // wParam=hContact
+ CLM_ADDGROUP = (CLM_FIRST+1); // wParam=hGroup
+ CLM_AUTOREBUILD = (CLM_FIRST+2);
+ CLM_DELETEITEM = (CLM_FIRST+3); // wParam=hItem
+ CLM_EDITLABEL = (CLM_FIRST+4); // wParam=hItem
+ CLM_ENDEDITLABELNOW = (CLM_FIRST+5); // wParam=cancel, 0 to save
+ CLM_ENSUREVISIBLE = (CLM_FIRST+6); // wParam=hItem, lParam=partialOk
+
+ CLE_TOGGLE = -1;
+ CLE_COLLAPSE = 0;
+ CLE_EXPAND = 1;
+ CLE_INVALID = $FFFF;
+
+ CLM_EXPAND = (CLM_FIRST+7); // wParam=hItem, lParam=CLE_
+ CLM_FINDCONTACT = (CLM_FIRST+8); // wParam=hContact, returns an hItem
+ CLM_FINDGROUP = (CLM_FIRST+9); // wParam=hGroup, returns an hItem
+ CLM_GETBKCOLOR = (CLM_FIRST+10); // returns a COLORREF
+ CLM_GETCHECKMARK = (CLM_FIRST+11); // wParam=hItem, returns 1 or 0
+ CLM_GETCOUNT = (CLM_FIRST+12); // returns the total number of items
+
+ CLM_GETEDITCONTROL = (CLM_FIRST+13); // returns the HWND, or NULL
+ CLM_GETEXPAND = (CLM_FIRST+14); // wParam=hItem, returns a CLE_, CLE_INVALID if not a group
+ CLM_GETEXTRACOLUMNS = (CLM_FIRST+15); // returns number of extra columns
+ CLM_GETEXTRAIMAGE = (CLM_FIRST+16); // wParam=hItem, lParam=MAKELPARAM(iColumn (0 based),0), returns iImage or $FF
+ CLM_GETEXTRAIMAGELIST = (CLM_FIRST+17); // returns HIMAGELIST
+ CLM_GETFONT = (CLM_FIRST+18); // wParam=fontId, see clm_setfont. returns hFont.
+ CLM_GETINDENT = (CLM_FIRST+19); // wParam=new group indent
+ CLM_GETISEARCHSTRING = (CLM_FIRST+20); // lParam=(char*)pszStr, max 120 bytes, returns number of chars in string
+ CLM_GETITEMTEXT = (CLM_FIRST+21); // wParam=hItem, lParam=(char*)pszStr, max 120 bytes
+ CLM_GETSCROLLTIME = (CLM_FIRST+22); // returns time in ms
+ CLM_GETSELECTION = (CLM_FIRST+23); // returns hItem
+
+ CLCHT_ABOVE = $0001; // above client area
+ CLCHT_BELOW = $0002; // below client area
+ CLCHT_TOLEFT = $0004; // left of client area
+ CLCHT_TORIGHT = $0008; // right of client area
+ CLCHT_NOWHERE = $0010; // in client area, not on an item
+ CLCHT_ONITEMICON = $0020;
+ CLCHT_ONITEMCHECK = $0040;
+ CLCHT_ONITEMLABEL = $0080;
+ CLCHT_ONITEMINDENT = $0100; // to the left of an item icon
+ CLCHT_ONITEMEXTRA = $0200; // on an extra icon, HIBYTE(HIWORD()) says which
+ CLCHT_ONITEM = $03E0;
+ CLCHT_INLEFTMARGIN = $0400;
+ CLCHT_BELOWITEMS = $0800; // in client area but below last item
+
+ CLM_HITTEST = (CLM_FIRST+25); // lParam=MAKELPARAM(x,y) (relative to control), wParam=(PDWORD)&hitTest (see encoding of HitTest() in clc.h, can be NULL) returns hItem or NULL
+ CLM_SELECTITEM = (CLM_FIRST+26); // wParam=hItem
+
+ CLB_TOPLEFT = 0;
+ CLB_STRETCHV = 1;
+ CLB_STRETCHH = 2; // and tile vertically
+ CLB_STRETCH = 3;
+
+ CLBM_TYPE = $00FF;
+ CLBF_TILEH = $1000;
+ CLBF_TILEV = $2000;
+ CLBF_PROPORTIONAL = $4000;
+ CLBF_SCROLL = $8000;
+
+ CLM_SETBKBITMAP = (CLM_FIRST+27); // wParam=mode, lParam=hBitmap (don't delete it), NULL for none
+ CLM_SETBKCOLOR = (CLM_FIRST+28); // wParam=a COLORREF, default is GetSysColor(COLOR_3DFACE)
+ CLM_SETCHECKMARK = (CLM_FIRST+29); // wParam=hItem, lParam=1 or 0
+ CLM_SETEXTRACOLUMNS = (CLM_FIRST+30); // wParam=number of extra columns (zero to MAXEXTRACOLUMNS from clc.h, currently 16)
+ CLM_SETEXTRAIMAGE = (CLM_FIRST+31); // wParam=hItem, lParam=MAKELPARAM(iColumn (0 based),iImage). iImage=$FF is a blank
+ CLM_SETEXTRAIMAGELIST = (CLM_FIRST+32); // lParam=HIMAGELIST
+
+ FONTID_CONTACTS = 0;
+ FONTID_INVIS = 1;
+ FONTID_OFFLINE = 2;
+ FONTID_NOTONLIST = 3;
+ FONTID_GROUPS = 4;
+ FONTID_GROUPCOUNTS = 5;
+ FONTID_DIVIDERS = 6;
+ FONTID_OFFINVIS = 7;
+ FONTID_MAX = 7;
+
+ CLM_SETFONT = (CLM_FIRST+33); // wParam=hFont, lParam=MAKELPARAM(fRedraw,fontId)
+ CLM_SETINDENT = (CLM_FIRST+34); // wParam=new indent, default is 3 pixels
+ CLM_SETITEMTEXT = (CLM_FIRST+35); // wParam=hItem, lParam=(char*)pszNewText
+ CLM_SETSCROLLTIME = (CLM_FIRST+36); // wParam=time in ms, default 200
+ CLM_SETHIDEEMPTYGROUPS = (CLM_FIRST+38); // wParam=TRUE/FALSE
+
+ GREYF_UNFOCUS = $80000000;
+ MODEF_OFFLINE = $40000000;
+
+ // and use the PF2_ #defines from m_protosvc.inc
+ CLM_SETGREYOUTFLAGS = (CLM_FIRST+39); // wParam=new flags
+ CLM_GETHIDEOFFLINEROOT = (CLM_FIRST+40); // returns TRUE/FALSE
+ CLM_SETHIDEOFFLINEROOT = (CLM_FIRST+41); // wParam=TRUE/FALSE
+ CLM_SETUSEGROUPS = (CLM_FIRST+42); // wParam=TRUE/FALSE
+ CLM_SETOFFLINEMODES = (CLM_FIRST+43); // for 'hide offline', wParam=PF2_ flags and MODEF_OFFLINE
+ CLM_GETEXSTYLE = (CLM_FIRST+44); // returns CLS_EX_ flags
+ CLM_SETEXSTYLE = (CLM_FIRST+45); // wParam=CLS_EX_ flags
+ CLM_GETLEFTMARGIN = (CLM_FIRST+46); // returns count of pixels
+ CLM_SETLEFTMARGIN = (CLM_FIRST+47); // wParam=pixels
+ // the order of info items is never changed, so make sure you add them in the
+ // order you want them to remain
+ CLM_ADDINFOITEM = (CLM_FIRST+48); // lParam=&TCLCINFOITEM, returns hItem
+ CLM_GETITEMTYPE = (CLM_FIRST+49); // wParam=hItem, returns a CLCIT_
+ CLM_GETNEXTITEM = (CLM_FIRST+50); // wParam=flag, lParam=hItem, returns an hItem
+ CLM_GETTEXTCOLOR = (CLM_FIRST+51); // wParam=FONTID_, returns COLORREF
+ CLM_SETTEXTCOLOR = (CLM_FIRST+52); // wParam=FONTID_, lParam=COLORREF
+
+ CLCIIF_BELOWGROUPS = 1; // put it between groups and contacts, default is at top
+ CLCIIF_BELOWCONTACTS = 2; // put it at the bottom
+ CLCIIF_CHECKBOX = $40; // give this item a check box
+ CLCIIF_GROUPFONT = $80; // draw the item using FONTID_GROUPS
+
+ CLCIT_INVALID = -1;
+ CLCIT_GROUP = 0;
+ CLCIT_CONTACT = 1;
+ CLCIT_DIVIDER = 2;
+ CLCIT_INFO = 3;
+
+ CLGN_ROOT = 0;
+ CLGN_CHILD = 1;
+ CLGN_PARENT = 2;
+ CLGN_NEXT = 3;
+ CLGN_PREVIOUS = 4;
+ CLGN_NEXTCONTACT = 5;
+ CLGN_PREVIOUSCONTACT = 6;
+ CLGN_NEXTGROUP = 7;
+ CLGN_PREVIOUSGROUP = 8;
+
+ CLNF_ISGROUP = 1;
+ CLNF_ISINFO = 2;
+
+ CLN_FIRST = (0-100);
+ CLN_EXPANDED = (CLN_FIRST-0); // hItem=hGroup, action=CLE_*
+ CLN_LISTREBUILT = (CLN_FIRST-1);
+ CLN_ITEMCHECKED = (CLN_FIRST-2); // todo // hItem,action,flags valid
+ CLN_DRAGGING = (CLN_FIRST-3); // hItem,pt,flags valid. only sent when cursor outside window, return nonzero if processed
+ CLN_DROPPED = (CLN_FIRST-4); // hItem,pt,flags valid. only sent when cursor outside window, return nonzero if processed
+ CLN_LISTSIZECHANGE = (CLN_FIRST-5); // pt.y valid. the vertical height of the visible items in the list has changed.
+ CLN_OPTIONSCHANGED = (CLN_FIRST-6); // nothing valid. If you set some extended options they have been overwritten and should be re-set
+ CLN_DRAGSTOP = (CLN_FIRST-7); // hItem,flags valid. sent when cursor goes back in to the window having been outside, return nonzero if processed
+ CLN_NEWCONTACT = (CLN_FIRST-8); // hItem,flags valid. sent when a new contact is added without a full list rebuild
+ CLN_CONTACTMOVED = (CLN_FIRST-9); // hItem,flags valid. sent when contact is moved without a full list rebuild
+ CLN_CHECKCHANGED = (CLN_FIRST-10); // hItem,flags valid. sent when any check mark is changed, but only for one change if there are many
+
+type
+
+ PCLCINFOITEM = ^TCLCINFOITEM;
+ TCLCINFOITEM = record
+ cbSize: int;
+ pszText: PChar;
+ hParentGroup: THandle;
+ flags: DWORD;
+ hIcon: THandle; // todo
+ end;
+
+ PNMCLISTCONTROL = ^TNMCLISTCONTROL;
+ TNMCLISTCONTROL = record
+ hdr: TNMHDR; // depends on Windows.pas
+ hItem: THandle;
+ action: int;
+ iColumn: int; // -1 if not on an extra column
+ flags: DWORD;
+ pt: TPoint; // depends on Windows.pas
+ end;
+
+ PCLCINFOTIP = ^TCLCINFOTIP;
+ TCLCINFOTIP = record
+ cbSize: int;
+ isTreeFocused: int; // so the plugin can provide an option
+ isGroup: int; // 0 if it's contact, 1 if it's a group
+ hItem: THandle; // handle to group or contact
+ ptCursor: TPoint;
+ rcItem: TRect;
+ end;
+
+const
+
+ {
+ wParam : 0
+ lParam : Pointer to a TCLCINFOTIP structure
+ Affect : An InfoTip for an item should be shown now, see notes
+ Returns: [non zero] if you process this, because it makes no sense
+ for more than one module to process this.
+ Notes : It's upto the module where to put the InfoTip, Normally
+ it's a few pixels below and to the right of the cursor.
+ -
+ This event is called after the mouse ehas been stationary over
+ a contact for (by default) 200ms
+ }
+ ME_CLC_SHOWINFOTIP = 'CLC/ShowInfoTip';
+
+ {
+ wParam : 0
+ lParam : Pointer to an initialised TCLCINFOTIP
+ Affect : It's time to destroy an infotip, see notes
+ Notes : Only cbSize, isGroup, hItem are set
+ notes : This is sent when the mouse moves off a contact when ME_CLC_SHOWINFOTIP
+ has previously been called.
+ -
+ If you don't want this behaviour, you should have grabbed the mouse
+ capture yourself --
+ }
+ ME_CLC_HIDEINFOTIP = 'CLC/HideInfoTip';
+
+ {
+ wParam : new_time
+ lParam : 0
+ Affect : Set a new hover time before the info tip hooks are called, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : The value of this setting is applid to all current CLC windows
+ and saved to b applied to all future windows, it is persistent.
+ -
+ Time is in milliseconds, default is 750ms
+ }
+ MS_CLC_SETINFOTIPHOVERTIME = 'CLC/SetInfoTipHoverTime';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : get the hover time before the infotip hooks are called
+ returns: the hover time in MS
+ }
+ MS_CLC_GETINFOTIPHOVERTIME = 'CLC/GetInfoTipHoverTime';
+
+{$ENDIF} \ No newline at end of file
diff --git a/plugins/ShlExt/inc/m_clist.inc b/plugins/ShlExt/inc/m_clist.inc
new file mode 100644
index 0000000000..58f59fac14
--- /dev/null
+++ b/plugins/ShlExt/inc/m_clist.inc
@@ -0,0 +1,641 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_CLIST}
+{$DEFINE M_CLIST}
+
+{$ifndef STATUSMODES}
+ {$include statusmodes.inc}
+{$endif}
+
+const
+
+ // for MS_CLIST_GETSTATUSMODEDESCRIPTION
+
+ GSMDF_PREFIXONLINE = 1; // prefix "Online :" for online submodes, e.g. 'away'
+
+ // for MS_CLIST_ADDMAINMENUITEM
+
+ CMIF_GRAYED = 1;
+ CMIF_CHECKED = 2;
+ CMIF_HIDDEN = 4; // only works on contact menus
+ CMIF_NOTOFFLINE = 8; // item won't appear for contacts that are offline
+ CMIF_NOTONLINE = 16; // " online
+ CMIF_NOTONLIST = 32; // item won't appear on standard contacts
+ CMIF_NOTOFFLIST = 64; // item won't appear on contacts that have the 'NotOnList' setting
+
+ // for MS_CLIST_MODIFYMENUITEM
+
+ CMIM_NAME = $80000000;
+ CMIM_FLAGS = $40000000;
+ CMIM_ICON = $20000000;
+ CMIM_HOTKEY = $10000000;
+ CMIM_ALL = $F0000000;
+
+ // for MS_CLIST_GETCONTACTDISPLAYNAME
+
+ // will never return the user's custom name, even if that's the one to be displayed
+ GCDNF_NOMYHANDLE = 1;
+
+ // for MS_CLIST_ADDEVENT
+
+ //flashes the icon even if the user is occupied, and puts the event
+ // at the top of the queue
+ CLEF_URGENT = 1;
+ { icon will not flash forever, only a few times, e.g. online alert }
+ CLEF_ONLYAFEW = 2;
+
+ // for MS_CLIST_GETICONSIMAGELIST
+
+ IMAGE_GROUPOPEN = 11;
+ IMAGE_GROUPSHUT = 12;
+
+ // for MS_CLIST_MENUPROCESSCOMMAND
+
+ MPCF_CONTACTMENU = 1; // test commands from a contact menu
+ MPCF_MAINMENU = 2; // test commands from the main menu
+
+ // for MS_CLIST_GROUPGETNAME/2
+
+ GROUPF_EXPANDED = $04;
+ GROUPF_HIDEOFFLINE = $08;
+
+ //
+
+ SETTING_TOOLWINDOW_DEFAULT = 1;
+ SETTING_SHOWMAINMENU_DEFAULT = 1;
+ SETTING_SHOWCAPTION_DEFAULT = 1;
+ SETTING_CLIENTDRAG_DEFAULT = 0;
+ SETTING_ONTOP_DEFAULT = 1;
+ SETTING_MIN2TRAY_DEFAULT = 1;
+ SETTING_TRAY1CLICK_DEFAULT = 0;
+ SETTING_HIDEOFFLINE_DEFAULT = 0;
+ SETTING_HIDEEMPTYGROUPS_DEFAULT = 0;
+ SETTING_USEGROUPS_DEFAULT = 1;
+ SETTING_SORTBYSTATUS_DEFAULT = 0;
+ SETTING_TRANSPARENT_DEFAULT = 0;
+ SETTING_ALPHA_DEFAULT = 200;
+ SETTING_AUTOALPHA_DEFAULT = 150;
+ SETTING_CONFIRMDELETE_DEFAULT = 1;
+ SETTING_AUTOHIDE_DEFAULT = 0;
+ SETTING_HIDETIME_DEFAULT = 30;
+ SETTING_CYCLETIME_DEFAULT = 4;
+ SETTING_ALWAYSSTATUS_DEFAULT = 0;
+ SETTING_ALWAYSMULTI_DEFAULT = 0;
+ SETTING_TRAYICON_SINGLE = 0;
+ SETTING_TRAYICON_CYCLE = 1;
+ SETTING_TRAYICON_MULTI = 2;
+ SETTING_TRAYICON_DEFAULT = SETTING_TRAYICON_SINGLE;
+ SETTING_STATE_HIDDEN = 0;
+ SETTING_STATE_MINIMIZED = 1;
+ SETTING_STATE_NORMAL = 2;
+
+type
+
+ PCLISTMENUITEM = ^TCLISTMENUITEM;
+ TCLISTMENUITEM = record
+ cbSize: int; // size in bytes of this structure
+ pszName: PChar; // text of the menu item
+ flags: DWORD;
+ position: int; // approx position on the menu, lower numbers go nearer the top
+ hIcon: THandle; // icon to put by the item, if this was *not* loaded from
+ // a resource, you can delete it straight after the call
+ pszService: PChar; // name of the service to call when the service is clicked
+ pszPopupName: PChar;// name of the popup menu that this item is on, if this
+ // is NULL the iteem is on the root of the menu
+ popupPosition: int; // position of the popup menu on the root menu, ignored
+ // if pszPopupName is NULL(0) or if the popup menu already exists
+ hotKey: DWORD; // keyboard accelerator, same as lParam of WM_HOTKEY, 0 for none
+ pszContactOwner: PChar; // contact menus only, the protocol module that owns
+ // the contacts to which this to which this menu item
+ // applies, NULL(0) if it applies to all contacts.
+ // if it applies to multiple but not all protocols
+ // add multiple menu items or use ME_CLIST_PREBUILDCONTACTMENU
+ end;
+
+ PCLISTDOUBLECLICKACTION = ^TCLISTDOUBLECLICKACTION;
+ TCLISTDOUBLECLICKACTION = record
+ cbSize: int;
+ pszContactOwner: PChar; // name of the protocol owning the contact or NULL(0) for all
+ flags: DWORD; // CMIF_NOT flags above
+ pszService: PChar; // service to call on double click, is called with wParam=hContact, lParam=0
+ end;
+
+ PCLISTEVENT = ^TCLISTEVENT;
+ TCLISTEVENT = record
+ cbSize: int; // size in bytes
+ hContact: THandle; // handle to the contact to put the icon by
+ hIcon: THandle; // icon to flash!
+ flags: DWORD;
+ hDBEvent: THandle; // caller defined, but should be unique for hContact
+ lParam: LPARAM;
+ pszService: PChar; // name of service to call on activation
+ pszTooltip: PChar; // short description of the event to display as a tooltip on the systray
+ end;
+
+const
+
+ {
+ wParam : new_status
+ lParam : 0
+ Affect : Sent when the user acks to change their status, see notes
+ Notes : Also sent due to a MS_CLIST_SETSTATUSMODE
+ }
+ ME_CLIST_STATUSMODECHANGE = 'CList/StatusModeChange';
+
+ {
+ wParam : new_status
+ lParam : 0
+ Affect : Force a change of status mode, see statusmodes.inc
+ }
+ MS_CLIST_SETSTATUSMODE = 'CList/SetStatusMode';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Get the current status mode, see notes
+ Notes : This is the status, as set by the user, not any protocol specific status
+ all protocol modules will attempt to conform to this setting at ALL times.
+ }
+ MS_CLIST_GETSTATUSMODE = 'CList/GetStatusMode';
+
+ {
+ wParam : status_mode
+ lParam : flags
+ Affect : Get a textual description of the given status mode
+ Returns: pointer to a static buffer of the description of the given status mode
+ or NULL(0) if the mode was unknown.
+ Version: v0.1.0.1+
+ }
+ MS_CLIST_GETSTATUSMODEDESCRIPTION = 'CList/GetStatusModeDescription';
+
+ {
+ wParam : 0
+ lParam : Pointer to a initalised TCLISTMENUITEM structure
+ Affect : Add a new menu item to the main menu, see notes
+ Returns: A handle to the new MENU item or NULL(0) on failure
+ Notes : The given TCLISTMENUITEM.pszService in is called when the item
+ get clicked with :
+ -
+ wParam = 0, lParam = hwndContactList
+ }
+ MS_CLIST_ADDMAINMENUITEM = 'CList/AddMainMenuItem';
+
+ {
+ wParam : 0
+ lParam : Pointer to a initalised TCLISTMENUITEM structure
+ Affect : Add a new item to the user contact menus, see notes
+ Notes : exactly the same as MS_CLIST_ADDMAINMENUITEM except when an item
+ is selected, the service gets called with wParam=hContact,
+ pszContactOwner is obeyed.
+ -
+ Popup menus are not supported, pszPopupName and popupPosition
+ are ignored. If CTRL is held down when right clicking the menu
+ position numbers will be displayed in brackets afterr the menu item
+ text, this only works in debug builds!
+ }
+ MS_CLIST_ADDCONTACTMENUITEM = 'CList/AddContactMenuItem';
+
+ {
+ wParam : HMENUITEM
+ lParam : Pointer to a initalised TCLISTMENUITEM
+ Affect : Modify an existing menu item, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : hMenuItem will have been returned by MS_CLIST_ADD[MAIN]MENUITEM
+ TCLISTMENUITEM.flags should contain CMIM_* constants (see above)
+ to mark which fields should be updated, if it's not present, they
+ can't be updated -- if flags do not exist for a field it can not
+ be updated.
+ Version: v0.1.0.1+
+ }
+ MS_CLIST_MODIFYMENUITEM = 'CList/ModifyMenuItem';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : the context menu for a contact is about to be built, see notes
+ Notes : modules should use this to change menu items that are specific
+ to the contact that has them
+ Version: v0.1.0.1+
+ }
+ ME_CLIST_PREBUILDCONTACTMENU = 'CList/PreBuildContactMenu';
+
+ {
+ wParam : 0
+ lParam : Pointer to a initalised TCLISTDOUBLECLICKACTION structure
+ Affect : Sets the service to call when a contact is double-clicked, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : in case of conflicts, the first module to have registered
+ will get the double click, no others will, this service
+ will return success even for duplicates
+ -
+ This service was dropped from development during 0.3.0.0, it is no
+ longer supported, see ME_CLIST_DOUBLECLICKED
+ Version: 0.1.2.2+, 0.2.0+ ONLY (not 3.0a)
+ }
+ MS_CLIST_SETDOUBLECLICKACTION = 'CList/SetDoubleClickAction';
+
+ {
+ wParam : HCONTACT
+ lParam : <none>
+ Affect : Register with this event to be notified of a double click on the CList
+ against a HCONTACT, you will not be notified if there is a pending CList event
+ that the double click clears, (i.e. flashing icon is presented to be clicked)
+ Version: 0.3.0.0
+ }
+ ME_CLIST_DOUBLECLICKED = 'CList/DoubleClicked';
+
+ {
+ wParam : HCONTACT
+ lParam : flags
+ Affect : Gets the string that the contact list will use to represent a contact
+ Returns: Always a pointer
+ Notes : Returns a pointer to the name, will always succeed, even if it needs
+ to return "(Unknown Contact)"
+ -
+ this pointer is a statically allocated buffer which will
+ be overwritten on every call to this service, callers should make
+ sure that they copy the information before they call it again
+ Version: v0.1.2.0+, 0.2.0+ ONLY (0.3a supports the contacts module)
+ }
+ MS_CLIST_GETCONTACTDISPLAYNAME = 'CList/GetContactDisplayName';
+
+ {
+ wParam : 0
+ lParam : Pointer to a TCLISTEVENT
+ Affect : Add's an event to the list
+ Notes : The service will flash TCLISTEVENT.hIcon, next to the
+ contact, TCLISTEVENT.hContact
+ -
+ pszService is called is called wParam=hwndContactList,
+ lParam=pointer to a TCLISTEVENT.
+ -
+ the TCLISTEVENT data is invalidated after this service returns
+ so copy anything from it if required.
+ -
+ TCLISTEVENT.pszService will also be called if the user
+ double clicks on the icon, at which point it will be removed
+ from the contact lists queue automatically.
+ -
+ TCLISTEVENT.hContact and TCLISTEVENT.hDBEvent should be unique.
+ }
+ MS_CLIST_ADDEVENT = 'CList/AddEvent';
+
+ {
+ wParam : HCONTACT
+ lParam : HDBEVENT
+ Affect : Remove an event from the contact list queue
+ Returns: 0 on success, [non zero] on failure
+ }
+ MS_CLIST_REMOVEEVENT = 'Clist/RemoveEvent';
+
+ {
+ wParam : HCONTACT
+ lParam : iEvent
+ Affect : Get the details of an event in the queue, see notes
+ Returns: A CLISTEVENT* or NULL(0) on failure
+ Notes : Returns the iEvent'1st/2nd/3rd/nth elemented queried,
+ e.g. iEvent=0 will get the event that will be returned if the
+ user double clicks on that HCONTACT
+ -
+ Use HCONTACT=NULL, iEvent=0 for example to get the event
+ the user will get if they double click on the tray.
+ Version: v0.1.2.1+
+ }
+ MS_CLIST_GETEVENT = 'CList/GetEvent';
+
+ {
+ wParam : ControlID
+ lParam : Pointer to MEASUREITEMSTRUCT struct
+ Affect : Process a WM_MEASUREITEM message for user context menus, see notes
+ Notes : just because wParam, lParam is defined here, only pass them
+ opaquely to this service, as is.
+ -
+ This is just to draw icons, if it is not called, the icons
+ will not be drawn
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_MENUMEASUREITEM = 'CList/MenuMeasureItem';
+
+ {
+ wParam :
+ lParam :
+ Affect : Process a WM_DRAWITEM message for user context menus,
+ wParam, lParam should be passed from such message handler.
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_MENUDRAWITEM = 'CList/MenuDrawItem';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Built the context menu for a specific contact
+ Returns: A HMENU handle identifying the menu, thhis should be DestroyMenu()ed
+ when done.
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_MENUBUILDCONTACT = 'CList/MenuBuildContact';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Get the image list handle with all the useful icons in it
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_GETICONSIMAGELIST = 'CList/GetIconsImageList';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Get the icon that should be associated with a contact
+ Returns: an index into the contact list imagelist, if the icon
+ is a flashing icon, this service won't return information about it
+ see below
+ Version: v0.1.2.0+
+ }
+ MS_CLIST_GETCONTACTICON = 'CList/GetContactIcon';
+
+ {
+ wParam : HCONTACT
+ lParam : ICON_ID
+ Affect : The icon of a contact in the contact list has changed,
+ ICON_ID is an index to what image has changed
+ Version: v0.1.2.1+
+ }
+ ME_CLIST_CONTACTICONCHANGED = 'CList/ContactIconChanged';
+
+ // ideally only used by a CLIST UI module
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Get the handle to Miranda's main menu
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_MENUGETMAIN = 'CList/MenuGetMain';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Get a handle to Miranda's status menu
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_MENUGETSTATUS = 'CList/MenuGetStatus';
+
+ {
+ wParam : MAKEWPARAM(LOWORD(wParam of WM_COMMAND),flags)
+ lParam : HCONTACT
+ Affect : Process a mennu selection from a menu, see notes
+ Returns: True if it processed the command, False otherwise
+ notes : hContact is the currently selected contact, it is not used
+ if this is a main menu command, if this is NULL then the command
+ is a contact menu one, the command is ignored
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_MENUPROCESSCOMMAND = 'CList/MenuProcessCommand';
+
+ {
+ wParam : virtual key code
+ lParam : MPCF_* flags
+ Affect : Process a menu hotkey, see notes
+ Returns: True if it processed the command, False otherwise
+ Notes : this should be called in WM_KEYDOWN
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_MENUPROCESSHOTKEY = 'CList/MenuProcessHotkey';
+
+ {
+ wParam : Pointer to a MSG structurer
+ lParam : Pointer to an LRESULT
+ Affect : Process all the messages required for docking, see notes
+ Returns: True if the message should NOT be processed anymore, False otherwise
+ Notes : only msg.hwnd, msg.message, msg.wParam and msg.lParam are used
+ your WndProc should return the lResult if AND only IF, TRUE is returned
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_DOCKINGPROCESSMESSAGE = 'CList/DockingProcessMessage';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Determines wheter the contact list docked
+ Returns: pnon zero] if the contact list is docked, or 0 if it's not
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_DOCKINGISDOCKED = 'CList/DockingIsDocked';
+
+ {
+ wParam : Pointer to a TMSG
+ lParam : Pointer to an LRESULT
+ Affect : Process all the messages required for the tray icon, see notes
+ Returns: TRUE if the message should not be processed anymore, False otherwise
+ Notes : Only msg.hwnd, msg.message, msg.wparam and msg.lParam are used
+ your WndProc should return LRESULT if and ONLY if TRUE is returned
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_TRAYICONPROCESSMESSAGE = 'CList/TrayIconProcessMessage';
+
+ {
+ wParam : Pointer to TMSG
+ lParam : Pointer to an LRESULT
+ Affect : Process all the messages required for hotkeys, see notes
+ Returns: True if the message should not be processed anymore or False otherwise
+ Notes : only msg.hwnd, msg.message, msg.wParam, msg.lParam are used
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_HOTKEYSPROCESSMESSAGE = 'CList/HotkeysProcessMessage';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Toggles the show/hide status of the contact list
+ Returns: 0 on success, [non zero] on failure
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_SHOWHIDE = 'CList/ShowHide';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : temporarily disable the autohide feature, see notes
+ Notes : this service will restart the auto hide timer, so if you need
+ to keep the window visible you'll have to bee getting user input
+ or calling this service each time
+ Version: v0.1.2.1+
+ }
+ MS_CLIST_PAUSEAUTOHIDE = 'CList/PauseAutoHide';
+
+ {
+ wParam : HPARENTGROUP
+ lParam : 0
+ Affect : Create a new group and calls CLUI to display it, see notes
+ Returns: A handle to the new group.
+ Notes : If HPARENTGROUP is NULL(0) it will create a group at the root.
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_GROUPCREATE = 'CList/GroupCreate';
+
+ {
+ wParam : HGROUP
+ lParam : 0
+ Affect : Delete a group and call CLUI to display the change
+ Returns: 0 on success, [non zero] on failure
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_GROUPDELETE = 'CList/GroupDelete';
+
+ {
+ wParam : HGROUP
+ lParam : newState
+ Affect : Change the expanded state flag for a group internally, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : if newState is non zero then the group is expanded, 0 it's collapsed
+ CLUI IS *NOT* called when the change is made.
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_GROUPSETEXPANDED = 'CList/GroupSetExpanded';
+
+ {
+ wParam : HGROUP
+ lParam : MAKELPARAM(flags, flagsMask)
+ Affect : Change the flag for a group, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : only if flags given in flagsmask are altered,
+ CLUI is called on change to GROUPF_HIDEOFFLINE
+ Version: v0.1.2.1+
+ }
+ MS_CLIST_GROUPSETFLAGS = 'CList/GroupSetFlags';
+
+ {
+ wParam : HGROUP
+ lParam : Pointer to a integer to be filled with expanded state
+ Affect : get the name of a group, see notes
+ Returns: a static buffer pointing to the name of the group
+ returns NULL(0) if HGROUP is invalid.
+ Notes : the returned buffer is only valid til the next call
+ to this service, lParam can be NULL(0) if you don't
+ want to know if the group is expanded
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_GROUPGETNAME = 'CList/GroupGetName';
+
+ {
+ wParam : HGROUP
+ lParam : Pointer to flags
+ Affect : Get the name of the group, see notes
+ Returns: A static buffer pointing to the name of the group
+ returns NULL(0) if HGROUP is invalid
+ Note : this buffer is only valid til the next call to this service
+ flags can be NULL(0), otherwise it'll return GROUPF_* constants
+ Version: v0.1.2.1+
+ }
+ MS_CLIST_GROUPGETNAME2 = 'CList/GroupGetName2';
+
+ {
+ wParam : HGROUP
+ lParam : HBEFOREGROUP
+ Affect : Move a group directly before another group
+ Returns: the new handle of the group on success, NULL(0) on failure
+ Notes : the order is represented by the order in which MS_CLUI_GROUPADDED
+ is called, however UI's are free to ignore this order and sort
+ if they wish.
+ Version: v0.1.2.1+
+ }
+ MS_CLIST_GROUPMOVEBEFORE = 'CList/GroupMoveBefore';
+
+ {
+ wParam : HGROUP
+ lParam : Pointer to a null terminated string containing the new name
+ Affect : Rename a group internally, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : this will fail if the group name is a duplicate of an existing
+ a name, CLUI is not called when this change is made.
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_GROUPRENAME = 'CList/GroupRename';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Build a menu of the group tree, see notes
+ Returns: Handle to the menu, NULL(0) on failure
+ Notes : NULL be returned if the user doesn't have any groups
+ the dwItemData of every menu item is the handle to that group.
+ Menu item ID's are assigned starting at 100 in no particular order
+ Version: v0.1.2.1+
+ }
+ MS_CLIST_GROUPBUILDMENU = 'CList/GroupBuildMenu';
+
+ {
+ wParam : newValue
+ lParam : 0
+ Affect : Changes the 'hide offline contacts' flag and calls CLUI, see notes
+ Returns: 0 success, [non zero] on failure
+ Notes : newValue is 0 to show all contacts, 1 to show only online contacts
+ -1 to toggle the value
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_SETHIDEOFFLINE = 'CList/SetHideOffline';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Do the message processing associated with the double clicking a contact
+ Returns: 0 on success, [non zero] on failure
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_CONTACTDOUBLECLICKED = 'CList/ContactDoubleClicked';
+
+ {
+ wParam : HCONTACT
+ lParam : Pointer to an array of pchar's containing files/dirs
+ Affect : Do the processing when some files are droppeed on a contact, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : the array is terminated when a NULL(0) entry is found
+ Version: v0.1.2.1+
+ }
+ MS_CLIST_CONTACTFILESDROPPED = 'CList/ContactFilesDropped';
+
+ {
+ wParam : HCONTACT
+ lParam : HGROUP
+ Affect : Change the group a contact belongs to, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : use hGroup=NULL(0) to remove any group association with the contact
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_CONTACTCHANGEGROUP = 'CList/ContactChangeGroup';
+
+ {
+ wParam : HCONTACT_1
+ lParam : HCONTACT_2
+ Affect : Determine the ordering of two given contacts
+ Returns: 0 if hContact1 is the same as hContact2
+ 1 if hContact1 should be displayed before hContact2
+ -1 if hContact1 should be displayed after hCotnact2
+ Version: v0.1.1.0+
+ }
+ MS_CLIST_CONTACTSCOMPARE = 'CList/ContactsCompare';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_clui.inc b/plugins/ShlExt/inc/m_clui.inc
new file mode 100644
index 0000000000..09f2b999a3
--- /dev/null
+++ b/plugins/ShlExt/inc/m_clui.inc
@@ -0,0 +1,215 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_CLUI}
+{$DEFINE M_CLUI}
+
+ {<</
+ this header was created for use for v0.1.1.0, most of it's UI related
+ stuff and you probably don't need to call it, see m_clist.inc instead.
+ -- There are some functions that were implemented in v0.1.2.0 though
+ />>}
+
+const
+
+ {
+ wParam : 0
+ lParam : 0
+ Affects: Returns a window handle for the contact list window, see notes
+ Returns: ""
+ Notes : This call has a very specific purpose internally Miranda
+ and shouldn't be used gratuitously, in almost all cases
+ there's another call to do whatever it is that you're
+ trying to do.
+ }
+ MS_CLUI_GETHWND = 'CLUI/GetHwnd';
+
+ {
+ wParam : new status
+ lParam : null terminated string to a protocol ID
+ Affects: Change the protocol specific status indicators, see notes!
+ Returns: 0 on success, [non zero] on failure
+ Notes : protocol modules don't want to call this, they want
+ clist/protocolstatuschanged instead
+ }
+ MS_CLUI_PROTOCOLSTATUSCHANGED = 'CLUI/ProtocolStatusChanged';
+
+ {
+ wParam : Handle to a group
+ lParam : 1 or 0
+ Affect : A new group was created, add it to the list, see notes
+ Notes : lParam is set to 1 or 0 if the user just created
+ the group or not.
+ -
+ this is also called when the contact list is being rebuilt,
+ new groups are always created with the name 'New group'
+ }
+ MS_CLUI_GROUPADDED = 'CLUI/GroupCreated';
+
+ {
+ wParam : HCONTACT
+ lParam : ICON_ID
+ Affect : Change the icon for a contact, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : ICON_ID is an offset in the imagelist, see clist/geticonsimagelist
+ }
+ MS_CLUI_CONTACTSETICON = 'CLUI/ContactSetIcon';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Remove a contact from the list, see notes
+ Returns: 0 on success, [non zereo] on failure
+ Notes : this contact is NOT actually being deleted, since if
+ a contact goes offline while 'hide offline' option is sset,
+ this service will be called then ALSO
+ }
+ MS_CLUI_CONTACTDELETED = 'CLUI/ContactDeleted';
+
+ {
+ wParam : HCONTACT
+ lParam : ICON_ID
+ Affect : Add a contact to the list, see note
+ returns: 0 on success, [non zero] on failure
+ Notes : the caller processes the 'hide offline' setting, so the callee
+ should not do further processing based on the value of this setting
+ -
+ WARNING: this will be called to re-add a contact when they come
+ online if 'hide offline' is on, but it cannot determine if
+ the contact is already on the list, so you may get requests to
+ add a contact when it is already on the list, which you should ignore.
+ -
+ You'll also get this whenever an event is added for a contact,
+ since if the contact was offline, it needs to be shown to
+ display the mesage, even if 'hide offlines' is on.
+ -
+ you should not resort the list on this call, a seperate resort
+ request will be sent.
+ -
+ ICON_ID is an offset in the image list, see clist/geticonsimagelist
+
+ }
+ MS_CLUI_CONTACTADDED = 'CLUI/ContactAdded';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Reename a contact in the lists, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : You should not re-sort the list on this call, a separate resort
+ request will be sent, you can get the new name from clist/getcontactdisplayname
+ }
+ MS_CLUI_CONTACTRENAMED = 'CLUI/ContactRenamed';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Start a rebuild of the contact list, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : this is the cue to clear the existing content of the list
+ expect to get a series of :
+
+ clui/groupadded
+ clui/contactadded
+ clui/resortlist
+ }
+ MS_CLUI_LISTBEGINREBUILD = 'CLUI/ListBeginRebuild';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : End a rebuild of the contact list, see notes
+ Returns: 0 on success, [non zero] on error
+ Notes : if you dissplayed an hourglass in beginbuild, set it back
+ here, you do not need to explicitly sort the list
+ }
+ MS_CLUI_LISTENDREBUILD = 'CLUI/ListEndRebuild';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Sort the contact list now, see notes
+ Returns: 0 success, [non zero] on failure
+ Notes : Sorts are buffered so you won't get this message lots of times
+ if the lists needs to be resorted many times rapidly
+ }
+ MS_CLUI_SORTLIST = 'CLUI/SortList';
+
+ {
+ wParam : CLUICAPS_*
+ lParam : 0
+ Affect : Gets a load of capabilites for the loaded CLUI, see notes
+ Returns: the requested value, 0 of wParam is unknown --
+ if this service is not implemented it is assumed all return
+ values will be 0.
+ Version: v0.1.2.1+
+ }
+
+ { can only provide this flag to return the following set of caps, the strings
+ show the database setting/type to store the list option, changing the value
+ does not reflect what the change is, i.e. ontop can only be affected with
+ a call to SetWindowPos() }
+ CLUICAPS_FLAGS1 = 0;
+ { empty groups aren't shown, 'CList/HideEmptyGroups' (byte) [changes make the list reload] }
+ CLUIF_HIDEEMPTYGROUPS = 1;
+ { groups can be disabled, lists can be merged into one seamlessly, (byte) 'CList/UseGroups' }
+ CLUIF_DISABLEGROUPS = 2;
+ { list can be displayed 'on top' of all other windows, 4 (byte) 'CList/OnTop' }
+ CLUIF_HASONTOPOPTION = 4;
+ { can disappear after a while of inactive use,
+ (byte) 'CList/AutoHide' (word) 'CList/HideTime' }
+ CLUIF_HASAUTOHIDEOPTION = 8;
+
+ MS_CLUI_GETCAPS = 'CLUI/GetCaps';
+
+ {
+ wParam : HCONTACT
+ lParam : MAKELPARAM(screenX, screenY)
+ Affect : A contact is being dragged outside the main window
+ Return : return [non zero] to show the drag cursor as "accepting" the drag
+ or zero to show the circle/slash 'not allowed'
+ Version: v0.1.2.0+
+ }
+ ME_CLUI_CONTACTDRAGGING = 'CLUI/ContactDragging';
+
+ {
+ wParam : HCONTACT
+ lParam : MAKELPARAM(screenX, screenY)
+ Affect : a contact has just been dropped outside the main window, see notes
+ Notes : return non zero to stop other hooks processing this event.
+ Version: v0.1.2.0+
+ }
+ ME_CLUI_CONTACTDROPPED = 'CLUI/ContactDropped';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : A contact that *was* being dragged outside the main window
+ has gone back to the main window
+ Return : always return 0
+ Version: v0.1.2.1+
+ }
+ ME_CLUI_CONTACTDRAGSTOP = 'CLUI/ContactDragStop';
+
+{$ENDIF} \ No newline at end of file
diff --git a/plugins/ShlExt/inc/m_contacts.inc b/plugins/ShlExt/inc/m_contacts.inc
new file mode 100644
index 0000000000..7ba6f68bbb
--- /dev/null
+++ b/plugins/ShlExt/inc/m_contacts.inc
@@ -0,0 +1,90 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+type
+
+ PCONTACTINFO = ^TCONTACTINFO;
+ TCONTACTINFO = record
+ cbSize: int;
+ dwFlag: Byte;
+ hContact: THandle;
+ szProto: PChar;
+ type_: Byte;
+ retval: record (* in C this is a nameless union *)
+ case longint of
+ 0: (bVal: Byte);
+ 1: (wVal: WORD);
+ 2: (dVal: DWORD);
+ 3: (pszVal: PChar);
+ 4: (cchVal: Word);
+ end;
+ end;
+
+const
+
+// CNF_* Types of information you can retreive by setting the dwFlag in CONTACTINFO
+
+ CNF_FIRSTNAME = 1; // returns first name (string)
+ CNF_LASTNAME = 2; // returns last name (string)
+ CNF_NICK = 3; // returns nick name (string)
+ CNF_CUSTOMNICK = 4; // returns custom nick name, clist name (string)
+ CNF_EMAIL = 5; // returns email (string)
+ CNF_CITY = 6; // returns city (string)
+ CNF_STATE = 7; // returns state (string)
+ CNF_COUNTRY = 8; // returns country (string)
+ CNF_PHONE = 9; // returns phone (string)
+ CNF_HOMEPAGE = 10; // returns homepage (string)
+ CNF_ABOUT = 11; // returns about info (string)
+ CNF_GENDER = 12; // returns gender (byte,'M','F' character)
+ CNF_AGE = 13; // returns age (byte, 0==unspecified)
+ CNF_FIRSTLAST = 14; // returns first name + last name (string)
+ CNF_UNIQUEID = 15; // returns uniqueid, protocol username (must check type for type of return)
+
+// Special types
+// Return the custom name using the name order setting
+// IMPORTANT: When using CNF_DISPLAY you MUST free the string returned
+// You must **NOT** do this from your version of free() you have to use Miranda's free()
+// you can get a function pointer to Miranda's free() via MS_SYSTEM_GET_MMI, see m_system.h
+ CNF_DISPLAY = 16;
+// Same as CNF_DISPLAY except the custom handle is not used
+// IMPORTANT: When using CNF_DISPLAYNC you MUST free the string returned
+// You must **NOT** do this from your version of free() you have to use Miranda's free()
+// you can get a function pointer to Miranda's free() via MS_SYSTEM_GET_MMI, see m_system.h
+ CNF_DISPLAYNC = 17;
+
+// If MS_CONTACT_GETCONTACTINFO returns 0 (valid), then one of the following
+// types is setting telling you what type of info you received
+ CNFT_BYTE = 1;
+ CNFT_WORD = 2;
+ CNFT_DWORD = 3;
+ CNFT_ASCIIZ = 4;
+
+ {
+ wParam : not used
+ lParam : Pointer to an initialised TCONTACTINFO structure
+ affects: Get contact information
+ returns: Zero on success, non zero on failure.
+ notes : If successful, the type is set and the result is put into the associated member of TCONTACTINFO
+ }
+ MS_CONTACT_GETCONTACTINFO = 'Miranda/Contact/GetContactInfo';
diff --git a/plugins/ShlExt/inc/m_database.inc b/plugins/ShlExt/inc/m_database.inc
new file mode 100644
index 0000000000..f2b26508df
--- /dev/null
+++ b/plugins/ShlExt/inc/m_database.inc
@@ -0,0 +1,654 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_DATABASE}
+{$DEFINE M_DATABASE}
+
+const
+
+ DBVT_DELETED = 0; // setting got deleted, no values are valid
+ DBVT_BYTE = 1; // bVal, cVal are valid
+ DBVT_WORD = 2; // wVal, sVal are valid
+ DBVT_DWORD = 4; // dVal, lVal are valid
+ DBVT_ASCIIZ = 255; // pszVal is valid
+ DBVT_BLOB = 254; // cpbVal and pbVal are valid
+ DBVTF_VARIABLELENGTH = $80; // ?
+
+type
+
+ HCONTACT = Integer;
+ HDBEVENT = Integer;
+
+ PDBVARIANT = ^TDBVARIANT;
+ TDBVARIANT = record
+ type_: Byte;
+ case LongInt of
+ 0: (bVal: Byte);
+ 1: (cVal: Char);
+ 2: (wVal: Word);
+ 3: (sVal: SmallInt);
+ 4: (dVal: LongInt);
+ 5: (lVal: Integer);
+ 6: (
+ pszVal: PChar;
+ cchVal: Word;
+ );
+ 7: (
+ cpbVal: Word;
+ pbVal: PByte;
+ );
+ end;
+
+const
+
+ {
+ wParam : size of the buffer to be filled
+ lParam : pointer to the buffer to be filled
+ affect : Get's the name of the current profile being used by the database
+ module -- this is the same as the filename of the profile without
+ the .ext
+ return : 0 on success, non zero on failure
+ }
+ MS_DB_GETPROFILENAME = 'DB/GetProfileName';
+
+ {
+ wParam : size of buffer pointed to by lParam
+ lParam : pointer to a buffer to be filled
+ affect : Fill a buffer with the current profile path being used, this does not include the trailing backslash.
+ return : 0 on success, non zero on failure
+ version: 0.3a only
+ }
+ MS_DB_GETPROFILEPATH = 'DB/GetProfilePath';
+
+type
+
+ PDBCONTACTGETSETTING = ^TDBCONTACTGETSETTING;
+ TDBCONTACTGETSETTING = record
+ { name of the module that wrote the setting to get }
+ szModule: PChar;
+ { the name of the setting to get }
+ szSetting: PChar;
+ { pointer to DBVARIANT to receive the value -- must be allocated for GETSETTINGSTATIC
+ calls thou }
+ pValue: PDBVARIANT;
+ end;
+
+ PDBCONTACTWRITESETTING = ^TDBCONTACTWRITESETTING;
+ TDBCONTACTWRITESETTING = record
+ { module sig to write this setting under }
+ szModule: PChar;
+ { setting name to write }
+ szSetting: PChar;
+ { variant containing value to set }
+ value: TDBVARIANT;
+ end;
+
+const
+
+ {
+ wParam : Handle of a contact to get the setting for (see notes)
+ lParam : pointer to a TDBCONTACTGETSETTING structure to be filled with setting
+ this structure also has to be initalised (see notes)
+ affect : Queries the database module for a setting from a contact.
+ returns: 0 on success, non zero on failure (contact not found, setting doesn't exist)
+ notes : TDBCONTACTGETSETTING must be filled with the module name that created
+ /wrote the setting you want to get (e.g. your module name)
+ and the actual setting to read with TDBCONTACTGETSETTING.szModule and
+ TDBCONTACTGETSETTING.szSetting -- TDBCONTACTGETSETTING.pValue is
+ a pointer to a TDBVARIANT with the returned setting, this maybe nil
+ and MUST be freed after you're done with it with FreeVariant()
+
+ There are helper functions for reading/writing/deleting common types to and
+ from the database -- see DBGetContactSetting<type>
+
+ the contact handle (hContact) can be returned by FindContact/AddContact
+ }
+ MS_DB_CONTACT_GETSETTING = 'DB/Contact/GetSetting';
+
+ {
+ wParam : Handle for a contact to query a setting for
+ lParam : Pointer to a TDBCONTACTGETSETTING structure
+ affects: This service is almost the same as the one above, but it does
+ not return a dynamic copy (with malloc()) -- the caller
+ must do this for datatypes which require it, e.g. a string.
+
+ This means the TDBCONTACTGETSETTING.pValue *has* to exist and be
+ allocated by the caller (doesn't have to be allocated from the heap)
+ the DBVARIANT structure has to be initalised with the type wanted
+ and enough buffer space around to return the info, do not
+ expect this service to be as fast as the one above.
+
+ returns: 0 on success, non zero on failure.
+ }
+ MS_DB_CONTACT_GETSETTINGSTATIC = 'DB/Contact/GetSettingStatic';
+
+ {
+ wParam : 0
+ lParam : Pointer to a TDBVARIANT structure
+ affect : Free's the passed DBVARIANT's dynamic memory (if any) see notes
+ returns: 0 on success, non zero on failure
+ notes : use the helper function FreeVariant()
+ }
+ MS_DB_CONTACT_FREEVARIANT = 'DB/Contact/FreeVariant';
+
+ {
+ wParam : Handle to contact to write setting for
+ lParam : Pointer to TDBCONTACTWRITESETTING which must be initalised
+ affects: writes a setting under a contact -- TDBCONTACTWRITESETTING structure
+ must contain the module name writing -- the setting name, and the value
+ to write (which is NOT a pointer) .szModule, .szSetting, .Value, see notes
+ returns: 0 on success, non zero on failure
+ notes : this service triggers 'DB/Contact/SettingChanged' before it returns
+ as always, there is a helper function to use this service.
+ }
+ MS_DB_CONTACT_WRITESETTING = 'DB/Contact/WriteSetting';
+
+ {
+ wParam : hContact under which the setting should be deleted
+ lParam : Pointer to a TDBCONTACTGETSETTING structure
+ affects: Deletes the given setting for a contact, the TDBCONTACTGETSETTING.pValue
+ field is ignored -- only .szModule and .szSetting are needed, see notes
+ returns: 0 on success, non zero on failure
+ notes : triggers 'DB/Contact/SettingChanged' BEFORE it deletes the given
+ setting, when the service returns the TDBVARIANT structure .type_ is set
+ to 0 and no fields are valid, there is a helper function for this
+ service, see below.
+ }
+ MS_DB_CONTACT_DELETESETTING = 'DB/Contact/DeleteSetting';
+
+ {
+ wParam : Handle of a contact to enum settings for
+ lParam : Pointer to a TDBCONTACTENUMSETTINGS structure, must be initalised
+ affect : Enumerates all settings for a given contact under a module,
+ TDBCONTACTENUMSETTINGS must be filled with the function pointer to call
+ the TDBCONTACTENUMSETTINGS.lParam value to pass to it each time,
+ as well as the .szModule under which the contact is valid
+ returns: returns the value of the last call to the enum function, or -1
+ if no settings could be enumerated
+ notes : the szSetting argument passed to the enumeration function is only
+ valid for the duration of that enumeration call,
+ it must be allocated dynamically if it is required after that call frame
+ has returned.
+ Also, deleting settings as they are enumerated has unpredictable results!
+ but writing a new value for a setting is okay.
+ it is unclear how you stop the enumeration once it is started, maybe
+ possible to return -1 to stop it.
+ vesion : only valid for 0.1.0.1+
+ }
+
+type
+
+ TDBSETTINGENUMPROC = function(const szSetting: PChar; lParam: LPARAM): int; cdecl;
+
+ PDBCONTACTENUMSETTINGS = ^TDBCONTACTENUMSETTINGS;
+ TDBCONTACTENUMSETTINGS = record
+ { function pointer to call to start the enum via MS_DB_CONTACT_ENUMSETTINGS }
+ pfnEnumProc: TDBSETTINGENUMPROC;
+ { passed to the above function }
+ lParam: LPARAM;
+ { name of the module to get settings for }
+ szModule: PChar;
+ { not used by us }
+ ofsSettings: DWORD;
+ end;
+
+const
+
+ MS_DB_CONTACT_ENUMSETTINGS = 'DB/Contact/EnumSettings';
+
+ {
+ wParam : 0
+ lParam : 0
+ affect : none
+ returns: Returns the number of contacts in the database for the loaded profile
+ not including the profile user, see notes.
+ notes : the contacts in the database can be read with FindFirst/FindNext
+ }
+ MS_DB_CONTACT_GETCOUNT = 'DB/Contact/GetCount';
+
+ {
+ wParam : 0
+ lParam : 0
+ returns: Returns a handle to the first contact in the database,
+ this handle does not need to be closed, if there are no users
+ NULL(0) is returned.
+ }
+ MS_DB_CONTACT_FINDFIRST = 'DB/Contact/FindFirst';
+
+ {
+ wParam : Contact handle
+ lParam : 0
+ returns: Returns a handle to the next contact after the given contact in
+ wParam, this handle does not neeed to be closed -- may return NULL(0)
+ if the given contact in wParam was the last in the database, or the
+ given contact was invalid
+ }
+ MS_DB_CONTACT_FINDNEXT = 'DB/Contact/FindNext';
+
+ {
+ wParam : Handle of a contact to delete
+ lParam : 0
+ affect : the user by the given handle is deleted from the database, see notes
+ returns: Returns 0 on success or nonzero if the handle was invalid
+ notes : this triggers DB/Contact/Deleted BEFORE it actually deletes the contact
+ all events are also deleted -- other modules may end up with invalid
+ handles because of this, which they should be prepared for.
+ }
+ MS_DB_CONTACT_DELETE = 'DB/Contact/Delete';
+
+ {
+ wParam : 0
+ lParam : 0
+ affects: creates a new contact in the database, they have no settings,
+ settings must be added with MS_DB_CONTACT_WRITESETTING or
+ database helper functions for writing, see notes
+ returns: A handle to a new contact or NULL(0) on failure.
+ notes : triggers the ME_DB_CONTACT_ADDED event just before the service returns
+ }
+ MS_DB_CONTACT_ADD = 'DB/Contact/Add';
+
+
+ {
+ wParam : (HANDLE) hContact
+ lParam : 0
+ affects: Checks the given handle within the database for valid information, for
+ a proper internal header.
+ returns: Returns 1 if the contact handle is valid, 0 if it is not
+ notes : Due to the nature of multiple threading a contact handle can be deleted
+ soon after this service has returned a handle as valid, however it will never point
+ to another contact.
+ }
+ MS_DB_CONTACT_IS = 'DB/Contact/Is';
+
+
+ {
+ wParam : contact handle for events count is needed
+ lParam : 0
+ service: Gets the number of events in the chain belonging to a contact
+ in the databasee.
+ returns: the numbef of events owned by hContact or -1 if hContact
+ is invalid, they can be found with the event/find* servicees
+ }
+ MS_DB_EVENT_GETCOUNT = 'DB/Event/GetCount';
+
+ {
+ wParam : contact handle to add an event for
+ lParam : Pointer to TDBEVENTINFO initialised with data
+ affect : Add's an event to the contact's event list, the TDBEVENTINFO
+ structure should be filled with the event of message -- see notes
+ returns: a handle to a DB event (HDBEVENT), or NULL on error
+ notes : Triggers DB/Event/Added event just before it returns,
+ Events are sorted chronologically as they are entered,
+ so you cannot guarantee that the new hEvent is the last event in the chain,
+ however if a new event is added that has a timestamp less than
+ 90 seconds *before* the event that should be after it,
+ it will be added afterwards, to allow for protocols that only
+ store times to the nearest minute, and slight delays in transports.
+ There are a few predefined eventTypes below for easier compatibility, but
+ modules are free to define their own, beginning at 2000
+ DBEVENTINFO.timestamp is in GMT, as returned by time()
+ }
+
+ DBEF_FIRST = 1; // internally only, do not use
+ DBEF_SENT = 2; // if set, the event was sent by the user, otherwise it was received
+ DBEF_READ = 4; // event has been read by the user -- only needed for history
+
+ EVENTTYPE_MESSAGE = 0;
+ EVENTTYPE_URL = 1;
+ EVENTTYPE_CONTACTS = 2; // v0.1.2.2+
+ EVENTTYPE_ADDED = 1000; // v0.1.1.0+: these used to be module-
+ EVENTTYPE_AUTHREQUEST = 1001; // specific codes, hence the module-
+ EVENTTYPE_FILE = 1002; // specific limit has been raised to 2000
+
+type
+
+ PDBEVENTINFO = ^TDBEVENTINFO;
+ TDBEVENTINFO = record
+ { size of the structure }
+ cbSize: int;
+ { module that 'owns' this event and controls the data format }
+ szModule: PChar;
+ { timestamp in UNIX time }
+ timestamp: DWORD;
+ { the DBEF_* flags above }
+ flags: DWORD;
+ { event type, such as message, can be module defined }
+ eventType: WORD;
+ { size in bytes of pBlob^ }
+ cbBlob: DWORD;
+ { pointer to buffer containing the module defined event data }
+ pBlob: PByte;
+ end;
+
+const
+
+ MS_DB_EVENT_ADD = 'DB/Event/Add';
+
+
+
+ {
+ wParam : Handle to the contact
+ lParam : HDBEVENT handle to delete
+ affects: Removes a single event from the database for the given contact
+ returns: 0 on success, nonzero on failure
+ notes : Triggers DB/Event/Deleted just before the event *is* deleted
+ }
+ MS_DB_EVENT_DELETE = 'DB/Event/Delete';
+
+ {
+ wParam : Handle to DB event
+ lParam : 0
+ returns: Returns the space in bytes requried to store the blob in HDBEVENT
+ given by HDBEVENT(wParam) -- or -1 on error
+ }
+ MS_DB_EVENT_GETBLOBSIZE = 'DB/Event/GetBlobSize';
+
+ {
+ wParam : Handle to a DB event
+ lParam : Pointer to a TDBEVENTINFO structure which must be initialised
+ affects: Returns all the information about an DB event handle to a TDBEVENTINFO
+ structure which must be initalised, DBEI.cbSize, DBEI.pBlob and DBEI.cbSize
+ before calling this service, the size can be assertained with
+ GetBlobSize() service, see notes
+ returns: Returns 0 on success, non zero on failure
+ notes : The correct value dbe.cbBlob can be got using db/event/getblobsize
+ If successful, all the fields of dbe are filled. dbe.cbBlob is set to the
+ actual number of bytes retrieved and put in dbe.pBlob
+ If dbe.cbBlob is too small, dbe.pBlob is filled up to the size of dbe.cbBlob
+ and then dbe.cbBlob is set to the required size of data to go in dbe.pBlob
+ On return, dbe.szModule is a pointer to the database module's
+ own internal list of modules. Look but don't touch.
+ }
+ MS_DB_EVENT_GET = 'DB/Event/Get';
+
+ {
+ wParam : HCONTACT
+ lParam : HDBEVENT
+ affect : Changes the flag for an event to mark it as read
+ Returns: Returns the entire flag DWORD for the event after the change, or -1
+ if HDBEVENT is invalid, see notes
+ notes : This iss one of the database write operations that does not trigger
+ an event, modules should not save flagss states for any length of time.
+ }
+ MS_DB_EVENT_MARKREAD = 'DB/Event/MarkRead';
+
+ {
+ wParam : HDBEVENT
+ lParam : 0
+ Affect : Returns a handle to a contact that owns the HDBEVENT,
+ see notes
+ Returns: Returns a handle if successful or HDBEEVENT(-1) on failure
+ notes : This service is very slow, only use wheen you have no other choice
+ at all.
+ }
+ MS_DB_EVENT_GETCONTACT = 'DB/Event/GetContact';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Retrieves a handlee to the first event in the chain
+ for a HCONTACT
+ returns: Returns a handle, or NULL(0) if HCONTACT is invalid or has
+ no events, events in a chain are sorted chronologically automatically
+ }
+ MS_DB_EVENT_FINDFIRST = 'DB/Event/FindFirst';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Retrieves a handle to the first unreead event in a chain for a HCONTACT
+ see notes
+ Returns: Returns a HDBEVENT handle or NULL(0) if the HCONTACT is invalid
+ or all it's events have beeen read.
+ Notes : Events in a chain are sorted chronologically automatically,
+ but this does not necessarily mean that all events after
+ the first unread are unread too.
+ They should be checked individually with event/findnext and event/get
+ This service is designed for startup, reloading all the events that remained
+ unread from last time
+ }
+ MS_DB_EVENT_FINDFIRSTUNREAD = 'DB/Event/FindFirstUnread';
+
+ {
+ wParam : HCONTACT
+ lParam : 0;
+ Affects: Retrieves a handle to the lasts event in the chain for a HCONTACT
+ Returns: Returns a handle or NULL(0) if HCONTACT is invalid or has no events
+ }
+ MS_DB_EVENT_FINDLAST = 'DB/Event/FindLast';
+
+ {
+ wParam : HDBEVENT
+ lParam : 0
+ Affects: Retrieves a handle to the next event in a chain after HDBEVENT
+ Returns: A handle to the next DB event or NULL(0) if HDBEVENT is invalid
+ or the last event in the chain.
+ }
+ MS_DB_EVENT_FINDNEXT = 'DB/Event/FindNext';
+
+ {
+ wParam : HDBEVENT
+ lParam : 0
+ Affects: Retrieves a handle to the previous event in a chain before HDBEVENT
+ Returns: A handle to the previous HDBEVENT or NULL(0) if HDBEVENT is invalid
+ or is the first event in the chain
+ }
+ MS_DB_EVENT_FINDPREV = 'DB/Event/FindPrev';
+
+
+
+ {
+ wParam : size in bytes of string buffer (including null term)
+ lParam : pointer to string buffer
+ Affect : Scrambles the string buffer in place using a strange encryption algorithm,
+ see notes
+ Returns: Always returns 0
+ notes : this service may be changed at a later date such that it increasess
+ the length of the string
+ }
+ MS_DB_CRYPT_ENCODESTRING = 'DB/Crypt/EncodeString';
+
+ {
+ wParam : size in bytes of string buffer, including null term
+ lParam : pointer to string buffer
+ Affect : Descrambles pszString in-place using the strange encryption algorithm,
+ see notes.
+ Return : Always returns 0
+ notes : Reverses the operation done by MS_DB_CRYPT_ENCODINGSTRING
+ }
+ MS_DB_CRYPT_DECODESTRING = 'DB/Crypt/DecodeString';
+
+
+
+ {
+ wParam : timestamp (DWORD)
+ lParam : 0
+ Affect : Converts a GMT timestap into local time
+ Returns: Returns the converted value, see notes
+ Notes : Timestamps have a zereo at midnight 1/1/1970 GMT, this service
+ converts such a value to be based at midnight 1/1/1970 local time.
+ This service does not use a simple conversion based on the current offset
+ between GMT and local. Rather, it figures out whether daylight savings time
+ would have been in place at the time of the stamp and gives the local time as
+ it would have been at the time and date the stamp contains.
+ }
+ MS_DB_TIME_TIMESTAMPTOLOCAL = 'DB/Time/TimestampToLocal';
+
+ {
+ wParam : timestamp (DWORD)
+ lParam : pointer to initalised DBTIMETOSTRING structure
+ Affect : Converts a GMT timestamp to a customisable local time string
+ see notes
+ Returns: Always returns 0
+ notes : The string is formatted according to thhe current user's locale
+ language and preference --
+
+ .szFormat can have the following special chars :
+ t time without seconds, e.g. hh:mm
+ s time with seconds, e.g. hh:mm:ss
+ m time without minutes e.g. hh
+ d short date, e.g. dd/mm/yyyy
+ D long date, e.g. d mmmm yyyy
+
+ all other characters are copied as is.
+ }
+
+type
+
+ PDBTIMETOSTRING = ^TDBTIMETOSTRING;
+ TDBTIMETOSTRING = record
+ { format string, see above }
+ szFormat: PChar;
+ { pointer to dest buffer to store the result }
+ szDest: PChar;
+ { size of the buffer }
+ cbDest: int;
+ end;
+
+const
+
+ MS_DB_TIME_TIMESTAMPTOSTRING = 'DB/Time/TimestampToString';
+
+
+
+ {
+ wParam : newSetting (BOOLEAN)
+ lParam : 0
+ Affect : Miranda's database is normally protected against corruption by
+ aggressively flushing data to the disk on writes, if you're doing
+ alot of writes e.g. an import plugin, it can sometimes be desirable
+ to switch this feature off to speed up the process, if you do switch
+ it off, you must remember that crashes are far more likely to be
+ catastrophic, so switch it back on at the earliest possible opportunity.
+ if you're doing a lot of setting writes, the flush is already delayed
+ so you need not use this service for that purpose, see notes.
+ Returns: Always returns 0 (successful)
+ notes : This is set to true initally
+ }
+ MS_DB_SETSAFETYMODE = 'DB/SetSafetyMode';
+
+ {
+ wParam : (caller defined data) will be passed to lParam of the call back
+ lParam : function pointer to TDBMODULEENUMPROC
+ Affects: Enumerates the names of all modules that have stored or
+ requested information from the database,
+ the modules are returned in no real order --
+ Writing to the database while module names are being enumerated will cause
+ unpredictable results in the enumeration, but the write will work.
+
+ the enumeration will stop if the callback returns a non zero value.
+
+ Returns: the last return value from the enumeration call back.
+ Notes : This service is only useful for debugging or EnumSettings
+ version: The service registered to enumerate all modules that have touched
+ the database module uses wParam as the lParam cookie value and the lParam
+ value given here is the function pointer -- this is not safe
+ to use before v0.1.2.1 because I don't know if this was done in v0.1.2.1-
+
+ prior to v0.1.2.1 you can not pass a value to the enumeration because
+ of a bug -- which is fixed, but hey :) -- [sam]
+ }
+type
+ TDBMODULEENUMPROC = function(const szModule: PChar; ofsModuleName: DWORD; lParam: LPARAM): int; cdecl;
+const
+ MS_DB_MODULES_ENUM = 'DB/Modules/Enum';
+
+
+
+ {
+ wParam : HCONTACT
+ lParam : HDBCONTACT
+ Affect : Called when a new event has been added to the event chain
+ for a contact, HCONTACT contains the contact who added the event,
+ HDBCONTACT a handle to what was added.
+ see notes
+ notes : since events are sorted chronologically, you can not guarantee
+ that HDBEVEnT is in any particular position in the chain.
+
+ }
+ ME_DB_EVENT_ADDED = 'DB/Event/Added';
+
+ {
+ wParam : HANDLE (hContact)
+ lParam : @DBEVENTINFO
+ Affects: Hook is fired before any DBEVENTS are created within the database for
+ a contact (or a user, if hContact is NULL(0)) - It allows a module to
+ query/change DBEVENTINFO before it is created, see notes.
+ Returns: Hook should return 1 to stop event being added (will stop other hooks seeing the event too)
+ Or 0 to continue processing (passing the data on as well)
+ Notes : This hook is fired for all event types, and the BLOBS that the eventypes mark
+ Maybe changed, therefore be careful about using BLOB formats.
+ Because the memory pointing within the DBEVENTINFO CAN NOT BE OWNED or free()'d
+ it is recommended that the hook only be used to stop events.
+ Version: 0.3.3a+ (2003/12/03)
+ }
+ ME_DB_EVENT_FILTER_ADD = 'DB/Event/FilterAdd';
+
+ {
+ wParam : HCONTACT
+ lParam : HDBEVENT
+ Affect : Called when an event is about to be deleted from the event chain
+ for a contact, see notes
+ notes : Returning non zero from your hook will NOT stop the deletion,
+ but it will as usual stop other hooks being called
+ }
+ ME_DB_EVENT_DELETED = 'DB/Event/Deleted';
+
+
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Called when a new contact has been added to the database,
+ HCONTACT contains a handle to the new contact.
+ }
+ ME_DB_CONTACT_ADDED = 'DB/Contact/Added';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Called when a contact is about to be deleted
+ Returns: Returning nonzero from your hook will not stop the deletion
+ but it will stop the other hooks from being called
+ }
+ ME_DB_CONTACT_DELETED = 'DB/Contact/Deleted';
+
+ {
+ wParam : HCONTACT
+ lParam : Pointer to a TDBCONTACTWRITESETTING
+ Affect : Calleed when a contact has one of it's settings changed
+ hContact is a valid handle to the contact that has changed,
+ see notes.
+ notes : this event will be triggered many times rapidly when alot of values
+ are set.
+ Modules that hook this should be aware of this fact and quickly
+ return if they are not interested in the value that has changed.
+ Careful not to get into infinite loops with this event,
+
+ The TDBCONTACTWRITESETTING pointer is the same one as the
+ original service all, so don't change any of it's fields
+ }
+ ME_DB_CONTACT_SETTINGCHANGED = 'DB/Contact/SettingChanged';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_email.inc b/plugins/ShlExt/inc/m_email.inc
new file mode 100644
index 0000000000..93312c7e59
--- /dev/null
+++ b/plugins/ShlExt/inc/m_email.inc
@@ -0,0 +1,39 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+{$IFNDEF M_EMAIL}
+{$DEFINE M_EMAIL}
+
+const
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affects: Send an e-mail to the specified contact, see notes
+ Returns: Returns 0 on success or nonzero on failure
+ Notes : If an error occurs the service displays a message box
+ with the error text -- use this service to alter this
+ }
+ MS_EMAIL_SENDEMAIL = 'SREMail/SendCommand';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_file.inc b/plugins/ShlExt/inc/m_file.inc
new file mode 100644
index 0000000000..dd14286455
--- /dev/null
+++ b/plugins/ShlExt/inc/m_file.inc
@@ -0,0 +1,66 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_FILE}
+{$DEFINE M_FILE}
+
+const
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affects: Brings up the send file dialog for a contact, see notes
+ Returns: 0 on success [non zero] on failure
+ Notes : Returns immediately without waiting for the send
+ }
+ MS_FILE_SENDFILE = 'SRFile/SendCommand';
+
+ {
+ wParam : HCONTACT
+ lParam : pointer to an array of PChar's the first nil item
+ terminates the list -- see notes
+ Affects: Brings up the send file dialog with specifieed files already chosen
+ the user is not prevented from editing the list --
+ Returns: 0 on success [non zero] on failure -- returns immediately without
+ waiting for the send to finish
+ Notes : both directories and files can be given
+ Version: v0.1.2.1+
+ }
+ MS_FILE_SENDSPECIFICFILES = 'SRFile/SendSpecificFiles';
+
+ {
+ wParam : HCONTACT
+ lParam : Pointer to a buffer
+ Affects: returns the received files folder for a contact, the buffer
+ should be at least MAX_PATH long (defined with WinAPI),
+ the returned path may not exist -- see notes
+ Returns: Returns 0 on success [non zero] on failure
+ notes : If HCONTACT is NULL(0) the path returned is the path
+ without the postfix contact name.
+ Version: v0.1.2.2+
+ }
+ MS_FILE_GETRECEIVEDFILESFOLDER = 'SRFile/GetReceivedFilesFolder';
+
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_findadd.inc b/plugins/ShlExt/inc/m_findadd.inc
new file mode 100644
index 0000000000..61b0d066b1
--- /dev/null
+++ b/plugins/ShlExt/inc/m_findadd.inc
@@ -0,0 +1,38 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+{$IFNDEF M_FINDADD}
+{$DEFINE M_FINDADD}
+
+const
+
+ {
+ wParam : 0
+ lParam : 0
+ Affects: Openss the find/add users dialog box, or gives it focus if it's
+ already open.
+ Returns: Always returns 0
+ }
+ MS_FINDADDFINDADD = 'FindAdd/FindAddCommand';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_globaldefs.pas b/plugins/ShlExt/inc/m_globaldefs.pas
new file mode 100644
index 0000000000..614719a68c
--- /dev/null
+++ b/plugins/ShlExt/inc/m_globaldefs.pas
@@ -0,0 +1,99 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFDEF FPC}
+ {$PACKRECORDS C}
+ {$MODE Delphi}
+{$ENDIF}
+
+unit m_globaldefs;
+
+interface
+
+uses
+
+{$ifdef FPC}
+ strings;
+{$else}
+ Windows;
+{$endif}
+
+type
+
+ PByte = ^Byte;
+ int = Integer;
+ pint = ^int;
+ WPARAM = Integer;
+ LPARAM = Integer;
+ DWORD = Integer;
+ THandle = Integer;
+
+ // strcpy()
+
+ {$ifdef FPC}
+ TStrCpy = function(Dst, Src: PChar): PChar;
+ {$else}
+ TStrCpy = function(Dst, Src: PChar): PChar; stdcall;
+ {$endif}
+
+ // strcat()
+
+ {$ifdef FPC}
+ TStrCat = function(Dst, Src: PChar): PChar;
+ {$else}
+ TStrCat = function(Dst, Src: PChar): PChar; stdcall;
+ {$endif}
+
+const
+
+ {$ifdef FPC}
+ strcpy: TStrCpy = strings.strcopy;
+ {$else}
+ strcpy: TStrCpy = lstrcpy;
+ {$endif}
+
+ {$ifdef FPC}
+ strcat: TStrCat = strings.strcat;
+ {$else}
+ strcat: TStrCat = lstrcat;
+ {$endif}
+
+ {$include newpluginapi.inc}
+ {$include m_v8.inc}
+
+var
+ { this is now a pointer to a record of function pointers to match the C API,
+ and to break old code and annoy you. }
+
+ PLUGINLINK: PPLUGINLINK;
+
+ { has to be returned via MirandaPluginInfo and has to be statically allocated,
+ this means only one module can return info, you shouldn't be merging them anyway! }
+
+ PLUGININFO: TPLUGININFO;
+ PLUGININFOEX: TPLUGININFOEX;
+
+implementation
+
+end.
diff --git a/plugins/ShlExt/inc/m_globaldefs.ppu b/plugins/ShlExt/inc/m_globaldefs.ppu
new file mode 100644
index 0000000000..dff0527ff7
--- /dev/null
+++ b/plugins/ShlExt/inc/m_globaldefs.ppu
Binary files differ
diff --git a/plugins/ShlExt/inc/m_helpers.inc b/plugins/ShlExt/inc/m_helpers.inc
new file mode 100644
index 0000000000..ef8edeb088
--- /dev/null
+++ b/plugins/ShlExt/inc/m_helpers.inc
@@ -0,0 +1,613 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$ifdef M_API_UNIT}
+
+ function PLUGIN_MAKE_VERSION(a,b,c,d: Cardinal): int;
+ function PLUGIN_CMP_VERSION(verA: LongInt; verB: LongInt): int;
+
+{$else}
+
+ function PLUGIN_MAKE_VERSION(a,b,c,d: Cardinal): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := (a shl 24) or (b shl 16) or (c shl 8) or d;
+ end;
+
+ function PLUGIN_CMP_VERSION(verA: LongInt; verB: LongInt): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := 0;
+ { could be used to compare for severity of age for positive values, if a<b
+ results are minus values, 0 for equal, positive if a is newer }
+ Inc(Result, (verA and $FF) - (verB and $FF));
+ Inc(Result, (verA and $FF00) - (verB and $FF00));
+ Inc(Result, (verA and $FF0000) - (verB and $FF0000));
+ Inc(Result, (verA and $FF000000) - (verB and $FF000000));
+ end;
+
+{$endif}
+
+{$ifdef M_SYSTEM}
+ {$ifdef M_API_UNIT}
+
+ function CallService(const szService: PChar; wParam: WPARAM; lParam: LPARAM): int;
+
+ function HookEvent(const szHook: PChar; hook_proc: TMIRANDAHOOK): int;
+
+ function CreateServiceFunction(const szName: PChar; const MirandaService: TMIRANDASERVICE): int;
+
+ {$else}
+
+ function CallService(const szService: PChar; wParam: WPARAM; lParam: lParam): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := PluginLink^.CallService(szService, wParam, lParam);
+ end;
+
+ function HookEvent(const szHook: PChar; hook_proc: TMIRANDAHOOK): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := PluginLink^.HookEvent(szHook, @hook_proc);
+ end;
+
+ function CreateServiceFunction(const szName: PChar; const MirandaService: TMIRANDASERVICE): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := PluginLink^.CreateServiceFunction(szName, @MirandaService);
+ end;
+
+ {$endif}
+
+{$endif}
+
+{$ifdef M_DATABASE}
+
+ {$ifdef M_API_UNIT}
+
+ function DBGetContactSettingByte(hContact: THandle;
+ const szModule: PChar; const szSetting: PChar; errorValue: Integer): Integer;
+
+ function DBGetContactSettingWord(hContact: THandle;
+ const szModule: PChar; const szSetting: PChar; errorValue: Integer): Integer;
+
+ function DBGetContactSettingDword(hContact: THandle;
+ const szModule: PChar; const szSetting: PChar; errorValue: Integer): Integer;
+
+ function DBGetContactSetting(hContact: THandle;
+ const szModule: PChar; const szSetting: PChar; dbv: PDBVARIANT): Integer;
+
+ function DBFreeVariant(dbv: PDBVARIANT): Integer;
+
+ function DBDeleteContactSetting(hContact: THandle; const szModule: PChar; const szSetting: PChar): Integer;
+
+ function DBWriteContactSettingByte(hContact: THandle; const szModule: PChar; const szSetting: PChar; val: Byte): Integer;
+
+ function DBWriteContactSettingWord(hContact: THandle; const szModule: PChar; const szSetting: PChar; val: Word): Integer;
+
+ function DBWriteContactSettingDWord(hContact: THandle; const szModule: PChar; const szSetting: PChar; val: LongInt): Integer;
+
+ function DBWriteContactSettingString(hContact: THandle; const szModule: PChar; const szSetting: PChar; const val: PChar): Integer;
+
+ {$else}
+
+ function DBGetContactSettingByte(hContact: THandle;
+ const szModule: PChar; const szSetting: PChar; errorValue: Integer): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ dbv: TDBVARIANT;
+ cgs: TDBCONTACTGETSETTING;
+ begin
+
+ cgs.szModule := szModule;
+ cgs.szSetting := szSetting;
+ cgs.pValue := @dbv;
+
+ If PluginLink^.CallService(MS_DB_CONTACT_GETSETTING, hContact, lParam(@cgs)) <> 0 then
+ Result := ErrorValue
+ else
+ Result := dbv.bVal;
+ end;
+
+ function DBGetContactSettingWord(hContact: THandle;
+ const szModule: PChar; const szSetting: PChar; errorValue: Integer): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ dbv: TDBVARIANT;
+ cgs: TDBCONTACTGETSETTING;
+ begin
+ cgs.szModule := szModule;
+ cgs.szSetting := szSetting;
+ cgs.pValue := @dbv;
+ If PluginLink^.CallService(MS_DB_CONTACT_GETSETTING, hContact, lParam(@cgs)) <> 0 then
+ Result := ErrorValue
+ else
+ Result := dbv.wVal;
+ end;
+
+ function DBGetContactSettingDword(hContact: THandle;
+ const szModule: PChar; const szSetting: PChar; errorValue: Integer): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ dbv: TDBVARIANT;
+ cgs: TDBCONTACTGETSETTING;
+ begin
+ cgs.szModule := szModule;
+ cgs.szSetting := szSetting;
+ cgs.pValue := @dbv;
+ If PluginLink^.CallService(MS_DB_CONTACT_GETSETTING, hContact, lParam(@cgs)) <> 0 then
+ Result := ErrorValue
+ else
+ Result := dbv.dVal;
+ end;
+
+ function DBGetContactSetting(hContact: THandle;
+ const szModule: PChar; const szSetting: PChar; dbv: PDBVARIANT): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ cgs: TDBCONTACTGETSETTING;
+ begin
+ cgs.szModule := szModule;
+ cgs.szSetting := szSetting;
+ cgs.pValue := dbv;
+ Result := PluginLink^.CallService(MS_DB_CONTACT_GETSETTING, hContact, lParam(@cgs));
+ end;
+
+ function DBFreeVariant(dbv: PDBVARIANT): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := PluginLink^.CallService(MS_DB_CONTACT_FREEVARIANT, 0, lParam(dbv));
+ end;
+
+ function DBDeleteContactSetting(hContact: THandle; const szModule: PChar; const szSetting: PChar): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ cgs: TDBCONTACTGETSETTING;
+ begin
+ cgs.szModule := szModule;
+ cgs.szSetting := szSetting;
+ Result := PluginLink^.CallService(MS_DB_CONTACT_DELETESETTING, hContact, lParam(@cgs));
+ end;
+
+ function DBWriteContactSettingByte(hContact: THandle; const szModule: PChar; const szSetting: PChar; val: Byte): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ cws: TDBCONTACTWRITESETTING;
+ begin
+ cws.szModule := szModule;
+ cws.szSetting := szSetting;
+ cws.value.type_ := DBVT_BYTE;
+ cws.value.bVal := Val;
+ Result := PluginLink^.CallService(MS_DB_CONTACT_WRITESETTING, hContact, lParam(@cws));
+ end;
+
+ function DBWriteContactSettingWord(hContact: THandle; const szModule: PChar; const szSetting: PChar; val: Word): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ cws: TDBCONTACTWRITESETTING;
+ begin
+ cws.szModule := szModule;
+ cws.szSetting := szSetting;
+ cws.value.type_ := DBVT_WORD;
+ cws.value.wVal := Val;
+ Result := PluginLink^.CallService(MS_DB_CONTACT_WRITESETTING, hContact, lParam(@cws));
+ end;
+
+ function DBWriteContactSettingDWord(hContact: THandle; const szModule: PChar; const szSetting: PChar; val: LongInt): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ cws: TDBCONTACTWRITESETTING;
+ begin
+ cws.szModule := szModule;
+ cws.szSetting := szSetting;
+ cws.value.type_ := DBVT_DWORD;
+ cws.value.dVal := Val;
+ Result := PluginLink^.CallService(MS_DB_CONTACT_WRITESETTING, hContact, lParam(@cws));
+ end;
+
+ function DBWriteContactSettingString(hContact: THandle; const szModule: PChar; const szSetting: PChar; const val: PChar): Integer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ cws: TDBCONTACTWRITESETTING;
+ begin
+ cws.szModule := szModule;
+ cws.szSetting := szSetting;
+ cws.value.type_ := DBVT_ASCIIZ;
+ cws.value.pszVal := Val;
+ Result := PluginLink^.CallService(MS_DB_CONTACT_WRITESETTING, hContact, lParam(@cws));
+ end;
+
+ {$endif}
+
+{$endif}
+
+{$ifdef M_NETLIB}
+
+ {$ifdef M_API_UNIT}
+
+ function Netlib_CloseHandle(Handle: THandle): int;
+
+ function Netlib_GetBase64DecodedBufferSize(const cchEncoded: int): int;
+
+ function Netlib_GetBase64EncodedBufferSize(const cbDecoded: int): int;
+
+ function Netlib_Send(hConn: THandle; const buf: PChar; len: int; flags: int): int;
+
+ function Netlib_Recv(hConn: THandle; const buf: PChar; len: int; flags: int): int;
+
+ procedure Netlib_Log(hNetLib: THandle; const sz: PChar);
+
+ {$else}
+
+ function Netlib_CloseHandle(Handle: THandle): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := PluginLink^.CallService(MS_NETLIB_CLOSEHANDLE, Handle, 0);
+ end;
+
+ function Netlib_GetBase64DecodedBufferSize(const cchEncoded: int): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := (cchEncoded shr 2) * 3;
+ end;
+
+ function Netlib_GetBase64EncodedBufferSize(const cbDecoded: int): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := (cbDecoded * 4+11) div 12*4+1;
+ end;
+
+ function Netlib_Send(hConn: THandle; const buf: PChar; len: int; flags: int): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ nlb: TNETLIBBUFFER;
+ begin
+ nlb.buf := buf;
+ nlb.len := len;
+ nlb.flags := flags;
+ Result := PluginLink^.CallService(MS_NETLIB_SEND, wParam(hConn), lParam(@nlb));
+ end;
+
+ function Netlib_Recv(hConn: THandle; const buf: PChar; len: int; flags: int): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ nlb: TNETLIBBUFFER;
+ begin
+ nlb.buf := buf;
+ nlb.len := len;
+ nlb.flags := flags;
+ Result := PluginLink^.CallService(MS_NETLIB_RECV, wParam(hConn), lParam(@nlb));
+ end;
+
+ procedure Netlib_Log(hNetLib: THandle; const sz: PChar);
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ PluginLink^.CallService(MS_NETLIB_LOG, hNetLib, lParam(sz));
+ end;
+
+ {$endif}
+
+{$endif}
+
+{$ifdef M_UTILS}
+
+ {$ifdef M_API_UNIT}
+
+ function WindowList_Add(hList: THandle; hWnd: HWND; hContact: THandle): int;
+
+ function WindowList_Remove(hList: THandle; hWnd: THandle): int;
+
+ function WindowList_Find(hList: THandle; hContact: THandle): int;
+
+ function WindowList_Broadcast(hList: THandle; message: int; wParam: WPARAM; lParam: LPARAM): int;
+
+ function Utils_SaveWindowPosition(hWnd: THandle; hContact: THandle; const szModule, szNamePrefix: PChar): int;
+
+ function Utils_RestoreWindowPosition(hWnd: THandle; hContact: THandle; Flags: int; const szModule, szNamePrefix: PChar): int;
+
+ {$else}
+
+ function WindowList_Add(hList: THandle; hWnd: hWnd; hContact: THandle): int;
+ var
+ wle: TWINDOWLISTENTRY;
+ begin
+ wle.hList := hList;
+ wle.hWnd := hWnd;
+ wle.hContact := hContact;
+ Result := PluginLink^.CallService(MS_UTILS_ADDTOWINDOWLIST, 0, lParam(@wle));
+ end;
+
+ function WindowList_Remove(hList: THandle; hWnd: THandle): int;
+ begin
+ Result := PluginLink^.CallService(MS_UTILS_REMOVEFROMWINDOWLIST, hList, hWnd);
+ end;
+
+ function WindowList_Find(hList: THandle; hContact: THandle): int;
+ begin
+ Result := PluginLink^.CallService(MS_UTILS_FINDWINDOWINLIST, hList, hContact);
+ end;
+
+ function WindowList_Broadcast(hList: THandle; message: int; wParam: WPARAM; lParam: LPARAM): int;
+ var
+ msg: TMSG;
+ begin
+ msg.message := message;
+ msg.wParam := wParam;
+ msg.lParam := lParam;
+ Result := PluginLink^.CallService(MS_UTILS_BROADCASTTOWINDOWLIST, hList, Integer(@Msg));
+ end;
+
+ function Utils_SaveWindowPosition(hWnd: THandle; hContact: THandle; const szModule, szNamePrefix: PChar): int;
+ var
+ swp: TSAVEWINDOWPOS;
+ begin
+ swp.hWnd := hWnd;
+ swp.hContact := hContact;
+ swp.szModule := szModule;
+ swp.szNamePrefix := szNamePrefix;
+ Result := PluginLink^.CallService(MS_UTILS_SAVEWINDOWPOSITION, 0, lParam(@swp));
+ end;
+
+ function Utils_RestoreWindowPosition(hWnd: THandle; hContact: THandle; Flags: int; const szModule, szNamePrefix: PChar): int;
+ var
+ swp: TSAVEWINDOWPOS;
+ begin
+ swp.hWnd := hWnd;
+ swp.hContact := hContact;
+ swp.szModule := szModule;
+ swp.szNamePrefix := szNamePrefix;
+ Result := PluginLink^.CallService(MS_UTILS_RESTOREWINDOWPOSITION, Flags, lParam(@swp));
+ end;
+
+ {$endif}
+
+{$endif}
+
+{$ifdef M_LANGPACK}
+
+ {$ifdef M_API_UNIT}
+
+ function Translate(sz: PChar): PChar;
+
+ function TranslateString(sz: string): string;
+
+ function TranslateDialogDefault(hwndDlg: THandle): int;
+
+ {$else}
+
+ function Translate(sz: PChar): PChar;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ { the return value maybe NULL(0) -- it's upto the caller to know if the allocated
+ string has to be removed from the DLL heap, this has little to do with Miranda,
+ but if a dynamic string is passed and a return string is used -- the dynamic
+ string is lost -- be careful, lazy? use TranslateString (note it's slower) }
+ Result := PChar(PluginLink^.CallService(MS_LANGPACK_TRANSLATESTRING, 0, lParam(sz)));
+ end;
+
+ function TranslateString(sz: string): string;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := string(PChar( PluginLink^.CallService(MS_LANGPACK_TRANSLATESTRING, 0, lParam(sz))));
+ end;
+
+ function TranslateDialogDefault(hwndDlg: THandle): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ lptd: TLANGPACKTRANSLATEDIALOG;
+ begin
+ lptd.cbSize := sizeof(lptd);
+ lptd.flags := 0;
+ lptd.hwndDlg := hwndDlg;
+ lptd.ignoreControls := nil;
+ Result := PluginLink^.CallService(MS_LANGPACK_TRANSLATEDIALOG, 0, lParam(@lptd));
+ end;
+
+ {$endif}
+
+{$endif}
+
+{$ifdef M_PROTOCOLS}
+ {$ifdef M_API_UNIT}
+
+ function CallContactService(hContact: THandle; const szProtoService: PChar; wParam: WPARAM; lParam: LPARAM): int;
+
+ function CallProtoService(const szModule, szService: PChar; wParam: WPARAM; lParam: LPARAM): int;
+
+ {$else}
+
+ function CallContactService(hContact: THandle; const szProtoService: PChar; wParam: WPARAM; lParam: LPARAM): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ css: TCCSDATA;
+ begin
+ css.hContact := hContact;
+ css.szProtoService := szProtoService;
+ css.wParam := wParam;
+ css.lParam := lParam;
+ Result := PluginLink^.CallService(MS_PROTO_CALLCONTACTSERVICE, 0, Integer(@css));
+ end;
+
+ function CallProtoService(const szModule, szService: PChar; wParam: WPARAM; lParam: LPARAM): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ szStr: array[0..MAXMODULELABELLENGTH] of Char;
+ begin
+ strcpy(szStr, szModule);
+ strcat(szStr, szService);
+ Result := PluginLink^.CallService(szStr, wParam, lParam);
+ end;
+
+ {$endif}
+{$endif}
+
+{$ifdef M_PROTOMOD}
+ {$ifdef M_API_UNIT}
+
+ function ProtoBroadcastAck(const szModule: PChar; hContact: THandle; type_: int; result_: int; hProcess: THandle; lParam: LPARAM): int;
+
+ function CreateProtoServiceFunction(const szModule, szService: PChar; serviceProc: TMIRANDASERVICE): int;
+
+ {$else}
+
+ function ProtoBroadcastAck(const szModule: PChar; hContact: THandle; type_: int; result_: int; hProcess: THandle; lParam: LPARAM): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ ack: TACKDATA;
+ begin
+ ack.cbSize := sizeof(TACKDATA);
+ ack.szModule := szModule;
+ ack.hContact := hContact;
+ ack.type_ := type_;
+ ack.result_ := result_;
+ ack.hProcess := hProcess;
+ ack.lParam := lParam;
+ Result := PluginLink^.CallService(MS_PROTO_BROADCASTACK, 0, Integer(@ack));
+ end;
+
+ function CreateProtoServiceFunction(const szModule, szService: PChar; serviceProc: TMIRANDASERVICE): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ szStr: array[0..MAXMODULELABELLENGTH] of Char;
+ begin
+ strcpy(szStr, szModule);
+ strcat(szStr, szService);
+ Result := PluginLink^.CreateServiceFunction(szStr, @serviceProc);
+ end;
+
+ {$endif}
+
+{$endif}
+
+{$ifdef M_SKIN}
+
+ {$ifdef M_API_UNIT}
+
+ function LoadSkinnedIcon(id: int): THandle;
+
+ function LoadSkinnedProtoIcon(const szProto: PChar; status: int): THandle;
+
+ function SkinAddNewSound(const name, description, defaultFile: PChar): int;
+
+ function SkinPlaySound (const name: PChar): int;
+
+ {$else}
+
+ function LoadSkinnedIcon(id: int): THandle;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := PluginLink^.CallService(MS_SKIN_LOADICON, id, 0);
+ end;
+
+ function LoadSkinnedProtoIcon(const szProto: PChar; status: int): THandle;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := PluginLink^.CallService(MS_SKIN_LOADPROTOICON, wParam(szProto), status);
+ end;
+
+ function SkinAddNewSound(const name, description, defaultFile: PChar): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ ssd: TSKINSOUNDDESC;
+ begin
+ ssd.cbSize := sizeof(ssd);
+ ssd.pszName := name;
+ ssd.pszDescription := description;
+ ssd.pszDefaultFile := defaultFile;
+ Result := PluginLink^.CallService(MS_SKIN_ADDNEWSOUND, 0, lParam(@ssd));
+ end;
+
+ function SkinPlaySound (const name: PChar): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := PluginLink^.CallService(MS_SKIN_PLAYSOUND, 0, lParam(name));
+ end;
+
+ {$endif}
+
+{$endif}
diff --git a/plugins/ShlExt/inc/m_history.inc b/plugins/ShlExt/inc/m_history.inc
new file mode 100644
index 0000000000..325afad909
--- /dev/null
+++ b/plugins/ShlExt/inc/m_history.inc
@@ -0,0 +1,37 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+{$IFNDEF M_HISTORY}
+{$DEFINE M_HISTORY}
+
+const
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affects: Show's the history dialog box for a contact, see notes
+ Notes : HCONTACT can be NULL(0) to show system messages
+ }
+ MS_HISTORY_SHOWCONTACTHISTORY = 'History/ShowContactHistory';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_icq.inc b/plugins/ShlExt/inc/m_icq.inc
new file mode 100644
index 0000000000..d359eae928
--- /dev/null
+++ b/plugins/ShlExt/inc/m_icq.inc
@@ -0,0 +1,191 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_ICQ}
+{$DEFINE M_ICQ}
+
+const
+
+ // extra database event type
+ ICQEVENTTYPE_WEBPAGER = 2003;
+
+ // extra flags for PSS_MESSAGE
+ PIMF_ROUTE_DEFAULT = 0;
+ PIMF_ROUTE_DIRECT = $10000;
+ PIMF_ROUTE_THRUSERVER = $20000;
+ PIMF_ROUTE_BESTWAY = $30000;
+ PIMF_ROUTE_MASK = $30000;
+
+ // for SMS
+
+ ICQACKTYPE_SMS = 1001;
+ ICQEVENTTYPE_SMS = 2001; // database event type
+
+ // for e-mail express
+
+ {
+ BLOB:
+ text: ASCIIZ usually in the form "Subject: %s\r\n%s"
+ from-name: ASCIIZ
+ from-e-mail: ASCIIZ
+ }
+
+ ICQEVENTTYPE_EMAILEXPRESS = 2002;
+
+ // for server side lists, used internally only
+
+ // hProcess=dwSequence, lParam=server's error code, 0 for success
+ ICQACKTYPE_SERVERCLIST = 1003;
+
+{$ifndef m_protosvc}
+ {$include m_protosvc.inc}
+{$endif}
+
+type
+
+ PICQSEARCHRESULT = ^TICQSEARCHRESULT;
+ TICQSEARCHRESULT = record
+ hdr: TPROTOSEARCHRESULT;
+ uin: DWORD;
+ auth: Byte;
+ end;
+
+ PICQDETAILSSEARCH = ^TICQDETAILSSEARCH;
+ TICQDETAILSSEARCH = record
+ nick: PChar;
+ firstName: PChar;
+ lastNamee: PChar;
+ end;
+
+const
+
+ {
+ wParam : 0
+ lParam : null terminated string containing e-mail to search
+ affects: Start a search for all ICQ users by e-mail -- see notes
+ returns: Returnss a handle to the search on success, NULL(0) on failure
+ notes : uses the same scheme as PSS_BASICSEARCH,
+ *DEPRECATED* in favour of PS_SEARCHBYEMAIL
+ }
+ MS_ICQ_SEARCHBYEMAIL = 'ICQ/SearchByEmail';
+
+ {
+ wParam : 0
+ lParam : POinter to a TICQDETAILSSEARCH structure
+ Affect : Start a search of all ICQ users by details, see notes
+ Returns: A handle to the search on success, NULL(0) on failure
+ Notes : Results are returned in the same scheme as in PSS_BASICSEARCH,
+ Not recommended, use PS_SEARCHBYNAME
+ }
+ MS_ICQ_SEARCHBYDETAILS = 'ICQ/SearchByDetails';
+
+ {
+ wParam : Pointer to a null terminated string containing phone number
+ lParam : Pointer to a null terminated string containing the message
+ Affect : Send an SMS via the ICQ network, See notes
+ Returns: Handle to the send on success, NULL(0) on failure
+ Notes : the phone number should be the full number with internation code
+ and prefixed by + e.g. +44<numba>
+ }
+ MS_ICQ_SENDSMS = 'ICQ/SendSMS';
+
+ {
+ wParam : level
+ lParam : null terminated string containing logging message
+ Affect : a logging message was sent from ICQLib
+ }
+ ME_ICQ_LOG = 'ICQ/Log';
+
+{$ENDIF}
+
+ {$ifdef __}
+//Changing user info:
+//See documentation of PS_CHANGEINFO
+//The changing user info stuff built into the protocol is purposely extremely
+//thin, to the extent that your data is passed as-is to the server without
+//verification. Don't mess up.
+//Everything is byte-aligned
+//WORD: 2 bytes, little-endian (that's x86 order)
+//DWORD: 4 bytes, little-endian
+//LNTS: a WORD containing the length of the string, followed by the string
+// itself. No zero terminator.
+#define ICQCHANGEINFO_MAIN 0xEA03
+/* pInfoData points to:
+ WORD datalen
+ LNTS nick
+ LNTS first
+ LNTS last
+ LNTS email
+ LNTS city
+ LNTS state
+ LNTS phone
+ LNTS fax
+ LNTS street
+ LNTS cellular (if SMS-able string contains an ending ' SMS')
+ LNTS zip
+ WORD country
+ BYTE gmt
+ BYTE unknown, usually 0
+*/
+#define ICQCHANGEINFO_MORE 0xFD03
+/* pInfoData points to:
+ WORD datalen
+ BYTE age
+ BYTE 0
+ BYTE sex
+ LNTS homepage
+ WORD birth-year
+ BYTE birth-month
+ BYTE birth-day
+ BYTE lang1
+ BYTE lang2
+ BYTE lang3
+*/
+#define ICQCHANGEINFO_ABOUT 0x0604
+/* pInfoData points to:
+ WORD datalen
+ LNTS about
+*/
+#define ICQCHANGEINFO_WORK 0xF303
+/* pInfoData points to:
+ WORD datalen
+ LNTS city
+ LNTS state
+ DWORD 0
+ LNTS street
+ LNTS zip
+ WORD country
+ LNTS company-name
+ LNTS company-dept
+ LNTS company-position
+ WORD 0
+ LNTS company-web
+*/
+#define ICQCHANGEINFO_PASSWORD 0x2E04
+/* pInfoData points to:
+ WORD datalen
+ LNTS newpassword
+*/
+ {$endif}
+
diff --git a/plugins/ShlExt/inc/m_ignore.inc b/plugins/ShlExt/inc/m_ignore.inc
new file mode 100644
index 0000000000..e4c9e3c062
--- /dev/null
+++ b/plugins/ShlExt/inc/m_ignore.inc
@@ -0,0 +1,74 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+{$IFNDEF M_IGNORE}
+{$DEFINE M_IGNORE}
+
+ { this module only provides UI and storage for blocking only, protocol modules
+ are responsible for implementing the block }
+
+const
+
+ IGNOREEVENT_ALL = LPARAM(-1);
+ IGNOREEVENT_MESSAGE = 1;
+ IGNOREEVENT_URL = 2;
+ IGNOREEVENT_FILE = 3;
+ IGNOREEVENT_USERONLINE = 4;
+ IGNOREEVENT_AUTHORIZATION=5;
+ IGNOREEVENT_YOUWEREADDED=6; // 0.3.3a+
+
+ {
+ wParam : HCONTACT
+ lParam : IGNOREEVENT_*
+ Affects: Determines if a message type to a contact should be ignored, see notes
+ Returns: 0 if the message type MUST be shown [non zero] if it MUST be ignored
+ Notes : HCONTACT can be NULL(0) to see what to do with a contact
+ that isn't on the list (or is unknown in some way)
+ don't use the IGNOREEVENT_ALL type!
+ Version: v0.1.0.1+
+ }
+ MS_IGNORE_ISIGNORED = 'Ignore/IsIgnored';
+
+ {
+ wParam : HCONTACT
+ lParam : IGNOREEVENT_* constant
+ Affects: Ignore future messages from a contact, see notes
+ Returns: 0 on success, [nonzero] on failure
+ Notes : wParam: NULL(0) can be used to see if an unknown contact should be ignored
+ or not - you can't SET unknown contact's ignore types, this is to stop
+ a plugin allowing certain functions (I guess)
+ Version: v0.1.0.1+
+ }
+ MS_IGNORE_IGNORE = 'Ignore/Ignore';
+
+ {
+ wParam : HCONTACT
+ lParam : IGNOREEVENT_*
+ Affects: Receive future messages from a contact -- of the given type, see notes
+ Returns: 0 on success, non zero on failure
+ Notes : Use NULL(0) for HCONTACT to retrieve the setting for an unknown contact
+ Version: v0.1.0.1+
+ }
+ MS_IGNORE_UNIGNORE = 'Ignore/Unignore';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_langpack.inc b/plugins/ShlExt/inc/m_langpack.inc
new file mode 100644
index 0000000000..498f844997
--- /dev/null
+++ b/plugins/ShlExt/inc/m_langpack.inc
@@ -0,0 +1,82 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_LANGPACK}
+{$DEFINE M_LANGPACK}
+
+const
+
+ {
+ wParam : 0
+ lParam : pointer to a null terminated string
+ Affects: Returns a pointer to a localised string, if there is no known
+ translation it will return lParam, the return value does *not*
+ have to be freed in anyway (if successful) -- see notes
+ Returns: a pointer to a null terminated string
+ Notes : No check is done to see if Miranda has the required version
+ Version: v0.1.1.0+
+ }
+ MS_LANGPACK_TRANSLATESTRING = 'LangPack/TranslateString';
+
+ {
+ wParam : 0
+ lParam : Pointer to a LANGPACKTRANSLATEDIALOG initialised structure, see notes
+ Affects: Translates a dialog into the user's local language
+ Returns: 0 on successs [non zero] on failure
+ Notes : this service only knows about the following window classes/elements:
+ Window titles, STATIC, EDIT, Hyperlink, BUTTON.
+ Version: v0.1.1.0+
+ }
+
+type
+
+ PLANGPACKTRANSLATEDIALOG = ^TLANGPACKTRANSLATEDIALOG;
+ TLANGPACKTRANSLATEDIALOG = record
+ cbSize: int;
+ flags: DWORD;
+ hwndDlg: THandle;
+ ignoreControls: ^Integer; // pointer to an array of integers? mebbe?
+ end;
+
+const
+
+ { translate all edit controls, by default non-read-only edit controls are not }
+ LPTDF_NOIGNOREEDIT = 1;
+ { don't translate the title of the dialog }
+ LPTDF_NOTITLE = 2;
+
+ MS_LANGPACK_TRANSLATEDIALOG = 'LangPack/TranslateDialog';
+
+ {
+ wParam : HMENU handle (WinAPI handle to a menu)
+ lParam : 0
+ Affects: Translates a menu into the user's local language -- see notes
+ Returns: 0 on success [non zero] on failure
+ Notes : This doesn't work with owner draw menus that store their
+ captions in a structure known by the owner -- something to be aware of ;)
+ version: v0.1.1.0+
+ }
+ MS_LANGPACK_TRANSLATEMENU = 'LangPack/TranslateMenu';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_message.inc b/plugins/ShlExt/inc/m_message.inc
new file mode 100644
index 0000000000..5cee0040b3
--- /dev/null
+++ b/plugins/ShlExt/inc/m_message.inc
@@ -0,0 +1,57 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_MESSAGE}
+{$DEFINE M_MESSAGE}
+
+const
+
+ {
+ wParam : HCONTACT
+ lParam : Pointer to a null terminated string
+ Affects: brings up the send message dialog for a contact, see notes
+ Returns: 0 on success, non zero on failure
+ Notes : returns immediately, just after the send dialog is shown,
+ the lParam is entered into the editbox of the window,
+ but it's not sent.
+ Version: v0.1.2.0+ only supports a string, prior NULL(0) is expected
+ this service was defined as 'SRMsg/LaunchMessageWindow'
+ use both if compatibility use both, the correct one will work,
+ but don't rely on the message to be displayed
+
+ }
+ MS_MSG_SENDMESSAGE = 'SRMsg/SendCommand';
+ MS_MSG_SENDMESSAGE_OLD = 'SRMsg/LaunchMessageWindow';
+
+ {
+ wParam : 0
+ lParam : Pointer to a null termed string
+ Affects: displays the send message dialog with the 'multiple' option open
+ and no contacts selected
+ Returns: Returns 0 on success, nonzero on failure
+ Version: only present after v0.1.2.1+
+ }
+ MS_MSG_FORWARDMESSAGE = 'SRMsg/ForwardMessage';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_netlib.inc b/plugins/ShlExt/inc/m_netlib.inc
new file mode 100644
index 0000000000..11334c9897
--- /dev/null
+++ b/plugins/ShlExt/inc/m_netlib.inc
@@ -0,0 +1,713 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_NETLIB}
+{$DEFINE M_NETLIB}
+
+{>>/
+
+ NetLib :
+
+ Instead of you writing all the code for working with sockets and supporting
+ app level protocols such as SOCKS5, it's all done for you.
+
+ NetLib takes care of all that and you can even register a special abstract
+ nexus, e.g. ICQ direct, the user can configure all this from the options dialog
+ and you don't have to bother with any of it.
+
+ NetLib wraps up any Winsock calls but you can still get the socket handle
+ from your netlib handle and do stuff.
+
+ It gives all modules an abstract way of dealing with transport -- mainly sockets
+ and proxies, Now the but..
+
+ It's new (mmmm) thus unsupported by any older version of Miranda, and if you
+ want to be lazy and not write any "wrapper" mini netlib then you'll have
+ the kudos of "only works with nightly build version of Miranda" :)
+
+/<<}
+
+ {$ifndef M_SYSTEM}
+ {$include m_system.inc}
+ {$endif}
+
+const
+
+ // for TNETLIBUSER.flags
+
+ { bind incoming ports }
+ NUF_INCOMING = $01;
+ { makes outgoing plain connections }
+ NUF_OUTGOING = $02;
+ { can use HTTP gateway for plain sockets. ???HttpGateway* are valid,
+ enables the HTTP proxy option, displayed in options }
+ NUF_HTTPGATEWAY = $04;
+ { don't show this as an entry for custom settings to be defined for,
+ TNETLIB.szDescriptiveName is ignored }
+ NUF_NOOPTIONS = $08;
+ { some connections are made for HTTP communication,
+ enables the HTTP proxy option, displayed in options }
+ NUF_HTTPCONNS = $10;
+ { Disables the HTTPS proxy option in options, Use this if all communication
+ is HTTP }
+ NUF_NOHTTPSOPTION = $20;
+
+ // for TNETLIBUSERSETTINGS.proxyType
+
+ { SOCKS4 -- No DNS or multi addressing mode (proxy side) -- optional username can
+ be given, no password }
+ PROXYTYPE_SOCKS4 = 1;
+ { SOCKS5 -- DNS names can be given as addresses to connect to, optional
+ plain text username/password scheme (which may cause failure due to denied access)
+ IP address maybe returned for DNS addresses -- thus server side DNS }
+ PROXYTYPE_SOCKS5 = 2;
+ PROXYTYPE_HTTP = 3;
+ PROXYTYPE_HTTPS = 4;
+
+ // for TNETLIBOPENCONNECTION.flags
+
+ { this connection will be useed for HTTP communications,
+ if configured for an HTTP(S) proxy the connection is opened as if there
+ was no proxy }
+
+ NLOCF_HTTP = $0001;
+
+ // for TNETLIBHTTPPROXYINFO.flags
+
+ { append sequence numbers to GET requests }
+ NLHPIF_USEGETSEQUENCE = $0001;
+ { append sequence numbers to POST requests }
+ NLHPIF_USEPOSTSEQUENCE = $0002;
+ { GET and POST use the same sequence }
+ NLHPIF_GETPOSTSAMESEQUENCE = $0004;
+
+ // for TNETLIBHTTPREQUEST.flags, .requestType
+
+ { used by MS_NETLIB_RECVHTTPHEADERS returned structure }
+
+ REQUEST_RESPONSE = 0;
+ REQUEST_GET = 1;
+ REQUEST_POST = 2;
+ REQUEST_CONNECT = 3;
+
+ { auto generate a 'host' header from .szUrl }
+ NLHRF_GENERATEHOST = $00000001;
+ { remove any host and/or protocol portion of szUrl before sending it }
+ NLHRF_REMOVEHOST = $00000002;
+ { removes host and/or protocol from szUrl unless the connection was
+ opened through an HTTP or HTTPS proxy. }
+ NLHRF_SMARTREMOVEHOST = $00000004;
+ { if the connection was opened through an HTTP or HTTPS proxy then
+ send a Proxy-Authorization header if required. }
+ NLHRF_SMARTAUTHHEADER = $00000008;
+ { never dump this to the log }
+ NLHRF_NODUMP = $00010000;
+ { don't dump http headers (only useful for POSTs and MS_NETLIB_HTTPTRANSACTION }
+ NLHRF_NODUMPHEADERS = $00020000;
+ { this transaction is a proxy communication. For dump filtering only. }
+ NLHRF_DUMPPROXY = $00040000;
+ { dump posted and reply data as text. Headers are always dumped as text. }
+ NLHRF_DUMPASTEXT = $00080000;
+
+ // for TNETLIBBUFFER.flags
+
+ { don't wrap outgoing packet using TNETLIBUSER.pfnHttpGatewayWrapSend }
+ MSG_NOHTTPGATEWAYWRAP = $010000;
+ { don't dump this packet to the log }
+ MSG_NODUMP = $020000;
+ { this iss proxy communication, for dump filtering only }
+ MSG_DUMPPROXY = $040000;
+ { don't dump as hex, it's text }
+ MSG_DUMPASTEXT = $080000;
+ { send as raw, bybpass HTTP proxy stuff }
+ MSG_RAW = $100000;
+
+
+ // all record types structures are declared in their own block because the C header
+ // file used forward declaration (to get typed parameters for certain function pointers)
+ // This sort of define-type-pointer-before-type can only be done in the same type block
+ // in D2 (don't know about later versions)
+
+type
+
+ { forward typed pointers to records }
+
+ PNETLIBOPENCONNECTION = ^TNETLIBOPENCONNECTION;
+ PNETLIBHTTPREQUEST = ^TNETLIBHTTPREQUEST;
+
+ { This function pointer is to the CRT realloc() used by Miranda -- it allows reallocation of memory passed
+ to us (not that we could EVER share the same CRT) but to allow DLLs in general to reallocate memory }
+ TNetlibRealloc = function(Mem: Pointer; size_t: int): Pointer; cdecl;
+ TNetlibHTTPGatewayInitProc = function(hConn: THandle; nloc: PNETLIBOPENCONNECTION; nlhr: PNETLIBHTTPREQUEST): int; cdecl;
+ TNetlibHTTPGatewayBeginProc = function(hConn: THandle; nloc: PNETLIBOPENCONNECTION): int; cdecl;
+ TNetlibHTTPGatewayWrapSendProc = function(hConn: THandle; buf: PByte; len: int; flags: int; pfnNetLibSend: TMIRANDASERVICE): int; cdecl;
+ TNetlibHTTPGatewayUnwrapRecvProc = function(nlhr: PNETLIBHTTPREQUEST; buf: PByte; len: int; outBufLen: pInt; NetlibRealloc: TNetlibRealloc): PByte; cdecl;
+
+ PNETLIBUSER = ^TNETLIBUSER;
+ TNETLIBUSER = record
+ cbSize: int;
+ { used for DB settings and log, 'NL' stuff }
+ szSettingsModule: PChar;
+ { shows a descriptive name for which different proxy settings can be defined }
+ szDescriptiveName: PChar;
+ { see NUF_* constants above }
+ flags: DWORD;
+ szHttpGatewayHello: PChar;
+ { can be NULL(0) to send no User-Agent: also used by HTTPS proxies }
+ szHttpGatewayUserAgent: PChar;
+ pfnHttpGatewayInit: TNetlibHTTPGatewayInitProc;
+ { can be NULL(0) if no begin is required }
+ pfnHttpGatewayBegin: TNetlibHTTPGatewayBeginProc;
+ { can be NULL(0) if no wrapping is required }
+ pfnHttpGatewayWrapSend: TNetlibHTTPGatewayWrapSendProc;
+ { can be NULL(0) " " }
+ pfnHttpGatewayUnwrapRecv: TNetlibHTTPGatewayUnwrapRecvProc;
+ { only if NUF_INCOMING, will be used for validation of user input }
+ minIncomingPorts: int;
+ end;
+
+ PNETLIBUSERSETTINGS = ^TNETLIBUSERSETTINGS;
+ TNETLIBUSERSETTINGS = record
+ { filled before calling }
+ cbSize: int;
+ { 1 or 0 }
+ useProxy: int;
+ { PROXYTYPE_* constant, see above }
+ proxyType: int;
+ { can be NULL(0) }
+ szProxyServer: PChar;
+ { in host byte order }
+ wProxyPort: int;
+ { 1 or 0, always 0 for SOCKS4 (doesn't have auth) }
+ useProxyAuth: int;
+ { can be NULL(0), always used by SOCKS4 }
+ szProxyAuthUser: PChar;
+ { can be NULL(0) }
+ szProxyAuthPassword: PChar;
+ { 1 or 0, only used by HTTP, HTTPS }
+ useProxyAuthNtlm: int;
+ { 1 or 0 }
+ dnsThroughProxy: int;
+ { 1 or 0 }
+ specifyIncomingPorts: int;
+ { can be NULL(0), form '1024-1050,1060-1070,2000' }
+ szIncomingPorts: PChar;
+ end;
+
+ TNetlibNewConnectionProc = procedure(hNewConnection: THandle; dwRemoveIP: DWORD); cdecl;
+
+ PNETLIBBIND = ^TNETLIBBIND;
+ TNETLIBBIND = record
+ cbSize: int;
+ { function to call when there's a new connection, dwRemoteIP is in host byte
+ order -- the handle is to the new connection }
+ pfnNewConnection: TNetlibNewConnectionProc;
+ { set on return, host byte order }
+ dwInternalIP: DWORD;
+ { set on return, host byte order }
+ wPort: WORD;
+ end;
+
+ { Pointered type is above }
+ TNETLIBOPENCONNECTION = record
+ cbSize: int;
+ szHost: PChar; // can be an IP in string form
+ wPort: Word;
+ flags: DWORD; // see NLOCF_* flags
+ end;
+
+ PNETLIBHTTPPROXYINFO = ^TNETLIBHTTPPROXYINFO;
+ TNETLIBHTTPPROXYINFO = record
+ cbSize: int;
+ { see NLHPIF_* above }
+ flags: DWORD;
+ szHttpPostUrl: PChar;
+ szHttpGetUrl: PChar;
+ firstGetSequence: int;
+ firstPostSequence: int;
+ end;
+
+ PNETLIBBASE64 = ^TNETLIBBASE64;
+ TNETLIBBASE64 = record
+ pszEncoded: PChar;
+ cchEncoded: int;
+ pbDecoded: PByte;
+ cbDecoded: int;
+ end;
+
+ PNETLIBHTTPHEADER = ^TNETLIBHTTPHEADER;
+ TNETLIBHTTPHEADER = record
+ szName: PChar;
+ szValue: PChar;
+ end;
+
+ { PNETLIBHTTPREQUEST = ^TNETLIBHTTPREQUEST, defined above because this is
+ forward referenced from there }
+ TNETLIBHTTPREQUEST = record
+ cbSize: int;
+ requestType: int; // REQUEST_* constant
+ flags: DWORD;
+ szUrl: PChar;
+ { doesn't contain Content-Length, it'll be added automatically }
+ headers: PNETLIBHTTPHEADER; // pointer to an array of em?
+ headersCount: int; // yes they do
+ pData: PChar; // data to be sent on POST request
+ dataLength: int; // must be 0 for REQUEST_GET/REQUEST_CONNECT
+ resultCode: int;
+ szResultDescr: PChar;
+ end;
+
+ PNETLIBBUFFER = ^TNETLIBBUFFER;
+ TNETLIBBUFFER = record
+ buf: PChar;
+ len: int;
+ { see MSG_* constants above }
+ flags: int;
+ end;
+
+ PNETLIBSELECT = ^TNETLIBSELECT;
+ TNETLIBSELECT = record
+ cbSize: int;
+ dwTimeout: DWORD; // in milliseconds, INFINITE is acceptable
+ hReadConns: array[0..64+1] of THandle;
+ hWriteConns: array[0..64+1] of THandle;
+ hExceptConns: array[0..64+1] of THandle;
+ end;
+
+ PNETLIBPACKETRECVER = ^TNETLIBPACKETRECVER;
+ TNETLIBPACKETRECVER = record
+ cbSize: int;
+ { infinite is allowed -- initialise before use }
+ dwTimeout: DWORD;
+ { this many bytes are removed from the start of the buffer,
+ set to 0 on return -- initialise before use }
+ bytesUsed: int;
+ { equal the returnd value by service, unless the return value is 0 (connection closed) }
+ bytesAvailable: int;
+ { same as the parameter given to MS_NETLIB_CREATEPACKETRECVER: wParam }
+ bufferSize: int;
+ { contains the read data }
+ buffer: PByte;
+ end;
+
+const
+
+ {
+ wParam : 0
+ lParam : Pointer to an initalised TNETLIBUSER structure
+ Affects: Initialises the netlib for a set of connections, see notes
+ Returns: Returns a handle for future netlib calls, NULL on failure.
+ Notes : Netlib is loaded AFTER all plugins, thus a call to this service
+ in Load() will fail, hook ME_SYSTEM_MODULESLOADED and call it
+ from there.
+ -
+ Netlib will save settings under .szSettings module, all settings
+ (being?) begin with 'NL'.
+ -
+ Defacto settings are the same as <All connections> combobox entry option
+ as seen in Miranda->Options->Network
+ Version: v0.1.2.2+
+ Errors : ERROR_INVALID_PARAMETER, ERROR_OUTOFMEMORY, ERROR_DUP_NAME
+ }
+ MS_NETLIB_REGISTERUSER = 'Netlib/RegisterUser';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to a initalised TNETLIBUSERSETTINGS structure
+ Affects: Gets the user configured settings for a Netlib user, see notes
+ Returns: [non zero] on SUCCESS, NULL(0) on failure
+ Notes : .cbSize must be filled with sizeof() before calling --
+ the returned null terminated strings (in the structure) are valid
+ as long as HANDLE remains open or proxy options are changed
+ again, do not rely on them being around forever.
+ Version: v0.1.2.2+
+ Errors : ERROR_INVALID_PARAMETER
+ }
+ MS_NETLIB_GETUSERSETTINGS = 'Netlib/GetUserSettings';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to a initalised NETLIBUSERSETTINGS structure
+ Affect : Changes the configurable settings for a Netlib user -- see notes
+ Returns: [non zero] on success, NULL(0) on failure
+ Notes : This service is only really useful for people that specify NUF_NOOPTIONS
+ when registering and want to create their own options.
+ Settings will be stored even if the option to enable it, is it not enabled,
+ e.g. useProxyAuth is 0, szProxyAuthPassword will still be saved
+ Errors : ERROR_INVALID_PARAMETER
+ }
+ MS_NETLIB_SETUSERSETTINGS = 'Netlib/SetUserSettings';
+
+ {
+ wParam : HANDLE / SOCKET
+ lParam : 0
+ Affects: Closes a handle, see notes
+ Returns: Returns [non zero] on success, NULL(0) on failure
+ Notes : All netlib handles should be closed once they're finished with,
+ If a SOCKET type is passed instead of netlib handle type, it is closed
+ Errors : ERROR_INVALID_PARAMETER
+ }
+ MS_NETLIB_CLOSEHANDLE = 'Netlib/CloseHandle';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to a initialised TNETLIBBIND
+ Affects: Open a port and wait for connections on it -- see notes
+ Returns: Returns a handle on success, NULL(0) on failure
+ Notes : this function does the equivalent of socket(), bind(), getsockname(),
+ listen(), accept() -- internally this function creates a new thread
+ which waits around in accept() for new connections.
+ When one is received, TNETLIBBIND.pfnNewConnection is called,
+ from the context of the NEW thread and then it
+ returns to waiting for connections.
+ -
+ Close the returned handle to end the thread and close the port.
+ -
+ Errors : ERROR_INVALID_PARAMETER, any returned by socket(), bind(), listen()
+ getsockname()
+ }
+ MS_NETLIB_BINDPORT = 'Netlib/BindPort';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to an initalised TNETLIBOPENCONNECTION structure
+ Affects: Opens a connection -- see notes
+ Returns: Returns a Handle to a new connection on success, NULL(0) on failure
+ Notes : internally this service is the equivalent of socket(), gethostbyname(),
+ connect()
+ -
+ If NLOCF_HTTP is set and HANDLE is configured for HTTP(S) proxy
+ then this function will connect() to that proxy server ONLY,
+ without performing any initialisation conversation.
+ -
+ If HANDLE is configured for an HTTP proxy and does not support
+ HTTP gateways and you try to open a connection without NLOCF_HTTP
+ then this service will first attempt to open an HTTPS connection,
+ if that fails, it will try a direct connection, if *that* fails
+ then it will return failure with the error
+ from connect() during the connection attempt
+ Errors : ERROR_INVALID_PARAMETER, any returned by socket(), gethostbyname(),
+ connect(), MS_NETLIB_SEND, MS_NETLIB_RECV, select()
+ -
+ ERROR_TIMEOUT (during proxy communication)
+ ERROR_BAD_FORMAT (very invalid proxy reply)
+ ERROR_ACCESS_DENIED (by proxy)
+ ERROR_CONNECTION_UNAVAIL (socks proxy can't connect to identd)
+ ERROR_INVALID_ACCESS (proxy refused identd auth)
+ ERROR_INVALID_DATA (proxy returned invalid code)
+ ERROR_INVALID_ID_AUTHORITY (proxy requires use of auth method that's not supported)
+ ERROR_GEN_FAILURE (socks5/https general failure)
+ ERROR_CALL_NOT_IMPLEMENTED (socks5 command not supported)
+ ERROR_INVALID_ADDRESS (socks5 address type not supported)
+ -
+ HTTP: anything from TNETLIBUSER.pfnHttpGatewayInit, TNETLIBUSER.pfnHttpGatewayBegin,
+ MS_NETLIB_SENDHTTPREQUEST or MS_NETLIB_RECVHTTPHEADERS
+ }
+ MS_NETLIB_OPENCONNECTION = 'Netlib/OpenConnection';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to an initialised NETLIBHTTPPROXYINFO structure
+ Affects: Sets the required information for an HTTP proxy connection -- see notes
+ Returns: [non zero] on success, NULL(0) on failure
+ Notes : This service is designed to be called from
+ within TNETLIBUSER.pfnHttpGatewayInit (see notes in C header under
+ MS_NETLIB_REGISTERUSER)
+ Errors : ERROR_INVALID_PARAMETER
+ }
+ MS_NETLIB_SETHTTPPROXYINFO = 'Netlib/SetHttpProxyInfo';
+
+ {
+ wParam : HANDLE
+ lParam : 0
+ Affects: Get's the SOCKET associated with a handle -- see notes
+ Returns: the SOCKET on success, INVALID_SOCKET on failure
+ Notes : The Netlib handle passed to this service should only be passed
+ if they were returned with MS_NETLIB_OPENCONNECTION or MS_NETLIB_BINDPORT
+ -
+ Be careful how you use this socket because you might be connected via an
+ HTTP proxy, in which case calling send/recv() will break things
+ -
+ Errors : ERROR_INVALID_PARAMETER
+ }
+ MS_NETLIB_GETSOCKET = 'Netlib/GetSocket';
+
+ {
+ wParam : 0
+ lParam : Pointer to a null terminated string
+ Affects: URL-encodes a string for x-www-form-urlencoded (and other uses) -- see notes
+ Returns: A pointer to a null terminated string, NULL(0) on failure
+ Notes : The returned string must be freed after it's no longer needed,
+ to do this Miranda's process heap must be used (under the WINAPI), e.g.
+ HeapFree(GetProcessHeap(), 0, the_returned_string)
+ Errors : ERROR_INVALID_PARAMETER, ERROR_OUTOFMEMORY
+ }
+ MS_NETLIB_URLENCODE = 'Netlib/UrlEncode';
+
+ {
+ wParam : 0
+ lParam : Pointer to a TNETLIBBASE64 initialised structure
+ Affects: Decodes a Base64 null terminated string, see notes
+ Returns: [non zero] on success, NULL(0) on failure
+ Notes : TNETLIBBASE64.pszEncoded and cchEncoded must contain a pointer to
+ a buffer to use as input, and it's length, the length
+ should not include space taken for null termination --
+ -
+ Output is placed in ..pbDecoded and ..cbDecoded for buffer and
+ length of buffer -- the maxiumum output for a given input can
+ be worked out with Netlib_GetBase64DecodedBufferSize() function
+ see below.
+ -
+ For more information on Base64 see rfc-1421.
+ Errors : ERROR_INVALID_PARAMETER, ERROR_INVALID_DATA, ERROR_BUFFER_OVERFLOW
+ }
+ MS_NETLIB_BASE64DECODE = 'Netlib/Base64Decode';
+
+ {
+ wParam : 0
+ lParam : Pointer to an initialised TNETLIBBASE64 structure
+ Affect : Base64 encode a string, see notes
+ Returns: [non zero] on success, NULL(0) on failure
+ Notes : TNETLIBBASE64.pbDecode and TNETLIBBASE64.cbDecoded contain
+ the input buffer and it's length --
+ TNETLIBBASE64.pszEncoded and TNETLIBBASE64.cchEncoded contain the
+ buffer in which to put the output and it's length.
+ -
+ The maximum output size for a given input can be worked
+ out with the function Netlib_GetBase64EncodedBufferSize() below
+ .pszEncoded is null terminated, on return TNETLIBBASE64.cchEncoded
+ is set to the actual length excluding 0.
+ Errors : ERROR_INVALID_PARAMETER, ERROR_BUFFER_OVERFLOW
+ }
+ MS_NETLIB_BASE64ENCODE = 'Netlib/Base64Encode';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to a initialised TNETLIBHTTPREQUEST structure
+ Affect : Send an HTTP request over a connection, see notes
+ Returns: The number of bytes on success, SOCKET_ERROR on failure
+ Notes : HANDLE must of been returned by MS_NETLIB_OPENCONNECTION,,
+ If you use NLHRF_SMARTAUTHHEADER and NTLM auth is in use then
+ full NTLM auth transcation occurs, comprising sending the
+ domain, getting the challenge, sending the response.
+ NETLIBHTTPREQUEST.resultCode and NETLIBHTTPREQUEST.szResultDescr are
+ ignored by this service.
+ Errors : ERROR_INVALID_PARAMETER, MS_NETLIB_SEND (return codes)
+ }
+ MS_NETLIB_SENDHTTPREQUEST = 'Netlib/SendHttpRequest';
+
+ {
+ wParam : HANDLE
+ lParam : 0
+ Affect : Receive HTTP headers, see notes
+ Returns: A pointer to a TNETLIBHTTPREQUEST structure on success, NULL(0) on failure
+ Notes : The returned pointer must be freed after it's done with
+ use MS_NETLIB_FREEHTTPREQUESTSTRUCT.
+ -
+ HANDLE must be returned by MS_NETLIB_OPENCONNECTION
+ -
+ Return^.pData=NIL and Return^.dataLength=0 always
+ -
+ The returned data should be retrieved using MS_NETLIB_RECV once
+ the headers have been parsed.
+ If headers haven't finished within 60 seconds the function returns
+ NULL(0) and ERROR_TIMEOUT
+ Errors : ERROR_INVALID_PARAMETER, any MS_NETLIB_RECV or select()
+ ERROR_HANDLE_EOF (connection closed bfore headers complete)
+ ERROR_TIMEOUT (headers still not complete after 60 seconds)
+ ERROR_BAD_FORMAT (invalid character or line ending in headers, or first line is blank)
+ ERROR_BUFFER_OVERFLOW (each header line must be less than 4096 chars long)
+ ERROR_INVALID_DATA (first header line is malformed ("http/[01].[0-9] [0-9]+ .*", or no colon in subsequent line)
+
+ }
+ MS_NETLIB_RECVHTTPHEADERS = 'Netlib/RecvHttpHeaders';
+
+ {
+ wParam : 0
+ lParam : Pointer returned by MS_NETLIB_RECVHTTPHEADERS to free
+ Affect : Free the memory used by a TNETLIBHTTPREQUEST structure, see notes
+ Returns: [non zero] on success, NULL(0) on failure
+ Notes : This service should only be used with memory pointers returned
+ by either MS_NETLIB_RECVHTTPHEADERS or MS_NETLIB_HTTPTRANSACTION!.
+ Errors : ERROR_INVALID_PARAMETER
+
+ }
+ MS_NETLIB_FREEHTTPREQUESTSTRUCT = 'Netlib/FreeHttpRequestStruct';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to a TNETLIBHTTPREQUEST structure
+ Affect : Carry out an entire HTTP transaction, see notes
+ Returns: another pointer to a TNETLIBHTTPREQUEST structure or NULL(0)
+ on failure
+ Notes : The returned pointer must be freed at some point
+ with MS_NETLIB_FREEHTTPREQUESTSTRUCT,
+ -
+ TNETLIBHTTPREQUEST.szUrl should have a full HTTP URL, if it
+ does not start with http://, that will be assumed, but do not
+ take this assumption to stay assumed (heh..) in the future
+ -
+ this service equivalent of open(), sendhttp(), getheaders()
+ netlib_recv(), netlib_closehandle()
+ -
+ TNETLIBHTTPREQUEST.headers will be added to with the following
+ headers if they're not already present :
+ "Host" (even if it is requested in .flags)
+ "User-Agent" (in form : 'Miranda/d.d.d.d <(status of release)>')
+ "Content-Length" (for POSTs only, set to TNETLIBHTTPREQUEST.dataLength)
+
+ If you don't want to send any of these headers --
+ set TNETLIBHTTPREQUEST.headers to NULL(0)
+ -
+ In the returned pointer, pData[dataLen] is always 0 for 'safety'
+ also : headers, headersCount, pData, dataLength, resultCode and
+ szResultDescr are all valid
+ -
+ Also take care not to assume that a returned pointer means that
+ at the HTTP level it all worked out -- refer to the resultCode for
+ 2xx before doing anything else
+ -
+ Errors : ERROR_INVALID_PARAMETER, ERROR_OUTOFMEMORY
+ Errors returned by the aforementioned internally used functions
+ }
+ MS_NETLIB_HTTPTRANSACTION = 'Netlib/HttpTransaction';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to an initialised TNETLIBBUFFER structure
+ Affect : Send data over an open connection see notes
+ Returns: The number of bytes sent on success, SOCKET_ERROR on failure
+ Notes : see Netlib_Send() helper function
+ Errors : ERROR_INVALID_PARAMETER,
+ anything from socket(), connect()
+ send(), TNETLIBUSER.pfnHttpGatewayWrapSend(),
+ (HTTP proxy): ERROR_GEN_FAILURE (http result code wasn't 2xx)
+ MS_NETLIB_SENDHTTPREQUEST, MS_NETLIB_RECVHTTPHEADERS
+ }
+ MS_NETLIB_SEND = 'Netlib/Send';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to an initialised TNETLIBBUFFER structure
+ Affect : Receive data over a connection, see notes
+ Returns: The number of bytes read on success, SOCKET_ERROR on failure
+ Notes :
+ This service uses some of the same flags as MS_NETLIB_SEND :
+ MSG_PEEK,
+ MSG_NODUMP,
+ MSG_DUMPPROXY,
+ MSG_NOHTTPGATEWAYWRAP,
+ MSG_DUMPASTEXT,
+ MSG_RAW
+ -
+ On using MSG_NOHTTPGATEWAYWRAP: Because packets through an HTTP proxy are
+ batched and cached and stuff, using this flag is not a guarantee that it
+ will be obeyed, and if it is it may even be propogated to future calls
+ even if you don't specify it then. Because of this, the flag should be
+ considered an all-or-nothing thing: either use it for the entire duration
+ of a connection, or not at all.
+ Errors : ERROR_INVALID_PARAMETER, anything from recv()
+ (HTTP proxy):
+ ERROR_GEN_FAILURE (http result code wasn't 2xx)
+ ERROR_INVALID_DATA (no Content-Length header in reply)
+ ERROR_NOT_ENOUGH_MEMORY (Content-Length very large)
+ ERROR_HANDLE_EOF (connection closed before Content-Length bytes recved)
+ anything from select(),
+ MS_NETLIB_RECVHTTPHEADERS, nlu.pfnHttpGatewayUnwrapRecv, socket(),
+ connect(), MS_NETLIB_SENDHTTPREQUEST
+
+ }
+ MS_NETLIB_RECV = 'Netlib/Recv';
+
+ {
+ wParam : 0
+ lParam : Pointer to an initialised TNETLIBSELECT structure
+ Affect : Determine the status of one or more connections, see notes
+ Returns: The numbe of ready connections, SOCKET_ERROR on failure
+ Notes : All handles passed to this service must have been returned
+ either by MS_NETLIB_OPENCONNECTION or MS_NETLIB_BINDPORT,
+ the last handle in each list must be followed by either NULL
+ or INVALID_HANDLE_VALUE.
+ Errors : ERROR_INVALID_HANDLE, ERROR_INVALID_DATA, anything from select()
+ }
+ MS_NETLIB_SELECT = 'Netlib/Select';
+
+ {
+ wParam : HANDLE
+ lParam : maxPacketSize
+ Affect : Create a packet receiver, see notes
+ Returns: A handle on success, NULL(0) on failure
+ Notes : The packet receiver implements the common situation where
+ you have a variable length of packets coming thru over a connection
+ and you want them split up in order to handle them.
+ -
+ The major limiation is, that the buffer is created in memory,
+ so you can't have arbitrarily large packets
+ Errors : ERROR_INVALID_PARAMETER, ERROR_OUTOFMEMORY
+ }
+ MS_NETLIB_CREATEPACKETRECVER = 'Netlib/CreatePacketRecver';
+
+ {
+ wParam : Handle returned by MS_NETLIB_CREATEPACKETRECVER
+ lParam : Pointer to an initialised TNETLIBPACKETRECVER
+ Returns: The total number of bytes available in the buffer, NULL(0)
+ if the connection was closed or SOCKET_ERROR.
+ -
+ If TNETLIBPACKETRECVER.bytesUsed is set to zero and the
+ buffer is already full up to the maxPacketSize, it is assumed
+ that a too large packet has been received, All data in
+ the buffer is discarded and receiving has started anew.
+ -
+ This will probably cause alignment problem so if you think
+ that tis iss likely to happen, then you should deal with it
+ yourself.
+ -
+ Closing the packet receiver will not close the associated
+ connection but will discard any bytes still in the buffer,
+ so if you intend to carry on reading from that connection,
+ make sure you have processed the buffer first.
+ -
+ This service is equivalent of memmove() to remove
+ the first bytesUsed from the buffer, select(), if dwTimeOut
+ is not INFINITE, then MS_NETLIB_RECV
+ Errors : ERROR_INVALID_PARAMETER, ERROR_TIMEOUT, anything from select(),
+ MS_NETLIB_RECV
+ }
+ MS_NETLIB_GETMOREPACKETS = 'Netlib/GetMorePackets';
+
+ {
+ wParam : HANDLE
+ lParam : Pointer to null terminated string to uh, log.
+ Affect : Add a message to the log (if it's running) see notes
+ Returns: non zeror on success, NULL(0) on failure
+ Notes : Don't include \r\n or #13#10 it's not needed,
+ -
+ Doesn't support formatting like the given C code for
+ Netlib_Logf, just use FmtStr() and then call this service
+ if you want that.
+ Errors : ERROR_INVALID_PARAMETER
+ }
+ MS_NETLIB_LOG = 'Netlib/Log';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_options.inc b/plugins/ShlExt/inc/m_options.inc
new file mode 100644
index 0000000000..6a011fecdc
--- /dev/null
+++ b/plugins/ShlExt/inc/m_options.inc
@@ -0,0 +1,109 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_OPTIONS}
+{$DEFINE M_OPTIONS}
+
+const
+
+ {
+ wParam : addinfo
+ lParam : 0
+ Affects: The user opened the options dialog, see notes
+ Notes : Modules should do whatever initalisation they need and call
+ MS_OPT_ADDPAGE with the wParam -- MS_OPT_ADDPAGE
+ can be called one or more times
+ if more than one page wants to be displayed.
+ }
+ ME_OPT_INITIALISE = 'Opt/Initialise';
+
+ {
+ wParam : wParam from ME_OPT_INITIALISE
+ lParam : Pointer to an initialised TOPTIONSDIALOGPAGE
+ Affects: Adds a page to the options dialog, see notes
+ Notes : Strings in the structure can be released as soon as the
+ service returns -- but icons must be kept around, this iss
+ not a problem if you're loading theem from a resource.
+ -
+ This service should only be called within the ME_OPT_INITIALISE
+ event hook.
+ -
+ Pages in the options dialog operate just like pages in property
+ sheets, See the WinAPI documentation for details on how they operate.
+ Version: Prior to v0.1.2.1 the options dialog would resize
+ to fit the largest page, but since then it's a fixed size
+ The largest page that fits neatly is 314x240 DLU's
+ -
+ Some of OPTIONSDIALOGPAGE's fields are version dependant.
+ }
+ MS_OPT_ADDPAGE = 'Opt/AddPage';
+
+ { defacto size }
+
+ OPTIONSDIALOGPAGE_V0100_SIZE = $18;
+ OPTIONSDIALOGPAGE_V0120_SIZE = $28;
+
+ { page is only shown when in 'simple' mode }
+ ODPF_SIMPLEONLY = 1;
+ { page is only shown when in 'expert' mode }
+ ODPF_EXPERTONLY = 2;
+ { give group box titles a bold font }
+ ODPF_BOLDGROUPS = 4;
+
+type
+
+ POPTIONSDIALOGPAGE = ^TOPTIONSDIALOGPAGE;
+ TOPTIONSDIALOGPAGE = record
+ cbSize: int;
+ position: int; // position number, lower numbers are top most
+ pszTitle: PChar;
+ pfnDlgProc: Pointer; // DLGPROC prototype
+ pszTemplate: PChar;
+ hInstance: THandle;
+ hIcon: THandle; // v0.1.0.1+
+ pszGroup: PChar; // v0.1.0.1+
+ groupPosition: int; // v0.1.0.1+
+ hGroupIcon: THandle; // v0.1.0.1+
+ flags: DWORD; // v0.1.2.1+
+ { if in simple mode the dialog will be cut off AFTER this control ID, 0
+ for disable }
+ nIDBottomSimpleControl: int; // v0.1.2.1+
+ { if in simple mode the dialog will cut off AFTER this control ID, 0 to disable }
+ nIDRightSimpleControl: int; // v0.1.2.1+
+ { these controls will be hidden in simple mode, pointer to an array of ID's
+ must remain valid for the duration of the dialog }
+ expertOnlyControls: ^int;
+ nExpertOnlyControls: int; // v0.1.2.1+
+ end;
+
+const
+
+ { sent to pages via WM_NOTIFY when the expert checkbox is clicked, lParam = new state }
+ PSN_EXPERTCHANGED = 2;
+ { returns true/false }
+ PSM_ISEXPERT = ($0400 + 101);
+ { returns HFONT used for group box titles }
+ PSM_GETBOLDFONT = ($0400 + 102);
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_plugins.inc b/plugins/ShlExt/inc/m_plugins.inc
new file mode 100644
index 0000000000..72d5ff69a3
--- /dev/null
+++ b/plugins/ShlExt/inc/m_plugins.inc
@@ -0,0 +1,70 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_PLUGINS}
+{$DEFINE M_PLUGINS}
+
+const
+
+ DEFMOD_PROTOCOLICQ = 1; // removed from v0.3.0.0 alpha
+ DEFMOD_PROTOCOLMSN = 2; // removed from v0.1.2.0+
+ DEFMOD_UIFINDADD = 3;
+ DEFMOD_UIUSERINFO = 4;
+ DEFMOD_SRMESSAGE = 5;
+ DEFMOD_SRURL = 6;
+ DEFMOD_SREMAIL = 7;
+ DEFMOD_SRAUTH = 8;
+ DEFMOD_SRFILE = 9;
+ DEFMOD_UIHELP = 10;
+ DEFMOD_UIHISTORY = 11;
+ DEFMOD_RNDCHECKUPD = 12;
+ DEFMOD_RNDICQIMPORT = 13; // not built in to v0.1.0.1+
+ DEFMOD_RNDAUTOAWAY = 14;
+ DEFMOD_RNDUSERONLINE = 15;
+ DEFMOD_RNDCRYPT = 16; // v0.1.0.1-v0.1.2.0
+ DEFMOD_SRAWAY = 17; // v0.1.0.1+
+ DEFMOD_RNDIGNORE = 18; // v0.1.0.1+
+ DEFMOD_UIVISIBILITY = 19; // v0.1.1.0+, options page only
+ DEFMOD_UICLUI = 20; // v0.1.1.0+
+ DEFMOD_UIPLUGINOPTS = 21; // v0.1.2.1+
+ DEFMOD_PROTOCOLNETLIB = 22; // v0.1.2.2+
+
+ DEFMOD_HIGHEST = 22;
+
+
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Gets an array of modules that the plugins report they want to replace
+ Returns: Returns a pointer to an array of ints, with elements 1 or 0,
+ indexed by the DEFMOD_* constants, 1 is to mark that the default
+ module shouldn't be loaded, see notes
+ Notes : this is primarily for use by the core's module initialiser,
+ but could also be used by modules that are doing
+ naughty things that are very feature-dependent.
+ }
+ MS_PLUGINS_GETDISABLEDEFAULTARRAY = 'Plugins/GetDisableDefaultArray';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_popup.inc b/plugins/ShlExt/inc/m_popup.inc
new file mode 100644
index 0000000000..f8d2ea9df9
--- /dev/null
+++ b/plugins/ShlExt/inc/m_popup.inc
@@ -0,0 +1,222 @@
+(*
+===============================================================================
+ PopUp plugin
+Plugin Name: PopUp
+Plugin author: hrk, Luca Santarelli, hrk@users.sourceforge.net
+This file has been created by egodust, Sam, egodust@users.sourceforge.net
+===============================================================================
+
+The purpose of this plugin is to give developers a common "platform/interface" to show PopUps. It is born from the source code of NewStatusNotify, another plugin I've made.
+
+Remember that users *must* have this plugin enabled, or they won't get any popup. Write this in the requirements, do whatever you wish ;-)... but tell them!
+===============================================================================
+
+-- To use this file you need Windows.pas, m_globaldefs.pas (get it from the CVS under the 'inc' module)
+-- To include this in the source, use {$include m_popup.h}
+
+*)
+
+{$ifndef M_POPUP_H}
+{$define M_POPUP_H}
+
+{$ifdef FPC}
+ {$PACKRECORDS C}
+ {$MODE Delphi}
+{$endif}
+
+const
+
+ MAX_CONTACTNAME = 2048;
+ MAX_SECONDLINE = 2048;
+
+ SM_WARNING = $01; //Triangle icon.
+ SM_NOTIFY = $02; //Exclamation mark icon.
+
+type
+
+ // for info on what this stuff is, see m_popup.h
+
+ PPOPUPDATA = ^TPOPUPDATA;
+ TPOPUPDATA = record
+ lchContact: HCONTACT;
+ lchIcon: THandle;
+ lpszContactName: array[0..MAX_CONTACTNAME-1] of Char;
+ lpszText: array[0..MAX_SECONDLINE-1] of Char;
+ colorBack: COLORREF;
+ colorForeText: COLORREF;
+ PluginWindowProc: Pointer; // must be a window procedure using stdcall
+ PluginData: Pointer;
+ end;
+
+type
+
+ // for info on what this stuff is, see m_popup.h
+
+ PPOPUPDATAEX = ^TPOPUPDATAEX;
+ TPOPUPDATAEX = record
+ lchContact: HCONTACT;
+ lchIcon: THandle;
+ lpszContactName: array[0..MAX_CONTACTNAME-1] of Char;
+ lpszText: array[0..MAX_SECONDLINE-1] of Char;
+ colorBack: COLORREF;
+ colorForeText: COLORREF;
+ PluginWindowProc: Pointer; // must be a window procedure using stdcall
+ PluginData: Pointer;
+ iSeconds: int; //Custom delay time in seconds. -1 means "forever", 0 means "default time".
+ cZero: array[0..15] of Char; //16 unused bytes which may come useful in the future.
+ end;
+
+const
+
+(*
+ Creates, adds and shows a popup, given a (valid) POPUPDATA structure pointer.
+ wParam = (WPARAM)(*POPUPDATA)PopUpDataAddress
+ lParam = 0
+ Returns: > 0 on success, 0 if creation went bad, -1 if the PopUpData contained unacceptable values.
+ NOTE: it returns -1 if the PopUpData was not valid, if there were already too many popups, if the module was disabled.
+ Otherwise, it can return anything else...
+*)
+
+ MS_POPUP_ADDPOPUP = 'PopUp/AddPopUp';
+
+(*
+ The same, but with a POPUPDATAEX structure pointer.
+ wParam = (WPARAM)(*POPUPDATAEX)PopUpDataExAddress
+ lParam = 0
+*)
+
+ MS_POPUP_ADDPOPUPEX = 'PopUp/AddPopUpEx';
+
+(*
+ Returns the handle to the contact associated to the specified PopUpWindow.
+ You will probably need to know this handle inside your WNDPROC. Exampole: you want to open the MessageWindow. :-)
+ Call MS_POPUP_GETCONTACT on the hWnd you were given in the WNDPROC.
+ wParam = (WPARAM)(HWND)hPopUpWindow
+ lParam = 0;
+ Returns: the HANDLE of the contact. Can return NULL, meaning it's the main contact. -1 means failure.
+*)
+
+ MS_POPUP_GETCONTACT = 'PopUp/GetContact';
+
+(*
+ wParam = hPopUpWindow
+ lParam = PluginDataAddress;
+ Returns: the address of the PLUGINDATA structure. Can return NULL, meaning nothing was given. -1 means failure.
+ IMPORTANT NOTE: it doesn't seem to work if you do:
+ CallService(..., (LPARAM)aPointerToAStruct);
+ and then use that struct.
+ Do this, instead:
+ aPointerToStruct = CallService(..., (LPARAM)aPointerToAStruct);
+ and it will work. Just look at the example I've written above (PopUpDlgProc).
+*)
+ MS_POPUP_GETPLUGINDATA = 'PopUp/GetPluginData';
+
+(*
+ wParam = 0
+ lParam = 0
+ Returns: 0 if the user has chosen not to have the second line, 1 if he choose to have the second line.
+*)
+ MS_POPUP_ISSECONDLINESHOWN = 'PopUp/IsSecondLineShown';
+
+(*
+ UM_FREEPLUGINDATA
+ wParam = lParam = 0. Process this message if you have allocated your own memory. (i.e.: POPUPDATA.PluginData != NULL)
+*)
+ UM_FREEPLUGINDATA = ((*WM_USER*)$400 + $200);
+
+(*
+ UM_DESTROYPOPUP
+ wParam = lParam = 0. Send this message when you want to destroy the popup, or use the function below.
+*)
+ UM_DESTROYPOPUP = ((*WM_USER*)$400 + $201);
+
+(*
+ UM_INITPOPUP
+ wParam = (WPARAM)(HWND)hPopUpWindow (but this is useless, since I'll directly send it to your hPopUpWindow
+ lParam = 0.
+ This message is sent to the PopUp when its creation has been finished, so POPUPDATA (and thus your PluginData) is reachable.
+ Catch it if you needed to catch WM_CREATE or WM_INITDIALOG, which you'll never ever get in your entire popup-life.
+ Return value: if you process this message, return 0. If you don't process it, return 0. Do whatever you like ;-)
+*)
+ UM_INITPOPUP = ($400(*WM_USER*) + $202);
+
+(*
+ wParam = hPopUpWindow
+ lParam = lpzNewText
+ returns: > 0 for success, -1 for failure, 0 if the failure is due to second line not being shown. (but you could call PUIsSecondLineShown() before changing the text...)
+ Changes the text displayed in the second line of the popup.
+*)
+ MS_POPUP_CHANGETEXT = 'PopUp/Changetext';
+
+(*
+ This is mainly for developers.
+ Shows a warning message in a PopUp. It's useful if you need a "MessageBox" like function, but you don't want a modal window (which will interfere with a DialogProcedure. MessageBox steals focus and control, this one not.
+ wParam = lpzMessage
+ lParam = 0; Returns: 0 if the popup was shown, -1 in case of failure.
+*)
+ MS_POPUP_SHOWMESSAGE = 'PopUp/ShowMessage';
+
+
+ (* helper functions, will be inlined on FPC if you have the swithces enabled *)
+
+ function PUAddPopup(ppdp: PPOPUPDATA): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := CallService(MS_POPUP_ADDPOPUP, WPARAM(ppdp), 0);
+ end;
+
+ function PUGetContact(hPopUpWindow: THandle): THandle;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := CallService(MS_POPUP_GETCONTACT, WPARAM(hPopUpWindow), 0);
+ end;
+
+ function PUGetPluginData(hPopUpWindow: THandle): Pointer;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ var
+ dummy: pointer;
+ begin
+ dummy := nil;
+ Int(Result) := CallService(MS_POPUP_GETPLUGINDATA, WPARAM(hPopUpWindow), LPARAM(dummy));
+ end;
+
+ function PUIsSecondLineShown: BOOL;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Int(Result) := CallService(MS_POPUP_ISSECONDLINESHOWN, 0, 0);
+ end;
+
+ function PUDeletePopUp(hWndPopUp: THandle): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := SendMessage(hWndPopUp, UM_DESTROYPOPUP, 0, 0);
+ end;
+
+ function PUChangeText(hWndPopUp: THandle; lpzNewText: PChar): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := CallService(MS_POPUP_CHANGETEXT, WPARAM(hWndPopUp), LPARAM(lpzNewText));
+ end;
+
+ function PUShowMessage(lpzText: PChar; kind: Byte): int;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := CallService(MS_POPUP_SHOWMESSAGE, WPARAM(lpzText), LPARAM(kind));
+ end;
+
+{$endif}
+
diff --git a/plugins/ShlExt/inc/m_protocols.inc b/plugins/ShlExt/inc/m_protocols.inc
new file mode 100644
index 0000000000..90bd12366b
--- /dev/null
+++ b/plugins/ShlExt/inc/m_protocols.inc
@@ -0,0 +1,180 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_PROTOCOLS}
+{$DEFINE M_PROTOCOLS}
+
+const
+
+ ACKTYPE_MESSAGE = 0;
+ ACKTYPE_URL = 1;
+ ACKTYPE_FILE = 2;
+ ACKTYPE_CHAT = 3;
+ ACKTYPE_AWAYMSG = 4;
+ ACKTYPE_AUTHREQ = 5;
+ ACKTYPE_ADDED = 6;
+ ACKTYPE_GETINFO = 7;
+ ACKTYPE_SETINFO = 8;
+ ACKTYPE_LOGIN = 9;
+ ACKTYPE_SEARCH = 10;
+ ACKTYPE_NEWUSER = 11;
+ ACKTYPE_STATUS = 12;
+ ACKTYPE_CONTACTS = 13; //send/recv of contacts
+
+ ACKRESULT_SUCCESS = 0;
+ ACKRESULT_FAILED = 1;
+ //'in progress' result codes:
+ ACKRESULT_CONNECTING = 100;
+ ACKRESULT_CONNECTED = 101;
+ ACKRESULT_INITIALISING = 102;
+ ACKRESULT_SENTREQUEST = 103; // waiting for reply...
+ ACKRESULT_DATA = 104; // blob of file data sent/recved, or search result
+ ACKRESULT_NEXTFILE = 105; // file transfer went to next file
+ ACKRESULT_FILERESUME = 106; // a file is about to be received, see PS_FILERESUME
+ ACKRESULT_DENIED = 107; // a file send has been denied (0.3a + only)
+
+ // for PROTOCOLDESCRIPTOR.type
+
+ PROTOTYPE_PROTOCOL = 1000;
+ PROTOTYPE_ENCRYPTION = 2000;
+ PROTOTYPE_FILTER = 3000;
+ PROTOTYPE_TRANSLATION = 4000;
+ PROTOTYPE_OTHER = 10000;//avoid using this if at all possible
+
+type
+
+ PCCSDATA = ^TCCSDATA;
+ TCCSDATA = record
+ hContact: THandle;
+ szProtoService: PChar; // a PS_* constant
+ wParam: WPARAM;
+ lParam: LPARAM;
+ end;
+
+ PACKDATA = ^TACKDATA;
+ TACKDATA = record
+ cbSize: int;
+ szModule: PChar; // the name of the protocol module which initiated this ack
+ hContact: THandle;
+ type_: int; // an ACKTYPE_* constant
+ result_: int; // an ACKRESULT_* constant
+ hProcess: THandle; // caller defined seq, I mean process code
+ lParam: LPARAM; // caller defined data
+ end;
+
+ // when type=ACKTYPE_FILE and (result=ACKRESULT_DATA or result=ACKRESULT_FILERESUME)
+
+ PPROTOFILETRANSFERSTATUS = ^TPROTOFILETRANSFERSTATUS;
+ TPROTOFILETRANSFERSTATUS = record
+ cbSize: int;
+ hContact: THandle;
+ sending: int; // true if sending, false if receiving
+ files: PChar; // pointer to an array of pchar's
+ totalFiles: int;
+ currentFileNumber: int;
+ totalBytes: LongInt;
+ totalProgress: LongInt;
+ workingDir: PChar;
+ currentFile: PChar;
+ currentFileSize: LongInt;
+ currentFileProgress: LongInt;
+ currentFileTime: LongInt; // UNIX time
+ end;
+
+ // for registering a protocol, enumeration
+
+ PPROTOCOLDESCRIPTOR = ^TPROTOCOLDESCRIPTOR;
+ TPROTOCOLDESCRIPTOR = record
+ cbSize: int;
+ szName: PChar; // unique name of module
+ type_: int; // a PROTOTYPE_* constant
+ end;
+
+const
+
+ {
+ wParam : 0
+ lParam : Pointer to an initalised CSSDATA structure
+ Affect : Send a general request thru the protocol chain for a contact
+ Return : the return value documented in the PS_* def (m_protosvc.inc)
+ }
+ MS_PROTO_CALLCONTACTSERVICE = 'Proto/CallContactService';
+
+ {
+ wParam : 0
+ lParam : Pointer to an initalised TACKDATA structure
+ Affect : a general 'ack', see notes
+ Notes : Just because defs are here doesn't mean they will be sent
+ read the docs for the function you are calling to see what
+ replies you will get.
+ }
+ ME_PROTO_ACK = 'Proto/Ack';
+
+ {
+ wParam : pointer to an int to store number of protocols
+ lParam : Pointer to an an array of PPROTOCOLDESCRIPTOR pointers
+ Affect : Enumerate the currently running protocols, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : Neither wParam/lParam maybe NULL(0), the list returned by
+ this service is the protocol modules currently installed
+ and running, it is not a complete list of protocols that have
+ ever been installed.
+ -
+ A protocol module does not have to be a protocol running thru
+ the internet, it can be a vast number of things
+ }
+ MS_PROTO_ENUMPROTOCOLS = 'Proto/EnumProtocols';
+
+ {
+ wParam : 0
+ lParam : Pointer to null terminated string containing protocol name
+ Affect : Determines if a protocol is running or not.
+ Returns: A pointer to the PPROTOCOLDESCRIPTOR if the protocol is loaded
+ or NULL(0) if it isn't
+ }
+ MS_PROTO_ISPROTOCOLLOADED = 'Proto/IsProtocolLoaded';
+
+ {
+ wParam : HCONTACT
+ lParam : Pointer to a null terminated string containing a name
+ Affect : Determine whether the given contact has the given protocol
+ in it's chain.
+ Returns : 0 if the protocol isn't in the chain, [non zero] if it is
+ }
+ MS_PROTO_ISPROTOONCONTACT = 'Proto/IsProtoOnContact';
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affect : Gets the network-level protocol associated with a contact
+ Returns: a PChar pointing to the ASCIIZ name of the protocol or NULL(0)
+ if the contact has no protocol, There's no need to dispsose
+ the returned string.
+ -
+ This is the name of the module that actually accesses the network
+ for that contact.
+ }
+ MS_PROTO_GETCONTACTBASEPROTO = 'Proto/GetContactBaseProto';
+
+{$ENDIF} \ No newline at end of file
diff --git a/plugins/ShlExt/inc/m_protomod.inc b/plugins/ShlExt/inc/m_protomod.inc
new file mode 100644
index 0000000000..8bf245316c
--- /dev/null
+++ b/plugins/ShlExt/inc/m_protomod.inc
@@ -0,0 +1,105 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_PROTOMOD}
+{$DEFINE M_PROTOMOD}
+
+ {$ifndef M_PROTOCOLS}
+ {$include m_protocols.inc}
+ {$endif}
+
+const
+
+ {
+ wParam : 0
+ lParam : Pointer to a initalised TPROTOCOLDESCRIPTOR structure
+ Affect : Register a protocol module, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : This service MUST be called from your module's Load() function
+ TPROTOCOLDESCRIPTOR.type can be a value other than PROTOTYPE_*
+ which are used to provide a more precise positioning information
+ for the contact protocol lists.
+ -
+ Relative values to the constants can be given, but this MUST NOT
+ be done for PROTOTYPE_PROTOCOL.
+ }
+ MS_PROTO_REGISTERMODULE = 'Proto/RegisterModule';
+
+ {
+ wParam : HCONTACT
+ lParam : protocol_name_string
+ Affect : Add the given protocol module to the chain for a contact, see notes
+ Returns: 0 success, [non zero] on failure
+ Notes : The module is added to the correct positioning according to it's
+ registered type.
+ }
+ MS_PROTO_ADDTOCONTACT = 'Proto/AddToContact';
+
+ {
+ wParam : HCONTACT
+ lParam : protocol_name_string
+ Affect : Remove the given protocol name from the chain for the given contact
+ Returns: 0 on success, [non zero] on failure
+ }
+ MS_PROTO_REMOVEFROMCONTACT = 'Proto/RemoveFromContact';
+
+ { see m_globaldefs.pas for CreateProtoServiceFunction }
+
+ {
+ wParam : wParam [arg]
+ lParam : lParam [arg]
+ Affect : Call the next service in the chain for the send operation, see notes
+ Return : Return value should be returned by CallService(MS_PROTO_CHAINSEND,wParam,lParam)
+ Notes : wParam MUST remain untouched, lParam is a pointer to a CSSDATA structure
+ and can be modified or copid if needed.
+ wParam and lParam should be the values passed to your service,
+ typically your service should return ASAP.
+ }
+ MS_PROTO_CHAINSEND = 'Proto/ChainSend';
+
+ {
+ wParam : wParam [arg]
+ lParam : lParam [arg]
+ Affect : Call the next service in the chain in this receive operation, see notes
+ Return : Return value should be returned by CallService(MS_PROTO_CHAINRECV,wParam,lParam)
+ Notes : wParam MUST remain untouched, lParam is a pointer to a CSSDATA structure
+ and can be modified or copied if needed.
+ wParam and lParam should be the values passed to your service,
+ typically your service should return ASAP.
+ -
+ MS_PROTO_CHAINRECV is thread safe since 0.1.2.0 -- calls
+ are translated to the main thread and passed from there.
+ }
+ MS_PROTO_CHAINRECV = 'Proto/ChainRecv';
+
+ {
+ wParam : 0
+ lParam : Pointer to an initalised ACKDATA
+ Affect : Broadcast a ME_PROTO_ACK event, see notes
+ Returns: The return value of the NotifyEventHooks() call
+ Notes : ME_PROTO_ACK is completely thread safe since 01.2.0
+ see notes in core/modules.h under NotifyEventHooks()
+ }
+ MS_PROTO_BROADCASTACK = 'Proto/BroadcastAck';
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_protosvc.inc b/plugins/ShlExt/inc/m_protosvc.inc
new file mode 100644
index 0000000000..9fde8268bb
--- /dev/null
+++ b/plugins/ShlExt/inc/m_protosvc.inc
@@ -0,0 +1,753 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_PROTOSVC}
+{$DEFINE M_PROTOSVC}
+
+{<</
+ none of these services should be used on there own (i.e. using CallService(), etc)
+ hence the PS_ prefix, instead use the services exposed in m_protocols.inc
+
+ these should be called with CallProtoService which prefixes the protocol module
+ name before calling.
+ -
+ Deleting contacts from protocols that store the contact list on the server:
+ If a contact is deleted while the protocol is online, it is expected that the
+ protocol will have hooked me_db_contact_deleted and take the appropriate
+ action by itself.
+ If a contact is deleted while the protocol is offline, the contact list will
+ display a message to the user about the problem, and set the byte setting
+ "CList"/"Delete" to 1. Each time such a protocol changes status from offline
+ or connecting to online the contact list will check for contacts with this
+ flag set and delete them at that time. Your hook for me_db_contact_deleted
+ will pick this up and everything will be good.
+/>>}
+
+const
+
+ PFLAGNUM_1 = $1;
+ PF1_IMSEND = $00000001; // supports IM sending
+ PF1_IMRECV = $00000002; // supports IM receiving
+ PF1_IM = (PF1_IMSEND or PF1_IMRECV);
+ PF1_URLSEND = $00000004; // supports separate URL sending
+ PF1_URLRECV = $00000008; // supports separate URL receiving
+ PF1_URL = (PF1_URLSEND or PF1_URLRECV);
+ PF1_FILESEND = $00000010; // supports file sending
+ PF1_FILERECV = $00000020; // supports file receiving
+ PF1_FILE = (PF1_FILESEND or PF1_FILERECV);
+ PF1_MODEMSGSEND = $00000040; // supports broadcasting away messages
+ PF1_MODEMSGRECV = $00000080; // supports reading others' away messages
+ PF1_MODEMSG = (PF1_MODEMSGSEND or PF1_MODEMSGRECV);
+ PF1_SERVERCLIST = $00000100; // contact lists are stored on the server, not locally. See notes below
+ PF1_AUTHREQ = $00000200; // will get authorisation requests for some or all contacts
+ PF1_ADDED = $00000400; // will get 'you were added' notifications
+ PF1_VISLIST = $00000800; // has an invisible list
+ PF1_INVISLIST = $00001000; // has a visible list for when in invisible mode
+ PF1_INDIVSTATUS = $00002000; // supports setting different status modes to each contact
+ PF1_EXTENSIBLE = $00004000; // the protocol is extensible and supports plugin-defined messages
+ PF1_PEER2PEER = $00008000; // supports direct (not server mediated) communication between clients
+ PF1_NEWUSER = $00010000; // supports creation of new user IDs
+ PF1_CHAT = $00020000; // has a realtime chat capability
+ PF1_INDIVMODEMSG = $00040000; // supports replying to a mode message request with different text depending on the contact requesting
+ PF1_BASICSEARCH = $00080000; // supports a basic user searching facility
+ PF1_EXTSEARCH = $00100000; // supports one or more protocol-specific extended search schemes
+ PF1_CANRENAMEFILE = $00200000; // supports renaming of incoming files as they are transferred
+ PF1_FILERESUME = $00400000; // can resume broken file transfers, see PS_FILERESUME below
+ PF1_ADDSEARCHRES = $00800000; // can add search results to the contact list
+ PF1_CONTACTSEND = $01000000; // can send contacts to other users
+ PF1_CONTACTRECV = $02000000; // can receive contacts from other users
+ PF1_CONTACT = (PF1_CONTACTSEND or PF1_CONTACTRECV);
+ PF1_CHANGEINFO = $04000000; // can change our user information stored on server
+ PF1_SEARCHBYEMAIL = $08000000; // supports a search by e-mail feature
+ PF1_USERIDISEMAIL = $10000000; // set if the uniquely identifying field of the network is the e-mail address
+ PF1_SEARCHBYNAME = $20000000; // supports searching by nick/first/last names
+ PF1_EXTSEARCHUI = $40000000; // has a dialog box to allow searching all the possible fields
+ PF1_NUMERICUSERID = $80000000; // the unique user IDs for this protocol are numeric
+
+ PFLAGNUM_2 = 2; // the status modes that the protocol supports
+ PF2_ONLINE = $00000001; // an unadorned online mode
+ PF2_INVISIBLE = $00000002;
+ PF2_SHORTAWAY = $00000004; // Away on ICQ, BRB on MSN
+ PF2_LONGAWAY = $00000008; // NA on ICQ, Away on MSN
+ PF2_LIGHTDND = $00000010; // Occupied on ICQ, Busy on MSN
+ PF2_HEAVYDND = $00000020; // DND on ICQ
+ PF2_FREECHAT = $00000040;
+ PF2_OUTTOLUNCH = $00000080;
+ PF2_ONTHEPHONE = $00000100;
+
+ PFLAGNUM_3 = 3; //the status modes that the protocol supports
+ //away-style messages for. Uses the PF2_ flags.
+ PFLAG_UNIQUEIDTEXT = 100; //returns a static buffer of text describing the unique field by which this protocol identifies users (already translated), or NULL
+
+ PFLAG_MAXCONTACTSPERPACKET = 200; //v0.1.2.2+: returns the maximum number of contacts which can be sent in a single PSS_CONTACTS.
+
+ PFLAGNUM_4 = 4; // v0.3+: flag asking a protocol plugin how auths are handled
+ PF4_FORCEAUTH = $00000001; // protocol has to send auth's for things to work
+ PF4_FORCEADDED = $00000002; // protocol has to tell people that they were added (otherwise things don't work)
+ PF4_NOCUSTOMAUTH = $00000004; // protocol can't send a custom message while asking others for auth
+
+ PFLAG_UNIQUEIDSETTING = 300; // v0.3+: returns the DB setting name (e.g. szProto=ICQ, szSetting=UIN) that has the ID which makes this user unique on that system (0.3a ONLY), the string is statically allocated so no need to free()
+
+ // for PS_SETSTATUS
+
+ LOGINERR_WRONGPASSWORD = 1;
+ LOGINERR_NONETWORK = 2;
+ LOGINERR_PROXYFAILURE = 3;
+ LOGINERR_BADUSERID = 4;
+ LOGINERR_NOSERVER = 5;
+ LOGINERR_TIMEOUT = 6;
+ LOGINERR_WRONGPROTOCOL = 7;
+
+ // flag for PS_ADDTOLIST
+
+ PALF_TEMPORARY = 1; // add the contact temporarily and invisibly, just to get user info or something
+
+ // flags for PS_GETINFO
+
+ SGIF_MINIMAL = 1; // get only the most basic information. This should
+ // contain at least a Nick and e-mail.
+
+ // for PSR_MESSAGE
+
+ PREF_CREATEREAD = 1; // create the database event with the 'read' flag set
+
+ // for PS_FILERESUME
+
+ FILERESUME_OVERWRITE= 1;
+ FILERESUME_RESUME = 2;
+ FILERESUME_RENAME = 3;
+ FILERESUME_SKIP = 4;
+
+type
+
+ PPROTOSEARCHRESULT = ^TPROTOSEARCHRESULT;
+ TPROTOSEARCHRESULT = record
+ cbSize: int;
+ nick: PChar;
+ firstName: PChar;
+ lastName: PChar;
+ email: PChar;
+ reserved: array [0..15] of Byte;
+ // Protocols may extend this structure with extra members at will and supply
+ // a larger cbSize to reflect the new information, but they must not change
+ // any elements above this comment
+ // The 'reserved' field is part of the basic structure, not space to
+ // overwrite with protocol-specific information.
+ // If modules do this, they should take steps to ensure that information
+ // they put there will be retained by anyone trying to save this structure.
+ end;
+
+ PPROTOSEARCHBYNAME = ^TPROTOSEARCHBYNAME;
+ TPROTOSEARCHBYNAME = record
+ pszNick: PChar;
+ pszFirstName: PChar;
+ pszLastName: PChar;
+ end;
+
+ PPROTORECVEVENT = ^TPROTORECVEVENT;
+ TPROTORECVEVENT = record
+ flags: DWORD;
+ timestamp: DWORD;
+ szMessage: PChar;
+ lParam: LPARAM;
+ end;
+
+ PPROTORECVFILE = ^TPROTORECVFILE;
+ TPROTORECVFILE = record
+ flags: DWORD;
+ timestamp: DWORD; // unix time
+ szDescription: PChar;
+ pFiles: PChar; // pointer to an array of pchar's
+ lParam: LPARAM;
+ end;
+
+ PPROTOFILERESUME = ^TPROTOFILERESUME;
+ TPROTOFILERESUME = record
+ action: int; // FILERESUME_* flag
+ szFilename: PChar; // full path, only valid if action=FILERESUME_RENAME
+ end;
+
+const
+
+ {
+ wParam : PFLAGNUM_* (see above)
+ lParam : 0
+ Affects: Returns a bitfield for settings corresponding to flag number, see notes
+ Returns: a bitfield of supported features -- or 0 if flag_num is not supported
+ Notes : this checks what sort of things are actively supported by a protocol
+ module
+ }
+ PS_GETCAPS = '/GetCaps';
+
+ {
+ wParam : cchName
+ lParam : Pointer to a buffer to fill with human-readable name
+ Affect : Get a human-readable name for the protocol, see notes
+ Result : 0 on success, [non zero] on failure
+ Notes : Should be translated before being returned, cchName
+ has the size of the buffer, example strings: "ICQ", "AIM"
+ }
+ PS_GETNAME = '/GetName';
+
+ {
+ wParam : whichIcon
+ lParam : 0
+ Affect : Loads one of the protocol-sspecific icons
+ Returns: the HICON or NULL on failure, the returned icon
+ must be DestroyIcon()ed, the UI should overlay
+ the online icon with further UI-specified icon to
+ repressent the exact status mode.
+ }
+ PLI_PROTOCOL = $1; // An icon representing the protocol (eg the multicoloured flower for ICQ)
+ PLI_ONLINE = $2; // Online state icon for that protocol (eg green flower for ICQ)
+ PLI_OFFLINE = $3; // Offline state icon for that protocol (eg red flower for ICQ)
+ PLIF_LARGE = $0; // Or with one of the above to get the large (32x32 by default) icon
+ PLIF_SMALL = $10000; // Or with one of the above to get the small (16x16 by default) icon
+
+ PS_LOADICON = '/LoadIcon';
+
+ {
+ wParam : status_mode
+ lParam : Pointer to a null terminated string containing message
+ Affect : Sets the status mode specific message for the user, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : This service is not available unless PF1_MODEMSGSEND is set,
+ and PF1_INDIVMODEMSG is *not* set.
+ If PF1_INDIVMODEMSG is set, then see PSS_AWAYMSSG for details
+ of operations of away messages.
+ -
+ Protocol modules smust support lParam=NULL, it may eithere mean
+ to use an empty message or (preferably) not to reply at all to
+ any requests.
+ }
+ PS_SETAWAYMSG = '/SetAwayMsg';
+
+ {
+ wParam : newMode from statusmodes.inc
+ lParam : 0
+ Affect : Change the protocol's status mode, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : Will send an ack with :
+ type=ACKTYPE_SUCCESS, result=ACKRESULT_SUCCESS, hProcess=previousMode, lParam=newMode
+ -
+ when the change completes. This ack is sent for all changes, not
+ just ones caused by calling this function.
+ -
+ NewMode can be ID_STATUS_CONNECTING<=newMode<ID_STATUS_CONNECTING+
+ MAX_CONNECT_RETRIES to signify that it's connecting and it's the nth retry.
+ -
+ Protocols are initially always in offline mode, if a protocol
+ doesn't support a specific status mode, it should pick the closest
+ ones that it does support, and change to that.
+
+ If a protocol has to switch from offline mode to online (or a substate
+ of online, like away) then it should report any errors in the
+ form of an additional ack :
+
+ type=ACKTYPE_LOGIN, result=ACKRESULT_FAILURE, hProcess=NULL, lParam=LOGINERR_*
+
+ SetStatus() is called when a protocol module is first loaded
+ with newMode=ID_STATUS_ONLINE.
+ -
+ Protocols can define their own LOGINERR_* starting at $1000, see
+ LOGINERR_* above
+ }
+ PS_SETSTATUS = '/SetStatus';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Get the status mode that a protocol is currently in, see notes
+ Returns: The current status mode
+ Notes : Only protocol modules need to implement this, non network level
+ protocol modules do not need to (but if you register as a protocol
+ you need to, Miranda will GPF otherwise)
+ }
+ PS_GETSTATUS = '/GetStatus';
+
+ {
+ wParam : HDBEVENT
+ lParam : 0
+ Affect : allow 'somebody' to add the user to their contact list, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : Auth request come in the form of an event added to the database
+ for the NULL(0) user, the form is:
+ -
+ protocolSpecific: DWORD;
+ nick, firstname, lastName, e-mail, requestReason: ASCIIZ;
+ -
+ HDBEVENT musts be the handle of such an event, one or more
+ fields may be empty if the protocol doesn't support them
+ }
+ PS_AUTHALLOW = '/Authorize';
+
+ {
+ wParam : HDBEVENT
+ lParam : Pointer to a null terminated string containing the reason, see notes
+ Affect : Deny an authorisation request
+ Returns: 0 on success, [non zero] on failure
+ Notes : Protocol modules must be able to cope with lParam=NULL(0)
+ }
+ PS_AUTHDENY = '/AuthDeny';
+
+ {
+ wParam : 0
+ lParam : Pointer to a null terminated string containing an ID to search for
+ Affect : Send a basic search request, see notes
+ Returns: A handle to the search request or NULL(0) on failure
+ Notes : All protocols identify users uniquely by a single field
+ this service will search by that field.
+ -
+ All search replies (even protocol-spec extended searches)
+ are replied by a series of ack's,-
+ -
+ Result acks are a series of:
+ type=ACKTYPE_SEARCH, result=ACKRESULT_DATA, lParam=Pointer to a TPROTOSEARCHRESULT structure
+ -
+ ending ack:
+ type=ACKTYPE_SEARCH, result=ACKRESULT_SUCCESS, lParam=0
+ -
+ The pointers in the structure are not guaranteed to be
+ valid after the ack is complete.
+ -
+ The structure to reply with search results can be extended
+ per protocol basis (see below)
+
+ }
+ PS_BASICSEARCH = '/BasicSearch';
+
+ {
+ wParam : 0
+ lParam : Pointer to a NULL terminated string containing the e-mail to search for
+ Affect : Search for user(s) by e-mail address, see notes
+ Returns: A HANDLE to the search, or NULL(0) on failure
+ Notes : Results are returned as for PS_BASICSEARCH, this service
+ is only available if the PF1_USERIDISEMAIL flag is set for caps --
+ -
+ This service with the above service should be mapped to the same
+ function if the aforementioned flag is set.
+ Version: v0.1.2.1+
+ }
+ PS_SEARCHBYEMAIL = '/SearchByEmail';
+
+ {
+ wParam : 0
+ lParam : Pointer to a TPROTOSEARCHBYNAME structure
+ Affect : Search for users by name, see notes
+ Returns: Handle to the search, NULL(0) on failure
+ Notes : this service is only available, if PF1_SEARCHBYNAME capability is set.
+ Results are returned in the same manner as PS_BASICSEEARCH
+ Version: v0.1.2.1+
+ }
+ PS_SEARCHBYNAME = '/SearchByName';
+
+ {
+ wParam : 0
+ lParam : Handle to window owner
+ Affect : Create the advanced search dialog box, see notes
+ Returns: A window handle, or NULL(0) on failure
+ Notes : this service is only available if PF1_EXTSEARCHUI capability is
+ set, advanced search is very protocol-spec'd so it is left to
+ the protocol itself to supply a dialog containing the options,
+ this dialog should not have a titlebar and contain only search
+ fields. the rest of the UI is supplied by Miranda.
+ -
+ The dialog should be created with CreateDialog() or it's kin
+ and still be hidden when this function returns,
+ -
+ The dialog will be destroyed when the find/add dialog is closed
+ Version: v0.1.2.1+
+ }
+ PS_CREATEADVSEARCHUI= '/CreateAdvSearchUI';
+
+ {
+ wParam : 0
+ lParam : Handle to advanced search window handle
+ Affect : Search using the advanced search dialog, see notes
+ Returns: A handle or NULL(0) on failure
+ Notes : Results are returned in the same manner as PS_BASICSEARCH,
+ this service is only available if PF1_EXTSEARCHUI capability is set
+ Version: v0.1.2.1+
+ }
+ PS_SEARCHBYADVANCED = '/SearchByAdvanced';
+
+ {
+ wParam : flags
+ lParam : Pointer to a TPROTOSEARCHRESULT structure
+ Affect : Adds a search result to the contact list, see notes
+ Returns: A handle to the new contact (HCONTACT) or NULL(0) on failure
+ Notes : The pointer MUST be a result returned by a search function
+ since there maybe extra protocol-spec data required by the protocol.
+ -
+ the protocol module should not allow duplicate contains to be added,
+ but if such a request *is* received it should return a HCONTACT
+ to the original user,
+ -
+ If flags is PALF_TEMPORARY set, the contact should be added
+ temorarily and invisiblely, just to get the user info (??)
+ -
+ }
+ PS_ADDTOLIST = '/AddToList';
+
+ {
+ wParam : MAKEWPARAM(flags, iContact)
+ lParam : HDBEVENT
+ Affects: Add a contact to the contact list given an auth/added/contacts events, see notes
+ Returns: A HCONTACT or NULL(0) on failure
+ Notes : HDBEVENT must be either EVENTTYPE_AUTHREQ or EVENTTYPE_ADDED
+ flags are the same as PS_ADDTOLIST,
+ -
+ iContacts is only used for contacts vents, it is 0-based index
+ of the contacts in the event to add, there's no way to add two or more
+ contacts at once, you should just call this as many times as needed.
+ }
+ PS_ADDTOLISTBYEVENT = '/AddToListByEvent';
+
+ {
+ wParam : InfoType
+ lParam : Pointer to InfoData
+ Affect : Changes user details as stored on the server, see notes
+ Returns: A Handle to the change request or NULL(0) on failure
+ Notes : the details stored on the server are very protocol spec'd
+ so this service just supplies an outline for protocols to use.
+ See protocol-specific documentation for what infoTypes are available
+ and what InfoData should be for each infoTypes.
+ -
+ Sends an ack type=ACKTYPE_SETINFO, result=ACKRESULT_SUCCESS/FAILURE, lParam=0
+ -
+ This description just leaves me cold.
+ Version: v0.1.2.0+
+ }
+ PS_CHANGEINFO = '/ChangeInfo';
+
+ {
+ wParam : HFILETRANSFER
+ lParam : Pointer to a initalised TPROTOFILERESUME
+ Affect : Informs the protocol of the user's chosen resume behaviour, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : If the protocol supports file resume (caps: PF1_FILERESUME) then before
+ each file receive begins it will broadcast an ack with :
+
+ type=ACKTYPE_FILE, result=ACKRESULT_RESUME, hProcess=hFileTransfer,
+ lParam = TPROTOFILETRANSFERSTATUS.
+
+ If the UI processes this ack it must return a [non zero] valuee from it's
+ hook, it all the hooks complete without returning [non zero] then the
+ protocol will assume that no resume UI was available and will continue
+ to receive the file with a default behaviour (default: overwrite)
+ -
+ If a hook does return [non zero] then that UI MUST call this service,
+ PS_FILERESUME at some point.
+ When the protocol module receives this call it will proceed wit the
+ file recieve usingg the given information.
+ -
+ Having sasid that, PS_FILERESUME MUST be called, it is also
+ acceptable to completely abort the transfer instead, i.e. the file
+ exists locally and the user doesn't want to overwrite or resume or
+ reget.
+ Version: v0.1.2.2+
+ }
+ PS_FILERESUME = '/FileResume';
+
+ // these should be called with CallContactService()
+
+ {<</
+ !IMPORTANT!
+ wParam, lParam data expected declarations should be treated with
+ one level of indirection, where it says (CCSDATA: Yes)
+ should be :
+
+ What you *actually* get in the service:
+
+ wParam = 0
+ lParam = pCCSDATA
+
+ CCSDATA contains the ..wParam, ..lParam, hContact data declared with each service,
+ so the wParam, lParam passed does not contain the data itself, but lParam
+ contains a pointer to a structure which contains the data.
+
+ />>}
+
+ {
+ CCSDATA: Yes
+ wParam : flags
+ Param : 0
+
+ Affect : Updates a contact's details from the server, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes :
+
+ flags which may have SGIF_MINIMAL set to only get
+ "basic" information, such as nickname, email address.
+
+ PCCSDATA(lParam)^.hContact has the HCONTACT handle to get user
+ information for.
+
+ Will update all the information in the database and then
+ send acks with :
+
+ type=ACKTYPE_GETINFO, result=ACKRESULT_SUCCESS, hProcess=nReplies, lParam=thisReply
+ -
+ Since some protocol do not allow the module to tell when it has
+ got all the information so it can send a final ack, one
+ ack will be sent after each chunk of data has been received,
+ -
+ nReplies contains the number of distinct acks
+ that will be sent to get all the information, 'thisReply'
+ is the zero based index of this ack.
+ When thisReply=0 the minimal information has just been received,
+ all other numbering is arbitrary.
+
+ }
+ PSS_GETINFO = '/GetInfo';
+
+ {
+ CCSDATA: Yes
+ wParam : flags
+ lParam : Pointer to a null terminated string
+ Affect : Send an instant message
+ Returns: an hProcess corresponding to an ACK which will be sent after
+ the hProcess.
+ Notes: type=ACKTYPE_MESSAGE, result=ACKRESULT_SUCCESS/FAILURE, lParam = 0
+ -
+ here's the deal, you must return a 'seq' from this service
+ which you have to ack when the message actually get's sent,
+ or send a fake ack sometime soon if you can't find out if the message
+ was successfully received with the protocol that you're using.
+ -
+ this event is NOT added to the database automatically.
+ }
+ PSS_MESSAGE = '/SendMsg';
+
+ {
+ CCSDATA: Yes
+ wParam : flags
+ lParam : null terminated string to the URL, see notes
+ Affect : Send a URL message, see notes
+ Returns: A hProcess which will be ack'd later
+ Notes : lParam may contain TWO strings, the first for URL, the second for
+ description, in the format :
+ <url>#0<desc>#0 or <url>#0#0
+ Will send an ack for hProcess when the URL actually gets sent
+ type=ACKTYPE_URL, result=ACKRESULT_SUCCESS/FAILURE, lParam=0
+ -
+ protocol modules are free to define flags starting at $10000
+ -
+ The event will *not* be added to the database automatically
+ }
+ PSS_URL = '/SendUrl';
+
+ {
+ CCSDATA: Yes
+ wParam : MAKEWPARAM(flags)
+ lParam : Pointer to hContactsList
+ Affect : Send a set of contacts, see notes
+ Returns: A hProcess which will be ack, NULL(0) on failure
+ Notes : hContactsList is an array of nContacts handles to contacts,
+ if this array includes one or more contains that can not be transferred
+ using this protocol the function will fail.
+ -
+ Will send an ack when the contacts actually get sent:
+
+ type=ACKTYPE_CONTACTS, result=ACKRESULT_SUCCESS/FAILURE, lParam=0
+ -
+ No flags have ben defined yet,
+ -
+ The event will *not* be added to the database automatically
+ }
+ PSS_CONTACTS = '/SendContacts';
+
+ {
+ CCSDATA: Yes
+ wParam : 0
+ lParam : 0
+ Affect : Send a request to retrieve HCONTACT's mode message, see notes
+ Returns: a hProcess which will be ack'd later, NULL(0) on failure
+ Notes : the reply will come in a form of an ack :
+
+ type=ACKTYPE_AWAYMSG, result=ACKRESULT_SUCCESS/FAILURE,
+ lParam=pointer to a null terminated string the containing message
+ }
+ PSS_GETAWAYMSG = '/GetAwayMsg';
+
+ {
+ CCSDATA: Yes
+ wParam : hProcess
+ lParam : pointer to a buffer to fill with away message to reply with
+ Affect : Sends an away message reply to a user, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : This service must only be called is caps has PF1_MODEMSGSEND set
+ as well as PF1_INDIVMODEMSG otherwise PS_SETAWAYMESSAGE should
+ be used.
+ -
+ Reply will be sent in the form of an ack :
+
+ type=ACKTYPE_AWAYMSG, result=ACKRESULT_SENTREQUEST, lParam=0
+ }
+ PSS_AWAYMSG = '/SendAwayMsg';
+
+ {
+ CCSDATA: Yes
+ wParam : status_mode
+ lParam : Pointer to a TPROTORECVEVENT structure
+ Affect : An away message reply has been received
+ }
+ PSR_AWAYMSG = '/RecvAwayMsg';
+
+ {
+ CCSDATA: Yes
+ wParam : status_mode
+ lParam : 0
+ Affect : Set the status mode the user will appear in to a user, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : If status_mode = 0 then revert to normal state for the user,
+ ID_STATUS_ONLINE is possible if PF1_VISLIST
+ ID_STATUS_ONLINE is possible if PF1_INDIVSTATUS
+ }
+ PSS_SETAPPARENTMODE = '/SetApparentMode';
+
+ // only valid if caps support IM xfers
+
+ {
+ CCSDATA: Yes
+ wParam : HTRANSFER
+ lParam : null terminated string containing the path
+ Affect : Allow a file transfer to begin, see notes
+ Returns: A handle to the transfer to be used from now on.
+ Notes : If the path does not point to a directory then:
+ if a single file is being transfered and the protocol supports
+ file renaming (PF1_CANRENAMEFILE) then the file is given
+ this name, othewise the file is removed and file(s) are placed
+ into the resulting directory.
+ -
+ File transfers are marked by a EVENTTYPE_FILE added to the database.
+ The format is :
+ hTransfer: DWORD
+ filename(s), description: ASCIIZ
+ }
+ PSS_FILEALLOW = '/FileAllow';
+
+ {
+ CCSDATA: Yes
+ wParam : HTRANSFER
+ lparam : Pointer to a buffer to be filled with reason
+ Affect : Refuses a file transfer request
+ Returns: 0 on success, [non zero] on failure
+ }
+ PSS_FILEDENY = '/FileDeny';
+
+ {
+ CCSDATA: Yes
+ wParam : HTRANSFER
+ lParam : 0
+ Affect : Cancel an in-progress file transfer
+ Returns: 0 on success, [non zero] on failure
+ }
+ PSS_FILECANCEL = '/FileCancel';
+
+ {
+ CCSDATA: Yes
+ wParam : null terminated string containing description
+ lParam : pointer to an array of pchar's containing file paths/directories
+ Affect : Start a file(s) send, see notes
+ Returns: A HTRANSFER handle on success, NULL(0) on failur
+ Notes : All notifications are done thru acks :
+ -
+ type=ACKTYPE_FILE, if result=ACKRESULT_FAILED then
+ lParam=null terminated string containing reason
+ }
+ PSS_FILE = '/SendFile';
+
+ // Receiving Services
+ {>>/
+ Receiving Services:
+ Before a message is sent to /RecvMessage it goes through a MS_PROTO_CHAINRECV
+ which allows any other module to change data (for decryption, etc),
+ this then reaches /RecvMessage.
+
+ This does not have to be the same structure/memory contained within that
+ structure that started the chain call.
+
+ /RecvMessage adds the event to the database, any other modules who
+ are interested in what message the user will see should hook at this point.
+ />>}
+
+ {
+ CCSDATA: Yes
+ wParam : 0
+ lParam : Pointer to a TPROTORECVEVENT
+ Affect : An instant message has beeen received, see notes
+ Returns: 0
+ Notes : lParam^.lParam^.szMessage has the message, see structure above
+ stored as DB event EVENTTYPE_MESSAGE, blob contains message
+ string without null termination.
+ }
+ PSR_MESSAGE = '/RecvMessage';
+
+ {
+ CCSDATA: Yes
+ wParam : 0
+ lParam : Pointer to a TPROTORECVEVENT, see notes
+ Affect : A URL has been received
+ Notes : szMessage is encoded the same as PSS_URL
+ -
+ Stored in the database : EVENTTYPE_URL, blob contains message
+ without null termination
+ }
+ PSR_URL = '/RecvUrl';
+
+ {
+ CCSDATA: Yes
+ wParam : 0
+ lParam : Pointer to a TPROTORECVEVENT
+ Affect : Contacts have been received, see notes
+ Notes : pre.szMessage is actually a PROTOSEARCHRESULT list
+ pre.lParam is the number of contains in that list.
+ -
+ PS_ADDTOLIST can be used to add contacts to the list
+ -
+ repeat [
+ ASCIIZ userNick
+ ASCIIZ userId
+ ]
+ userNick should be a human-readable description of the user. It need not
+ be the nick, or even confined to displaying just one type of
+ information.
+ userId should be a machine-readable representation of the unique
+ protocol identifying field of the user. Because of the need to be
+ zero-terminated, binary data should be converted to text.
+ Use PS_ADDTOLISTBYEVENT to add the contacts from one of these to the list.
+ }
+ PSR_CONTACTS = '/RecvContacts';
+
+ {
+ CCSDATA: Yes
+ wParam : 0
+ lParam : Pointer to a TPROTORECVFILE
+ Affect : File(s) have been received
+ }
+ PSR_FILE = '/RecvFile';
+
+{$ENDIF}
+
diff --git a/plugins/ShlExt/inc/m_skin.inc b/plugins/ShlExt/inc/m_skin.inc
new file mode 100644
index 0000000000..aee28ae4d9
--- /dev/null
+++ b/plugins/ShlExt/inc/m_skin.inc
@@ -0,0 +1,120 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+{$IFNDEF M_SKIN}
+{$DEFINE M_SKIN}
+
+const
+
+ // event icons
+
+ SKINICON_EVENT_MESSAGE = 100;
+ SKINICON_EVENT_URL = 101;
+ SKINICON_EVENT_FILE = 102;
+
+ // other icons
+ SKINICON_OTHER_MIRANDA = 200;
+ SKINICON_OTHER_EXIT = 201;
+ SKINICON_OTHER_SHOWHIDE = 202;
+ SKINICON_OTHER_GROUPOPEN = 203; // v0.1.1.0+
+ SKINICON_OTHER_GROUPSHUT = 205; // v0.1.1.0+
+ SKINICON_OTHER_USERONLINE = 204; // v0.1.0.1+
+
+ // menu icons are owned by the module that uses them so are not and should not
+ // be skinnable. Except exit and show/hide
+
+ // status mode icons. NOTE: These are deprecated in favour of LoadSkinnedProtoIcon()
+ SKINICON_STATUS_OFFLINE = 0;
+ SKINICON_STATUS_ONLINE = 1;
+ SKINICON_STATUS_AWAY = 2;
+ SKINICON_STATUS_NA = 3;
+ SKINICON_STATUS_OCCUPIED = 4;
+ SKINICON_STATUS_DND = 5;
+ SKINICON_STATUS_FREE4CHAT = 6;
+ SKINICON_STATUS_INVISIBLE = 7;
+ SKINICON_STATUS_ONTHEPHONE = 8;
+ SKINICON_STATUS_OUTTOLUNCH = 9;
+
+type
+
+ PSKINSOUNDDESC = ^TSKINSOUNDDESC;
+ TSKINSOUNDDESC = record
+ cbSize: int;
+ { name to refer to sound when playing and in DB }
+ pszName: PChar;
+ { description to use for it in options dialog }
+ pszDescription: PChar;
+ { the default sound file to use, WITHOUT path }
+ pszDefaultFile: PChar;
+ end;
+
+const
+
+ {
+ wParam : ICON_ID
+ lParam : 0
+ Affect : Load an icon from the user's custom skin lib, or from the exe
+ if there isn't one loaded, see notes
+ Return : HICON for the new icon, do *not* DestroyIcon() the return value
+ returns NULL(0) if ICON_ID is invalid, but always success for a valid
+ ID.
+ }
+ MS_SKIN_LOADICON = 'Skin/Icons/Load';
+
+ {
+ wParam : null terminated string containing the protocol name
+ lParam : status_wanted
+ Affect : Load an icon representing the status_wanted for a particular protocol, see notes
+ Returns: an HICON for the new icon, do NOT DestroyIcon() the return value
+ returns NULL(0) on failure.
+ Notes : If wParam is NULL(0) the service will load the user's selected
+ 'all protocols' status icon
+ }
+ MS_SKIN_LOADPROTOICON = 'Skin/Icons/LoadProto';
+
+ {
+ wParam : 0
+ lParam : Pointer to a initialised SKINSOUNDDESC
+ Affect : Add a new sound so it has a default and can be changed in the options dialog
+ Returns: 0 on success, [non zero] on failure
+ }
+ MS_SKIN_ADDNEWSOUND = 'Skin/Sounds/AddNew';
+
+ {
+ wParam : 0
+ lParam : Pointer to a null terminated string containing the name of the sound to play
+ Affect : play a named sound event, play name should of been added
+ with MS_SKIN_ADDNEWSOUND, see notes
+ Notes : function will not fail, it will play the Windows
+ }
+ MS_SKIN_PLAYSOUND = 'Skin/Sounds/Play';
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Sent when the icons DLL has been changed in the options dialog
+ and everyone should remake their image lists.
+ }
+ ME_SKIN_ICONSCHANGED = 'Skin/IconsChanged';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_system.inc b/plugins/ShlExt/inc/m_system.inc
new file mode 100644
index 0000000000..90d7f53858
--- /dev/null
+++ b/plugins/ShlExt/inc/m_system.inc
@@ -0,0 +1,170 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+{$IFNDEF M_SYSTEM}
+{$DEFINE M_SYSTEM}
+
+type
+
+ TMM_INTERFACE = record
+ cbSize: int;
+ _malloc: function(cbSize: Integer): Pointer; cdecl;
+ _realloc: function (pb: Pointer; cbSize: Integer): Pointer; cdecl;
+ _free: procedure(pb: Pointer); cdecl;
+ end;
+
+const
+
+ MIRANDANAME = 'Miranda';
+
+ {
+ wParam : 0
+ lParam : 0
+ affect : called after all modules have been successfully initialised
+ used to resolve double-dependencies in the module load order, see notes
+ return : 0
+ notes : Can be used to call services, etc that have not yet loaded
+ when your module has.
+ }
+ ME_SYSTEM_MODULESLOADED = 'Miranda/System/ModulesLoaded';
+
+ {
+ wParam : 0
+ lParam : 0
+ affect : called just before Miranda terminates, the database is still running
+ during this hook
+ return : 0
+ }
+ ME_SYSTEM_SHUTDOWN = 'Miranda/System/Shutdown';
+
+ {
+ wParam : 0
+ lParam : 0
+ affect : called before Miranda actually shuts down -- everyone has to agree
+ or it is not shut down.
+ return : non zero to stop the shutdown
+ }
+ ME_SYSTEM_OKTOEXIT = 'Miranda/System/OkToExitEvent';
+
+ {
+ wParam : 0
+ lParam : 0
+ affect : service which sends everyone the ME_SYSTEM_OKTOEXIT event
+ return : true if everyone is okay to exit, otherwise false
+ }
+ MS_SYSTEM_OKTOEXIT = 'Miranda/System/OkToExit';
+
+ {
+ wParam : 0
+ lParam : 0
+ return : returns the version number -- each byte set with version index,
+ e.g. 1.2.3.4 $01020304
+ }
+ MS_SYSTEM_GETVERSION = 'Miranda/System/GetVersion';
+
+ {
+ wParam : size in bytes of the buffer to be filled
+ lParam : pointer to the buffer to be filled
+ affect : returns Miranda's version as text with build type such as '1.2.3.4 alpha'
+ return : 0 on success -- non zero on failure
+ }
+ MS_SYSTEM_GETVERSIONTEXT = 'Miranda/System/GetVersionText';
+
+ {
+ wParam : Handle of a wait object to be used
+ lParam : pointer to service name
+ affect : causes the service name to be called whenever the wait object
+ is signalled with CallService(Service, wParam=hWaitObjeect, lParam=0)
+ return : 0 on success, non zero on failure, will always fail if
+ more than 64 event objects are already being waited on because
+ of the limit imposed by Windows.
+ version: implemented after v0.1.2.0+
+ other : QueueUserAPC() can be used instead of this service to wait
+ for notifications, BUT *only* after v0.1.2.2+ since that deals
+ with APC's
+ }
+ MS_SYSTEM_WAITONHANDLE = 'Miranda/System/WaitOnHandle';
+
+ {
+ wParam : hWaitObject to be removed
+ lParam : 0
+ affect : removes the wait object from the list, see above.
+ returns: 0 on success, nonzero on failure
+ version: implemented after v0.1.2.0+
+ }
+ MS_SYSTEM_REMOVEWAIT = 'Miranda/System/RemoveWait';
+
+ {
+ wParam : 0
+ lParam : Pointer to an initialised TMM_INTERFACE
+ affect : Get function pointers to, malloc(), free() and realloc() used by Miranda
+ note : this should only be used carefully, make sure .cbSize is initialised with sizeof(TMM_INTERFACE)
+ version: 0.1.2.2+
+ }
+ MS_SYSTEM_GET_MMI = 'Miranda/System/GetMMI';
+
+ {
+ wParam=0
+ lParam=0
+
+ Add a thread to the unwind wait stack that Miranda will poll on
+ when it is tearing down modules.
+
+ This must be called in the context of the thread that is to be pushed
+ i.e. there are no args, it works out what thread is being called
+ and gets itself a handle to the calling thread.
+ }
+ MS_SYSTEM_THREAD_PUSH = 'Miranda/Thread/Push';
+
+ {
+ wParam=0
+ lParam=0
+
+ Remove a thread from the unwind wait stack -- it is expected
+ that the call be made in the context of the thread to be removed.
+
+ Miranda will begin to tear down modules and plugins if/when the
+ last thread from the unwind stack is removed.
+ }
+ MS_SYSTEM_THREAD_POP = 'Miranda/Thread/Pop';
+
+ {
+ wParam=0
+ lParam=0
+
+ This hook is fired just before the thread unwind stack is used,
+ it allows MT plugins to shutdown threads if they have any special
+ processing to do, etc.
+ }
+ ME_SYSTEM_PRESHUTDOWN = 'Miranda/System/PShutdown';
+
+ {
+ wParam=0
+ lParam=0
+
+ Returns TRUE when Miranda has got WM_QUIT and is in the process
+ of shutting down
+ }
+ MS_SYSTEM_TERMINATED = 'Miranda/SysTerm';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_url.inc b/plugins/ShlExt/inc/m_url.inc
new file mode 100644
index 0000000000..a541576329
--- /dev/null
+++ b/plugins/ShlExt/inc/m_url.inc
@@ -0,0 +1,39 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_URL}
+{$DEFINE M_URL}
+
+const
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affects: bring up the send URL dialogbox for a user
+ Returns: 0 on success, nonzero on failure, see notes
+ Notes : service returns before the URL is sent.
+ }
+ MS_URL_SENDURL = 'SRUrl/SendCommand';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_userinfo.inc b/plugins/ShlExt/inc/m_userinfo.inc
new file mode 100644
index 0000000000..8f5e1eb654
--- /dev/null
+++ b/plugins/ShlExt/inc/m_userinfo.inc
@@ -0,0 +1,84 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_USERINFO}
+{$DEFINE M_USERINFO}
+
+const
+
+ {
+ wParam : HCONTACT
+ lParam : 0
+ Affects: Show the user details dialog box for a contact, see notes
+ Notes : I think this can be used to display "My User Details"... if NULL(0) is used
+ }
+ MS_USERINFO_SHOWDIALOG = 'UserInfo/ShowDialog';
+
+ {
+ wParam : 0
+ lParam : HCONTACT
+ Affects: The details dialog box was opened for a contact maybe NULL(0)
+ showing the user details -- see notes
+ Notes : The module should do whatever initialisation they need and
+ call MS_USERINFO_ADDPAGE one or more times if they want
+ pages displayed in the options dialog -- wParam should be passed
+ straight as the wParam of MS_USERINFO_ADDPAGE.
+ -
+ The builtin userinfo module is not loaded til after all plugins
+ have loaded -- therefore a HookEvent() for this event will fail,
+ use ME_SYSTEM_MODULESLOADED event to know when everything has
+ loaded and it's okay to hook this event.
+ Version: v0.1.2.0+
+ }
+ ME_USERINFO_INITIALISE = 'UserInfo/Initialise';
+
+ {
+ wParam : wParam from ME_USERINFO_INITIALISE
+ lParam : pointer to an initialised OPTIONSDIALOGPAGE (see m_options.inc)
+ Affects: Adds a page to the details dialog, see notes
+ Notes : this service should only be called within the ME_USERINFO_INITIALISE
+ event -- when the pages get (WM_INITDIALOG lParam=HCONTACT) strings
+ in the passed dialog structure can be freed soon as the service returns
+ icons must be kept around (not a problem if you're loading from resource).
+ -
+ The group elements within the OPTIONSDIALOGPAGE are ignored,
+ details dialog page should be 222x132 DLU's -- the details dialog
+ box currently has no cancel button, pages will be sent PSN_INFOCHANGED
+ thru WM_NOTIFY (idFrom=0) when a protocol ACK is broadcast for
+ the correct contact with the type ACKTYPE_GETINFO.
+ -
+ PSN_INFOCHANGED will also be sent just after the page is created
+ to help you out.
+ -
+ All PSN_* WM_NOTIFY messages have PSHNOTIFY.lParam=(LPARAM)hContact
+ Version: v0.1.2.0+
+ }
+
+ PSN_INFOCHANGED = 1;
+ { force-send a PSN_INFOCHANGED to all pages }
+ PSM_FORCECHANGED = ($0400 + 100);
+
+ MS_USERINFO_ADDPAGE = 'UserInfo/AddPage';
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/m_utils.inc b/plugins/ShlExt/inc/m_utils.inc
new file mode 100644
index 0000000000..325b61db24
--- /dev/null
+++ b/plugins/ShlExt/inc/m_utils.inc
@@ -0,0 +1,279 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF M_UTILS}
+{$DEFINE M_UTILS}
+
+const
+
+ RD_ANCHORX_CUSTOM = 0; // function did everything required to the x axis, do no more processing
+ RD_ANCHORX_LEFT = 0; // move the control to keep it constant distance from the left edge of the dialog
+ RD_ANCHORX_RIGHT = 1; // move the control to keep it constant distance from the right edge of the dialog
+ RD_ANCHORX_WIDTH = 2; // size the control to keep it constant distance from both edges of the dialog
+ RD_ANCHORX_CENTRE = 4; // move the control to keep it constant distance from the centre of the dialog
+ RD_ANCHORY_CUSTOM = 0;
+ RD_ANCHORY_TOP = 0;
+ RD_ANCHORY_BOTTOM = 8;
+ RD_ANCHORY_HEIGHT = 16;
+ RD_ANCHORY_CENTRE = 32;
+
+ // for MS_UTILS_RESTOREWINDOWPOSITION
+
+ RWPF_NOSIZE = 1; // don't use stored size info: leave dialog same size
+ RWPF_NOMOVE = 2; // don't use stored position
+
+ // for WNDCLASS_COLOURPICKER
+
+ CPM_SETCOLOUR = $1000;// lParam=new colour
+ CPM_GETCOLOUR = $1001;// returns colour
+ CPM_SETDEFAULTCOLOUR = $1002;// lParam=default, used as first custom colour
+ CPM_GETDEFAULTCOLOUR = $1003;// returns colour
+ CPN_COLOURCHANGED = 1; // sent through WM_COMMAND
+
+type
+
+ PUTILRESIZECONTROL = ^TUTILRESIZECONTROL;
+ TUTILRESIZECONTROL = record
+ cbSize: int;
+ wId: int; // control ID
+ rcItem: TRect; // original control rectangle, relative to dialog
+ // modify in-placee to specify the new position
+ dlgOriginalSize: TSize; // size of dialog client area in template
+ dlgNewSize: TSize; // current size of dialog client area
+ end;
+
+ TDIALOGRESIZERPROC = function(hwndDlg: THandle; lParam: LPARAM; urc: PUTILRESIZECONTROL): int; cdecl;
+
+ PUTILRESIZEDIALOG = ^TUTILRESIZEDIALOG;
+ TUTILRESIZEDIALOG = record
+ cbSize: int;
+ hwndDlg: THandle;
+ hInstance: THandle;
+ lpTemplate: PChar;
+ lParam: LPARAM;
+ pfnResizer: TDIALOGRESIZERPROC;
+ end;
+
+ PCountryListEntry = ^TCountryListEntry;
+ TCountryListEntry = record
+ id: int;
+ szName: PChar;
+ end;
+
+ PWINDOWLISTENTRY = ^TWINDOWLISTENTRY;
+ TWINDOWLISTENTRY = record
+ hList: THandle;
+ hWnd: THandle;
+ hContact: THandle;
+ end;
+
+ PSAVEWINDOWPOS = ^TSAVEWINDOWPOS;
+ TSAVEWINDOWPOS = record
+ hWnd: THandle;
+ hContact: THandle;
+ szModule: PChar; // module name eto store the settings in
+ szNamePrefix: PChar; // text to prefix on 'x', 'width', etc
+ end;
+
+const
+
+ {
+ wParam : bOpenInNewWindow
+ lParam : Pointer to a null terminated string containing Url
+ Affect : Open a URRL in the user's default web browser, see notes
+ Returns: 0 on success, [non zero on failure]
+ Notes : bOpenInWindow should be zero to open the URL in the browoser window
+ the user last used, or nonzero to open in a new browser window,
+ if there's no browser running, it will be started to show the URL
+ Version: v0.1.0.1+
+ }
+ MS_UTILS_OPENURL = 'Utils/OpenURL';
+
+ {
+ wParam : 0
+ lParam : Pointer to an initalised TUTILRESIZEDIALOG structure
+ Affect : Resize a dialog by calling a custom routine to move each control, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : Does not support DIALOGTEMPLATEEX dialogboxes, and will return
+ failure if you try to resize one.-
+ the dialog iteself should have been resized prior to calling this
+ service, .pfnResizer is called once for each control in the dialog
+ .pfnResizer should return a combination of one RD_ANCHORx_ and one RD_ANCHORy constant
+ Version: v0.1.0.1+
+ }
+ MS_UTILS_RESIZEDIALOG = 'Utils/ResizeDialog';
+
+ {
+ wParam : countryID
+ lParam : 0
+ Affect : Get the name of a country given it's number, e.g. 44 = UK
+ Returns: Returns a pointer to a string containing the country name on success
+ NULL(0) on failure
+ Version: v0.1.2.0+
+ }
+ MS_UTILS_GETCOUNTRYBYNUMBER = 'Utils/GetCountryByNumber';
+
+ {
+ wParam : Pointer to an int to be filled with count -- !TODO! test.
+ lParam : Pointer to an PCountryListEntry, see notes
+ Affect : Get the full list of country IDs, see notes
+ Returns: 0 always
+ Notes : the list is sorted alphabetically by name, on the assumption
+ it's quicker to search numbers that are out of outer, than strings
+ that are out of order. a NULL(0) entry terminates
+ -
+ Neither wParam or lParam can be NULL(0)
+ -
+ lParam is filled with the first entry, it can be accessed as a pointer,
+ to get the next entry, increment the pointer by sizeof(Pointer) NOT
+ sizeof(TCountryList), only increment the pointer as many times as
+ given by iCount.
+ -
+ this data can NOT be copied if an array of TCountryListEntry's is passed
+ so don't try it.
+ Version: v0.1.2.0+
+ }
+ MS_UTILS_GETCOUNTRYLIST = 'Utils/GetCountryList';
+
+ // see WindowList_* functions below
+
+ {
+ wParam : 0
+ lParam : 0
+ Affect : Allocate a window list
+ Returns: A handle to the new window list
+ Version: v0.1.0.1+
+ }
+ MS_UTILS_ALLOCWINDOWLIST = 'Utils/AllocWindowList';
+
+ {
+ wParam : 0
+ lParam : Pointer to an initalised TWINDOWLISTENTRY structure
+ Affect : Add a window to a given window list handle
+ Returns: 0 on success, [non zero] on failure
+ Version: v0.1.0.1+
+ }
+ MS_UTILS_ADDTOWINDOWLIST = 'Utils/AddToWindowList';
+
+ {
+ wParam : Handle to window list to remove from
+ lParam : Window handle to remove
+ Affect : Remove a window from the specified window list
+ Returns: 0 on success, [non zero] on failure
+ Version: v0.1.0.1+
+ }
+ MS_UTILS_REMOVEFROMWINDOWLIST = 'Utils/RemoveFromWindowList';
+
+ {
+ wParam : Handle to the window list to look in
+ lParam : Handle to a HCONTACT to find in the window list
+ Affect : Find a window handle given the hContact
+ Returns: The found window handle or NULL(0) on failure
+ Version: v0.1.0.1+
+ }
+ MS_UTILS_FINDWINDOWINLIST = 'Utils/FindWindowInList';
+
+ {
+ wParam : Handle to window list
+ lParam : Pointer to TMSG (initalised with what to broadcast)
+ Affect : Broadcast a message to all windows in a list, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : only TMSG.Message, .wParam, .lParam are used
+ Version: v0.1.0.1+
+ }
+ MS_UTILS_BROADCASTTOWINDOWLIST = 'Utils/BroadcastToWindowList';
+
+ {
+ There aren't any services here, there's no need for them, the control class
+ will obey the SS_LEFT (0), SS_CENTER (1), SS_RIGHT(2) styles
+ the control will send STN_CLICKED via WM_COMMAND when the link itself is clicked
+ -
+ These are defined by STATIC controls and STN_CLICKED is sent to standard
+ STATIC classes when they're clicked -- look at WINAPI docs for more info
+ }
+ WNDCLASS_HYPERLINK = 'Hyperlink';
+
+ {
+ wParam : 0
+ lParam : Pointer to a initialised TSAVEWINDOWPOS structure
+ Affect :
+ Returns: 0 on success, [non zero] on failure
+ Notes :
+ Version: v0.1.1.0+
+ }
+ MS_UTILS_SAVEWINDOWPOSITION = 'Utils/SaveWindowPos';
+
+ {
+ wParam : see RWPF_* flags
+ lParam : Pointer to a initalised TSAVEWINDOWPOS
+ Affect : Restores the position of a window from the database, see notes
+ Returns: 0 on success, [non zero] on failure
+ Notes : If no position info was found, the service will return 1.
+ The NoSize version won't use stored information size, the window
+ is left the same size
+ -
+ See Utils_RestoreWindowPosition() Helper function, this function is
+ a bit different from the C function (which can be inlined too! dammit)
+ that there's only one function and not three (which just passed different flags)
+ Version: v0.1.1.0+
+ }
+ MS_UTILS_RESTOREWINDOWPOSITION = 'Utils/RestoreWindowPos';
+
+ {
+ Colour picker control, see CPM_* and CPN_* constants above
+ }
+ WNDCLASS_COLOURPICKER = 'ColourPicker';
+
+ {
+ wParam : 0
+ lParam : Pointer to a null terminated string containing filename
+ Affect : Loads a bitmap (or other graphic type, see Notes
+ Returns: HBITMAP on success, NULL(0) on failure
+ Notes : This function also supports JPEG, GIF (and maybe PNG too)
+ For speed, if the file extention is .bmp or .rle it will use LoadImage()
+ and not load OLE for the extra image support
+ -
+ Remember to delete the returned handle with DeleteObject (see GDI documentation for WINAPI)
+ Version: v0.1.2.1+
+ }
+ MS_UTILS_LOADBITMAP = 'Utils/LoadBitmap';
+
+ {
+ wParam : byte length of buffer (not to be confused with byte range)
+ lParam : Pointer to buffer
+ Affect : Get the filter strings for use in the open file dialog, see notes
+ Returns: 0 on success [non zero] on failure
+ Notes : See the WINAPI under OPENFILENAME.lpStrFiler for formatting,
+ an 'All bitmaps' item is alway first, and 'All files' is always last
+ -
+ The returned string is always formatted
+ -
+ To build this filter, the filter string consists of
+ filter followed by a descriptive text
+ followed by more filters and their descriptive texts -- end with double NULL(0)
+ e.g. *.bmp' #0 'All bitmaps' #0 '*.*' #0 'All Files' #0 #0
+ }
+ MS_UTILS_GETBITMAPFILTERSTRINGS = 'Utils/GetBitmapFilterStrings';
+
+{$endif}
diff --git a/plugins/ShlExt/inc/m_v8.inc b/plugins/ShlExt/inc/m_v8.inc
new file mode 100644
index 0000000000..e0c9d1e0c8
--- /dev/null
+++ b/plugins/ShlExt/inc/m_v8.inc
@@ -0,0 +1,62 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+{$IFNDEF V8}
+{$DEFINE V8}
+
+type
+
+ PMUUID = ^TMUUID;
+ TMUUID = record
+ a: LongWord;
+ b, c: Word;
+ d: array[0..7] of Byte;
+ end;
+
+ PPLUGININFOEX = ^TPLUGININFOEX;
+ TPLUGININFOEX = record
+ cbSize: int;
+ shortName: PChar;
+ version: DWORD;
+ description: PChar;
+ author: PChar;
+ authorEmail: PChar;
+ copyright: PChar;
+ homepage: PChar;
+ isTransient: Byte; // leave zero for now
+ { one of the DEFMOD_* consts in m_plugin or zero, if non zero, this will
+ suppress loading of the specified builtin module }
+ replacesDefaultModule: int;
+ uuid: TMUUID;
+ end;
+
+ { any module must export the below functions to be valid plugin
+ the export names MUST be 'MirandaPluginInfo' 'Load' 'Unload' }
+
+ // defined in newpluginapi.inc
+
+ //TMirandaPluginInfo = function(mirandaVersion: DWORD): PPLUGININFO; cdecl;
+ //TLoad = function(link: PPLUGINLINK): int; cdecl;
+ //TUnload = function: int; cdecl;
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/newpluginapi.inc b/plugins/ShlExt/inc/newpluginapi.inc
new file mode 100644
index 0000000000..85a7df9a2b
--- /dev/null
+++ b/plugins/ShlExt/inc/newpluginapi.inc
@@ -0,0 +1,94 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+{$IFNDEF NEWPLUGINAPI}
+{$DEFINE NEWPLUGINAPI}
+
+const
+
+ MAXMODULELABELLENGTH = 64;
+
+type
+
+ PPLUGININFO = ^TPLUGININFO;
+ TPLUGININFO = record
+ cbSize: int;
+ shortName: PChar;
+ version: DWORD;
+ description: PChar;
+ author: PChar;
+ authorEmail: PChar;
+ copyright: PChar;
+ homepage: PChar;
+ isTransient: Byte; // leave zero for now
+ { one of the DEFMOD_* consts in m_plugin or zero, if non zero, this will
+ suppress loading of the specified builtin module }
+ replacesDefaultModule: int;
+ end;
+
+ { modules.h is never defined -- no check needed }
+
+ TMIRANDAHOOK = function(wParam: WPARAM; lParam: LPARAM): int; cdecl;
+ TMIRANDASERVICE = function(wParam: WPARAM; lParam: LPARAM): int; cdecl;
+
+ //see modules.h tor what all this stuff is
+
+ TCreateHookableEvent = function(const char: PChar): THandle; cdecl;
+ TDestroyHookableEvent = function(Handle: THandle): int; cdecl;
+ TNotifyEventHooks = function(Handle: THandle; wParam: WPARAM; lParam: LPARAM): int; cdecl;
+ THookEvent = function(const char: PChar; MIRANDAHOOK: TMIRANDAHOOK): THandle; cdecl;
+ THookEventMessage = function(const char: PChar; Wnd: THandle; wMsg: Integer): THandle; cdecl;
+ TUnhookEvent = function(Handle: THandle): int; cdecl;
+ TCreateServiceFunction = function(const char: PChar; MIRANDASERVICE: TMIRANDASERVICE): THandle; cdecl;
+ TCreateTransientServiceFunction = function(const char: PChar; MIRANDASERVICE: TMIRANDASERVICE): THandle; cdecl;
+ TDestroyServiceFunction = function(Handle: THandle): int; cdecl;
+ TCallService = function(const char: PChar; wParam: WPARAM; lParam: LPARAM): int; cdecl;
+ TServiceExists = function(const char: PChar): int; cdecl;
+
+ PPLUGINLINK = ^TPLUGINLINK;
+ TPLUGINLINK = record
+ CreateHookableEvent: TCreateHookableEvent;
+ DestroyHookableEvent: TDestroyHookableEvent;
+ NotifyEventHooks: TNotifyEventHooks;
+ HookEvent: THookEvent;
+ HookEventMessage: THookEventMessage;
+ UnhookEvent: TUnhookEvent;
+ CreateServiceFunction: TCreateServiceFunction;
+ CreateTransientServiceFunction: TCreateTransientServiceFunction;
+ DestroyServiceFunction: TDestroyServiceFunction;
+ CallService: TCallService;
+ ServiceExists: TServiceExists; // v0.1.0.1+
+ end;
+
+ { any module must export the below functions to be valid plugin
+ the export names MUST be 'MirandaPluginInfo' 'Load' 'Unload' }
+
+ TMirandaPluginInfo = function(mirandaVersion: DWORD): PPLUGININFO; cdecl;
+ TLoad = function(link: PPLUGINLINK): int; cdecl;
+ TUnload = function: int; cdecl;
+
+const
+
+ CALLSERVICE_NOTFOUND = $80000000;
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/statusmodes.inc b/plugins/ShlExt/inc/statusmodes.inc
new file mode 100644
index 0000000000..2cf180569f
--- /dev/null
+++ b/plugins/ShlExt/inc/statusmodes.inc
@@ -0,0 +1,54 @@
+(*
+
+Miranda IM: the free IM client for Microsoft* Windows*
+
+Copyright 2000-2004 Miranda ICQ/IM project,
+all portions of this codebase are copyrighted to the people
+listed in contributors.txt.
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*)
+
+{$IFNDEF STATUSMODES}
+{$DEFINE STATUSMODES}
+
+const
+
+ // add 1 to the ID_STATUS_CONNECTING to mark retries (v0.1.0.1+)
+ // e.g. ID_STATUS_CONNECTING+2 is the third connection attempt, or the second retry
+
+ ID_STATUS_CONNECTING = 1;
+
+ // max retries is just a marker, so that the clist knows what
+ // numbers represent retries, it should set any kind of limit on the number
+ // of retries you can and/or should do
+
+ MAX_CONNECT_RETRIES = 10000;
+
+ // and the modes!
+
+ ID_STATUS_OFFLINE = 40071;
+ ID_STATUS_ONLINE = 40072;
+ ID_STATUS_AWAY = 40073;
+ ID_STATUS_DND = 40074;
+ ID_STATUS_NA = 40075;
+ ID_STATUS_OCCUPIED = 40076;
+ ID_STATUS_FREECHAT = 40077;
+ ID_STATUS_INVISIBLE = 40078;
+ ID_STATUS_ONTHEPHONE = 40079;
+ ID_STATUS_OUTTOLUNCH = 40080;
+
+{$ENDIF}
diff --git a/plugins/ShlExt/inc/testdll.dpr b/plugins/ShlExt/inc/testdll.dpr
new file mode 100644
index 0000000000..478212d82c
--- /dev/null
+++ b/plugins/ShlExt/inc/testdll.dpr
@@ -0,0 +1,60 @@
+library testdll;
+
+uses
+
+ m_globaldefs, m_api, Windows;
+
+ {$include m_helpers.inc}
+
+ function MirandaPluginInfo(mirandaVersion: DWORD): PPLUGININFO; cdecl;
+ begin
+ Result := @PLUGININFO;
+ PLUGININFO.cbSize := sizeof(TPLUGININFO);
+ PLUGININFO.shortName := 'Plugin Template';
+ PLUGININFO.version := PLUGIN_MAKE_VERSION(0,0,0,1);
+ PLUGININFO.description := 'The long description of your plugin, to go in the plugin options dialog';
+ PLUGININFO.author := 'J. Random Hacker';
+ PLUGININFO.authorEmail := 'noreply@sourceforge.net';
+ PLUGININFO.copyright := '(c) 2003 J. Random Hacker';
+ PLUGININFO.homepage := 'http://miranda-icq.sourceforge.net/';
+ PLUGININFO.isTransient := 0;
+ PLUGININFO.replacesDefaultModule := 0;
+ end;
+
+ function PluginMenuCommand(wParam: WPARAM; lParam: LPARAM): Integer; cdecl;
+ begin
+ Result := 0;
+ // this is called by Miranda, thus has to use the cdecl calling convention
+ // all services and hooks need this.
+ MessageBox(0, 'Just groovy, baby!', 'Plugin-o-rama', MB_OK);
+ end;
+
+ function Load(link: PPLUGINLINK): int; cdecl;
+ var
+ mi: TCListMenuItem;
+ begin
+ // this line is VERY VERY important, if it's not present, expect crashes.
+ PLUGINLINK := Pointer(link);
+ pluginLink^.CreateServiceFunction('TestPlug/MenuCommand', @PluginMenuCommand);
+ FillChar(mi, sizeof(mi), 0);
+ mi.cbSize := sizeof(mi);
+ mi.position := $7FFFFFFF;
+ mi.flags := 0;
+ mi.hIcon := LoadSkinnedIcon(SKINICON_OTHER_MIRANDA);
+ mi.pszName := '&Test Plugin...';
+ mi.pszService := 'TestPlug/MenuCommand';
+ pluginLink^.CallService(MS_CLIST_ADDMAINMENUITEM, 0, lParam(@mi));
+ Result := 0;
+ end;
+
+ function Unload: int; cdecl;
+ begin
+ Result := 0;
+ end;
+
+ exports
+
+ MirandaPluginInfo, Load, Unload;
+
+begin
+end.
diff --git a/plugins/ShlExt/make.bat b/plugins/ShlExt/make.bat
new file mode 100644
index 0000000000..40131550cf
--- /dev/null
+++ b/plugins/ShlExt/make.bat
@@ -0,0 +1,9 @@
+@echo off
+REM -Fi/u are for include/unit dirs
+REM -Mdelphi is delphi mode
+REM -WG - graphical app
+REM -v0 turn off warnings
+REM -O2 -Os // optimise
+REM -Rintel (intel style asm)
+REM -WB (relocatable) -WR (relocate)
+fpc shlext.dpr -Fiinc -Fuinc -Mdelphi -WG -O2 -Os -Rintel -WR -WB49ac0000 -v0 \ No newline at end of file
diff --git a/plugins/ShlExt/resource.h b/plugins/ShlExt/resource.h
new file mode 100644
index 0000000000..c89660a88d
--- /dev/null
+++ b/plugins/ShlExt/resource.h
@@ -0,0 +1,13 @@
+#define IDD_SHLOPTS 101
+#define IDC_USEGROUPS 1014
+#define IDC_CLISTGROUPS 1015
+#define IDC_SHOWFULL 1016
+#define IDC_NOPROF 1020
+#define IDC_SHOWINVISIBLES 1021
+#define IDC_HIDEOFFLINE 1022
+#define IDC_STATUS 1023
+#define IDC_CAPMENUS 1025
+#define IDC_CAPSTATUS 1026
+#define IDC_CAPSHLSTATUS 1027
+#define IDC_REMOVE 1028
+#define IDC_USEOWNERDRAW 1029
diff --git a/plugins/ShlExt/shlc.inc b/plugins/ShlExt/shlc.inc
new file mode 100644
index 0000000000..122e0fee14
--- /dev/null
+++ b/plugins/ShlExt/shlc.inc
@@ -0,0 +1,168 @@
+{$IFDEF SHL_IDC}
+const
+ IDD_SHLOPTS = 101;
+ IDC_USEGROUPS = 1014;
+ IDC_CLISTGROUPS = 1015;
+// Show "HIT"
+ IDC_SHOWFULL = 1016;
+ IDC_NOPROF = 1020;
+ IDC_SHOWINVISIBLES = 1021;
+ IDC_HIDEOFFLINE = 1022;
+// only in the options dialog
+ IDC_STATUS = 1023;
+ IDC_CAPMENUS = 1025;
+ IDC_CAPSTATUS = 1026;
+ IDC_CAPSHLSTATUS = 1027;
+ IDC_REMOVE = 1028;
+ IDC_USEOWNERDRAW = 1029;
+{$ENDIF}
+{$IFDEF SHL_KEYS}
+const
+ SHLExt_Name: PChar = 'shlext15';
+ SHLExt_MRU: PChar = 'MRU';
+ SHLExt_UseGroups: PChar = 'UseGroups';
+ SHLExt_UseCListSetting:PChar = 'UseCLGroups';
+ SHLExt_UseHITContacts:PChar = 'UseHITContacts';
+// HIT2 contacts will get your messages but don't know your state
+ SHLExt_UseHIT2Contacts: PChar = 'UseHIT2Contacts';
+ SHLExt_ShowNoProfile:PChar = 'ShowNoProfile';
+ SHLExt_ShowNoIcons:PChar = 'ShowNoIcons';
+ SHLExt_ShowNoOffline:PChar = 'ShowNoOffline';
+{$ENDIF}
+{$IFDEF SHLCOM}
+const
+
+ S_OK = 0;
+ S_FALSE = 1;
+
+ E_UNEXPECTED = $8000FFFF;
+ E_NOTIMPL = $80004001;
+ E_INVALIDARG = $80070057;
+
+ CLASS_E_NOAGGREGATION = $80040110;
+ CLASS_E_CLASSNOTAVAILABLE = $80040111;
+
+ CLSCTX_INPROC_SERVER = $1;
+
+ { for FORMATETC }
+
+ TYMED_HGLOBAL = 1;
+ DVASPECT_CONTENT = 1;
+
+type
+
+ PGUID = ^TGUID;
+ TGUID = record
+ D1: Longint;
+ D2: Word;
+ D3: Word;
+ D4: array[0..7] of Byte;
+ end;
+
+ TIID = TGUID;
+ TCLSID = TGUID;
+
+ TStgMedium = record
+ tymed: Longint;
+ case Integer of
+ 0: (hBitmap: HBitmap; unkForRelease: Pointer{IUnknown});
+ 1: (hMetaFilePict: THandle);
+ 2: (hEnhMetaFile: THandle);
+ 3: (hGlobal: HGlobal);
+ 4: (lpszFileName: Pointer{POleStr});
+ 5: (stm: Pointer{IUnknown});
+ 6: (stg: Pointer{IStorage});
+ end;
+
+ PFormatEtc = ^TFormatEtc;
+ TFormatEtc = record
+ cfFormat: Word; {TClipFormat;}
+ ptd: Pointer; {PDVTargetDevice;}
+ dwAspect: Longint;
+ lindex: Longint;
+ tymed: Longint;
+ end;
+
+{$ENDIF}
+{$IFDEF COM_STRUCTS}
+const
+
+ IID_IUnknown : TGUID = (
+ D1:$00000000;
+ D2:$0000;
+ D3:$0000;
+ D4:($C0,$00,$00,$00,$00,$00,$00,$46)
+ );
+
+ IID_IClassFactory : TGUID = (
+ D1:$00000001;
+ D2:$0000;
+ D3:$0000;
+ D4:($C0,$00,$00,$00,$00,$00,$00,$46)
+ );
+
+ IID_IShellExtInit : TGUID = (
+ D1:$000214E8;
+ D2:$0000;
+ D3:$0000;
+ D4:($C0,$00,$00,$00,$00,$00,$00,$46)
+ );
+
+ IID_IContextMenu : TGUID = (
+ D1:$000214E4;
+ D2:$0000;
+ D3:$0000;
+ D4:($C0,$00,$00,$00,$00,$00,$00,$46)
+ );
+
+ IID_IContextMenu2 : TGUID = (
+ D1:$000214F4;
+ D2:$0000;
+ D3:$0000;
+ D4:($C0,$00,$00,$00,$00,$00,$00,$46)
+ );
+
+ IID_IContextMenu3 : TGUID = (
+ D1:$BCFCE0A0;
+ D2:$EC17;
+ D3:$11D0;
+ D4:($8D,$10,$00,$A0,$C9,$0F,$27,$19)
+ );
+
+ IID_WICImagingFactory: TGUID = (
+ D1:$EC5EC8A9;
+ D2:$C395;
+ D3:$4314;
+ D4:($9C,$77,$54,$D7,$A9,$35,$FF,$70)
+ );
+
+
+ // Vista+ only
+
+ CLSID_WICImagingFactory : TGUID = (
+ D1:$cacaf262;
+ D2:$9370;
+ D3:$4615;
+ D4:($A1,$3B,$9F,$55,$39,$DA,$4C,$0A)
+ );
+
+ // anything before 0.0.1.5 was : {A321A032-7976-11d6-A310-ED893982BF28}
+ // changed to a new GUID to avoid older plugins
+ // {72013A26-A94C-11d6-8540-A5E62932711D}
+ // the IPC header now checks the plugin version given anyway.
+
+ CLSID_ISHLCOM : TGUID = (
+ D1: $72013a26;
+ D2: $a94c;
+ D3: $11d6;
+ D4: ($85,$40,$a5,$e6,$29,$32,$71,$1d);
+ );
+{$ENDIF}
+{$IFDEF COMAPI}
+ function CoCreateInstance(const rclsid: TCLSID; pUnkOuter: Pointer; dwClsContext: DWORD; const riid: TIID; var ppv): HResult; stdcall; external 'ole32.dll' name 'CoCreateInstance';
+ procedure ReleaseStgMedium(var medium: TStgMedium); stdcall; external 'ole32.dll' name 'ReleaseStgMedium';
+ function IsEqualGUID(const guid1, guid2: TGUID): Boolean; stdcall; external 'ole32.dll' name 'IsEqualGUID';
+ function IsEqualIID(const iid1, iid2: TIID): Boolean; stdcall; external 'ole32.dll' name 'IsEqualGUID';
+ function IsEqualCLSID(const clsid1, clsid2: TCLSID): Boolean; stdcall; external 'ole32.dll' name 'IsEqualGUID';
+ function QueueUserAPC(pfnAPC: Pointer; hThread: THandle; dwData: DWORD): BOOL; stdcall; external 'kernel32' name 'QueueUserAPC';
+{$ENDIF}
diff --git a/plugins/ShlExt/shlcom.pas b/plugins/ShlExt/shlcom.pas
new file mode 100644
index 0000000000..79a9134012
--- /dev/null
+++ b/plugins/ShlExt/shlcom.pas
@@ -0,0 +1,2383 @@
+unit shlcom;
+
+{$IFDEF FPC}
+ {$PACKRECORDS 4}
+ {$MODE Delphi}
+{$ENDIF}
+
+interface
+
+uses
+
+ Windows, m_globaldefs, shlipc, shlicons;
+
+ {$define COM_STRUCTS}
+ {$define SHLCOM}
+ {$include shlc.inc}
+ {$undef SHLCOM}
+ {$undef COM_STRUCTS}
+
+ function DllGetClassObject(const CLSID: TCLSID; const IID: TIID;
+ var Obj): HResult; stdcall;
+ function DllCanUnloadNow: HResult; stdcall;
+
+ procedure InvokeThreadServer;
+
+ procedure CheckRegisterServer;
+
+ procedure CheckUnregisterServer;
+
+ function RemoveCOMRegistryEntries: HResult;
+
+ function ExtractIcon(hInst: THandle; pszExe: PChar; nIndex: Integer): HICON; stdcall; external 'shell32.dll' name 'ExtractIconA';
+
+implementation
+
+var
+
+ dllpublic: record
+ FactoryCount: Integer;
+ ObjectCount: Integer;
+ end;
+
+ VistaOrLater: Boolean;
+
+ {$include m_database.inc}
+ {$include m_clist.inc}
+ {$include m_protocols.inc}
+ {$include m_protosvc.inc}
+ {$include m_ignore.inc}
+ {$include m_skin.inc}
+ {$include m_file.inc}
+ {$include m_system.inc}
+ {$include m_langpack.inc}
+ {$include m_skin.inc}
+ {$include statusmodes.inc}
+
+ {$define COMAPI}
+ {$include shlc.inc}
+ {$undef COMAPI}
+
+ {$include m_helpers.inc}
+
+const
+
+ IPC_PACKET_SIZE = $1000 * 32;
+ //IPC_PACKET_NAME = 'm.mi.miranda.ipc'; // prior to 1.0.6.6
+ //IPC_PACKET_NAME = 'mi.miranda.IPCServer'; // prior to 2.0.0.9
+ IPC_PACKET_NAME = 'm.mi.miranda.ipc.server';
+
+const
+
+{ Flags returned by IContextMenu*:QueryContextMenu() }
+
+ CMF_NORMAL = $00000000;
+ CMF_DEFAULTONLY = $00000001;
+ CMF_VERBSONLY = $00000002;
+ CMF_EXPLORE = $00000004;
+ CMF_NOVERBS = $00000008;
+ CMF_CANRENAME = $00000010;
+ CMF_NODEFAULT = $00000020;
+ CMF_INCLUDESTATIC = $00000040;
+ CMF_RESERVED = $FFFF0000; { view specific }
+
+{ IContextMenu*:GetCommandString() uType flags }
+
+ GCS_VERBA = $00000000; // canonical verb
+ GCS_HELPTEXTA = $00000001; // help text (for status bar)
+ GCS_VALIDATEA = $00000002; // validate command exists
+ GCS_VERBW = $00000004; // canonical verb (unicode)
+ GC_HELPTEXTW = $00000005; // help text (unicode version)
+ GCS_VALIDATEW = $00000006; // validate command exists (unicode)
+ GCS_UNICODE = $00000004; // for bit testing - Unicode string
+ GCS_VERB = GCS_VERBA; //
+ GCS_HELPTEXT = GCS_HELPTEXTA;
+ GCS_VALIDATE = GCS_VALIDATEA;
+
+type
+
+ { this structure is returned by InvokeCommand() }
+
+ PCMInvokeCommandInfo = ^TCMInvokeCommandInfo;
+ TCMInvokeCommandInfo = packed record
+ cbSize: DWORD;
+ fMask: DWORD;
+ hwnd: HWND;
+ lpVerb: PChar; { maybe index, type cast as Integer }
+ lpParams: PChar;
+ lpDir: PChar;
+ nShow: Integer;
+ dwHotkey: DWORD;
+ hIcon: THandle;
+ end;
+
+{ completely stolen from modules.c: 'NameHashFunction' modified slightly }
+
+ function StrHash(const szStr: PChar): DWORD; cdecl;
+ asm
+ // esi content has to be preserved with basm
+ push esi
+ xor edx,edx
+ xor eax,eax
+ mov esi,szStr
+ mov al,[esi]
+ xor cl,cl
+ @@lph_top: //only 4 of 9 instructions in here don't use AL, so optimal pipe use is impossible
+ xor edx,eax
+ inc esi
+ xor eax,eax
+ and cl,31
+ mov al,[esi]
+ add cl,5
+ test al,al
+ rol eax,cl //rol is u-pipe only, but pairable
+ //rol doesn't touch z-flag
+ jnz @@lph_top //5 clock tick loop. not bad.
+ xor eax,edx
+ pop esi
+ end;
+
+ function CreateProcessUID(const pid: Cardinal): string;
+ var
+ pidrep: string[16];
+ begin
+ str(pid, pidrep);
+ Result := Concat('mim.shlext.', pidrep, '$');
+ end;
+
+ function CreateUID: string;
+ var
+ pidrep, tidrep: string[16];
+ begin
+ str(GetCurrentProcessId(), pidrep);
+ str(GetCurrentThreadId(), tidrep);
+ Result := Concat('mim.shlext.caller', pidrep, '$', tidrep);
+ end;
+
+ // FPC doesn't support array[0..n] of Char extended syntax with Str()
+
+ function wsprintf(lpOut, lpFmt: PChar; ArgInt: Integer): Integer; cdecl; external 'user32.dll' name 'wsprintfA';
+
+ procedure Str(i: Integer; S: PChar);
+ begin
+ i := wsprintf(s, '%d', i);
+ if i > 2 then PChar(s)[i] := #0;
+ end;
+
+{ IShlCom }
+
+type
+
+ PLResult = ^LResult;
+
+ // bare minimum interface of IDataObject, since GetData() is only required.
+
+ PVTable_IDataObject = ^TVTable_IDataObject;
+ TVTable_IDataObject = record
+ { IUnknown }
+ QueryInterface: Pointer;
+ AddRef: function(Self: Pointer): Cardinal; stdcall;
+ Release: function(Self: Pointer): Cardinal; stdcall;
+ { IDataObject }
+ GetData: function(Self: Pointer; var formatetcIn: TFormatEtc; var medium: TStgMedium): HResult; stdcall;
+ GetDataHere: Pointer;
+ QueryGetData: Pointer;
+ GetCanonicalFormatEtc: Pointer;
+ SetData: Pointer;
+ EnumFormatEtc: Pointer;
+ DAdvise: Pointer;
+ DUnadvise: Pointer;
+ EnumDAdvise: Pointer;
+ end;
+
+ PDataObject_Interface = ^TDataObject_Interface;
+ TDataObject_Interface = record
+ ptrVTable: PVTable_IDataObject;
+ end;
+
+ { TShlComRec inherits from different interfaces with different function tables
+ all "compiler magic" is lost in this case, but it's pretty easy to return
+ a different function table for each interface, IContextMenu is returned
+ as IContextMenu'3' since it inherits from '2' and '1' }
+
+ PVTable_IShellExtInit = ^TVTable_IShellExtInit;
+ TVTable_IShellExtInit = record
+ { IUnknown }
+ QueryInterface: Pointer;
+ AddRef: Pointer;
+ Release: Pointer;
+ { IShellExtInit }
+ Initialise: Pointer;
+ end;
+
+ PShlComRec = ^TShlComRec;
+ PShellExtInit_Interface = ^TShellExtInit_Interface;
+ TShellExtInit_Interface = record
+ { pointer to function table }
+ ptrVTable: PVTable_IShellExtInit;
+ { instance data }
+ ptrInstance: PShlComRec;
+ { function table itself }
+ vTable: TVTable_IShellExtInit;
+ end;
+
+ PVTable_IContextMenu3 = ^TVTable_IContextMenu3;
+ TVTable_IContextMenu3 = record
+ { IUnknown }
+ QueryInterface: Pointer;
+ AddRef: Pointer;
+ Release: Pointer;
+ { IContextMenu }
+ QueryContextMenu: Pointer;
+ InvokeCommand: Pointer;
+ GetCommandString: Pointer;
+ { IContextMenu2 }
+ HandleMenuMsg: Pointer;
+ { IContextMenu3 }
+ HandleMenuMsg2: Pointer;
+ end;
+
+ PContextMenu3_Interface = ^TContextMenu3_Interface;
+ TContextMenu3_Interface = record
+ ptrVTable: PVTable_IContextMenu3;
+ ptrInstance: PShlComRec;
+ vTable: TVTable_IContextMenu3;
+ end;
+
+ PCommon_Interface = ^TCommon_Interface;
+ TCommon_Interface = record
+ ptrVTable: Pointer;
+ ptrInstance: PShlComRec;
+ end;
+
+ TShlComRec = record
+ ShellExtInit_Interface: TShellExtInit_Interface;
+ ContextMenu3_Interface: TContextMenu3_Interface;
+ {fields}
+ RefCount: LongInt;
+ // this is owned by the shell after items are added 'n' is used to
+ // grab menu information directly via id rather than array indexin'
+ hRootMenu: THandle;
+ idCmdFirst: Integer;
+ // most of the memory allocated is on this heap object so HeapDestroy()
+ // can do most of the cleanup, extremely lazy I know.
+ hDllHeap: THandle;
+ // This is a submenu that recently used contacts are inserted into
+ // the contact is inserted twice, once in its normal list (or group) and here
+ // Note: These variables are global data, but refered to locally by each instance
+ // Do not rely on these variables outside the process enumeration.
+ hRecentMenu: THandle;
+ RecentCount: Cardinal; // number of added items
+ // array of all the protocol icons, for every running instance!
+ ProtoIcons: ^TSlotProtoIconsArray;
+ ProtoIconsCount: Cardinal;
+ // maybe null, taken from IShellExtInit_Initalise() and AddRef()'d
+ // only used if a Miranda instance is actually running and a user
+ // is selected
+ pDataObject: PDataObject_Interface;
+ // DC is used for font metrics and saves on creating and destroying lots of DC handles
+ // during WM_MEASUREITEM
+ hMemDC: HDC;
+ end;
+
+ { this is passed to the enumeration callback so it can process PID's with
+ main windows by the class name MIRANDANAME loaded with the plugin
+ and use the IPC stuff between enumerations -- }
+
+ PEnumData = ^TEnumData;
+ TEnumData = record
+ Self: PShlComRec;
+ // autodetected, don't hard code since shells that don't support it
+ // won't send WM_MEASUREITETM/WM_DRAWITEM at all.
+ bOwnerDrawSupported: LongBool;
+ // as per user setting (maybe of multiple Mirandas)
+ bShouldOwnerDraw: LongBool;
+ idCmdFirst: Integer;
+ ipch: PHeaderIPC;
+ // OpenEvent()'d handle to give each IPC server an object to set signalled
+ hWaitFor: THandle;
+ pid: DWORD; // sub-unique value used to make work object name
+ end;
+
+ procedure FreeGroupTreeAndEmptyGroups(hParentMenu: THandle; pp, p: PGroupNode);
+ var
+ q: PGroupNode;
+ begin
+ while p <> nil do
+ begin
+ q := p^.Right;
+ if p^.Left <> nil then
+ begin
+ FreeGroupTreeAndEmptyGroups(p^.Left^.hMenu, p, p^.Left);
+ end; //if
+ if p^.dwItems = 0 then
+ begin
+ if pp <> nil then
+ begin
+ DeleteMenu(pp^.hMenu, p^.hMenuGroupID, MF_BYCOMMAND)
+ end else begin
+ DeleteMenu(hParentMenu, p^.hMenuGroupID, MF_BYCOMMAND);
+ end; //if
+ end else begin
+ // make sure this node's parent know's it exists
+ if pp <> nil then inc (pp^.dwItems);
+ end;
+ Dispose(p);
+ p := q;
+ end;
+ end;
+
+ procedure DecideMenuItemInfo(pct: PSlotIPC; pg: PGroupNode; var mii: TMenuItemInfo; lParam: PEnumData);
+ var
+ psd: PMenuDrawInfo;
+ hDllHeap: THandle;
+ j, c: Cardinal;
+ pp: ^TSlotProtoIconsArray;
+ begin
+ mii.wID := lParam^.idCmdFirst;
+ Inc(lParam^.idCmdFirst);
+ // get the heap object
+ hDllHeap := lParam^.Self^.hDllHeap;
+ psd := HeapAlloc(hDllHeap, 0, sizeof(TMenuDrawInfo));
+ if pct <> nil then
+ begin
+ psd^.cch := pct^.cbStrSection-1; // no null;
+ psd^.szText := HeapAlloc(hDllHeap, 0, pct^.cbStrSection);
+ strcpy(psd^.szText, PChar(Integer(pct)+sizeof(TSlotIPC)));
+ psd^.hContact := pct^.hContact;
+ psd^.fTypes := [dtContact];
+ // find the protocol icon array to use and which status
+ c := lParam^.Self^.protoIconsCount;
+ pp := lParam^.Self^.protoIcons;
+ psd^.hStatusIcon := 0;
+ while c > 0 do
+ begin
+ dec(c);
+ if (pp[c].hProto = pct^.hProto) and (pp[c].pid = lParam^.pid) then
+ begin
+ psd^.hStatusIcon := pp[c].hIcons[pct^.Status - ID_STATUS_OFFLINE];
+ psd^.hStatusBitmap := pp[c].hBitmaps[pct^.Status - ID_STATUS_OFFLINE];
+ break;
+ end;
+ end; //while
+ psd^.pid := lParam^.pid;
+ end else if pg <> nil then
+ begin
+ // store the given ID
+ pg^.hMenuGroupID := mii.wID;
+ // steal the pointer from the group node it should be on the heap
+ psd^.cch := pg^.cchGroup;
+ psd^.szText := pg^.szGroup;
+ psd^.fTypes := [dtGroup];
+ end; //if
+ psd^.wID := mii.wID;
+ psd^.szProfile := nil;
+ // store
+ mii.dwItemData := Integer(psd);
+
+ if ((lParam^.bOwnerDrawSupported) and (lParam^.bShouldOwnerDraw)) then
+ begin
+ mii.fType := MFT_OWNERDRAW;
+ Pointer(mii.dwTypeData) := psd;
+ end else begin
+ // normal menu
+ mii.fType := MFT_STRING;
+ if pct <> nil then
+ begin
+ Integer(mii.dwTypeData) := Integer(pct) + sizeof(TSlotIPC);
+ end else begin
+ mii.dwTypeData := pg^.szGroup;
+ end;
+ { For Vista + let the system draw the theme and icons, pct = contact associated data }
+ if VistaOrLater and ( pct <> nil ) and ( psd <> nil) then
+ begin
+ mii.fMask := MIIM_BITMAP or MIIM_FTYPE or MIIM_ID or MIIM_DATA or MIIM_STRING;
+ // BuildSkinIcons() built an array of bitmaps which we can use here
+ mii.hBmpItem := psd^.hStatusBitmap;
+ end;
+ end; //if
+ end;
+
+ // must be called after DecideMenuItemInfo()
+ procedure BuildMRU(pct: PSlotIPC; var mii: TMenuItemInfo; lParam: PEnumData);
+ begin
+ if pct^.MRU > 0 then
+ begin
+ Inc(lParam^.Self^.RecentCount);
+ // lParam^.Self == pointer to object data
+ InsertMenuitem(lParam^.Self^.hRecentMenu, $FFFFFFFF, True, mii);
+ end;
+ end;
+
+ procedure BuildContactTree(group: PGroupNode; lParam: PEnumData);
+ label
+ grouploop;
+ var
+ pct: PSlotIPC;
+ pg, px: PGroupNode;
+ str: TStrTokRec;
+ sz: PChar;
+ Hash: Cardinal;
+ Depth: Cardinal;
+ mii: TMenuItemInfo;
+ begin
+ // set up the menu item
+ mii.cbSize := sizeof(TMenuItemInfo);
+ mii.fMask := MIIM_ID or MIIM_TYPE or MIIM_DATA;
+ // set up the scanner
+ str.szSet := ['\'];
+ str.bSetTerminator := False;
+ // go thru all the contacts
+ pct := lParam^.ipch^.ContactsBegin;
+ while (pct <> nil) and (pct^.cbSize=sizeof(TSlotIPC)) and (pct^.fType=REQUEST_CONTACTS) do
+ begin
+ if pct^.hGroup <> 0 then
+ begin
+ // at the end of the slot header is the contact's display name
+ // and after a double NULL char there is the group string, which has the full path of the group
+ // this must be tokenised at '\' and we must walk the in memory group tree til we find our group
+ // this is faster than the old version since we only ever walk one or at most two levels of the tree
+ // per tokenised section, and it doesn't matter if two levels use the same group name (which is valid)
+ // as the tokens processed is equatable to depth of the tree
+ str.szStr := PChar(Integer(pct)+sizeof(TSlotIPC)+pct^.cbStrSection+1);
+ sz := StrTok(str);
+ // restore the root
+ pg := group;
+ Depth := 0;
+ while sz <> nil do
+ begin
+ Hash := StrHash(sz);
+ // find this node within
+ while pg <> nil do
+ begin
+ // does this node have the right hash and the right depth?
+ if (Hash = pg^.Hash) and (Depth = pg^.Depth) then Break;
+ // each node may have a left pointer going to a sub tree
+ // the path syntax doesn't know if a group is a group at the same level
+ // or a nested one, which means the search node can be anywhere
+ px := pg^.Left;
+ if px <> nil then
+ begin
+ // keep searching this level
+ while px <> nil do
+ begin
+ if (hash = px^.Hash) and (Depth = px^.Depth) then
+ begin
+ // found the node we're looking for at the next level to pg, px is now pq for next time
+ pg := px;
+ goto grouploop;
+ end; //if
+ px := px^.Right;
+ end; //if
+ end; //if
+ pg := pg^.Right;
+ end; //while
+ grouploop:
+ inc (Depth);
+ // process next token
+ sz := StrTok(str);
+ end; //while
+ // tokenisation finished, if pg <> nil then the group is found
+ if pg <> nil then
+ begin
+ DecideMenuItemInfo(pct, nil, mii, lParam);
+ BuildMRU(pct, mii, lParam);
+ InsertMenuitem(pg^.hMenu, $FFFFFFFF,True, mii);
+ Inc(pg^.dwItems);
+ end;
+ end; //if
+ pct := pct^.Next;
+ end; //while
+ end;
+
+ procedure BuildMenuGroupTree(p: PGroupNode; lParam: PEnumData; hLastMenu: HMENU);
+ var
+ mii: TMenuItemInfo;
+ begin
+ mii.cbSize := sizeof(TMenuItemInfo);
+ mii.fMask := MIIM_ID or MIIM_DATA or MIIM_TYPE or MIIM_SUBMENU;
+ // go thru each group and create a menu for it adding submenus too.
+ while p <> nil do
+ begin
+ mii.hSubMenu := CreatePopupMenu();
+ if p^.Left <> nil then BuildMenuGroupTree(p^.Left, lParam, mii.hSubMenu);
+ p^.hMenu := mii.hSubMenu;
+ DecideMenuItemInfo(nil, P, mii, lParam);
+ InsertMenuItem(hLastMenu, $FFFFFFFF, True, mii);
+ p := p^.Right;
+ end; //while
+ end;
+
+ { this callback is triggered by the menu code and IPC is already taking place,
+ just the transfer type+data needs to be setup }
+ function ClearMRUIPC(
+ pipch: PHeaderIPC; // IPC header info, already mapped
+ hWorkThreadEvent: THandle; // event object being waited on on miranda thread
+ hAckEvent: THandle; // ack event object that has been created
+ psd: PMenuDrawInfo // command/draw info
+ ): Integer; stdcall;
+ begin
+ Result := S_OK;
+ ipcPrepareRequests(IPC_PACKET_SIZE, pipch, REQUEST_CLEARMRU);
+ ipcSendRequest(hWorkThreadEvent, hAckEvent, pipch, 100) ;
+ end;
+
+ procedure RemoveCheckmarkSpace(hMenu: HMENU);
+ const
+ MIM_STYLE = $00000010;
+ MNS_CHECKORBMP = $4000000;
+ type
+ TMENUINFO = record
+ cbSize: DWORD;
+ fMask: DWORD;
+ dwStyle: DWORD;
+ cyMax: LongInt;
+ hbrBack: THandle;
+ dwContextHelpID: DWORD;
+ dwMenuData: Pointer;
+ end;
+ var
+ SetMenuInfo: function(hMenu: HMENU; var mi: TMenuInfo): Boolean; stdcall;
+ mi: TMENUINFO;
+ begin
+ if not VistaOrLater then Exit;
+ SetMenuInfo := GetProcAddress(GetModuleHandle('user32'), 'SetMenuInfo');
+ if @SetMenuInfo = nil then Exit;
+ mi.cbSize := sizeof(mi);
+ mi.fMask := MIM_STYLE;
+ mi.dwStyle := MNS_CHECKORBMP;
+ SetMenuInfo(hMenu, mi);
+ end;
+
+ procedure BuildMenus(lParam: PEnumData);
+ {$define SHL_IDC}
+ {$define SHL_KEYS}
+ {$include shlc.inc}
+ {$undef SHL_KEYS}
+ {$undef SHL_IDC}
+ var
+ hBaseMenu: HMENU;
+ hGroupMenu: HMENU;
+ pg: PSlotIPC;
+ szProf: PChar;
+ mii: TMenuItemInfo;
+ j: TGroupNodeList;
+ p, q: PGroupNode;
+ Depth, Hash: Cardinal;
+ Token: PChar;
+ tk: TStrTokRec;
+ szBuf: PChar;
+ hDllHeap: THandle;
+ psd: PMenuDrawInfo;
+ c: Cardinal;
+ pp: ^TSlotProtoIconsArray;
+ begin
+ ZeroMemory(@mii, sizeof(mii));
+ hDllHeap := lParam^.Self^.hDllHeap;
+ hBaseMenu := lParam^.Self^.hRootMenu;
+ // build an in memory tree of the groups
+ pg := lParam^.ipch^.GroupsBegin;
+ tk.szSet := ['\'];
+ tk.bSetTerminator := False;
+ j.First := nil;
+ j.Last := nil;
+ while pg <> nil do
+ begin
+ if (pg^.cbSize <> sizeof(TSlotIPC)) or (pg^.fType <> REQUEST_GROUPS) then Break;
+ Depth := 0;
+ p := j.First; // start at root again
+ // get the group
+ Integer(tk.szStr) := (Integer(pg) + sizeof(TSlotIPC));
+ // find each word between \ and create sub groups if needed.
+ Token := StrTok(tk);
+ while Token <> nil do
+ begin
+ Hash := StrHash(Token);
+ // if the (sub)group doesn't exist, create it.
+ q := FindGroupNode(p, Hash, Depth);
+ if q = nil then
+ begin
+ q := AllocGroupNode(@j, p, Depth);
+ q^.Depth := Depth;
+ // this is the hash of this group node, but it can be anywhere
+ // i.e. Foo\Foo this is because each node has a different depth
+ // trouble is contacts don't come with depths!
+ q^.Hash := Hash;
+ // don't assume that pg^.hGroup's hash is valid for this token
+ // since it maybe Miranda\Blah\Blah and we have created the first node
+ // which maybe Miranda, thus giving the wrong hash
+ // since "Miranda" can be a group of it's own and a full path
+ q^.cchGroup := lstrlen(Token);
+ q^.szGroup := HeapAlloc(hDllHeap, 0, q^.cchGroup+1);
+ strcpy(q^.szGroup, Token);
+ q^.dwItems := 0;
+ end;
+ p := q;
+ Inc(Depth);
+ Token := StrTok(tk);
+ end; //while
+ pg := pg^.Next;
+ end; // while
+ // build the menus inserting into hGroupMenu which will be a submenu of
+ // the instance menu item. e.g. Miranda -> [Groups ->] contacts
+ hGroupMenu := CreatePopupMenu();
+
+ // allocate MRU menu, this will be associated with the higher up menu
+ // so doesn't need to be freed (unless theres no MRUs items attached)
+ // This menu is per process but the handle is stored globally (like a stack)
+ lParam^.Self^.hRecentMenu := CreatePopupMenu();
+ lParam^.Self^.RecentCount := 0;
+ // create group menus only if they exist!
+ if lParam^.ipch^.GroupsBegin <> nil then
+ begin
+ BuildMenuGroupTree(j.First, lParam, hGroupMenu);
+ // add contacts that have a group somewhere
+ BuildContactTree(j.First, lParam);
+ end;
+ //
+ mii.cbSize := sizeof(TMenuItemInfo);
+ mii.fMask := MIIM_ID or MIIM_TYPE or MIIM_DATA;
+ // add all the contacts that have no group (which maybe all of them)
+ pg := lParam^.ipch^.ContactsBegin;
+ while pg <> nil do
+ begin
+ if (pg^.cbSize <> sizeof(TSlotIPC)) or (pg^.fType <> REQUEST_CONTACTS) then Break;
+ if pg^.hGroup = 0 then
+ begin
+ DecideMenuItemInfo(pg, nil, mii, lParam);
+ BuildMRU(pg, mii, lParam);
+ InsertMenuItem(hGroupMenu, $FFFFFFFF, True, mii);
+ end; //if
+ pg := pg^.Next;
+ end; //while
+
+ // insert MRU menu as a submenu of the contact menu only if
+ // the MRU list has been created, the menu popup will be deleted by itself
+ if lParam^.Self^.RecentCount > 0 then
+ begin
+
+ // insert seperator and 'clear list' menu
+ mii.fType := MFT_SEPARATOR;
+ mii.fMask := MIIM_TYPE;
+ InsertMenuitem(lParam^.Self^.hRecentMenu, $FFFFFFFF, True, mii);
+
+ // insert 'clear MRU' item and setup callback
+ mii.fMask := MIIM_TYPE or MIIM_ID or MIIM_DATA;
+ mii.wID := lParam^.idCmdFirst;
+ Inc(lParam^.idCmdFirst);
+ mii.fType := MFT_STRING;
+ mii.dwTypeData := lParam^.ipch^.ClearEntries; // "Clear entries"
+ //allocate menu substructure
+ psd := HeapAlloc(hDllHeap, 0, sizeof(TMenuDrawInfo));
+ psd^.fTypes := [dtCommand];
+ psd^.MenuCommandCallback := @ClearMRUIPC;
+ psd^.wID := mii.wID;
+ // this is needed because there is a clear list command per each process.
+ psd^.pid := lParam^.pid;
+ mii.dwItemData := Integer(psd);
+ InsertMenuitem(lParam^.Self^.hRecentMenu, $FFFFFFFF, True, mii);
+
+ // insert MRU submenu into group menu (with) ownerdraw support as needed
+ psd := HeapAlloc(hDllHeap, 0, sizeof(TMenuDrawInfo));
+ psd^.szProfile := 'MRU';
+ psd^.fTypes := [dtGroup];
+ // the IPC string pointer wont be around forever, must make a copy
+ psd^.cch := strlen(lParam^.ipch^.MRUMenuName);
+ psd^.szText := HeapAlloc(hDllHeap, 0, psd^.cch+1);
+ lstrcpyn(psd^.szText, lParam^.ipch^.MRUMenuName, sizeof(lParam^.ipch^.MRUMenuName)-1);
+
+ mii.dwItemData := Integer(psd);
+ if (lParam^.bOwnerDrawSupported) and (lParam^.bShouldOwnerDraw) then
+ begin
+ mii.fType := MFT_OWNERDRAW;
+ Pointer(mii.dwTypeData) := psd;
+ end else
+ begin
+ mii.dwTypeData := lParam^.ipch^.MRUMenuName; // 'Recent';
+ end;
+ mii.wID := lParam^.idCmdFirst;
+ Inc(lParam^.idCmdFirst);
+ mii.fMask := MIIM_TYPE or MIIM_SUBMENU or MIIM_DATA or MIIM_ID;
+ mii.hSubMenu := lParam^.Self^.hRecentMenu;
+ InsertMenuItem(hGroupMenu, 0, True, mii);
+ end
+ else
+ begin
+ // no items were attached to the MRU, delete the MRU menu
+ DestroyMenu(lParam^.Self^.hRecentMenu);
+ lParam^.Self^.hRecentMenu := 0;
+ end;
+
+ // allocate display info/memory for "Miranda" string
+
+ mii.cbSize := sizeof(TMenuItemInfo);
+ mii.fMask := MIIM_ID or MIIM_DATA or MIIM_TYPE or MIIM_SUBMENU;
+ if VistaOrLater then
+ begin
+ mii.fMask := MIIM_ID or MIIM_DATA or MIIM_FTYPE or MIIM_SUBMENU or MIIM_STRING or MIIM_BITMAP;
+ end;
+ mii.hSubMenu := hGroupMenu;
+
+ // by default, the menu will have space for icons and checkmarks (on Vista+) and we don't need this
+ RemoveCheckmarkSpace(hGroupMenu);
+
+
+ psd := HeapAlloc(hDllHeap, 0, sizeof(TMenuDrawInfo));
+ psd^.cch := strlen(lParam^.ipch^.MirandaName);
+ psd^.szText := HeapAlloc(hDllHeap, 0, psd^.cch+1);
+ lstrcpyn(psd^.szText, lParam^.ipch^.MirandaName, sizeof(lParam^.ipch^.MirandaName)-1);
+ // there may not be a profile name
+ pg := lParam^.ipch^.DataPtr;
+ psd^.szProfile := nil;
+ if ((pg <> nil) and (pg^.Status = STATUS_PROFILENAME)) then
+ begin
+ psd^.szProfile := HeapAlloc(hDllHeap, 0, pg^.cbStrSection);
+ strcpy(psd^.szProfile, PChar(Integer(pg) + sizeof(TSlotIPC)));
+ end; //if
+ // owner draw menus need ID's
+ mii.wID := lParam^.idCmdFirst;
+ Inc(lParam^.idCmdFirst);
+ psd^.fTypes := [dtEntry];
+ psd^.wID := mii.wID;
+ psd^.hContact := 0;
+ // get Miranda's icon or bitmap
+ c := lParam^.Self^.protoIconsCount;
+ pp := lParam^.Self^.protoIcons;
+ while c > 0 do
+ begin
+ dec(c);
+ if (pp[c].pid = lParam^.pid) and (pp[c].hProto = 0) then
+ begin
+ // either of these can be 0
+ psd^.hStatusIcon := pp[c].hIcons[0];
+ mii.hBmpItem := pp[c].hBitmaps[0];
+ break;
+ end; //if
+ end; //while
+ mii.dwItemData := Integer(psd);
+ if ((lParam^.bOwnerDrawSupported) and (lParam^.bShouldOwnerDraw)) then
+ begin
+ mii.fType := MFT_OWNERDRAW;
+ Pointer(mii.dwTypeData) := psd;
+ end else begin
+ mii.fType := MFT_STRING;
+ mii.dwTypeData := lParam^.ipch^.MirandaName;
+ mii.cch := sizeof(lParam^.ipch^.MirandaName)-1;
+ end;
+ // add it all
+ InsertMenuItem(hBaseMenu, 0, True, mii);
+ // free the group tree
+ FreeGroupTreeAndEmptyGroups(hGroupMenu, nil, j.First);
+ end;
+
+ procedure BuildSkinIcons(lParam: PEnumData);
+ var
+ pct: PSlotIPC;
+ p, d: PSlotProtoIcons;
+ Self: PShlComRec;
+ j: Cardinal;
+ imageFactory: PImageFactory_Interface;
+ begin
+ pct := lParam^.ipch^.NewIconsBegin;
+ self := lParam^.Self;
+ while (pct <> nil) do
+ begin
+ if (pct^.cbSize <> sizeof(TSlotIPC)) or (pct^.fType <> REQUEST_NEWICONS) then Break;
+ Integer(p) := Integer(pct) + sizeof(TSlotIPC);
+ ReAllocMem(self^.protoIcons, (self^.protoIconsCount+1)*sizeof(TSlotProtoIcons));
+ d := @self^.protoIcons[self^.protoIconsCount];
+ CopyMemory(d,p,sizeof(TSlotProtoIcons));
+
+ {
+ If using Vista (or later), clone all the icons into bitmaps and keep these around,
+ if using anything older, just use the default code, the bitmaps (and or icons) will be freed
+ with the shell object.
+ }
+
+ imageFactory := nil;
+
+ for j := 0 to 9 do
+ begin
+ if imageFactory = nil then imageFactory := ARGB_GetWorker();
+ if VistaOrLater then
+ begin
+ d^.hBitmaps[j] := ARGB_BitmapFromIcon(imageFactory, self^.hMemDC, p^.hIcons[j] );
+ d^.hIcons[j] := 0;
+ end else
+ begin
+ d^.hBitmaps[j] := 0;
+ d^.hIcons[j] := CopyIcon(p^.hIcons[j]);
+ end;
+ end;
+
+ if imageFactory <> nil then
+ begin
+ imageFactory^.ptrVTable^.Release(imageFactory);
+ imageFactory := nil;
+ end;
+
+ inc(self^.protoIconsCount);
+ pct := pct^.Next;
+ end;
+ end;
+
+ function ProcessRequest(hwnd: HWND; lParam: PEnumData): BOOL; stdcall;
+ var
+ pid: Integer;
+ hMirandaWorkEvent: THandle;
+ replyBits: Integer;
+ hScreenDC: THandle;
+ szBuf: array[0..MAX_PATH] of Char;
+ begin
+ Result := True;
+ pid := 0;
+ GetWindowThreadProcessId(hwnd, @pid);
+ If pid <> 0 then
+ begin
+ // old system would get a window's pid and the module handle that created it
+ // and try to OpenEvent() a event object name to it (prefixed with a string)
+ // this was fine for most Oses (not the best way) but now actually compares
+ // the class string (a bit slower) but should get rid of those bugs finally.
+ hMirandaWorkEvent := OpenEvent(EVENT_ALL_ACCESS, False, PChar(CreateProcessUID(pid)));
+ if (hMirandaWorkEvent <> 0) then
+ begin
+ GetClassName(hwnd, szBuf, sizeof(szBuf));
+ if lstrcmp(szBuf, MIRANDANAME) <> 0 then
+ begin
+ // opened but not valid.
+ CloseHandle(hMirandaWorkEvent); Exit;
+ end; //if
+ end; //if
+ { If the event object exists, then a shlext.dll running in the instance must of created it. }
+ If hMirandaWorkEvent <> 0 then
+ begin
+ { prep the request }
+ ipcPrepareRequests(IPC_PACKET_SIZE, lParam^.ipch, REQUEST_ICONS or REQUEST_GROUPS or REQUEST_CONTACTS or REQUEST_NEWICONS);
+ // slots will be in the order of icon data, groups then contacts, the first
+ // slot will contain the profile name
+ replyBits := ipcSendRequest(hMirandaWorkEvent, lParam^.hWaitFor, lParam^.ipch, 1000);
+ { replyBits will be REPLY_FAIL if the wait timed out, or it'll be the request
+ bits as sent or a series of *_NOTIMPL bits where the request bit were, if there are no
+ contacts to speak of, then don't bother showing this instance of Miranda }
+ if (replyBits <> REPLY_FAIL) and (lParam^.ipch^.ContactsBegin <> nil) then
+ begin
+ // load the address again, the server side will always overwrite it
+ lParam^.ipch^.pClientBaseAddress := lParam^.ipch;
+ // fixup all the pointers to be relative to the memory map
+ // the base pointer of the client side version of the mapped file
+ ipcFixupAddresses(False, lParam^.ipch);
+ // store the PID used to create the work event object
+ // that got replied to -- this is needed since each contact
+ // on the final menu maybe on a different instance and another OpenEvent() will be needed.
+ lParam^.pid := pid;
+ // check out the user options from the server
+ lParam^.bShouldOwnerDraw := (lParam^.ipch^.dwFlags and HIPC_NOICONS) = 0;
+ // process the icons
+ BuildSkinIcons(lParam);
+ // process other replies
+ BuildMenus(lParam);
+ end;
+ { close the work object }
+ CloseHandle(hMirandaWorkEvent);
+ end; //if
+ end; //if
+ end;
+
+ function TShlComRec_QueryInterface(Self: PCommon_Interface;
+ const IID: TIID; var Obj): HResult; stdcall;
+ begin
+ Pointer(Obj) := nil;
+ { IShellExtInit is given when the TShlRec is created }
+ if IsEqualIID(IID, IID_IContextMenu)
+ or IsEqualIID(IID, IID_IContextMenu2)
+ or IsEqualIID(IID, IID_IContextMenu3) then
+ begin
+ with Self^.ptrInstance^ do
+ begin
+ Pointer(Obj) := @ContextMenu3_Interface;
+ Inc(RefCount);
+ end; {with}
+ Result := S_OK;
+ end else begin
+ // under XP, it may ask for IShellExtInit again, this fixes the -double- click to see menus issue
+ // which was really just the object not being created
+ if IsEqualIID(IID, IID_IShellExtInit) then
+ begin
+ with Self^.ptrInstance^ do
+ begin
+ Pointer(Obj) := @ShellExtInit_Interface;
+ Inc(RefCount);
+ end; //if
+ Result := S_OK;
+ end else begin
+ Result := CLASS_E_CLASSNOTAVAILABLE;
+ end; //if
+ end; //if
+ end;
+
+ function TShlComRec_AddRef(Self: PCommon_Interface): LongInt; stdcall;
+ begin
+ with Self^.ptrInstance^ do
+ begin
+ Inc(RefCount);
+ Result := RefCount;
+ end; {with}
+ end;
+
+ function TShlComRec_Release(Self: PCommon_Interface): LongInt; stdcall;
+ var
+ j, c: Cardinal;
+ begin
+ with Self^.ptrInstance^ do
+ begin
+ Dec(RefCount);
+ Result := RefCount;
+ If RefCount = 0 then
+ begin
+ // time to go byebye.
+ with Self^.ptrInstance^ do
+ begin
+ // Note MRU menu is associated with a window (indirectly) so windows will free it.
+ // free icons!
+ if protoIcons <> nil then
+ begin
+ c := protoIconsCount;
+ while c > 0 do
+ begin
+ dec(c);
+ for j := 0 to 9 do
+ begin
+ with protoIcons[c] do
+ begin
+ if hIcons[j] <> 0 then DestroyIcon(hIcons[j]);
+ if hBitmaps[j] <> 0 then DeleteObject(hBitmaps[j]);
+ end;
+ end;
+ end;
+ FreeMem(protoIcons); protoIcons := nil;
+ end; //if
+ // free IDataObject reference if pointer exists
+ if pDataObject <> nil then
+ begin
+ pDataObject^.ptrvTable^.Release(pDataObject);
+ end; //if
+ pDataObject := nil;
+ // free the heap and any memory allocated on it
+ HeapDestroy(hDllHeap);
+ // destroy the DC
+ if hMemDC <> 0 then DeleteDC(hMemDC);
+ end; //with
+ // free the instance (class record) created
+ Dispose(Self^.ptrInstance);
+ Dec(dllpublic.ObjectCount);
+ end; {if}
+ end; {with}
+ end;
+
+ function TShlComRec_Initialise(Self: PContextMenu3_Interface;
+ pidLFolder: Pointer; DObj: PDataObject_Interface; hKeyProdID: HKEY): HResult; stdcall;
+ begin
+ // DObj is a pointer to an instance of IDataObject which is a pointer itself
+ // it contains a pointer to a function table containing the function pointer
+ // address of GetData() - the instance data has to be passed explicitly since
+ // all compiler magic has gone.
+ with Self^.ptrInstance^ do
+ begin
+ if DObj <> nil then
+ begin
+ Result := S_OK;
+ // if an instance already exists, free it.
+ if pDataObject <> nil then pDataObject^.ptrVTable^.Release(pDataObject);
+ // store the new one and AddRef() it
+ pDataObject := DObj;
+ pDataObject^.ptrVTable^.AddRef(pDataObject);
+ end else begin
+ Result := E_INVALIDARG;
+ end; //if
+ end; //if
+ end;
+
+ function MAKE_HRESULT(Severity, Facility, Code: Integer): HResult;
+ {$ifdef FPC}
+ inline;
+ {$endif}
+ begin
+ Result := (Severity shl 31) or (Facility shl 16) or Code;
+ end;
+
+ function TShlComRec_QueryContextMenu(Self: PContextMenu3_Interface;
+ Menu: HMENU; indexMenu, idCmdFirst, idCmdLast, uFlags: UINT): HResult; stdcall;
+ type
+ TDllVersionInfo = record
+ cbSize: DWORD;
+ dwMajorVersion: DWORD;
+ dwMinorVersion: DWORD;
+ dwBuildNumber: DWORD;
+ dwPlatformID: DWORD;
+ end;
+ TDllGetVersionProc = function(var dv: TDllVersionInfo): HResult; stdcall;
+ var
+ hShellInst: THandle;
+ bMF_OWNERDRAW: Boolean;
+ DllGetVersionProc: TDllGetVersionProc;
+ dvi: TDllVersionInfo;
+ ed: TEnumData;
+ hMap: THandle;
+ pipch: PHeaderIPC;
+ begin
+ Result := 0;
+ if ((LOWORD(uFlags) and CMF_VERBSONLY) <> CMF_VERBSONLY) and ((LOWORD(uFlags) and CMF_DEFAULTONLY) <> CMF_DEFAULTONLY) then
+ begin
+ bMF_OWNERDRAW := False;
+ // get the shell version
+ hShellInst := LoadLibrary('shell32.dll');
+ if hShellInst <> 0 then
+ begin
+ DllGetVersionProc := GetProcAddress(hShellInst, 'DllGetVersion');
+ if @DllGetVersionProc <> nil then
+ begin
+ dvi.cbSize := sizeof(TDllVersionInfo);
+ if DllGetVersionProc(dvi) >= 0 then
+ begin
+ // it's at least 4.00
+ bMF_OWNERDRAW := (dvi.dwMajorVersion > 4) or (dvi.dwMinorVersion >= 71);
+ end; //if
+ end; //if
+ FreeLibrary(hShellInst);
+ end; //if
+
+ // if we're using Vista (or later), then the ownerdraw code will be disabled, because the system draws the icons.
+ if VistaOrLater then bMF_OWNERDRAW := False;
+
+ hMap := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, IPC_PACKET_SIZE, IPC_PACKET_NAME);
+ If (hMap <> 0) and (GetLastError <> ERROR_ALREADY_EXISTS) then
+ begin
+ { map the memory to this address space }
+ pipch := MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
+ If pipch <> nil then
+ begin
+ { let the callback have instance vars }
+ ed.Self := Self^.ptrInstance;
+ // not used 'ere
+ ed.Self^.hRootMenu := Menu;
+ // store the first ID to offset with index for InvokeCommand()
+ Self^.ptrInstance^.idCmdFirst := idCmdFirst;
+ // store the starting index to offset
+ Result := idCmdFirst;
+ ed.bOwnerDrawSupported := bMF_OWNERDRAW;
+ ed.bShouldOwnerDraw := True;
+ ed.idCmdFirst := idCmdFirst;
+ ed.ipch := pipch;
+ { allocate a wait object so the ST can signal us, it can't be anon
+ since it has to used by OpenEvent() }
+ strcpy(@pipch^.SignalEventName, PChar(CreateUID()));
+ { create the wait wait-for-wait object }
+ ed.hWaitFor := CreateEvent(nil, False, False, pipch^.SignalEventName);
+ If ed.hWaitFor <> 0 then
+ begin
+ { enumerate all the top level windows to find all loaded MIRANDANAME
+ classes -- }
+ EnumWindows(@ProcessRequest, lParam(@ed));
+ { close the wait-for-reply object }
+ CloseHandle(ed.hWaitFor);
+ end;
+ { unmap the memory from this address space }
+ UnmapViewOfFile(pipch);
+ end; {if}
+ { close the mapping }
+ CloseHandle(hMap);
+ // use the MSDN recommended way, thou there ain't much difference
+ Result := MAKE_HRESULT(0, 0, (ed.idCmdFirst - Result) + 1);
+ end else begin
+ // the mapping file already exists, which is not good!
+ end;
+ end else begin
+ // same as giving a SEVERITY_SUCCESS, FACILITY_NULL, since that
+ // just clears the higher bits, which is done anyway
+ Result := MAKE_HRESULT(0, 0, 1);
+ end; //if
+ end;
+
+ function TShlComRec_GetCommandString(Self: PContextMenu3_Interface;
+ idCmd, uType: UINT; pwReserved: PUINT; pszName: PChar; cchMax: UINT): HResult; stdcall;
+ begin
+ Result := E_NOTIMPL;
+ end;
+
+ function ipcGetFiles(pipch: PHeaderIPC; pDataObject: PDataObject_Interface; const hContact: THandle): Integer;
+ type
+ TDragQueryFile = function(hDrop: THandle; fileIndex: Integer; FileName: PChar; cbSize: Integer): Integer; stdcall;
+ var
+ fet: TFormatEtc;
+ stgm: TStgMedium;
+ pct: PSlotIPC;
+ iFile: Cardinal;
+ iFileMax: Cardinal;
+ hShell: THandle;
+ DragQueryFile: TDragQueryFile;
+ cbSize: Integer;
+ hDrop: THandle;
+ begin
+ Result := E_INVALIDARG;
+ hShell := LoadLibrary('shell32.dll');
+ if hShell <> 0 then
+ begin
+ DragQueryFile := GetProcAddress(hShell, 'DragQueryFileA');
+ if @DragQueryFile <> nil then
+ begin
+ fet.cfFormat := CF_HDROP;
+ fet.ptd := nil;
+ fet.dwAspect := DVASPECT_CONTENT;
+ fet.lindex := -1;
+ fet.tymed := TYMED_HGLOBAL;
+ Result := pDataObject^.ptrVTable^.GetData(pDataObject, fet, stgm);
+ if Result = S_OK then
+ begin
+ // FIX, actually lock the global object and get a pointer
+ Pointer(hDrop) := GlobalLock(stgm.hGlobal);
+ if hDrop <> 0 then
+ begin
+ // get the maximum number of files
+ iFileMax := DragQueryFile(stgm.hGlobal, $FFFFFFFF, nil, 0);
+ iFile := 0;
+ while iFile < iFileMax do
+ begin
+ // get the size of the file path
+ cbSize := DragQueryFile(stgm.hGlobal, iFile, nil, 0);
+ // get the buffer
+ pct := ipcAlloc(pipch, cbSize + 1); // including null term
+ // allocated?
+ if pct = nil then Break;
+ // store the hContact
+ pct^.hContact := hContact;
+ // copy it to the buffer
+ DragQueryFile(stgm.hGlobal, iFile, PChar(Integer(pct)+sizeof(TSlotIPC)), pct^.cbStrSection);
+ // next file
+ Inc(iFile);
+ end; //while
+ // store the number of files
+ pipch^.Slots := iFile;
+ GlobalUnlock(stgm.hGlobal);
+ end; //if hDrop check
+ // release the mediumn the lock may of failed
+ ReleaseStgMedium(stgm);
+ end; //if
+ end; //if
+ // free the dll
+ FreeLibrary(hShell);
+ end; //if
+ end;
+
+ function RequestTransfer(Self: PShlComRec; idxCmd: Integer): Integer;
+ var
+ hMap: THandle;
+ pipch: PHeaderIPC;
+ mii: TMenuItemInfo;
+ hTransfer: THandle;
+ psd: PMenuDrawInfo;
+ hReply: THandle;
+ replyBits: Integer;
+ begin
+ Result := E_INVALIDARG;
+ // get the contact information
+ mii.cbSize := sizeof(TMenuItemInfo);
+ mii.fMask := MIIM_ID or MIIM_DATA;
+ if GetMenuItemInfo(Self^.hRootMenu, Self^.idCmdFirst + idxCmd, False, mii) then
+ begin
+ // get the pointer
+ Integer(psd) := mii.dwItemData;
+ // the ID stored in the item pointer and the ID for the menu must match
+ if (psd = nil) or (psd^.wID <> mii.wID) then
+ begin
+ //MessageBox(0,'ptr assocated with menu is NULL','',MB_OK);
+ Exit;
+ end; //if
+ end else begin
+ //MessageBox(0,'GetMenuItemInfo failed?','',MB_OK);
+ // couldn't get the info, can't start the transfer
+ Result := E_INVALIDARG; Exit;
+ end; //if
+ // is there an IDataObject instance?
+ if Self^.pDataObject <> nil then
+ begin
+ // OpenEvent() the work object to see if the instance is still around
+ hTransfer := OpenEvent(EVENT_ALL_ACCESS, False, PChar(CreateProcessUID(psd^.pid)));
+ if hTransfer <> 0 then
+ begin
+ // map the ipc file again
+ hMap := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, IPC_PACKET_SIZE, IPC_PACKET_NAME);
+ if (hMap <> 0) and (GetLastError <> ERROR_ALREADY_EXISTS) then
+ begin
+ // map it to process
+ pipch := MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
+ if pipch <> nil then
+ begin
+ // create the name of the object to be signalled by the ST
+ strcpy(pipch^.SignalEventName, PChar(CreateUID()));
+ // create it
+ hReply := CreateEvent(nil, False, False, pipch^.SignalEventName);
+ if hReply <> 0 then
+ begin
+ if dtCommand in psd^.fTypes then
+ begin
+ if Assigned(psd^.MenuCommandCallback) then
+ Result := psd^.MenuCommandCallback(pipch, hTransfer, hReply, psd);
+ end
+ else
+ begin
+
+ // prepare the buffer
+ ipcPrepareRequests(IPC_PACKET_SIZE, pipch, REQUEST_XFRFILES);
+ // get all the files into the packet
+ if ipcGetFiles(pipch, Self^.pDataObject, psd^.hContact) = S_OK then
+ begin
+ // need to wait for the ST to open the mapping object
+ // since if we close it before it's opened it the data it
+ // has will be undefined
+ replyBits := ipcSendRequest(hTransfer, hReply, pipch, 200);
+ if replyBits <> REPLY_FAIL then
+ begin
+ // they got the files!
+ Result := S_OK;
+ end; //if
+ end;
+
+ end;
+ // close the work object name
+ CloseHandle(hReply);
+ end; //if
+ // unmap it from this process
+ UnmapViewOfFile(pipch);
+ end; //if
+ // close the map
+ CloseHandle(hMap);
+ end; //if
+ // close the handle to the ST object name
+ CloseHandle(hTransfer);
+ end; //if
+ end //if;
+ end;
+
+ function TShlComRec_InvokeCommand(Self: PContextMenu3_Interface;
+ var lpici: TCMInvokeCommandInfo): HResult; stdcall;
+ begin
+ Result := RequestTransfer(Self^.ptrInstance, LOWORD(Integer(lpici.lpVerb)));
+ end;
+
+ function TShlComRec_HandleMenuMsgs(Self: PContextMenu3_Interface;
+ uMsg: UINT; wParam: WPARAM; lParam: LPARAM; pResult: PLResult): HResult;
+ const
+ WM_DRAWITEM = $002B;
+ WM_MEASUREITEM = $002C;
+ var
+ dwi: PDrawItemStruct;
+ msi: PMeasureItemStruct;
+ psd: PMenuDrawInfo;
+ ncm: TNonClientMetrics;
+ hOldFont: THandle;
+ hFont: THandle;
+ tS: TSize;
+ dx: Integer;
+ hBr: HBRUSH;
+ icorc: TRect;
+ hMemDC: HDC;
+ begin
+ pResult^ := Integer(True);
+ if (uMsg = WM_DRAWITEM) and (wParam = 0) then
+ begin
+ // either a main sub menu, a group menu or a contact
+ dwi := PDrawItemStruct(lParam);
+ Integer(psd) := dwi^.itemData;
+ // don't fill
+ SetBkMode(dwi^.hDC, TRANSPARENT);
+ // where to draw the icon?
+ icorc.Left := 0;
+ // center it
+ with dwi^ do
+ icorc.Top := rcItem.Top + ((rcItem.Bottom - rcItem.Top) div 2) - (16 div 2);
+ icorc.Right := icorc.Left + 16;
+ icorc.Bottom := icorc.Top + 16;
+ // draw for groups
+ if (dtGroup in psd^.fTypes) or (dtEntry in psd^.fTypes) then
+ begin
+ hBr := GetSysColorBrush(COLOR_MENU);
+ FillRect(dwi^.hDC, dwi^.rcItem, hBr);
+ DeleteObject(hBr);
+ //
+ if (ODS_SELECTED and dwi^.itemState = ODS_SELECTED) then
+ begin
+ // only do this for entry menu types otherwise a black mask
+ // is drawn under groups
+ hBr := GetSysColorBrush(COLOR_HIGHLIGHT);
+ FillRect(dwi^.hDC, dwi^.rcItem, hBr);
+ DeleteObject(hBr);
+ SetTextColor(dwi^.hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
+ end; //if
+ // draw icon
+ with dwi^, icorc do
+ begin
+ if (ODS_SELECTED and dwi^.itemState) = ODS_SELECTED then
+ begin
+ hBr := GetSysColorBrush(COLOR_HIGHLIGHT);
+ end else begin
+ hBr := GetSysColorBrush(COLOR_MENU);
+ end; //if
+ DrawIconEx(hDC, Left+1, Top, psd^.hStatusIcon,
+ 16, 16, // width, height
+ 0, // step
+ hBr, // brush
+ DI_NORMAL);
+ DeleteObject(hBr);
+ end; //with
+ // draw the text
+ with dwi^ do
+ begin
+ Inc(rcItem.Left, ((rcItem.Bottom-rcItem.Top)-2));
+ DrawText(hDC, psd^.szText, psd^.cch, rcItem, DT_NOCLIP or DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER);
+ // draw the name of the database text if it's there
+ if psd^.szProfile <> nil then
+ begin
+ GetTextExtentPoint32(dwi^.hDC, psd^.szText, psd^.cch, tS);
+ Inc(rcItem.Left, tS.cx+8);
+ SetTextColor(hDC, GetSysColor(COLOR_GRAYTEXT));
+ DrawText(hDC, psd^.szProfile, lstrlen(psd^.szProfile), rcItem, DT_NOCLIP or DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER);
+ end; //if
+ end; //with
+ end else
+ begin
+ // it's a contact!
+ hBr := GetSysColorBrush(COLOR_MENU);
+ FillRect(dwi^.hDC, dwi^.rcItem, hBr);
+ DeleteObject(hBr);
+ if ODS_SELECTED and dwi^.itemState = ODS_SELECTED then
+ begin
+ hBr := GetSysColorBrush(COLOR_HIGHLIGHT);
+ FillRect(dwi^.hDC, dwi^.rcItem, hBr);
+ DeleteObject(hBr);
+ SetTextColor(dwi^.hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
+ end;
+ // draw icon
+ with dwi^, icorc do
+ begin
+ if (ODS_SELECTED and dwi^.itemState) = ODS_SELECTED then
+ begin
+ hBr := GetSysColorBrush(COLOR_HIGHLIGHT);
+ end else begin
+ hBr := GetSysColorBrush(COLOR_MENU);
+ end; //if
+ DrawIconEx(hDC, Left+2, Top, psd^.hStatusIcon,
+ 16, 16, // width, height
+ 0, // step
+ hBr, // brush
+ DI_NORMAL);
+ DeleteObject(hBr);
+ end; //with
+ // draw the text
+ with dwi^ do
+ begin
+ Inc(rcItem.Left, (rcItem.Bottom-rcItem.Top) + 1);
+ DrawText(hDC, psd^.szText, psd^.cch, rcItem, DT_NOCLIP or DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER);
+ end; //with
+ end; //if
+ end
+ else if (uMsg = WM_MEASUREITEM) then
+ begin
+ // don't check if it's really a menu
+ msi := PMeasureItemStruct(lParam);
+ Integer(psd) := msi^.itemData;
+ ncm.cbSize := sizeof(TNonClientMetrics);
+ SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @ncm, 0);
+ // create the font used in menus, this font should be cached somewhere really
+ {$IFDEF FPC}
+ hFont := CreateFontIndirect(@ncm.lfMenuFont);
+ {$ELSE}
+ hFont := CreateFontIndirect(ncm.lfMenuFont);
+ {$ENDIF}
+ hMemDC := Self^.ptrInstance^.hMemDC;
+ // select in the font
+ hOldFont := SelectObject(hMemDC, hFont);
+ // default to an icon
+ dx := 16;
+ // get the size 'n' account for the icon
+ GetTextExtentPoint32(hMemDC, psd^.szText, psd^.cch, tS);
+ Inc(dx, tS.cx);
+ // main menu item?
+ if psd^.szProfile <> nil then
+ begin
+ GetTextExtentPoint32(hMemDC, psd^.szProfile, lstrlen(psd^.szProfile), tS);
+ Inc(dx, tS.cx);
+ end;
+ // store it
+ msi^.itemWidth := dx + Integer(ncm.iMenuWidth);
+ msi^.itemHeight := Integer(ncm.iMenuHeight)+2;
+ if tS.cy > msi^.itemHeight then Inc(msi^.itemHeight, tS.cy - msi^.itemHeight);
+ // clean up
+ SelectObject(hMemDC, hOldFont);
+ DeleteObject(hFont);
+ end;
+ Result := S_OK;
+ end;
+
+ function TShlComRec_HandleMenuMsg(Self: PContextMenu3_Interface;
+ uMsg: UINT; wParam: WPARAM; lParam: LPARAM): HResult; stdcall;
+ var
+ Dummy: HResult;
+ begin
+ Result := TShlComRec_HandleMenuMsgs(Self, uMsg, wParam, lParam, @Dummy);
+ end;
+
+ function TShlComRec_HandleMenuMsg2(Self: PContextMenu3_Interface;
+ uMsg: UINT; wParam: WPARAM; lParam: LPARAM; plResult: Pointer{^LResult}): HResult; stdcall;
+ var
+ Dummy: HResult;
+ begin
+ // this will be null if a return value isn't needed.
+ if plResult = nil then plResult := @Dummy;
+ Result := TShlComRec_HandleMenuMsgs(Self, uMsg, wParam, lParam, plResult);
+ end;
+
+ function TShlComRec_Create: PShlComRec;
+ var
+ DC: HDC;
+ begin
+ New(Result);
+ { build all the function tables for interfaces }
+ with Result^.ShellExtInit_Interface do
+ begin
+ { this is only owned by us... }
+ ptrVTable := @vTable;
+ { IUnknown }
+ vTable.QueryInterface := @TShlComRec_QueryInterface;
+ vTable.AddRef := @TShlComRec_AddRef;
+ vTable.Release := @TShlComRec_Release;
+ { IShellExtInit }
+ vTable.Initialise := @TShlComRec_Initialise;
+ { instance of a TShlComRec }
+ ptrInstance := Result;
+ end;
+ with Result^.ContextMenu3_Interface do
+ begin
+ ptrVTable := @vTable;
+ { IUnknown }
+ vTable.QueryInterface := @TShlComRec_QueryInterface;
+ vTable.AddRef := @TShlComRec_AddRef;
+ vTable.Release := @TShlComRec_Release;
+ { IContextMenu }
+ vTable.QueryContextMenu := @TShlComRec_QueryContextMenu;
+ vTable.InvokeCommand := @TShlComRec_InvokeCommand;
+ vTable.GetCommandString := @TShlComRec_GetCommandString;
+ { IContextMenu2 }
+ vTable.HandleMenuMsg := @TShlComRec_HandleMenuMsg;
+ { IContextMenu3 }
+ vTable.HandleMenuMsg2 := @TShlComRec_HandleMenuMsg2;
+ { instance data }
+ ptrInstance := Result;
+ end;
+ { initalise variables }
+ Result^.RefCount := 1;
+ Result^.hDllHeap := HeapCreate(0, 0, 0);
+ Result^.hRootMenu := 0;
+ Result^.hRecentMenu := 0;
+ Result^.RecentCount := 0;
+ Result^.idCmdFirst := 0;
+ Result^.pDataObject := nil;
+ Result^.ProtoIcons := nil;
+ Result^.ProtoIconsCount := 0;
+ // create an inmemory DC
+ DC := GetDC(0);
+ Result^.hMemDC := CreateCompatibleDC(DC);
+ ReleaseDC(0,DC);
+ { keep count on the number of objects }
+ Inc(dllpublic.ObjectCount);
+ end;
+
+{ IClassFactory }
+
+type
+
+ PVTable_IClassFactory = ^TVTable_IClassFactory;
+ TVTable_IClassFactory = record
+ { IUnknown }
+ QueryInterface: Pointer;
+ AddRef: Pointer;
+ Release: Pointer;
+ { IClassFactory }
+ CreateInstance: Pointer;
+ LockServer: Pointer;
+ end;
+ PClassFactoryRec = ^TClassFactoryRec;
+ TClassFactoryRec = record
+ ptrVTable: PVTable_IClassFactory;
+ vTable: TVTable_IClassFactory;
+ {fields}
+ RefCount: LongInt;
+ end;
+
+ function TClassFactoryRec_QueryInterface(Self: PClassFactoryRec;
+ const IID: TIID; var Obj): HResult; stdcall;
+ begin
+ Pointer(Obj) := nil;
+ Result := E_NOTIMPL;
+ end;
+
+ function TClassFactoryRec_AddRef(Self: PClassFactoryRec): LongInt; stdcall;
+ begin
+ Inc(Self^.RefCount);
+ Result := Self^.RefCount;
+ end;
+
+ function TClassFactoryRec_Release(Self: PClassFactoryRec): LongInt; stdcall;
+ begin
+ Dec(Self^.RefCount);
+ Result := Self^.RefCount;
+ if Result = 0 then
+ begin
+ Dispose(Self);
+ Dec(dllpublic.FactoryCount);
+ end; {if}
+ end;
+
+ function TClassFactoryRec_CreateInstance(Self: PClassFactoryRec;
+ unkOuter: Pointer; const IID: TIID; var Obj): HResult; stdcall;
+ var
+ ShlComRec: PShlComRec;
+ begin
+ Pointer(Obj) := nil;
+ Result := CLASS_E_NOAGGREGATION;
+ if unkOuter = nil then
+ begin
+ { Before Vista, the system queried for a IShell interface then queried for a context menu, Vista now
+ queries for a context menu (or a shell menu) then QI()'s the other interface }
+ if IsEqualIID(IID, IID_IContextMenu) then
+ begin
+ Result := S_OK;
+ ShlComRec := TShlComRec_Create;
+ Pointer(Obj) := @ShlComRec^.ContextMenu3_Interface;
+ end;
+ if IsEqualIID(IID, IID_IShellExtInit) then
+ begin
+ Result := S_OK;
+ ShlComRec := TShlComRec_Create;
+ Pointer(Obj) := @ShlComRec^.ShellExtInit_Interface;
+ end; //if
+ end; //if
+ end;
+ function TClassFactoryRec_LockServer(Self: PClassFactoryRec; fLock: BOOL): HResult; stdcall;
+ begin
+ Result := E_NOTIMPL;
+ end;
+
+ function TClassFactoryRec_Create: PClassFactoryRec;
+ begin
+ New(Result);
+ Result^.ptrVTable := @Result^.vTable;
+ { IUnknown }
+ Result^.vTable.QueryInterface := @TClassFactoryRec_QueryInterface;
+ Result^.vTable.AddRef := @TClassFactoryRec_AddRef;
+ Result^.vTable.Release := @TClassFactoryRec_Release;
+ { IClassFactory }
+ Result^.vTable.CreateInstance := @TClassFactoryRec_CreateInstance;
+ Result^.vTable.LockServer := @TClassFactoryRec_LockServer;
+ { inital the variables }
+ Result^.RefCount := 1;
+ { count the number of factories }
+ Inc(dllpublic.FactoryCount);
+ end;
+
+ //
+ // IPC part
+ //
+
+
+ type
+ PFileList = ^TFileList;
+ TFileList = array[0..0] of PChar;
+ PAddArgList = ^TAddArgList;
+ TAddArgList = record
+ szFile: PChar; // file being processed
+ cch: Cardinal; // it's length (with space for NULL char)
+ count: Cardinal; // number we have so far
+ files: PFileList;
+ hContact: THandle;
+ hEvent: THandle;
+ end;
+
+ function AddToList(var args: TAddArgList): LongBool;
+ var
+ attr: Cardinal;
+ p: Pointer;
+ hFind: THandle;
+ fd: TWIN32FINDDATA;
+ szBuf: array[0..MAX_PATH] of Char;
+ szThis: PChar;
+ cchThis: Cardinal;
+ begin
+ Result := False;
+ attr := GetFileAttributes(args.szFile);
+ if (attr <> $FFFFFFFF) and ((attr and FILE_ATTRIBUTE_HIDDEN) = 0) then
+ begin
+ if args.count mod 10 = 5 then
+ begin
+ if CallService(MS_SYSTEM_TERMINATED,0,0) <> 0 then
+ begin
+ Result := True; Exit;
+ end; //if
+ end;
+ if attr and FILE_ATTRIBUTE_DIRECTORY <> 0 then
+ begin
+ // add the directory
+ strcpy(szBuf,args.szFile);
+ ReallocMem(args.files,(args.count+1)*sizeof(PChar));
+ GetMem(p,strlen(szBuf)+1);
+ strcpy(p,szBuf);
+ args.files^[args.count] := p;
+ inc(args.count);
+ // tack on ending search token
+ strcat(szBuf,'\*');
+ hFind := FindFirstFile(szBuf,fd);
+ while True do
+ begin
+ if fd.cFileName[0] <> '.' then
+ begin
+ strcpy(szBuf,args.szFile);
+ strcat(szBuf,'\');
+ strcat(szBuf,fd.cFileName);
+ // keep a copy of the current thing being processed
+ szThis := args.szFile; args.szFile := szBuf;
+ cchThis := args.cch; args.cch := strlen(szBuf)+1;
+ // recurse
+ Result := AddToList(args);
+ // restore
+ args.szFile := szThis;
+ args.cch := cchThis;
+ if Result then Break;
+ end; //if
+ if not FindNextFile(hFind,fd) then Break;
+ end; //while
+ FindClose(hFind);
+ end else begin
+ // add the file
+ ReallocMem(args.files,(args.count+1)*sizeof(PChar));
+ GetMem(p,args.cch);
+ strcpy(p,args.szFile);
+ args.files^[args.count] := p;
+ inc (args.count);
+ end; //if
+ end;
+ end;
+
+ procedure MainThreadIssueTransfer(p: PAddArgList); stdcall;
+ {$define SHL_IDC}
+ {$define SHL_KEYS}
+ {$include shlc.inc}
+ {$undef SHL_KEYS}
+ {$undef SHL_IDC}
+ begin
+ DBWriteContactSettingByte(p^.hContact, SHLExt_Name, SHLExt_MRU, 1);
+ CallService(MS_FILE_SENDSPECIFICFILES,p^.hContact,lParam(p^.files));
+ SetEvent(p^.hEvent);
+ end;
+
+ function IssueTransferThread(pipch: PHeaderIPC): Cardinal; stdcall;
+ var
+ szBuf: array[0..MAX_PATH] of Char;
+ pct: PSlotIPC;
+ args: TAddArgList;
+ bQuit: LongBool;
+ j,c: Cardinal;
+ p: Pointer;
+ hMainThread: THandle;
+ begin
+ CallService(MS_SYSTEM_THREAD_PUSH,0,0);
+ hMainThread := THandle(pipch^.Param);
+ GetCurrentDirectory(sizeof(szBuf),szBuf);
+ args.count := 0;
+ args.files := nil;
+ pct := pipch^.DataPtr;
+ bQuit := False;
+ while pct <> nil do
+ begin
+ if (pct^.cbSize <> sizeof(TSlotIPC)) then break;
+ args.szFile := PChar(Integer(pct) + sizeof(TSlotIPC));
+ args.hContact := pct^.hContact;
+ args.cch := pct^.cbStrSection+1;
+ bQuit := AddToList(args);
+ if bQuit then Break;
+ pct := pct^.next;
+ end; //while
+ if args.files <> nil then
+ begin
+ ReallocMem(args.files,(args.count+1)*sizeof(PChar));
+ args.files^[args.count] := nil;
+ inc (args.count);
+ if (not bQuit) then
+ begin
+ args.hEvent := CreateEvent(nil, True, False, nil);
+ QueueUserAPC(@MainThreadIssueTransfer,hMainThread,DWORD(@args));
+ while True do
+ begin
+ if WaitForSingleObjectEx(args.hEvent,INFINITE,True) <> WAIT_IO_COMPLETION then Break;
+ end;
+ CloseHandle(args.hEvent);
+ end; //if
+ c := args.count-1;
+ for j := 0 to c do
+ begin
+ p := args.files^[j];
+ if p <> nil then FreeMem(p);
+ end;
+ FreeMem(args.files);
+ end;
+ SetCurrentDirectory(szBuf);
+ FreeMem(pipch);
+ CloseHandle(hMainThread);
+ CallService(MS_SYSTEM_THREAD_POP,0,0);
+ ExitThread(0);
+ end;
+
+type
+
+ PSlotInfo = ^TSlotInfo;
+ TSlotInfo = record
+ hContact: THandle;
+ hProto: Cardinal;
+ dwStatus: Integer; // will be aligned anyway
+ end;
+ TSlotArray = array[0..$FFFFFF] of TSlotInfo;
+ PSlotArray = ^TSlotArray;
+
+ function SortContact(var Item1, Item2: TSlotInfo): Integer; stdcall;
+ begin
+ Result := PluginLink^.CallService(MS_CLIST_CONTACTSCOMPARE, item1.hContact, item2.hContact);
+ end;
+
+ // from FP FCL
+
+ procedure QuickSort (FList: PSlotArray; L, R: LongInt);
+ var
+ I, J: LongInt;
+ P, Q: TSlotInfo;
+ begin
+ repeat
+ I := L;
+ J := R;
+ P := FList^[ (L+R) div 2 ];
+ repeat
+ while SortContact(P, FList^[i]) > 0 do Inc(i);
+ while SortContact(P, FList^[j]) < 0 do Dec(j);
+ if I <= J then
+ begin
+ Q := FList^[I];
+ FList^[I] := FList^[J];
+ FList^[J] := Q;
+ Inc(I);
+ Dec(J);
+ end; //if
+ until I > J;
+ if L < J then QuickSort (FList, L, J);
+ L := I;
+ until I >= R;
+ end;
+
+ {$define SHL_KEYS}
+ {$include shlc.inc}
+ {$undef SHL_KEYS}
+
+ procedure ipcGetSkinIcons(ipch: PHeaderIPC);
+ var
+ protoCount: Integer;
+ pp: ^PPROTOCOLDESCRIPTOR;
+ spi: TSlotProtoIcons;
+ j: Cardinal;
+ pct: PSlotIPC;
+ szTmp: array[0..63] of Char;
+ dwCaps: Cardinal;
+ begin
+ if (CallService(MS_PROTO_ENUMPROTOCOLS,wParam(@protoCount),lParam(@pp)) = 0) and (protoCount <> 0) then
+ begin
+ spi.pid := GetCurrentProcessId();
+ while protoCount > 0 do
+ begin
+ if (pp^.type_ = PROTOTYPE_PROTOCOL) then
+ begin
+ strcpy(szTmp,pp^.szName);
+ strcat(szTmp,PS_GETCAPS);
+ dwCaps := CallService(szTmp,PFLAGNUM_1,0);
+ if (dwCaps and PF1_FILESEND) <> 0 then
+ begin
+ pct := ipcAlloc(ipch,sizeof(TSlotProtoIcons));
+ if pct <> nil then
+ begin
+ // capture all the icons!
+ spi.hProto := StrHash(pp^.szName);
+ for j := 0 to 9 do
+ begin
+ spi.hIcons[j] := LoadSkinnedProtoIcon(pp^.szName,ID_STATUS_OFFLINE+j);
+ end; //for
+ pct^.fType := REQUEST_NEWICONS;
+ CopyMemory(Pointer(Integer(pct)+sizeof(TSlotIPC)),@spi,sizeof(TSlotProtoIcons));
+ if ipch^.NewIconsBegin = nil then ipch^.NewIconsBegin := pct;
+ end; //if
+ end; //if
+ end; //if
+ inc (pp);
+ dec (protoCount);
+ end; //while
+ end; //if
+ // add Miranda icon
+ pct := ipcAlloc(ipch, sizeof(TSlotProtoIcons));
+ if pct <> nil then
+ begin
+ ZeroMemory(@spi.hIcons, sizeof(spi.hIcons));
+ spi.hProto := 0; // no protocol
+ spi.hIcons[0] := LoadSkinnedIcon(SKINICON_OTHER_MIRANDA);
+ pct^.fType := REQUEST_NEWICONS;
+ CopyMemory(Pointer(Integer(pct)+sizeof(TSlotIPC)),@spi,sizeof(TSlotProtoIcons));
+ if ipch^.NewIconsBegin = nil then ipch^.NewIconsBegin := pct;
+ end; //if
+ end;
+
+ function ipcGetSortedContacts(ipch: PHeaderIPC; pSlot: pint; bGroupMode: Boolean): Boolean;
+ var
+ dwContacts: Cardinal;
+ pContacts: PSlotArray;
+ hContact: THandle;
+ I: Integer;
+ dwOnline: Cardinal;
+ szProto: PChar;
+ dwStatus: Integer;
+ pct: PSlotIPC;
+ szContact: PChar;
+ dbv: TDBVariant;
+ bHideOffline: Boolean;
+ szTmp: array[0..63] of Char;
+ dwCaps: Cardinal;
+ szSlot: PChar;
+ n, rc, cch: Cardinal;
+ begin
+ Result := False;
+ // hide offliners?
+ bHideOffline := DBGetContactSettingByte(0, 'CList', 'HideOffline', 0) = 1;
+ // do they wanna hide the offline people anyway?
+ if DBGetContactSettingByte(0, SHLExt_Name, SHLExt_ShowNoOffline, 0) = 1 then
+ begin
+ // hide offline people
+ bHideOffline := True;
+ end;
+ // get the number of contacts
+ dwContacts := PluginLink^.CallService(MS_DB_CONTACT_GETCOUNT, 0, 0);
+ if dwContacts = 0 then Exit;
+ // get the contacts in the array to be sorted by status, trim out anyone
+ // who doesn't wanna be seen.
+ GetMem(pContacts, (dwContacts+2) * sizeof(TSlotInfo));
+ i := 0;
+ dwOnline := 0;
+ hContact := PluginLink^.CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ while (hContact <> 0) do
+ begin
+ if i >= dwContacts then Break;
+ (* do they have a running protocol? *)
+ Integer(szProto) := PluginLink^.CallService(MS_PROTO_GETCONTACTBASEPROTO, hContact, 0);
+ if szProto <> nil then
+ begin
+ (* does it support file sends? *)
+ strcpy(szTmp, szProto);
+ strcat(szTmp, PS_GETCAPS);
+ dwCaps := CallService(szTmp,PFLAGNUM_1,0);
+ if (dwCaps and PF1_FILESEND) = 0 then
+ begin
+ hContact := CallService(MS_DB_CONTACT_FINDNEXT,hContact,0);
+ continue;
+ end;
+ dwStatus := DBGetContactSettingWord(hContact, szProto, 'Status', ID_STATUS_OFFLINE);
+ if dwStatus <> ID_STATUS_OFFLINE then Inc(dwOnline)
+ else if bHideOffline then
+ begin
+ hContact := PluginLink^.CallService(MS_DB_CONTACT_FINDNEXT, hContact, 0);
+ continue;
+ end; //if
+ // is HIT on?
+ if BST_UNCHECKED = DBGetContactSettingByte(0, SHLExt_Name, SHLExt_UseHITContacts, BST_UNCHECKED) then
+ begin
+ // don't show people who are "Hidden" "NotOnList" or Ignored
+ if (DBGetContactSettingByte(hContact, 'CList', 'Hidden', 0) = 1)
+ or (DBGetContactSettingByte(hContact, 'CList', 'NotOnList', 0) = 1)
+ or (PluginLink^.CallService(MS_IGNORE_ISIGNORED, hContact, IGNOREEVENT_MESSAGE or IGNOREEVENT_URL or IGNOREEVENT_FILE) <> 0) then
+ begin
+ hContact := PluginLink^.CallService(MS_DB_CONTACT_FINDNEXT, hContact, 0);
+ continue;
+ end; //if
+ end; //if
+ // is HIT2 off?
+ if BST_UNCHECKED = DBGetContactSettingByte(0, SHLExt_Name, SHLExt_UseHIT2Contacts, BST_UNCHECKED) then
+ begin
+ if DBGetContactSettingWord(hContact, szProto, 'ApparentMode', 0) = ID_STATUS_OFFLINE then
+ begin
+ hContact := PluginLink^.CallService(MS_DB_CONTACT_FINDNEXT, hContact, 0);
+ continue;
+ end; //if
+ end; //if
+ // store
+ pContacts^[i].hContact := hContact;
+ pContacts^[i].dwStatus := dwStatus;
+ pContacts^[i].hProto := StrHash(szProto);
+ Inc(i);
+ end else begin
+ // contact has no protocol!
+ end; //if
+ hContact := PluginLink^.CallService(MS_DB_CONTACT_FINDNEXT, hContact, 0);
+ end; //while
+ // if no one is online and the CList isn't showing offliners, quit
+ if (dwOnline = 0) and (bHideOffline) then
+ begin
+ FreeMem(pContacts); Exit;
+ end; //if
+ dwContacts := i; i := 0;
+ // sort the array
+ QuickSort(pContacts, 0, dwContacts-1);
+ // create an IPC slot for each contact and store display name, etc
+ while i < dwContacts do
+ begin
+ Integer(szContact) := PluginLink^.CallService(MS_CLIST_GETCONTACTDISPLAYNAME, pContacts^[i].hContact, 0);
+ if (szContact <> nil) then
+ begin
+ n := 0;
+ rc := 1;
+ if bGroupMode then
+ begin
+ rc := DBGetContactSetting(pContacts^[i].hContact,'CList','Group',@dbv);
+ if rc = 0 then
+ begin
+ n := lstrlen(dbv.pszVal)+1;
+ end;
+ end; //if
+ cch := lstrlen(szContact)+1;
+ pct := ipcAlloc(ipch, cch + 1 + n);
+ if pct = nil then
+ begin
+ DBFreeVariant(@dbv);
+ break;
+ end;
+ // lie about the actual size of the TSlotIPC
+ pct^.cbStrSection := cch;
+ szSlot := PChar(Integer(pct) + sizeof(TSlotIPC));
+ strcpy(szSlot, szContact);
+ pct^.fType := REQUEST_CONTACTS;
+ pct^.hContact := pContacts^[i].hContact;
+ pct^.Status := pContacts^[i].dwStatus;
+ pct^.hProto := pContacts^[i].hProto;
+ pct^.MRU := DBGetContactSettingByte(pct^.hContact, SHLExt_Name, SHLExt_MRU, 0);
+ if ipch^.ContactsBegin = nil then ipch^.ContactsBegin := pct;
+ inc(szSlot,cch+1);
+ if rc=0 then
+ begin
+ pct^.hGroup := StrHash(dbv.pszVal);
+ strcpy(szSlot,dbv.pszVal);
+ DBFreeVariant(@dbv);
+ end else begin
+ pct^.hGroup := 0;
+ szSlot^ := #0;
+ end;
+ inc(pSlot^);
+ end; //if
+ Inc(i);
+ end; //while
+ FreeMem(pContacts);
+ //
+ Result := True;
+ end;
+
+ // worker thread to clear MRU, called by the IPC bridge
+ function ClearMRUThread(notused: Pointer): Cardinal; stdcall;
+ {$define SHL_IDC}
+ {$define SHL_KEYS}
+ {$include shlc.inc}
+ {$undef SHL_KEYS}
+ {$undef SHL_IDC}
+ var
+ hContact: THandle;
+ begin
+ CallService(MS_SYSTEM_THREAD_PUSH,0,0);
+ begin
+ hContact := pluginLink^.CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ while hContact <> 0 do
+ begin
+ if DBGetContactSettingByte(hContact, SHLExt_Name, SHLExt_MRU, 0) > 0 then
+ begin
+ DBWriteContactSettingByte(hContact, SHLExt_Name, SHLExt_MRU, 0);
+ end;
+ hContact := pluginLink^.CallService(MS_DB_CONTACT_FINDNEXT, hContact, 0);
+ end;
+ end;
+ CallService(MS_SYSTEM_THREAD_POP,0,0);
+ ExitThread(0);
+ end;
+
+ // this function is called from an APC into the main thread
+ procedure ipcService(dwParam: DWORD); stdcall;
+ label
+ Reply;
+ var
+ hMap: THandle;
+ pMMT: PHeaderIPC;
+ hSignal: THandle;
+ pct: PSlotIPC;
+ hContact: THandle;
+ szContact: PChar;
+ Status: int;
+ szBuf: PChar;
+ iSlot: Integer;
+ szGroupStr: array[0..31] of Char;
+ dbv: TDBVARIANT;
+ bits: pint;
+ hIcon: THandle;
+ I: Integer;
+ bGroupMode: Boolean;
+ tid: Cardinal;
+ cloned: PHeaderIPC;
+ szMiranda: PChar;
+ begin
+ { try to open the file mapping object the caller must make sure no other
+ running instance is using this file }
+ hMap := OpenFileMapping(FILE_MAP_ALL_ACCESS, False, IPC_PACKET_NAME);
+ If hMap <> 0 then
+ begin
+ { map the file to this process }
+ pMMT := MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
+ { if it fails the caller should of had some timeout in wait }
+ if (pMMT <> nil) and (pMMT^.cbSize = sizeof(THeaderIPC)) and (pMMT^.dwVersion = PLUGIN_MAKE_VERSION(2,0,1,2)) then
+ begin
+ // toggle the right bits
+ bits := @pMMT^.fRequests;
+ // jump right to a worker thread for file processing?
+ if (bits^ and REQUEST_XFRFILES) = REQUEST_XFRFILES then
+ begin
+ GetMem(cloned, IPC_PACKET_SIZE);
+ // translate from client space to cloned heap memory
+ pMMT^.pServerBaseAddress := pMMT^.pClientBaseAddress;
+ pMMT^.pClientBaseAddress := cloned;
+ CopyMemory(cloned, pMMT, IPC_PACKET_SIZE);
+ ipcFixupAddresses(True, cloned);
+ DuplicateHandle(GetCurrentProcess(),GetCurrentThread(),GetCurrentProcess(),@cloned^.Param,THREAD_SET_CONTEXT,FALSE,0);
+ CloseHandle(CreateThread(nil,0,@IssueTransferThread,cloned,0,tid));
+ goto Reply;
+ end;
+ // the request was to clear the MRU entries, we have no return data
+ if (bits^ and REQUEST_CLEARMRU) = REQUEST_CLEARMRU then
+ begin
+ CloseHandle(CreateThread(nil,0,@ClearMRUThread,nil,0,tid));
+ goto reply;
+ end;
+ // the IPC header may have pointers that need to be translated
+ // in either case the supplied data area pointers has to be
+ // translated to this address space.
+ // the server base address is always removed to get an offset
+ // to which the client base is added, this is what ipcFixupAddresses() does
+ pMMT^.pServerBaseAddress := pMMT^.pClientBaseAddress;
+ pMMT^.pClientBaseAddress := pMMT;
+ // translate to the server space map
+ ipcFixupAddresses(True, pMMT);
+ // store the address map offset so the caller can retranslate
+ pMMT^.pServerBaseAddress := pMMT;
+ // return some options to the client
+ if DBGetContactSettingByte(0,SHLExt_Name,SHLExt_ShowNoIcons,0) <> 0 then
+ begin
+ pMMT^.dwFlags := HIPC_NOICONS;
+ end;
+ // see if we have a custom string for 'Miranda'
+ szMiranda := Translate('Miranda');
+ lstrcpyn(pMMT^.MirandaName,szMiranda,sizeof(pMMT^.MirandaName)-1);
+
+ // for the MRU menu
+ szBuf := Translate('Recently');
+ lstrcpyn(pMMT^.MRUMenuName, szBuf, sizeof(pMMT^.MRUMenuName)-1);
+
+ // and a custom string for "clear entries"
+ szBuf := Translate('Clear entries');
+ lstrcpyn(pMMT^.ClearEntries,szBuf, sizeof(pMMT^.ClearEntries)-1);
+
+ // if the group mode is on, check if they want the CList setting
+ bGroupMode := BST_CHECKED = DBGetContactSettingByte(0, SHLExt_Name, SHLExt_UseGroups, BST_UNCHECKED);
+ if bGroupMode and (BST_CHECKED = DBGetContactSettingByte(0, SHLExt_Name, SHLExt_UseCListSetting, BST_UNCHECKED)) then
+ begin
+ bGroupMode := 1 = DBGetContactSettingByte(0, 'CList', 'UseGroups', 0);
+ end;
+ iSlot := 0;
+ // return profile if set
+ if BST_UNCHECKED = DBGetContactSettingByte(0, SHLExt_Name, SHLExt_ShowNoProfile, BST_UNCHECKED) then
+ begin
+ pct := ipcAlloc(pMMT, 50);
+ if pct <> nil then
+ begin
+ // will actually return with .dat if there's space for it, not what the docs say
+ pct^.Status := STATUS_PROFILENAME;
+ PluginLink^.CallService(MS_DB_GETPROFILENAME, 49, Integer(pct)+sizeof(TSlotIPC));
+ end; //if
+ end; //if
+ if (bits^ and REQUEST_NEWICONS) = REQUEST_NEWICONS then
+ begin
+ ipcGetSkinIcons(pMMT);
+ end;
+ if (bits^ and REQUEST_GROUPS = REQUEST_GROUPS) then
+ begin
+ // return contact's grouping if it's present
+ while bGroupMode do
+ begin
+ Str(iSlot, szGroupStr);
+ if DBGetContactSetting(0, 'CListGroups', szGroupStr, @dbv) <> 0 then Break;
+ pct := ipcAlloc(pMMT, lstrlen(dbv.pszVal+1)+1); // first byte has flags, need null term
+ if pct <> nil then
+ begin
+ if pMMT^.GroupsBegin = nil then pMMT^.GroupsBegin := pct;
+ pct^.fType := REQUEST_GROUPS;
+ pct^.hContact := 0;
+ Integer (szBuf) := Integer(pct) + sizeof(TSlotIPC); // get the end of the slot
+ strcpy(szBuf, dbv.pszVal+1);
+ pct^.hGroup := 0;
+ DBFreeVariant(@dbv); // free the string
+ end else begin
+ // outta space
+ DBFreeVariant(@dbv);
+ Break;
+ end; //if
+ Inc(iSlot);
+ end; {while}
+ // if there was no space left, it'll end on null
+ if pct = nil then bits^ := (bits^ or GROUPS_NOTIMPL) and not REQUEST_GROUPS;
+ end; {if: group request}
+ // SHOULD check slot space.
+ if (bits^ and REQUEST_CONTACTS = REQUEST_CONTACTS) then
+ begin
+ if not ipcGetSortedContacts(pMMT, @iSlot, bGroupMode) then
+ begin
+ // fail if there were no contacts AT ALL
+ bits^ := (bits^ or CONTACTS_NOTIMPL) and not REQUEST_CONTACTS;
+ end; //if
+ end; // if:contact request
+ // store the number of slots allocated
+ pMMT^.Slots := iSlot;
+ Reply:
+ { get the handle the caller wants to be signalled on }
+ hSignal := OpenEvent(EVENT_ALL_ACCESS, False, pMMT^.SignalEventName);
+ { did it open? }
+ If hSignal <> 0 then
+ begin
+ { signal and close }
+ SetEvent(hSignal); CloseHandle(hSignal);
+ end;
+ { unmap the shared memory from this process }
+ UnmapViewOfFile(pMMT);
+ end;
+ { close the map file }
+ CloseHandle(hMap);
+ end; {if}
+ //
+ end;
+
+ function ThreadServer(hMainThread: Pointer): Cardinal;
+ {$ifdef FPC}
+ stdcall;
+ {$endif}
+ var
+ hEvent: THandle;
+ begin
+ CallService(MS_SYSTEM_THREAD_PUSH,0,0);
+ hEvent := CreateEvent(nil, False, False, PChar(CreateProcessUID(GetCurrentProcessId())));
+ while True do
+ begin
+ Result := WaitForSingleObjectEx(hEvent,INFINITE,True);
+ if Result = WAIT_OBJECT_0 then
+ begin
+ QueueUserAPC(@ipcService,THandle(hMainThread),0);
+ end; //if
+ if CallService(MS_SYSTEM_TERMINATED,0,0)=1 then Break;
+ end; //while
+ CloseHandle(hEvent);
+ CloseHandle(THandle(hMainThread));
+ CallService(MS_SYSTEM_THREAD_POP,0,0);
+ ExitThread(0);
+ end;
+
+ procedure InvokeThreadServer;
+ var
+ {$ifdef FPC}
+ TID: LongWord;
+ {$else}
+ TID: Cardinal;
+ {$endif}
+ var
+ hMainThread: THandle;
+ begin
+ hMainThread := 0;
+ DuplicateHandle(GetCurrentProcess(),GetCurrentThread(),GetCurrentProcess(),@hMainThread,THREAD_SET_CONTEXT,FALSE,0);
+ if hMainThread <> 0 then
+ begin
+ {$ifdef FPC}
+ CloseHandle(CreateThread(nil,0,@ThreadServer,Pointer(hMainThread),0,TID));
+ {$else}
+ CloseHandle(BeginThread(nil,0,@ThreadServer,Pointer(hMainThread),0,TID));
+ {$endif}
+ end; //if
+ end;
+
+{ exported functions }
+
+ function DllGetClassObject(const CLSID: TCLSID; const IID: TIID; var Obj): HResult; stdcall;
+ begin
+ Pointer(Obj) := nil;
+ Result := CLASS_E_CLASSNOTAVAILABLE;
+ if (IsEqualCLSID(CLSID,CLSID_ISHLCOM))
+ and (IsEqualIID(IID,IID_IClassFactory))
+ and (FindWindow(MIRANDANAME,nil) <> 0) then
+ begin
+ Pointer(Obj) := TClassFactoryRec_Create;
+ Result := S_OK;
+ end; //if
+ end;
+
+ function DllCanUnloadNow: HResult;
+ begin
+ if ((dllpublic.FactoryCount = 0) and (dllpublic.ObjectCount = 0)) then
+ begin
+ Result := S_OK;
+ end else begin
+ Result := S_FALSE;
+ end; //if
+ end;
+
+{ helper functions }
+
+type
+
+ PSHELLEXECUTEINFO = ^TSHELLEXECUTEINFO;
+ TSHELLEXECUTEINFO = record
+ cbSize: DWORD;
+ fMask: LongInt;
+ hwnd: THandle;
+ lpVerb: PChar;
+ lpFile: PChar;
+ lpParameters: PChar;
+ lpDirectory: PChar;
+ nShow: Integer;
+ hInstApp: THandle;
+ lpIDLIst: Pointer;
+ lpClass: PChar;
+ hKey: THandle;
+ dwHotKey: DWORD;
+ hIcon: THandle; // is union
+ hProcess: THandle;
+ end;
+
+ function ShellExecuteEx(var se: TSHELLEXECUTEINFO): Boolean; stdcall; external 'shell32.dll' name 'ShellExecuteExA';
+
+ function wsprintfs(lpOut, lpFmt: PChar; ArgS: PChar): Integer; cdecl; external 'user32.dll' name 'wsprintfA';
+
+ function RemoveCOMRegistryEntries: HResult;
+ var
+ hRootKey: HKEY;
+ begin
+ if RegOpenKeyEx(HKEY_CLASSES_ROOT, 'miranda.shlext', 0, KEY_READ, hRootKey) = ERROR_SUCCESS then
+ begin
+ (* need to delete the subkey before the parent key is deleted under NT/2000/XP *)
+ RegDeleteKey(hRootKey, 'CLSID');
+ (* close the key *)
+ RegCloseKey(hRootKey);
+ (* delete it *)
+ if RegDeleteKey(HKEY_CLASSES_ROOT, 'miranda.shlext') <> ERROR_SUCCESS then
+ begin
+ MessageBox(0, 'Unable to delete registry key for "shlext COM", this key may already be deleted or you may need admin rights.', 'Problem', MB_ICONERROR);
+ end; //if
+ end; //if
+ if RegOpenKeyEx(HKEY_CLASSES_ROOT, '\*\shellex\ContextMenuHandlers', 0, KEY_ALL_ACCESS, hRootKey) = ERROR_SUCCESS then
+ begin
+ if RegDeleteKey(hRootKey, 'miranda.shlext') <> ERROR_SUCCESS then
+ begin
+ MessageBox(0, 'Unable to delete registry key for "File context menu handlers", this key may already be deleted or you may need admin rights.', 'Problem', MB_ICONERROR);
+ end; //if
+ RegCloseKey(hRootKey);
+ end; //if
+ if RegOpenKeyEx(HKEY_CLASSES_ROOT, 'Directory\shellex\ContextMenuHandlers', 0, KEY_ALL_ACCESS, hRootKey) = ERROR_SUCCESS then
+ begin
+ if RegDeleteKey(hRootKey, 'miranda.shlext') <> ERROR_SUCCESS then
+ begin
+ MessageBox(0, 'Unable to delete registry key for "Directory context menu handlers", this key may already be deleted or you may need admin rights.', 'Problem', MB_ICONERROR);
+ end; //if
+ RegCloseKey(hRootKey);
+ end; //if
+ if ERROR_SUCCESS = RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved', 0, KEY_ALL_ACCESS, hRootKey) then
+ begin
+ if RegDeleteValue(hRootKey, '{72013A26-A94C-11d6-8540-A5E62932711D}') <> ERROR_SUCCESS then
+ begin
+ MessageBox(0, 'Unable to delete registry entry for "Approved context menu handlers", this key may already be deleted or you may need admin rights.', 'Problem', MB_ICONERROR);
+ end; //if
+ RegCloseKey(hRootKey);
+ end; //if
+ Result := S_OK;
+ end;
+
+ { called by the options code to remove COM entries, and before that, get permission, if required.
+ }
+
+ procedure CheckUnregisterServer;
+ var
+ sei: TSHELLEXECUTEINFO;
+ szBuf: array[0..MAX_PATH*2] of Char;
+ szFileName: array[0..MAX_PATH] of Char;
+ begin
+ if not VistaOrLater then
+ begin
+ RemoveCOMRegistryEntries();
+ Exit;
+ end;
+ // launches regsvr to remove the dll under admin.
+ GetModuleFileName(System.hInstance, szFileName, sizeof(szFileName));
+ wsprintfs(szBuf, '/s /u "%s"', szFileName);
+ ZeroMemory(@sei, sizeof(sei));
+ sei.cbSize := sizeof(sei);
+ sei.lpVerb := 'runas';
+ sei.lpFile := 'regsvr32';
+ sei.lpParameters := szBuf;
+ ShellExecuteEx(sei);
+ Sleep(1000);
+ RemoveCOMRegistryEntries();
+ end;
+
+ { Wow, I can't believe there isn't a direct API for this - 'runas' will invoke the UAC and ask
+ for permission before installing the shell extension. note the filepath arg has to be quoted }
+ procedure CheckRegisterServer;
+ var
+ hRegKey: HKEY;
+ sei: TSHELLEXECUTEINFO;
+ szBuf: array[0..MAX_PATH*2] of Char;
+ szFileName: array[0..MAX_PATH] of Char;
+ begin
+ if ERROR_SUCCESS = RegOpenKeyEx(HKEY_CLASSES_ROOT, 'miranda.shlext', 0, KEY_READ, hRegKey) then
+ begin
+ RegCloseKey(hRegKey);
+ end else begin
+ if VistaOrLater then
+ begin
+ MessageBox(0, 'Shell context menus requires your permission to register with Windows Explorer (one time only).',
+ 'Miranda IM - Shell context menus (shlext.dll)', MB_OK or MB_ICONINFORMATION);
+ // /s = silent
+ GetModuleFileName(System.hInstance, szFileName, sizeof(szFileName));
+ wsprintfs(szBuf, '/s "%s"', szFileName);
+ ZeroMemory(@sei, sizeof(sei));
+ sei.cbSize := sizeof(sei);
+ sei.lpVerb := 'runas';
+ sei.lpFile := 'regsvr32';
+ sei.lpParameters := szBuf;
+ ShellExecuteEx(sei);
+ end;
+ end;
+ end;
+
+initialization
+begin
+ FillChar(dllpublic, sizeof(dllpublic), 0);
+ IsMultiThread := True;
+ VistaOrLater := GetProcAddress(GetModuleHandle('kernel32'), 'GetProductInfo') <> nil;
+end;
+
+end.
+
diff --git a/plugins/ShlExt/shldlgs.rc b/plugins/ShlExt/shldlgs.rc
new file mode 100644
index 0000000000..0e9cd82b04
--- /dev/null
+++ b/plugins/ShlExt/shldlgs.rc
@@ -0,0 +1,93 @@
+#include "resource.h"
+//#include "afxres.h"
+#define WS_POPUP 0x80000000L
+#define WS_CHILD 0x40000000L
+#define BS_AUTOCHECKBOX 0x00000003L
+#define WS_TABSTOP 0x00010000L
+#define SS_ETCHEDHORZ 0x00000010L
+#define WS_GROUP 0x00020000L
+#ifndef IDC_STATIC
+#define IDC_STATIC (-1)
+#endif
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_SHLOPTS DIALOG DISCARDABLE 0, 0, 312, 238
+STYLE WS_POPUP
+FONT 8, "MS Shell Dlg"
+BEGIN
+ CONTROL "Display contacts in their assigned groups (if any)",
+ IDC_USEGROUPS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,
+ 35,281,8
+ CONTROL "Only if/when the contact list is using them",
+ IDC_CLISTGROUPS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,29,
+ 50,267,8
+ CONTROL "Display hidden, ignored or temporary contacts",
+ IDC_SHOWFULL,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,65,
+ 281,8
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,26,21,192,1
+ LTEXT "Menus",IDC_CAPMENUS,10,17,24,8
+ LTEXT "",IDC_STATIC,214,16,10,11,NOT WS_GROUP
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,34,145,183,1
+ LTEXT "Shell Status",IDC_CAPSHLSTATUS,10,141,43,8
+ LTEXT "",IDC_STATIC,214,111,10,11,NOT WS_GROUP
+ LTEXT "...",IDC_STATUS,15,154,253,12
+ GROUPBOX "Shell context menus",IDC_STATIC,0,0,311,238
+ CONTROL "Do not display the profile name in use",IDC_NOPROF,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,80,285,8
+ CONTROL "Show contacts that you have set privacy rules for",
+ IDC_SHOWINVISIBLES,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 15,110,290,8
+ PUSHBUTTON "Remove",IDC_REMOVE,14,173,42,14
+ CONTROL "Do not show status icons in menus",IDC_USEOWNERDRAW,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,95,290,8
+ LTEXT "",IDC_STATIC,214,136,10,11,NOT WS_GROUP
+ CONTROL "Do not show contacts that are offline, even if my contact list does",IDC_HIDEOFFLINE,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,15,125,290,8
+END
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION 1,0,6,6
+ PRODUCTVERSION 1,0,6,6
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x4L
+ FILETYPE 0x2L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "080904b0"
+ BEGIN
+ VALUE "Comments", "\0"
+ VALUE "CompanyName", "\0"
+ VALUE "FileDescription", "'Click ''n'' send support from Explorer/Common dialogs/Desktop, Right click on a file/folder to be presented with all your Miranda contact lists and then select the profile/contact you want to send to.\0"
+ VALUE "FileVersion", "1, 0, 6, 6\0"
+ VALUE "InternalName", "shlext\0"
+ VALUE "LegalCopyright", "\0"
+ VALUE "LegalTrademarks", "\0"
+ VALUE "OriginalFilename", "shlext.dll\0"
+ VALUE "PrivateBuild", "\0"
+ VALUE "ProductName", "\0"
+ VALUE "ProductVersion", "1, 0, 6, 6\0"
+ VALUE "SpecialBuild", "\0"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x809, 1200
+ END
+END
+
diff --git a/plugins/ShlExt/shldlgs.res b/plugins/ShlExt/shldlgs.res
new file mode 100644
index 0000000000..3de576e992
--- /dev/null
+++ b/plugins/ShlExt/shldlgs.res
Binary files differ
diff --git a/plugins/ShlExt/shlext.dpr b/plugins/ShlExt/shlext.dpr
new file mode 100644
index 0000000000..eb772e98a8
--- /dev/null
+++ b/plugins/ShlExt/shlext.dpr
@@ -0,0 +1,379 @@
+{$IFDEF FPC}
+ {$PACKRECORDS 4}
+ {$MODE Delphi}
+ {$ASMMODE intel}
+ {$INLINE ON}
+ {$MACRO ON}
+ {$APPTYPE GUI}
+ {$IMAGEBASE $49ac0000}
+{$ELSE}
+ {$IMAGEBASE $49ac0000} // this is ignored with FPC, must be set via the command line
+{$ENDIF}
+
+library shlext;
+uses
+
+ Windows, shlcom, shlipc, m_globaldefs;
+
+ // use the registry to store the COM information needed by the shell
+
+ function DllRegisterServer: HResult; stdcall;
+ var
+ szData: PChar;
+ hRegKey: HKEY;
+ begin
+
+ {$IFDEF INSTALLER_REGISTER}
+ Result := S_OK;
+ {$ELSE}
+ // progID
+ szData := 'shlext (1.0.6.6) - shell context menu support for Miranda v0.3.0.0+';
+ if ERROR_SUCCESS = RegSetValue(HKEY_CLASSES_ROOT, 'miranda.shlext', REG_SZ, szData, Length(szData)) then
+ begin
+ // CLSID related to ProgID
+ szData := '{72013A26-A94C-11d6-8540-A5E62932711D}';
+ if ERROR_SUCCESS = RegSetValue(HKEY_CLASSES_ROOT, 'miranda.shlext\CLSID', REG_SZ, szData, Length(szData)) then
+ begin
+ // CLSID link back to progID
+ szData := 'miranda.shlext';
+ if ERROR_SUCCESS = RegSetValue(HKEY_CLASSES_ROOT, 'CLSID\{72013A26-A94C-11d6-8540-A5E62932711D}', REG_SZ, szData, Length(szData)) then
+ begin
+ // CLSID link back to ProgID under \ProgID again?
+ szData := 'miranda.shlext';
+ if ERROR_SUCCESS = RegSetValue(HKEY_CLASSES_ROOT, 'CLSID\{72013A26-A94C-11d6-8540-A5E62932711D}\ProgID', REG_SZ, szData, Length(szData)) then
+ begin
+ GetMem(szData, MAX_PATH);
+ GetModuleFileName(hInstance, szData, MAX_PATH-1);
+ Result := RegSetValue(HKEY_CLASSES_ROOT, 'CLSID\{72013A26-A94C-11d6-8540-A5E62932711D}\InprocServer32', REG_SZ, szData, Length(szData));
+ FreeMem(szData);
+ if Result = ERROR_SUCCESS then
+ begin
+ // have to add threading model
+ szData := 'CLSID\{72013A26-A94C-11d6-8540-A5E62932711D}\InprocServer32';
+ Result := RegCreateKeyEx(HKEY_CLASSES_ROOT, szData, 0, nil, 0, KEY_SET_VALUE or KEY_CREATE_SUB_KEY, nil, hRegKey, nil);
+ if Result = ERROR_SUCCESS then
+ begin
+ szData := 'Apartment';
+ RegSetValueEx(hRegKey, 'ThreadingModel', 0, REG_SZ, PByte(szData), Length(szData)+1);
+ RegCloseKey(hRegKey);
+ // write which file types to show under
+ szData := '{72013A26-A94C-11d6-8540-A5E62932711D}';
+ // note that *\ should use AllFilesystemObjects for 4.71+
+ if ERROR_SUCCESS = RegSetValue(HKEY_CLASSES_ROOT, '*\shellex\ContextMenuHandlers\miranda.shlext', REG_SZ, szData, Length(szData)) then
+ begin
+ // don't support directories
+ if ERROR_SUCCESS = RegSetValue(HKEY_CLASSES_ROOT, 'Directory\shellex\ContextMenuHandlers\miranda.shlext', REG_SZ, szData, Length(szData)) then
+ begin
+ Result := S_OK;
+ // have to add to the approved list under NT/2000/XP with {CLSID}="<description>"
+ szData := 'SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved';
+ Result := RegCreateKeyEx(HKEY_LOCAL_MACHINE, szData, 0, nil, 0, KEY_SET_VALUE or KEY_CREATE_SUB_KEY, nil, hRegKey, nil);
+ if Result = ERROR_SUCCESS then
+ begin
+ szData := 'shlext (1.0.6.6) - context menu support for Miranda v0.3.0.0+';
+ RegSetValueEx(hRegKey, '{72013A26-A94C-11d6-8540-A5E62932711D}', 0, REG_SZ, PByte(szData), Length(szData)+1);
+ RegCloseKey(hRegKey);
+ end; //if
+ end else Result := E_FAIL;
+ end else Result := E_FAIL;
+ end else Result := E_FAIL;
+ end else Result := E_FAIL;
+ end else Result := E_FAIL;
+ end else Result := E_FAIL;
+ end else Result := E_FAIL;
+ end else Result := E_FAIL;
+ //
+ {$ENDIF}
+
+ end;
+
+ function DllUnregisterServer: HResult; stdcall;
+ begin
+ Result := RemoveCOMRegistryEntries();
+ end;
+
+ // - miranda section ----
+
+ {$include m_options.inc}
+ {$include m_system.inc}
+ {$include m_database.inc}
+ {$include m_file.inc}
+ {$include m_langpack.inc}
+ {$include m_helpers.inc}
+ {$include m_v8.inc}
+
+const
+
+ COMREG_UNKNOWN = $00000000;
+ COMREG_OK = $00000001;
+ COMREG_APPROVED = $00000002;
+
+ function IsCOMRegistered: Integer;
+ var
+ hRegKey: HKEY;
+ lpType: Integer;
+ begin
+ Result := 0;
+ // these arent the BEST checks in the world
+ if ERROR_SUCCESS = RegOpenKeyEx(HKEY_CLASSES_ROOT, 'miranda.shlext', 0, KEY_READ, hRegKey) then
+ begin
+ Result := Result or COMREG_OK;
+ RegCloseKey(hRegKey);
+ end; //if
+ lpType := REG_SZ;
+ if ERROR_SUCCESS = RegOpenKeyEx(HKEY_LOCAL_MACHINE, 'Software\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved', 0, KEY_READ, hRegKey) then
+ begin
+ if ERROR_SUCCESS = RegQueryValueEx(hRegKey, '{72013A26-A94C-11d6-8540-A5E62932711D}', nil, @lpType, nil, nil) then
+ begin
+ Result := Result or COMREG_APPROVED;
+ end; //if
+ RegCloseKey(hRegKey);
+ end; // if
+ end;
+
+ procedure AutoSize(hwnd: THandle);
+ var
+ szBuf: array[0..MAX_PATH] of Char;
+ DC: HDC;
+ tS: TSize;
+ i: Integer;
+ hFont, hOldFont: THandle;
+ begin
+ DC := GetDC(hwnd);
+ hFont := GetStockObject(DEFAULT_GUI_FONT);
+ hOldFont := SelectObject(DC, hFont);
+ i := GetWindowText(hwnd, szBuf, MAX_PATH);
+ GetTextExtentPoint32(DC, szBuf, i, tS);
+ SelectObject(DC, hOldFont);
+ DeleteObject(hFont);
+ ReleaseDC(hwnd, DC);
+ SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, tS.cx + 10, tS.cy, SWP_NOMOVE or SWP_FRAMECHANGED);
+ end;
+
+ function OptDialogProc(hwndDlg: THandle; wMsg: Integer; wParam: WPARAM; lParam: LPARAM): BOOL; stdcall;
+ // don't wanna bring in CommCtrl just for a few constants
+ const
+ {$IFNDEF FPC}
+ WM_INITDIALOG = $0110;
+ WM_COMMAND = $0111;
+ WM_USER = $0400;
+ WM_NOTIFY = $004E;
+ {$ENDIF}
+ { propsheet notifications/msessages }
+ //PSN_APPLY = (-200) - 2;
+ PSM_CHANGED = WM_USER + 104;
+ { button styles }
+ BCM_SETSHIELD = ({BCM_FIRST}$1600 + $000C);
+ { hotkey }
+ // bring in the IDC's and storage key names
+ {$define SHL_IDC}
+ {$define SHL_KEYS}
+ {$include shlc.inc}
+ {$undef SHL_KEYS}
+ {$undef SHL_IDC}
+ const
+ COM_OKSTR: array[Boolean] of PChar = (
+ 'Problem, registration missing/deleted.',
+ 'Successfully created shell registration.'
+ );
+ COM_APPROVEDSTR: array[Boolean] of PChar = (
+ 'Not Approved',
+ 'Approved'
+ );
+ var
+ comReg: Integer;
+ iCheck: Integer;
+ szBuf: array[0..MAX_PATH] of Char;
+ cgs: TDBCONTACTGETSETTING;
+ begin
+ Result := wMsg = WM_INITDIALOG;
+ case wMsg of
+ WM_NOTIFY:
+ begin
+ {* FP 2.2.2 seems to have a bug, 'Code' is supposed to be signed
+ but isn't signed, so when comparing -202 (=PSN_APPLY) It doesn't work
+ so here, -202 is converted into hex, what you are looking at is the
+ code == PSN_APPLY check. *}
+ if $FFFFFF36 = pNMHDR(lParam)^.code then
+ begin
+ DBWriteContactSettingByte(0, SHLExt_Name, SHLExt_UseGroups, IsDlgButtonChecked(hwndDlg, IDC_USEGROUPS));
+ DBWriteContactSettingByte(0, SHLExt_Name, SHLExt_UseCListSetting, IsDlgButtonChecked(hwndDlg, IDC_CLISTGROUPS));
+ DBWriteContactSettingByte(0, SHLExt_Name, SHLExt_ShowNoProfile, IsDlgButtonChecked(hwndDlg, IDC_NOPROF));
+ DBWriteContactSettingByte(0, SHLExt_Name, SHLExt_UseHITContacts, IsDlgButtonChecked(hwndDlg, IDC_SHOWFULL));
+ DBWriteContactSettingByte(0, SHLExt_Name, SHLExt_UseHIT2Contacts, IsDlgButtonChecked(hwndDlg, IDC_SHOWINVISIBLES));
+ DBWriteContactSettingByte(0, SHLExt_Name, SHLExt_ShowNoIcons, IsDlgButtonChecked(hwndDlg, IDC_USEOWNERDRAW));
+ DBWriteContactSettingByte(0, SHLExt_Name, SHLExt_ShowNoOffline, IsDlgButtonChecked(hwndDlg, IDC_HIDEOFFLINE));
+ end; //if
+ end;
+ WM_INITDIALOG:
+ begin
+ TranslateDialogDefault(hwndDlg);
+ comReg := IsCOMRegistered();
+ FillChar(szBuf, MAX_PATH, 0);
+ lstrcat(szBuf, Translate(COM_OKSTR[comReg and COMREG_OK = COMREG_OK]));
+ lstrcat(szBuf, ' (');
+ lstrcat(szBuf, Translate(COM_APPROVEDSTR[comReg and COMREG_APPROVED = COMREG_APPROVED]));
+ lstrcat(szBuf, ')');
+ SetWindowText(GetDlgItem(hwndDlg, IDC_STATUS), szBuf);
+ // auto size the static windows to fit their text
+ // they're rendering in a font not selected into the DC.
+ AutoSize(GetDlgItem(hwndDlg, IDC_CAPMENUS));
+ AutoSize(GetDlgItem(hwndDlg, IDC_CAPSTATUS));
+ AutoSize(GetDlgItem(hwndDlg, IDC_CAPSHLSTATUS));
+ // show all the options
+ iCheck := DBGetContactSettingByte(0, SHLExt_Name, SHLExt_UseGroups, BST_UNCHECKED);
+ CheckDlgButton(hwndDlg, IDC_USEGROUPS, iCheck);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_CLISTGROUPS), iCheck = BST_CHECKED);
+ CheckDlgButton(hwndDlg, IDC_CLISTGROUPS, DBGetContactSettingByte(0, SHLExt_Name, SHLExt_UseCListSetting, BST_UNCHECKED));
+ CheckDlgButton(hwndDlg, IDC_NOPROF, DBGetContactSettingByte(0, SHLExt_Name, SHLExt_ShowNoProfile, BST_UNCHECKED));
+ CheckDlgButton(hwndDlg, IDC_SHOWFULL, DBGetContactSettingByte(0, SHLExt_Name, SHLExt_UseHITContacts, BST_UNCHECKED));
+ CheckDlgButton(hwndDlg, IDC_SHOWINVISIBLES, DBGetContactSettingByte(0, SHLExt_Name, SHLExt_UseHIT2Contacts, BST_UNCHECKED));
+ CheckDlgButton(hwndDlg, IDC_USEOWNERDRAW, DBGetContactSettingByte(0, SHLExt_Name, SHLExt_ShowNoIcons, BST_UNCHECKED));
+ CheckDlgButton(hwndDlg, IDC_HIDEOFFLINE, DBGetContactSettingByte(0, SHLExt_Name, SHLExt_ShowNoOffline, BST_UNCHECKED));
+ // give the Remove button a Vista icon
+ SendMessage(GetDlgItem(hwndDlg, IDC_REMOVE), BCM_SETSHIELD, 0, 1);
+ end;
+ WM_COMMAND:
+ begin
+ // don't send the changed message if remove is clicked
+ if LOWORD(wParam) <> IDC_REMOVE then
+ begin
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ end; //if
+ case LOWORD(wParam) of
+ IDC_USEGROUPS:
+ begin
+ EnableWindow(GetDlgItem(hwndDlg, IDC_CLISTGROUPS), BST_CHECKED = IsDlgButtonChecked(hwndDlg, IDC_USEGROUPS));
+ end; //if
+ IDC_REMOVE:
+ begin
+ if IDYES = MessageBox(0, Translate('Are you sure? this will remove all the settings stored in your database and all registry entries created for shlext to work with Explorer'), Translate('Disable/Remove shlext'), MB_YESNO or MB_ICONQUESTION) then
+ begin
+ cgs.szModule := SHLExt_Name;
+
+ cgs.szSetting := SHLExt_UseGroups;
+ CallService(MS_DB_CONTACT_DELETESETTING, 0, Integer(@cgs));
+
+ cgs.szSetting := SHLExt_UseCListSetting;
+ CallService(MS_DB_CONTACT_DELETESETTING, 0, Integer(@cgs));
+
+ cgs.szSetting := SHLExt_UseHITContacts;
+ CallService(MS_DB_CONTACT_DELETESETTING, 0, Integer(@cgs));
+
+ cgs.szSetting := SHLExt_UseHIT2Contacts;
+ CallService(MS_DB_CONTACT_DELETESETTING, 0, Integer(@cgs));
+
+ cgs.szSetting := SHLExt_ShowNoProfile;
+ CallService(MS_DB_CONTACT_DELETESETTING, 0, Integer(@cgs));
+
+ cgs.szSetting := SHLExt_ShowNoIcons;
+ CallService(MS_DB_CONTACT_DELETESETTING, 0, Integer(@cgs));
+
+ cgs.szSetting := SHLExt_ShowNoOffline;
+ CallService(MS_DB_CONTACT_DELETESETTING, 0, Integer(@cgs));
+
+ (* remove from Explorer *)
+ //DllUnregisterServer();
+ CheckUnregisterServer();
+ (* show all the settings have gone... *)
+ SendMessage(hwndDlg, WM_INITDIALOG, 0, 0);
+ end; //if
+ end; //if
+ end; //case
+ // LOWORD(wParam) == IDC_*
+ end;{outercase}
+ end; //case
+ end;
+
+ function InitialiseOptionPages(wParam: WPARAM; lParam: LPARAM): int; cdecl;
+ const
+ IDD_SHLOPTS = 101;
+ var
+ optDialog: TOPTIONSDIALOGPAGE;
+ begin
+ Result := 0;
+ FillChar(optDialog, sizeof(TOPTIONSDIALOGPAGE), 0);
+ optDialog.cbSize := sizeof(TOPTIONSDIALOGPAGE);
+ optDialog.flags := ODPF_BOLDGROUPS;
+ optDialog.groupPosition := 0;
+ optDialog.pszGroup := 'Plugins';
+ optDialog.position := -1066;
+ optDialog.pszTitle := Translate('Shell context menus');
+ optDialog.pszTemplate := MAKEINTRESOURCE(IDD_SHLOPTS);
+ {$ifdef VER140}
+ optDialog.hInstance := HInstance;
+ {$else}
+ optDialog.hInstance := System.hInstance;
+ {$endif}
+ optDialog.pfnDlgProc := @OptDialogProc;
+ PluginLink^.CallService(MS_OPT_ADDPAGE, wParam, Integer(@optDialog));
+ end;
+
+ function MirandaPluginInfoEx(mirandaVersion: DWORD): PPLUGININFOEX; cdecl;
+ begin
+ Result := nil;
+ { only support v0.3.0.0+ }
+ if PLUGIN_MAKE_VERSION(0,3,0,0) > MirandaVersion then Exit;
+ { fill in plugininfo }
+ PLUGININFOEX.cbSize := sizeof(PLUGININFOEX);
+ PLUGININFOEX.shortName := 'Shell context menus for transfers';
+ PLUGININFOEX.version := PLUGIN_MAKE_VERSION(2,0,1,2);
+ {$ifdef FPC}
+ PLUGININFOEX.description := 'Click ''n'' send support from Explorer/Common dialogs/Desktop, Right click on a file/folder to be presented with all your Miranda contact lists and then select the profile/contact you want to send to. Built on ' + {$I %DATE%} + ' at ' + {$I %TIME%} + ' with FPC ' + {$I %FPCVERSION%};
+ {$else}
+ PLUGININFOEX.description := '';
+ {$endif}
+ PLUGININFOEX.author := 'egoDust';
+ PLUGININFOEX.authorEmail := 'egodust@users.sourceforge.net';
+ PLUGININFOEX.copyright := '(c) 2009 Sam Kothari (egoDust)';
+ PLUGININFOEX.homePage := 'http://addons.miranda-im.org/details.php?action=viewfile&id=534';
+ PLUGININFOEX.isTransient := 0;
+ PLUGININFOEX.replacesDefaultModule := 0;
+ { This UUID is fetched twice }
+ CopyMemory(@PLUGININFOEX.uuid, @CLSID_ISHLCOM, sizeof(TMUUID));
+ { return info }
+ Result := @PLUGININFOEX;
+ end;
+
+ function MirandaPluginInterfaces: PMUUID; cdecl;
+ const
+ ifaces: array[0..1] of TMUUID =
+ (
+ // same as CLSID_ISHLCOM
+ (a: $72013a26; b: $a94c; c: $11d6; d: ($85,$40,$a5,$e6,$29,$32,$71,$1d) ),
+
+ // MUUID_LASTPLUGIN
+ (a: 0; b: 0; c: 0; d:(0,0,0,0,0,0,0,0) )
+ );
+ begin
+ Result := @ifaces;
+ end;
+
+ function Load(link: PPLUGINLINK): int; cdecl;
+ begin
+ Result := 0;
+ PLUGINLINK := Pointer(link);
+ InvokeThreadServer;
+ PluginLink^.HookEvent(ME_OPT_INITIALISE, InitialiseOptionPages);
+ DllRegisterServer();
+ CheckRegisterServer();
+ //DisableThreadLibraryCalls(System.hInstance);
+ end;
+
+ function Unload: int; cdecl;
+ begin
+ Result := 0;
+ end;
+
+ {$R shldlgs.res}
+
+ exports
+
+ MirandaPluginInfoEx, MirandaPluginInterfaces, Load, Unload;
+
+ exports
+
+ DllGetClassObject, DllCanUnloadNow, DllRegisterServer, DllUnregisterServer;
+
+begin
+end.
diff --git a/plugins/ShlExt/shlicons.pas b/plugins/ShlExt/shlicons.pas
new file mode 100644
index 0000000000..a5c2e5d393
--- /dev/null
+++ b/plugins/ShlExt/shlicons.pas
@@ -0,0 +1,162 @@
+unit shlicons;
+
+interface
+
+uses
+
+ Windows;
+
+type
+
+ PVTable_IWICBitmap = ^TVTable_IWICBitmap;
+ TVTable_IWICBitmap = record
+ { IUnknown }
+ QueryInterface: Pointer;
+ AddRef: function(Self: Pointer): Cardinal; stdcall;
+ Release: function(Self: Pointer): Cardinal; stdcall;
+ { IWICBitmapSource }
+ GetSize: function(Self: Pointer; var Width, Height: LongInt): HResult; stdcall;
+ GetPixelFormat: Pointer;
+ GetResolution: Pointer;
+ CopyPalette: Pointer;
+ CopyPixels: function(Self: Pointer; prc: Pointer; cbStride, cbBufferSize: LongWord; pbBuffer: PByte): HResult; stdcall;
+ { IWICBitmap }
+ // .... not used
+
+ end;
+
+ PWICBitmap_Interface = ^TWICBitmap_Interface;
+ TWICBitmap_Interface = record
+ ptrVTable: PVTable_IWICBitmap;
+ end;
+
+ // bare minmum interface to ImagingFactory
+
+ PVTable_ImagingFactory = ^TVTable_ImagingFactory;
+ TVTable_ImagingFactory = record
+ { IUnknown }
+ QueryInterface: Pointer;
+ AddRef: function(Self: Pointer): Cardinal; stdcall;
+ Release: function(Self: Pointer): Cardinal; stdcall;
+ { ImagingFactory }
+ CreateDecoderFromFilename: Pointer;
+ CreateDecoderFromStream: Pointer;
+ CreateDecoderFromFileHandle: Pointer;
+ CreateComponentInfo: Pointer;
+ CreateDecoder: Pointer;
+ CreateEncoder: Pointer;
+ CreatePalette: Pointer;
+ CreateFormatConverter: Pointer;
+ CreateBitmapScaler: Pointer;
+ CreateBitmapClipper: Pointer;
+ CreateBitmapFlipRotator: Pointer;
+ CreateStream: Pointer;
+ CreateColorContext: Pointer;
+ CreateColorTransformer: Pointer;
+ CreateBitmap: Pointer;
+ CreateBitmapFromSource: Pointer;
+ CreateBitmapFromSourceRect: Pointer;
+ CreateBitmapFromMemory: Pointer;
+ CreateBitmapFromHBITMAP: Pointer;
+ CreateBitmapFromHICON: function(Self: Pointer; hIcon: Windows.HICON; var foo: Pointer): HResult; stdcall;
+ { rest ommited }
+ end;
+
+ PImageFactory_Interface = ^TImageFactory_Interface;
+ TImageFactory_Interface = record
+ ptrVTable: PVTable_ImagingFactory;
+ end;
+
+ function ARGB_GetWorker: PImageFactory_Interface;
+
+ function ARGB_BitmapFromIcon(Factory: PImageFactory_Interface; hdc: Windows.HDC; hIcon: HICON): HBitmap;
+
+implementation
+
+ {$define SHLCOM}
+ {$define COM_STRUCTS}
+ {$define COMAPI}
+ {$include shlc.inc}
+ {$undef SHLCOM}
+ {$undef COM_STRUCTS}
+ {$undef COMAPI}
+
+ {
+ The following implementation has been ported from:
+
+ http://web.archive.org/web/20080121112802/http://shellrevealed.com/blogs/shellblog/archive/2007/02/06/Vista-Style-Menus_2C00_-Part-1-_2D00_-Adding-icons-to-standard-menus.aspx
+
+ It uses WIC (Windows Imaging Codec) to convert the given Icon into a bitmap in ARGB format, this is required
+ by Windows for use as an icon (but in bitmap format), so that Windows draws everything (including theme)
+ so we don't have to.
+
+ Why didn't they just do this themselves? ...
+ }
+
+ {
+ The object returned from this function has to be released using the QI COM interface, don't forget.
+ Note this function won't work on anything where WIC isn't installed (XP can have it installed, but not by default)
+ anything less won't work.
+ }
+ function ARGB_GetWorker: PImageFactory_Interface;
+ var
+ hr: HRESULT;
+ begin
+ hr := CoCreateInstance(CLSID_WICImagingFactory, nil, CLSCTX_INPROC_SERVER, IID_WICImagingFactory, Result);
+ end;
+
+ function ARGB_BitmapFromIcon(Factory: PImageFactory_Interface; hdc: Windows.HDC; hIcon: HICON): HBitmap;
+ var
+ bmi: BITMAPINFO;
+ hr: HRESULT;
+ bitmap: PWICBitmap_Interface;
+ cx, cy: LongInt;
+ pbBuffer: PByte;
+ hBmp: HBITMAP;
+ cbStride, cbBuffer: LongInt;
+ begin
+ { This code gives an icon to WIC and gets a bitmap object in return, it then creates a DIB section
+ which is 32bits and the same H*W as the icon. It then asks the bitmap object to copy itself into the DIB }
+ Result := 0;
+ ZeroMemory(@bmi, sizeof(bmi));
+ bmi.bmiHeader.biSize := sizeof(BITMAPINFOHEADER);
+ bmi.bmiHeader.biPlanes := 1;
+ bmi.bmiHeader.biCompression := BI_RGB;
+
+ bmi.bmiHeader.biBitCount := 32;
+
+ hr := factory^.ptrVTable^.CreateBitmapFromHICON(factory, hIcon, bitmap);
+ if hr = S_OK then
+ begin
+ hr := bitmap^.ptrVTable^.GetSize(bitmap, cx, cy);
+ if hr = S_OK then
+ begin
+
+ bmi.bmiHeader.biWidth := cx;
+ bmi.bmiHeader.biHeight := -cy;
+
+ hBmp := CreateDIBSection(hdc, bmi, DIB_RGB_COLORS, pbBuffer, 0, 0);
+ if hBmp <> 0 then
+ begin
+ cbStride := cx * sizeof(DWORD); // ARGB = DWORD
+ cbBuffer := cy * cbStride;
+ // note: the pbBuffer memory is owned by the DIB and will be freed when the bitmap is released
+ hr := bitmap^.ptrVTable^.CopyPixels(bitmap, nil, cbStride, cbBuffer, pbBuffer);
+ if hr = S_OK then
+ begin
+ Result := hBmp;
+ end else begin
+ // the copy failed, delete the DIB
+ DeleteObject(hBmp);
+ end;
+ end;
+ end;
+ // release the bitmap object now
+ bitmap^.ptrVTable^.Release(bitmap);
+ bitmap := nil;
+ end;
+
+ end;
+
+end
+. \ No newline at end of file
diff --git a/plugins/ShlExt/shlipc.pas b/plugins/ShlExt/shlipc.pas
new file mode 100644
index 0000000000..377a82f294
--- /dev/null
+++ b/plugins/ShlExt/shlipc.pas
@@ -0,0 +1,369 @@
+unit shlIPC;
+
+interface
+
+uses
+
+ m_globaldefs, Windows;
+
+const
+
+ REPLY_FAIL = $88888888;
+ REPLY_OK = $00000000;
+
+ REQUEST_ICONS = 1;
+ REQUEST_GROUPS = (REQUEST_ICONS) shl 1;
+ REQUEST_CONTACTS = (REQUEST_GROUPS) shl 1;
+ REQUEST_XFRFILES = (REQUEST_CONTACTS) shl 1;
+ REQUEST_NEWICONS = (REQUEST_XFRFILES) shl 1;
+ REQUEST_CLEARMRU = (REQUEST_NEWICONS) shl 1;
+
+ ICONS_NOTIMPL = $00000008;
+ GROUPS_NOTIMPL = $00000080;
+ CONTACTS_NOTIMPL = $00000800;
+
+ STATUS_PROFILENAME = 2;
+
+
+ // there maybe more than one reason why any request type wasn't returned
+
+type
+
+ { this can be a group entry, if it is, hContact = <index>
+ the string contains the full group path }
+
+ PSlotIPC = ^TSlotIPC;
+ TSlotIPC = packed record
+ cbSize: Byte;
+ fType: int; // a REQUEST_* type
+ Next: PSlotIPC;
+ hContact: THandle;
+ hProto: Cardinal; // hash of the protocol the user is on
+ hGroup: Cardinal; // hash of the entire path (not defined for REQUEST_GROUPS slots)
+ Status: Word; // only used for contacts -- can be STATUS_PROFILENAME -- but that is because returning the profile name is optional
+ MRU: Byte; // if set, contact has been recently used
+ cbStrSection: int;
+ end;
+
+ // if the slot contains a nickname, after the NULL, there is another NULL or a group path string
+
+ PSlotProtoIcons = ^TSlotProtoIcons;
+ TSlotProtoIcons = packed record
+ pid: Cardinal; // pid of Miranda this protocol was on
+ hProto: Cardinal; // hash of the protocol
+ hIcons: array[0..9] of HICON; // each status in order of ID_STATUS_*
+ hBitmaps: array[0..9] of HBITMAP; // each status "icon" as a bitmap
+ end;
+ TSlotProtoIconsArray=array[0..0] of TSlotProtoIcons;
+ // the process space the thread is running in WILL use a different mapping
+ // address than the client's process space, addresses need to be adjusted
+ // to the client's process space.. this is done by the following means :
+
+ //
+ // new_addr := (old_address - serverbase) + client base
+ //
+ // this isn't the best of solutions, the link list should be a variant array
+ // without random access, which would mean each element's different
+ // size would need to be computed each time it is accessed or read past
+
+ PHeaderIPC = ^THeaderIPC;
+ THeaderIPC = record
+ cbSize: Cardinal;
+ dwVersion: Cardinal;
+ pServerBaseAddress: Pointer;
+ pClientBaseAddress: Pointer;
+ fRequests: Cardinal;
+ dwFlags: Cardinal;
+ Slots: Cardinal;
+ Param: Cardinal;
+ SignalEventName: array[0..63] of Char;
+ // Translate() won't work via Explorer
+ MirandaName: array[0..63] of Char;
+ MRUMenuName: array[0..63] of Char; // for the MRU menu itself
+ ClearEntries: array[0..63] of Char; // for the "clear entries"
+ IconsBegin: PSlotIPC;
+ ContactsBegin: PSlotIPC;
+ GroupsBegin: PSlotIPC;
+ NewIconsBegin: PSlotIPC;
+ // start of an flat memory stack, which is referenced as a linked list
+ DataSize: int;
+ DataPtr: PSlotIPC;
+ DataPtrEnd: PSlotIPC;
+ DataFramePtr: Pointer;
+ end;
+
+ const HIPC_NOICONS = 1;
+
+ procedure ipcPrepareRequests(ipcPacketSize: int; pipch: PHeaderIPC; fRequests: Cardinal);
+ function ipcSendRequest(hSignal, hWaitFor: THandle; pipch: PHeaderIPC; dwTimeoutMsecs: DWORD): Cardinal;
+ function ipcAlloc(pipch: PHeaderIPC; nSize: Integer): PSlotIPC;
+ procedure ipcFixupAddresses(FromServer: LongBool; pipch: PHeaderIPC);
+
+type
+
+ TStrTokRec = record
+ szStr: PChar;
+ szSet: set of Char;
+ // need a delimiter after the token too?, e.g. FOO^BAR^ if FOO^BAR
+ // is the string then only FOO^ is returned, could cause infinite loops
+ // if the condition isn't accounted for thou.
+ bSetTerminator: Boolean;
+ end;
+
+ function StrTok(var strr: TStrTokRec): PChar;
+
+type
+
+ PGroupNode = ^TGroupNode;
+ TGroupNode = record
+ Left, Right, _prev, _next: PGroupNode;
+ Depth: Cardinal;
+ Hash: Cardinal; // hash of the group name alone
+ szGroup: PChar;
+ cchGroup: Integer;
+ hMenu: THandle;
+ hMenuGroupID: Integer;
+ dwItems: Cardinal;
+ end;
+
+ PGroupNodeList = ^TGroupNodeList;
+ TGroupNodeList = record
+ First, Last: PGroupNode;
+ end;
+
+ function AllocGroupNode(list: PGroupNodeList; Root: PGroupNode; Depth: Integer): PGroupNode;
+ function FindGroupNode(P: PGroupNode; const Hash, Depth: Integer): PGroupNode;
+
+type
+
+ // a contact can never be a submenu too.
+ TSlotDrawType = (dtEntry, dtGroup, dtContact, dtCommand);
+ TSlotDrawTypes = set of TSlotDrawType;
+
+ PMenuDrawInfo = ^TMenuDrawInfo;
+
+ TMenuCommandCallback = function(
+ pipch: PHeaderIPC; // IPC header info, already mapped
+ hWorkThreadEvent: THandle; // event object being waited on on miranda thread
+ hAckEvent: THandle; // ack event object that has been created
+ psd: PMenuDrawInfo // command/draw info
+ ): Integer; stdcall;
+
+ TMenuDrawInfo = record
+ szText: PChar;
+ szProfile: PChar;
+ cch: Integer;
+ wID: Integer; // should be the same as the menu item's ID
+ fTypes: TSlotDrawTypes;
+ hContact: THandle;
+ hStatusIcon: THandle; // HICON from Self^.ProtoIcons[index].hIcons[status]; Do not DestroyIcon()
+ hStatusBitmap: THandle; // HBITMAP, don't free.
+ pid: Integer;
+ MenuCommandCallback: TMenuCommandCallback; // dtCommand must be set also.
+ end;
+
+
+
+implementation
+
+ {$include m_helpers.inc}
+
+ function FindGroupNode(P: PGroupNode; const Hash, Depth: Integer): PGroupNode;
+ begin
+ Result := P;
+ while Result <> nil do
+ begin
+ if (Result^.Hash = Hash) and (Result^.Depth = Depth) then Exit;
+ If Result^.Left <> nil then
+ begin
+ P := Result;
+ Result := FindGroupNode(Result^.Left, Hash, Depth);
+ If Result <> nil then Exit;
+ Result := P;
+ end;
+ Result := Result^.Right;
+ end; //while
+ end;
+
+ function AllocGroupNode(list: PGroupNodeList; Root: PGroupNode; Depth: Integer): PGroupNode;
+ begin
+ New(Result);
+ Result^.Left := nil;
+ Result^.Right := nil;
+ Result^.Depth := Depth;
+ if Depth > 0 then
+ begin
+ if root^.left = nil then root^.left := Result
+ else begin
+ root := root^.left;
+ while root^.right <> nil do root := root^.right;
+ root^.right := Result;
+ end;
+ end else
+ begin
+ if list^.first = nil then list^.first := Result;
+ if list^.last <> nil then list^.last^.right := Result;
+ list^.last := Result;
+ end; //if
+ end;
+
+ procedure ipcPrepareRequests(ipcPacketSize: int; pipch: PHeaderIPC; fRequests: Cardinal);
+ begin
+ // some fields may already have values like the event object name to open
+ pipch^.cbSize := sizeof(THeaderIPC);
+ pipch^.dwVersion := PLUGIN_MAKE_VERSION(2,0,1,2);
+ pipch^.dwFlags := 0;
+ pipch^.pServerBaseAddress := nil;
+ pipch^.pClientBaseAddress := pipch;
+ pipch^.fRequests := fRequests;
+ pipch^.Slots := 0;
+ pipch^.IconsBegin := nil;
+ pipch^.ContactsBegin := nil;
+ pipch^.GroupsBegin := nil;
+ pipch^.NewIconsBegin := nil;
+ pipch^.DataSize := ipcPacketSize - pipch^.cbSize;
+ // the server side will adjust these pointers as soon as it opens
+ // the mapped file to it's base address, these are set 'ere because ipcAlloc()
+ // maybe used on the client side and are translated by the server side.
+ // ipcAlloc() is used on the client side when transferring filenames
+ // to the ST thread.
+ Integer(pipch^.DataPtr) := Integer(pipch) + sizeof(THeaderIPC);
+ Integer(pipch^.DataPtrEnd) := Integer(pipch^.DataPtr) + pipch^.DataSize;
+ pipch^.DataFramePtr := pipch^.DataPtr;
+ // fill the data area
+ FillChar(pipch^.DataPtr^, pipch^.DataSize, 0);
+ end;
+
+ function ipcSendRequest(hSignal, hWaitFor: THandle; pipch: PHeaderIPC; dwTimeoutMsecs: DWORD): Cardinal;
+ begin
+ { signal ST to work }
+ SetEvent(hSignal);
+ { wait for reply, it should open a handle to hWaitFor... }
+ while True do
+ begin
+ Result := WaitForSingleObjectEx(hWaitFor, dwTimeoutMsecs, True);
+ if Result = WAIT_OBJECT_0 then
+ begin
+ Result := pipch^.fRequests; break;
+ end else if Result = WAIT_IO_COMPLETION then
+ begin
+ (* APC call... *)
+ end else begin
+ Result := REPLY_FAIL; break;
+ end; //if
+ end; //while
+ end;
+
+ function ipcAlloc(pipch: PHeaderIPC; nSize: Integer): PSlotIPC;
+ var
+ PSP: int;
+ begin
+ Result := nil;
+ { nSize maybe zero, in that case there is no string section --- }
+ PSP := int( pipch^.DataFramePtr ) + sizeof(TSlotIPC) + nSize;
+ { is it past the end? }
+ If PSP >= int(pipch^.DataPtrEnd) then Exit;
+ { return the pointer }
+ Result := pipch^.DataFramePtr;
+ { set up the item }
+ Result^.cbSize := sizeof(TSlotIPC);
+ Result^.cbStrSection := nSize;
+ { update the frame ptr }
+ pipch^.DataFramePtr := Pointer(PSP);
+ { let this item jump to the next yet-to-be-allocated-item which should be null anyway }
+ Result^.Next := Pointer(PSP);
+ end;
+
+ procedure ipcFixupAddresses(FromServer: LongBool; pipch: PHeaderIPC);
+ var
+ pct: PSlotIPC;
+ q: ^PSlotIPC;
+ iServerBase: Integer;
+ iClientBase: Integer;
+ begin
+ if pipch^.pServerBaseAddress = pipch^.pClientBaseAddress then Exit;
+ iServerBase := Integer(pipch^.pServerBaseAddress);
+ iClientBase := Integer(pipch^.pClientBaseAddress);
+ // fix up all the pointers in the header
+ if pipch^.iconsBegin <> nil then
+ begin
+ Integer(pipch^.IconsBegin) := (Integer(pipch^.IconsBegin) - iServerBase) + iClientBase;
+ end; //if
+ if pipch^.contactsBegin <> nil then
+ begin
+ Integer(pipch^.ContactsBegin) := (Integer(pipch^.ContactsBegin) - iServerBase) + iClientBase;
+ end; //if
+ if pipch^.groupsBegin <> nil then
+ begin
+ Integer(pipch^.GroupsBegin) := (Integer(pipch^.GroupsBegin) - iServerBase) + iClientBase;
+ end; //if
+ if pipch^.NewIconsBegin <> nil then
+ begin
+ Integer(pipch^.NewIconsBegin) := (Integer(pipch^.NewIconsBegin) - iServerBase) + iClientBase;
+ end;
+ Integer(pipch^.DataPtr) := (Integer(pipch^.DataPtr) - iServerBase) + iClientBase;
+ Integer(pipch^.DataPtrEnd) := (Integer(pipch^.DataPtrEnd) - iServerBase) + iClientBase;
+ Integer(pipch^.DataFramePtr) := (Integer(pipch^.DataFramePtr) - iServerBase) + iClientBase;
+ // and the link list
+ pct := pipch^.DataPtr;
+ while (pct <> nil) do
+ begin
+ // the first pointer is already fixed up, have to get a pointer
+ // to the next pointer and modify where it jumps to
+ q := @pct^.Next;
+ if q^ <> nil then
+ begin
+ Integer(q^) := (Integer(q^) - iServerBase) + iClientBase;
+ end; //if
+ pct := q^;
+ end; //while
+ end;
+
+ function StrTok(var strr: TStrTokRec): PChar;
+ begin
+ Result := nil;
+ { don't allow #0's in sets or null strings }
+ If (strr.szStr = nil) or (#0 in strr.szSet) then Exit;
+ { strip any leading delimiters }
+ while strr.szStr^ in strr.szSet do Inc(strr.szStr);
+ { end on null? full of delimiters }
+ If strr.szStr^ = #0 then
+ begin
+ // wipe out the pointer
+ strr.szStr := nil;
+ Exit;
+ end;
+ { store the start of the token }
+ Result := strr.szStr;
+ { process til start of another delim }
+ while not (strr.szStr^ in strr.szSet) do
+ begin
+ { don't process past the real null, is a delimter required to cap the token? }
+ If strr.szStr^ = #0 then Break;
+ Inc(strr.szStr);
+ end;
+ { if we end on a null stop reprocessin' }
+ If strr.szStr^ = #0 then
+ begin
+ // no more tokens can be read
+ strr.szStr := nil;
+ // is a ending delimiter required?
+ If strr.bSetTerminator then
+ begin
+ // rollback
+ strr.szStr := Result;
+ Result := nil;
+ end;
+ //
+ end else
+ begin
+ { mark the end of the token, may AV if a constant pchar is passed }
+ strr.szStr^ := #0;
+ { skip past this fake null for next time }
+ Inc(strr.szStr);
+ end;
+ end;
+
+end.
+
+
diff --git a/plugins/SmartAutoReplier/ActionsHandler.cpp b/plugins/SmartAutoReplier/ActionsHandler.cpp
new file mode 100644
index 0000000000..53bf7d2aea
--- /dev/null
+++ b/plugins/SmartAutoReplier/ActionsHandler.cpp
@@ -0,0 +1,31 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "actionshandler.h"
+
+CActionsHandler::CActionsHandler(void)
+{
+}
+
+CActionsHandler::~CActionsHandler(void)
+{
+}
diff --git a/plugins/SmartAutoReplier/ActionsHandler.h b/plugins/SmartAutoReplier/ActionsHandler.h
new file mode 100644
index 0000000000..cb2e996111
--- /dev/null
+++ b/plugins/SmartAutoReplier/ActionsHandler.h
@@ -0,0 +1,30 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+/// manager that executes actions...
+class CActionsHandler
+{
+public:
+ CActionsHandler(void);
+ ~CActionsHandler(void);
+};
diff --git a/plugins/SmartAutoReplier/AggressiveOptimize.h b/plugins/SmartAutoReplier/AggressiveOptimize.h
new file mode 100644
index 0000000000..076d96d920
--- /dev/null
+++ b/plugins/SmartAutoReplier/AggressiveOptimize.h
@@ -0,0 +1,59 @@
+
+//////////////////////////////
+// Version 1.10
+// Jan 23rd, 2000
+// Version 1.00
+// May 20th, 1999
+// Todd C. Wilson, Fresh Ground Software
+// (todd@nopcode.com)
+// This header file will kick in settings for Visual C++ 5 and 6 that will (usually)
+// result in smaller exe's.
+// The "trick" is to tell the compiler to not pad out the function calls; this is done
+// by not using the /O1 or /O2 option - if you do, you implicitly use /Gy, which pads
+// out each and every function call. In one single 500k dll, I managed to cut out 120k
+// by this alone!
+// The other two "tricks" are telling the Linker to merge all data-type segments together
+// in the exe file. The relocation, read-only (constants) data, and code section (.text)
+// sections can almost always be merged. Each section merged can save 4k in exe space,
+// since each section is padded out to 4k chunks. This is very noticable with smaller
+// exes, since you could have only 700 bytes of data, 300 bytes of code, 94 bytes of
+// strings - padded out, this could be 12k of runtime, for 1094 bytes of stuff!
+// Note that if you're using MFC static or some other 3rd party libs, you may get poor
+// results with merging the readonly (.rdata) section - the exe may grow larger.
+// To use this feature, define _MERGE_DATA_ in your project or before this header is used.
+// With Visual C++ 5, the program uses a file alignement of 512 bytes, which results
+// in a small exe. Under VC6, the program instead uses 4k, which is the same as the
+// section size. The reason (from what I understand) is that 4k is the chunk size of
+// the virtual memory manager, and that WinAlign (an end-user tuning tool for Win98)
+// will re-align the programs on this boundary. The problem with this is that all of
+// Microsoft's system exes and dlls are not tuned like this, and using 4k causes serious
+// exe bloat. Very noticable for smaller programs.
+// The "trick" for this is to use the undocumented FILEALIGN linker parm to change the
+// padding from 4k to 1/2k, which results in a much smaller exe - anywhere from 20%-75%
+// depending on the size.
+
+
+#ifdef NDEBUG
+#pragma message( "Using AggressiveOptimise" )
+// /Og (global optimizations), /Os (favor small code), /Oy (no frame pointers)
+#pragma optimize("gsy",on)
+
+#pragma comment(linker,"/RELEASE")
+
+// Note that merging the .rdata section will result in LARGER exe's if you using
+// MFC (esp. static link). If this is desirable, define _MERGE_RDATA_ in your project.
+#ifdef _MERGE_RDATA_
+#pragma comment(linker,"/merge:.rdata=.data")
+#endif // _MERGE_RDATA_
+
+#pragma comment(linker,"/merge:.text=.data")
+//#pragma comment(linker,"/merge:.reloc=.data")
+
+#if _MSC_VER >= 1000
+// Only supported/needed with VC6; VC5 already does 0x200 for release builds.
+// Totally undocumented! And if you set it lower than 512 bytes, the program crashes.
+// Either leave at 0x200 or 0x1000
+#pragma comment(linker,"/FILEALIGN:0x200")
+#endif // _MSC_VER >= 1000
+
+#endif // NDEBUG
diff --git a/plugins/SmartAutoReplier/Crc32Static.cpp b/plugins/SmartAutoReplier/Crc32Static.cpp
new file mode 100644
index 0000000000..89646ec0bb
--- /dev/null
+++ b/plugins/SmartAutoReplier/Crc32Static.cpp
@@ -0,0 +1,139 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "Crc32Static.h"
+
+// Static CRC table
+DWORD CCrc32Static::s_arrdwCrc32Table[256] =
+{
+ 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
+ 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
+ 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
+ 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
+ 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
+ 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
+ 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
+ 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
+ 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
+ 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
+ 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
+ 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
+ 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
+ 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
+ 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
+ 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
+
+ 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
+ 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
+ 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
+ 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
+ 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
+ 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
+ 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
+ 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
+ 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
+ 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
+ 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
+ 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
+ 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
+ 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
+ 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
+ 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
+
+ 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
+ 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
+ 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
+ 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
+ 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
+ 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
+ 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
+ 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
+ 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
+ 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
+ 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
+ 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
+ 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
+ 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
+ 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
+ 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
+
+ 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
+ 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
+ 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
+ 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
+ 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
+ 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
+ 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
+ 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
+ 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
+ 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
+ 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
+ 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
+ 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
+ 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
+ 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
+ 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D,
+};
+
+/// ctor
+CCrc32Static::CCrc32Static()
+{
+}
+
+/// dtor
+CCrc32Static::~CCrc32Static()
+{
+}
+
+/// calculating crc32
+inline void CCrc32Static::CalcCrc32(const BYTE byte, DWORD &dwCrc32)
+{
+ dwCrc32 = ((dwCrc32) >> 8) ^ s_arrdwCrc32Table[(byte) ^ ((dwCrc32) & 0x000000FF)];
+}
+
+/// getting crc32 for a string
+DWORD CCrc32Static::StringCrc32(LPCTSTR szString, DWORD &dwCrc32)
+{
+ _ASSERTE(szString);
+
+ DWORD dwErrorCode = NO_ERROR;
+
+ dwCrc32 = 0xFFFFFFFF;
+
+ try
+ {
+ while(*szString != _T('\0'))
+ {
+ CalcCrc32((BYTE)*szString, dwCrc32);
+ szString++;
+ }
+ }
+ catch(...)
+ {
+ // An unknown exception happened
+ dwErrorCode = ERROR_CRC;
+ }
+
+ dwCrc32 = ~dwCrc32;
+
+ return dwErrorCode;
+}
diff --git a/plugins/SmartAutoReplier/Crc32Static.h b/plugins/SmartAutoReplier/Crc32Static.h
new file mode 100644
index 0000000000..4039822cae
--- /dev/null
+++ b/plugins/SmartAutoReplier/Crc32Static.h
@@ -0,0 +1,33 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+class CCrc32Static
+{
+public:
+ CCrc32Static();
+ virtual ~CCrc32Static();
+ static DWORD StringCrc32(LPCTSTR szString, DWORD &dwCrc32);
+protected:
+ static inline void CalcCrc32(const BYTE byte, DWORD &dwCrc32);
+ static DWORD s_arrdwCrc32Table[256];
+};
diff --git a/plugins/SmartAutoReplier/CrushLog.cpp b/plugins/SmartAutoReplier/CrushLog.cpp
new file mode 100644
index 0000000000..639e4965ff
--- /dev/null
+++ b/plugins/SmartAutoReplier/CrushLog.cpp
@@ -0,0 +1,165 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "crushlog.h"
+#include "shlobj.h"
+
+extern HINSTANCE hInst;
+extern CCrushLog CRUSHLOGOBJ;
+
+/// init static members
+TCHAR CCrushLog::m_szLogPath[MAX_PATH] = {0};
+CRITICAL_SECTION CCrushLog::m_critSect;
+
+/// ctor
+CCrushLog::CCrushLog(void)
+{/// nothing for now
+BEGIN_PROTECT_AND_LOG_CODE
+END_PROTECT_AND_LOG_CODE
+}
+
+/// d'ctor
+CCrushLog::~CCrushLog(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+END_PROTECT_AND_LOG_CODE
+}
+
+/// deinit internal data...
+void CCrushLog::DeInit(void)
+{
+ DeleteCriticalSection(&m_critSect);
+}
+
+/// init internal data...
+void CCrushLog::Init(void)
+{
+ HRESULT hr = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, m_szLogPath);
+ size_t nLen = _tcslen(m_szLogPath);
+
+ if (m_szLogPath[nLen - 1] != TEXT('\\'))
+ {
+ _tcscat(m_szLogPath, TEXT("\\Sar\\"));
+ }
+ else
+ {
+ _tcscat(m_szLogPath, TEXT("Sar\\"));
+ }
+
+ CreateDirectory(m_szLogPath, NULL);
+
+ _tcscat(m_szLogPath, LOG_FILENAME);
+
+ /*if (_tcslen(m_szLogPath) == 0) /// let's get path to log file
+ {
+ GetModuleFileName(hInst, m_szLogPath, sizeof(m_szLogPath) * sizeof(TCHAR));
+
+ TCHAR *ptrPos = _tcsrchr(m_szLogPath, '\\');
+ if (ptrPos)
+ {
+ ptrPos++;
+ _tcscpy(ptrPos, LOG_FILENAME);
+ }
+ else
+ {
+ _RPT0(_CRT_WARN, "CCrushLog::CCrushLog - unable to form path");
+ }
+ }*/
+
+ InitializeCriticalSection(&m_critSect);
+}
+
+/// provides forming data struct and saving it to log
+void CCrushLog::InternalProtect(CHAR* FunctionName, CHAR* FileName,
+ CHAR* CompilationDate, INT LineNumber,
+ INT LastError)
+{
+ CRUSHLOG_ITEM item = {0};
+
+ item.CompilationDate = CompilationDate;
+ item.FileName = FileName;
+ item.FunctionName = FunctionName;
+ item.LineNumber = LineNumber;
+ item.LastError = LastError;
+ g_crushLog.SaveToLog(item);
+
+ TCHAR tch[MAX_PATH * 3] = {0};
+ _tcscpy(tch, TranslateTS(TEXT("Exception has occured please, analize or just send log file\n\r ")));
+ _tcscat(tch, CCrushLog::m_szLogPath);
+ _tcscat(tch, TranslateTS(TEXT("\r\n to developer.")));
+
+ ::MessageBox (NULL, tch, TranslateTS(TEXT("Smart Auto Replier crash. Send the log file to http://shcherbyna.com/forum/viewforum.php?f=8")), MB_OK);
+}
+
+/// saving log information
+void CCrushLog::SaveToLog(CRUSHLOG_ITEM & item)
+{
+ EnterCriticalSection(&m_critSect);
+
+ HANDLE hFile = NULL;
+ hFile = CreateFile (m_szLogPath, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+
+ if (hFile == INVALID_HANDLE_VALUE)
+ {
+ LeaveCriticalSection(&m_critSect);
+
+ return;
+ }
+
+ {
+ DWORD dwRetVal = 0;
+ DWORD dw = GetFileSize(hFile, &dwRetVal);
+ SetFilePointer(hFile, dw, NULL, FILE_BEGIN);
+ }
+
+ int nSize = strlen(item.CompilationDate);
+ nSize += strlen(item.FileName);
+ nSize += strlen(item.FunctionName);
+ nSize *= 2;
+
+ CHAR *tsz = new CHAR[nSize];
+
+ if (tsz)
+ {
+ strcpy(tsz, ("******\n"));
+ strcat(tsz, item.CompilationDate);
+ strcat(tsz, ("\n"));
+ strcat(tsz, item.FileName);
+ strcat(tsz, ("\n"));
+ strcat(tsz, item.FunctionName);
+ strcat(tsz, ("\n"));
+ CHAR tchtemp[MAX_PATH] = {0};
+ itoa(item.LineNumber, tchtemp, 10);
+ strcat(tsz, tchtemp);
+ strcat(tsz, ("\n"));
+ itoa(item.LastError, tchtemp, 10);
+ strcat(tsz, tchtemp);
+ strcat(tsz, ("\n"));
+ DWORD dw = 0;
+ WriteFile (hFile, tsz, strlen(tsz), &dw, NULL);
+
+ delete tsz;
+ }
+
+ CloseHandle (hFile);
+ LeaveCriticalSection(&m_critSect);
+}
diff --git a/plugins/SmartAutoReplier/CrushLog.h b/plugins/SmartAutoReplier/CrushLog.h
new file mode 100644
index 0000000000..1a595d055b
--- /dev/null
+++ b/plugins/SmartAutoReplier/CrushLog.h
@@ -0,0 +1,54 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+/// crash item that is written in file...
+typedef struct _CRUSHLOG_ITEM
+{
+ CHAR* CompilationDate; /// compilation date of the source file
+ CHAR* FileName; /// file name where exception has occured
+ CHAR* FunctionName; /// function name where exception has occured
+ INT LineNumber; /// line number
+ INT LastError; /// last error
+}CRUSHLOG_ITEM, *PCRUSHLOG_ITEM;
+
+#define LOG_FILENAME TEXT("sarcrushes.log")
+
+/// class that handles all crushes
+/// occured between BEGIN_LOG_AND_PRO.. and END_LOG..
+class CCrushLog
+{
+public: /// ctors, dtors section...
+ CCrushLog(void);
+ ~CCrushLog(void);
+public:
+ static void Init(void); /// inits internal data..
+ static void DeInit(void); /// deinits internal data..
+ static void SaveToLog(CRUSHLOG_ITEM & item); /// saves data to log file
+ static void InternalProtect(CHAR* FunctionName, CHAR* FileName,
+ CHAR* CompilationDate, INT LineNumber,
+ INT LastError);
+public:
+ static TCHAR m_szLogPath[MAX_PATH]; /// path to log file
+private:
+ static CRITICAL_SECTION m_critSect; /// sync object...
+};
diff --git a/plugins/SmartAutoReplier/GUI/AddRuleDlg.cpp b/plugins/SmartAutoReplier/GUI/AddRuleDlg.cpp
new file mode 100644
index 0000000000..0d76db3210
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/AddRuleDlg.cpp
@@ -0,0 +1,219 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "../resource.h"
+#include "addruledlg.h"
+#include "addruledlg.h"
+#include "selectuserdlg.h"
+
+extern LPTSTR g_strPluginName;
+extern CMessagesHandler *g_pMessHandler;
+extern CCrushLog CRUSHLOGOBJ;
+
+CAddRuleDlg::CAddRuleDlg(void) : m_dwCRC32(NULL), m_baur2thisMode(false), m_bEditing(false)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ ZeroMemory(&m_item, sizeof(m_item));
+END_PROTECT_AND_LOG_CODE
+}
+
+CAddRuleDlg::~CAddRuleDlg(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+END_PROTECT_AND_LOG_CODE
+}
+
+LRESULT CAddRuleDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ TranslateDialogDefault(m_hWnd);
+ m_editRuleName = GetDlgItem(IDC_ED_RULENAME);
+ m_editContactName = GetDlgItem(IDC_ED_RULECNAME);
+ m_editReplyText = GetDlgItem(IDC_ED_RULEREPLY);
+ //m_editReplyAction = GetDlgItem(IDC_ED_RULEACTION);
+ m_btnSelUser = GetDlgItem(IDC_BTN_SELUSER);
+
+ CenterWindow();
+
+ if (m_dwCRC32)
+ {
+ SetWindowText(TranslateTS(TEXT("Edit rule")));
+ m_editRuleName.SetWindowText(m_item.RuleName);
+ m_editContactName.SetWindowText(m_item.ContactName);
+ m_editReplyText.SetWindowText(m_item.ReplyText);
+ //m_editReplyAction.SetWindowText(m_item.ReplyAction);
+ m_bEditing = true;
+ }
+ else if (m_baur2thisMode)
+ {
+ m_editRuleName.SetWindowText(m_item.RuleName);
+ m_editContactName.SetWindowText(m_item.ContactName);
+ m_editReplyText.SetWindowText(m_item.ReplyText);
+ //m_editReplyAction.SetWindowText(m_item.ReplyAction);
+
+ m_btnSelUser.EnableWindow(FALSE);
+ m_editContactName.EnableWindow(FALSE);
+ m_editReplyText.SetSel(0, _tcslen(m_item.ReplyText), FALSE);
+ m_editReplyText.SetFocus();
+ }
+ else
+ {
+ m_editRuleName.SetWindowText(SETTINGS_DEF_RULE_NAME);
+ m_editReplyText.SetWindowText(SETTINGS_DEF_MESSAGE_RULE);
+ }
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT CAddRuleDlg::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return FALSE;
+END_PROTECT_AND_LOG_CODE
+}
+
+BOOL CAddRuleDlg::PreTranslateMessage(MSG* pMsg)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return FALSE;
+END_PROTECT_AND_LOG_CODE
+}
+
+LRESULT CAddRuleDlg::OnBtnOKClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+#define ON_ERROR_1BYTE(x) if (x == 1) { \
+ MessageBox(TranslateTS(TEXT("Please, specify longer contact name")), g_strPluginName, MB_OK); \
+ return FALSE; }
+
+#define ON_ERROR(x) MessageBox(TranslateTS(x), g_strPluginName, MB_OK); \
+ return FALSE;
+
+ int nLength = m_editRuleName.GetWindowTextLength();
+ if (nLength)
+ {
+ nLength++;
+ m_item.RuleName = new TCHAR[nLength];
+
+ if (m_item.RuleName != NULL)
+ {
+ memset(m_item.RuleName, 0, nLength * sizeof(TCHAR));
+ m_editRuleName.GetWindowText(m_item.RuleName, nLength);
+ }
+ }
+ else
+ {
+ ON_ERROR(TEXT("Please, specify Rule Name"))
+ }
+
+ nLength = m_editContactName.GetWindowTextLength();
+ if (nLength)
+ {
+ ON_ERROR_1BYTE(nLength)
+ nLength++;
+ m_item.ContactName = new TCHAR[nLength];
+
+ if (m_item.ContactName != NULL)
+ {
+ memset(m_item.ContactName, 0, nLength * sizeof(TCHAR));
+ m_editContactName.GetWindowText(m_item.ContactName, nLength);
+ }
+ }
+ else
+ {
+ ON_ERROR(TEXT("Please, specify Contact Name"))
+ }
+
+ nLength = m_editReplyText.GetWindowTextLength();
+ if (nLength)
+ {
+ if (nLength > SETTINGS_MESSAGE_MAXVALENGTH)
+ {
+ MessageBox(TranslateTS(TEXT("header is too big")), g_strPluginName, MB_OK);
+ return FALSE;
+ }
+
+ nLength++;
+ m_item.ReplyText = new TCHAR[nLength];
+
+ if (m_item.ContactName != NULL)
+ {
+ memset(m_item.ReplyText, 0, nLength * sizeof(TCHAR));
+ m_editReplyText.GetWindowText(m_item.ReplyText, nLength);
+ }
+ }
+ else
+ {
+ ON_ERROR(TEXT("Please, specify Reply Text"))
+ }
+
+ {
+ if (m_bEditing)
+ {/// delete prev item from storage...
+ g_pMessHandler->getSettings().getStorage().RemReplyAction(m_dwCRC32);
+ }
+
+ bool b;
+ DWORD dwCrc = g_pMessHandler->getSettings().AddReplyAction(m_item, b);
+ if (b)
+ {
+ MessageBox(TranslateTS(TEXT("Rule with the same contact name already exists")), g_strPluginName, MB_OK);
+ return FALSE;
+ }
+
+ m_bAddedOk = ((b == false) && dwCrc);
+ m_dwCRC32 = dwCrc;
+ }
+
+ EndDialog(0);
+#undef ON_ERROR
+#undef ON_ERROR_1BYTE
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT CAddRuleDlg::OnBtnCancelClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_bAddedOk = false;
+ EndDialog(0);
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+LRESULT CAddRuleDlg::OnBnClickedBtnSeluser(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ CSelectUserDlg dlg;
+ dlg.DoModal(m_hWnd);
+ if (dlg.m_bAllOk == true)
+ {
+ m_editContactName.SetWindowText(dlg.m_szRetVal);
+ m_editReplyText.SetFocus();
+ }
+ else
+ {
+ m_editContactName.SetFocus();
+ }
+END_PROTECT_AND_LOG_CODE
+ return 0;
+}
diff --git a/plugins/SmartAutoReplier/GUI/AddRuleDlg.h b/plugins/SmartAutoReplier/GUI/AddRuleDlg.h
new file mode 100644
index 0000000000..d02fde733c
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/AddRuleDlg.h
@@ -0,0 +1,67 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include <commctrl.h>
+#include <atlbase.h>
+#include <atlapp.h>
+#include <atlwin.h>
+
+#include "../RuleItem.h"
+
+class CAddRuleDlg : public CDialogImpl<CAddRuleDlg>, public CMessageFilter
+{
+public:
+ CAddRuleDlg(void);
+ virtual ~CAddRuleDlg(void);
+public:
+ enum {IDD = IDD_ADDRULE_DLG};
+ BEGIN_MSG_MAP(COptionsDlg)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+
+ COMMAND_ID_HANDLER(IDOK, OnBtnOKClicked)
+ COMMAND_ID_HANDLER(IDCANCEL, OnBtnCancelClicked)
+ COMMAND_HANDLER(IDC_BTN_SELUSER, BN_CLICKED, OnBnClickedBtnSeluser)
+ END_MSG_MAP()
+protected:
+ virtual BOOL PreTranslateMessage(MSG* pMsg);
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnBtnOKClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnBtnCancelClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnBnClickedBtnSeluser(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+protected:
+ CEdit m_editRuleName;
+ CEdit m_editContactName;
+ CEdit m_editReplyText;
+ //CEdit m_editReplyAction;
+ CButton m_btnSelUser;
+public:
+ RULE_ITEM m_item;
+ bool m_bAddedOk;
+ DWORD m_dwCRC32;
+private:
+ bool m_bEditing;
+public:
+ bool m_baur2thisMode;
+};
diff --git a/plugins/SmartAutoReplier/GUI/EditReplyDlg.cpp b/plugins/SmartAutoReplier/GUI/EditReplyDlg.cpp
new file mode 100644
index 0000000000..5dbc6989bc
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/EditReplyDlg.cpp
@@ -0,0 +1,88 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "editreplydlg.h"
+
+extern LPTSTR g_strPluginName;
+
+CEditReplyDlg::CEditReplyDlg(void)
+{
+}
+
+CEditReplyDlg::~CEditReplyDlg(void)
+{
+}
+
+BOOL CEditReplyDlg::PreTranslateMessage(MSG* pMsg)
+{
+ return IsDialogMessage(pMsg);
+}
+
+LRESULT CEditReplyDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+ TranslateDialogDefault(m_hWnd);
+ m_editReplyText = GetDlgItem(IDC_ED_TEXT);
+
+ if (m_commRule.Message)
+ {
+ m_editReplyText.SetWindowText(m_commRule.Message);
+ }
+
+ CenterWindow(GetDesktopWindow());
+
+ return FALSE;
+}
+
+LRESULT CEditReplyDlg::OnBtnOKClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+ int nLength = 0;
+
+ delete m_commRule.Message;
+
+ nLength = m_editReplyText.GetWindowTextLength();
+
+ if (nLength > SETTINGS_MESSAGE_MAXVALENGTH)
+ {
+ MessageBox(TranslateTS(TEXT("message is too big")), g_strPluginName, MB_OK);
+
+ return FALSE;
+ }
+ nLength++;
+ m_commRule.Message = new TCHAR[nLength];
+
+ if (!m_commRule.Message)
+ return FALSE;
+
+ memset(m_commRule.Message, 0, nLength * sizeof(TCHAR));
+ m_editReplyText.GetWindowText((LPTSTR)m_commRule.Message, nLength);
+
+ m_bAllOk = true;
+ EndDialog(1);
+ return FALSE;
+}
+
+LRESULT CEditReplyDlg::OnBtnCancelClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+ m_bAllOk = false;
+ EndDialog(0);
+ return FALSE;
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/GUI/EditReplyDlg.h b/plugins/SmartAutoReplier/GUI/EditReplyDlg.h
new file mode 100644
index 0000000000..0b4a5fb94a
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/EditReplyDlg.h
@@ -0,0 +1,55 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "..\resource.h"
+
+#include <commctrl.h>
+#include <atlbase.h>
+#include <atlapp.h>
+#include <atlwin.h>
+
+class CEditReplyDlg : public CDialogImpl<CEditReplyDlg>, public CMessageFilter
+{
+public:
+ CEditReplyDlg(void);
+ ~CEditReplyDlg(void);
+public:
+ enum {IDD = IDD_SET_AURMESSAGEDLG};
+ BEGIN_MSG_MAP(CEditReplyDlg)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ COMMAND_ID_HANDLER(IDOK, OnBtnOKClicked)
+ COMMAND_ID_HANDLER(IDCANCEL, OnBtnCancelClicked)
+ END_MSG_MAP()
+protected:
+ virtual BOOL PreTranslateMessage(MSG* pMsg);
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnBtnOKClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnBtnCancelClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+public:
+ REPLYER_SETTINGS m_settings;
+ COMMON_RULE_ITEM m_commRule;
+ bool m_bAllOk;
+protected:
+ CEdit m_editReplyText;
+ CEdit m_editReplyHeader;
+};
diff --git a/plugins/SmartAutoReplier/GUI/OptionsDlg.cpp b/plugins/SmartAutoReplier/GUI/OptionsDlg.cpp
new file mode 100644
index 0000000000..1f25812101
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/OptionsDlg.cpp
@@ -0,0 +1,528 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "optionsdlg.h"
+#include "addruledlg.h"
+
+/// need ptr to get/set info
+extern CMessagesHandler *g_pMessHandler;
+extern CCrushLog CRUSHLOGOBJ;
+extern LPTSTR g_strPluginName;
+
+//COptionsDlg g_optionsDlg;
+
+BOOL CALLBACK COptionsDlg::DlgProcCluiOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+
+ /*if (g_optionsDlg.m_bDestroying)
+ return FALSE;
+
+ if (g_optionsDlg.m_hWnd == NULL)
+ g_optionsDlg.Attach(hwndDlg);
+
+ LRESULT lre = {0};
+ DWORD dwId = {0};
+ return g_optionsDlg.ProcessWindowMessage(hwndDlg, msg, wParam, lParam, lre, dwId);*/
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+COptionsDlg::COptionsDlg(void) : m_bShown(false), m_szMessage(NULL)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+///g_optionsDlg.m_bDestroying = false;
+m_bDestroying = false;
+END_PROTECT_AND_LOG_CODE
+}
+
+COptionsDlg::~COptionsDlg(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+END_PROTECT_AND_LOG_CODE
+}
+
+BOOL COptionsDlg::PreTranslateMessage(MSG* pMsg)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return ::IsDialogMessage(m_hWnd, pMsg);
+END_PROTECT_AND_LOG_CODE
+}
+
+/// process OnInitDialog
+LRESULT COptionsDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ TranslateDialogDefault(m_hWnd);
+
+ if (!g_pMessHandler)
+ return FALSE;
+
+ m_listRules = GetDlgItem(IDC_LIST_RULES);
+ m_editReplayDelay = GetDlgItem(IDC_EDIT_REPLAYDELAY);
+// m_editHeaderMessage = GetDlgItem(IDC_EDIT_HEADER);
+ m_editMessageText = GetDlgItem(IDC_EDIT_MESSAGE);
+ m_btnAdd = GetDlgItem(IDC_BTN_ADDRULE);
+ m_btnDel = GetDlgItem(IDC_BTN_DELRULE);
+ m_btnChange = GetDlgItem(IDC_BTN_EDITRULE);
+ m_wndCheckDOnSOn = GetDlgItem(IDC_CHECK_DISABLEWMON);
+ m_wndCheckModeTypes = GetDlgItem(IDC_CH_ENABLE_WSCH);
+ m_cbModeTypes = GetDlgItem(IDC_CB_ENWSC);
+ m_chbShowAurWhmc = GetDlgItem(IDC_CH_SHOWCG);
+ m_cbDisWMBTypes = GetDlgItem(IDC_CB_DWSB);
+ m_chDisWMB = GetDlgItem(IDC_CH_DISWHSB);
+ m_chSaveAURSToHist = GetDlgItem(IDC_CH_SAVE_AURS);
+
+ m_cbModeTypes.AddString(TranslateTS(TEXT("DND/NA/Away/Occupied modes")));
+ m_cbModeTypes.AddString(TranslateTS(TEXT("DND mode")));
+ m_cbModeTypes.AddString(TranslateTS(TEXT("NA mode")));
+ m_cbModeTypes.AddString(TranslateTS(TEXT("Away mode")));
+ m_cbModeTypes.AddString(TranslateTS(TEXT("Occupied mode")));
+
+ m_cbDisWMBTypes.AddString(TranslateTS(TEXT("Online/Free for chat modes")));
+ m_cbDisWMBTypes.AddString(TranslateTS(TEXT("Online mode")));
+ m_cbDisWMBTypes.AddString(TranslateTS(TEXT("Free for chat mode")));
+
+ COMMON_RULE_ITEM & commRules = g_pMessHandler->getSettings().getStorage().getCommonRule();
+ REPLYER_SETTINGS & settings = g_pMessHandler->getSettings().getSettings();
+
+ if (settings.ModeValue > m_cbModeTypes.GetCount())
+ m_cbModeTypes.SetCurSel(0);
+ else
+ m_cbModeTypes.SetCurSel(settings.ModeValue);
+ if (settings.ModeDisValue > m_cbDisWMBTypes.GetCount())
+ m_cbDisWMBTypes.SetCurSel(0);
+ else
+ m_cbDisWMBTypes.SetCurSel(settings.ModeDisValue);
+
+ m_cbDisWMBTypes.EnableWindow(settings.bDisableWhenModeIsSet);
+
+ if (settings.bDisableWhenModeIsSet)
+ {
+ m_chDisWMB.SendMessage(BM_SETCHECK, BST_CHECKED, 0);
+ }
+ else
+ {
+ m_chDisWMB.SendMessage(BM_SETCHECK, BST_UNCHECKED, 0);
+ }
+
+ if (settings.bShowAURDlgWhenModeChanges)
+ {
+ m_chbShowAurWhmc.SendMessage(BM_SETCHECK, BST_CHECKED, 0);
+ }
+ else
+ {
+ m_chbShowAurWhmc.SendMessage(BST_UNCHECKED, BST_CHECKED, 0);
+ }
+
+ if (settings.bEnableWhenModeIsSet)
+ {
+ m_wndCheckModeTypes.SendMessage(BM_SETCHECK, BST_CHECKED, 0);
+ }
+ else
+ {
+ m_wndCheckModeTypes.SendMessage(BST_UNCHECKED, BST_CHECKED, 0);
+ }
+
+ if (settings.bSaveToHistory)
+ {
+ m_chSaveAURSToHist.SendMessage(BM_SETCHECK, BST_CHECKED, 0);
+ }
+ else
+ {
+ m_chSaveAURSToHist.SendMessage(BST_UNCHECKED, BST_CHECKED, 0);
+ }
+
+ m_cbModeTypes.EnableWindow(settings.bEnableWhenModeIsSet);
+
+ int nLength = settings.ReplayDelay;
+ if (nLength == 0)
+ nLength = SETTINGS_DEF_COMMON_VALREPDELAY;
+
+ if (settings.bDisableWhenMirandaIsOn)
+ m_wndCheckDOnSOn.SendMessage(BM_SETCHECK, BST_CHECKED, 0);
+ else
+ m_wndCheckDOnSOn.SendMessage(BM_SETCHECK, BST_UNCHECKED, 0);
+
+ TCHAR strNumber[MAX_PATH] = {0};
+ m_editReplayDelay.SetWindowText(_itot(nLength, strNumber, 10));
+ m_nReplayDelay = nLength;
+
+ TCHAR* str = commRules.Message;
+ m_editMessageText.SetWindowText(str);
+
+ if (m_szMessage)
+ {
+ delete m_szMessage;
+ m_szMessage = NULL;
+ }
+
+ m_szMessage = new TCHAR[SETTINGS_MESSAGE_MAXVALENGTH];
+
+ if (!m_szMessage)
+ return FALSE;
+
+ memset(m_szMessage, 0, SETTINGS_MESSAGE_MAXVALENGTH * sizeof(TCHAR));
+
+ m_editMessageText.GetWindowText(m_szMessage, SETTINGS_MESSAGE_MAXVALENGTH);
+
+ { /// filling listbox with rule names...
+ RulesHash::iterator it;
+ RulesHash & hash = g_pMessHandler->getSettings().getStorage().getHashTable();
+ int nPos = 0;
+
+ bool bAdded = false;
+ for (it = hash.begin(); it != hash.end(); it++)
+ {
+ nPos = m_listRules.AddString(it->second.RuleName);
+ if (nPos != -1)
+ {
+ m_listRules.SetItemData(nPos, it->first);
+ if (!bAdded)
+ bAdded = true;
+ }
+ }
+ if (bAdded)
+ {
+ OnSetSelInRulesList(0);
+ }
+ }
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+/// process WM_DESTROY
+LRESULT COptionsDlg::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_bDestroying = true;
+ ///g_optionsDlg.m_bDestroying = true;
+ ///::DestroyWindow(m_hWnd);
+ ///g_optionsDlg.m_hWnd = NULL;
+ //m_hWnd = NULL;
+ m_szMessage = NULL;
+ // m_bDestroying = false;
+ ///g_optionsDlg.m_bDestroying = false;
+ return FALSE;
+END_PROTECT_AND_LOG_CODE
+}
+
+void COptionsDlg::OnNotifyAboutChanges(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ SendMessage(m_hwndHolder, PSM_CHANGED, 0, 0);
+END_PROTECT_AND_LOG_CODE
+}
+
+/// handler of typing in replay delay edit box
+LRESULT COptionsDlg::OnEditReply(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ if (m_bShown)
+ {
+ m_bShown = false;
+ return FALSE;
+ }
+ TCHAR tch[MAX_PATH] = {0};
+ GetDlgItemText (IDC_EDIT_REPLAYDELAY, tch, sizeof(tch));
+ int nValue = _tstoi(tch);
+
+ if (nValue != m_nReplayDelay)
+ {
+ m_nReplayDelay = nValue;
+ OnNotifyAboutChanges();
+ }
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnNotify(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ switch (((LPNMHDR)lParam)->code)
+ {
+ case PSN_APPLY:
+ { /// apply our changes...
+ REPLYER_SETTINGS sett;
+ COMMON_RULE_ITEM commrule;
+
+ commrule.Message = m_szMessage;
+
+ sett.bEnabled = g_pMessHandler->getSettings().getSettings().bEnabled;
+ sett.ReplayDelay = m_nReplayDelay;
+
+ LRESULT lres = m_wndCheckDOnSOn.SendMessage(BM_GETCHECK, 0, 0);
+ sett.bDisableWhenMirandaIsOn = (lres == BST_CHECKED);
+ lres = m_wndCheckModeTypes.SendMessage(BM_GETCHECK, 0, 0);
+ sett.bEnableWhenModeIsSet = (lres == BST_CHECKED);
+ lres = m_chbShowAurWhmc.SendMessage(BM_GETCHECK, 0, 0);
+ sett.bShowAURDlgWhenModeChanges = (lres == BST_CHECKED);
+ lres = m_chSaveAURSToHist.SendMessage(BM_GETCHECK, 0, 0);
+ sett.bSaveToHistory = (lres == BST_CHECKED);
+ sett.ModeValue = m_cbModeTypes.GetCurSel();
+ lres = m_chDisWMB.SendMessage(BM_GETCHECK, 0, 0);
+ sett.bDisableWhenModeIsSet = (lres == BST_CHECKED);
+ sett.ModeDisValue = m_cbDisWMBTypes.GetCurSel();
+
+ CSettingsHandler & handler = g_pMessHandler->getSettings();
+ handler.setSettings(sett, &commrule);
+ //handler.getStorage().Flush(); /// flush all unflushed rules into hdd
+ }
+ }
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnEditHeader(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnEditMessage(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ if (!m_szMessage)
+ return FALSE;
+
+ int nLength = m_editMessageText.GetWindowTextLength();
+
+ if (nLength > SETTINGS_MESSAGE_MAXVALENGTH)
+ {
+ MessageBox(TranslateTS(TEXT("too big size")), g_strPluginName, MB_OK);
+ m_editMessageText.SetWindowText(m_szMessage);
+
+ return FALSE;
+ }
+ nLength++;
+ LPTSTR str2 = new TCHAR[nLength];
+
+ if (!str2)
+ return FALSE;
+
+ memset(str2, 0, nLength * sizeof(TCHAR));
+ m_editMessageText.GetWindowText(str2, nLength);
+
+ if (_tcscmp(m_szMessage, str2) != 0)
+ {
+ _tcscpy(m_szMessage, str2);
+ OnNotifyAboutChanges();
+ }
+
+ delete str2;
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+void COptionsDlg::OnSetSelInRulesList(int nIndex)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_listRules.SetCurSel(nIndex);
+ BOOL b;
+ OnListBoxSelChanged(0, 0, 0, b);
+END_PROTECT_AND_LOG_CODE
+}
+
+LRESULT COptionsDlg::OnBtnAddRuleClick(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ CAddRuleDlg dlg;
+ dlg.DoModal(m_hWnd, 0);
+ if (dlg.m_bAddedOk)
+ {
+ int npos = m_listRules.AddString(dlg.m_item.RuleName);
+ if (npos != -1)
+ {
+ m_listRules.SetItemData(npos, dlg.m_dwCRC32);
+ OnSetSelInRulesList(npos);
+ OnNotifyAboutChanges();
+ }
+ }
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnBtnEditRuleClick(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ int nIndex = m_listRules.GetCurSel();
+ if (nIndex >= 0)
+ {
+ DWORD dwCrc32 = static_cast<DWORD>(m_listRules.GetItemData(nIndex));
+ if (dwCrc32)
+ {
+ CAddRuleDlg dlgEdit;
+ RulesHash::iterator it;
+ RulesHash & hash = g_pMessHandler->getSettings().getStorage().getHashTable();
+ it = hash.find(dwCrc32);
+ if (it != hash.end())
+ {
+ dlgEdit.m_item = it->second;
+ dlgEdit.m_dwCRC32 = dwCrc32;
+ dlgEdit.DoModal();
+ if (dlgEdit.m_bAddedOk)
+ {/// the rule is edited...
+ m_listRules.DeleteString(nIndex);
+ nIndex = m_listRules.AddString(dlgEdit.m_item.RuleName);
+ m_listRules.SetItemData(nIndex, dlgEdit.m_dwCRC32);
+ OnSetSelInRulesList(nIndex);
+ OnNotifyAboutChanges();
+ }
+ }
+ }
+ }
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnBtnDeleteRuleClick(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ int nIndex = m_listRules.GetCurSel();
+ if (nIndex >= 0)
+ {
+ DWORD dwptr = static_cast<DWORD>(m_listRules.GetItemData(nIndex));
+ if (dwptr)/// we have ptr
+ {
+ if (MessageBox(TranslateTS(TEXT("Do you really want delete selected rule ?")), g_strPluginName, MB_YESNO) == IDNO)
+ return FALSE;
+
+ CRulesStorage & hash = g_pMessHandler->getSettings().getStorage();
+
+ if (hash.RemReplyAction(dwptr))
+ {/// we found item in storage list...
+ int nCount = m_listRules.DeleteString(nIndex);
+ if (nCount != LB_ERR)
+ { /// set sel to prev one
+ if (nIndex == 0 && nCount)
+ OnSetSelInRulesList(0);
+ else
+ if ( (nIndex - 1) <= nCount)
+ {
+ OnSetSelInRulesList(nIndex - 1);
+ }
+ }
+
+ OnNotifyAboutChanges();
+ }
+ }
+ }
+
+ BOOL b;
+ OnListBoxSelChanged(0, 0, 0, b);
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnListBoxSelChanged(WORD wParam, WORD w2Param, HWND hwnd, BOOL & bHandled)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ int nCount = m_listRules.GetCurSel();
+ //m_btnChange.EnableWindow((nCount >= 0));
+ BOOL bEnable = (nCount >= 0);
+ m_btnDel.EnableWindow(bEnable);
+ m_btnChange.EnableWindow(bEnable);
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnBnClickedCheck(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ OnNotifyAboutChanges();
+
+ return FALSE;
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnBnCheckEnableWhenModeIsOn(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ LRESULT lres = m_wndCheckModeTypes.SendMessage(BM_GETCHECK, 0, 0);
+ m_cbModeTypes.EnableWindow(lres == BST_CHECKED);
+ OnNotifyAboutChanges();
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnCbnSelchangeCbEnwsc(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ OnNotifyAboutChanges();
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnCheckSaveToHistory(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ OnNotifyAboutChanges();
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnBnCheckDisableWhenModeIsOn(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ LRESULT lres = m_chDisWMB.SendMessage(BM_GETCHECK, 0, 0);
+ m_cbDisWMBTypes.EnableWindow(lres == BST_CHECKED);
+ OnNotifyAboutChanges();
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnCbnSelchangeCbDisnwsc(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ OnNotifyAboutChanges();
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+/// options are changed in another place...
+/// so just update them all...
+LRESULT COptionsDlg::OnRefreshOptions(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ MessageBox (TranslateTS(TEXT("Options are changed in another dialog")), g_strPluginName, MB_OK);
+ ///OnNotifyAboutChanges();
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT COptionsDlg::OnLbnDblclkListRules(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return OnBtnEditRuleClick(wNotifyCode, wID, hWndCtl, bHandled);
+END_PROTECT_AND_LOG_CODE
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/GUI/OptionsDlg.h b/plugins/SmartAutoReplier/GUI/OptionsDlg.h
new file mode 100644
index 0000000000..0e2e91f191
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/OptionsDlg.h
@@ -0,0 +1,119 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+/// #warning: redeclaring....quick programming ;)
+/// look at stdafx.h
+#ifndef REFRESH_OPTS_MSG
+ #define REFRESH_OPTS_MSG WM_USER + 666
+#endif
+
+#include <commctrl.h>
+#include <atlbase.h>
+#include <atlapp.h>
+#include <atlwin.h>
+#include <atlctrls.h>
+
+/// here is a wrapper on options dlg
+class COptionsDlg : public CDialogImpl<COptionsDlg>, public CMessageFilter
+{
+public:
+ COptionsDlg(void);
+ virtual ~COptionsDlg(void);
+public:
+ enum {IDD = IDD_OPTIONS};
+ BEGIN_MSG_MAP(COptionsDlg)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_HANDLER(WM_NOTIFY, OnNotify)
+ MESSAGE_HANDLER(REFRESH_OPTS_MSG, OnRefreshOptions)
+ COMMAND_ID_HANDLER(IDC_BTN_ADDRULE, OnBtnAddRuleClick)
+ COMMAND_ID_HANDLER(IDC_BTN_DELRULE, OnBtnDeleteRuleClick)
+ COMMAND_ID_HANDLER(IDC_BTN_EDITRULE, OnBtnEditRuleClick)
+ COMMAND_ID_HANDLER(IDC_EDIT_REPLAYDELAY, OnEditReply)
+ COMMAND_ID_HANDLER(IDC_EDIT_HEADER, OnEditHeader)
+ COMMAND_ID_HANDLER(IDC_EDIT_MESSAGE, OnEditMessage)
+ COMMAND_CODE_HANDLER(LBN_SELCHANGE, OnListBoxSelChanged)
+ COMMAND_HANDLER(IDC_LIST_RULES, LBN_DBLCLK, OnLbnDblclkListRules)
+ COMMAND_HANDLER(IDC_CHECK_DISABLEWMON, BN_CLICKED, OnBnClickedCheck)
+ COMMAND_HANDLER(IDC_CH_ENABLE_WSCH, BN_CLICKED, OnBnCheckEnableWhenModeIsOn)
+ COMMAND_HANDLER(IDC_CH_SHOWCG, BN_CLICKED, OnBnCheckEnableWhenModeIsOn)
+ COMMAND_HANDLER(IDC_CH_SAVE_AURS, BN_CLICKED, OnCheckSaveToHistory)
+ COMMAND_HANDLER(IDC_CB_ENWSC, CBN_SELENDOK, OnCbnSelchangeCbEnwsc)
+ COMMAND_HANDLER(IDC_CH_DISWHSB, BN_CLICKED, OnBnCheckDisableWhenModeIsOn)
+ COMMAND_HANDLER(IDC_CB_DWSB, CBN_SELENDOK, OnCbnSelchangeCbDisnwsc)
+ END_MSG_MAP()
+ virtual BOOL PreTranslateMessage(MSG* pMsg);
+protected:
+ /// messages handlers prototypes
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnNotify(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnRefreshOptions(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+
+ /// commands handlers prototypes
+ LRESULT OnBtnAddRuleClick(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnBtnDeleteRuleClick(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnBtnEditRuleClick(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnEditReply(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnEditHeader(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnEditMessage(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnListBoxSelChanged(WORD wParam, WORD wParam2, HWND hwnd, BOOL & bHandled);
+ LRESULT OnBnClickedCheck(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnBnCheckEnableWhenModeIsOn(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnCbnSelchangeCbEnwsc(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnBnCheckDisableWhenModeIsOn(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnCheckSaveToHistory(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnCbnSelchangeCbDisnwsc(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnLbnDblclkListRules(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+public:
+ static BOOL CALLBACK DlgProcCluiOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+private:
+ void OnNotifyAboutChanges(void);
+ void OnSetSelInRulesList(int nIndex);
+protected:
+ CEdit m_editReplayDelay; /// edit box where reply delay is specifyed
+ CEdit m_editMessageText; /// edit box where message text is specifyed
+ CListBox m_listRules; /// list box where all rules are specifyed
+ CButton m_btnAdd; /// button add rule
+ CButton m_btnDel; /// button delete rule
+ CButton m_btnChange; /// button change rule
+ CWindow m_wndCheckDOnSOn; /// checkbox that specifyes dis of plug. when mir is on
+ CComboBox m_cbModeTypes; /// cb mode types
+ CWindow m_wndCheckModeTypes; /// ch mode types
+ CWindow m_chbShowAurWhmc; /// ch show edit reply message
+ CWindow m_chDisWMB; /// ch disable when mode becomes...
+ CWindow m_chSaveAURSToHist; /// save aurs to history
+ CComboBox m_cbDisWMBTypes; /// cb disable when mode becomes...
+private:
+ LPTSTR m_szMessage;
+ int m_nReplayDelay;
+ bool m_bDestroying;
+protected:
+ bool m_bShown;
+public:
+ HWND m_hwndHolder;
+};
+
+/// here is static dlg proc for options dialog..
+/// very bad but mirand can accept only this function
+BOOL CALLBACK DlgProcCluiOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam); \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/GUI/SelectUserDlg.cpp b/plugins/SmartAutoReplier/GUI/SelectUserDlg.cpp
new file mode 100644
index 0000000000..6a51ccae19
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/SelectUserDlg.cpp
@@ -0,0 +1,109 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "selectuserdlg.h"
+#include "selectuserdlg.h"
+
+extern LPTSTR g_strPluginName;
+extern CMessagesHandler * g_pMessHandler;
+
+
+CSelectUserDlg::CSelectUserDlg(void) : m_bAllOk(false)
+{
+}
+
+CSelectUserDlg::~CSelectUserDlg(void)
+{
+}
+
+BOOL CSelectUserDlg::PreTranslateMessage(MSG* pMsg)
+{
+ return IsDialogMessage(pMsg);
+}
+
+LRESULT CSelectUserDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ TranslateDialogDefault(m_hWnd);
+ m_listUsers = GetDlgItem(IDC_LIST_USERS);
+ RebuildCL();
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+void CSelectUserDlg::RebuildCL()
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ HANDLE hContact= reinterpret_cast<HANDLE> (CallService(MS_DB_CONTACT_FINDFIRST, 0, 0));
+ TCHAR* szContactName = NULL;
+ TCHAR* szProto = NULL;
+ DWORD wId = 0;
+ while (hContact != NULL)
+ {
+ szContactName = g_pMessHandler->GetContactName(hContact);
+ szProto = (TCHAR*)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0);
+ if (szProto)
+ {
+ size_t nPos = -1;
+ if (szContactName)
+ {
+ nPos = m_listUsers.AddString(szContactName);
+ }
+
+ /*DBVARIANT db = {0};
+ DBGetContactSetting(hContact, szProto, "uin", &db);
+ DBGetContactSetting(hContact, szProto, "UIN", &db);*/
+ //m_listUsers.SetItemData(nPos, )
+ }
+
+ hContact = reinterpret_cast<HANDLE> (CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM) hContact, 0));
+ }
+END_PROTECT_AND_LOG_CODE
+}
+
+LRESULT CSelectUserDlg::OnBtnOKClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ INT nsel = m_listUsers.GetCurSel();
+ m_bAllOk = (nsel != -1);
+ if (m_bAllOk == true)
+ {
+ m_listUsers.GetText(nsel, m_szRetVal);
+ EndDialog(0);
+ }
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT CSelectUserDlg::OnBtnCancelClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_bAllOk = false;
+ EndDialog(0);
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT CSelectUserDlg::OnLbnDblclkListUsers(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
+{
+ return OnBtnOKClicked(wNotifyCode, wID, hWndCtl, bHandled);
+}
diff --git a/plugins/SmartAutoReplier/GUI/SelectUserDlg.h b/plugins/SmartAutoReplier/GUI/SelectUserDlg.h
new file mode 100644
index 0000000000..1756e7a4b8
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/SelectUserDlg.h
@@ -0,0 +1,58 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "..\resource.h"
+
+#include <commctrl.h>
+#include <atlbase.h>
+#include <atlapp.h>
+#include <atlwin.h>
+
+class CSelectUserDlg : public CDialogImpl<CSelectUserDlg>, public CMessageFilter
+{
+public:
+ CSelectUserDlg(void);
+ ~CSelectUserDlg(void);
+public:
+ enum {IDD = IDD_SEL_USER};
+ BEGIN_MSG_MAP(CSelectUserDlg)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ COMMAND_ID_HANDLER(IDOK, OnBtnOKClicked)
+ COMMAND_ID_HANDLER(IDCANCEL, OnBtnCancelClicked)
+ COMMAND_HANDLER(IDC_LIST_USERS, LBN_DBLCLK, OnLbnDblclkListUsers)
+ END_MSG_MAP()
+protected:
+ virtual BOOL PreTranslateMessage(MSG* pMsg);
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnBtnOKClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+ LRESULT OnBtnCancelClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+private:
+ void RebuildCL();
+public:
+ bool m_bAllOk;
+ TCHAR m_szRetVal[MAX_PATH];
+protected:
+ CListBox m_listUsers;
+public:
+ LRESULT OnLbnDblclkListUsers(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
+};
diff --git a/plugins/SmartAutoReplier/GUI/SettingsDlgHolder.cpp b/plugins/SmartAutoReplier/GUI/SettingsDlgHolder.cpp
new file mode 100644
index 0000000000..4a9eae542a
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/SettingsDlgHolder.cpp
@@ -0,0 +1,207 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "settingsdlgholder.h"
+
+/// #warning
+/// dont make Translate each time
+/// instead once fill list of translated strings
+/// and use them
+
+extern LPTSTR g_strPluginName;
+extern CMessagesHandler * g_pMessHandler;
+CSettingsDlgHolder * CSettingsDlgHolder::m_pThis = NULL;
+
+CSettingsDlgHolder::CSettingsDlgHolder(void) :
+IMSingeltone<CSettingsDlgHolder>(this),
+m_bTabSelected(false),
+m_bDestroying(false)
+{
+}
+
+CSettingsDlgHolder::~CSettingsDlgHolder(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ BOOL b;
+ OnDestroy(NULL, NULL, NULL, b);
+END_PROTECT_AND_LOG_CODE
+}
+
+BOOL CSettingsDlgHolder::PreTranslateMessage(MSG* pMsg)
+{
+ return IsDialogMessage(pMsg);
+}
+
+LRESULT CSettingsDlgHolder::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ TranslateDialogDefault(m_hWnd);
+
+ m_tabCtrl = GetDlgItem(IDC_TABSHOLDER);
+ m_statusMsg = GetDlgItem(IDC_STATUSMSG);
+
+ TCITEM ti = {0};
+ ti.mask = TCIF_TEXT;
+ ti.pszText = TranslateTS(TEXT("General"));
+ ti.cchTextMax = _tcslen(ti.pszText);
+ m_tabCtrl.InsertItem(0, &ti);
+ /*ti.pszText = Translate("About");
+ ti.cchTextMax = _tcslen(ti.pszText);
+ m_tabCtrl.InsertItem(1, &ti);*/
+
+ m_generalOpt.Create(m_tabCtrl, NULL);
+ m_generalOpt.m_hwndHolder = this->m_hWnd;
+ m_tabCtrl.SetCurSel(0);
+
+ /// #warning
+ /// copy paste from OnNotify(), fix later
+ /*m_statusMsg.SetWindowText(Translate("General options, provides basic functionality."));*/
+ m_statusMsg.SetWindowText(TranslateTS(TEXT("")));
+ m_generalOpt.SetWindowPos(NULL, 7, 23, NULL, NULL, SWP_NOSIZE);
+ m_generalOpt.ShowWindow(SW_SHOW);
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+void CSettingsDlgHolder::OnNotifyParents(LPNMHDR lpnmhdr, int nCode)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ lpnmhdr->code = nCode;
+ m_generalOpt.SendMessage(WM_NOTIFY, 0, reinterpret_cast<LPARAM>(lpnmhdr));
+END_PROTECT_AND_LOG_CODE
+}
+
+LRESULT CSettingsDlgHolder::OnNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ LPNMHDR lpnmhdr = NULL;
+ lpnmhdr = (LPNMHDR)lParam;
+ if (lpnmhdr == NULL)
+ {
+ return FALSE;
+ }
+
+ if (m_bTabSelected == false)
+ {
+ m_bTabSelected = true;
+ return FALSE;
+ }
+
+ switch (lpnmhdr->code)
+ {
+ case PSN_APPLY:
+ OnNotifyParents(lpnmhdr, PSN_APPLY);
+ break;
+ }
+
+ int nSel = -1;
+ if (lpnmhdr->hwndFrom == m_tabCtrl)
+ {
+ nSel = m_tabCtrl.GetCurSel();
+ /// let's make a switch by dialogs...
+ if (nSel == 0)
+ {
+ m_statusMsg.SetWindowText(TranslateTS(TEXT("General options, provides basic functionality.")));
+ m_generalOpt.ShowWindow(SW_SHOW);
+ m_generalOpt.SetWindowPos(NULL, 7, 23, NULL, NULL, SWP_NOSIZE);
+ }
+ else
+ m_generalOpt.ShowWindow(SW_HIDE);
+ }
+
+ m_bTabSelected = false;
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+BOOL CALLBACK CSettingsDlgHolder::FakeDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ CSettingsDlgHolder *pHandler = CSettingsDlgHolder::GetObject();
+
+ if (pHandler == NULL)
+ return FALSE;
+
+ if (pHandler->m_bDestroying == true)
+ return FALSE;
+
+ if (pHandler->m_hWnd == NULL)
+ pHandler->Attach(hwndDlg);
+
+ LRESULT lr = 0;
+ DWORD dwid = 0;
+ BOOL bRetVal = pHandler->ProcessWindowMessage(hwndDlg, msg, wParam, lParam, lr, dwid);
+ return bRetVal;
+ END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT CSettingsDlgHolder::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_bDestroying = true;
+
+ if (m_tabCtrl.IsWindow())
+ {
+ m_tabCtrl.DeleteAllItems();
+ m_tabCtrl.DestroyWindow();
+ }
+ if (m_statusMsg.IsWindow())
+ m_statusMsg.DestroyWindow();
+
+ if (m_generalOpt.IsWindow())
+ {
+ /*try
+ {*/
+ //OSVERSIONINFO ver = {0};
+ //ver.dwOSVersionInfoSize = sizeof(ver);
+
+ //if (GetVersionEx(&ver) == TRUE)
+ //{
+ // if (ver.dwMajorVersion > 4)
+ // {
+ NMHDR h = {0};
+ h.code = PSN_APPLY;
+ OnNotifyParents(&h, PSN_APPLY);
+ // }
+ //}
+ m_generalOpt.DestroyWindow();
+ //}
+ //catch (...)
+ //{/// win9x will die here
+ //}
+ }
+ m_hWnd = NULL;
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+LRESULT CSettingsDlgHolder::OnSettingsChanged(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return SendMessage(GetParent(), PSM_CHANGED, 0, 0);
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/GUI/SettingsDlgHolder.h b/plugins/SmartAutoReplier/GUI/SettingsDlgHolder.h
new file mode 100644
index 0000000000..61fb460e5b
--- /dev/null
+++ b/plugins/SmartAutoReplier/GUI/SettingsDlgHolder.h
@@ -0,0 +1,69 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "..\resource.h"
+
+#include <commctrl.h>
+#include <atlbase.h>
+#include <atlapp.h>
+#include <atlwin.h>
+
+#include "optionsdlg.h"
+
+/// dialog that holds all
+/// gui dialogs..
+class CSettingsDlgHolder : public CDialogImpl<CSettingsDlgHolder>,
+ public CMessageFilter,
+ public IMSingeltone<CSettingsDlgHolder>
+{
+public: /// ctors
+ CSettingsDlgHolder(void);
+ /// dctors
+ ~CSettingsDlgHolder(void);
+public:
+ enum {IDD = IDD_SDLGHOLDER};
+ BEGIN_MSG_MAP(CSettingsDlgHolder)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ MESSAGE_HANDLER(WM_NOTIFY, OnNotify)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_HANDLER(PSM_CHANGED, OnSettingsChanged)
+ END_MSG_MAP()
+protected:
+ virtual BOOL PreTranslateMessage(MSG* pMsg);
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnNotify(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+ LRESULT OnSettingsChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
+private:
+ void OnNotifyParents(LPNMHDR lpnmhdr, int nCode);
+private:
+ bool m_bTabSelected;
+public:
+ static BOOL CALLBACK FakeDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+protected:
+ CTabCtrl m_tabCtrl; /// holder of all settings dlg
+ CStatic m_statusMsg;
+ COptionsDlg m_generalOpt; /// general options dlg
+public:
+ bool m_bDestroying;
+};
diff --git a/plugins/SmartAutoReplier/Interfaces/ISettings.h b/plugins/SmartAutoReplier/Interfaces/ISettings.h
new file mode 100644
index 0000000000..4a789be694
--- /dev/null
+++ b/plugins/SmartAutoReplier/Interfaces/ISettings.h
@@ -0,0 +1,34 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+/// base for settings data...
+interface ISettingsStream
+{
+};
+
+/// base interface for settings managers...
+interface ISettings
+{
+ virtual bool Serialize(ISettingsStream *pStream, DWORD & ObjectSize) = NULL;
+ virtual bool Deserialize(DWORD & ObjectSize) = NULL;
+}; \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/Interfaces/ISingletone.h b/plugins/SmartAutoReplier/Interfaces/ISingletone.h
new file mode 100644
index 0000000000..7474127e89
--- /dev/null
+++ b/plugins/SmartAutoReplier/Interfaces/ISingletone.h
@@ -0,0 +1,35 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+/// base class for singletones in plugin
+template <class T>
+class IMSingeltone
+{
+public:
+ IMSingeltone(){};
+ IMSingeltone(T * ptclass) {m_pThis = ptclass;}
+ static void SetObject(T* pObj) {m_pThis = pObj;};
+ static T* GetObject(){return m_pThis;};
+protected:
+ static T* m_pThis;
+}; \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/LuaBridge.cpp b/plugins/SmartAutoReplier/LuaBridge.cpp
new file mode 100644
index 0000000000..764dec3381
--- /dev/null
+++ b/plugins/SmartAutoReplier/LuaBridge.cpp
@@ -0,0 +1,127 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This code is inspired by article of RichardS at http://www.codeproject.com/Articles/11508/Integrating-Lua-into-C
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "LuaBridge.h"
+
+CLuaBridge::CLuaBridge(void) : m_pLuaContext(NULL)
+{
+ m_pLuaContext = lua_open();
+
+ if (m_pLuaContext != NULL)
+ {
+ lua_pushcclosure(m_pLuaContext, LuaDebugMessage, 0);
+ lua_setglobal(m_pLuaContext, "trace");
+
+ lua_atpanic(m_pLuaContext, (lua_CFunction)HandleLuaAsssert);
+
+ luaopen_io(m_pLuaContext);
+ luaopen_math(m_pLuaContext);
+ luaopen_base(m_pLuaContext);
+ luaopen_loadlib(m_pLuaContext);
+ luaopen_table(m_pLuaContext);
+ luaopen_string(m_pLuaContext);
+ luaopen_debug(m_pLuaContext);
+ }
+}
+
+CLuaBridge::~CLuaBridge(void)
+{
+ if (m_pLuaContext != NULL)
+ {
+ lua_close(m_pLuaContext);
+ }
+}
+
+int CLuaBridge::LuaDebugMessage(lua_State *pContext)
+{
+ const char *szFunction = NULL;
+ const char *szMessage = NULL;
+ lua_Debug LuaDebug = {0};
+
+ int n = lua_tonumber(pContext, 1);
+ szMessage = lua_tostring(pContext, 1);
+
+ if (szMessage == NULL)
+ {
+ return FALSE;
+ }
+
+ lua_getstack(pContext, 1, &LuaDebug);
+ lua_getinfo (pContext, "Snl", &LuaDebug);
+
+ szFunction = LuaDebug.source;
+
+ if (szFunction == NULL)
+ {
+ return FALSE;
+ }
+
+ OutputDebugStringA("Smart Auto Replier : ");
+ OutputDebugStringA("(");
+ OutputDebugStringA(szFunction);
+ OutputDebugStringA("): ");
+ OutputDebugStringA(szMessage);
+ OutputDebugStringA("\r\n");
+
+ return TRUE;
+}
+
+void CLuaBridge::HandleLuaAsssert(lua_State * pContext)
+{
+ DebugBreak();
+}
+
+bool CLuaBridge::RunScript(const char *szScript, size_t nLength, const char *szFuncName)
+{
+ bool bRetVal = false;
+
+ if (szFuncName == NULL)
+ {
+ szFuncName = "SarFakeProcedure";
+ }
+
+ if (luaL_loadbuffer(m_pLuaContext, szScript, nLength, szFuncName) == 0)
+ {
+ bRetVal = (lua_pcall(m_pLuaContext, 0, LUA_MULTRET, 0) == 0);
+ }
+
+ return bRetVal;
+}
+
+bool CLuaBridge::ExecuteFunction(int nArgs, int nReturns)
+{
+ bool bRetVal = false;
+
+ if (lua_isfunction(m_pLuaContext, -nArgs - 1))
+ {
+ bRetVal = (lua_pcall(m_pLuaContext, nArgs, nReturns, 0) == FALSE);
+ }
+
+ return bRetVal;
+}
+
+CLuaBridge::operator lua_State *()
+{
+ return m_pLuaContext;
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/LuaBridge.h b/plugins/SmartAutoReplier/LuaBridge.h
new file mode 100644
index 0000000000..f012a55db4
--- /dev/null
+++ b/plugins/SmartAutoReplier/LuaBridge.h
@@ -0,0 +1,96 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This code is inspired by article of RichardS at http://www.codeproject.com/Articles/11508/Integrating-Lua-into-C
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "luainc.h"
+
+class CLuaBridge
+{
+public:
+ CLuaBridge(void);
+ ~CLuaBridge(void);
+
+public:
+ static int LuaDebugMessage(lua_State * pContext);
+ static void HandleLuaAsssert(lua_State * pContext);
+
+ bool RunScript(const char *szScript, size_t nLength, const char *szFuncName = NULL);
+ bool ExecuteFunction(int nArgs, int nReturns = 0);
+ operator lua_State *();
+
+protected:
+ lua_State *m_pLuaContext;
+};
+
+class CLuaStack
+{
+public:
+ CLuaStack(CLuaBridge & luaBridge) : m_pState(NULL), m_nTopIndex(0)
+ {
+ m_pState = (lua_State*)luaBridge;
+ m_nTopIndex = lua_gettop(m_pState);
+ }
+
+ virtual ~CLuaStack()
+ {
+ lua_settop(m_pState, m_nTopIndex);
+ }
+
+protected:
+
+ lua_State *m_pState;
+ int m_nTopIndex;
+};
+
+class CLuaTableThis
+{
+public:
+ CLuaTableThis(CLuaBridge & luaBridge, int nRef) : m_nOldRef(0), m_luaBridge(luaBridge)
+ {
+ lua_State *state = (lua_State*)m_luaBridge;
+
+ lua_getglobal(state, "this");
+ m_nOldRef = luaL_ref(state, LUA_REGISTRYINDEX);
+
+ lua_rawgeti(state, LUA_REGISTRYINDEX, nRef);
+ lua_setglobal(state, "this");
+ }
+
+ virtual ~CLuaTableThis()
+ {
+ lua_State *state = (lua_State*)m_luaBridge;
+
+ if (m_nOldRef > 0)
+ {
+ lua_rawgeti(state, LUA_REGISTRYINDEX, m_nOldRef);
+ lua_setglobal (state, "this");
+ luaL_unref(state, LUA_REGISTRYINDEX, m_nOldRef);
+ }
+ }
+
+protected:
+ int m_nOldRef;
+ CLuaBridge & m_luaBridge;
+};
+
diff --git a/plugins/SmartAutoReplier/LuaScript.cpp b/plugins/SmartAutoReplier/LuaScript.cpp
new file mode 100644
index 0000000000..5ad1508d99
--- /dev/null
+++ b/plugins/SmartAutoReplier/LuaScript.cpp
@@ -0,0 +1,215 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This code is inspired by article of RichardS at http://www.codeproject.com/Articles/11508/Integrating-Lua-into-C
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+
+#include <assert.h>
+#include "luainc.h"
+#include "luascript.h"
+
+#define LUA_CODE_CHUNK_ENTER(luaBridge) lua_State *state = (lua_State*)luaBridge;
+
+#define LUA_CODE_CHUNK_LEAVE
+
+CLuaScript::CLuaScript(CLuaBridge & luaBridge) : m_luaBridge(luaBridge), m_nMethods(DEFAULT_INDEX_INITIALIZER), m_nThisRef(DEFAULT_INDEX_INITIALIZER), m_nArgs(DEFAULT_INDEX_INITIALIZER)
+{
+LUA_CODE_CHUNK_ENTER(luaBridge)
+
+ lua_newtable(state);
+ m_nThisRef = luaL_ref(state, LUA_REGISTRYINDEX);
+
+ CLuaStack luaStack(luaBridge);
+ lua_rawgeti(state, LUA_REGISTRYINDEX, m_nThisRef);
+ lua_pushlightuserdata(state, reinterpret_cast<void*>(this));
+ lua_rawseti(state, -2, 0);
+
+LUA_CODE_CHUNK_LEAVE
+}
+
+CLuaScript::~CLuaScript(void)
+{
+ CLuaStack luaStack(m_luaBridge);
+
+LUA_CODE_CHUNK_ENTER(m_luaBridge)
+
+ lua_rawgeti(state, LUA_REGISTRYINDEX, m_nThisRef);
+ lua_pushnil(state);
+ lua_rawseti(state, -2, 0);
+
+LUA_CODE_CHUNK_LEAVE
+}
+
+int CLuaScript::LuaCallback(lua_State *lua)
+{
+ int iNumberIdx = lua_upvalueindex(1);
+ int nRetsOnStack = 0;
+
+ bool bRetVal = false;
+
+ if (lua_istable(lua, 1))
+ {
+ lua_rawgeti(lua, 1, 0);
+
+ if (lua_islightuserdata(lua, -1))
+ {
+ CLuaScript *pThis = reinterpret_cast<CLuaScript*>(lua_touserdata(lua, -1));
+ int nMethod = static_cast<int>(lua_tonumber(lua, iNumberIdx));
+
+ assert(!(nMethod > pThis->MethodsCount()));
+
+ lua_remove(lua, 1); lua_remove(lua, -1);
+
+ nRetsOnStack = pThis->ScriptCalling(pThis->Bridge(), nMethod);
+
+ bRetVal = true;
+ }
+ }
+
+ if (bRetVal == false)
+ {
+ lua_error(lua);
+ }
+
+ return nRetsOnStack;
+}
+
+bool CLuaScript::CompileScript(const char *szScript, size_t nLength)
+{
+ CLuaTableThis luaThisTable(m_luaBridge, m_nThisRef);
+
+ return m_luaBridge.RunScript(szScript, nLength);
+}
+
+int CLuaScript::RegisterFunction(const char *szFuncName)
+{
+ int nMethod = -1;
+
+ CLuaStack luaStack(m_luaBridge);
+
+LUA_CODE_CHUNK_ENTER(m_luaBridge)
+
+ nMethod = ++m_nMethods;
+
+ lua_rawgeti(state, LUA_REGISTRYINDEX, m_nThisRef);
+ lua_pushstring(state, szFuncName);
+ lua_pushnumber(state, (lua_Number)nMethod);
+ lua_pushcclosure(state, CLuaScript::LuaCallback, 1);
+ lua_settable(state, -3);
+
+LUA_CODE_CHUNK_LEAVE
+
+ return nMethod;
+}
+
+bool CLuaScript::SelectScriptFunction(const char *szFunction)
+{
+ bool bRetVal = true;
+
+LUA_CODE_CHUNK_ENTER(m_luaBridge)
+
+ lua_rawgeti(state, LUA_REGISTRYINDEX, m_nThisRef);
+ lua_pushstring(state, szFunction);
+ lua_rawget(state, -2);
+ lua_remove(state, -2);
+
+ lua_rawgeti(state, LUA_REGISTRYINDEX, m_nThisRef);
+
+ if (!lua_isfunction(state, -2))
+ {
+ bRetVal = false;
+ lua_pop(state, 2);
+ }
+ else
+ {
+ m_nArgs = 0;
+ m_szFunction = szFunction;
+ }
+
+LUA_CODE_CHUNK_LEAVE
+
+ return bRetVal;
+}
+
+bool CLuaScript::ScriptHasFunction(const char * szFunction)
+{
+ CLuaStack luaStack(m_luaBridge);
+
+ bool bRetVal = false;
+
+LUA_CODE_CHUNK_ENTER(m_luaBridge)
+
+ lua_rawgeti(state, LUA_REGISTRYINDEX, m_nThisRef);
+ lua_pushstring(state, szFunction);
+ lua_rawget(state, -2);
+ lua_remove(state, -2);
+
+ bRetVal = (lua_isfunction(state, -1) != FALSE);
+
+LUA_CODE_CHUNK_LEAVE
+
+ return bRetVal;
+}
+
+void CLuaScript::AddParam(char * szValue)
+{
+LUA_CODE_CHUNK_ENTER(m_luaBridge)
+ lua_pushstring(state, szValue); ++m_nArgs;
+LUA_CODE_CHUNK_LEAVE
+}
+
+void CLuaScript::AddParam(int nValue)
+{
+LUA_CODE_CHUNK_ENTER(m_luaBridge)
+ lua_pushnumber(state, (lua_Number)nValue); ++m_nArgs;
+LUA_CODE_CHUNK_LEAVE
+}
+
+void CLuaScript::AddParam(float fValue)
+{
+LUA_CODE_CHUNK_ENTER(m_luaBridge)
+ lua_pushnumber(state, (lua_Number)fValue); ++m_nArgs;
+LUA_CODE_CHUNK_LEAVE
+}
+
+bool CLuaScript::Run(int nRetValues)
+{
+ bool bRetVal = m_luaBridge.ExecuteFunction((m_nArgs + 1), nRetValues);
+
+ if (bRetVal == true && nRetValues > 0)
+ {
+ HandleReturns(m_luaBridge, m_szFunction);
+ lua_pop(static_cast<lua_State*>(m_luaBridge), nRetValues);
+ }
+
+ return bRetVal;
+}
+
+CLuaBridge & CLuaScript::Bridge()
+{
+ return m_luaBridge;
+}
+
+int CLuaScript::MethodsCount()
+{
+ return m_nMethods;
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/LuaScript.h b/plugins/SmartAutoReplier/LuaScript.h
new file mode 100644
index 0000000000..73c29c0a3f
--- /dev/null
+++ b/plugins/SmartAutoReplier/LuaScript.h
@@ -0,0 +1,68 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This code is inspired by article of RichardS at http://www.codeproject.com/Articles/11508/Integrating-Lua-into-C
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "luainc.h"
+#include "LuaBridge.h"
+
+///
+#define DEFAULT_INDEX_INITIALIZER 0
+
+class CLuaScript
+{
+public:
+ CLuaScript(CLuaBridge & luaBridge);
+ virtual ~CLuaScript();
+
+public:
+
+ static int LuaCallback (lua_State *lua);
+ bool CompileScript(const char *szScript, size_t nLength);
+ int RegisterFunction(const char *szFuncName);
+ bool SelectScriptFunction(const char *szFunction);
+ bool ScriptHasFunction(const char *szFunction);
+ bool Run(int nRetValues = 0);
+
+public:
+ void AddParam(int nValue);
+ void AddParam(float fValue);
+ void AddParam(char *szValue);
+ CLuaBridge & Bridge();
+
+ int MethodsCount();
+
+public:
+ virtual int ScriptCalling(CLuaBridge & luaBridge, int nFunction) = 0;
+ virtual void HandleReturns(CLuaBridge & luaBridge, const char * szFunction) = 0;
+
+protected:
+
+ CLuaBridge & m_luaBridge;
+
+ const char * m_szFunction;
+
+ int m_nMethods,
+ m_nThisRef,
+ m_nArgs;
+}; \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/MessagesHandler.cpp b/plugins/SmartAutoReplier/MessagesHandler.cpp
new file mode 100644
index 0000000000..3f3e8e5ad5
--- /dev/null
+++ b/plugins/SmartAutoReplier/MessagesHandler.cpp
@@ -0,0 +1,469 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "messageshandler.h"
+#include "SarLuaScript.h"
+#include <time.h>
+
+extern CCrushLog CRUSHLOGOBJ;
+
+/// init static members...
+CMessagesHandler * CMessagesHandler::m_pThis = NULL;
+
+/// thread that is checking
+/// users that sent messages,
+/// analize sent time and if
+/// reply delay is greater then
+/// difference between current time and
+/// sent time thread deletes item.
+INT WINAPI ContactsFetcherThread(LPVOID lp)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+#define SLEEP_TIME 50
+ CMessagesHandler *pHolder = CMessagesHandler::GetObject();
+ if (pHolder)
+ {
+ while (pHolder->m_bShouldWork)
+ {
+ WaitForSingleObject(pHolder->m_hEnableEvent, INFINITE);
+ if (!pHolder->m_bShouldWork)
+ break;
+
+ EnterCriticalSection(&pHolder->m_critSect);
+
+ if (pHolder->m_contacts.size() == 0)
+ {
+ LeaveCriticalSection(&pHolder->m_critSect);
+ Sleep (SLEEP_TIME);
+ continue;
+ }
+
+ SYSTEMTIME sysTime = {0};
+ FILETIME ft = {0};
+ LARGE_INTEGER liNow = {0};
+
+ GetLocalTime (&sysTime);
+ SystemTimeToFileTime(&sysTime, &ft);
+ memcpy(&liNow, &ft, sizeof(liNow));
+
+ ContactsMap::iterator it;
+
+ CONTACT_METAINFO rawm = {0};
+ LARGE_INTEGER liDiff = {0};
+
+ for (it = pHolder->m_contacts.begin(); it != pHolder->m_contacts.end(); it++)
+ {
+ if (pHolder->m_contacts.size() == 0)
+ {
+ break;
+ }
+ rawm = it->second;
+ liDiff.QuadPart = liNow.QuadPart - rawm.StartTime.QuadPart;
+ if (liDiff.QuadPart >= rawm.DiffTime.QuadPart)
+ {
+ if (pHolder->m_contacts.size() == 1)
+ {
+ pHolder->m_contacts.clear();
+ break;
+ }
+ else
+ pHolder->m_contacts.erase(it);
+ }
+ }
+
+ LeaveCriticalSection(&pHolder->m_critSect);
+
+ Sleep (SLEEP_TIME);
+ }
+ }
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+/// ctor of main plugin manager
+CMessagesHandler::CMessagesHandler(void) : IMSingeltone<CMessagesHandler>(this),
+m_hFetcherThread(NULL),
+m_hEnableEvent(NULL),
+m_bShouldWork(true),
+m_bInited(false)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_settings.Init();
+END_PROTECT_AND_LOG_CODE
+}
+
+/// dtor of main plugin manager
+CMessagesHandler::~CMessagesHandler(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_settings.DeInit();
+ m_bShouldWork = false;
+ CMessagesHandler::m_pThis = NULL;
+END_PROTECT_AND_LOG_CODE
+}
+
+/// enables or disables feature
+void CMessagesHandler::MakeAction(bool bEnable)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ REPLYER_SETTINGS & s = m_settings.getSettings();
+ s.bEnabled = bEnable;
+ m_settings.setSettings(s);
+
+ if (bEnable)
+ {
+ HookEvents();
+ SetEvent (m_hEnableEvent);
+ }
+ else
+ UnHookEvents();
+END_PROTECT_AND_LOG_CODE
+}
+
+bool CMessagesHandler::AllowReply(HANDLE hContact)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ if (!m_settings.getSettings().bEnabled)
+ return FALSE;
+ ContactsMap::iterator it;
+ bool bRetVal = false;
+
+ EnterCriticalSection(&m_critSect);
+
+ it = m_contacts.find(hContact);
+
+ SYSTEMTIME sysTime = {0};
+ FILETIME ft = {0};
+ GetLocalTime (&sysTime);
+ SystemTimeToFileTime(&sysTime, &ft);
+
+ if (it == m_contacts.end())
+ { /// no such contact...
+ CONTACT_METAINFO cm = {0};
+
+ memcpy(&cm.StartTime, &ft, sizeof(cm.StartTime));
+ cm.DiffTime.QuadPart = m_settings.getSettings().ReplayDelay * nano100SecInSec;
+ ContactsPair p(hContact, cm);
+
+ m_contacts.insert(p);
+ bRetVal = true;
+ }
+ else
+ { /// there is one...
+ memcpy(&it->second.StartTime, &ft, sizeof(it->second.StartTime));
+ }
+
+ LeaveCriticalSection(&m_critSect);
+
+ return bRetVal;
+END_PROTECT_AND_LOG_CODE
+ return false;
+}
+
+void CMessagesHandler::HookEvents(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+#ifdef _DEBUG
+#endif
+
+ InitializeCriticalSection(&m_critSect);
+ m_settings.Init();
+#ifdef _DEBUG
+ bool bEnabled = m_settings.getSettings().bEnabled;
+#endif
+ m_hEnableEvent = CreateEvent(NULL, TRUE, m_settings.getSettings().bEnabled, NULL);
+
+ DWORD dw = 0;
+ m_bShouldWork = true;
+ m_hFetcherThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ContactsFetcherThread, NULL, NULL, &dw);
+ m_hEvents[0] = HookEvent(ME_DB_EVENT_ADDED, CMessagesHandler::EventAddHook);
+ m_bInited = true;
+END_PROTECT_AND_LOG_CODE
+}
+
+void CMessagesHandler::UnHookEvents(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_bShouldWork = false;
+ if (!m_bInited)
+ return;
+ SetEvent(m_hEnableEvent);
+
+ for (size_t i = 0; i < HOOKS_NUM; i++)
+ UnhookEvent(m_hEvents[i]);
+
+ WaitForSingleObject(m_hFetcherThread, INFINITE);
+ DeleteCriticalSection(&m_critSect);
+ CloseHandle(m_hEnableEvent);
+ //m_settings.DeInit();
+
+ m_hEnableEvent = NULL;
+ m_hFetcherThread = NULL;
+
+END_PROTECT_AND_LOG_CODE
+}
+
+LPTSTR CMessagesHandler::GetContactName(HANDLE hContact)
+{
+ LPARAM lFlags = GCDNF_NOMYHANDLE;
+
+#ifdef _UNICODE
+ lFlags |= GCDNF_UNICODE;
+#endif
+BEGIN_PROTECT_AND_LOG_CODE
+ return reinterpret_cast<LPTSTR>(CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM)hContact, lFlags));
+END_PROTECT_AND_LOG_CODE
+ return NULL;
+}
+
+int CMessagesHandler::SendProtoMess(HANDLE hContact, LPCSTR szMess)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return CallContactService(hContact, PSS_MESSAGE, 0, reinterpret_cast<LPARAM>(szMess));
+END_PROTECT_AND_LOG_CODE
+ return 0;
+}
+
+/** Convert unicode to ansi (utf16 to utf8)
+
+ * @return ansi string or null
+*/
+char* Utf16toUtf8(LPCWSTR lpwszStrIn, UINT & nSize)
+{
+ LPSTR pszOut = NULL;
+
+ if (lpwszStrIn != NULL)
+ {
+
+#define SAFE_DELTA 2
+
+ int nInputStrLen = (int)wcslen(lpwszStrIn);
+ int nOutputStrLen = WideCharToMultiByte(CP_UTF8, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0);
+
+ if (nOutputStrLen == 0)
+ {
+ return NULL;
+ }
+
+ nOutputStrLen += SAFE_DELTA;
+
+ pszOut = (LPSTR)malloc(nOutputStrLen);
+
+ if (pszOut)
+ {
+ nSize = nOutputStrLen - SAFE_DELTA;
+ memset(pszOut, 0x00, nOutputStrLen);
+
+ WideCharToMultiByte(CP_UTF8, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);
+ }
+ }
+
+ return pszOut;
+}
+
+/** Convert unicode to ansi (utf16 to utf8)
+
+ * @return ansi string or null
+*/
+wchar_t* Utf8toUtf16(CHAR * szStrIn, UINT & nSize)
+{
+ wchar_t * pszOut = NULL;
+
+ if (szStrIn != NULL)
+ {
+
+#define SAFE_DELTA 2
+
+ int nInputStrLen = (int)nSize;
+ int nOutputStrLen = MultiByteToWideChar(CP_UTF8, 0, szStrIn, nInputStrLen, NULL, 0);
+
+ if (nOutputStrLen == 0)
+ {
+ return NULL;
+ }
+
+ nOutputStrLen += SAFE_DELTA;
+
+ pszOut = (wchar_t*)malloc(nOutputStrLen * sizeof(wchar_t));
+
+ if (pszOut)
+ {
+ nSize = nOutputStrLen - SAFE_DELTA;
+ memset(pszOut, 0x00, nOutputStrLen * sizeof(wchar_t));
+
+ MultiByteToWideChar(CP_UTF8, 0, szStrIn, nInputStrLen, pszOut, nOutputStrLen);
+ }
+ }
+
+ return pszOut;
+}
+
+/// this handle is invoked wnen
+/// event is added to db
+int CMessagesHandler::EventAddHook(WPARAM wp, LPARAM lp)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ DWORD dwOffset = static_cast<DWORD> (lp);
+ HANDLE hContact = reinterpret_cast<HANDLE>(wp);
+ DBEVENTINFO dbei;
+
+ if (!hContact || !dwOffset)
+ {
+ return FALSE; /// unspecifyed error
+ }
+
+ ZeroMemory(&dbei, sizeof(dbei));
+ dbei.cbSize = sizeof(dbei);
+ dbei.cbBlob = 0;
+
+ CallService(MS_DB_EVENT_GET, lp, (LPARAM)&dbei); /// detect size of msg
+
+ if ((dbei.eventType != EVENTTYPE_MESSAGE) || (dbei.flags == DBEF_READ) || (dbei.flags == DBEF_SENT) )
+ {
+ return FALSE; /// we need EVENTTYPE_MESSAGE event..
+ }
+ else
+ { /// needed event has occured..
+ if (!dbei.cbBlob) /// invalid size
+ {
+ return FALSE;
+ }
+
+ dbei.pBlob = new BYTE[dbei.cbBlob];
+
+ if (dbei.pBlob)
+ {
+ LPARAM lParam = GCDNF_NOMYHANDLE;
+
+#ifdef _UNICODE
+ lParam |= GCDNF_UNICODE;
+#endif
+ CallService(MS_DB_EVENT_GET, lp, reinterpret_cast<LPARAM>(&dbei));
+
+ TCHAR * szMessage = DbGetEventTextT(&dbei, 0);
+
+ TCHAR * szContactName = reinterpret_cast<TCHAR*>(CallService(MS_CLIST_GETCONTACTDISPLAYNAME, wp, lParam));
+
+ CMessagesHandler *ptrHolder = NULL;
+ ptrHolder = CMessagesHandler::GetObject();
+
+ if (!szContactName || !ptrHolder)
+ {
+ return FALSE;
+ }
+
+ if (!ptrHolder->AllowReply(hContact))
+ {
+ return FALSE;
+ }
+
+ TCHAR * lpMessage = NULL;
+
+ {
+ RULE_METAINFO inf = {0};
+ inf.ContactName = szContactName;
+
+ /// analizes all rules and formes autoreply
+ /// message - it's stored in lpMessage
+ /// then - just sent it to user
+ CSettingsHandler & settingsManager = ptrHolder->getSettings();
+ settingsManager.getStorage().IsRuleMatch(inf, lpMessage, szMessage);
+
+ {
+ /// do the lua trick
+ CLuaBridge luaBridge;
+ CSarLuaScript script(luaBridge);
+
+ UINT nReplyScriptLength = 0;
+ CHAR * szReplyScript = NULL;
+
+ szReplyScript = Utf16toUtf8(lpMessage, nReplyScriptLength);
+
+ if (szReplyScript != NULL)
+ {
+ UINT nUserMessage = 0;
+ CHAR * szUserMessage = Utf16toUtf8(szMessage, nUserMessage);
+
+ UINT nUserName = 0;
+ CHAR * szUserName = Utf16toUtf8(szContactName, nUserName);
+
+ script.CompileScript(szReplyScript, nReplyScriptLength);
+
+ script.SelectScriptFunction("SAR");
+ script.AddParam((int)hContact);
+ script.AddParam(szUserMessage);
+ script.AddParam(szUserName);
+ script.AddParam((char*)dbei.szModule);
+ script.Run();
+
+ free(szReplyScript);
+ free(szUserMessage);
+ free(szUserName);
+ }
+ }
+
+ mir_free(szMessage);
+
+ delete lpMessage;
+ delete dbei.pBlob;
+
+ return FALSE;
+ }
+ }
+ }
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+void CMessagesHandler::WriteToHistory(LPTSTR lpMsg, HANDLE hContact)
+{
+ LPTSTR lp1 = TranslateTS(TEXT("Generated autoreply:\r\n"));
+
+ LPTSTR lpszMess = new TCHAR[_tcslen(lpMsg) + _tcslen(lp1)];
+ if (lpszMess == NULL)
+ return;
+
+ memset(lpszMess, 0, (_tcslen(lpMsg) + _tcslen(lp1)) * sizeof(TCHAR));
+ _tcscpy(lpszMess, lp1);
+ _tcscat(lpszMess, lpMsg);
+
+ DBEVENTINFO dbei = {0};
+ dbei.cbSize = sizeof(dbei);
+ dbei.eventType = EVENTTYPE_MESSAGE;
+ dbei.flags = DBEF_READ;
+ dbei.szModule = (char*)CallService(MS_PROTO_GETCONTACTBASEPROTO,(WPARAM)hContact, 0);
+ dbei.timestamp = time(NULL);
+ dbei.cbBlob = _tcslen(lpszMess) + 1;
+ dbei.pBlob = (PBYTE)lpszMess;
+ CallService(MS_DB_EVENT_ADD, (WPARAM)hContact, (LPARAM)&dbei);
+
+ delete lpszMess;
+}
+
+/// getting settings..
+CSettingsHandler & CMessagesHandler::getSettings(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return m_settings;
+END_PROTECT_AND_LOG_CODE
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/MessagesHandler.h b/plugins/SmartAutoReplier/MessagesHandler.h
new file mode 100644
index 0000000000..2d9240f0d5
--- /dev/null
+++ b/plugins/SmartAutoReplier/MessagesHandler.h
@@ -0,0 +1,72 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "settingshandler.h"
+#include "interfaces\ISingletone.h"
+
+#include <map>
+using namespace std;
+
+typedef struct _CONTACT_METAINFO
+{
+ LARGE_INTEGER StartTime;
+ LARGE_INTEGER DiffTime;
+}CONTACT_METAINFO,*PCONTACT_METAINFO;
+
+typedef std::map<HANDLE, CONTACT_METAINFO> ContactsMap;
+typedef std::pair<HANDLE, CONTACT_METAINFO> ContactsPair;
+const __int64 nano100SecInSec = (__int64)10000000;
+
+/// hooks def...
+#define HOOKS_NUM 1
+
+INT WINAPI ContactsFetcherThread(LPVOID lp);
+
+class CMessagesHandler : public IMSingeltone<CMessagesHandler>
+{
+ friend INT WINAPI ContactsFetcherThread(LPVOID lp);
+public:
+ CMessagesHandler(void);
+ ~CMessagesHandler(void);
+public:
+ void HookEvents(void);
+ void UnHookEvents(void);
+ void WriteToHistory(LPTSTR lpMsg, HANDLE hContact);
+ CSettingsHandler & getSettings(void);
+ bool AllowReply(HANDLE hContact);
+ void MakeAction(bool bEnable);
+ static LPTSTR GetContactName(HANDLE hContact);
+ static int SendProtoMess(HANDLE hContact, LPCSTR szMess);
+protected: // hooks procs
+ static int EventAddHook(WPARAM wp, LPARAM lp);
+private:
+ bool m_bInited;
+private:
+ HANDLE m_hEvents[HOOKS_NUM];
+ CSettingsHandler m_settings;
+ ContactsMap m_contacts;
+ CRITICAL_SECTION m_critSect;
+ HANDLE m_hFetcherThread;
+ HANDLE m_hEnableEvent;
+ bool m_bShouldWork;
+}; \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/ModeMessHandler.cpp b/plugins/SmartAutoReplier/ModeMessHandler.cpp
new file mode 100644
index 0000000000..5509bea091
--- /dev/null
+++ b/plugins/SmartAutoReplier/ModeMessHandler.cpp
@@ -0,0 +1,119 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "modemesshandler.h"
+
+/// TODO: add comments and change char* to TCHAR* !!!
+
+/// ctor
+CModeMessHandler::CModeMessHandler(void)
+{
+}
+
+/// dtor
+CModeMessHandler::~CModeMessHandler(void)
+{
+}
+
+TCHAR * CModeMessHandler::StatusModeToDbSetting(int status, TCHAR *suffix)
+{
+ LPTSTR prefix;
+ static TCHAR str[64] = {0};
+
+ switch(status) {
+ case ID_STATUS_AWAY: prefix = TEXT("Away"); break;
+ case ID_STATUS_NA: prefix = TEXT("Na"); break;
+ case ID_STATUS_DND: prefix = TEXT("Dnd"); break;
+ case ID_STATUS_OCCUPIED: prefix = TEXT("Occupied"); break;
+ case ID_STATUS_FREECHAT: prefix = TEXT("FreeChat"); break;
+ case ID_STATUS_ONLINE: prefix = TEXT("On"); break;
+ case ID_STATUS_OFFLINE: prefix = TEXT("Off"); break;
+ case ID_STATUS_INVISIBLE: prefix = TEXT("Inv"); break;
+ case ID_STATUS_ONTHEPHONE: prefix = TEXT("Otp"); break;
+ case ID_STATUS_OUTTOLUNCH: prefix = TEXT("Otl"); break;
+ default:
+ return NULL;
+ }
+ lstrcpy(str, prefix);
+ _tcscat(str, suffix);
+
+ return str;
+}
+
+LPTSTR CModeMessHandler::GetDefaultMessage(INT status)
+{
+ switch (status)
+ {
+ case ID_STATUS_AWAY: return TranslateTS(TEXT("I've been away since %time%."));
+ case ID_STATUS_NA: return TranslateTS(TEXT("Give it up, I'm not in!"));
+ case ID_STATUS_OCCUPIED: return TranslateTS(TEXT("Not right now."));
+ case ID_STATUS_DND: return TranslateTS(TEXT("Give a guy some peace, would ya?"));
+ case ID_STATUS_FREECHAT: return TranslateTS(TEXT("Well, I would talk to you if Miranda IM supported chat"));
+ case ID_STATUS_ONLINE: return TranslateTS(TEXT("Yep, I'm here."));
+ case ID_STATUS_OFFLINE: return TranslateTS(TEXT("Nope, not here."));
+ case ID_STATUS_INVISIBLE: return TranslateTS(TEXT("I'm hiding from the mafia."));
+ case ID_STATUS_ONTHEPHONE: return TranslateTS(TEXT("That'll be the phone."));
+ case ID_STATUS_OUTTOLUNCH: return TranslateTS(TEXT("Mmm...food."));
+ }
+ return NULL;
+}
+
+/// returnes mode message
+/// looks like ret. val should be free(), but
+/// read notes in the place where this func is used
+LPTSTR CModeMessHandler::GetModeMessage(INT statusMode)
+{
+ /*DBVARIANT dbv = {0};
+ INT nretVal = {0}; /// suppose failure..
+
+ nretVal = DBGetContactSetting(NULL, TCHAR("SRAway"), StatusModeToDbSetting(statusMode, TCHAR("Msg")), &dbv);
+ if (nretVal) /// unable to get away msg...
+ {
+ dbv.pszVal = _tcsdup(GetDefaultMessage(statusMode));
+ if (dbv.pszVal == NULL) /// maybe will occure ;)
+ {
+ DBGetContactSetting(NULL, TCHAR("SRAway"), StatusModeToDbSetting(statusMode, TCHAR("Default")), &dbv);
+ }
+ }
+
+ int i;
+ TCHAR substituteStr[128] = {0};
+ for(i = 0; dbv.pszVal[i]; i++)
+ {
+ if (dbv.pszVal[i] != '%')
+ continue;
+ if (!_tcsncicmp((TCHAR*)dbv.pszVal+i, TEXT("%time%"), 6))
+ GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL, NULL, substituteStr, sizeof(substituteStr) / sizeof (TCHAR));
+ else if (!_tcsncicmp((TCHAR*)dbv.pszVal+i, TEXT("%date%"), 6))
+ GetDateFormat(LOCALE_USER_DEFAULT, DATE_SHORTDATE, NULL, NULL, substituteStr, sizeof(substituteStr) / sizeof(TCHAR));
+ else
+ continue;
+ if (_tcslen(substituteStr) > 6)
+ dbv.pszVal = ((TCHAR*))realloc((TCHAR*)dbv.pszVal, _tcslen((TCHAR*)dbv.pszVal) + 1 + _tcslen(substituteStr) - 6);
+ MoveMemory(dbv.pszVal + i + _tcslen(substituteStr), dbv.pszVal + i + 6, _tcslen(dbv.pszVal) - i - 5);
+ CopyMemory(dbv.pszVal + i, substituteStr, _tcslen(substituteStr));
+ }*/
+
+ //return dbv.pszVal;
+
+ return NULL;
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/ModeMessHandler.h b/plugins/SmartAutoReplier/ModeMessHandler.h
new file mode 100644
index 0000000000..87931ba487
--- /dev/null
+++ b/plugins/SmartAutoReplier/ModeMessHandler.h
@@ -0,0 +1,34 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+class CModeMessHandler
+{
+public:
+ CModeMessHandler(void);
+ ~CModeMessHandler(void);
+public:
+ static LPTSTR GetModeMessage(INT nMode);
+private:
+ static LPTSTR GetDefaultMessage(INT status);
+ static TCHAR *StatusModeToDbSetting(int status, TCHAR *suffix);
+};
diff --git a/plugins/SmartAutoReplier/RuleItem.h b/plugins/SmartAutoReplier/RuleItem.h
new file mode 100644
index 0000000000..dd7bfa7549
--- /dev/null
+++ b/plugins/SmartAutoReplier/RuleItem.h
@@ -0,0 +1,47 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "interfaces\isettings.h"
+
+/// a typical rule item
+/// contains info to reply to specific user
+typedef struct _RULE_ITEM : ISettingsStream
+{
+ LPTSTR RuleName, /// item name
+ ContactName, /// contact name
+ ReplyText; /// reply text
+ /*ReplyAction; /// reply action*/
+}RULE_ITEM, *PRULE_ITEM;
+
+/// common item... - a rule that is
+/// applied to all users.
+typedef struct _COMMON_RULE_ITEM : ISettingsStream
+{
+ //LPTSTR Header;
+ LPTSTR Message;
+}COMMON_RULE_ITEM, *P_COMMON_RULE_ITEM;
+
+typedef struct _RULE_METAINFO
+{
+ LPTSTR ContactName;
+}RULE_METAINFO, *PRULE_METAINFO;
diff --git a/plugins/SmartAutoReplier/RulesStorage.cpp b/plugins/SmartAutoReplier/RulesStorage.cpp
new file mode 100644
index 0000000000..6b4f6a2ab0
--- /dev/null
+++ b/plugins/SmartAutoReplier/RulesStorage.cpp
@@ -0,0 +1,536 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "rulesstorage.h"
+#include "crc32static.h"
+
+extern HINSTANCE hInst;
+extern CCrushLog CRUSHLOGOBJ;
+extern CMessagesHandler * g_pMessHandler;
+
+/// ctor...
+CRulesStorage::CRulesStorage(void) : m_hFile(NULL)
+{
+ m_comItem.Message = NULL;
+BEGIN_PROTECT_AND_LOG_CODE
+ MakeFullPath(m_szSettFileName, sizeof(m_szSettFileName), STORAGE_NAME);
+ InitializeCriticalSection(&m_critSect);
+END_PROTECT_AND_LOG_CODE
+}
+
+/// dtor...
+CRulesStorage::~CRulesStorage(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ DeleteCriticalSection(&m_critSect);
+ DeInit();
+END_PROTECT_AND_LOG_CODE
+}
+
+bool CRulesStorage::Serialize(ISettingsStream *pSettings, DWORD & ObjectSize)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ Flush();
+END_PROTECT_AND_LOG_CODE
+ return true;
+}
+
+bool CRulesStorage::Deserialize(DWORD & ObjectSize)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ Init();
+END_PROTECT_AND_LOG_CODE
+ return false;
+}
+
+/// deiniting...
+void CRulesStorage::DeInit(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ if (m_hFile && m_hFile != INVALID_HANDLE_VALUE)
+ CloseHandle(m_hFile);
+
+ m_hFile = NULL;
+
+ /// now release memory...
+ for (RulesHash::iterator it = m_hashTable.begin(); it != m_hashTable.end(); it++)
+ {
+ RULE_ITEM & i = it->second;
+
+ delete i.ContactName;
+ delete i.ReplyText;
+ delete i.RuleName;
+ }
+
+ m_hashTable.clear();
+
+ if (m_comItem.Message != NULL)
+ {
+ delete m_comItem.Message;
+ m_comItem.Message = NULL;
+ }
+
+END_PROTECT_AND_LOG_CODE
+}
+
+/// writing a string into a file..
+void CRulesStorage::RawWriteDataBufByChunk(LPTSTR str)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ int nLength = _tcslen(str) * sizeof(TCHAR);
+ DWORD dwWritten = 0;
+ BOOL bVal = FALSE;
+
+ bVal = WriteFile(m_hFile, &nLength, sizeof(nLength), &dwWritten, NULL);
+
+ if (!bVal || dwWritten != sizeof(nLength))
+ throw bVal;
+
+ bVal = WriteFile(m_hFile, str, nLength, &dwWritten, NULL);
+ if (!bVal || nLength != dwWritten)
+ {
+ throw bVal;
+ }
+END_PROTECT_AND_LOG_CODE
+}
+
+/// flushing all data from memory into a file...
+void CRulesStorage::Flush(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ RulesHash::iterator it;
+
+ SetFilePointer(m_hFile, NULL, NULL, FILE_BEGIN);
+ SetEndOfFile(m_hFile); /// clear old data
+
+ SetCommonMessages();
+
+ for (it = m_hashTable.begin(); it != m_hashTable.end(); it++)
+ {
+ FlushItem(it->second);
+ }
+
+END_PROTECT_AND_LOG_CODE
+}
+
+/// n.c.
+bool CRulesStorage::IsRuleMatch(RULE_METAINFO & info, LPTSTR & strMess, LPTSTR & lpIncomingMsg)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ EnterCriticalSection(&m_critSect);
+
+ RulesHash::iterator iter;
+ bool bExists = false;
+ DWORD dwCRC32 = 0;
+ CCrc32Static::StringCrc32(info.ContactName, dwCRC32);
+ iter = m_hashTable.find(dwCRC32);
+
+ CScriptsReader & screader = g_pMessHandler->getSettings().getScriptsReader();
+
+ if (iter != m_hashTable.end())
+ {
+ /// I have to make copy of ReplyText,
+ /// cause GetReturnedMessage will release ptr
+ /// that is stored rule
+ /// found this bug after 20 min. of debugging ;(
+ strMess = new TCHAR[_tcslen(iter->second.ReplyText) + (1 * sizeof(TCHAR))];
+
+ if (strMess == NULL) /// ooops...
+ {
+ //screader.GetReturnMessage(info.ContactName, strMess, lpIncomingMsg);
+ LeaveCriticalSection(&m_critSect);
+
+ return false;
+ }
+
+ memset(strMess, 0, _tcslen(iter->second.ReplyText) * sizeof(TCHAR) + (1 * sizeof(TCHAR)));
+ _tcscpy(strMess, iter->second.ReplyText);
+ bExists = true;
+ //screader.GetReturnMessage(iter->second.ContactName, strMess, lpIncomingMsg);
+ }
+ else
+ screader.GetReturnMessage(info.ContactName, strMess, lpIncomingMsg);
+
+ LeaveCriticalSection(&m_critSect);
+ return bExists;
+END_PROTECT_AND_LOG_CODE
+ return false;
+}
+
+/// adding rule into memory...
+DWORD CRulesStorage::AddRuleItem(RULE_ITEM item, bool & bExists)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ DWORD dwCRC32 = NULL;
+ CCrc32Static::StringCrc32(item.ContactName, dwCRC32);
+ RulesHash::iterator iter;
+ iter = m_hashTable.find(dwCRC32);
+
+ if (iter != m_hashTable.end())
+ {
+ bExists = true;
+ return 0;
+ }
+
+ bExists = false;
+
+ m_hashTable.insert(RulesHash::value_type(dwCRC32, item));
+ return dwCRC32;
+END_PROTECT_AND_LOG_CODE
+ return 0;
+}
+
+/// flushing item...
+void CRulesStorage::FlushItem(RULE_ITEM & item)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ RawWriteDataBufByChunk(item.RuleName);
+ RawWriteDataBufByChunk(item.ContactName);
+ RawWriteDataBufByChunk(item.ReplyText);
+ //RawWriteDataBufByChunk(item.ReplyAction);
+END_PROTECT_AND_LOG_CODE
+}
+
+/// initing rules manager...
+void CRulesStorage::Init(void)
+{
+#ifdef _DEBUG
+ //MessageBox (NULL, __FUNCTION__, __FILE__, MB_OK);
+#endif
+BEGIN_PROTECT_AND_LOG_CODE
+ if (m_hFile)
+ CloseHandle (m_hFile);
+
+ bool bFileExists = true;
+ if (!PathFileExists(m_szSettFileName))
+ {/// file does not exists...
+ /// need to fill it with common rules...
+ bFileExists = false;
+ }
+
+ m_hFile = CreateFile (m_szSettFileName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, (bFileExists ? OPEN_ALWAYS : CREATE_ALWAYS), FILE_ATTRIBUTE_NORMAL, NULL);
+
+ if (m_hFile == INVALID_HANDLE_VALUE)
+ {/// show notification msg to user..
+ throw INVALID_HANDLE_VALUE;
+ }
+
+ if (bFileExists == false)
+ {
+ ClearCommonMessages();
+ m_comItem.Message = new TCHAR[sizeof(SETTINGS_DEF_MESSAGE) / sizeof(TCHAR) + sizeof(TCHAR)];
+
+ if (m_comItem.Message != NULL)
+ {
+ memset(m_comItem.Message, 0, sizeof(SETTINGS_DEF_MESSAGE) / sizeof(TCHAR) + sizeof(TCHAR));
+ _tcscpy(m_comItem.Message, SETTINGS_DEF_MESSAGE);
+ SetCommonMessages();
+ }
+ }
+
+ DWORD dwSize = 0;
+ dwSize = GetFileSize(m_hFile, &dwSize);
+
+ DWORD dwReaded = 0,
+ dwCrc32 = 0;
+
+ int nLength = 0;
+
+ /// suppose that func is failed
+ BOOL bReaded = FALSE;
+ bool bFailed = false;
+
+ if (bFileExists)
+ {
+ dwSize -= GetCommonMessages();
+ }
+ else
+ {
+ dwSize -= _tcslen(SETTINGS_DEF_MESSAGE) * sizeof(TCHAR);
+ dwSize -= 1 * sizeof(int);
+ }
+
+ while (dwSize)
+ {
+ RULE_ITEM it;
+
+ bReaded = ReadFile(m_hFile, &nLength, sizeof(nLength), &dwReaded, NULL);
+
+ if (bReaded == FALSE || dwReaded != sizeof(nLength))
+ {
+ bFailed = true;
+ break;
+ }
+
+ dwSize -= sizeof(nLength);
+ it.RuleName = new TCHAR[nLength / sizeof(TCHAR) + (1 * sizeof(TCHAR))];
+
+ if (it.RuleName == NULL)
+ {
+ bFailed = true;
+ break;
+ }
+
+ memset(it.RuleName, 0, (nLength + (1 * sizeof(TCHAR))));
+
+ bReaded = ReadFile(m_hFile, it.RuleName, nLength, &dwReaded, NULL);
+ if (bReaded == FALSE || dwReaded != (nLength))
+ {
+ delete it.RuleName;
+ bFailed = true;
+ break;
+ }
+
+ dwSize -= dwReaded;
+ bReaded = ReadFile(m_hFile, &nLength, sizeof(nLength), &dwReaded, NULL);
+
+ if (bReaded == FALSE || dwReaded != sizeof(nLength))
+ {
+ delete it.RuleName;
+ bFailed = true;
+ break;
+ }
+
+ dwSize -= sizeof(nLength);
+ it.ContactName = new TCHAR[nLength / sizeof(TCHAR) + (1 * sizeof(TCHAR))];
+
+ if (it.ContactName == NULL)
+ {
+ delete it.RuleName;
+ bFailed = true;
+ break;
+ }
+
+ memset(it.ContactName, 0, (nLength + (1 * sizeof(TCHAR))));
+ bReaded = ReadFile(m_hFile, it.ContactName, nLength, &dwReaded, NULL);
+
+ if (bReaded == FALSE || dwReaded != (nLength))
+ {
+ delete it.RuleName;
+ delete it.ContactName;
+ bFailed = true;
+ break;
+ }
+
+ dwSize -= dwReaded;
+ bReaded = ReadFile (m_hFile, &nLength, sizeof(nLength), &dwReaded, NULL);
+
+ if (bReaded == FALSE || dwReaded != sizeof(nLength))
+ {
+ delete it.RuleName;
+ delete it.ContactName;
+ bFailed = true;
+ break;
+ }
+
+ dwSize -= sizeof(nLength);
+ it.ReplyText = new TCHAR[nLength / sizeof(TCHAR) + (1 * sizeof(TCHAR))];
+
+ if (it.ReplyText == NULL)
+ {
+ delete it.RuleName;
+ delete it.ContactName;
+ bFailed = true;
+ break;
+ }
+
+ memset(it.ReplyText, 0, (nLength + (1 * sizeof(TCHAR))));
+ bReaded = ReadFile (m_hFile, it.ReplyText, nLength, &dwReaded, NULL);
+
+ if (bReaded == FALSE || dwReaded != (nLength))
+ {
+ delete it.RuleName;
+ delete it.ContactName;
+ delete it.ReplyText;
+
+ bFailed = true;
+ break;
+ }
+
+ dwSize -= dwReaded;
+
+ dwCrc32 = NULL;
+ CCrc32Static::StringCrc32(it.ContactName, dwCrc32);
+ m_hashTable.insert(RulesHash::value_type(dwCrc32, it) ); /// filling list
+ }
+
+ if (bFailed)
+ { /// upps...
+ bool bdelete = NotifyAboutWrongSettings(m_szSettFileName);
+
+ if (bdelete)
+ {
+ CloseHandle (m_hFile);
+ m_hFile = NULL;
+ DeleteFile (m_szSettFileName);
+ DeInit();
+ Init();
+ }
+ }
+
+END_PROTECT_AND_LOG_CODE
+}
+
+/// reading an data from file storage...
+UINT CRulesStorage::RawReadDataBufByChunk(LPTSTR & szData)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ UINT nRetVal = 0;
+
+ if (m_hFile == NULL || m_hFile == INVALID_HANDLE_VALUE)
+ {
+ return nRetVal;
+ }
+
+ int nSizeOf = 0;
+ DWORD dwReaded = 0;
+ const int nsizeof = sizeof(nSizeOf);
+ BOOL bReaded = ReadFile(m_hFile, &nSizeOf, nsizeof, &dwReaded, NULL);
+ nRetVal += dwReaded;
+
+ if (bReaded == FALSE || dwReaded != nsizeof)
+ {
+ return nRetVal;
+ }
+
+ szData = new TCHAR[(nSizeOf / sizeof(TCHAR)) + (1 * sizeof(TCHAR))];
+
+ if (szData == NULL)
+ {
+ return nRetVal + dwReaded;
+ }
+
+ memset(szData, 0, nSizeOf + (1 * sizeof(TCHAR)));
+ bReaded = ReadFile(m_hFile, szData, nSizeOf, &dwReaded, NULL);
+ nRetVal += dwReaded;
+
+ if (bReaded == FALSE || dwReaded != nSizeOf)
+ {
+ delete szData;
+ szData = NULL;
+ return nRetVal;
+ }
+
+ return nRetVal;
+END_PROTECT_AND_LOG_CODE
+}
+
+///
+void CRulesStorage::SetCommonMessages(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ RawWriteDataBufByChunk(m_comItem.Message);
+END_PROTECT_AND_LOG_CODE
+}
+
+void CRulesStorage::ClearCommonMessages(void)
+{
+ if (m_comItem.Message)
+ {
+ delete m_comItem.Message;
+ m_comItem.Message = NULL;
+ }
+}
+
+/// reads from storage common rules - header and
+/// message that is replyed to all users...
+UINT CRulesStorage::GetCommonMessages(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ ClearCommonMessages();
+ UINT nRetVal = 0;
+
+ nRetVal += RawReadDataBufByChunk(m_comItem.Message);
+
+ return nRetVal;
+END_PROTECT_AND_LOG_CODE
+#undef RAW_DATACLEAR
+ return 0;
+}
+
+void CRulesStorage::setCommonRule(COMMON_RULE_ITEM r) /// n.c.
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ memcpy (&m_comItem, &r, sizeof(COMMON_RULE_ITEM));
+END_PROTECT_AND_LOG_CODE
+}
+
+COMMON_RULE_ITEM & CRulesStorage::getCommonRule(void) /// n.c.
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return m_comItem;
+END_PROTECT_AND_LOG_CODE
+}
+
+/// getting hash table
+RulesHash & CRulesStorage::getHashTable(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return m_hashTable;
+END_PROTECT_AND_LOG_CODE
+}
+
+/// remove rule by its id
+bool CRulesStorage::RemReplyAction(DWORD dwCrc32)
+{
+ bool bRetVal = false;
+BEGIN_PROTECT_AND_LOG_CODE
+ EnterCriticalSection(&m_critSect);
+ RulesHash::iterator it;
+ it = m_hashTable.find(dwCrc32);
+ if (it != m_hashTable.end())
+ {
+ delete it->second.ContactName;
+ delete it->second.ReplyText;
+ delete it->second.RuleName;
+
+ m_hashTable.erase(it);
+ bRetVal = true;
+ }
+ LeaveCriticalSection(&m_critSect);
+END_PROTECT_AND_LOG_CODE
+ return bRetVal;
+}
+
+bool CRulesStorage::RuleIsRegistered(LPTSTR lpContactName)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ bool bRetVal = false;
+ if (lpContactName == NULL)
+ return bRetVal;
+ DWORD dwCRC32 = NULL;
+ CCrc32Static::StringCrc32(lpContactName, dwCRC32);
+ RulesHash::iterator iter;
+
+ EnterCriticalSection(&m_critSect);
+ iter = m_hashTable.find(dwCRC32);
+
+ if (iter != m_hashTable.end())
+ {
+ bRetVal = true;
+ }
+ LeaveCriticalSection(&m_critSect);
+
+ return bRetVal;
+END_PROTECT_AND_LOG_CODE
+ return false;
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/RulesStorage.h b/plugins/SmartAutoReplier/RulesStorage.h
new file mode 100644
index 0000000000..25cbec2942
--- /dev/null
+++ b/plugins/SmartAutoReplier/RulesStorage.h
@@ -0,0 +1,63 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "RuleItem.h"
+#include <map>
+
+#define STORAGE_NAME TEXT("sar.rsu") /// a def. name of a file that is storing settings
+typedef std::map<INT, RULE_ITEM> RulesHash; /// storage representation in memory
+
+/// storage manager..
+class CRulesStorage : ISettings
+{
+public: /// ctor'rs, dtors..
+ CRulesStorage(void);
+ ~CRulesStorage(void);
+public: /// ISettings interface...
+ bool Serialize(ISettingsStream *pSettings, DWORD & ObjectSize);
+ bool Deserialize(DWORD & ObjectSize);
+public:
+ void Init(void); /// initing state of an object
+ void DeInit(void); /// deiniting state of an object
+ DWORD AddRuleItem(RULE_ITEM item, bool & bExists); /// n.c.
+ bool RemReplyAction(DWORD dwCrc32); /// n.c.
+ RulesHash & getHashTable(void); /// n.c.
+ COMMON_RULE_ITEM & getCommonRule(void); /// n.c.
+ void setCommonRule(COMMON_RULE_ITEM r); /// n.c.
+ void Flush(void); /// flushes all from memory to a file
+ void FlushItem(RULE_ITEM & item); /// flushes an item into file from memory
+ bool IsRuleMatch(RULE_METAINFO & info, LPTSTR & strMess, LPTSTR & lpIncomingMsg); /// n.c.
+ void ClearCommonMessages(void); /// releases memory that is commited for comm. rule
+ bool RuleIsRegistered(LPTSTR lpContactName);
+private:
+ void RawWriteDataBufByChunk(LPTSTR); /// writes string to a file
+ UINT RawReadDataBufByChunk(LPTSTR & szData); /// reads string from file
+ UINT GetCommonMessages(void); /// gets common rules from file to memory
+ void SetCommonMessages(void); /// sets common rules from memory to file
+private:
+ COMMON_RULE_ITEM m_comItem; /// common rule item..
+ RulesHash m_hashTable; /// main storage...
+ HANDLE m_hFile; /// handle to file that is storing data
+ TCHAR m_szSettFileName[MAX_PATH]; /// path to a file...
+ CRITICAL_SECTION m_critSect; /// needed for sync
+}; \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/SAR.cpp b/plugins/SmartAutoReplier/SAR.cpp
new file mode 100644
index 0000000000..901ef60b69
--- /dev/null
+++ b/plugins/SmartAutoReplier/SAR.cpp
@@ -0,0 +1,462 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "resource.h"
+
+/// these dlg are necessary here..
+#include "gui\settingsdlgholder.h"
+#include "gui\EditReplyDlg.h"
+#include "gui\addruledlg.h"
+
+#include "../updater/m_updater.h"
+
+/// let's advertise myselft and this plugin ;)
+#define ICQPROTONAME "SAR"
+#if defined( _UNICODE )
+#define ICQPROTODECRSHORT "Smart Auto Replier"
+#else
+#define ICQPROTODECRSHORT "Smart Auto Replier"
+#endif
+#define ICQPROTODECR "Plugin is able to reply on all incoming messages, making possible use of rules that are applied to specific contacts. Plugin allows to use Lua scripts as a rules, thus allowing user to make virtually any type of customizations."
+#define DEVNAME "Volodymyr M. Shcherbyna"
+#define DEVMAIL "volodymyr@shcherbyna.com"
+#define DEVCOPYRIGHT "� 2004-2012 Volodymyr M. Shcherbyna, www.shcherbyna.com"
+#define DEVWWW "http://www.shcherbyna.com/forum/viewforum.php?f=8"
+#define GLOB_HOOKS 3
+
+/// global menu items strings...
+#define MENU_ITEM_DISABLE_CAPTION TranslateTS(TEXT("Disable Smart Auto Replier"))
+#define MENU_ITEM_ENABLE_CAPTION TranslateTS(TEXT("Enable Smart Auto Replier"))
+
+//#define
+/// global data...
+HINSTANCE hInst = NULL; /// hinstance
+PLUGINLINK *pluginLink = NULL; /// ptr to plugin object
+CMessagesHandler *g_pMessHandler = NULL; /// ptr to "main" global manager object
+CSettingsDlgHolder *g_pSettingsDlg = NULL;
+static HANDLE g_hHook[GLOB_HOOKS] = {NULL}; /// global hooks
+CLISTMENUITEM g_mi = {NULL}; /// handle to menu item that is used to switch on/off plugin
+CLISTMENUITEM g_miAUR2This = {NULL}; /// handle to menu item that is used to add user to aur
+bool g_bEnableMItem = true; /// flag for menu item..
+HANDLE g_hMenuItem; /// global handle to menu service
+CCrushLog CRUSHLOGOBJ; /// global object that handles all crushes
+LPTSTR g_strPluginName = TEXT(ICQPROTONAME); /// global string that represents plugin name...
+INT g_nCurrentMode = 0; /// current mode of a protocol == i duno which exactly protocol...
+HANDLE g_hAUR2User = NULL; /// handle to proto service of "autoreply to this user"
+
+struct MM_INTERFACE mmi;
+
+/// forming an info structure
+PLUGININFOEX pluginInfo =
+{
+ sizeof(PLUGININFOEX),
+ ICQPROTODECRSHORT,
+ PLUGIN_MAKE_VERSION(2, 0, 0, 3),
+ ICQPROTODECR,
+ DEVNAME,
+ DEVMAIL,
+ DEVCOPYRIGHT,
+ DEVWWW,
+ UNICODE_AWARE,
+ 0,
+//#if defined( _UNICODE )
+// // {B9C9AC38-9D81-45D3-A9D7-67A7D8EA9D29}
+// { 0xb9c9ac38, 0x9d81, 0x45d3, { 0xa9, 0xd7, 0x67, 0xa7, 0xd8, 0xea, 0x9d, 0x29 } }
+//#else
+ // {9E536082-017E-423B-BF4F-DEDFEB9B3B60}
+ { 0x9e536082, 0x17e, 0x423b, { 0xbf, 0x4f, 0xde, 0xdf, 0xeb, 0x9b, 0x3b, 0x60 } }
+//#endif
+};
+
+/// mapping into mirandaim.exe
+BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ hInst = hinstDLL;
+ DisableThreadLibraryCalls(hinstDLL);
+ return TRUE;
+END_PROTECT_AND_LOG_CODE
+}
+
+__declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
+{
+ return &pluginInfo;
+}
+
+static const MUUID interfaces[] = {MIID_CHAT, MIID_SRMM, MIID_LAST};
+
+__declspec(dllexport) const MUUID * MirandaPluginInterfaces(void)
+{
+ return interfaces;
+}
+
+/// handler of event when the options are choosed
+static int OptionsInitialized(WPARAM wp, LPARAM lp)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ LPTSTR lpszGroup = TranslateTS(TEXT("Plugins"));
+ OPTIONSDIALOGPAGE optsDialog = {0};
+ optsDialog.cbSize = sizeof(OPTIONSDIALOGPAGE);
+ optsDialog.hInstance = hInst;
+ optsDialog.position = 910000000;
+ optsDialog.pszTemplate = (char*)MAKEINTRESOURCE(IDD_SDLGHOLDER);
+ TCHAR szMax[MAX_PATH] = {0};
+ _tcscpy(szMax, TranslateTS(TEXT(ICQPROTODECRSHORT)));
+
+#ifdef _UNICODE
+ optsDialog.ptszGroup = lpszGroup;
+ optsDialog.ptszTitle = szMax;
+#else
+ optsDialog.pszTitle = (char*)szMax;
+ optsDialog.pszGroup = lpszGroup;
+#endif
+ optsDialog.pfnDlgProc = (DLGPROC)&CSettingsDlgHolder::FakeDlgProc;
+ optsDialog.flags = ODPF_BOLDGROUPS/*|ODPF_EXPERTONLY*/; /// some lames are scaring that option...
+#ifdef _UNICODE
+ optsDialog.flags |= ODPF_UNICODE;
+#endif
+
+ g_pSettingsDlg->m_bDestroying = false;
+ CallService(MS_OPT_ADDPAGE, wp, reinterpret_cast<LPARAM>(&optsDialog));
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+/// pre building menu item for a contact..
+static int AURContactPreBuildMenu(WPARAM wParam, LPARAM lParam)
+{
+ LPTSTR lpContactName = g_pMessHandler->GetContactName(reinterpret_cast<HANDLE>(wParam));
+ CRulesStorage & storage = g_pMessHandler->getSettings().getStorage();
+ bool bval = storage.RuleIsRegistered(lpContactName);
+
+ if (bval)
+ {
+ g_miAUR2This.flags = CMIM_FLAGS | CMIF_GRAYED;
+ }
+ else
+ {
+ g_miAUR2This.flags = CMIM_FLAGS;
+ }
+
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM)g_hAUR2User, (LPARAM)&g_miAUR2This);
+
+ return 0;
+}
+
+/// handler of clicking on menu item
+/// aur to this user...
+static int AUR2User(WPARAM wParam, LPARAM lParam)
+{
+ CAddRuleDlg dlg;
+ RULE_ITEM item;
+ item.ContactName = g_pMessHandler->GetContactName(reinterpret_cast<HANDLE>(wParam));
+ //item.ReplyAction = " ";
+ item.ReplyText = SETTINGS_DEF_MESSAGE_RULE;
+ TCHAR rulename[MAX_PATH * 5] = {0};
+ _tcscat(rulename, TEXT("reply to "));
+ _tcscat(rulename, item.ContactName);
+ item.RuleName = rulename;
+
+ dlg.m_baur2thisMode = true;
+ dlg.m_item = item;
+ dlg.DoModal();
+ if (dlg.m_bAddedOk)
+ { /// already added...
+ OnRefreshSettings();
+ }
+
+ return 0;
+}
+
+/// handler of clicking on menu item enablr/disable plugin...
+static int PluginMenuCommand(WPARAM wParam, LPARAM lParam)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ if (!g_pMessHandler)
+ return 0;
+
+ if (g_bEnableMItem)
+ {/// lets handle enabling of AUR feature
+ g_pMessHandler->MakeAction(true); /// this will enable plugin
+ }
+ else
+ {/// lets handle disabling of AUR feature
+ g_pMessHandler->MakeAction(false); /// this will disable plugin
+ }
+
+ /// put here stuff to do
+ TCHAR sz[MAX_PATH] = {0};
+ _tcscpy(sz, (g_bEnableMItem == true ? MENU_ITEM_DISABLE_CAPTION : MENU_ITEM_ENABLE_CAPTION));
+ g_mi.pszName = (char*)TranslateTS(sz);
+ g_mi.flags = CMIM_NAME;
+
+#ifdef _UNICODE
+ g_mi.flags |= CMIF_UNICODE;
+#endif
+
+#ifdef _DEBUG
+ int nretval =
+#endif
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM)g_hMenuItem, (LPARAM)&g_mi);
+
+ g_bEnableMItem = !g_bEnableMItem;
+END_PROTECT_AND_LOG_CODE
+ return 0;
+}
+
+/// handler that is invoked when mode is changed
+static int OnStatusModeChanged(WPARAM wp, LPARAM lp)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ g_nCurrentMode = static_cast<INT>(wp);
+ if (!g_pMessHandler)
+ return FALSE;
+
+ bool bNonOnOffLine = (wp != ID_STATUS_ONLINE &&
+ wp != ID_STATUS_OFFLINE &&
+ wp != ID_STATUS_FREECHAT);
+
+ REPLYER_SETTINGS & s = g_pMessHandler->getSettings().getSettings();
+ COMMON_RULE_ITEM & r = g_pMessHandler->getSettings().getStorage().getCommonRule();
+
+ if (!bNonOnOffLine && s.bDisableWhenModeIsSet)
+ {
+ if (s.bEnabled) /// plugin is enabled... we have a chance to disable it
+ {
+ bool bDisableIt = false;
+
+ if (s.ModeDisValue == 0)
+ bDisableIt = true;
+ else if (s.ModeDisValue == 1 && wp == ID_STATUS_ONLINE)
+ bDisableIt = true;
+ else if (s.ModeDisValue == 2 && wp == ID_STATUS_FREECHAT)
+ bDisableIt = true;
+
+ if (bDisableIt)
+ { /// disable plugin...
+ PluginMenuCommand(0, 0);
+ }
+ }
+ return FALSE;
+ }
+
+ if (s.bShowAURDlgWhenModeChanges)
+ {
+ CEditReplyDlg dlg;
+ dlg.m_commRule = r;
+
+ dlg.DoModal();
+ if (dlg.m_bAllOk)
+ {
+ r = dlg.m_commRule;
+ }
+ }
+ if (s.bEnableWhenModeIsSet)
+ {
+ if (!s.bEnabled)
+ {
+ bool bEnable = false;
+ if (s.ModeValue == 0 && bNonOnOffLine)
+ bEnable = true;
+ else if (s.ModeValue == 1 && wp == ID_STATUS_DND)
+ bEnable = true;
+ else if (s.ModeValue == 2 && wp == ID_STATUS_NA)
+ bEnable = true;
+ else if (s.ModeValue == 3 && wp == ID_STATUS_AWAY)
+ bEnable = true;
+ else if (s.ModeValue == 4 && wp == ID_STATUS_OCCUPIED)
+ bEnable = true;
+
+ if (bEnable) /// enabling plugin... (I realize that enabling and disabling is made via ass but i am lazy today)
+ PluginMenuCommand(0, 0);
+ }
+ }
+
+ return FALSE;
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+#ifndef _DEBUG
+LPTOP_LEVEL_EXCEPTION_FILTER UnhandledExceptionFilter(
+ LPTOP_LEVEL_EXCEPTION_FILTER lpTopLevelExceptionFilter
+)
+{
+ LPTOP_LEVEL_EXCEPTION_FILTER f = {0};
+BEGIN_PROTECT_AND_LOG_CODE
+ throw f; /// show msgbox to user and store inf to file
+END_PROTECT_AND_LOG_CODE
+ return f; /// let compiler shut ups...
+}
+#endif
+
+int OnModulesLoaded(WPARAM wParam, LPARAM lParam)
+{
+ Update update = {0}; // for c you'd use memset or ZeroMemory...
+ char szVersion[16];
+
+ update.cbSize = sizeof(Update);
+
+ update.szComponentName = pluginInfo.shortName;
+ update.pbVersion = (BYTE*)CreateVersionStringPluginEx(&pluginInfo, szVersion);
+ update.cpbVersion = strlen((char*)update.pbVersion);
+
+ // these are the three lines that matter - the archive, the page containing the version string, and the text (or data)
+ // before the version that we use to locate it on the page
+ // (note that if the update URL and the version URL point to standard file listing entries, the backend xml
+ // data will be used to check for updates rather than the actual web page - this is not true for beta urls)
+ //update.szUpdateURL = "http://www.shcherbyna.com/files/sar/SAR.zip";
+ //update.szVersionURL = "http://www.shcherbyna.com/files/sar/SAR.html";
+
+ update.szUpdateURL = "http://addons.miranda-im.org/details.php?action=viewfile&id=1609";
+
+ //update.pbVersionPrefix = (BYTE *)"SAR version ";
+
+ //update.cpbVersionPrefix = strlen((char *)update.pbVersionPrefix);
+
+ // do the same for the beta versions of the above struct members if you wish to allow beta updates from another URL
+
+ CallService(MS_UPDATE_REGISTER, 0, (WPARAM)&update);
+
+ // Alternatively, to register a plugin with e.g. file ID 2254 on the file listing...
+ // CallService(MS_UPDATE_REGISTERFL, (WPARAM)2254, (LPARAM)&pluginInfo);
+
+ return 0;
+}
+
+/// loading plugin
+extern "C" int __declspec(dllexport) Load(PLUGINLINK *link)
+{
+#ifndef _DEBUG
+ SetUnhandledExceptionFilter(UnhandledExceptionFilter);
+#endif
+#ifdef _DEBUG
+ //MessageBox (NULL, __FUNCTION__, __FILE__, MB_OK);
+#endif
+
+ CCrushLog::Init(); /// crushes manager should be inited first
+ int nRetVal = 0;
+BEGIN_PROTECT_AND_LOG_CODE
+ pluginLink = link;
+
+#ifndef _DEBUG
+ /// creates help file near plugin
+ /// if it is absent...
+ /// note: originally help is in recources of plugin
+ //CheckForHelpFile();
+#endif
+ /// main manager...
+ g_pMessHandler = new CMessagesHandler();
+ g_pSettingsDlg = new CSettingsDlgHolder();
+
+ if (g_pMessHandler)
+ { /// is inited
+ REPLYER_SETTINGS & s = g_pMessHandler->getSettings().getSettings();
+ if (s.bDisableWhenMirandaIsOn)
+ {
+ s.bEnabled = false;
+ }
+ else
+ {
+ if (s.bEnabled)
+ g_pMessHandler->HookEvents();
+ }
+
+ /// hook main events
+ //HookEvent(MS_AWAYMSG_SHOWAWAYMSG, OnShow
+ g_hHook[0] = HookEvent(ME_OPT_INITIALISE, OptionsInitialized);
+ g_hHook[1] = HookEvent(ME_CLIST_STATUSMODECHANGE, OnStatusModeChanged);
+ g_hHook[2] = HookEvent(ME_SYSTEM_MODULESLOADED, OnModulesLoaded);
+
+ /// Yushenko Tak, Yanukovich - Mudak. (Orange revolution)
+ /// this was written in 2004-2005 in Kiev :)
+
+ /// create menu item for disabling / enabling plugin
+ CreateServiceFunction("AUR/MenuCommand", PluginMenuCommand);
+ ZeroMemory(&g_mi, sizeof(g_mi));
+ g_mi.cbSize = sizeof(g_mi);
+ g_mi.position = -0x7FFFFFFF;
+ g_mi.flags = 0;
+ g_mi.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_SAR_ICON)); //LoadSkinnedIcon(IDI_AUR_ICON/*SKINICON_OTHER_MIRANDA*/);
+ bool bVal = g_pMessHandler->getSettings().getSettings().bEnabled;
+ TCHAR sz[MAX_PATH] = {0};
+ _tcscpy(sz, bVal ? MENU_ITEM_DISABLE_CAPTION : MENU_ITEM_ENABLE_CAPTION);
+#ifdef _UNICODE
+ g_mi.ptszName = TranslateTS(sz);
+ g_mi.flags = CMIF_UNICODE;
+#else
+ g_mi.pszName = (char*)TranslateTS(sz);
+#endif
+ g_mi.pszService = "AUR/MenuCommand";
+
+ g_hMenuItem = (HANDLE)CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM)&g_mi);
+ g_bEnableMItem = !bVal;
+
+ /// creating menu item for a contact
+ ZeroMemory(&g_miAUR2This, sizeof(g_miAUR2This));
+ g_miAUR2This.cbSize = sizeof(g_miAUR2This);
+ g_miAUR2This.position = -2000010000;
+ g_miAUR2This.flags = 0;
+ g_miAUR2This.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_SAR_ICON));
+ g_miAUR2This.pszContactOwner = NULL;
+#ifdef _UNICODE
+ g_miAUR2This.ptszName = TranslateTS(TEXT("&Smart Auto Reply to this user ..."));
+ g_miAUR2This.flags = CMIF_UNICODE;
+#else
+ g_miAUR2This.pszName = TranslateTS(TEXT("&Smart Auto Reply to this user ..."));
+#endif
+ CreateServiceFunction("AUR/AURToThis", AUR2User);
+ g_miAUR2This.pszService = "AUR/AURToThis";
+ g_hAUR2User = (HANDLE)CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM)&g_miAUR2This);
+ HookEvent(ME_CLIST_PREBUILDCONTACTMENU, AURContactPreBuildMenu);
+ }
+
+ CallService(MS_SYSTEM_GET_MMI, 0, (LPARAM)&mmi);
+
+END_PROTECT_AND_LOG_CODE
+ return FALSE;
+}
+
+/// unloading plugin
+extern "C" int __declspec(dllexport) Unload(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ for (size_t i = 0; i < GLOB_HOOKS; i++)
+ UnhookEvent(g_hHook[i]);
+
+ if (g_pSettingsDlg)
+ {
+ if (g_pSettingsDlg->IsWindow())
+ g_pSettingsDlg->DestroyWindow();
+ delete g_pSettingsDlg;
+ }
+ if (g_pMessHandler)
+ { /// unhook manager's events...
+ g_pMessHandler->UnHookEvents();
+ delete g_pMessHandler; /// call dtor
+ g_pMessHandler = NULL;
+ }
+END_PROTECT_AND_LOG_CODE
+
+ CCrushLog::DeInit(); /// destroy crushes manager obj
+ return FALSE;
+}
diff --git a/plugins/SmartAutoReplier/SAR.rc b/plugins/SmartAutoReplier/SAR.rc
new file mode 100644
index 0000000000..5ae222d012
--- /dev/null
+++ b/plugins/SmartAutoReplier/SAR.rc
@@ -0,0 +1,274 @@
+// Microsoft Visual C++ generated resource script.
+//
+#include "resource.h"
+
+#define APSTUDIO_READONLY_SYMBOLS
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 2 resource.
+//
+#include "afxres.h"
+
+/////////////////////////////////////////////////////////////////////////////
+#undef APSTUDIO_READONLY_SYMBOLS
+
+/////////////////////////////////////////////////////////////////////////////
+// Ukrainian (Ukraine) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_UKR)
+LANGUAGE LANG_UKRAINIAN, SUBLANG_DEFAULT
+#pragma code_page(1251)
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_OPTIONS DIALOGEX 0, 0, 308, 208
+STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_SYSMENU
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ EDITTEXT IDC_EDIT_REPLAYDELAY,68,10,29,13,ES_MULTILINE | ES_AUTOHSCROLL | ES_WANTRETURN | ES_NUMBER
+ EDITTEXT IDC_EDIT_MESSAGE,68,24,232,53,ES_MULTILINE | ES_WANTRETURN | WS_VSCROLL
+ LISTBOX IDC_LIST_RULES,60,84,236,61,LBS_SORT | LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_GROUP | WS_TABSTOP
+ PUSHBUTTON "Add rule",IDC_BTN_ADDRULE,8,85,50,14
+ PUSHBUTTON "Delete rule",IDC_BTN_DELRULE,8,101,50,14,WS_DISABLED
+ PUSHBUTTON "Edit rule",IDC_BTN_EDITRULE,8,117,50,14,WS_DISABLED
+ LTEXT "Action script:",IDC_STATIC_MESSAGE_TEXT,8,42,51,10
+ GROUPBOX "Auto replier settings",IDC_STATIC,0,0,306,204
+ LTEXT "Reply delay:",IDC_STATIC,9,12,41,8
+ LTEXT "second(s)",IDC_STATIC,106,13,32,8
+ GROUPBOX "Custom rules",IDC_STATIC,5,75,294,73
+ CONTROL "Disable when Miranda is switched on",IDC_CHECK_DISABLEWMON,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,149,12,151,11
+ CONTROL "Enable when status becomes",IDC_CH_ENABLE_WSCH,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,6,152,125,10
+ COMBOBOX IDC_CB_ENWSC,144,151,156,36,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
+ CONTROL "Ask to set autoreply message when mode changes",IDC_CH_SHOWCG,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,6,180,266,10
+ CONTROL "Disable when status becomes",IDC_CH_DISWHSB,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,6,167,129,10
+ COMBOBOX IDC_CB_DWSB,143,165,156,40,CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP
+ CONTROL "Save autoreplies to history",IDC_CH_SAVE_AURS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,6,193,266,10
+END
+
+IDD_ADDRULE_DLG DIALOGEX 0, 0, 384, 250
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Add contact specific Smart Auto Replier action script"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ EDITTEXT IDC_ED_RULENAME,68,14,184,12,ES_MULTILINE | ES_WANTRETURN | WS_VSCROLL
+ EDITTEXT IDC_ED_RULECNAME,68,29,168,13,ES_MULTILINE | ES_WANTRETURN | WS_VSCROLL
+ EDITTEXT IDC_ED_RULEREPLY,21,54,342,166,ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL
+ DEFPUSHBUTTON "OK",IDOK,325,231,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,273,231,50,14
+ PUSHBUTTON "...",IDC_BTN_SELUSER,238,28,13,14
+ GROUPBOX "Rule settings",IDC_STATIC,7,3,368,225
+ LTEXT "Rule name:",IDC_STATIC,15,16,41,10
+ LTEXT "Contact name",IDC_STATIC,15,31,46,10
+ GROUPBOX "Action script",IDC_STATIC,14,42,355,182
+END
+
+IDD_SET_AURMESSAGEDLG DIALOGEX 0, 0, 291, 157
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Set Smart Auto Replier action script"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ EDITTEXT IDC_ED_TEXT,6,10,278,123,ES_MULTILINE | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL
+ DEFPUSHBUTTON "OK",IDOK,239,139,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,186,139,50,14
+ GROUPBOX "Smart Auto Replier action script",IDC_STATIC,2,0,287,137
+END
+
+IDD_SEL_USER DIALOGEX 0, 0, 92, 194
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Select user from a list"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ DEFPUSHBUTTON "Select",IDOK,51,178,40,14
+ PUSHBUTTON "Exit",IDCANCEL,1,178,38,14
+ LISTBOX IDC_LIST_USERS,1,2,89,174,LBS_HASSTRINGS | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
+END
+
+IDD_HISTORYLOGS DIALOGEX 0, 0, 186, 95
+STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
+CAPTION "Dialog"
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ DEFPUSHBUTTON "OK",IDOK,129,7,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,129,24,50,14
+END
+
+IDD_SDLGHOLDER DIALOGEX 0, 0, 326, 253
+STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_SYSMENU
+FONT 8, "MS Shell Dlg", 400, 0, 0x1
+BEGIN
+ CONTROL "",IDC_TABSHOLDER,"SysTabControl32",0x0,4,13,316,224
+ LTEXT "Static",IDC_STATUSMSG,7,3,300,8
+END
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// DESIGNINFO
+//
+
+#ifdef APSTUDIO_INVOKED
+GUIDELINES DESIGNINFO
+BEGIN
+ IDD_OPTIONS, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ TOPMARGIN, 3
+ BOTTOMMARGIN, 195
+ END
+
+ IDD_ADDRULE_DLG, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 377
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 247
+ END
+
+ IDD_SET_AURMESSAGEDLG, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 284
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 150
+ END
+
+ IDD_SEL_USER, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 85
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 187
+ END
+
+ IDD_HISTORYLOGS, DIALOG
+ BEGIN
+ LEFTMARGIN, 7
+ RIGHTMARGIN, 179
+ TOPMARGIN, 7
+ BOTTOMMARGIN, 88
+ END
+
+ IDD_SDLGHOLDER, DIALOG
+ BEGIN
+ LEFTMARGIN, 2
+ RIGHTMARGIN, 302
+ TOPMARGIN, 3
+ BOTTOMMARGIN, 237
+ END
+END
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_SAR_ICON ICON "sar.ico"
+#endif // Ukrainian (Ukraine) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+/////////////////////////////////////////////////////////////////////////////
+// English (United States) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+#pragma code_page(1252)
+
+#ifdef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// TEXTINCLUDE
+//
+
+1 TEXTINCLUDE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE
+BEGIN
+ "#include ""afxres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+#endif // English (United States) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+/////////////////////////////////////////////////////////////////////////////
+// French (Switzerland) resources
+
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_FRS)
+LANGUAGE LANG_FRENCH, SUBLANG_FRENCH_SWISS
+#pragma code_page(1252)
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION 2,0,0,3
+ PRODUCTVERSION 2,0,0,3
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE 0x0L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "042204b0"
+ BEGIN
+ VALUE "CompanyName", "Volodymyr Shcherbyna, www.shcherbyna.com"
+ VALUE "FileDescription", "Smart Auto Replier plugin for Miranda IM, http://shcherbyna.com/forum/viewforum.php?f=8"
+ VALUE "FileVersion", "2.0.0.3"
+ VALUE "InternalName", "sar.dll"
+ VALUE "LegalCopyright", "Copyright (C) 2004 - 2012 by Volodymyr Shcherbyna"
+ VALUE "OriginalFilename", "sar.dll"
+ VALUE "ProductName", "sar.dll"
+ VALUE "ProductVersion", "2.0.0.3"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x422, 1200
+ END
+END
+
+#endif // French (Switzerland) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/plugins/SmartAutoReplier/SAR.sln b/plugins/SmartAutoReplier/SAR.sln
new file mode 100644
index 0000000000..b4ec12ff29
--- /dev/null
+++ b/plugins/SmartAutoReplier/SAR.sln
@@ -0,0 +1,25 @@
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SAR", "SAR.vcxproj", "{C71749EF-EBA8-4317-9F9E-327E1A7366EC}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lualib", "..\lualib\lualib.vcxproj", "{6DB53D29-2EA9-407B-84F3-06E8031F3314}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Win32 = Debug|Win32
+ Release|Win32 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {C71749EF-EBA8-4317-9F9E-327E1A7366EC}.Debug|Win32.ActiveCfg = Debug|Win32
+ {C71749EF-EBA8-4317-9F9E-327E1A7366EC}.Debug|Win32.Build.0 = Debug|Win32
+ {C71749EF-EBA8-4317-9F9E-327E1A7366EC}.Release|Win32.ActiveCfg = Release|Win32
+ {C71749EF-EBA8-4317-9F9E-327E1A7366EC}.Release|Win32.Build.0 = Release|Win32
+ {6DB53D29-2EA9-407B-84F3-06E8031F3314}.Debug|Win32.ActiveCfg = Debug|Win32
+ {6DB53D29-2EA9-407B-84F3-06E8031F3314}.Debug|Win32.Build.0 = Debug|Win32
+ {6DB53D29-2EA9-407B-84F3-06E8031F3314}.Release|Win32.ActiveCfg = Release|Win32
+ {6DB53D29-2EA9-407B-84F3-06E8031F3314}.Release|Win32.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/plugins/SmartAutoReplier/SAR.vcxproj b/plugins/SmartAutoReplier/SAR.vcxproj
new file mode 100644
index 0000000000..3091d45ae8
--- /dev/null
+++ b/plugins/SmartAutoReplier/SAR.vcxproj
@@ -0,0 +1,189 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Template|Win32">
+ <Configuration>Template</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>{C71749EF-EBA8-4317-9F9E-327E1A7366EC}</ProjectGuid>
+ <Keyword>Win32Proj</Keyword>
+ <ProjectName>SAR</ProjectName>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <CharacterSet>MultiByte</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfAtl>Static</UseOfAtl>
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup>
+ <_ProjectFileVersion>10.0.40219.1</_ProjectFileVersion>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Debug\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Release\</IntDir>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
+ <CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Template|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
+ <CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Template|Win32'" />
+ <CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Template|Win32'" />
+ <IncludePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\lualib;..\wtl\Include;$(IncludePath)</IncludePath>
+ <IncludePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\wtl\Include;$(IncludePath)</IncludePath>
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>C:\Users\vshcherbyna\Downloads\aur\wtl\Include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;SAR_EXPORTS;UNICODE;_UNICODE</PreprocessorDefinitions>
+ <MinimalRebuild>true</MinimalRebuild>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeader>Use</PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <AdditionalDependencies>D:\Projects\smart-auto-replier\sar\Debug\lualib.lib;shell32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>C:\Program Files (x86)\Miranda IM\Plugins\Sar.dll</OutputFile>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(OutDir)SAR.pdb</ProgramDatabaseFile>
+ <SubSystem>Windows</SubSystem>
+ <BaseAddress>0x40000000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(OutDir)SAR.lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ <ModuleDefinitionFile>sar.def</ModuleDefinitionFile>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <Optimization>MinSpace</Optimization>
+ <EnableFiberSafeOptimizations>true</EnableFiberSafeOptimizations>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;SAR_EXPORTS;UNICODE;_UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <PrecompiledHeader>Use</PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ </ClCompile>
+ <Link>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Windows</SubSystem>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <BaseAddress>0x40000000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(OutDir)SAR.lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ <AdditionalDependencies>D:\Projects\smart-auto-replier\sar\Release\lualib.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <ModuleDefinitionFile>sar.def</ModuleDefinitionFile>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Template|Win32'">
+ <Link>
+ <ModuleDefinitionFile>sar.def</ModuleDefinitionFile>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="ActionsHandler.cpp" />
+ <ClCompile Include="LuaBridge.cpp" />
+ <ClCompile Include="LuaScript.cpp" />
+ <ClCompile Include="SAR.cpp" />
+ <ClCompile Include="comfunc.cpp" />
+ <ClCompile Include="Crc32Static.cpp" />
+ <ClCompile Include="CrushLog.cpp" />
+ <ClCompile Include="MessagesHandler.cpp" />
+ <ClCompile Include="ModeMessHandler.cpp" />
+ <ClCompile Include="RulesStorage.cpp" />
+ <ClCompile Include="SarLuaScript.cpp" />
+ <ClCompile Include="ScriptsReader.cpp" />
+ <ClCompile Include="SettingsHandler.cpp" />
+ <ClCompile Include="stdafx.cpp">
+ <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
+ <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
+ </ClCompile>
+ <ClCompile Include="Gui\AddRuleDlg.cpp" />
+ <ClCompile Include="Gui\EditReplyDlg.cpp" />
+ <ClCompile Include="Gui\OptionsDlg.cpp" />
+ <ClCompile Include="Gui\SelectUserDlg.cpp" />
+ <ClCompile Include="Gui\SettingsDlgHolder.cpp" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="ActionsHandler.h" />
+ <ClInclude Include="AggressiveOptimize.h" />
+ <ClInclude Include="comfunc.h" />
+ <ClInclude Include="comlogging.h" />
+ <ClInclude Include="Crc32Static.h" />
+ <ClInclude Include="CrushLog.h" />
+ <ClInclude Include="LuaBridge.h" />
+ <ClInclude Include="luainc.h" />
+ <ClInclude Include="LuaScript.h" />
+ <ClInclude Include="MessagesHandler.h" />
+ <ClInclude Include="ModeMessHandler.h" />
+ <ClInclude Include="resource.h" />
+ <ClInclude Include="RuleItem.h" />
+ <ClInclude Include="RulesStorage.h" />
+ <ClInclude Include="SarLuaScript.h" />
+ <ClInclude Include="ScriptsReader.h" />
+ <ClInclude Include="SettingsHandler.h" />
+ <ClInclude Include="stdafx.h" />
+ <ClInclude Include="Gui\AddRuleDlg.h" />
+ <ClInclude Include="Gui\EditReplyDlg.h" />
+ <ClInclude Include="Gui\OptionsDlg.h" />
+ <ClInclude Include="Gui\SelectUserDlg.h" />
+ <ClInclude Include="Gui\SettingsDlgHolder.h" />
+ <ClInclude Include="Interfaces\ISettings.h" />
+ <ClInclude Include="Interfaces\ISingletone.h" />
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="SAR.rc" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="sar.def" />
+ <None Include="sar.ico" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+ <ProjectExtensions>
+ <VisualStudio>
+ <UserProperties RESOURCE_FILE="SAR.rc" />
+ </VisualStudio>
+ </ProjectExtensions>
+</Project> \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/SAR.vcxproj.filters b/plugins/SmartAutoReplier/SAR.vcxproj.filters
new file mode 100644
index 0000000000..8c8e9d59f4
--- /dev/null
+++ b/plugins/SmartAutoReplier/SAR.vcxproj.filters
@@ -0,0 +1,77 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup>
+ <ClCompile Include="ActionsHandler.cpp" />
+ <ClCompile Include="SAR.cpp" />
+ <ClCompile Include="comfunc.cpp" />
+ <ClCompile Include="Crc32Static.cpp" />
+ <ClCompile Include="CrushLog.cpp" />
+ <ClCompile Include="MessagesHandler.cpp" />
+ <ClCompile Include="ModeMessHandler.cpp" />
+ <ClCompile Include="RulesStorage.cpp" />
+ <ClCompile Include="ScriptsReader.cpp" />
+ <ClCompile Include="SettingsHandler.cpp" />
+ <ClCompile Include="stdafx.cpp" />
+ <ClCompile Include="Gui\AddRuleDlg.cpp" />
+ <ClCompile Include="Gui\EditReplyDlg.cpp" />
+ <ClCompile Include="Gui\OptionsDlg.cpp" />
+ <ClCompile Include="Gui\SelectUserDlg.cpp" />
+ <ClCompile Include="Gui\SettingsDlgHolder.cpp" />
+ <ClCompile Include="LuaBridge.cpp">
+ <Filter>Lua</Filter>
+ </ClCompile>
+ <ClCompile Include="LuaScript.cpp">
+ <Filter>Lua</Filter>
+ </ClCompile>
+ <ClCompile Include="SarLuaScript.cpp">
+ <Filter>Lua</Filter>
+ </ClCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="ActionsHandler.h" />
+ <ClInclude Include="AggressiveOptimize.h" />
+ <ClInclude Include="comfunc.h" />
+ <ClInclude Include="comlogging.h" />
+ <ClInclude Include="Crc32Static.h" />
+ <ClInclude Include="CrushLog.h" />
+ <ClInclude Include="MessagesHandler.h" />
+ <ClInclude Include="ModeMessHandler.h" />
+ <ClInclude Include="resource.h" />
+ <ClInclude Include="RuleItem.h" />
+ <ClInclude Include="RulesStorage.h" />
+ <ClInclude Include="ScriptsReader.h" />
+ <ClInclude Include="SettingsHandler.h" />
+ <ClInclude Include="stdafx.h" />
+ <ClInclude Include="Gui\AddRuleDlg.h" />
+ <ClInclude Include="Gui\EditReplyDlg.h" />
+ <ClInclude Include="Gui\OptionsDlg.h" />
+ <ClInclude Include="Gui\SelectUserDlg.h" />
+ <ClInclude Include="Gui\SettingsDlgHolder.h" />
+ <ClInclude Include="Interfaces\ISettings.h" />
+ <ClInclude Include="Interfaces\ISingletone.h" />
+ <ClInclude Include="LuaBridge.h">
+ <Filter>Lua</Filter>
+ </ClInclude>
+ <ClInclude Include="luainc.h">
+ <Filter>Lua</Filter>
+ </ClInclude>
+ <ClInclude Include="LuaScript.h">
+ <Filter>Lua</Filter>
+ </ClInclude>
+ <ClInclude Include="SarLuaScript.h">
+ <Filter>Lua</Filter>
+ </ClInclude>
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="SAR.rc" />
+ </ItemGroup>
+ <ItemGroup>
+ <Filter Include="Lua">
+ <UniqueIdentifier>{f3d54a11-21ba-4f12-b8c0-8576228a1625}</UniqueIdentifier>
+ </Filter>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="sar.ico" />
+ <None Include="sar.def" />
+ </ItemGroup>
+</Project> \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/SarLuaScript.cpp b/plugins/SmartAutoReplier/SarLuaScript.cpp
new file mode 100644
index 0000000000..d83f82c51d
--- /dev/null
+++ b/plugins/SmartAutoReplier/SarLuaScript.cpp
@@ -0,0 +1,358 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This code is inspired by article of RichardS at http://www.codeproject.com/Articles/11508/Integrating-Lua-into-C
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "SarLuaScript.h"
+
+#include "../miranda32/m_protomod.h"
+#include "../miranda32/m_protosvc.h"
+
+extern INT g_nCurrentMode;
+extern CMessagesHandler *g_pMessHandler;
+
+wchar_t* Utf8toUtf16(CHAR * szStrIn, UINT & nSize);
+char* Utf16toUtf8(LPCWSTR lpwszStrIn, UINT & nSize);
+
+CSarLuaScript::CSarLuaScript(CLuaBridge & luaBridge) : CLuaScript(luaBridge)
+{
+ m_nFuncBaseIndex = RegisterFunction("SendMessage");
+
+ RegisterFunction("GetMyStatus");
+ RegisterFunction("SetMyStatus");
+ RegisterFunction("Wait");
+ RegisterFunction("FindUser");
+ RegisterFunction("SetVariable");
+ RegisterFunction("GetVariable");
+}
+
+CSarLuaScript::~CSarLuaScript(void)
+{
+}
+
+int CSarLuaScript::ScriptCalling(CLuaBridge & luaBridge, int nFncNumber)
+{
+ switch (nFncNumber - m_nFuncBaseIndex)
+ {
+ case 0:
+ return SendMessage(luaBridge);
+
+ case 1:
+ return GetMyStatus(luaBridge);
+
+ case 2:
+ return SetMyStatus(luaBridge);
+
+ case 3:
+ return Wait(luaBridge);
+
+ case 4:
+ return FindUser(luaBridge);
+
+ case 5:
+ return SetVariable(luaBridge);
+
+ case 6:
+ return GetVariable(luaBridge);
+ }
+
+ return FALSE;
+}
+
+int CSarLuaScript::SendMessage(CLuaBridge & luaBridge)
+{
+ lua_State *pFunctionContext = (lua_State*)luaBridge;
+
+ UINT nMessageLen = lua_strlen(pFunctionContext, -1);
+ const char * szMessage = lua_tostring(pFunctionContext, -1);
+ int hUserToken = (int)lua_tonumber(pFunctionContext, -2);
+
+ if (szMessage == NULL)
+ {
+ return FALSE;
+ }
+
+ int nRetVal = 0;
+
+#ifdef _UNICODE
+ /*/// as I am in unicode, I have to convert all strings from utf8 to utf16 :)
+ wchar_t * szwMessage = Utf8toUtf16((char*)szMessage, nMessageLen);*/
+
+ nRetVal = CallContactService((HANDLE)hUserToken, PSS_MESSAGE, PREF_UTF, reinterpret_cast<LPARAM>(szMessage));
+
+ /*free(szwMessage);*/
+#else
+ nRetVal = CallContactService((HANDLE)hUserToken, PSS_MESSAGE, 0, reinterpret_cast<LPARAM>(szMessage));
+#endif
+
+ return FALSE;
+}
+
+int CSarLuaScript::GetMyStatus(CLuaBridge & luaBridge)
+{
+ lua_State *pFunctionContext = (lua_State*)luaBridge;
+ int nStatusMode = CallService(MS_CLIST_GETSTATUSMODE, (WPARAM)0, (LPARAM)0);
+
+ nStatusMode = g_nCurrentMode;
+
+ switch (nStatusMode)
+ {
+ case ID_STATUS_ONLINE:
+ AddParam("Online");
+ break;
+
+ case ID_STATUS_OFFLINE:
+ AddParam("Offline");
+ break;
+
+ case ID_STATUS_AWAY:
+ AddParam("Away");
+ break;
+
+ case ID_STATUS_DND:
+ AddParam("DND");
+ break;
+
+ case ID_STATUS_NA:
+ AddParam("NA");
+ break;
+
+ case ID_STATUS_OCCUPIED:
+ AddParam("Occupied");
+ break;
+
+ case ID_STATUS_FREECHAT:
+ AddParam("FreeChat");
+ break;
+
+ case ID_STATUS_INVISIBLE:
+ AddParam("Invisible");
+ break;
+
+ case ID_STATUS_ONTHEPHONE:
+ AddParam("OnThePhone");
+ break;
+
+ case ID_STATUS_OUTTOLUNCH:
+ AddParam("OutToLunch");
+ break;
+
+ default:
+ AddParam("Unknown");
+ break;
+ }
+
+ return TRUE;
+}
+
+int CSarLuaScript::SetMyStatus(CLuaBridge & luaBridge)
+{
+ int nNewStatus = 0;
+ lua_State *pFunctionContext = (lua_State*)luaBridge;
+
+ const char * szStatus = lua_tostring(pFunctionContext, -1);
+
+ if (szStatus == NULL)
+ {
+ return FALSE;
+ }
+
+ if (strcmp(szStatus, "Online") == 0)
+ {
+ nNewStatus = ID_STATUS_ONLINE;
+ }
+ else if (strcmp(szStatus, "Offline") == 0)
+ {
+ nNewStatus = ID_STATUS_OFFLINE;
+ }
+ else if (strcmp(szStatus, "Away") == 0)
+ {
+ nNewStatus = ID_STATUS_AWAY;
+ }
+ else if (strcmp(szStatus, "DND") == 0)
+ {
+ nNewStatus = ID_STATUS_DND;
+ }
+ else if (strcmp(szStatus, "NA") == 0)
+ {
+ nNewStatus = ID_STATUS_NA;
+ }
+ else if (strcmp(szStatus, "Occupied") == 0)
+ {
+ nNewStatus = ID_STATUS_OCCUPIED;
+ }
+ else if (strcmp(szStatus, "FreeChat") == 0)
+ {
+ nNewStatus = ID_STATUS_FREECHAT;
+ }
+ else if (strcmp(szStatus, "Invisible") == 0)
+ {
+ nNewStatus = ID_STATUS_INVISIBLE;
+ }
+ else if (strcmp(szStatus, "OnThePhone") == 0)
+ {
+ nNewStatus = ID_STATUS_ONTHEPHONE;
+ }
+ else if (strcmp(szStatus, "OutToLunch") == 0)
+ {
+ nNewStatus = ID_STATUS_OUTTOLUNCH;
+ }
+
+ CallService(MS_CLIST_SETSTATUSMODE, (WPARAM)nNewStatus, (LPARAM)0);
+
+ return FALSE;
+}
+
+typedef map<wstring, wstring> MapOfStrings;
+
+MapOfStrings g_MapOfVariables;
+
+int CSarLuaScript::SetVariable(CLuaBridge & luaBridge)
+{
+ lua_State *pFunctionContext = (lua_State*)luaBridge;
+
+ UINT nNameLength = lua_strlen(pFunctionContext, -2);
+ const char * szName = lua_tostring(pFunctionContext, -2);
+
+ UINT nVariableLength = lua_strlen(pFunctionContext, -1);
+ const char * szVariable = lua_tostring(pFunctionContext, -1);
+
+ if (szName == NULL || szVariable == NULL)
+ {
+ return FALSE;
+ }
+
+ wchar_t * szwName = Utf8toUtf16((char*)szName, nNameLength);
+ wchar_t * szwVariable = Utf8toUtf16((char*)szVariable, nVariableLength);
+
+ if (szwName && szwVariable)
+ {
+ g_MapOfVariables[szwName] = szwVariable;
+ }
+
+ if (szwName)
+ {
+ free(szwName);
+ }
+
+ if (szwVariable)
+ {
+ free(szwVariable);
+ }
+
+ return FALSE;
+}
+
+int CSarLuaScript::GetVariable(CLuaBridge & luaBridge)
+{
+ lua_State *pFunctionContext = (lua_State*)luaBridge;
+
+ UINT nNameLength = lua_strlen(pFunctionContext, -1);
+ const char * szName = lua_tostring(pFunctionContext, -1);
+
+ if (szName == NULL)
+ {
+ return FALSE;
+ }
+
+ wchar_t * szwName = Utf8toUtf16((char*)szName, nNameLength);
+
+ if (szwName)
+ {
+ MapOfStrings::iterator it = g_MapOfVariables.find(szwName);
+
+ if (it != g_MapOfVariables.end())
+ {
+ UINT nSize = 0;
+ char * szUtf = Utf16toUtf8(it->second.c_str(), nSize);
+
+ if (szUtf != NULL)
+ {
+ AddParam(szUtf);
+ free(szUtf);
+ free(szwName);
+
+ return TRUE;
+ }
+ }
+ }
+
+ if (szwName)
+ {
+ free(szwName);
+ }
+
+ return FALSE;
+}
+
+int CSarLuaScript::Wait(CLuaBridge & luaBridge)
+{
+ lua_State *pFunctionContext = (lua_State*)luaBridge;
+
+ int nSleepInterval = (int)lua_tonumber(pFunctionContext, -1);
+
+ Sleep(1000 * nSleepInterval);
+
+ return FALSE;
+}
+
+int CSarLuaScript::FindUser(CLuaBridge & luaBridge)
+{
+ lua_State *pFunctionContext = (lua_State*)luaBridge;
+
+ const CHAR * szUser = (CHAR*)lua_tostring(pFunctionContext, -2);
+ const CHAR * szProtocol = (CHAR*)lua_tostring(pFunctionContext, -1);
+
+ if (szProtocol == NULL || szUser == NULL)
+ {
+ return FALSE;
+ }
+
+ HANDLE hContact = reinterpret_cast<HANDLE>(CallService(MS_DB_CONTACT_FINDFIRST, 0, 0));
+ CHAR* szContactName = NULL;
+ CHAR* szProto = NULL;
+ DWORD wId = 0;
+
+ while (hContact != NULL)
+ {
+ szContactName = reinterpret_cast<CHAR*>(CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM)hContact, GCDNF_NOMYHANDLE));
+ szProto = (CHAR*)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)hContact, 0);
+
+ if (szProto && szContactName)
+ {
+ if ( (strcmp(szUser, szContactName)) == 0 && (strcmp(szProto, szProtocol) == 0))
+ {
+ AddParam((int)hContact);
+ return TRUE;
+ }
+ }
+
+ hContact = reinterpret_cast<HANDLE> (CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM) hContact, 0));
+ }
+
+ return FALSE;
+}
+
+void CSarLuaScript::HandleReturns(CLuaBridge & luaBridge, const char *szFunc)
+{
+
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/SarLuaScript.h b/plugins/SmartAutoReplier/SarLuaScript.h
new file mode 100644
index 0000000000..26b9ba1a61
--- /dev/null
+++ b/plugins/SmartAutoReplier/SarLuaScript.h
@@ -0,0 +1,57 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This code is inspired by article of RichardS at http://www.codeproject.com/Articles/11508/Integrating-Lua-into-C
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "LuaBridge.h"
+#include "LuaScript.h"
+
+#include <map>
+#include <string>
+
+using namespace std;
+
+class CSarLuaScript : public CLuaScript
+{
+public:
+ CSarLuaScript(CLuaBridge & luaBridge);
+ ~CSarLuaScript(void);
+
+private:
+ int SendMessage(CLuaBridge & luaBridge);
+ int GetMyStatus(CLuaBridge & luaBridge);
+ int SetMyStatus(CLuaBridge & luaBridge);
+ int Wait(CLuaBridge & luaBridge);
+ int FindUser(CLuaBridge & luaBridge);
+ int SetVariable(CLuaBridge & luaBridge);
+ int GetVariable(CLuaBridge & luaBridge);
+
+protected:
+ int ScriptCalling(CLuaBridge & luaBridge, int nFncNumber);
+
+ void HandleReturns(CLuaBridge & luaBridge, const char *szFunc);
+
+protected:
+ int m_nFuncBaseIndex;
+};
+
diff --git a/plugins/SmartAutoReplier/ScriptsReader.cpp b/plugins/SmartAutoReplier/ScriptsReader.cpp
new file mode 100644
index 0000000000..4bd45d22e6
--- /dev/null
+++ b/plugins/SmartAutoReplier/ScriptsReader.cpp
@@ -0,0 +1,175 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "scriptsreader.h"
+#include "messageshandler.h"
+#include "modemesshandler.h"
+
+extern INT g_nCurrentMode;
+extern CMessagesHandler * g_pMessHandler;
+
+/// ctor
+CScriptsReader::CScriptsReader(void)
+{
+}
+
+/// dtor
+CScriptsReader::~CScriptsReader(void)
+{
+}
+
+/// dtor
+void CScriptsReader::InternalInit(void)
+{
+}
+
+ACTIONS CScriptsReader::ParceString(LPTSTR & strMessage)
+{
+ ACTIONS act;
+ return act;
+}
+
+bool CScriptsReader::Replace(LPSTR & lpString, LPSTR strReplWhat, LPSTR & strReplWith)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ if (strcmp(lpString, strReplWhat) == 0)
+ {
+ strcpy(lpString, strReplWith);
+ return true;
+ }
+ char * ptr = strstr(lpString, strReplWhat);
+ if (ptr)
+ {
+ int nPos = static_cast<int>(ptr - lpString + 1);
+ if (!nPos)
+ return false;
+ char *szPrev = new char[nPos];
+
+ if (!szPrev)
+ return false;
+ strncpy(szPrev, lpString, nPos - 1);
+ int nPos2 = static_cast<int>(nPos + strlen(strReplWhat));
+ int nLength = static_cast<int>(strlen(lpString));
+ int nSize2 = nLength - nPos2 + 1;
+ if (nSize2 == 0)
+ nSize2++;
+ char *szPost = new char[nSize2];
+ if (!szPost)
+ {
+ delete szPrev;
+ return false;
+ }
+ ptr += strlen(strReplWhat);
+ if (nPos == 1)
+ {
+ ptr++;
+ }
+ strncpy(szPost, ptr, nSize2);
+ strcpy(lpString, szPrev);
+ strcat(lpString, strReplWith);
+ if (nPos == 1)
+ strcat(lpString, " ");
+ strcat(lpString, szPost);
+ delete szPrev;
+ delete szPost;
+
+ return Replace(lpString, strReplWhat, strReplWith);
+ }
+ else
+ return false;
+END_PROTECT_AND_LOG_CODE
+ return false;
+}
+
+/// returnes message that is replied to contact.
+/// the core of a plugin ;) (a joke..)
+bool CScriptsReader::GetReturnMessage(LPTSTR lpContactName, LPTSTR & lpMsg, LPTSTR & lpIncomingMsg)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ DWORD dwSizeOfMess = SETTINGS_MESSAGE_MAXVALENGTH + SETTINGS_HEADER_MAXVALENGTH;
+ dwSizeOfMess += _tcslen(lpIncomingMsg);
+ LPTSTR szOwnNick = g_pMessHandler->GetContactName(NULL);
+ if (szOwnNick)
+ dwSizeOfMess += _tcslen(szOwnNick);
+
+ bool bspecific = (lpMsg != NULL);
+ dwSizeOfMess = dwSizeOfMess * 3; /// Any replacing can cause increasing size of data
+ LPTSTR lpPrev = NULL;
+ if (bspecific)
+ {
+ dwSizeOfMess += _tcslen(lpMsg);
+ lpPrev = lpMsg;
+ }
+
+ lpMsg = new TCHAR[dwSizeOfMess];
+
+ memset(lpMsg, 0, dwSizeOfMess * sizeof(TCHAR));
+
+ COMMON_RULE_ITEM & commRule = g_pMessHandler->getSettings().getStorage().getCommonRule();
+
+ if (!bspecific)
+ {
+ _tcscpy(lpMsg, commRule.Message);
+ }
+ else
+ {
+ _tcscpy(lpMsg, lpPrev);
+ VirtualFree (lpPrev, NULL, MEM_RELEASE);
+ }
+
+ /*TCHAR strDate[0x100] = {0};
+ SYSTEMTIME t = {0};
+ GetLocalTime(&t);
+ sprintf(strDate, "[%d-%d-%d %d-%d-%d]", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond);
+ LPSTR lp = strDate;
+ if (!bspecific)
+ {
+ _tcscat(lpMsg, "\r\n");
+ _tcscat(lpMsg, commRule.Message);
+ }
+
+ Replace(lpMsg, SETTINGS_SCRIPT_CURRDATA, lp);
+ Replace(lpMsg, SETTINGS_SCRIPT_USERNAME, lpContactName);
+ Replace(lpMsg, SETTINGS_SCRIPT_OWNNICKNAME, szOwnNick);
+
+ LPTSTR lptMMess = CModeMessHandler::GetModeMessage(g_nCurrentMode);
+
+ if (lptMMess)
+ {
+ Replace(lpMsg, SETTINGS_SCRIPT_MODEMESSAGE, lptMMess);
+ /// seems like i should free this ptr
+ /// but when this is done heap is corrupted
+ /// so better we have a leak of small amount
+ /// of memory then corrupted heap. (imho).Sad
+ /// free (lptMMess);
+ }
+
+ Replace(lpMsg, SETTINGS_SCRIPT_INCOMMINGMESSAGE, lpIncomingMsg);*/
+
+ if (lpMsg)
+ return true;
+ else
+ return false;
+
+END_PROTECT_AND_LOG_CODE
+ return false;
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/ScriptsReader.h b/plugins/SmartAutoReplier/ScriptsReader.h
new file mode 100644
index 0000000000..c2b89c3d0f
--- /dev/null
+++ b/plugins/SmartAutoReplier/ScriptsReader.h
@@ -0,0 +1,57 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include <list>
+
+/// class that converts all scripts
+/// into an actions or raw text
+
+/// replacing commands
+#define SETTINGS_SCRIPT_USERNAME "%username%"
+#define SETTINGS_SCRIPT_CURRDATA "%currdate%"
+#define SETTINGS_SCRIPT_MODEMESSAGE "%modemessage%"
+#define SETTINGS_SCRIPT_INCOMMINGMESSAGE "%incomingmessage%"
+#define SETTINGS_SCRIPT_OWNNICKNAME "%ownnickname%"
+
+/// actios commands
+
+typedef struct _ACTION
+{
+ LPTSTR ActionCode;
+}ACTION, *PACTION;
+
+typedef std::list<ACTION> ACTIONS;
+
+class CScriptsReader
+{
+public:
+ CScriptsReader(void);
+ ~CScriptsReader(void);
+public:
+ ACTIONS ParceString(LPTSTR & strMessage);
+ bool GetReturnMessage(LPTSTR lpContactName, LPTSTR & lpMsg, LPTSTR & lpIncomingMsg);
+ static bool Replace(LPSTR & lpString, LPSTR strReplWhat, LPSTR & strReplWith);
+private:
+ void InternalInit(void);
+private:
+}; \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/SettingsHandler.cpp b/plugins/SmartAutoReplier/SettingsHandler.cpp
new file mode 100644
index 0000000000..c95ea0c539
--- /dev/null
+++ b/plugins/SmartAutoReplier/SettingsHandler.cpp
@@ -0,0 +1,204 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "settingshandler.h"
+#include "modemesshandler.h"
+
+/// we need hinst
+extern HINSTANCE hInst;
+extern CCrushLog CRUSHLOGOBJ;
+extern INT g_nCurrentMode;
+
+/// ctor
+CSettingsHandler::CSettingsHandler(void) : m_bResettings(false),
+m_replSize(sizeof(REPLYER_SETTINGS))
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ MakeFullPath(m_szSettFileName, sizeof(m_szSettFileName), SETTINGS_DB);
+ m_rulesStorage.Init();
+END_PROTECT_AND_LOG_CODE
+}
+
+/// d'ctor
+CSettingsHandler::~CSettingsHandler(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ DeInit();
+ m_rulesStorage.Flush();
+END_PROTECT_AND_LOG_CODE
+}
+
+/// changing settings...
+void CSettingsHandler::setSettings(REPLYER_SETTINGS & settings, COMMON_RULE_ITEM * pcommrule)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ m_Settings = settings;
+#ifdef _DEBUG
+ bool bflushed =
+#endif
+ Serialize(&m_Settings, m_replSize);
+ if (pcommrule)
+ {
+ m_rulesStorage.setCommonRule(*pcommrule);
+ DWORD dw = NULL;
+ m_rulesStorage.Serialize(NULL, dw);
+ }
+END_PROTECT_AND_LOG_CODE
+}
+
+bool CSettingsHandler::Serialize(ISettingsStream *pSettings, DWORD & ObjectSize)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ bool bRetVal = false;
+ HANDLE hFile = CreateFile (m_szSettFileName, GENERIC_WRITE,
+ FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
+ FILE_ATTRIBUTE_NORMAL, NULL);
+ if (hFile == NULL || hFile == INVALID_HANDLE_VALUE)
+ return bRetVal; ///
+ else
+ { /// check ptr for null
+ bool bValid = (pSettings != NULL);
+ if (bValid) /// for readibility..
+ bValid = (IsBadReadPtr(pSettings, sizeof(pSettings)) == TRUE ? false : true);
+
+ DWORD dwWritten = NULL;
+ bRetVal = (WriteFile (hFile, (bValid ? pSettings : &m_Settings), sizeof(REPLYER_SETTINGS), &dwWritten, NULL) == TRUE ? true : false);
+ CloseHandle (hFile);
+ return bRetVal;
+ }
+END_PROTECT_AND_LOG_CODE
+ return false;
+}
+
+bool CSettingsHandler::Deserialize(DWORD & ObjectSize)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ bool bRetVal = false;
+ HANDLE hFile = CreateFile (m_szSettFileName, GENERIC_READ,
+ FILE_SHARE_READ, NULL, OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL, NULL);
+ if (hFile == NULL || hFile == INVALID_HANDLE_VALUE)
+ return bRetVal; ///
+ else
+ {
+ DWORD dwSizeHigh = 0;
+ DWORD dwSize = GetFileSize(hFile, &dwSizeHigh);
+
+ if (dwSize != ObjectSize)
+ {
+ bool bDel = NotifyAboutWrongSettings(m_szSettFileName);
+ if (bDel)
+ {
+ CloseHandle (hFile);
+ DeleteFile (m_szSettFileName);
+ m_bResettings = true;
+ Init();
+ m_bResettings = false;
+ return true;
+ }
+ }
+ DWORD dwReaded = NULL;
+ bRetVal = (ReadFile (hFile, &m_Settings, ObjectSize, &dwReaded, NULL) == TRUE ? true : false);
+ CloseHandle (hFile);
+
+ return bRetVal;
+ }
+END_PROTECT_AND_LOG_CODE
+ return false;
+}
+
+void CSettingsHandler::Init(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+
+ if (!PathFileExists(m_szSettFileName))
+ { /// create file with def settings...
+ /// create def. configuration and store it to file...
+ m_Settings.bDisableWhenModeIsSet = SETTINGS_DEF_COMMON_EN_DISONMODEON;
+ m_Settings.ModeDisValue = SETTINGS_DEF_COMMON_EN_ONMODEDISVAL;
+ m_Settings.bShowAURDlgWhenModeChanges = false;
+ m_Settings.bEnableWhenModeIsSet = SETTINGS_DEF_COMMON_EN_ONMODEON;
+ m_Settings.ModeValue = SETTINGS_DEF_COMMON_EN_ONMODEONVAL;
+
+ m_Settings.bDisableWhenMirandaIsOn = SETTINGS_DEF_COMMON_DWMION;
+ m_Settings.ReplayDelay = SETTINGS_DEF_COMMON_VALREPDELAY;
+ m_Settings.bEnabled = true;
+ m_Settings.bFirstRun = !m_bResettings;
+ m_Settings.bSaveToHistory = false;
+
+ Serialize(&m_Settings, m_replSize);
+
+ if (m_Settings.bFirstRun)
+ { /// show only once to user readme file...
+ m_Settings.bFirstRun = false;
+ TCHAR * szreadme = NULL;
+ szreadme = new TCHAR[MAX_PATH + 1];
+ if (szreadme)
+ {
+ //MakeFullPath(szreadme, MAX_PATH, READMEFILE);
+ ::ShellExecute(NULL, TEXT("open"), TEXT("http://www.shcherbyna.com/?page_id=1747"), NULL, NULL, SW_SHOW);
+ //::ShellExecute(NULL, "open", TEXT("http://shcherbyna.com/forum/viewforum.php?f=8"), NULL, NULL, SW_SHOW);
+
+ delete szreadme;
+ }
+ }
+ }
+ else
+ {
+ Deserialize(m_replSize);
+ }
+END_PROTECT_AND_LOG_CODE
+}
+
+void CSettingsHandler::DeInit(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ Serialize(&m_Settings, m_replSize);
+END_PROTECT_AND_LOG_CODE
+}
+
+CScriptsReader & CSettingsHandler::getScriptsReader(void)
+{
+ return m_scriptsReader;
+}
+
+REPLYER_SETTINGS & CSettingsHandler::getSettings(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return m_Settings;
+END_PROTECT_AND_LOG_CODE
+}
+
+DWORD CSettingsHandler::AddReplyAction(RULE_ITEM item, bool & bExists)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return m_rulesStorage.AddRuleItem(item, bExists);
+END_PROTECT_AND_LOG_CODE
+ return 0;
+}
+
+CRulesStorage & CSettingsHandler::getStorage(void)
+{
+BEGIN_PROTECT_AND_LOG_CODE
+ return m_rulesStorage;
+END_PROTECT_AND_LOG_CODE
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/SettingsHandler.h b/plugins/SmartAutoReplier/SettingsHandler.h
new file mode 100644
index 0000000000..9e0a859796
--- /dev/null
+++ b/plugins/SmartAutoReplier/SettingsHandler.h
@@ -0,0 +1,96 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "RuleItem.h"
+#include "RulesStorage.h"
+#include "interfaces\ISettings.h"
+#include "comfunc.h"
+#include "scriptsreader.h"
+
+/// settings defs...
+#define SETTINGS_DB TEXT("sar.csu")
+#define READMEFILE TEXT("sar.html")
+
+#define SETTINGS_HEADER_MAXVALENGTH 1024 * 1 /// 1 kb by def
+#define SETTINGS_MESSAGE_MAXVALENGTH 1024 * 3 /// 3 kb by def
+
+#define SETTINGS_DEF_COMMON_DWMION 1
+#define SETTINGS_DEF_COMMVALUE 0
+
+#define SETTINGS_DEF_MESSAGE TEXT("function this.SAR(this, hUser, szMessage, szUser, szProtocol)\r\n this:SendMessage(hUser, \"Here is my autoreply!\")\r\nend")
+#define SETTINGS_DEF_MESSAGE_RULE TEXT("-- Main handler function written in Lua:\r\n\r\nfunction this.SAR(this, hUser, szMessage, szUser, szProtocol)\r\n this:SendMessage(hUser, \"Here is my specific to user autoreply!\")\r\nend")
+#define SETTINGS_DEF_RULE_NAME TEXT("Some generic rule name")
+
+#define SETTINGS_DEF_COMMON_VALREPDELAY 2
+#define SETTINGS_DEF_COMMON_EN_ONMODEON 0
+#define SETTINGS_DEF_COMMON_EN_DISONMODEON 0
+
+#define SETTINGS_DEF_COMMON_EN_ONMODEDISVAL 0
+#define SETTINGS_DEF_COMMON_EN_ONMODEONVAL 0
+#define SETTINGS_DEF_COMMON_SHOWAURDLGWMC 0
+
+/// settings that are stored in file...
+/// serialized
+typedef struct _REPLYER_SETTINGS : ISettingsStream
+{
+ bool bEnabled;
+ bool bDisableWhenMirandaIsOn;
+ int ReplayDelay;
+ bool bEnableWhenModeIsSet;
+ bool bDisableWhenModeIsSet;
+ int ModeValue;
+ int ModeDisValue;
+ bool bShowAURDlgWhenModeChanges;
+ bool bFirstRun;
+ bool bSaveToHistory;
+}REPLYER_SETTINGS, *PREPLYER_SETTINGS;
+
+#ifndef MAX_PATH
+ #define MAX_PATH 260
+#endif
+
+/// manager that handles settings of a plugin...
+class CSettingsHandler : ISettings
+{
+public:
+ CSettingsHandler(void);
+ ~CSettingsHandler(void);
+public: /// ISettings interface...
+ bool Serialize(ISettingsStream *pSettings, DWORD & ObjectSize);
+ bool Deserialize(DWORD & ObjectSize);
+public:
+ void Init(void); /// deserialize...
+ void DeInit(void); /// serialize...
+ REPLYER_SETTINGS & getSettings(void);
+ CScriptsReader & getScriptsReader(void);
+ CRulesStorage & getStorage(void);
+ void setSettings(REPLYER_SETTINGS & settings, COMMON_RULE_ITEM * pcommrule = NULL);
+ DWORD AddReplyAction(RULE_ITEM item, bool & bExists);
+private:
+ REPLYER_SETTINGS m_Settings;
+ TCHAR m_szSettFileName[MAX_PATH];
+ bool m_bResettings;
+ CRulesStorage m_rulesStorage;
+ CScriptsReader m_scriptsReader;
+ DWORD m_replSize;
+}; \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/comfunc.cpp b/plugins/SmartAutoReplier/comfunc.cpp
new file mode 100644
index 0000000000..0f79871fbb
--- /dev/null
+++ b/plugins/SmartAutoReplier/comfunc.cpp
@@ -0,0 +1,74 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+#include "comfunc.h"
+#include "shlobj.h"
+
+extern LPTSTR g_strPluginName;
+extern HINSTANCE hInst;
+
+/// show to user msgbox that settings
+/// file is corrupted...
+bool NotifyAboutWrongSettings(LPTSTR szFile)
+{
+ TCHAR szTxt[MAX_PATH * 2] = {0};
+ _tcscpy(szTxt, TEXT("Settings file: "));
+ _tcscat(szTxt, szFile);
+ _tcscat(szTxt, TEXT(" is corrupted !\n"));
+ _tcscat(szTxt, TEXT("As a result plugin can crush.\n"));
+ _tcscat(szTxt, TEXT("Reset settings to default ?"));
+
+ DWORD dw = MessageBox(NULL, TranslateTS(szTxt), g_strPluginName, MB_YESNO);
+ return (dw == IDYES);
+}
+
+/// forming path
+bool MakeFullPath(LPTSTR lpRetval, DWORD dwSize, LPTSTR lpFile)
+{
+ HRESULT hr = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, lpRetval);
+ size_t nLen = _tcslen(lpRetval);
+
+ if (lpRetval[nLen - 1] != TEXT('\\'))
+ {
+ _tcscat(lpRetval, TEXT("\\Sar\\"));
+ }
+ else
+ {
+ _tcscat(lpRetval, TEXT("Sar\\"));
+ }
+
+ _tcscat(lpRetval, lpFile);
+
+ /*GetModuleFileName(hInst, lpRetval, dwSize);
+ TCHAR *ptrPos = _tcsrchr(lpRetval, '\\');
+ if (ptrPos)
+ {
+ ptrPos++;
+ _tcscpy (ptrPos, lpFile);
+ }
+ else
+ {
+ _RPT0(_CRT_WARN, "MakeFullPath - unable to form path");
+ return false;
+ }*/
+ return true;
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/comfunc.h b/plugins/SmartAutoReplier/comfunc.h
new file mode 100644
index 0000000000..ab74a7e8ca
--- /dev/null
+++ b/plugins/SmartAutoReplier/comfunc.h
@@ -0,0 +1,26 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+bool NotifyAboutWrongSettings(LPTSTR szFile);
+bool MakeFullPath(LPTSTR lpRetval, DWORD dwSize, LPTSTR lpFile);
+bool CheckForHelpFile(); \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/comlogging.h b/plugins/SmartAutoReplier/comlogging.h
new file mode 100644
index 0000000000..ea8482a198
--- /dev/null
+++ b/plugins/SmartAutoReplier/comlogging.h
@@ -0,0 +1,42 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+/// define hlobal object..
+#ifndef CRUSHLOGOBJ
+ #define CRUSHLOGOBJ g_crushLog
+#endif
+
+/// this macro should be placed at the begining of any func of plugin..
+#ifndef BEGIN_PROTECT_AND_LOG_CODE
+ #define BEGIN_PROTECT_AND_LOG_CODE try { \
+ SetLastError(0);
+#endif
+
+/// this macro should be placed at the end of any func of plugin..
+#ifndef END_PROTECT_AND_LOG_CODE
+ #define END_PROTECT_AND_LOG_CODE } \
+ catch (...) \
+ { \
+ CCrushLog::InternalProtect(__FUNCTION__, __FILE__, __DATE__, __LINE__, GetLastError());\
+ }
+#endif
diff --git a/plugins/SmartAutoReplier/luainc.h b/plugins/SmartAutoReplier/luainc.h
new file mode 100644
index 0000000000..276c25bae5
--- /dev/null
+++ b/plugins/SmartAutoReplier/luainc.h
@@ -0,0 +1,31 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This code is inspired by article of RichardS at http://www.codeproject.com/Articles/11508/Integrating-Lua-into-C
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+extern "C"
+{
+ #include "../lualib/lua.h"
+ #include "../lualib/lauxlib.h"
+ #include "../lualib/lualib.h"
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/lualib/ReadMe.txt b/plugins/SmartAutoReplier/lualib/ReadMe.txt
new file mode 100644
index 0000000000..457efed27e
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ReadMe.txt
@@ -0,0 +1,37 @@
+========================================================================
+ STATIC LIBRARY : lualib Project Overview
+========================================================================
+
+AppWizard has created this lualib library project for you.
+
+This file contains a summary of what you will find in each of the files that
+make up your lualib application.
+
+
+lualib.vcxproj
+ This is the main project file for VC++ projects generated using an Application Wizard.
+ It contains information about the version of Visual C++ that generated the file, and
+ information about the platforms, configurations, and project features selected with the
+ Application Wizard.
+
+lualib.vcxproj.filters
+ This is the filters file for VC++ projects generated using an Application Wizard.
+ It contains information about the association between the files in your project
+ and the filters. This association is used in the IDE to show grouping of files with
+ similar extensions under a specific node (for e.g. ".cpp" files are associated with the
+ "Source Files" filter).
+
+
+/////////////////////////////////////////////////////////////////////////////
+
+StdAfx.h, StdAfx.cpp
+ These files are used to build a precompiled header (PCH) file
+ named lualib.pch and a precompiled types file named StdAfx.obj.
+
+/////////////////////////////////////////////////////////////////////////////
+Other notes:
+
+AppWizard uses "TODO:" comments to indicate parts of the source code you
+should add to or customize.
+
+/////////////////////////////////////////////////////////////////////////////
diff --git a/plugins/SmartAutoReplier/lualib/lapi.c b/plugins/SmartAutoReplier/lualib/lapi.c
new file mode 100644
index 0000000000..d5dd9ca465
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lapi.c
@@ -0,0 +1,922 @@
+/*
+** $Id: lapi.c,v 1.235 2003/04/07 14:36:08 roberto Exp $
+** Lua API
+** See Copyright Notice in lua.h
+*/
+
+
+#include <assert.h>
+#include <string.h>
+
+#define lapi_c
+
+#include "lua.h"
+
+#include "lapi.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+#include "lundump.h"
+#include "lvm.h"
+
+
+const char lua_ident[] =
+ "$Lua: " LUA_VERSION " " LUA_COPYRIGHT " $\n"
+ "$Authors: " LUA_AUTHORS " $\n"
+ "$URL: www.lua.org $\n";
+
+
+
+#ifndef api_check
+#define api_check(L, o) /*{ assert(o); }*/
+#endif
+
+#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base))
+
+#define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;}
+
+
+
+
+static TObject *negindex (lua_State *L, int idx) {
+ if (idx > LUA_REGISTRYINDEX) {
+ api_check(L, idx != 0 && -idx <= L->top - L->base);
+ return L->top+idx;
+ }
+ else switch (idx) { /* pseudo-indices */
+ case LUA_REGISTRYINDEX: return registry(L);
+ case LUA_GLOBALSINDEX: return gt(L);
+ default: {
+ TObject *func = (L->base - 1);
+ idx = LUA_GLOBALSINDEX - idx;
+ lua_assert(iscfunction(func));
+ return (idx <= clvalue(func)->c.nupvalues)
+ ? &clvalue(func)->c.upvalue[idx-1]
+ : NULL;
+ }
+ }
+}
+
+
+static TObject *luaA_index (lua_State *L, int idx) {
+ if (idx > 0) {
+ api_check(L, idx <= L->top - L->base);
+ return L->base + idx - 1;
+ }
+ else {
+ TObject *o = negindex(L, idx);
+ api_check(L, o != NULL);
+ return o;
+ }
+}
+
+
+static TObject *luaA_indexAcceptable (lua_State *L, int idx) {
+ if (idx > 0) {
+ TObject *o = L->base+(idx-1);
+ api_check(L, idx <= L->stack_last - L->base);
+ if (o >= L->top) return NULL;
+ else return o;
+ }
+ else
+ return negindex(L, idx);
+}
+
+
+void luaA_pushobject (lua_State *L, const TObject *o) {
+ setobj2s(L->top, o);
+ incr_top(L);
+}
+
+
+LUA_API int lua_checkstack (lua_State *L, int size) {
+ int res;
+ lua_lock(L);
+ if ((L->top - L->base + size) > LUA_MAXCSTACK)
+ res = 0; /* stack overflow */
+ else {
+ luaD_checkstack(L, size);
+ if (L->ci->top < L->top + size)
+ L->ci->top = L->top + size;
+ res = 1;
+ }
+ lua_unlock(L);
+ return res;
+}
+
+
+LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
+ int i;
+ lua_lock(to);
+ api_checknelems(from, n);
+ from->top -= n;
+ for (i = 0; i < n; i++) {
+ setobj2s(to->top, from->top + i);
+ api_incr_top(to);
+ }
+ lua_unlock(to);
+}
+
+
+LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
+ lua_CFunction old;
+ lua_lock(L);
+ old = G(L)->panic;
+ G(L)->panic = panicf;
+ lua_unlock(L);
+ return old;
+}
+
+
+LUA_API lua_State *lua_newthread (lua_State *L) {
+ lua_State *L1;
+ lua_lock(L);
+ luaC_checkGC(L);
+ L1 = luaE_newthread(L);
+ setthvalue(L->top, L1);
+ api_incr_top(L);
+ lua_unlock(L);
+ lua_userstateopen(L1);
+ return L1;
+}
+
+
+
+/*
+** basic stack manipulation
+*/
+
+
+LUA_API int lua_gettop (lua_State *L) {
+ return (L->top - L->base);
+}
+
+
+LUA_API void lua_settop (lua_State *L, int idx) {
+ lua_lock(L);
+ if (idx >= 0) {
+ api_check(L, idx <= L->stack_last - L->base);
+ while (L->top < L->base + idx)
+ setnilvalue(L->top++);
+ L->top = L->base + idx;
+ }
+ else {
+ api_check(L, -(idx+1) <= (L->top - L->base));
+ L->top += idx+1; /* `subtract' index (index is negative) */
+ }
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_remove (lua_State *L, int idx) {
+ StkId p;
+ lua_lock(L);
+ p = luaA_index(L, idx);
+ while (++p < L->top) setobjs2s(p-1, p);
+ L->top--;
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_insert (lua_State *L, int idx) {
+ StkId p;
+ StkId q;
+ lua_lock(L);
+ p = luaA_index(L, idx);
+ for (q = L->top; q>p; q--) setobjs2s(q, q-1);
+ setobjs2s(p, L->top);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_replace (lua_State *L, int idx) {
+ lua_lock(L);
+ api_checknelems(L, 1);
+ setobj(luaA_index(L, idx), L->top - 1); /* write barrier */
+ L->top--;
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushvalue (lua_State *L, int idx) {
+ lua_lock(L);
+ setobj2s(L->top, luaA_index(L, idx));
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+
+/*
+** access functions (stack -> C)
+*/
+
+
+LUA_API int lua_type (lua_State *L, int idx) {
+ StkId o = luaA_indexAcceptable(L, idx);
+ return (o == NULL) ? LUA_TNONE : ttype(o);
+}
+
+
+LUA_API const char *lua_typename (lua_State *L, int t) {
+ UNUSED(L);
+ return (t == LUA_TNONE) ? "no value" : luaT_typenames[t];
+}
+
+
+LUA_API int lua_iscfunction (lua_State *L, int idx) {
+ StkId o = luaA_indexAcceptable(L, idx);
+ return (o == NULL) ? 0 : iscfunction(o);
+}
+
+
+LUA_API int lua_isnumber (lua_State *L, int idx) {
+ TObject n;
+ const TObject *o = luaA_indexAcceptable(L, idx);
+ return (o != NULL && tonumber(o, &n));
+}
+
+
+LUA_API int lua_isstring (lua_State *L, int idx) {
+ int t = lua_type(L, idx);
+ return (t == LUA_TSTRING || t == LUA_TNUMBER);
+}
+
+
+LUA_API int lua_isuserdata (lua_State *L, int idx) {
+ const TObject *o = luaA_indexAcceptable(L, idx);
+ return (o != NULL && (ttisuserdata(o) || ttislightuserdata(o)));
+}
+
+
+LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
+ StkId o1 = luaA_indexAcceptable(L, index1);
+ StkId o2 = luaA_indexAcceptable(L, index2);
+ return (o1 == NULL || o2 == NULL) ? 0 /* index out of range */
+ : luaO_rawequalObj(o1, o2);
+}
+
+
+LUA_API int lua_equal (lua_State *L, int index1, int index2) {
+ StkId o1, o2;
+ int i;
+ lua_lock(L); /* may call tag method */
+ o1 = luaA_indexAcceptable(L, index1);
+ o2 = luaA_indexAcceptable(L, index2);
+ i = (o1 == NULL || o2 == NULL) ? 0 /* index out of range */
+ : equalobj(L, o1, o2);
+ lua_unlock(L);
+ return i;
+}
+
+
+LUA_API int lua_lessthan (lua_State *L, int index1, int index2) {
+ StkId o1, o2;
+ int i;
+ lua_lock(L); /* may call tag method */
+ o1 = luaA_indexAcceptable(L, index1);
+ o2 = luaA_indexAcceptable(L, index2);
+ i = (o1 == NULL || o2 == NULL) ? 0 /* index out-of-range */
+ : luaV_lessthan(L, o1, o2);
+ lua_unlock(L);
+ return i;
+}
+
+
+
+LUA_API lua_Number lua_tonumber (lua_State *L, int idx) {
+ TObject n;
+ const TObject *o = luaA_indexAcceptable(L, idx);
+ if (o != NULL && tonumber(o, &n))
+ return nvalue(o);
+ else
+ return 0;
+}
+
+
+LUA_API int lua_toboolean (lua_State *L, int idx) {
+ const TObject *o = luaA_indexAcceptable(L, idx);
+ return (o != NULL) && !l_isfalse(o);
+}
+
+
+LUA_API const char *lua_tostring (lua_State *L, int idx) {
+ StkId o = luaA_indexAcceptable(L, idx);
+ if (o == NULL)
+ return NULL;
+ else if (ttisstring(o))
+ return svalue(o);
+ else {
+ const char *s;
+ lua_lock(L); /* `luaV_tostring' may create a new string */
+ s = (luaV_tostring(L, o) ? svalue(o) : NULL);
+ luaC_checkGC(L);
+ lua_unlock(L);
+ return s;
+ }
+}
+
+
+LUA_API size_t lua_strlen (lua_State *L, int idx) {
+ StkId o = luaA_indexAcceptable(L, idx);
+ if (o == NULL)
+ return 0;
+ else if (ttisstring(o))
+ return tsvalue(o)->tsv.len;
+ else {
+ size_t l;
+ lua_lock(L); /* `luaV_tostring' may create a new string */
+ l = (luaV_tostring(L, o) ? tsvalue(o)->tsv.len : 0);
+ lua_unlock(L);
+ return l;
+ }
+}
+
+
+LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
+ StkId o = luaA_indexAcceptable(L, idx);
+ return (o == NULL || !iscfunction(o)) ? NULL : clvalue(o)->c.f;
+}
+
+
+LUA_API void *lua_touserdata (lua_State *L, int idx) {
+ StkId o = luaA_indexAcceptable(L, idx);
+ if (o == NULL) return NULL;
+ switch (ttype(o)) {
+ case LUA_TUSERDATA: return (uvalue(o) + 1);
+ case LUA_TLIGHTUSERDATA: return pvalue(o);
+ default: return NULL;
+ }
+}
+
+
+LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
+ StkId o = luaA_indexAcceptable(L, idx);
+ return (o == NULL || !ttisthread(o)) ? NULL : thvalue(o);
+}
+
+
+LUA_API const void *lua_topointer (lua_State *L, int idx) {
+ StkId o = luaA_indexAcceptable(L, idx);
+ if (o == NULL) return NULL;
+ else {
+ switch (ttype(o)) {
+ case LUA_TTABLE: return hvalue(o);
+ case LUA_TFUNCTION: return clvalue(o);
+ case LUA_TTHREAD: return thvalue(o);
+ case LUA_TUSERDATA:
+ case LUA_TLIGHTUSERDATA:
+ return lua_touserdata(L, idx);
+ default: return NULL;
+ }
+ }
+}
+
+
+
+/*
+** push functions (C -> stack)
+*/
+
+
+LUA_API void lua_pushnil (lua_State *L) {
+ lua_lock(L);
+ setnilvalue(L->top);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
+ lua_lock(L);
+ setnvalue(L->top, n);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) {
+ lua_lock(L);
+ luaC_checkGC(L);
+ setsvalue2s(L->top, luaS_newlstr(L, s, len));
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushstring (lua_State *L, const char *s) {
+ if (s == NULL)
+ lua_pushnil(L);
+ else
+ lua_pushlstring(L, s, strlen(s));
+}
+
+
+LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
+ va_list argp) {
+ const char *ret;
+ lua_lock(L);
+ luaC_checkGC(L);
+ ret = luaO_pushvfstring(L, fmt, argp);
+ lua_unlock(L);
+ return ret;
+}
+
+
+LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
+ const char *ret;
+ va_list argp;
+ lua_lock(L);
+ luaC_checkGC(L);
+ va_start(argp, fmt);
+ ret = luaO_pushvfstring(L, fmt, argp);
+ va_end(argp);
+ lua_unlock(L);
+ return ret;
+}
+
+
+LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
+ Closure *cl;
+ lua_lock(L);
+ luaC_checkGC(L);
+ api_checknelems(L, n);
+ cl = luaF_newCclosure(L, n);
+ cl->c.f = fn;
+ L->top -= n;
+ while (n--)
+ setobj2n(&cl->c.upvalue[n], L->top+n);
+ setclvalue(L->top, cl);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushboolean (lua_State *L, int b) {
+ lua_lock(L);
+ setbvalue(L->top, (b != 0)); /* ensure that true is 1 */
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
+ lua_lock(L);
+ setpvalue(L->top, p);
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+
+/*
+** get functions (Lua -> stack)
+*/
+
+
+LUA_API void lua_gettable (lua_State *L, int idx) {
+ StkId t;
+ lua_lock(L);
+ t = luaA_index(L, idx);
+ setobj2s(L->top - 1, luaV_gettable(L, t, L->top - 1, 0));
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_rawget (lua_State *L, int idx) {
+ StkId t;
+ lua_lock(L);
+ t = luaA_index(L, idx);
+ api_check(L, ttistable(t));
+ setobj2s(L->top - 1, luaH_get(hvalue(t), L->top - 1));
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {
+ StkId o;
+ lua_lock(L);
+ o = luaA_index(L, idx);
+ api_check(L, ttistable(o));
+ setobj2s(L->top, luaH_getnum(hvalue(o), n));
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_newtable (lua_State *L) {
+ lua_lock(L);
+ luaC_checkGC(L);
+ sethvalue(L->top, luaH_new(L, 0, 0));
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+LUA_API int lua_getmetatable (lua_State *L, int objindex) {
+ const TObject *obj;
+ Table *mt = NULL;
+ int res;
+ lua_lock(L);
+ obj = luaA_indexAcceptable(L, objindex);
+ if (obj != NULL) {
+ switch (ttype(obj)) {
+ case LUA_TTABLE:
+ mt = hvalue(obj)->metatable;
+ break;
+ case LUA_TUSERDATA:
+ mt = uvalue(obj)->uv.metatable;
+ break;
+ }
+ }
+ if (mt == NULL || mt == hvalue(defaultmeta(L)))
+ res = 0;
+ else {
+ sethvalue(L->top, mt);
+ api_incr_top(L);
+ res = 1;
+ }
+ lua_unlock(L);
+ return res;
+}
+
+
+LUA_API void lua_getfenv (lua_State *L, int idx) {
+ StkId o;
+ lua_lock(L);
+ o = luaA_index(L, idx);
+ setobj2s(L->top, isLfunction(o) ? &clvalue(o)->l.g : gt(L));
+ api_incr_top(L);
+ lua_unlock(L);
+}
+
+
+/*
+** set functions (stack -> Lua)
+*/
+
+
+LUA_API void lua_settable (lua_State *L, int idx) {
+ StkId t;
+ lua_lock(L);
+ api_checknelems(L, 2);
+ t = luaA_index(L, idx);
+ luaV_settable(L, t, L->top - 2, L->top - 1);
+ L->top -= 2; /* pop index and value */
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_rawset (lua_State *L, int idx) {
+ StkId t;
+ lua_lock(L);
+ api_checknelems(L, 2);
+ t = luaA_index(L, idx);
+ api_check(L, ttistable(t));
+ setobj2t(luaH_set(L, hvalue(t), L->top-2), L->top-1); /* write barrier */
+ L->top -= 2;
+ lua_unlock(L);
+}
+
+
+LUA_API void lua_rawseti (lua_State *L, int idx, int n) {
+ StkId o;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ o = luaA_index(L, idx);
+ api_check(L, ttistable(o));
+ setobj2t(luaH_setnum(L, hvalue(o), n), L->top-1); /* write barrier */
+ L->top--;
+ lua_unlock(L);
+}
+
+
+LUA_API int lua_setmetatable (lua_State *L, int objindex) {
+ TObject *obj, *mt;
+ int res = 1;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ obj = luaA_index(L, objindex);
+ mt = (!ttisnil(L->top - 1)) ? L->top - 1 : defaultmeta(L);
+ api_check(L, ttistable(mt));
+ switch (ttype(obj)) {
+ case LUA_TTABLE: {
+ hvalue(obj)->metatable = hvalue(mt); /* write barrier */
+ break;
+ }
+ case LUA_TUSERDATA: {
+ uvalue(obj)->uv.metatable = hvalue(mt); /* write barrier */
+ break;
+ }
+ default: {
+ res = 0; /* cannot set */
+ break;
+ }
+ }
+ L->top--;
+ lua_unlock(L);
+ return res;
+}
+
+
+LUA_API int lua_setfenv (lua_State *L, int idx) {
+ StkId o;
+ int res = 0;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ o = luaA_index(L, idx);
+ L->top--;
+ api_check(L, ttistable(L->top));
+ if (isLfunction(o)) {
+ res = 1;
+ clvalue(o)->l.g = *(L->top);
+ }
+ lua_unlock(L);
+ return res;
+}
+
+
+/*
+** `load' and `call' functions (run Lua code)
+*/
+
+LUA_API void lua_call (lua_State *L, int nargs, int nresults) {
+ StkId func;
+ lua_lock(L);
+ api_checknelems(L, nargs+1);
+ func = L->top - (nargs+1);
+ luaD_call(L, func, nresults);
+ lua_unlock(L);
+}
+
+
+
+/*
+** Execute a protected call.
+*/
+struct CallS { /* data to `f_call' */
+ StkId func;
+ int nresults;
+};
+
+
+static void f_call (lua_State *L, void *ud) {
+ struct CallS *c = cast(struct CallS *, ud);
+ luaD_call(L, c->func, c->nresults);
+}
+
+
+
+LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) {
+ struct CallS c;
+ int status;
+ ptrdiff_t func;
+ lua_lock(L);
+ func = (errfunc == 0) ? 0 : savestack(L, luaA_index(L, errfunc));
+ c.func = L->top - (nargs+1); /* function to be called */
+ c.nresults = nresults;
+ status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
+ lua_unlock(L);
+ return status;
+}
+
+
+/*
+** Execute a protected C call.
+*/
+struct CCallS { /* data to `f_Ccall' */
+ lua_CFunction func;
+ void *ud;
+};
+
+
+static void f_Ccall (lua_State *L, void *ud) {
+ struct CCallS *c = cast(struct CCallS *, ud);
+ Closure *cl;
+ cl = luaF_newCclosure(L, 0);
+ cl->c.f = c->func;
+ setclvalue(L->top, cl); /* push function */
+ incr_top(L);
+ setpvalue(L->top, c->ud); /* push only argument */
+ incr_top(L);
+ luaD_call(L, L->top - 2, 0);
+}
+
+
+LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) {
+ struct CCallS c;
+ int status;
+ lua_lock(L);
+ c.func = func;
+ c.ud = ud;
+ status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0);
+ lua_unlock(L);
+ return status;
+}
+
+
+LUA_API int lua_load (lua_State *L, lua_Chunkreader reader, void *data,
+ const char *chunkname) {
+ ZIO z;
+ int status;
+ int c;
+ lua_lock(L);
+ if (!chunkname) chunkname = "?";
+ luaZ_init(&z, reader, data, chunkname);
+ c = luaZ_lookahead(&z);
+ status = luaD_protectedparser(L, &z, (c == LUA_SIGNATURE[0]));
+ lua_unlock(L);
+ return status;
+}
+
+
+LUA_API int lua_dump (lua_State *L, lua_Chunkwriter writer, void *data) {
+ int status;
+ TObject *o;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ o = L->top - 1;
+ if (isLfunction(o) && clvalue(o)->l.nupvalues == 0) {
+ luaU_dump(L, clvalue(o)->l.p, writer, data);
+ status = 1;
+ }
+ else
+ status = 0;
+ lua_unlock(L);
+ return status;
+}
+
+
+/*
+** Garbage-collection functions
+*/
+
+/* GC values are expressed in Kbytes: #bytes/2^10 */
+#define GCscalel(x) ((x)>>10)
+#define GCscale(x) (cast(int, GCscalel(x)))
+#define GCunscale(x) (cast(lu_mem, x)<<10)
+
+LUA_API int lua_getgcthreshold (lua_State *L) {
+ int threshold;
+ lua_lock(L);
+ threshold = GCscale(G(L)->GCthreshold);
+ lua_unlock(L);
+ return threshold;
+}
+
+LUA_API int lua_getgccount (lua_State *L) {
+ int count;
+ lua_lock(L);
+ count = GCscale(G(L)->nblocks);
+ lua_unlock(L);
+ return count;
+}
+
+LUA_API void lua_setgcthreshold (lua_State *L, int newthreshold) {
+ lua_lock(L);
+ if (cast(lu_mem, newthreshold) > GCscalel(MAX_LUMEM))
+ G(L)->GCthreshold = MAX_LUMEM;
+ else
+ G(L)->GCthreshold = GCunscale(newthreshold);
+ luaC_checkGC(L);
+ lua_unlock(L);
+}
+
+
+/*
+** miscellaneous functions
+*/
+
+
+LUA_API const char *lua_version (void) {
+ return LUA_VERSION;
+}
+
+
+LUA_API int lua_error (lua_State *L) {
+ lua_lock(L);
+ api_checknelems(L, 1);
+ luaG_errormsg(L);
+ lua_unlock(L);
+ return 0; /* to avoid warnings */
+}
+
+
+LUA_API int lua_next (lua_State *L, int idx) {
+ StkId t;
+ int more;
+ lua_lock(L);
+ t = luaA_index(L, idx);
+ api_check(L, ttistable(t));
+ more = luaH_next(L, hvalue(t), L->top - 1);
+ if (more) {
+ api_incr_top(L);
+ }
+ else /* no more elements */
+ L->top -= 1; /* remove key */
+ lua_unlock(L);
+ return more;
+}
+
+
+LUA_API void lua_concat (lua_State *L, int n) {
+ lua_lock(L);
+ luaC_checkGC(L);
+ api_checknelems(L, n);
+ if (n >= 2) {
+ luaV_concat(L, n, L->top - L->base - 1);
+ L->top -= (n-1);
+ }
+ else if (n == 0) { /* push empty string */
+ setsvalue2s(L->top, luaS_newlstr(L, NULL, 0));
+ api_incr_top(L);
+ }
+ /* else n == 1; nothing to do */
+ lua_unlock(L);
+}
+
+
+LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
+ Udata *u;
+ lua_lock(L);
+ luaC_checkGC(L);
+ u = luaS_newudata(L, size);
+ setuvalue(L->top, u);
+ api_incr_top(L);
+ lua_unlock(L);
+ return u + 1;
+}
+
+
+LUA_API int lua_pushupvalues (lua_State *L) {
+ Closure *func;
+ int n, i;
+ lua_lock(L);
+ api_check(L, iscfunction(L->base - 1));
+ func = clvalue(L->base - 1);
+ n = func->c.nupvalues;
+ luaD_checkstack(L, n + LUA_MINSTACK);
+ for (i=0; i<n; i++) {
+ setobj2s(L->top, &func->c.upvalue[i]);
+ L->top++;
+ }
+ lua_unlock(L);
+ return n;
+}
+
+
+static const char *aux_upvalue (lua_State *L, int funcindex, int n,
+ TObject **val) {
+ Closure *f;
+ StkId fi = luaA_index(L, funcindex);
+ if (!ttisfunction(fi)) return NULL;
+ f = clvalue(fi);
+ if (f->c.isC) {
+ if (n > f->c.nupvalues) return NULL;
+ *val = &f->c.upvalue[n-1];
+ return "";
+ }
+ else {
+ Proto *p = f->l.p;
+ if (n > p->sizeupvalues) return NULL;
+ *val = f->l.upvals[n-1]->v;
+ return getstr(p->upvalues[n-1]);
+ }
+}
+
+
+LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
+ const char *name;
+ TObject *val;
+ lua_lock(L);
+ name = aux_upvalue(L, funcindex, n, &val);
+ if (name) {
+ setobj2s(L->top, val);
+ api_incr_top(L);
+ }
+ lua_unlock(L);
+ return name;
+}
+
+
+LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
+ const char *name;
+ TObject *val;
+ lua_lock(L);
+ api_checknelems(L, 1);
+ name = aux_upvalue(L, funcindex, n, &val);
+ if (name) {
+ L->top--;
+ setobj(val, L->top); /* write barrier */
+ }
+ lua_unlock(L);
+ return name;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lapi.h b/plugins/SmartAutoReplier/lualib/lapi.h
new file mode 100644
index 0000000000..d12612f304
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lapi.h
@@ -0,0 +1,16 @@
+/*
+** $Id: lapi.h,v 1.21 2002/03/04 21:29:41 roberto Exp $
+** Auxiliary functions from Lua API
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lapi_h
+#define lapi_h
+
+
+#include "lobject.h"
+
+
+void luaA_pushobject (lua_State *L, const TObject *o);
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lauxlib.c b/plugins/SmartAutoReplier/lualib/lauxlib.c
new file mode 100644
index 0000000000..ee2d1339b0
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lauxlib.c
@@ -0,0 +1,591 @@
+/*
+** $Id: lauxlib.c,v 1.100 2003/04/07 14:35:00 roberto Exp $
+** Auxiliary functions for building Lua libraries
+** See Copyright Notice in lua.h
+*/
+
+
+#include <ctype.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+
+
+/* This file uses only the official API of Lua.
+** Any function declared here could be written as an application function.
+*/
+
+#define lauxlib_c
+
+#include "lua.h"
+
+#include "lauxlib.h"
+
+
+/* number of prereserved references (for internal use) */
+#define RESERVED_REFS 2
+
+/* reserved references */
+#define FREELIST_REF 1 /* free list of references */
+#define ARRAYSIZE_REF 2 /* array sizes */
+
+
+/* convert a stack index to positive */
+#define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
+ lua_gettop(L) + (i) + 1)
+
+
+/*
+** {======================================================
+** Error-report functions
+** =======================================================
+*/
+
+
+LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
+ lua_Debug ar;
+ lua_getstack(L, 0, &ar);
+ lua_getinfo(L, "n", &ar);
+ if (strcmp(ar.namewhat, "method") == 0) {
+ narg--; /* do not count `self' */
+ if (narg == 0) /* error is in the self argument itself? */
+ return luaL_error(L, "calling `%s' on bad self (%s)", ar.name, extramsg);
+ }
+ if (ar.name == NULL)
+ ar.name = "?";
+ return luaL_error(L, "bad argument #%d to `%s' (%s)",
+ narg, ar.name, extramsg);
+}
+
+
+LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
+ const char *msg = lua_pushfstring(L, "%s expected, got %s",
+ tname, lua_typename(L, lua_type(L,narg)));
+ return luaL_argerror(L, narg, msg);
+}
+
+
+static void tag_error (lua_State *L, int narg, int tag) {
+ luaL_typerror(L, narg, lua_typename(L, tag));
+}
+
+
+LUALIB_API void luaL_where (lua_State *L, int level) {
+ lua_Debug ar;
+ if (lua_getstack(L, level, &ar)) { /* check function at level */
+ lua_getinfo(L, "Snl", &ar); /* get info about it */
+ if (ar.currentline > 0) { /* is there info? */
+ lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
+ return;
+ }
+ }
+ lua_pushliteral(L, ""); /* else, no information available... */
+}
+
+
+LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
+ va_list argp;
+ va_start(argp, fmt);
+ luaL_where(L, 1);
+ lua_pushvfstring(L, fmt, argp);
+ va_end(argp);
+ lua_concat(L, 2);
+ return lua_error(L);
+}
+
+/* }====================================================== */
+
+
+LUALIB_API int luaL_findstring (const char *name, const char *const list[]) {
+ int i;
+ for (i=0; list[i]; i++)
+ if (strcmp(list[i], name) == 0)
+ return i;
+ return -1; /* name not found */
+}
+
+
+LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
+ lua_pushstring(L, tname);
+ lua_rawget(L, LUA_REGISTRYINDEX); /* get registry.name */
+ if (!lua_isnil(L, -1)) /* name already in use? */
+ return 0; /* leave previous value on top, but return 0 */
+ lua_pop(L, 1);
+ lua_newtable(L); /* create metatable */
+ lua_pushstring(L, tname);
+ lua_pushvalue(L, -2);
+ lua_rawset(L, LUA_REGISTRYINDEX); /* registry.name = metatable */
+ lua_pushvalue(L, -1);
+ lua_pushstring(L, tname);
+ lua_rawset(L, LUA_REGISTRYINDEX); /* registry[metatable] = name */
+ return 1;
+}
+
+
+LUALIB_API void luaL_getmetatable (lua_State *L, const char *tname) {
+ lua_pushstring(L, tname);
+ lua_rawget(L, LUA_REGISTRYINDEX);
+}
+
+
+LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
+ const char *tn;
+ if (!lua_getmetatable(L, ud)) return NULL; /* no metatable? */
+ lua_rawget(L, LUA_REGISTRYINDEX); /* get registry[metatable] */
+ tn = lua_tostring(L, -1);
+ if (tn && (strcmp(tn, tname) == 0)) {
+ lua_pop(L, 1);
+ return lua_touserdata(L, ud);
+ }
+ else {
+ lua_pop(L, 1);
+ return NULL;
+ }
+}
+
+
+LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
+ if (!lua_checkstack(L, space))
+ luaL_error(L, "stack overflow (%s)", mes);
+}
+
+
+LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
+ if (lua_type(L, narg) != t)
+ tag_error(L, narg, t);
+}
+
+
+LUALIB_API void luaL_checkany (lua_State *L, int narg) {
+ if (lua_type(L, narg) == LUA_TNONE)
+ luaL_argerror(L, narg, "value expected");
+}
+
+
+LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
+ const char *s = lua_tostring(L, narg);
+ if (!s) tag_error(L, narg, LUA_TSTRING);
+ if (len) *len = lua_strlen(L, narg);
+ return s;
+}
+
+
+LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
+ const char *def, size_t *len) {
+ if (lua_isnoneornil(L, narg)) {
+ if (len)
+ *len = (def ? strlen(def) : 0);
+ return def;
+ }
+ else return luaL_checklstring(L, narg, len);
+}
+
+
+LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
+ lua_Number d = lua_tonumber(L, narg);
+ if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
+ tag_error(L, narg, LUA_TNUMBER);
+ return d;
+}
+
+
+LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
+ if (lua_isnoneornil(L, narg)) return def;
+ else return luaL_checknumber(L, narg);
+}
+
+
+LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
+ if (!lua_getmetatable(L, obj)) /* no metatable? */
+ return 0;
+ lua_pushstring(L, event);
+ lua_rawget(L, -2);
+ if (lua_isnil(L, -1)) {
+ lua_pop(L, 2); /* remove metatable and metafield */
+ return 0;
+ }
+ else {
+ lua_remove(L, -2); /* remove only metatable */
+ return 1;
+ }
+}
+
+
+LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
+ obj = abs_index(L, obj);
+ if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
+ return 0;
+ lua_pushvalue(L, obj);
+ lua_call(L, 1, 1);
+ return 1;
+}
+
+
+LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
+ const luaL_reg *l, int nup) {
+ if (libname) {
+ lua_pushstring(L, libname);
+ lua_gettable(L, LUA_GLOBALSINDEX); /* check whether lib already exists */
+ if (lua_isnil(L, -1)) { /* no? */
+ lua_pop(L, 1);
+ lua_newtable(L); /* create it */
+ lua_pushstring(L, libname);
+ lua_pushvalue(L, -2);
+ lua_settable(L, LUA_GLOBALSINDEX); /* register it with given name */
+ }
+ lua_insert(L, -(nup+1)); /* move library table to below upvalues */
+ }
+ for (; l->name; l++) {
+ int i;
+ lua_pushstring(L, l->name);
+ for (i=0; i<nup; i++) /* copy upvalues to the top */
+ lua_pushvalue(L, -(nup+1));
+ lua_pushcclosure(L, l->func, nup);
+ lua_settable(L, -(nup+3));
+ }
+ lua_pop(L, nup); /* remove upvalues */
+}
+
+
+
+/*
+** {======================================================
+** getn-setn: size for arrays
+** =======================================================
+*/
+
+static int checkint (lua_State *L, int topop) {
+ int n = (int)lua_tonumber(L, -1);
+ if (n == 0 && !lua_isnumber(L, -1)) n = -1;
+ lua_pop(L, topop);
+ return n;
+}
+
+
+static void getsizes (lua_State *L) {
+ lua_rawgeti(L, LUA_REGISTRYINDEX, ARRAYSIZE_REF);
+ if (lua_isnil(L, -1)) { /* no `size' table? */
+ lua_pop(L, 1); /* remove nil */
+ lua_newtable(L); /* create it */
+ lua_pushvalue(L, -1); /* `size' will be its own metatable */
+ lua_setmetatable(L, -2);
+ lua_pushliteral(L, "__mode");
+ lua_pushliteral(L, "k");
+ lua_rawset(L, -3); /* metatable(N).__mode = "k" */
+ lua_pushvalue(L, -1);
+ lua_rawseti(L, LUA_REGISTRYINDEX, ARRAYSIZE_REF); /* store in register */
+ }
+}
+
+
+void luaL_setn (lua_State *L, int t, int n) {
+ t = abs_index(L, t);
+ lua_pushliteral(L, "n");
+ lua_rawget(L, t);
+ if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */
+ lua_pushliteral(L, "n"); /* use it */
+ lua_pushnumber(L, (lua_Number)n);
+ lua_rawset(L, t);
+ }
+ else { /* use `sizes' */
+ getsizes(L);
+ lua_pushvalue(L, t);
+ lua_pushnumber(L, (lua_Number)n);
+ lua_rawset(L, -3); /* sizes[t] = n */
+ lua_pop(L, 1); /* remove `sizes' */
+ }
+}
+
+
+int luaL_getn (lua_State *L, int t) {
+ int n;
+ t = abs_index(L, t);
+ lua_pushliteral(L, "n"); /* try t.n */
+ lua_rawget(L, t);
+ if ((n = checkint(L, 1)) >= 0) return n;
+ getsizes(L); /* else try sizes[t] */
+ lua_pushvalue(L, t);
+ lua_rawget(L, -2);
+ if ((n = checkint(L, 2)) >= 0) return n;
+ for (n = 1; ; n++) { /* else must count elements */
+ lua_rawgeti(L, t, n);
+ if (lua_isnil(L, -1)) break;
+ lua_pop(L, 1);
+ }
+ lua_pop(L, 1);
+ return n - 1;
+}
+
+/* }====================================================== */
+
+
+
+/*
+** {======================================================
+** Generic Buffer manipulation
+** =======================================================
+*/
+
+
+#define bufflen(B) ((B)->p - (B)->buffer)
+#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
+
+#define LIMIT (LUA_MINSTACK/2)
+
+
+static int emptybuffer (luaL_Buffer *B) {
+ size_t l = bufflen(B);
+ if (l == 0) return 0; /* put nothing on stack */
+ else {
+ lua_pushlstring(B->L, B->buffer, l);
+ B->p = B->buffer;
+ B->lvl++;
+ return 1;
+ }
+}
+
+
+static void adjuststack (luaL_Buffer *B) {
+ if (B->lvl > 1) {
+ lua_State *L = B->L;
+ int toget = 1; /* number of levels to concat */
+ size_t toplen = lua_strlen(L, -1);
+ do {
+ size_t l = lua_strlen(L, -(toget+1));
+ if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
+ toplen += l;
+ toget++;
+ }
+ else break;
+ } while (toget < B->lvl);
+ lua_concat(L, toget);
+ B->lvl = B->lvl - toget + 1;
+ }
+}
+
+
+LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
+ if (emptybuffer(B))
+ adjuststack(B);
+ return B->buffer;
+}
+
+
+LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
+ while (l--)
+ luaL_putchar(B, *s++);
+}
+
+
+LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
+ luaL_addlstring(B, s, strlen(s));
+}
+
+
+LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
+ emptybuffer(B);
+ lua_concat(B->L, B->lvl);
+ B->lvl = 1;
+}
+
+
+LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
+ lua_State *L = B->L;
+ size_t vl = lua_strlen(L, -1);
+ if (vl <= bufffree(B)) { /* fit into buffer? */
+ memcpy(B->p, lua_tostring(L, -1), vl); /* put it there */
+ B->p += vl;
+ lua_pop(L, 1); /* remove from stack */
+ }
+ else {
+ if (emptybuffer(B))
+ lua_insert(L, -2); /* put buffer before new value */
+ B->lvl++; /* add new value into B stack */
+ adjuststack(B);
+ }
+}
+
+
+LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
+ B->L = L;
+ B->p = B->buffer;
+ B->lvl = 0;
+}
+
+/* }====================================================== */
+
+
+LUALIB_API int luaL_ref (lua_State *L, int t) {
+ int ref;
+ t = abs_index(L, t);
+ if (lua_isnil(L, -1)) {
+ lua_pop(L, 1); /* remove from stack */
+ return LUA_REFNIL; /* `nil' has a unique fixed reference */
+ }
+ lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
+ ref = (int)lua_tonumber(L, -1); /* ref = t[FREELIST_REF] */
+ lua_pop(L, 1); /* remove it from stack */
+ if (ref != 0) { /* any free element? */
+ lua_rawgeti(L, t, ref); /* remove it from list */
+ lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
+ }
+ else { /* no free elements */
+ ref = luaL_getn(L, t);
+ if (ref < RESERVED_REFS)
+ ref = RESERVED_REFS; /* skip reserved references */
+ ref++; /* create new reference */
+ luaL_setn(L, t, ref);
+ }
+ lua_rawseti(L, t, ref);
+ return ref;
+}
+
+
+LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
+ if (ref >= 0) {
+ t = abs_index(L, t);
+ lua_rawgeti(L, t, FREELIST_REF);
+ lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
+ lua_pushnumber(L, (lua_Number)ref);
+ lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
+ }
+}
+
+
+
+/*
+** {======================================================
+** Load functions
+** =======================================================
+*/
+
+typedef struct LoadF {
+ FILE *f;
+ char buff[LUAL_BUFFERSIZE];
+} LoadF;
+
+
+static const char *getF (lua_State *L, void *ud, size_t *size) {
+ LoadF *lf = (LoadF *)ud;
+ (void)L;
+ if (feof(lf->f)) return NULL;
+ *size = fread(lf->buff, 1, LUAL_BUFFERSIZE, lf->f);
+ return (*size > 0) ? lf->buff : NULL;
+}
+
+
+static int errfile (lua_State *L, int fnameindex) {
+ const char *filename = lua_tostring(L, fnameindex) + 1;
+ lua_pushfstring(L, "cannot read %s: %s", filename, strerror(errno));
+ lua_remove(L, fnameindex);
+ return LUA_ERRFILE;
+}
+
+
+LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
+ LoadF lf;
+ int status, readstatus;
+ int c;
+ int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
+ if (filename == NULL) {
+ lua_pushliteral(L, "=stdin");
+ lf.f = stdin;
+ }
+ else {
+ lua_pushfstring(L, "@%s", filename);
+ lf.f = fopen(filename, "r");
+ }
+ if (lf.f == NULL) return errfile(L, fnameindex); /* unable to open file */
+ c = ungetc(getc(lf.f), lf.f);
+ if (!(isspace(c) || isprint(c)) && lf.f != stdin) { /* binary file? */
+ fclose(lf.f);
+ lf.f = fopen(filename, "rb"); /* reopen in binary mode */
+ if (lf.f == NULL) return errfile(L, fnameindex); /* unable to reopen file */
+ }
+ status = lua_load(L, getF, &lf, lua_tostring(L, -1));
+ readstatus = ferror(lf.f);
+ if (lf.f != stdin) fclose(lf.f); /* close file (even in case of errors) */
+ if (readstatus) {
+ lua_settop(L, fnameindex); /* ignore results from `lua_load' */
+ return errfile(L, fnameindex);
+ }
+ lua_remove(L, fnameindex);
+ return status;
+}
+
+
+typedef struct LoadS {
+ const char *s;
+ size_t size;
+} LoadS;
+
+
+static const char *getS (lua_State *L, void *ud, size_t *size) {
+ LoadS *ls = (LoadS *)ud;
+ (void)L;
+ if (ls->size == 0) return NULL;
+ *size = ls->size;
+ ls->size = 0;
+ return ls->s;
+}
+
+
+LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
+ const char *name) {
+ LoadS ls;
+ ls.s = buff;
+ ls.size = size;
+ return lua_load(L, getS, &ls, name);
+}
+
+/* }====================================================== */
+
+
+/*
+** {======================================================
+** compatibility code
+** =======================================================
+*/
+
+
+static void callalert (lua_State *L, int status) {
+ if (status != 0) {
+ lua_getglobal(L, "_ALERT");
+ if (lua_isfunction(L, -1)) {
+ lua_insert(L, -2);
+ lua_call(L, 1, 0);
+ }
+ else { /* no _ALERT function; print it on stderr */
+ fprintf(stderr, "%s\n", lua_tostring(L, -2));
+ lua_pop(L, 2); /* remove error message and _ALERT */
+ }
+ }
+}
+
+
+static int aux_do (lua_State *L, int status) {
+ if (status == 0) { /* parse OK? */
+ status = lua_pcall(L, 0, LUA_MULTRET, 0); /* call main */
+ }
+ callalert(L, status);
+ return status;
+}
+
+
+LUALIB_API int lua_dofile (lua_State *L, const char *filename) {
+ return aux_do(L, luaL_loadfile(L, filename));
+}
+
+
+LUALIB_API int lua_dobuffer (lua_State *L, const char *buff, size_t size,
+ const char *name) {
+ return aux_do(L, luaL_loadbuffer(L, buff, size, name));
+}
+
+
+LUALIB_API int lua_dostring (lua_State *L, const char *str) {
+ return lua_dobuffer(L, str, strlen(str), str);
+}
+
+/* }====================================================== */
diff --git a/plugins/SmartAutoReplier/lualib/lauxlib.h b/plugins/SmartAutoReplier/lualib/lauxlib.h
new file mode 100644
index 0000000000..450e16c720
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lauxlib.h
@@ -0,0 +1,145 @@
+/*
+** $Id: lauxlib.h,v 1.60 2003/04/03 13:35:34 roberto Exp $
+** Auxiliary functions for building Lua libraries
+** See Copyright Notice in lua.h
+*/
+
+
+#ifndef lauxlib_h
+#define lauxlib_h
+
+
+#include <stddef.h>
+#include <stdio.h>
+
+#include "lua.h"
+
+
+#ifndef LUALIB_API
+#define LUALIB_API LUA_API
+#endif
+
+
+
+typedef struct luaL_reg {
+ const char *name;
+ lua_CFunction func;
+} luaL_reg;
+
+
+LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
+ const luaL_reg *l, int nup);
+LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *e);
+LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *e);
+LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname);
+LUALIB_API int luaL_argerror (lua_State *L, int numarg, const char *extramsg);
+LUALIB_API const char *luaL_checklstring (lua_State *L, int numArg, size_t *l);
+LUALIB_API const char *luaL_optlstring (lua_State *L, int numArg,
+ const char *def, size_t *l);
+LUALIB_API lua_Number luaL_checknumber (lua_State *L, int numArg);
+LUALIB_API lua_Number luaL_optnumber (lua_State *L, int nArg, lua_Number def);
+
+LUALIB_API void luaL_checkstack (lua_State *L, int sz, const char *msg);
+LUALIB_API void luaL_checktype (lua_State *L, int narg, int t);
+LUALIB_API void luaL_checkany (lua_State *L, int narg);
+
+LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname);
+LUALIB_API void luaL_getmetatable (lua_State *L, const char *tname);
+LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname);
+
+LUALIB_API void luaL_where (lua_State *L, int lvl);
+LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...);
+
+LUALIB_API int luaL_findstring (const char *st, const char *const lst[]);
+
+LUALIB_API int luaL_ref (lua_State *L, int t);
+LUALIB_API void luaL_unref (lua_State *L, int t, int ref);
+
+LUALIB_API int luaL_getn (lua_State *L, int t);
+LUALIB_API void luaL_setn (lua_State *L, int t, int n);
+
+LUALIB_API int luaL_loadfile (lua_State *L, const char *filename);
+LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t sz,
+ const char *name);
+
+
+
+/*
+** ===============================================================
+** some useful macros
+** ===============================================================
+*/
+
+#define luaL_argcheck(L, cond,numarg,extramsg) if (!(cond)) \
+ luaL_argerror(L, numarg,extramsg)
+#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
+#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
+#define luaL_checkint(L,n) ((int)luaL_checknumber(L, n))
+#define luaL_checklong(L,n) ((long)luaL_checknumber(L, n))
+#define luaL_optint(L,n,d) ((int)luaL_optnumber(L, n,(lua_Number)(d)))
+#define luaL_optlong(L,n,d) ((long)luaL_optnumber(L, n,(lua_Number)(d)))
+
+
+/*
+** {======================================================
+** Generic Buffer manipulation
+** =======================================================
+*/
+
+
+#ifndef LUAL_BUFFERSIZE
+#define LUAL_BUFFERSIZE BUFSIZ
+#endif
+
+
+typedef struct luaL_Buffer {
+ char *p; /* current position in buffer */
+ int lvl; /* number of strings in the stack (level) */
+ lua_State *L;
+ char buffer[LUAL_BUFFERSIZE];
+} luaL_Buffer;
+
+#define luaL_putchar(B,c) \
+ ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \
+ (*(B)->p++ = (char)(c)))
+
+#define luaL_addsize(B,n) ((B)->p += (n))
+
+LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B);
+LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B);
+LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l);
+LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s);
+LUALIB_API void luaL_addvalue (luaL_Buffer *B);
+LUALIB_API void luaL_pushresult (luaL_Buffer *B);
+
+
+/* }====================================================== */
+
+
+
+/*
+** Compatibility macros and functions
+*/
+
+LUALIB_API int lua_dofile (lua_State *L, const char *filename);
+LUALIB_API int lua_dostring (lua_State *L, const char *str);
+LUALIB_API int lua_dobuffer (lua_State *L, const char *buff, size_t sz,
+ const char *n);
+
+
+#define luaL_check_lstr luaL_checklstring
+#define luaL_opt_lstr luaL_optlstring
+#define luaL_check_number luaL_checknumber
+#define luaL_opt_number luaL_optnumber
+#define luaL_arg_check luaL_argcheck
+#define luaL_check_string luaL_checkstring
+#define luaL_opt_string luaL_optstring
+#define luaL_check_int luaL_checkint
+#define luaL_check_long luaL_checklong
+#define luaL_opt_int luaL_optint
+#define luaL_opt_long luaL_optlong
+
+
+#endif
+
+
diff --git a/plugins/SmartAutoReplier/lualib/lbaselib.c b/plugins/SmartAutoReplier/lualib/lbaselib.c
new file mode 100644
index 0000000000..7381cf3357
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lbaselib.c
@@ -0,0 +1,674 @@
+/*
+** $Id: lbaselib.c,v 1.130 2003/04/03 13:35:34 roberto Exp $
+** Basic library
+** See Copyright Notice in lua.h
+*/
+
+
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define lbaselib_c
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+
+
+/*
+** If your system does not support `stdout', you can just remove this function.
+** If you need, you can define your own `print' function, following this
+** model but changing `fputs' to put the strings at a proper place
+** (a console window or a log file, for instance).
+*/
+static int luaB_print (lua_State *L) {
+ int n = lua_gettop(L); /* number of arguments */
+ int i;
+ lua_getglobal(L, "tostring");
+ for (i=1; i<=n; i++) {
+ const char *s;
+ lua_pushvalue(L, -1); /* function to be called */
+ lua_pushvalue(L, i); /* value to print */
+ lua_call(L, 1, 1);
+ s = lua_tostring(L, -1); /* get result */
+ if (s == NULL)
+ return luaL_error(L, "`tostring' must return a string to `print'");
+ if (i>1) fputs("\t", stdout);
+ fputs(s, stdout);
+ lua_pop(L, 1); /* pop result */
+ }
+ fputs("\n", stdout);
+ return 0;
+}
+
+
+static int luaB_tonumber (lua_State *L) {
+ int base = luaL_optint(L, 2, 10);
+ if (base == 10) { /* standard conversion */
+ luaL_checkany(L, 1);
+ if (lua_isnumber(L, 1)) {
+ lua_pushnumber(L, lua_tonumber(L, 1));
+ return 1;
+ }
+ }
+ else {
+ const char *s1 = luaL_checkstring(L, 1);
+ char *s2;
+ unsigned long n;
+ luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
+ n = strtoul(s1, &s2, base);
+ if (s1 != s2) { /* at least one valid digit? */
+ while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */
+ if (*s2 == '\0') { /* no invalid trailing characters? */
+ lua_pushnumber(L, (lua_Number)n);
+ return 1;
+ }
+ }
+ }
+ lua_pushnil(L); /* else not a number */
+ return 1;
+}
+
+
+static int luaB_error (lua_State *L) {
+ int level = luaL_optint(L, 2, 1);
+ luaL_checkany(L, 1);
+ if (!lua_isstring(L, 1) || level == 0)
+ lua_pushvalue(L, 1); /* propagate error message without changes */
+ else { /* add extra information */
+ luaL_where(L, level);
+ lua_pushvalue(L, 1);
+ lua_concat(L, 2);
+ }
+ return lua_error(L);
+}
+
+
+static int luaB_getmetatable (lua_State *L) {
+ luaL_checkany(L, 1);
+ if (!lua_getmetatable(L, 1)) {
+ lua_pushnil(L);
+ return 1; /* no metatable */
+ }
+ luaL_getmetafield(L, 1, "__metatable");
+ return 1; /* returns either __metatable field (if present) or metatable */
+}
+
+
+static int luaB_setmetatable (lua_State *L) {
+ int t = lua_type(L, 2);
+ luaL_checktype(L, 1, LUA_TTABLE);
+ luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
+ "nil or table expected");
+ if (luaL_getmetafield(L, 1, "__metatable"))
+ luaL_error(L, "cannot change a protected metatable");
+ lua_settop(L, 2);
+ lua_setmetatable(L, 1);
+ return 1;
+}
+
+
+static void getfunc (lua_State *L) {
+ if (lua_isfunction(L, 1)) lua_pushvalue(L, 1);
+ else {
+ lua_Debug ar;
+ int level = luaL_optint(L, 1, 1);
+ luaL_argcheck(L, level >= 0, 1, "level must be non-negative");
+ if (lua_getstack(L, level, &ar) == 0)
+ luaL_argerror(L, 1, "invalid level");
+ lua_getinfo(L, "f", &ar);
+ if (lua_isnil(L, -1))
+ luaL_error(L, "no function environment for tail call at level %d",
+ level);
+ }
+}
+
+
+static int aux_getfenv (lua_State *L) {
+ lua_getfenv(L, -1);
+ lua_pushliteral(L, "__fenv");
+ lua_rawget(L, -2);
+ return !lua_isnil(L, -1);
+}
+
+
+static int luaB_getfenv (lua_State *L) {
+ getfunc(L);
+ if (!aux_getfenv(L)) /* __fenv not defined? */
+ lua_pop(L, 1); /* remove it, to return real environment */
+ return 1;
+}
+
+
+static int luaB_setfenv (lua_State *L) {
+ luaL_checktype(L, 2, LUA_TTABLE);
+ getfunc(L);
+ if (aux_getfenv(L)) /* __fenv defined? */
+ luaL_error(L, "`setfenv' cannot change a protected environment");
+ else
+ lua_pop(L, 2); /* remove __fenv and real environment table */
+ lua_pushvalue(L, 2);
+ if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0)
+ lua_replace(L, LUA_GLOBALSINDEX);
+ else if (lua_setfenv(L, -2) == 0)
+ luaL_error(L, "`setfenv' cannot change environment of given function");
+ return 0;
+}
+
+
+static int luaB_rawequal (lua_State *L) {
+ luaL_checkany(L, 1);
+ luaL_checkany(L, 2);
+ lua_pushboolean(L, lua_rawequal(L, 1, 2));
+ return 1;
+}
+
+
+static int luaB_rawget (lua_State *L) {
+ luaL_checktype(L, 1, LUA_TTABLE);
+ luaL_checkany(L, 2);
+ lua_rawget(L, 1);
+ return 1;
+}
+
+static int luaB_rawset (lua_State *L) {
+ luaL_checktype(L, 1, LUA_TTABLE);
+ luaL_checkany(L, 2);
+ luaL_checkany(L, 3);
+ lua_rawset(L, 1);
+ return 1;
+}
+
+
+static int luaB_gcinfo (lua_State *L) {
+ lua_pushnumber(L, (lua_Number)lua_getgccount(L));
+ lua_pushnumber(L, (lua_Number)lua_getgcthreshold(L));
+ return 2;
+}
+
+
+static int luaB_collectgarbage (lua_State *L) {
+ lua_setgcthreshold(L, luaL_optint(L, 1, 0));
+ return 0;
+}
+
+
+static int luaB_type (lua_State *L) {
+ luaL_checkany(L, 1);
+ lua_pushstring(L, lua_typename(L, lua_type(L, 1)));
+ return 1;
+}
+
+
+static int luaB_next (lua_State *L) {
+ luaL_checktype(L, 1, LUA_TTABLE);
+ lua_settop(L, 2); /* create a 2nd argument if there isn't one */
+ if (lua_next(L, 1))
+ return 2;
+ else {
+ lua_pushnil(L);
+ return 1;
+ }
+}
+
+
+static int luaB_pairs (lua_State *L) {
+ luaL_checktype(L, 1, LUA_TTABLE);
+ lua_pushliteral(L, "next");
+ lua_rawget(L, LUA_GLOBALSINDEX); /* return generator, */
+ lua_pushvalue(L, 1); /* state, */
+ lua_pushnil(L); /* and initial value */
+ return 3;
+}
+
+
+static int luaB_ipairs (lua_State *L) {
+ lua_Number i = lua_tonumber(L, 2);
+ luaL_checktype(L, 1, LUA_TTABLE);
+ if (i == 0 && lua_isnone(L, 2)) { /* `for' start? */
+ lua_pushliteral(L, "ipairs");
+ lua_rawget(L, LUA_GLOBALSINDEX); /* return generator, */
+ lua_pushvalue(L, 1); /* state, */
+ lua_pushnumber(L, 0); /* and initial value */
+ return 3;
+ }
+ else { /* `for' step */
+ i++; /* next value */
+ lua_pushnumber(L, i);
+ lua_rawgeti(L, 1, (int)i);
+ return (lua_isnil(L, -1)) ? 0 : 2;
+ }
+}
+
+
+static int load_aux (lua_State *L, int status) {
+ if (status == 0) /* OK? */
+ return 1;
+ else {
+ lua_pushnil(L);
+ lua_insert(L, -2); /* put before error message */
+ return 2; /* return nil plus error message */
+ }
+}
+
+
+static int luaB_loadstring (lua_State *L) {
+ size_t l;
+ const char *s = luaL_checklstring(L, 1, &l);
+ const char *chunkname = luaL_optstring(L, 2, s);
+ return load_aux(L, luaL_loadbuffer(L, s, l, chunkname));
+}
+
+
+static int luaB_loadfile (lua_State *L) {
+ const char *fname = luaL_optstring(L, 1, NULL);
+ return load_aux(L, luaL_loadfile(L, fname));
+}
+
+
+static int luaB_dofile (lua_State *L) {
+ const char *fname = luaL_optstring(L, 1, NULL);
+ int status = luaL_loadfile(L, fname);
+ if (status != 0) lua_error(L);
+ lua_call(L, 0, LUA_MULTRET);
+ return lua_gettop(L) - 1;
+}
+
+
+static int luaB_assert (lua_State *L) {
+ luaL_checkany(L, 1);
+ if (!lua_toboolean(L, 1))
+ return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
+ lua_settop(L, 1);
+ return 1;
+}
+
+
+static int luaB_unpack (lua_State *L) {
+ int n, i;
+ luaL_checktype(L, 1, LUA_TTABLE);
+ n = luaL_getn(L, 1);
+ luaL_checkstack(L, n, "table too big to unpack");
+ for (i=1; i<=n; i++) /* push arg[1...n] */
+ lua_rawgeti(L, 1, i);
+ return n;
+}
+
+
+static int luaB_pcall (lua_State *L) {
+ int status;
+ luaL_checkany(L, 1);
+ status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
+ lua_pushboolean(L, (status == 0));
+ lua_insert(L, 1);
+ return lua_gettop(L); /* return status + all results */
+}
+
+
+static int luaB_xpcall (lua_State *L) {
+ int status;
+ luaL_checkany(L, 2);
+ lua_settop(L, 2);
+ lua_insert(L, 1); /* put error function under function to be called */
+ status = lua_pcall(L, 0, LUA_MULTRET, 1);
+ lua_pushboolean(L, (status == 0));
+ lua_replace(L, 1);
+ return lua_gettop(L); /* return status + all results */
+}
+
+
+static int luaB_tostring (lua_State *L) {
+ char buff[64];
+ luaL_checkany(L, 1);
+ if (luaL_callmeta(L, 1, "__tostring")) /* is there a metafield? */
+ return 1; /* use its value */
+ switch (lua_type(L, 1)) {
+ case LUA_TNUMBER:
+ lua_pushstring(L, lua_tostring(L, 1));
+ return 1;
+ case LUA_TSTRING:
+ lua_pushvalue(L, 1);
+ return 1;
+ case LUA_TBOOLEAN:
+ lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
+ return 1;
+ case LUA_TTABLE:
+ sprintf(buff, "table: %p", lua_topointer(L, 1));
+ break;
+ case LUA_TFUNCTION:
+ sprintf(buff, "function: %p", lua_topointer(L, 1));
+ break;
+ case LUA_TUSERDATA:
+ case LUA_TLIGHTUSERDATA:
+ sprintf(buff, "userdata: %p", lua_touserdata(L, 1));
+ break;
+ case LUA_TTHREAD:
+ sprintf(buff, "thread: %p", (void *)lua_tothread(L, 1));
+ break;
+ case LUA_TNIL:
+ lua_pushliteral(L, "nil");
+ return 1;
+ }
+ lua_pushstring(L, buff);
+ return 1;
+}
+
+
+static int luaB_newproxy (lua_State *L) {
+ lua_settop(L, 1);
+ lua_newuserdata(L, 0); /* create proxy */
+ if (lua_toboolean(L, 1) == 0)
+ return 1; /* no metatable */
+ else if (lua_isboolean(L, 1)) {
+ lua_newtable(L); /* create a new metatable `m' ... */
+ lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
+ lua_pushboolean(L, 1);
+ lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
+ }
+ else {
+ int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
+ if (lua_getmetatable(L, 1)) {
+ lua_rawget(L, lua_upvalueindex(1));
+ validproxy = lua_toboolean(L, -1);
+ lua_pop(L, 1); /* remove value */
+ }
+ luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
+ lua_getmetatable(L, 1); /* metatable is valid; get it */
+ }
+ lua_setmetatable(L, 2);
+ return 1;
+}
+
+
+/*
+** {======================================================
+** `require' function
+** =======================================================
+*/
+
+
+/* name of global that holds table with loaded packages */
+#define REQTAB "_LOADED"
+
+/* name of global that holds the search path for packages */
+#define LUA_PATH "LUA_PATH"
+
+#ifndef LUA_PATH_SEP
+#define LUA_PATH_SEP ';'
+#endif
+
+#ifndef LUA_PATH_MARK
+#define LUA_PATH_MARK '?'
+#endif
+
+#ifndef LUA_PATH_DEFAULT
+#define LUA_PATH_DEFAULT "?;?.lua"
+#endif
+
+
+static const char *getpath (lua_State *L) {
+ const char *path;
+ lua_getglobal(L, LUA_PATH); /* try global variable */
+ path = lua_tostring(L, -1);
+ lua_pop(L, 1);
+ if (path) return path;
+ path = getenv(LUA_PATH); /* else try environment variable */
+ if (path) return path;
+ return LUA_PATH_DEFAULT; /* else use default */
+}
+
+
+static const char *pushnextpath (lua_State *L, const char *path) {
+ const char *l;
+ if (*path == '\0') return NULL; /* no more paths */
+ if (*path == LUA_PATH_SEP) path++; /* skip separator */
+ l = strchr(path, LUA_PATH_SEP); /* find next separator */
+ if (l == NULL) l = path+strlen(path);
+ lua_pushlstring(L, path, l - path); /* directory name */
+ return l;
+}
+
+
+static void pushcomposename (lua_State *L) {
+ const char *path = lua_tostring(L, -1);
+ const char *wild;
+ int n = 1;
+ while ((wild = strchr(path, LUA_PATH_MARK)) != NULL) {
+ /* is there stack space for prefix, name, and eventual last sufix? */
+ luaL_checkstack(L, 3, "too many marks in a path component");
+ lua_pushlstring(L, path, wild - path); /* push prefix */
+ lua_pushvalue(L, 1); /* push package name (in place of MARK) */
+ path = wild + 1; /* continue after MARK */
+ n += 2;
+ }
+ lua_pushstring(L, path); /* push last sufix (`n' already includes this) */
+ lua_concat(L, n);
+}
+
+
+static int luaB_require (lua_State *L) {
+ const char *path;
+ int status = LUA_ERRFILE; /* not found (yet) */
+ luaL_checkstring(L, 1);
+ lua_settop(L, 1);
+ lua_getglobal(L, REQTAB);
+ if (!lua_istable(L, 2)) return luaL_error(L, "`" REQTAB "' is not a table");
+ path = getpath(L);
+ lua_pushvalue(L, 1); /* check package's name in book-keeping table */
+ lua_rawget(L, 2);
+ if (lua_toboolean(L, -1)) /* is it there? */
+ return 1; /* package is already loaded; return its result */
+ else { /* must load it */
+ while (status == LUA_ERRFILE) {
+ lua_settop(L, 3); /* reset stack position */
+ if ((path = pushnextpath(L, path)) == NULL) break;
+ pushcomposename(L);
+ status = luaL_loadfile(L, lua_tostring(L, -1)); /* try to load it */
+ }
+ }
+ switch (status) {
+ case 0: {
+ lua_getglobal(L, "_REQUIREDNAME"); /* save previous name */
+ lua_insert(L, -2); /* put it below function */
+ lua_pushvalue(L, 1);
+ lua_setglobal(L, "_REQUIREDNAME"); /* set new name */
+ lua_call(L, 0, 1); /* run loaded module */
+ lua_insert(L, -2); /* put result below previous name */
+ lua_setglobal(L, "_REQUIREDNAME"); /* reset to previous name */
+ if (lua_isnil(L, -1)) { /* no/nil return? */
+ lua_pushboolean(L, 1);
+ lua_replace(L, -2); /* replace to true */
+ }
+ lua_pushvalue(L, 1);
+ lua_pushvalue(L, -2);
+ lua_rawset(L, 2); /* mark it as loaded */
+ return 1; /* return value */
+ }
+ case LUA_ERRFILE: { /* file not found */
+ return luaL_error(L, "could not load package `%s' from path `%s'",
+ lua_tostring(L, 1), getpath(L));
+ }
+ default: {
+ return luaL_error(L, "error loading package `%s' (%s)",
+ lua_tostring(L, 1), lua_tostring(L, -1));
+ }
+ }
+}
+
+/* }====================================================== */
+
+
+static const luaL_reg base_funcs[] = {
+ {"error", luaB_error},
+ {"getmetatable", luaB_getmetatable},
+ {"setmetatable", luaB_setmetatable},
+ {"getfenv", luaB_getfenv},
+ {"setfenv", luaB_setfenv},
+ {"next", luaB_next},
+ {"ipairs", luaB_ipairs},
+ {"pairs", luaB_pairs},
+ {"print", luaB_print},
+ {"tonumber", luaB_tonumber},
+ {"tostring", luaB_tostring},
+ {"type", luaB_type},
+ {"assert", luaB_assert},
+ {"unpack", luaB_unpack},
+ {"rawequal", luaB_rawequal},
+ {"rawget", luaB_rawget},
+ {"rawset", luaB_rawset},
+ {"pcall", luaB_pcall},
+ {"xpcall", luaB_xpcall},
+ {"collectgarbage", luaB_collectgarbage},
+ {"gcinfo", luaB_gcinfo},
+ {"loadfile", luaB_loadfile},
+ {"dofile", luaB_dofile},
+ {"loadstring", luaB_loadstring},
+ {"require", luaB_require},
+ {NULL, NULL}
+};
+
+
+/*
+** {======================================================
+** Coroutine library
+** =======================================================
+*/
+
+static int auxresume (lua_State *L, lua_State *co, int narg) {
+ int status;
+ if (!lua_checkstack(co, narg))
+ luaL_error(L, "too many arguments to resume");
+ lua_xmove(L, co, narg);
+ status = lua_resume(co, narg);
+ if (status == 0) {
+ int nres = lua_gettop(co);
+ if (!lua_checkstack(L, nres))
+ luaL_error(L, "too many results to resume");
+ lua_xmove(co, L, nres); /* move yielded values */
+ return nres;
+ }
+ else {
+ lua_xmove(co, L, 1); /* move error message */
+ return -1; /* error flag */
+ }
+}
+
+
+static int luaB_coresume (lua_State *L) {
+ lua_State *co = lua_tothread(L, 1);
+ int r;
+ luaL_argcheck(L, co, 1, "coroutine expected");
+ r = auxresume(L, co, lua_gettop(L) - 1);
+ if (r < 0) {
+ lua_pushboolean(L, 0);
+ lua_insert(L, -2);
+ return 2; /* return false + error message */
+ }
+ else {
+ lua_pushboolean(L, 1);
+ lua_insert(L, -(r + 1));
+ return r + 1; /* return true + `resume' returns */
+ }
+}
+
+
+static int luaB_auxwrap (lua_State *L) {
+ lua_State *co = lua_tothread(L, lua_upvalueindex(1));
+ int r = auxresume(L, co, lua_gettop(L));
+ if (r < 0) {
+ if (lua_isstring(L, -1)) { /* error object is a string? */
+ luaL_where(L, 1); /* add extra info */
+ lua_insert(L, -2);
+ lua_concat(L, 2);
+ }
+ lua_error(L); /* propagate error */
+ }
+ return r;
+}
+
+
+static int luaB_cocreate (lua_State *L) {
+ lua_State *NL = lua_newthread(L);
+ luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
+ "Lua function expected");
+ lua_pushvalue(L, 1); /* move function to top */
+ lua_xmove(L, NL, 1); /* move function from L to NL */
+ return 1;
+}
+
+
+static int luaB_cowrap (lua_State *L) {
+ luaB_cocreate(L);
+ lua_pushcclosure(L, luaB_auxwrap, 1);
+ return 1;
+}
+
+
+static int luaB_yield (lua_State *L) {
+ return lua_yield(L, lua_gettop(L));
+}
+
+
+static int luaB_costatus (lua_State *L) {
+ lua_State *co = lua_tothread(L, 1);
+ luaL_argcheck(L, co, 1, "coroutine expected");
+ if (L == co) lua_pushliteral(L, "running");
+ else {
+ lua_Debug ar;
+ if (lua_getstack(co, 0, &ar) == 0 && lua_gettop(co) == 0)
+ lua_pushliteral(L, "dead");
+ else
+ lua_pushliteral(L, "suspended");
+ }
+ return 1;
+}
+
+
+static const luaL_reg co_funcs[] = {
+ {"create", luaB_cocreate},
+ {"wrap", luaB_cowrap},
+ {"resume", luaB_coresume},
+ {"yield", luaB_yield},
+ {"status", luaB_costatus},
+ {NULL, NULL}
+};
+
+/* }====================================================== */
+
+
+
+static void base_open (lua_State *L) {
+ lua_pushliteral(L, "_G");
+ lua_pushvalue(L, LUA_GLOBALSINDEX);
+ luaL_openlib(L, NULL, base_funcs, 0); /* open lib into global table */
+ lua_pushliteral(L, "_VERSION");
+ lua_pushliteral(L, LUA_VERSION);
+ lua_rawset(L, -3); /* set global _VERSION */
+ /* `newproxy' needs a weaktable as upvalue */
+ lua_pushliteral(L, "newproxy");
+ lua_newtable(L); /* new table `w' */
+ lua_pushvalue(L, -1); /* `w' will be its own metatable */
+ lua_setmetatable(L, -2);
+ lua_pushliteral(L, "__mode");
+ lua_pushliteral(L, "k");
+ lua_rawset(L, -3); /* metatable(w).__mode = "k" */
+ lua_pushcclosure(L, luaB_newproxy, 1);
+ lua_rawset(L, -3); /* set global `newproxy' */
+ lua_rawset(L, -1); /* set global _G */
+}
+
+
+LUALIB_API int luaopen_base (lua_State *L) {
+ base_open(L);
+ luaL_openlib(L, LUA_COLIBNAME, co_funcs, 0);
+ lua_newtable(L);
+ lua_setglobal(L, REQTAB);
+ return 0;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lcode.c b/plugins/SmartAutoReplier/lualib/lcode.c
new file mode 100644
index 0000000000..d626ecd60e
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lcode.c
@@ -0,0 +1,714 @@
+/*
+** $Id: lcode.c,v 1.117 2003/04/03 13:35:34 roberto Exp $
+** Code generator for Lua
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stdlib.h>
+
+#define lcode_c
+
+#include "lua.h"
+
+#include "lcode.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "llex.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lparser.h"
+#include "ltable.h"
+
+
+#define hasjumps(e) ((e)->t != (e)->f)
+
+
+void luaK_nil (FuncState *fs, int from, int n) {
+ Instruction *previous;
+ if (fs->pc > fs->lasttarget && /* no jumps to current position? */
+ GET_OPCODE(*(previous = &fs->f->code[fs->pc-1])) == OP_LOADNIL) {
+ int pfrom = GETARG_A(*previous);
+ int pto = GETARG_B(*previous);
+ if (pfrom <= from && from <= pto+1) { /* can connect both? */
+ if (from+n-1 > pto)
+ SETARG_B(*previous, from+n-1);
+ return;
+ }
+ }
+ luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0); /* else no optimization */
+}
+
+
+int luaK_jump (FuncState *fs) {
+ int jpc = fs->jpc; /* save list of jumps to here */
+ int j;
+ fs->jpc = NO_JUMP;
+ j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);
+ luaK_concat(fs, &j, jpc); /* keep them on hold */
+ return j;
+}
+
+
+static int luaK_condjump (FuncState *fs, OpCode op, int A, int B, int C) {
+ luaK_codeABC(fs, op, A, B, C);
+ return luaK_jump(fs);
+}
+
+
+static void luaK_fixjump (FuncState *fs, int pc, int dest) {
+ Instruction *jmp = &fs->f->code[pc];
+ int offset = dest-(pc+1);
+ lua_assert(dest != NO_JUMP);
+ if (abs(offset) > MAXARG_sBx)
+ luaX_syntaxerror(fs->ls, "control structure too long");
+ SETARG_sBx(*jmp, offset);
+}
+
+
+/*
+** returns current `pc' and marks it as a jump target (to avoid wrong
+** optimizations with consecutive instructions not in the same basic block).
+*/
+int luaK_getlabel (FuncState *fs) {
+ fs->lasttarget = fs->pc;
+ return fs->pc;
+}
+
+
+static int luaK_getjump (FuncState *fs, int pc) {
+ int offset = GETARG_sBx(fs->f->code[pc]);
+ if (offset == NO_JUMP) /* point to itself represents end of list */
+ return NO_JUMP; /* end of list */
+ else
+ return (pc+1)+offset; /* turn offset into absolute position */
+}
+
+
+static Instruction *getjumpcontrol (FuncState *fs, int pc) {
+ Instruction *pi = &fs->f->code[pc];
+ if (pc >= 1 && testOpMode(GET_OPCODE(*(pi-1)), OpModeT))
+ return pi-1;
+ else
+ return pi;
+}
+
+
+/*
+** check whether list has any jump that do not produce a value
+** (or produce an inverted value)
+*/
+static int need_value (FuncState *fs, int list, int cond) {
+ for (; list != NO_JUMP; list = luaK_getjump(fs, list)) {
+ Instruction i = *getjumpcontrol(fs, list);
+ if (GET_OPCODE(i) != OP_TEST || GETARG_C(i) != cond) return 1;
+ }
+ return 0; /* not found */
+}
+
+
+static void patchtestreg (Instruction *i, int reg) {
+ if (reg == NO_REG) reg = GETARG_B(*i);
+ SETARG_A(*i, reg);
+}
+
+
+static void luaK_patchlistaux (FuncState *fs, int list,
+ int ttarget, int treg, int ftarget, int freg, int dtarget) {
+ while (list != NO_JUMP) {
+ int next = luaK_getjump(fs, list);
+ Instruction *i = getjumpcontrol(fs, list);
+ if (GET_OPCODE(*i) != OP_TEST) {
+ lua_assert(dtarget != NO_JUMP);
+ luaK_fixjump(fs, list, dtarget); /* jump to default target */
+ }
+ else {
+ if (GETARG_C(*i)) {
+ lua_assert(ttarget != NO_JUMP);
+ patchtestreg(i, treg);
+ luaK_fixjump(fs, list, ttarget);
+ }
+ else {
+ lua_assert(ftarget != NO_JUMP);
+ patchtestreg(i, freg);
+ luaK_fixjump(fs, list, ftarget);
+ }
+ }
+ list = next;
+ }
+}
+
+
+static void luaK_dischargejpc (FuncState *fs) {
+ luaK_patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc, NO_REG, fs->pc);
+ fs->jpc = NO_JUMP;
+}
+
+
+void luaK_patchlist (FuncState *fs, int list, int target) {
+ if (target == fs->pc)
+ luaK_patchtohere(fs, list);
+ else {
+ lua_assert(target < fs->pc);
+ luaK_patchlistaux(fs, list, target, NO_REG, target, NO_REG, target);
+ }
+}
+
+
+void luaK_patchtohere (FuncState *fs, int list) {
+ luaK_getlabel(fs);
+ luaK_concat(fs, &fs->jpc, list);
+}
+
+
+void luaK_concat (FuncState *fs, int *l1, int l2) {
+ if (l2 == NO_JUMP) return;
+ else if (*l1 == NO_JUMP)
+ *l1 = l2;
+ else {
+ int list = *l1;
+ int next;
+ while ((next = luaK_getjump(fs, list)) != NO_JUMP) /* find last element */
+ list = next;
+ luaK_fixjump(fs, list, l2);
+ }
+}
+
+
+void luaK_checkstack (FuncState *fs, int n) {
+ int newstack = fs->freereg + n;
+ if (newstack > fs->f->maxstacksize) {
+ if (newstack >= MAXSTACK)
+ luaX_syntaxerror(fs->ls, "function or expression too complex");
+ fs->f->maxstacksize = cast(lu_byte, newstack);
+ }
+}
+
+
+void luaK_reserveregs (FuncState *fs, int n) {
+ luaK_checkstack(fs, n);
+ fs->freereg += n;
+}
+
+
+static void freereg (FuncState *fs, int reg) {
+ if (reg >= fs->nactvar && reg < MAXSTACK) {
+ fs->freereg--;
+ lua_assert(reg == fs->freereg);
+ }
+}
+
+
+static void freeexp (FuncState *fs, expdesc *e) {
+ if (e->k == VNONRELOC)
+ freereg(fs, e->info);
+}
+
+
+static int addk (FuncState *fs, TObject *k, TObject *v) {
+ const TObject *idx = luaH_get(fs->h, k);
+ if (ttisnumber(idx)) {
+ lua_assert(luaO_rawequalObj(&fs->f->k[cast(int, nvalue(idx))], v));
+ return cast(int, nvalue(idx));
+ }
+ else { /* constant not found; create a new entry */
+ Proto *f = fs->f;
+ luaM_growvector(fs->L, f->k, fs->nk, f->sizek, TObject,
+ MAXARG_Bx, "constant table overflow");
+ setobj2n(&f->k[fs->nk], v);
+ setnvalue(luaH_set(fs->L, fs->h, k), cast(lua_Number, fs->nk));
+ return fs->nk++;
+ }
+}
+
+
+int luaK_stringK (FuncState *fs, TString *s) {
+ TObject o;
+ setsvalue(&o, s);
+ return addk(fs, &o, &o);
+}
+
+
+int luaK_numberK (FuncState *fs, lua_Number r) {
+ TObject o;
+ setnvalue(&o, r);
+ return addk(fs, &o, &o);
+}
+
+
+static int nil_constant (FuncState *fs) {
+ TObject k, v;
+ setnilvalue(&v);
+ sethvalue(&k, fs->h); /* cannot use nil as key; instead use table itself */
+ return addk(fs, &k, &v);
+}
+
+
+void luaK_setcallreturns (FuncState *fs, expdesc *e, int nresults) {
+ if (e->k == VCALL) { /* expression is an open function call? */
+ SETARG_C(getcode(fs, e), nresults+1);
+ if (nresults == 1) { /* `regular' expression? */
+ e->k = VNONRELOC;
+ e->info = GETARG_A(getcode(fs, e));
+ }
+ }
+}
+
+
+void luaK_dischargevars (FuncState *fs, expdesc *e) {
+ switch (e->k) {
+ case VLOCAL: {
+ e->k = VNONRELOC;
+ break;
+ }
+ case VUPVAL: {
+ e->info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->info, 0);
+ e->k = VRELOCABLE;
+ break;
+ }
+ case VGLOBAL: {
+ e->info = luaK_codeABx(fs, OP_GETGLOBAL, 0, e->info);
+ e->k = VRELOCABLE;
+ break;
+ }
+ case VINDEXED: {
+ freereg(fs, e->aux);
+ freereg(fs, e->info);
+ e->info = luaK_codeABC(fs, OP_GETTABLE, 0, e->info, e->aux);
+ e->k = VRELOCABLE;
+ break;
+ }
+ case VCALL: {
+ luaK_setcallreturns(fs, e, 1);
+ break;
+ }
+ default: break; /* there is one value available (somewhere) */
+ }
+}
+
+
+static int code_label (FuncState *fs, int A, int b, int jump) {
+ luaK_getlabel(fs); /* those instructions may be jump targets */
+ return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
+}
+
+
+static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
+ luaK_dischargevars(fs, e);
+ switch (e->k) {
+ case VNIL: {
+ luaK_nil(fs, reg, 1);
+ break;
+ }
+ case VFALSE: case VTRUE: {
+ luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
+ break;
+ }
+ case VK: {
+ luaK_codeABx(fs, OP_LOADK, reg, e->info);
+ break;
+ }
+ case VRELOCABLE: {
+ Instruction *pc = &getcode(fs, e);
+ SETARG_A(*pc, reg);
+ break;
+ }
+ case VNONRELOC: {
+ if (reg != e->info)
+ luaK_codeABC(fs, OP_MOVE, reg, e->info, 0);
+ break;
+ }
+ default: {
+ lua_assert(e->k == VVOID || e->k == VJMP);
+ return; /* nothing to do... */
+ }
+ }
+ e->info = reg;
+ e->k = VNONRELOC;
+}
+
+
+static void discharge2anyreg (FuncState *fs, expdesc *e) {
+ if (e->k != VNONRELOC) {
+ luaK_reserveregs(fs, 1);
+ discharge2reg(fs, e, fs->freereg-1);
+ }
+}
+
+
+static void luaK_exp2reg (FuncState *fs, expdesc *e, int reg) {
+ discharge2reg(fs, e, reg);
+ if (e->k == VJMP)
+ luaK_concat(fs, &e->t, e->info); /* put this jump in `t' list */
+ if (hasjumps(e)) {
+ int final; /* position after whole expression */
+ int p_f = NO_JUMP; /* position of an eventual LOAD false */
+ int p_t = NO_JUMP; /* position of an eventual LOAD true */
+ if (need_value(fs, e->t, 1) || need_value(fs, e->f, 0)) {
+ int fj = NO_JUMP; /* first jump (over LOAD ops.) */
+ if (e->k != VJMP)
+ fj = luaK_jump(fs);
+ p_f = code_label(fs, reg, 0, 1);
+ p_t = code_label(fs, reg, 1, 0);
+ luaK_patchtohere(fs, fj);
+ }
+ final = luaK_getlabel(fs);
+ luaK_patchlistaux(fs, e->f, p_f, NO_REG, final, reg, p_f);
+ luaK_patchlistaux(fs, e->t, final, reg, p_t, NO_REG, p_t);
+ }
+ e->f = e->t = NO_JUMP;
+ e->info = reg;
+ e->k = VNONRELOC;
+}
+
+
+void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
+ luaK_dischargevars(fs, e);
+ freeexp(fs, e);
+ luaK_reserveregs(fs, 1);
+ luaK_exp2reg(fs, e, fs->freereg - 1);
+}
+
+
+int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
+ luaK_dischargevars(fs, e);
+ if (e->k == VNONRELOC) {
+ if (!hasjumps(e)) return e->info; /* exp is already in a register */
+ if (e->info >= fs->nactvar) { /* reg. is not a local? */
+ luaK_exp2reg(fs, e, e->info); /* put value on it */
+ return e->info;
+ }
+ }
+ luaK_exp2nextreg(fs, e); /* default */
+ return e->info;
+}
+
+
+void luaK_exp2val (FuncState *fs, expdesc *e) {
+ if (hasjumps(e))
+ luaK_exp2anyreg(fs, e);
+ else
+ luaK_dischargevars(fs, e);
+}
+
+
+int luaK_exp2RK (FuncState *fs, expdesc *e) {
+ luaK_exp2val(fs, e);
+ switch (e->k) {
+ case VNIL: {
+ if (fs->nk + MAXSTACK <= MAXARG_C) { /* constant fit in argC? */
+ e->info = nil_constant(fs);
+ e->k = VK;
+ return e->info + MAXSTACK;
+ }
+ else break;
+ }
+ case VK: {
+ if (e->info + MAXSTACK <= MAXARG_C) /* constant fit in argC? */
+ return e->info + MAXSTACK;
+ else break;
+ }
+ default: break;
+ }
+ /* not a constant in the right range: put it in a register */
+ return luaK_exp2anyreg(fs, e);
+}
+
+
+void luaK_storevar (FuncState *fs, expdesc *var, expdesc *exp) {
+ switch (var->k) {
+ case VLOCAL: {
+ freeexp(fs, exp);
+ luaK_exp2reg(fs, exp, var->info);
+ return;
+ }
+ case VUPVAL: {
+ int e = luaK_exp2anyreg(fs, exp);
+ luaK_codeABC(fs, OP_SETUPVAL, e, var->info, 0);
+ break;
+ }
+ case VGLOBAL: {
+ int e = luaK_exp2anyreg(fs, exp);
+ luaK_codeABx(fs, OP_SETGLOBAL, e, var->info);
+ break;
+ }
+ case VINDEXED: {
+ int e = luaK_exp2RK(fs, exp);
+ luaK_codeABC(fs, OP_SETTABLE, var->info, var->aux, e);
+ break;
+ }
+ default: {
+ lua_assert(0); /* invalid var kind to store */
+ break;
+ }
+ }
+ freeexp(fs, exp);
+}
+
+
+void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
+ int func;
+ luaK_exp2anyreg(fs, e);
+ freeexp(fs, e);
+ func = fs->freereg;
+ luaK_reserveregs(fs, 2);
+ luaK_codeABC(fs, OP_SELF, func, e->info, luaK_exp2RK(fs, key));
+ freeexp(fs, key);
+ e->info = func;
+ e->k = VNONRELOC;
+}
+
+
+static void invertjump (FuncState *fs, expdesc *e) {
+ Instruction *pc = getjumpcontrol(fs, e->info);
+ lua_assert(testOpMode(GET_OPCODE(*pc), OpModeT) &&
+ GET_OPCODE(*pc) != OP_TEST);
+ SETARG_A(*pc, !(GETARG_A(*pc)));
+}
+
+
+static int jumponcond (FuncState *fs, expdesc *e, int cond) {
+ if (e->k == VRELOCABLE) {
+ Instruction ie = getcode(fs, e);
+ if (GET_OPCODE(ie) == OP_NOT) {
+ fs->pc--; /* remove previous OP_NOT */
+ return luaK_condjump(fs, OP_TEST, NO_REG, GETARG_B(ie), !cond);
+ }
+ /* else go through */
+ }
+ discharge2anyreg(fs, e);
+ freeexp(fs, e);
+ return luaK_condjump(fs, OP_TEST, NO_REG, e->info, cond);
+}
+
+
+void luaK_goiftrue (FuncState *fs, expdesc *e) {
+ int pc; /* pc of last jump */
+ luaK_dischargevars(fs, e);
+ switch (e->k) {
+ case VK: case VTRUE: {
+ pc = NO_JUMP; /* always true; do nothing */
+ break;
+ }
+ case VFALSE: {
+ pc = luaK_jump(fs); /* always jump */
+ break;
+ }
+ case VJMP: {
+ invertjump(fs, e);
+ pc = e->info;
+ break;
+ }
+ default: {
+ pc = jumponcond(fs, e, 0);
+ break;
+ }
+ }
+ luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */
+}
+
+
+void luaK_goiffalse (FuncState *fs, expdesc *e) {
+ int pc; /* pc of last jump */
+ luaK_dischargevars(fs, e);
+ switch (e->k) {
+ case VNIL: case VFALSE: {
+ pc = NO_JUMP; /* always false; do nothing */
+ break;
+ }
+ case VTRUE: {
+ pc = luaK_jump(fs); /* always jump */
+ break;
+ }
+ case VJMP: {
+ pc = e->info;
+ break;
+ }
+ default: {
+ pc = jumponcond(fs, e, 1);
+ break;
+ }
+ }
+ luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */
+}
+
+
+static void codenot (FuncState *fs, expdesc *e) {
+ luaK_dischargevars(fs, e);
+ switch (e->k) {
+ case VNIL: case VFALSE: {
+ e->k = VTRUE;
+ break;
+ }
+ case VK: case VTRUE: {
+ e->k = VFALSE;
+ break;
+ }
+ case VJMP: {
+ invertjump(fs, e);
+ break;
+ }
+ case VRELOCABLE:
+ case VNONRELOC: {
+ discharge2anyreg(fs, e);
+ freeexp(fs, e);
+ e->info = luaK_codeABC(fs, OP_NOT, 0, e->info, 0);
+ e->k = VRELOCABLE;
+ break;
+ }
+ default: {
+ lua_assert(0); /* cannot happen */
+ break;
+ }
+ }
+ /* interchange true and false lists */
+ { int temp = e->f; e->f = e->t; e->t = temp; }
+}
+
+
+void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
+ t->aux = luaK_exp2RK(fs, k);
+ t->k = VINDEXED;
+}
+
+
+void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) {
+ if (op == OPR_MINUS) {
+ luaK_exp2val(fs, e);
+ if (e->k == VK && ttisnumber(&fs->f->k[e->info]))
+ e->info = luaK_numberK(fs, -nvalue(&fs->f->k[e->info]));
+ else {
+ luaK_exp2anyreg(fs, e);
+ freeexp(fs, e);
+ e->info = luaK_codeABC(fs, OP_UNM, 0, e->info, 0);
+ e->k = VRELOCABLE;
+ }
+ }
+ else /* op == NOT */
+ codenot(fs, e);
+}
+
+
+void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
+ switch (op) {
+ case OPR_AND: {
+ luaK_goiftrue(fs, v);
+ luaK_patchtohere(fs, v->t);
+ v->t = NO_JUMP;
+ break;
+ }
+ case OPR_OR: {
+ luaK_goiffalse(fs, v);
+ luaK_patchtohere(fs, v->f);
+ v->f = NO_JUMP;
+ break;
+ }
+ case OPR_CONCAT: {
+ luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */
+ break;
+ }
+ default: {
+ luaK_exp2RK(fs, v);
+ break;
+ }
+ }
+}
+
+
+static void codebinop (FuncState *fs, expdesc *res, BinOpr op,
+ int o1, int o2) {
+ if (op <= OPR_POW) { /* arithmetic operator? */
+ OpCode opc = cast(OpCode, (op - OPR_ADD) + OP_ADD); /* ORDER OP */
+ res->info = luaK_codeABC(fs, opc, 0, o1, o2);
+ res->k = VRELOCABLE;
+ }
+ else { /* test operator */
+ static const OpCode ops[] = {OP_EQ, OP_EQ, OP_LT, OP_LE, OP_LT, OP_LE};
+ int cond = 1;
+ if (op >= OPR_GT) { /* `>' or `>='? */
+ int temp; /* exchange args and replace by `<' or `<=' */
+ temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */
+ }
+ else if (op == OPR_NE) cond = 0;
+ res->info = luaK_condjump(fs, ops[op - OPR_NE], cond, o1, o2);
+ res->k = VJMP;
+ }
+}
+
+
+void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) {
+ switch (op) {
+ case OPR_AND: {
+ lua_assert(e1->t == NO_JUMP); /* list must be closed */
+ luaK_dischargevars(fs, e2);
+ luaK_concat(fs, &e1->f, e2->f);
+ e1->k = e2->k; e1->info = e2->info; e1->aux = e2->aux; e1->t = e2->t;
+ break;
+ }
+ case OPR_OR: {
+ lua_assert(e1->f == NO_JUMP); /* list must be closed */
+ luaK_dischargevars(fs, e2);
+ luaK_concat(fs, &e1->t, e2->t);
+ e1->k = e2->k; e1->info = e2->info; e1->aux = e2->aux; e1->f = e2->f;
+ break;
+ }
+ case OPR_CONCAT: {
+ luaK_exp2val(fs, e2);
+ if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) {
+ lua_assert(e1->info == GETARG_B(getcode(fs, e2))-1);
+ freeexp(fs, e1);
+ SETARG_B(getcode(fs, e2), e1->info);
+ e1->k = e2->k; e1->info = e2->info;
+ }
+ else {
+ luaK_exp2nextreg(fs, e2);
+ freeexp(fs, e2);
+ freeexp(fs, e1);
+ e1->info = luaK_codeABC(fs, OP_CONCAT, 0, e1->info, e2->info);
+ e1->k = VRELOCABLE;
+ }
+ break;
+ }
+ default: {
+ int o1 = luaK_exp2RK(fs, e1);
+ int o2 = luaK_exp2RK(fs, e2);
+ freeexp(fs, e2);
+ freeexp(fs, e1);
+ codebinop(fs, e1, op, o1, o2);
+ }
+ }
+}
+
+
+void luaK_fixline (FuncState *fs, int line) {
+ fs->f->lineinfo[fs->pc - 1] = line;
+}
+
+
+int luaK_code (FuncState *fs, Instruction i, int line) {
+ Proto *f = fs->f;
+ luaK_dischargejpc(fs); /* `pc' will change */
+ /* put new instruction in code array */
+ luaM_growvector(fs->L, f->code, fs->pc, f->sizecode, Instruction,
+ MAX_INT, "code size overflow");
+ f->code[fs->pc] = i;
+ /* save corresponding line information */
+ luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
+ MAX_INT, "code size overflow");
+ f->lineinfo[fs->pc] = line;
+ return fs->pc++;
+}
+
+
+int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {
+ lua_assert(getOpMode(o) == iABC);
+ return luaK_code(fs, CREATE_ABC(o, a, b, c), fs->ls->lastline);
+}
+
+
+int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
+ lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);
+ return luaK_code(fs, CREATE_ABx(o, a, bc), fs->ls->lastline);
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lcode.h b/plugins/SmartAutoReplier/lualib/lcode.h
new file mode 100644
index 0000000000..74908c6580
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lcode.h
@@ -0,0 +1,74 @@
+/*
+** $Id: lcode.h,v 1.38 2002/12/11 12:34:22 roberto Exp $
+** Code generator for Lua
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lcode_h
+#define lcode_h
+
+#include "llex.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lparser.h"
+
+
+/*
+** Marks the end of a patch list. It is an invalid value both as an absolute
+** address, and as a list link (would link an element to itself).
+*/
+#define NO_JUMP (-1)
+
+
+/*
+** grep "ORDER OPR" if you change these enums
+*/
+typedef enum BinOpr {
+ OPR_ADD, OPR_SUB, OPR_MULT, OPR_DIV, OPR_POW,
+ OPR_CONCAT,
+ OPR_NE, OPR_EQ,
+ OPR_LT, OPR_LE, OPR_GT, OPR_GE,
+ OPR_AND, OPR_OR,
+ OPR_NOBINOPR
+} BinOpr;
+
+#define binopistest(op) ((op) >= OPR_NE)
+
+typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_NOUNOPR } UnOpr;
+
+
+#define getcode(fs,e) ((fs)->f->code[(e)->info])
+
+#define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx)
+
+int luaK_code (FuncState *fs, Instruction i, int line);
+int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);
+int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);
+void luaK_fixline (FuncState *fs, int line);
+void luaK_nil (FuncState *fs, int from, int n);
+void luaK_reserveregs (FuncState *fs, int n);
+void luaK_checkstack (FuncState *fs, int n);
+int luaK_stringK (FuncState *fs, TString *s);
+int luaK_numberK (FuncState *fs, lua_Number r);
+void luaK_dischargevars (FuncState *fs, expdesc *e);
+int luaK_exp2anyreg (FuncState *fs, expdesc *e);
+void luaK_exp2nextreg (FuncState *fs, expdesc *e);
+void luaK_exp2val (FuncState *fs, expdesc *e);
+int luaK_exp2RK (FuncState *fs, expdesc *e);
+void luaK_self (FuncState *fs, expdesc *e, expdesc *key);
+void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k);
+void luaK_goiftrue (FuncState *fs, expdesc *e);
+void luaK_goiffalse (FuncState *fs, expdesc *e);
+void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e);
+void luaK_setcallreturns (FuncState *fs, expdesc *var, int nresults);
+int luaK_jump (FuncState *fs);
+void luaK_patchlist (FuncState *fs, int list, int target);
+void luaK_patchtohere (FuncState *fs, int list);
+void luaK_concat (FuncState *fs, int *l1, int l2);
+int luaK_getlabel (FuncState *fs);
+void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v);
+void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);
+void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/ldblib.c b/plugins/SmartAutoReplier/lualib/ldblib.c
new file mode 100644
index 0000000000..6dc9b64cfc
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ldblib.c
@@ -0,0 +1,299 @@
+/*
+** $Id: ldblib.c,v 1.80 2003/04/03 13:35:34 roberto Exp $
+** Interface from Lua to its debug API
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define ldblib_c
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+
+static void settabss (lua_State *L, const char *i, const char *v) {
+ lua_pushstring(L, i);
+ lua_pushstring(L, v);
+ lua_rawset(L, -3);
+}
+
+
+static void settabsi (lua_State *L, const char *i, int v) {
+ lua_pushstring(L, i);
+ lua_pushnumber(L, (lua_Number)v);
+ lua_rawset(L, -3);
+}
+
+
+static int getinfo (lua_State *L) {
+ lua_Debug ar;
+ const char *options = luaL_optstring(L, 2, "flnSu");
+ if (lua_isnumber(L, 1)) {
+ if (!lua_getstack(L, (int)(lua_tonumber(L, 1)), &ar)) {
+ lua_pushnil(L); /* level out of range */
+ return 1;
+ }
+ }
+ else if (lua_isfunction(L, 1)) {
+ lua_pushfstring(L, ">%s", options);
+ options = lua_tostring(L, -1);
+ lua_pushvalue(L, 1);
+ }
+ else
+ return luaL_argerror(L, 1, "function or level expected");
+ if (!lua_getinfo(L, options, &ar))
+ return luaL_argerror(L, 2, "invalid option");
+ lua_newtable(L);
+ for (; *options; options++) {
+ switch (*options) {
+ case 'S':
+ settabss(L, "source", ar.source);
+ settabss(L, "short_src", ar.short_src);
+ settabsi(L, "linedefined", ar.linedefined);
+ settabss(L, "what", ar.what);
+ break;
+ case 'l':
+ settabsi(L, "currentline", ar.currentline);
+ break;
+ case 'u':
+ settabsi(L, "nups", ar.nups);
+ break;
+ case 'n':
+ settabss(L, "name", ar.name);
+ settabss(L, "namewhat", ar.namewhat);
+ break;
+ case 'f':
+ lua_pushliteral(L, "func");
+ lua_pushvalue(L, -3);
+ lua_rawset(L, -3);
+ break;
+ }
+ }
+ return 1; /* return table */
+}
+
+
+static int getlocal (lua_State *L) {
+ lua_Debug ar;
+ const char *name;
+ if (!lua_getstack(L, luaL_checkint(L, 1), &ar)) /* level out of range? */
+ return luaL_argerror(L, 1, "level out of range");
+ name = lua_getlocal(L, &ar, luaL_checkint(L, 2));
+ if (name) {
+ lua_pushstring(L, name);
+ lua_pushvalue(L, -2);
+ return 2;
+ }
+ else {
+ lua_pushnil(L);
+ return 1;
+ }
+}
+
+
+static int setlocal (lua_State *L) {
+ lua_Debug ar;
+ if (!lua_getstack(L, luaL_checkint(L, 1), &ar)) /* level out of range? */
+ return luaL_argerror(L, 1, "level out of range");
+ luaL_checkany(L, 3);
+ lua_pushstring(L, lua_setlocal(L, &ar, luaL_checkint(L, 2)));
+ return 1;
+}
+
+
+static int auxupvalue (lua_State *L, int get) {
+ const char *name;
+ int n = luaL_checkint(L, 2);
+ luaL_checktype(L, 1, LUA_TFUNCTION);
+ if (lua_iscfunction(L, 1)) return 0; /* cannot touch C upvalues from Lua */
+ name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
+ if (name == NULL) return 0;
+ lua_pushstring(L, name);
+ lua_insert(L, -(get+1));
+ return get + 1;
+}
+
+
+static int getupvalue (lua_State *L) {
+ return auxupvalue(L, 1);
+}
+
+
+static int setupvalue (lua_State *L) {
+ luaL_checkany(L, 3);
+ return auxupvalue(L, 0);
+}
+
+
+
+static const char KEY_HOOK = 'h';
+
+
+static void hookf (lua_State *L, lua_Debug *ar) {
+ static const char *const hooknames[] =
+ {"call", "return", "line", "count", "tail return"};
+ lua_pushlightuserdata(L, (void *)&KEY_HOOK);
+ lua_rawget(L, LUA_REGISTRYINDEX);
+ if (lua_isfunction(L, -1)) {
+ lua_pushstring(L, hooknames[(int)ar->event]);
+ if (ar->currentline >= 0)
+ lua_pushnumber(L, (lua_Number)ar->currentline);
+ else lua_pushnil(L);
+ lua_assert(lua_getinfo(L, "lS", ar));
+ lua_call(L, 2, 0);
+ }
+ else
+ lua_pop(L, 1); /* pop result from gettable */
+}
+
+
+static int makemask (const char *smask, int count) {
+ int mask = 0;
+ if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
+ if (strchr(smask, 'r')) mask |= LUA_MASKRET;
+ if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
+ if (count > 0) mask |= LUA_MASKCOUNT;
+ return mask;
+}
+
+
+static char *unmakemask (int mask, char *smask) {
+ int i = 0;
+ if (mask & LUA_MASKCALL) smask[i++] = 'c';
+ if (mask & LUA_MASKRET) smask[i++] = 'r';
+ if (mask & LUA_MASKLINE) smask[i++] = 'l';
+ smask[i] = '\0';
+ return smask;
+}
+
+
+static int sethook (lua_State *L) {
+ if (lua_isnoneornil(L, 1)) {
+ lua_settop(L, 1);
+ lua_sethook(L, NULL, 0, 0); /* turn off hooks */
+ }
+ else {
+ const char *smask = luaL_checkstring(L, 2);
+ int count = luaL_optint(L, 3, 0);
+ luaL_checktype(L, 1, LUA_TFUNCTION);
+ lua_sethook(L, hookf, makemask(smask, count), count);
+ }
+ lua_pushlightuserdata(L, (void *)&KEY_HOOK);
+ lua_pushvalue(L, 1);
+ lua_rawset(L, LUA_REGISTRYINDEX); /* set new hook */
+ return 0;
+}
+
+
+static int gethook (lua_State *L) {
+ char buff[5];
+ int mask = lua_gethookmask(L);
+ lua_Hook hook = lua_gethook(L);
+ if (hook != NULL && hook != hookf) /* external hook? */
+ lua_pushliteral(L, "external hook");
+ else {
+ lua_pushlightuserdata(L, (void *)&KEY_HOOK);
+ lua_rawget(L, LUA_REGISTRYINDEX); /* get hook */
+ }
+ lua_pushstring(L, unmakemask(mask, buff));
+ lua_pushnumber(L, (lua_Number)lua_gethookcount(L));
+ return 3;
+}
+
+
+static int debug (lua_State *L) {
+ for (;;) {
+ char buffer[250];
+ fputs("lua_debug> ", stderr);
+ if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
+ strcmp(buffer, "cont\n") == 0)
+ return 0;
+ lua_dostring(L, buffer);
+ lua_settop(L, 0); /* remove eventual returns */
+ }
+}
+
+
+#define LEVELS1 12 /* size of the first part of the stack */
+#define LEVELS2 10 /* size of the second part of the stack */
+
+static int errorfb (lua_State *L) {
+ int level = 1; /* skip level 0 (it's this function) */
+ int firstpart = 1; /* still before eventual `...' */
+ lua_Debug ar;
+ if (lua_gettop(L) == 0)
+ lua_pushliteral(L, "");
+ else if (!lua_isstring(L, 1)) return 1; /* no string message */
+ else lua_pushliteral(L, "\n");
+ lua_pushliteral(L, "stack traceback:");
+ while (lua_getstack(L, level++, &ar)) {
+ if (level > LEVELS1 && firstpart) {
+ /* no more than `LEVELS2' more levels? */
+ if (!lua_getstack(L, level+LEVELS2, &ar))
+ level--; /* keep going */
+ else {
+ lua_pushliteral(L, "\n\t..."); /* too many levels */
+ while (lua_getstack(L, level+LEVELS2, &ar)) /* find last levels */
+ level++;
+ }
+ firstpart = 0;
+ continue;
+ }
+ lua_pushliteral(L, "\n\t");
+ lua_getinfo(L, "Snl", &ar);
+ lua_pushfstring(L, "%s:", ar.short_src);
+ if (ar.currentline > 0)
+ lua_pushfstring(L, "%d:", ar.currentline);
+ switch (*ar.namewhat) {
+ case 'g': /* global */
+ case 'l': /* local */
+ case 'f': /* field */
+ case 'm': /* method */
+ lua_pushfstring(L, " in function `%s'", ar.name);
+ break;
+ default: {
+ if (*ar.what == 'm') /* main? */
+ lua_pushfstring(L, " in main chunk");
+ else if (*ar.what == 'C' || *ar.what == 't')
+ lua_pushliteral(L, " ?"); /* C function or tail call */
+ else
+ lua_pushfstring(L, " in function <%s:%d>",
+ ar.short_src, ar.linedefined);
+ }
+ }
+ lua_concat(L, lua_gettop(L));
+ }
+ lua_concat(L, lua_gettop(L));
+ return 1;
+}
+
+
+static const luaL_reg dblib[] = {
+ {"getlocal", getlocal},
+ {"getinfo", getinfo},
+ {"gethook", gethook},
+ {"getupvalue", getupvalue},
+ {"sethook", sethook},
+ {"setlocal", setlocal},
+ {"setupvalue", setupvalue},
+ {"debug", debug},
+ {"traceback", errorfb},
+ {NULL, NULL}
+};
+
+
+LUALIB_API int luaopen_debug (lua_State *L) {
+ luaL_openlib(L, LUA_DBLIBNAME, dblib, 0);
+ lua_pushliteral(L, "_TRACEBACK");
+ lua_pushcfunction(L, errorfb);
+ lua_settable(L, LUA_GLOBALSINDEX);
+ return 1;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/ldebug.c b/plugins/SmartAutoReplier/lualib/ldebug.c
new file mode 100644
index 0000000000..8e511e3bd9
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ldebug.c
@@ -0,0 +1,585 @@
+/*
+** $Id: ldebug.c,v 1.150 2003/03/19 21:24:04 roberto Exp $
+** Debug Interface
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stdlib.h>
+#include <string.h>
+
+#define ldebug_c
+
+#include "lua.h"
+
+#include "lapi.h"
+#include "lcode.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+#include "lvm.h"
+
+
+
+static const char *getfuncname (CallInfo *ci, const char **name);
+
+
+#define isLua(ci) (!((ci)->state & CI_C))
+
+
+static int currentpc (CallInfo *ci) {
+ if (!isLua(ci)) return -1; /* function is not a Lua function? */
+ if (ci->state & CI_HASFRAME) /* function has a frame? */
+ ci->u.l.savedpc = *ci->u.l.pc; /* use `pc' from there */
+ /* function's pc is saved */
+ return pcRel(ci->u.l.savedpc, ci_func(ci)->l.p);
+}
+
+
+static int currentline (CallInfo *ci) {
+ int pc = currentpc(ci);
+ if (pc < 0)
+ return -1; /* only active lua functions have current-line information */
+ else
+ return getline(ci_func(ci)->l.p, pc);
+}
+
+
+void luaG_inithooks (lua_State *L) {
+ CallInfo *ci;
+ for (ci = L->ci; ci != L->base_ci; ci--) /* update all `savedpc's */
+ currentpc(ci);
+ L->hookinit = 1;
+}
+
+
+/*
+** this function can be called asynchronous (e.g. during a signal)
+*/
+LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
+ if (func == NULL || mask == 0) { /* turn off hooks? */
+ mask = 0;
+ func = NULL;
+ }
+ L->hook = func;
+ L->basehookcount = count;
+ resethookcount(L);
+ L->hookmask = cast(lu_byte, mask);
+ L->hookinit = 0;
+ return 1;
+}
+
+
+LUA_API lua_Hook lua_gethook (lua_State *L) {
+ return L->hook;
+}
+
+
+LUA_API int lua_gethookmask (lua_State *L) {
+ return L->hookmask;
+}
+
+
+LUA_API int lua_gethookcount (lua_State *L) {
+ return L->basehookcount;
+}
+
+
+LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
+ int status;
+ CallInfo *ci;
+ lua_lock(L);
+ for (ci = L->ci; level > 0 && ci > L->base_ci; ci--) {
+ level--;
+ if (!(ci->state & CI_C)) /* Lua function? */
+ level -= ci->u.l.tailcalls; /* skip lost tail calls */
+ }
+ if (level > 0 || ci == L->base_ci) status = 0; /* there is no such level */
+ else if (level < 0) { /* level is of a lost tail call */
+ status = 1;
+ ar->i_ci = 0;
+ }
+ else {
+ status = 1;
+ ar->i_ci = ci - L->base_ci;
+ }
+ lua_unlock(L);
+ return status;
+}
+
+
+static Proto *getluaproto (CallInfo *ci) {
+ return (isLua(ci) ? ci_func(ci)->l.p : NULL);
+}
+
+
+LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
+ const char *name;
+ CallInfo *ci;
+ Proto *fp;
+ lua_lock(L);
+ name = NULL;
+ ci = L->base_ci + ar->i_ci;
+ fp = getluaproto(ci);
+ if (fp) { /* is a Lua function? */
+ name = luaF_getlocalname(fp, n, currentpc(ci));
+ if (name)
+ luaA_pushobject(L, ci->base+(n-1)); /* push value */
+ }
+ lua_unlock(L);
+ return name;
+}
+
+
+LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
+ const char *name;
+ CallInfo *ci;
+ Proto *fp;
+ lua_lock(L);
+ name = NULL;
+ ci = L->base_ci + ar->i_ci;
+ fp = getluaproto(ci);
+ L->top--; /* pop new value */
+ if (fp) { /* is a Lua function? */
+ name = luaF_getlocalname(fp, n, currentpc(ci));
+ if (!name || name[0] == '(') /* `(' starts private locals */
+ name = NULL;
+ else
+ setobjs2s(ci->base+(n-1), L->top);
+ }
+ lua_unlock(L);
+ return name;
+}
+
+
+static void funcinfo (lua_Debug *ar, StkId func) {
+ Closure *cl = clvalue(func);
+ if (cl->c.isC) {
+ ar->source = "=[C]";
+ ar->linedefined = -1;
+ ar->what = "C";
+ }
+ else {
+ ar->source = getstr(cl->l.p->source);
+ ar->linedefined = cl->l.p->lineDefined;
+ ar->what = (ar->linedefined == 0) ? "main" : "Lua";
+ }
+ luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
+}
+
+
+static const char *travglobals (lua_State *L, const TObject *o) {
+ Table *g = hvalue(gt(L));
+ int i = sizenode(g);
+ while (i--) {
+ Node *n = gnode(g, i);
+ if (luaO_rawequalObj(o, gval(n)) && ttisstring(gkey(n)))
+ return getstr(tsvalue(gkey(n)));
+ }
+ return NULL;
+}
+
+
+static void info_tailcall (lua_State *L, lua_Debug *ar) {
+ ar->name = ar->namewhat = "";
+ ar->what = "tail";
+ ar->linedefined = ar->currentline = -1;
+ ar->source = "=(tail call)";
+ luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
+ ar->nups = 0;
+ setnilvalue(L->top);
+}
+
+
+static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
+ StkId f, CallInfo *ci) {
+ int status = 1;
+ for (; *what; what++) {
+ switch (*what) {
+ case 'S': {
+ funcinfo(ar, f);
+ break;
+ }
+ case 'l': {
+ ar->currentline = (ci) ? currentline(ci) : -1;
+ break;
+ }
+ case 'u': {
+ ar->nups = clvalue(f)->c.nupvalues;
+ break;
+ }
+ case 'n': {
+ ar->namewhat = (ci) ? getfuncname(ci, &ar->name) : NULL;
+ if (ar->namewhat == NULL) {
+ /* try to find a global name */
+ if ((ar->name = travglobals(L, f)) != NULL)
+ ar->namewhat = "global";
+ else ar->namewhat = ""; /* not found */
+ }
+ break;
+ }
+ case 'f': {
+ setobj2s(L->top, f);
+ break;
+ }
+ default: status = 0; /* invalid option */
+ }
+ }
+ return status;
+}
+
+
+LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
+ int status = 1;
+ lua_lock(L);
+ if (*what == '>') {
+ StkId f = L->top - 1;
+ if (!ttisfunction(f))
+ luaG_runerror(L, "value for `lua_getinfo' is not a function");
+ status = auxgetinfo(L, what + 1, ar, f, NULL);
+ L->top--; /* pop function */
+ }
+ else if (ar->i_ci != 0) { /* no tail call? */
+ CallInfo *ci = L->base_ci + ar->i_ci;
+ lua_assert(ttisfunction(ci->base - 1));
+ status = auxgetinfo(L, what, ar, ci->base - 1, ci);
+ }
+ else
+ info_tailcall(L, ar);
+ if (strchr(what, 'f')) incr_top(L);
+ lua_unlock(L);
+ return status;
+}
+
+
+/*
+** {======================================================
+** Symbolic Execution and code checker
+** =======================================================
+*/
+
+#define check(x) if (!(x)) return 0;
+
+#define checkjump(pt,pc) check(0 <= pc && pc < pt->sizecode)
+
+#define checkreg(pt,reg) check((reg) < (pt)->maxstacksize)
+
+
+
+static int precheck (const Proto *pt) {
+ check(pt->maxstacksize <= MAXSTACK);
+ check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0);
+ lua_assert(pt->numparams+pt->is_vararg <= pt->maxstacksize);
+ check(GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN);
+ return 1;
+}
+
+
+static int checkopenop (const Proto *pt, int pc) {
+ Instruction i = pt->code[pc+1];
+ switch (GET_OPCODE(i)) {
+ case OP_CALL:
+ case OP_TAILCALL:
+ case OP_RETURN: {
+ check(GETARG_B(i) == 0);
+ return 1;
+ }
+ case OP_SETLISTO: return 1;
+ default: return 0; /* invalid instruction after an open call */
+ }
+}
+
+
+static int checkRK (const Proto *pt, int r) {
+ return (r < pt->maxstacksize || (r >= MAXSTACK && r-MAXSTACK < pt->sizek));
+}
+
+
+static Instruction luaG_symbexec (const Proto *pt, int lastpc, int reg) {
+ int pc;
+ int last; /* stores position of last instruction that changed `reg' */
+ last = pt->sizecode-1; /* points to final return (a `neutral' instruction) */
+ check(precheck(pt));
+ for (pc = 0; pc < lastpc; pc++) {
+ const Instruction i = pt->code[pc];
+ OpCode op = GET_OPCODE(i);
+ int a = GETARG_A(i);
+ int b = 0;
+ int c = 0;
+ checkreg(pt, a);
+ switch (getOpMode(op)) {
+ case iABC: {
+ b = GETARG_B(i);
+ c = GETARG_C(i);
+ if (testOpMode(op, OpModeBreg)) {
+ checkreg(pt, b);
+ }
+ else if (testOpMode(op, OpModeBrk))
+ check(checkRK(pt, b));
+ if (testOpMode(op, OpModeCrk))
+ check(checkRK(pt, c));
+ break;
+ }
+ case iABx: {
+ b = GETARG_Bx(i);
+ if (testOpMode(op, OpModeK)) check(b < pt->sizek);
+ break;
+ }
+ case iAsBx: {
+ b = GETARG_sBx(i);
+ break;
+ }
+ }
+ if (testOpMode(op, OpModesetA)) {
+ if (a == reg) last = pc; /* change register `a' */
+ }
+ if (testOpMode(op, OpModeT)) {
+ check(pc+2 < pt->sizecode); /* check skip */
+ check(GET_OPCODE(pt->code[pc+1]) == OP_JMP);
+ }
+ switch (op) {
+ case OP_LOADBOOL: {
+ check(c == 0 || pc+2 < pt->sizecode); /* check its jump */
+ break;
+ }
+ case OP_LOADNIL: {
+ if (a <= reg && reg <= b)
+ last = pc; /* set registers from `a' to `b' */
+ break;
+ }
+ case OP_GETUPVAL:
+ case OP_SETUPVAL: {
+ check(b < pt->nups);
+ break;
+ }
+ case OP_GETGLOBAL:
+ case OP_SETGLOBAL: {
+ check(ttisstring(&pt->k[b]));
+ break;
+ }
+ case OP_SELF: {
+ checkreg(pt, a+1);
+ if (reg == a+1) last = pc;
+ break;
+ }
+ case OP_CONCAT: {
+ /* `c' is a register, and at least two operands */
+ check(c < MAXSTACK && b < c);
+ break;
+ }
+ case OP_TFORLOOP:
+ checkreg(pt, a+c+5);
+ if (reg >= a) last = pc; /* affect all registers above base */
+ /* go through */
+ case OP_FORLOOP:
+ checkreg(pt, a+2);
+ /* go through */
+ case OP_JMP: {
+ int dest = pc+1+b;
+ check(0 <= dest && dest < pt->sizecode);
+ /* not full check and jump is forward and do not skip `lastpc'? */
+ if (reg != NO_REG && pc < dest && dest <= lastpc)
+ pc += b; /* do the jump */
+ break;
+ }
+ case OP_CALL:
+ case OP_TAILCALL: {
+ if (b != 0) {
+ checkreg(pt, a+b-1);
+ }
+ c--; /* c = num. returns */
+ if (c == LUA_MULTRET) {
+ check(checkopenop(pt, pc));
+ }
+ else if (c != 0)
+ checkreg(pt, a+c-1);
+ if (reg >= a) last = pc; /* affect all registers above base */
+ break;
+ }
+ case OP_RETURN: {
+ b--; /* b = num. returns */
+ if (b > 0) checkreg(pt, a+b-1);
+ break;
+ }
+ case OP_SETLIST: {
+ checkreg(pt, a + (b&(LFIELDS_PER_FLUSH-1)) + 1);
+ break;
+ }
+ case OP_CLOSURE: {
+ int nup;
+ check(b < pt->sizep);
+ nup = pt->p[b]->nups;
+ check(pc + nup < pt->sizecode);
+ for (; nup>0; nup--) {
+ OpCode op1 = GET_OPCODE(pt->code[pc+nup]);
+ check(op1 == OP_GETUPVAL || op1 == OP_MOVE);
+ }
+ break;
+ }
+ default: break;
+ }
+ }
+ return pt->code[last];
+}
+
+#undef check
+#undef checkjump
+#undef checkreg
+
+/* }====================================================== */
+
+
+int luaG_checkcode (const Proto *pt) {
+ return luaG_symbexec(pt, pt->sizecode, NO_REG);
+}
+
+
+static const char *kname (Proto *p, int c) {
+ c = c - MAXSTACK;
+ if (c >= 0 && ttisstring(&p->k[c]))
+ return svalue(&p->k[c]);
+ else
+ return "?";
+}
+
+
+static const char *getobjname (CallInfo *ci, int stackpos, const char **name) {
+ if (isLua(ci)) { /* a Lua function? */
+ Proto *p = ci_func(ci)->l.p;
+ int pc = currentpc(ci);
+ Instruction i;
+ *name = luaF_getlocalname(p, stackpos+1, pc);
+ if (*name) /* is a local? */
+ return "local";
+ i = luaG_symbexec(p, pc, stackpos); /* try symbolic execution */
+ lua_assert(pc != -1);
+ switch (GET_OPCODE(i)) {
+ case OP_GETGLOBAL: {
+ int g = GETARG_Bx(i); /* global index */
+ lua_assert(ttisstring(&p->k[g]));
+ *name = svalue(&p->k[g]);
+ return "global";
+ }
+ case OP_MOVE: {
+ int a = GETARG_A(i);
+ int b = GETARG_B(i); /* move from `b' to `a' */
+ if (b < a)
+ return getobjname(ci, b, name); /* get name for `b' */
+ break;
+ }
+ case OP_GETTABLE: {
+ int k = GETARG_C(i); /* key index */
+ *name = kname(p, k);
+ return "field";
+ }
+ case OP_SELF: {
+ int k = GETARG_C(i); /* key index */
+ *name = kname(p, k);
+ return "method";
+ }
+ default: break;
+ }
+ }
+ return NULL; /* no useful name found */
+}
+
+
+static const char *getfuncname (CallInfo *ci, const char **name) {
+ Instruction i;
+ if ((isLua(ci) && ci->u.l.tailcalls > 0) || !isLua(ci - 1))
+ return NULL; /* calling function is not Lua (or is unknown) */
+ ci--; /* calling function */
+ i = ci_func(ci)->l.p->code[currentpc(ci)];
+ if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL)
+ return getobjname(ci, GETARG_A(i), name);
+ else
+ return NULL; /* no useful name can be found */
+}
+
+
+/* only ANSI way to check whether a pointer points to an array */
+static int isinstack (CallInfo *ci, const TObject *o) {
+ StkId p;
+ for (p = ci->base; p < ci->top; p++)
+ if (o == p) return 1;
+ return 0;
+}
+
+
+void luaG_typeerror (lua_State *L, const TObject *o, const char *op) {
+ const char *name = NULL;
+ const char *t = luaT_typenames[ttype(o)];
+ const char *kind = (isinstack(L->ci, o)) ?
+ getobjname(L->ci, o - L->base, &name) : NULL;
+ if (kind)
+ luaG_runerror(L, "attempt to %s %s `%s' (a %s value)",
+ op, kind, name, t);
+ else
+ luaG_runerror(L, "attempt to %s a %s value", op, t);
+}
+
+
+void luaG_concaterror (lua_State *L, StkId p1, StkId p2) {
+ if (ttisstring(p1)) p1 = p2;
+ lua_assert(!ttisstring(p1));
+ luaG_typeerror(L, p1, "concatenate");
+}
+
+
+void luaG_aritherror (lua_State *L, const TObject *p1, const TObject *p2) {
+ TObject temp;
+ if (luaV_tonumber(p1, &temp) == NULL)
+ p2 = p1; /* first operand is wrong */
+ luaG_typeerror(L, p2, "perform arithmetic on");
+}
+
+
+int luaG_ordererror (lua_State *L, const TObject *p1, const TObject *p2) {
+ const char *t1 = luaT_typenames[ttype(p1)];
+ const char *t2 = luaT_typenames[ttype(p2)];
+ if (t1[2] == t2[2])
+ luaG_runerror(L, "attempt to compare two %s values", t1);
+ else
+ luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
+ return 0;
+}
+
+
+static void addinfo (lua_State *L, const char *msg) {
+ CallInfo *ci = L->ci;
+ if (isLua(ci)) { /* is Lua code? */
+ char buff[LUA_IDSIZE]; /* add file:line information */
+ int line = currentline(ci);
+ luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE);
+ luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
+ }
+}
+
+
+void luaG_errormsg (lua_State *L) {
+ if (L->errfunc != 0) { /* is there an error handling function? */
+ StkId errfunc = restorestack(L, L->errfunc);
+ if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR);
+ setobjs2s(L->top, L->top - 1); /* move argument */
+ setobjs2s(L->top - 1, errfunc); /* push function */
+ incr_top(L);
+ luaD_call(L, L->top - 2, 1); /* call it */
+ }
+ luaD_throw(L, LUA_ERRRUN);
+}
+
+
+void luaG_runerror (lua_State *L, const char *fmt, ...) {
+ va_list argp;
+ va_start(argp, fmt);
+ addinfo(L, luaO_pushvfstring(L, fmt, argp));
+ va_end(argp);
+ luaG_errormsg(L);
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/ldebug.h b/plugins/SmartAutoReplier/lualib/ldebug.h
new file mode 100644
index 0000000000..7ff395839c
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ldebug.h
@@ -0,0 +1,31 @@
+/*
+** $Id: ldebug.h,v 1.32 2002/11/18 11:01:55 roberto Exp $
+** Auxiliary functions from Debug Interface module
+** See Copyright Notice in lua.h
+*/
+
+#ifndef ldebug_h
+#define ldebug_h
+
+
+#include "lstate.h"
+
+
+#define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1)
+
+#define getline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0)
+
+#define resethookcount(L) (L->hookcount = L->basehookcount)
+
+
+void luaG_inithooks (lua_State *L);
+void luaG_typeerror (lua_State *L, const TObject *o, const char *opname);
+void luaG_concaterror (lua_State *L, StkId p1, StkId p2);
+void luaG_aritherror (lua_State *L, const TObject *p1, const TObject *p2);
+int luaG_ordererror (lua_State *L, const TObject *p1, const TObject *p2);
+void luaG_runerror (lua_State *L, const char *fmt, ...);
+void luaG_errormsg (lua_State *L);
+int luaG_checkcode (const Proto *pt);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/ldo.c b/plugins/SmartAutoReplier/lualib/ldo.c
new file mode 100644
index 0000000000..ae4f22fd44
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ldo.c
@@ -0,0 +1,458 @@
+/*
+** $Id: ldo.c,v 1.217 2003/04/03 13:35:34 roberto Exp $
+** Stack and Call structure of Lua
+** See Copyright Notice in lua.h
+*/
+
+
+#include <setjmp.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define ldo_c
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lparser.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+#include "lundump.h"
+#include "lvm.h"
+#include "lzio.h"
+
+
+
+
+/*
+** {======================================================
+** Error-recovery functions (based on long jumps)
+** =======================================================
+*/
+
+
+/* chain list of long jump buffers */
+struct lua_longjmp {
+ struct lua_longjmp *previous;
+ jmp_buf b;
+ volatile int status; /* error code */
+};
+
+
+static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
+ switch (errcode) {
+ case LUA_ERRMEM: {
+ setsvalue2s(oldtop, luaS_new(L, MEMERRMSG));
+ break;
+ }
+ case LUA_ERRERR: {
+ setsvalue2s(oldtop, luaS_new(L, "error in error handling"));
+ break;
+ }
+ case LUA_ERRSYNTAX:
+ case LUA_ERRRUN: {
+ setobjs2s(oldtop, L->top - 1); /* error message on current top */
+ break;
+ }
+ }
+ L->top = oldtop + 1;
+}
+
+
+void luaD_throw (lua_State *L, int errcode) {
+ if (L->errorJmp) {
+ L->errorJmp->status = errcode;
+ longjmp(L->errorJmp->b, 1);
+ }
+ else {
+ G(L)->panic(L);
+ exit(EXIT_FAILURE);
+ }
+}
+
+
+int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
+ struct lua_longjmp lj;
+ lj.status = 0;
+ lj.previous = L->errorJmp; /* chain new error handler */
+ L->errorJmp = &lj;
+ if (setjmp(lj.b) == 0)
+ (*f)(L, ud);
+ L->errorJmp = lj.previous; /* restore old error handler */
+ return lj.status;
+}
+
+
+static void restore_stack_limit (lua_State *L) {
+ L->stack_last = L->stack+L->stacksize-1;
+ if (L->size_ci > LUA_MAXCALLS) { /* there was an overflow? */
+ int inuse = (L->ci - L->base_ci);
+ if (inuse + 1 < LUA_MAXCALLS) /* can `undo' overflow? */
+ luaD_reallocCI(L, LUA_MAXCALLS);
+ }
+}
+
+/* }====================================================== */
+
+
+static void correctstack (lua_State *L, TObject *oldstack) {
+ CallInfo *ci;
+ GCObject *up;
+ L->top = (L->top - oldstack) + L->stack;
+ for (up = L->openupval; up != NULL; up = up->gch.next)
+ gcotouv(up)->v = (gcotouv(up)->v - oldstack) + L->stack;
+ for (ci = L->base_ci; ci <= L->ci; ci++) {
+ ci->top = (ci->top - oldstack) + L->stack;
+ ci->base = (ci->base - oldstack) + L->stack;
+ }
+ L->base = L->ci->base;
+}
+
+
+void luaD_reallocstack (lua_State *L, int newsize) {
+ TObject *oldstack = L->stack;
+ luaM_reallocvector(L, L->stack, L->stacksize, newsize, TObject);
+ L->stacksize = newsize;
+ L->stack_last = L->stack+newsize-1-EXTRA_STACK;
+ correctstack(L, oldstack);
+}
+
+
+void luaD_reallocCI (lua_State *L, int newsize) {
+ CallInfo *oldci = L->base_ci;
+ luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo);
+ L->size_ci = cast(unsigned short, newsize);
+ L->ci = (L->ci - oldci) + L->base_ci;
+ L->end_ci = L->base_ci + L->size_ci;
+}
+
+
+void luaD_growstack (lua_State *L, int n) {
+ if (n <= L->stacksize) /* double size is enough? */
+ luaD_reallocstack(L, 2*L->stacksize);
+ else
+ luaD_reallocstack(L, L->stacksize + n + EXTRA_STACK);
+}
+
+
+static void luaD_growCI (lua_State *L) {
+ if (L->size_ci > LUA_MAXCALLS) /* overflow while handling overflow? */
+ luaD_throw(L, LUA_ERRERR);
+ else {
+ luaD_reallocCI(L, 2*L->size_ci);
+ if (L->size_ci > LUA_MAXCALLS)
+ luaG_runerror(L, "stack overflow");
+ }
+}
+
+
+void luaD_callhook (lua_State *L, int event, int line) {
+ lua_Hook hook = L->hook;
+ if (hook && L->allowhook) {
+ ptrdiff_t top = savestack(L, L->top);
+ ptrdiff_t ci_top = savestack(L, L->ci->top);
+ lua_Debug ar;
+ ar.event = event;
+ ar.currentline = line;
+ if (event == LUA_HOOKTAILRET)
+ ar.i_ci = 0; /* tail call; no debug information about it */
+ else
+ ar.i_ci = L->ci - L->base_ci;
+ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
+ L->ci->top = L->top + LUA_MINSTACK;
+ L->allowhook = 0; /* cannot call hooks inside a hook */
+ lua_unlock(L);
+ (*hook)(L, &ar);
+ lua_lock(L);
+ lua_assert(!L->allowhook);
+ L->allowhook = 1;
+ L->ci->top = restorestack(L, ci_top);
+ L->top = restorestack(L, top);
+ }
+}
+
+
+static void adjust_varargs (lua_State *L, int nfixargs, StkId base) {
+ int i;
+ Table *htab;
+ TObject nname;
+ int actual = L->top - base; /* actual number of arguments */
+ if (actual < nfixargs) {
+ luaD_checkstack(L, nfixargs - actual);
+ for (; actual < nfixargs; ++actual)
+ setnilvalue(L->top++);
+ }
+ actual -= nfixargs; /* number of extra arguments */
+ htab = luaH_new(L, actual, 1); /* create `arg' table */
+ for (i=0; i<actual; i++) /* put extra arguments into `arg' table */
+ setobj2n(luaH_setnum(L, htab, i+1), L->top - actual + i);
+ /* store counter in field `n' */
+ setsvalue(&nname, luaS_newliteral(L, "n"));
+ setnvalue(luaH_set(L, htab, &nname), cast(lua_Number, actual));
+ L->top -= actual; /* remove extra elements from the stack */
+ sethvalue(L->top, htab);
+ incr_top(L);
+}
+
+
+static StkId tryfuncTM (lua_State *L, StkId func) {
+ const TObject *tm = luaT_gettmbyobj(L, func, TM_CALL);
+ StkId p;
+ ptrdiff_t funcr = savestack(L, func);
+ if (!ttisfunction(tm))
+ luaG_typeerror(L, func, "call");
+ /* Open a hole inside the stack at `func' */
+ for (p = L->top; p > func; p--) setobjs2s(p, p-1);
+ incr_top(L);
+ func = restorestack(L, funcr); /* previous call may change stack */
+ setobj2s(func, tm); /* tag method is the new function to be called */
+ return func;
+}
+
+
+StkId luaD_precall (lua_State *L, StkId func) {
+ LClosure *cl;
+ ptrdiff_t funcr = savestack(L, func);
+ if (!ttisfunction(func)) /* `func' is not a function? */
+ func = tryfuncTM(L, func); /* check the `function' tag method */
+ if (L->ci + 1 == L->end_ci) luaD_growCI(L);
+ else condhardstacktests(luaD_reallocCI(L, L->size_ci));
+ cl = &clvalue(func)->l;
+ if (!cl->isC) { /* Lua function? prepare its call */
+ CallInfo *ci;
+ Proto *p = cl->p;
+ if (p->is_vararg) /* varargs? */
+ adjust_varargs(L, p->numparams, func+1);
+ luaD_checkstack(L, p->maxstacksize);
+ ci = ++L->ci; /* now `enter' new function */
+ L->base = L->ci->base = restorestack(L, funcr) + 1;
+ ci->top = L->base + p->maxstacksize;
+ ci->u.l.savedpc = p->code; /* starting point */
+ ci->u.l.tailcalls = 0;
+ ci->state = CI_SAVEDPC;
+ while (L->top < ci->top)
+ setnilvalue(L->top++);
+ L->top = ci->top;
+ return NULL;
+ }
+ else { /* if is a C function, call it */
+ CallInfo *ci;
+ int n;
+ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
+ ci = ++L->ci; /* now `enter' new function */
+ L->base = L->ci->base = restorestack(L, funcr) + 1;
+ ci->top = L->top + LUA_MINSTACK;
+ ci->state = CI_C; /* a C function */
+ if (L->hookmask & LUA_MASKCALL)
+ luaD_callhook(L, LUA_HOOKCALL, -1);
+ lua_unlock(L);
+#ifdef LUA_COMPATUPVALUES
+ lua_pushupvalues(L);
+#endif
+ n = (*clvalue(L->base - 1)->c.f)(L); /* do the actual call */
+ lua_lock(L);
+ return L->top - n;
+ }
+}
+
+
+static StkId callrethooks (lua_State *L, StkId firstResult) {
+ ptrdiff_t fr = savestack(L, firstResult); /* next call may change stack */
+ luaD_callhook(L, LUA_HOOKRET, -1);
+ if (!(L->ci->state & CI_C)) { /* Lua function? */
+ while (L->ci->u.l.tailcalls--) /* call hook for eventual tail calls */
+ luaD_callhook(L, LUA_HOOKTAILRET, -1);
+ }
+ return restorestack(L, fr);
+}
+
+
+void luaD_poscall (lua_State *L, int wanted, StkId firstResult) {
+ StkId res;
+ if (L->hookmask & LUA_MASKRET)
+ firstResult = callrethooks(L, firstResult);
+ res = L->base - 1; /* res == final position of 1st result */
+ L->ci--;
+ L->base = L->ci->base; /* restore base */
+ /* move results to correct place */
+ while (wanted != 0 && firstResult < L->top) {
+ setobjs2s(res++, firstResult++);
+ wanted--;
+ }
+ while (wanted-- > 0)
+ setnilvalue(res++);
+ L->top = res;
+}
+
+
+/*
+** Call a function (C or Lua). The function to be called is at *func.
+** The arguments are on the stack, right after the function.
+** When returns, all the results are on the stack, starting at the original
+** function position.
+*/
+void luaD_call (lua_State *L, StkId func, int nResults) {
+ StkId firstResult;
+ lua_assert(!(L->ci->state & CI_CALLING));
+ if (++L->nCcalls >= LUA_MAXCCALLS) {
+ if (L->nCcalls == LUA_MAXCCALLS)
+ luaG_runerror(L, "C stack overflow");
+ else if (L->nCcalls >= (LUA_MAXCCALLS + (LUA_MAXCCALLS>>3)))
+ luaD_throw(L, LUA_ERRERR); /* error while handing stack error */
+ }
+ firstResult = luaD_precall(L, func);
+ if (firstResult == NULL) /* is a Lua function? */
+ firstResult = luaV_execute(L); /* call it */
+ luaD_poscall(L, nResults, firstResult);
+ L->nCcalls--;
+ luaC_checkGC(L);
+}
+
+
+static void resume (lua_State *L, void *ud) {
+ StkId firstResult;
+ int nargs = *cast(int *, ud);
+ CallInfo *ci = L->ci;
+ if (ci == L->base_ci) { /* no activation record? */
+ if (nargs >= L->top - L->base)
+ luaG_runerror(L, "cannot resume dead coroutine");
+ luaD_precall(L, L->top - (nargs + 1)); /* start coroutine */
+ }
+ else if (ci->state & CI_YIELD) { /* inside a yield? */
+ if (ci->state & CI_C) { /* `common' yield? */
+ /* finish interrupted execution of `OP_CALL' */
+ int nresults;
+ lua_assert((ci-1)->state & CI_SAVEDPC);
+ lua_assert(GET_OPCODE(*((ci-1)->u.l.savedpc - 1)) == OP_CALL ||
+ GET_OPCODE(*((ci-1)->u.l.savedpc - 1)) == OP_TAILCALL);
+ nresults = GETARG_C(*((ci-1)->u.l.savedpc - 1)) - 1;
+ luaD_poscall(L, nresults, L->top - nargs); /* complete it */
+ if (nresults >= 0) L->top = L->ci->top;
+ }
+ else { /* yielded inside a hook: just continue its execution */
+ ci->state &= ~CI_YIELD;
+ }
+ }
+ else
+ luaG_runerror(L, "cannot resume non-suspended coroutine");
+ firstResult = luaV_execute(L);
+ if (firstResult != NULL) /* return? */
+ luaD_poscall(L, LUA_MULTRET, firstResult); /* finalize this coroutine */
+}
+
+
+LUA_API int lua_resume (lua_State *L, int nargs) {
+ int status;
+ lu_byte old_allowhooks;
+ lua_lock(L);
+ old_allowhooks = L->allowhook;
+ lua_assert(L->errfunc == 0 && L->nCcalls == 0);
+ status = luaD_rawrunprotected(L, resume, &nargs);
+ if (status != 0) { /* error? */
+ L->ci = L->base_ci; /* go back to initial level */
+ L->base = L->ci->base;
+ L->nCcalls = 0;
+ luaF_close(L, L->base); /* close eventual pending closures */
+ seterrorobj(L, status, L->base);
+ L->allowhook = old_allowhooks;
+ restore_stack_limit(L);
+ }
+ lua_unlock(L);
+ return status;
+}
+
+
+LUA_API int lua_yield (lua_State *L, int nresults) {
+ CallInfo *ci;
+ lua_lock(L);
+ ci = L->ci;
+ if (L->nCcalls > 0)
+ luaG_runerror(L, "attempt to yield across metamethod/C-call boundary");
+ if (ci->state & CI_C) { /* usual yield */
+ if ((ci-1)->state & CI_C)
+ luaG_runerror(L, "cannot yield a C function");
+ if (L->top - nresults > L->base) { /* is there garbage in the stack? */
+ int i;
+ for (i=0; i<nresults; i++) /* move down results */
+ setobjs2s(L->base + i, L->top - nresults + i);
+ L->top = L->base + nresults;
+ }
+ } /* else it's an yield inside a hook: nothing to do */
+ ci->state |= CI_YIELD;
+ lua_unlock(L);
+ return -1;
+}
+
+
+int luaD_pcall (lua_State *L, Pfunc func, void *u,
+ ptrdiff_t old_top, ptrdiff_t ef) {
+ int status;
+ unsigned short oldnCcalls = L->nCcalls;
+ ptrdiff_t old_ci = saveci(L, L->ci);
+ lu_byte old_allowhooks = L->allowhook;
+ ptrdiff_t old_errfunc = L->errfunc;
+ L->errfunc = ef;
+ status = luaD_rawrunprotected(L, func, u);
+ if (status != 0) { /* an error occurred? */
+ StkId oldtop = restorestack(L, old_top);
+ luaF_close(L, oldtop); /* close eventual pending closures */
+ seterrorobj(L, status, oldtop);
+ L->nCcalls = oldnCcalls;
+ L->ci = restoreci(L, old_ci);
+ L->base = L->ci->base;
+ L->allowhook = old_allowhooks;
+ restore_stack_limit(L);
+ }
+ L->errfunc = old_errfunc;
+ return status;
+}
+
+
+
+/*
+** Execute a protected parser.
+*/
+struct SParser { /* data to `f_parser' */
+ ZIO *z;
+ Mbuffer buff; /* buffer to be used by the scanner */
+ int bin;
+};
+
+static void f_parser (lua_State *L, void *ud) {
+ struct SParser *p;
+ Proto *tf;
+ Closure *cl;
+ luaC_checkGC(L);
+ p = cast(struct SParser *, ud);
+ tf = p->bin ? luaU_undump(L, p->z, &p->buff) : luaY_parser(L, p->z, &p->buff);
+ cl = luaF_newLclosure(L, 0, gt(L));
+ cl->l.p = tf;
+ setclvalue(L->top, cl);
+ incr_top(L);
+}
+
+
+int luaD_protectedparser (lua_State *L, ZIO *z, int bin) {
+ struct SParser p;
+ int status;
+ ptrdiff_t oldtopr = savestack(L, L->top); /* save current top */
+ p.z = z; p.bin = bin;
+ luaZ_initbuffer(L, &p.buff);
+ status = luaD_rawrunprotected(L, f_parser, &p);
+ luaZ_freebuffer(L, &p.buff);
+ if (status != 0) { /* error? */
+ StkId oldtop = restorestack(L, oldtopr);
+ seterrorobj(L, status, oldtop);
+ }
+ return status;
+}
+
+
diff --git a/plugins/SmartAutoReplier/lualib/ldo.h b/plugins/SmartAutoReplier/lualib/ldo.h
new file mode 100644
index 0000000000..2a61bf5bb2
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ldo.h
@@ -0,0 +1,60 @@
+/*
+** $Id: ldo.h,v 1.56 2002/12/04 17:29:32 roberto Exp $
+** Stack and Call structure of Lua
+** See Copyright Notice in lua.h
+*/
+
+#ifndef ldo_h
+#define ldo_h
+
+
+#include "lobject.h"
+#include "lstate.h"
+#include "lzio.h"
+
+
+/*
+** macro to control inclusion of some hard tests on stack reallocation
+*/
+#ifndef HARDSTACKTESTS
+#define condhardstacktests(x) { /* empty */ }
+#else
+#define condhardstacktests(x) x
+#endif
+
+
+#define luaD_checkstack(L,n) \
+ if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TObject)) \
+ luaD_growstack(L, n); \
+ else condhardstacktests(luaD_reallocstack(L, L->stacksize));
+
+
+#define incr_top(L) {luaD_checkstack(L,1); L->top++;}
+
+#define savestack(L,p) ((char *)(p) - (char *)L->stack)
+#define restorestack(L,n) ((TObject *)((char *)L->stack + (n)))
+
+#define saveci(L,p) ((char *)(p) - (char *)L->base_ci)
+#define restoreci(L,n) ((CallInfo *)((char *)L->base_ci + (n)))
+
+
+/* type of protected functions, to be ran by `runprotected' */
+typedef void (*Pfunc) (lua_State *L, void *ud);
+
+void luaD_resetprotection (lua_State *L);
+int luaD_protectedparser (lua_State *L, ZIO *z, int bin);
+void luaD_callhook (lua_State *L, int event, int line);
+StkId luaD_precall (lua_State *L, StkId func);
+void luaD_call (lua_State *L, StkId func, int nResults);
+int luaD_pcall (lua_State *L, Pfunc func, void *u,
+ ptrdiff_t oldtop, ptrdiff_t ef);
+void luaD_poscall (lua_State *L, int wanted, StkId firstResult);
+void luaD_reallocCI (lua_State *L, int newsize);
+void luaD_reallocstack (lua_State *L, int newsize);
+void luaD_growstack (lua_State *L, int n);
+
+void luaD_throw (lua_State *L, int errcode);
+int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/ldump.c b/plugins/SmartAutoReplier/lualib/ldump.c
new file mode 100644
index 0000000000..234b011f5f
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ldump.c
@@ -0,0 +1,170 @@
+/*
+** $Id: ldump.c,v 1.4 2003/02/11 23:52:12 lhf Exp $
+** save bytecodes
+** See Copyright Notice in lua.h
+*/
+
+#include <stddef.h>
+
+#define ldump_c
+
+#include "lua.h"
+
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lstate.h"
+#include "lundump.h"
+
+#define DumpVector(b,n,size,D) DumpBlock(b,(n)*(size),D)
+#define DumpLiteral(s,D) DumpBlock("" s,(sizeof(s))-1,D)
+
+typedef struct {
+ lua_State* L;
+ lua_Chunkwriter write;
+ void* data;
+} DumpState;
+
+static void DumpBlock(const void* b, size_t size, DumpState* D)
+{
+ lua_unlock(D->L);
+ (*D->write)(D->L,b,size,D->data);
+ lua_lock(D->L);
+}
+
+static void DumpByte(int y, DumpState* D)
+{
+ char x=(char)y;
+ DumpBlock(&x,sizeof(x),D);
+}
+
+static void DumpInt(int x, DumpState* D)
+{
+ DumpBlock(&x,sizeof(x),D);
+}
+
+static void DumpSize(size_t x, DumpState* D)
+{
+ DumpBlock(&x,sizeof(x),D);
+}
+
+static void DumpNumber(lua_Number x, DumpState* D)
+{
+ DumpBlock(&x,sizeof(x),D);
+}
+
+static void DumpString(TString* s, DumpState* D)
+{
+ if (s==NULL || getstr(s)==NULL)
+ DumpSize(0,D);
+ else
+ {
+ size_t size=s->tsv.len+1; /* include trailing '\0' */
+ DumpSize(size,D);
+ DumpBlock(getstr(s),size,D);
+ }
+}
+
+static void DumpCode(const Proto* f, DumpState* D)
+{
+ DumpInt(f->sizecode,D);
+ DumpVector(f->code,f->sizecode,sizeof(*f->code),D);
+}
+
+static void DumpLocals(const Proto* f, DumpState* D)
+{
+ int i,n=f->sizelocvars;
+ DumpInt(n,D);
+ for (i=0; i<n; i++)
+ {
+ DumpString(f->locvars[i].varname,D);
+ DumpInt(f->locvars[i].startpc,D);
+ DumpInt(f->locvars[i].endpc,D);
+ }
+}
+
+static void DumpLines(const Proto* f, DumpState* D)
+{
+ DumpInt(f->sizelineinfo,D);
+ DumpVector(f->lineinfo,f->sizelineinfo,sizeof(*f->lineinfo),D);
+}
+
+static void DumpUpvalues(const Proto* f, DumpState* D)
+{
+ int i,n=f->sizeupvalues;
+ DumpInt(n,D);
+ for (i=0; i<n; i++) DumpString(f->upvalues[i],D);
+}
+
+static void DumpFunction(const Proto* f, const TString* p, DumpState* D);
+
+static void DumpConstants(const Proto* f, DumpState* D)
+{
+ int i,n;
+ DumpInt(n=f->sizek,D);
+ for (i=0; i<n; i++)
+ {
+ const TObject* o=&f->k[i];
+ DumpByte(ttype(o),D);
+ switch (ttype(o))
+ {
+ case LUA_TNUMBER:
+ DumpNumber(nvalue(o),D);
+ break;
+ case LUA_TSTRING:
+ DumpString(tsvalue(o),D);
+ break;
+ case LUA_TNIL:
+ break;
+ default:
+ lua_assert(0); /* cannot happen */
+ break;
+ }
+ }
+ DumpInt(n=f->sizep,D);
+ for (i=0; i<n; i++) DumpFunction(f->p[i],f->source,D);
+}
+
+static void DumpFunction(const Proto* f, const TString* p, DumpState* D)
+{
+ DumpString((f->source==p) ? NULL : f->source,D);
+ DumpInt(f->lineDefined,D);
+ DumpByte(f->nups,D);
+ DumpByte(f->numparams,D);
+ DumpByte(f->is_vararg,D);
+ DumpByte(f->maxstacksize,D);
+ DumpLines(f,D);
+ DumpLocals(f,D);
+ DumpUpvalues(f,D);
+ DumpConstants(f,D);
+ DumpCode(f,D);
+}
+
+static void DumpHeader(DumpState* D)
+{
+ DumpLiteral(LUA_SIGNATURE,D);
+ DumpByte(VERSION,D);
+ DumpByte(luaU_endianness(),D);
+ DumpByte(sizeof(int),D);
+ DumpByte(sizeof(size_t),D);
+ DumpByte(sizeof(Instruction),D);
+ DumpByte(SIZE_OP,D);
+ DumpByte(SIZE_A,D);
+ DumpByte(SIZE_B,D);
+ DumpByte(SIZE_C,D);
+ DumpByte(sizeof(lua_Number),D);
+ DumpNumber(TEST_NUMBER,D);
+}
+
+/*
+** dump function as precompiled chunk
+*/
+void luaU_dump (lua_State* L, const Proto* Main, lua_Chunkwriter w, void* data)
+{
+ DumpState D;
+ D.L=L;
+ D.write=w;
+ D.data=data;
+ DumpHeader(&D);
+ DumpFunction(Main,NULL,&D);
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lfunc.c b/plugins/SmartAutoReplier/lualib/lfunc.c
new file mode 100644
index 0000000000..31044fa56b
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lfunc.c
@@ -0,0 +1,135 @@
+/*
+** $Id: lfunc.c,v 1.67 2003/03/18 12:50:04 roberto Exp $
+** Auxiliary functions to manipulate prototypes and closures
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stdlib.h>
+
+#define lfunc_c
+
+#include "lua.h"
+
+#include "lfunc.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+
+
+#define sizeCclosure(n) (cast(int, sizeof(CClosure)) + \
+ cast(int, sizeof(TObject)*((n)-1)))
+
+#define sizeLclosure(n) (cast(int, sizeof(LClosure)) + \
+ cast(int, sizeof(TObject *)*((n)-1)))
+
+
+
+Closure *luaF_newCclosure (lua_State *L, int nelems) {
+ Closure *c = cast(Closure *, luaM_malloc(L, sizeCclosure(nelems)));
+ luaC_link(L, valtogco(c), LUA_TFUNCTION);
+ c->c.isC = 1;
+ c->c.nupvalues = cast(lu_byte, nelems);
+ return c;
+}
+
+
+Closure *luaF_newLclosure (lua_State *L, int nelems, TObject *e) {
+ Closure *c = cast(Closure *, luaM_malloc(L, sizeLclosure(nelems)));
+ luaC_link(L, valtogco(c), LUA_TFUNCTION);
+ c->l.isC = 0;
+ c->l.g = *e;
+ c->l.nupvalues = cast(lu_byte, nelems);
+ return c;
+}
+
+
+UpVal *luaF_findupval (lua_State *L, StkId level) {
+ GCObject **pp = &L->openupval;
+ UpVal *p;
+ UpVal *v;
+ while ((p = ngcotouv(*pp)) != NULL && p->v >= level) {
+ if (p->v == level) return p;
+ pp = &p->next;
+ }
+ v = luaM_new(L, UpVal); /* not found: create a new one */
+ v->tt = LUA_TUPVAL;
+ v->marked = 1; /* open upvalues should not be collected */
+ v->v = level; /* current value lives in the stack */
+ v->next = *pp; /* chain it in the proper position */
+ *pp = valtogco(v);
+ return v;
+}
+
+
+void luaF_close (lua_State *L, StkId level) {
+ UpVal *p;
+ while ((p = ngcotouv(L->openupval)) != NULL && p->v >= level) {
+ setobj(&p->value, p->v); /* save current value (write barrier) */
+ p->v = &p->value; /* now current value lives here */
+ L->openupval = p->next; /* remove from `open' list */
+ luaC_link(L, valtogco(p), LUA_TUPVAL);
+ }
+}
+
+
+Proto *luaF_newproto (lua_State *L) {
+ Proto *f = luaM_new(L, Proto);
+ luaC_link(L, valtogco(f), LUA_TPROTO);
+ f->k = NULL;
+ f->sizek = 0;
+ f->p = NULL;
+ f->sizep = 0;
+ f->code = NULL;
+ f->sizecode = 0;
+ f->sizelineinfo = 0;
+ f->sizeupvalues = 0;
+ f->nups = 0;
+ f->upvalues = NULL;
+ f->numparams = 0;
+ f->is_vararg = 0;
+ f->maxstacksize = 0;
+ f->lineinfo = NULL;
+ f->sizelocvars = 0;
+ f->locvars = NULL;
+ f->lineDefined = 0;
+ f->source = NULL;
+ return f;
+}
+
+
+void luaF_freeproto (lua_State *L, Proto *f) {
+ luaM_freearray(L, f->code, f->sizecode, Instruction);
+ luaM_freearray(L, f->p, f->sizep, Proto *);
+ luaM_freearray(L, f->k, f->sizek, TObject);
+ luaM_freearray(L, f->lineinfo, f->sizelineinfo, int);
+ luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar);
+ luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *);
+ luaM_freelem(L, f);
+}
+
+
+void luaF_freeclosure (lua_State *L, Closure *c) {
+ int size = (c->c.isC) ? sizeCclosure(c->c.nupvalues) :
+ sizeLclosure(c->l.nupvalues);
+ luaM_free(L, c, size);
+}
+
+
+/*
+** Look for n-th local variable at line `line' in function `func'.
+** Returns NULL if not found.
+*/
+const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
+ int i;
+ for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
+ if (pc < f->locvars[i].endpc) { /* is variable active? */
+ local_number--;
+ if (local_number == 0)
+ return getstr(f->locvars[i].varname);
+ }
+ }
+ return NULL; /* not found */
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lfunc.h b/plugins/SmartAutoReplier/lualib/lfunc.h
new file mode 100644
index 0000000000..5d5325076b
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lfunc.h
@@ -0,0 +1,25 @@
+/*
+** $Id: lfunc.h,v 1.21 2003/03/18 12:50:04 roberto Exp $
+** Auxiliary functions to manipulate prototypes and closures
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lfunc_h
+#define lfunc_h
+
+
+#include "lobject.h"
+
+
+Proto *luaF_newproto (lua_State *L);
+Closure *luaF_newCclosure (lua_State *L, int nelems);
+Closure *luaF_newLclosure (lua_State *L, int nelems, TObject *e);
+UpVal *luaF_findupval (lua_State *L, StkId level);
+void luaF_close (lua_State *L, StkId level);
+void luaF_freeproto (lua_State *L, Proto *f);
+void luaF_freeclosure (lua_State *L, Closure *c);
+
+const char *luaF_getlocalname (const Proto *func, int local_number, int pc);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lgc.c b/plugins/SmartAutoReplier/lualib/lgc.c
new file mode 100644
index 0000000000..4cc45e39d0
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lgc.c
@@ -0,0 +1,493 @@
+/*
+** $Id: lgc.c,v 1.171 2003/04/03 13:35:34 roberto Exp $
+** Garbage Collector
+** See Copyright Notice in lua.h
+*/
+
+#include <string.h>
+
+#define lgc_c
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+
+
+typedef struct GCState {
+ GCObject *tmark; /* list of marked objects to be traversed */
+ GCObject *wk; /* list of traversed key-weak tables (to be cleared) */
+ GCObject *wv; /* list of traversed value-weak tables */
+ GCObject *wkv; /* list of traversed key-value weak tables */
+ global_State *g;
+} GCState;
+
+
+/*
+** some userful bit tricks
+*/
+#define setbit(x,b) ((x) |= (1<<(b)))
+#define resetbit(x,b) ((x) &= cast(lu_byte, ~(1<<(b))))
+#define testbit(x,b) ((x) & (1<<(b)))
+
+#define unmark(x) resetbit((x)->gch.marked, 0)
+#define ismarked(x) ((x)->gch.marked & ((1<<4)|1))
+
+#define stringmark(s) setbit((s)->tsv.marked, 0)
+
+
+#define isfinalized(u) (!testbit((u)->uv.marked, 1))
+#define markfinalized(u) resetbit((u)->uv.marked, 1)
+
+
+#define KEYWEAKBIT 1
+#define VALUEWEAKBIT 2
+#define KEYWEAK (1<<KEYWEAKBIT)
+#define VALUEWEAK (1<<VALUEWEAKBIT)
+
+
+
+#define markobject(st,o) { checkconsistency(o); \
+ if (iscollectable(o) && !ismarked(gcvalue(o))) reallymarkobject(st,gcvalue(o)); }
+
+#define condmarkobject(st,o,c) { checkconsistency(o); \
+ if (iscollectable(o) && !ismarked(gcvalue(o)) && (c)) \
+ reallymarkobject(st,gcvalue(o)); }
+
+#define markvalue(st,t) { if (!ismarked(valtogco(t))) \
+ reallymarkobject(st, valtogco(t)); }
+
+
+
+static void reallymarkobject (GCState *st, GCObject *o) {
+ lua_assert(!ismarked(o));
+ setbit(o->gch.marked, 0); /* mark object */
+ switch (o->gch.tt) {
+ case LUA_TUSERDATA: {
+ markvalue(st, gcotou(o)->uv.metatable);
+ break;
+ }
+ case LUA_TFUNCTION: {
+ gcotocl(o)->c.gclist = st->tmark;
+ st->tmark = o;
+ break;
+ }
+ case LUA_TTABLE: {
+ gcotoh(o)->gclist = st->tmark;
+ st->tmark = o;
+ break;
+ }
+ case LUA_TTHREAD: {
+ gcototh(o)->gclist = st->tmark;
+ st->tmark = o;
+ break;
+ }
+ case LUA_TPROTO: {
+ gcotop(o)->gclist = st->tmark;
+ st->tmark = o;
+ break;
+ }
+ default: lua_assert(o->gch.tt == LUA_TSTRING);
+ }
+}
+
+
+static void marktmu (GCState *st) {
+ GCObject *u;
+ for (u = st->g->tmudata; u; u = u->gch.next) {
+ unmark(u); /* may be marked, if left from previous GC */
+ reallymarkobject(st, u);
+ }
+}
+
+
+/* move `dead' udata that need finalization to list `tmudata' */
+void luaC_separateudata (lua_State *L) {
+ GCObject **p = &G(L)->rootudata;
+ GCObject *curr;
+ GCObject *collected = NULL; /* to collect udata with gc event */
+ GCObject **lastcollected = &collected;
+ while ((curr = *p) != NULL) {
+ lua_assert(curr->gch.tt == LUA_TUSERDATA);
+ if (ismarked(curr) || isfinalized(gcotou(curr)))
+ p = &curr->gch.next; /* don't bother with them */
+
+ else if (fasttm(L, gcotou(curr)->uv.metatable, TM_GC) == NULL) {
+ markfinalized(gcotou(curr)); /* don't need finalization */
+ p = &curr->gch.next;
+ }
+ else { /* must call its gc method */
+ *p = curr->gch.next;
+ curr->gch.next = NULL; /* link `curr' at the end of `collected' list */
+ *lastcollected = curr;
+ lastcollected = &curr->gch.next;
+ }
+ }
+ /* insert collected udata with gc event into `tmudata' list */
+ *lastcollected = G(L)->tmudata;
+ G(L)->tmudata = collected;
+}
+
+
+static void removekey (Node *n) {
+ setnilvalue(gval(n)); /* remove corresponding value ... */
+ if (iscollectable(gkey(n)))
+ setttype(gkey(n), LUA_TNONE); /* dead key; remove it */
+}
+
+
+static void traversetable (GCState *st, Table *h) {
+ int i;
+ int weakkey = 0;
+ int weakvalue = 0;
+ const TObject *mode;
+ markvalue(st, h->metatable);
+ lua_assert(h->lsizenode || h->node == st->g->dummynode);
+ mode = gfasttm(st->g, h->metatable, TM_MODE);
+ if (mode && ttisstring(mode)) { /* is there a weak mode? */
+ weakkey = (strchr(svalue(mode), 'k') != NULL);
+ weakvalue = (strchr(svalue(mode), 'v') != NULL);
+ if (weakkey || weakvalue) { /* is really weak? */
+ GCObject **weaklist;
+ h->marked &= ~(KEYWEAK | VALUEWEAK); /* clear bits */
+ h->marked |= cast(lu_byte, (weakkey << KEYWEAKBIT) |
+ (weakvalue << VALUEWEAKBIT));
+ weaklist = (weakkey && weakvalue) ? &st->wkv :
+ (weakkey) ? &st->wk :
+ &st->wv;
+ h->gclist = *weaklist; /* must be cleared after GC, ... */
+ *weaklist = valtogco(h); /* ... so put in the appropriate list */
+ }
+ }
+ if (!weakvalue) {
+ i = h->sizearray;
+ while (i--)
+ markobject(st, &h->array[i]);
+ }
+ i = sizenode(h);
+ while (i--) {
+ Node *n = gnode(h, i);
+ if (!ttisnil(gval(n))) {
+ lua_assert(!ttisnil(gkey(n)));
+ condmarkobject(st, gkey(n), !weakkey);
+ condmarkobject(st, gval(n), !weakvalue);
+ }
+ }
+}
+
+
+static void traverseproto (GCState *st, Proto *f) {
+ int i;
+ stringmark(f->source);
+ for (i=0; i<f->sizek; i++) { /* mark literal strings */
+ if (ttisstring(f->k+i))
+ stringmark(tsvalue(f->k+i));
+ }
+ for (i=0; i<f->sizeupvalues; i++) /* mark upvalue names */
+ stringmark(f->upvalues[i]);
+ for (i=0; i<f->sizep; i++) /* mark nested protos */
+ markvalue(st, f->p[i]);
+ for (i=0; i<f->sizelocvars; i++) /* mark local-variable names */
+ stringmark(f->locvars[i].varname);
+ lua_assert(luaG_checkcode(f));
+}
+
+
+
+static void traverseclosure (GCState *st, Closure *cl) {
+ if (cl->c.isC) {
+ int i;
+ for (i=0; i<cl->c.nupvalues; i++) /* mark its upvalues */
+ markobject(st, &cl->c.upvalue[i]);
+ }
+ else {
+ int i;
+ lua_assert(cl->l.nupvalues == cl->l.p->nups);
+ markvalue(st, hvalue(&cl->l.g));
+ markvalue(st, cl->l.p);
+ for (i=0; i<cl->l.nupvalues; i++) { /* mark its upvalues */
+ UpVal *u = cl->l.upvals[i];
+ if (!u->marked) {
+ markobject(st, &u->value);
+ u->marked = 1;
+ }
+ }
+ }
+}
+
+
+static void checkstacksizes (lua_State *L, StkId max) {
+ int used = L->ci - L->base_ci; /* number of `ci' in use */
+ if (4*used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci)
+ luaD_reallocCI(L, L->size_ci/2); /* still big enough... */
+ else condhardstacktests(luaD_reallocCI(L, L->size_ci));
+ used = max - L->stack; /* part of stack in use */
+ if (4*used < L->stacksize && 2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize)
+ luaD_reallocstack(L, L->stacksize/2); /* still big enough... */
+ else condhardstacktests(luaD_reallocstack(L, L->stacksize));
+}
+
+
+static void traversestack (GCState *st, lua_State *L1) {
+ StkId o, lim;
+ CallInfo *ci;
+ markobject(st, gt(L1));
+ lim = L1->top;
+ for (ci = L1->base_ci; ci <= L1->ci; ci++) {
+ lua_assert(ci->top <= L1->stack_last);
+ lua_assert(ci->state & (CI_C | CI_HASFRAME | CI_SAVEDPC));
+ if (!(ci->state & CI_C) && lim < ci->top)
+ lim = ci->top;
+ }
+ for (o = L1->stack; o < L1->top; o++)
+ markobject(st, o);
+ for (; o <= lim; o++)
+ setnilvalue(o);
+ checkstacksizes(L1, lim);
+}
+
+
+static void propagatemarks (GCState *st) {
+ while (st->tmark) { /* traverse marked objects */
+ switch (st->tmark->gch.tt) {
+ case LUA_TTABLE: {
+ Table *h = gcotoh(st->tmark);
+ st->tmark = h->gclist;
+ traversetable(st, h);
+ break;
+ }
+ case LUA_TFUNCTION: {
+ Closure *cl = gcotocl(st->tmark);
+ st->tmark = cl->c.gclist;
+ traverseclosure(st, cl);
+ break;
+ }
+ case LUA_TTHREAD: {
+ lua_State *th = gcototh(st->tmark);
+ st->tmark = th->gclist;
+ traversestack(st, th);
+ break;
+ }
+ case LUA_TPROTO: {
+ Proto *p = gcotop(st->tmark);
+ st->tmark = p->gclist;
+ traverseproto(st, p);
+ break;
+ }
+ default: lua_assert(0);
+ }
+ }
+}
+
+
+static int valismarked (const TObject *o) {
+ if (ttisstring(o))
+ stringmark(tsvalue(o)); /* strings are `values', so are never weak */
+ return !iscollectable(o) || testbit(o->value.gc->gch.marked, 0);
+}
+
+
+/*
+** clear collected keys from weaktables
+*/
+static void cleartablekeys (GCObject *l) {
+ while (l) {
+ Table *h = gcotoh(l);
+ int i = sizenode(h);
+ lua_assert(h->marked & KEYWEAK);
+ while (i--) {
+ Node *n = gnode(h, i);
+ if (!valismarked(gkey(n))) /* key was collected? */
+ removekey(n); /* remove entry from table */
+ }
+ l = h->gclist;
+ }
+}
+
+
+/*
+** clear collected values from weaktables
+*/
+static void cleartablevalues (GCObject *l) {
+ while (l) {
+ Table *h = gcotoh(l);
+ int i = h->sizearray;
+ lua_assert(h->marked & VALUEWEAK);
+ while (i--) {
+ TObject *o = &h->array[i];
+ if (!valismarked(o)) /* value was collected? */
+ setnilvalue(o); /* remove value */
+ }
+ i = sizenode(h);
+ while (i--) {
+ Node *n = gnode(h, i);
+ if (!valismarked(gval(n))) /* value was collected? */
+ removekey(n); /* remove entry from table */
+ }
+ l = h->gclist;
+ }
+}
+
+
+static void freeobj (lua_State *L, GCObject *o) {
+ switch (o->gch.tt) {
+ case LUA_TPROTO: luaF_freeproto(L, gcotop(o)); break;
+ case LUA_TFUNCTION: luaF_freeclosure(L, gcotocl(o)); break;
+ case LUA_TUPVAL: luaM_freelem(L, gcotouv(o)); break;
+ case LUA_TTABLE: luaH_free(L, gcotoh(o)); break;
+ case LUA_TTHREAD: {
+ lua_assert(gcototh(o) != L && gcototh(o) != G(L)->mainthread);
+ luaE_freethread(L, gcototh(o));
+ break;
+ }
+ case LUA_TSTRING: {
+ luaM_free(L, o, sizestring(gcotots(o)->tsv.len));
+ break;
+ }
+ case LUA_TUSERDATA: {
+ luaM_free(L, o, sizeudata(gcotou(o)->uv.len));
+ break;
+ }
+ default: lua_assert(0);
+ }
+}
+
+
+static int sweeplist (lua_State *L, GCObject **p, int limit) {
+ GCObject *curr;
+ int count = 0; /* number of collected items */
+ while ((curr = *p) != NULL) {
+ if (curr->gch.marked > limit) {
+ unmark(curr);
+ p = &curr->gch.next;
+ }
+ else {
+ count++;
+ *p = curr->gch.next;
+ freeobj(L, curr);
+ }
+ }
+ return count;
+}
+
+
+static void sweepstrings (lua_State *L, int all) {
+ int i;
+ for (i=0; i<G(L)->strt.size; i++) { /* for each list */
+ G(L)->strt.nuse -= sweeplist(L, &G(L)->strt.hash[i], all);
+ }
+}
+
+
+static void checkSizes (lua_State *L) {
+ /* check size of string hash */
+ if (G(L)->strt.nuse < cast(ls_nstr, G(L)->strt.size/4) &&
+ G(L)->strt.size > MINSTRTABSIZE*2)
+ luaS_resize(L, G(L)->strt.size/2); /* table is too big */
+ /* check size of buffer */
+ if (luaZ_sizebuffer(&G(L)->buff) > LUA_MINBUFFER*2) { /* buffer too big? */
+ size_t newsize = luaZ_sizebuffer(&G(L)->buff) / 2;
+ luaZ_resizebuffer(L, &G(L)->buff, newsize);
+ }
+ G(L)->GCthreshold = 2*G(L)->nblocks; /* new threshold */
+}
+
+
+static void do1gcTM (lua_State *L, Udata *udata) {
+ const TObject *tm = fasttm(L, udata->uv.metatable, TM_GC);
+ if (tm != NULL) {
+ setobj2s(L->top, tm);
+ setuvalue(L->top+1, udata);
+ L->top += 2;
+ luaD_call(L, L->top - 2, 0);
+ }
+}
+
+
+void luaC_callGCTM (lua_State *L) {
+ lu_byte oldah = L->allowhook;
+ L->allowhook = 0; /* stop debug hooks during GC tag methods */
+ L->top++; /* reserve space to keep udata while runs its gc method */
+ while (G(L)->tmudata != NULL) {
+ GCObject *o = G(L)->tmudata;
+ Udata *udata = gcotou(o);
+ G(L)->tmudata = udata->uv.next; /* remove udata from `tmudata' */
+ udata->uv.next = G(L)->rootudata; /* return it to `root' list */
+ G(L)->rootudata = o;
+ setuvalue(L->top - 1, udata); /* keep a reference to it */
+ unmark(o);
+ markfinalized(udata);
+ do1gcTM(L, udata);
+ }
+ L->top--;
+ L->allowhook = oldah; /* restore hooks */
+}
+
+
+void luaC_sweep (lua_State *L, int all) {
+ if (all) all = 256; /* larger than any mark */
+ sweeplist(L, &G(L)->rootudata, all);
+ sweepstrings(L, all);
+ sweeplist(L, &G(L)->rootgc, all);
+}
+
+
+/* mark root set */
+static void markroot (GCState *st, lua_State *L) {
+ global_State *g = st->g;
+ markobject(st, defaultmeta(L));
+ markobject(st, registry(L));
+ traversestack(st, g->mainthread);
+ if (L != g->mainthread) /* another thread is running? */
+ markvalue(st, L); /* cannot collect it */
+}
+
+
+static void mark (lua_State *L) {
+ GCState st;
+ GCObject *wkv;
+ st.g = G(L);
+ st.tmark = NULL;
+ st.wkv = st.wk = st.wv = NULL;
+ markroot(&st, L);
+ propagatemarks(&st); /* mark all reachable objects */
+ cleartablevalues(st.wkv);
+ cleartablevalues(st.wv);
+ wkv = st.wkv; /* keys must be cleared after preserving udata */
+ st.wkv = NULL;
+ st.wv = NULL;
+ luaC_separateudata(L); /* separate userdata to be preserved */
+ marktmu(&st); /* mark `preserved' userdata */
+ propagatemarks(&st); /* remark, to propagate `preserveness' */
+ cleartablekeys(wkv);
+ /* `propagatemarks' may resuscitate some weak tables; clear them too */
+ cleartablekeys(st.wk);
+ cleartablevalues(st.wv);
+ cleartablekeys(st.wkv);
+ cleartablevalues(st.wkv);
+}
+
+
+void luaC_collectgarbage (lua_State *L) {
+ mark(L);
+ luaC_sweep(L, 0);
+ checkSizes(L);
+ luaC_callGCTM(L);
+}
+
+
+void luaC_link (lua_State *L, GCObject *o, lu_byte tt) {
+ o->gch.next = G(L)->rootgc;
+ G(L)->rootgc = o;
+ o->gch.marked = 0;
+ o->gch.tt = tt;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lgc.h b/plugins/SmartAutoReplier/lualib/lgc.h
new file mode 100644
index 0000000000..6ab6c91749
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lgc.h
@@ -0,0 +1,25 @@
+/*
+** $Id: lgc.h,v 1.19 2003/02/28 19:45:15 roberto Exp $
+** Garbage Collector
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lgc_h
+#define lgc_h
+
+
+#include "lobject.h"
+
+
+#define luaC_checkGC(L) { lua_assert(!(L->ci->state & CI_CALLING)); \
+ if (G(L)->nblocks >= G(L)->GCthreshold) luaC_collectgarbage(L); }
+
+
+void luaC_separateudata (lua_State *L);
+void luaC_callGCTM (lua_State *L);
+void luaC_sweep (lua_State *L, int all);
+void luaC_collectgarbage (lua_State *L);
+void luaC_link (lua_State *L, GCObject *o, lu_byte tt);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/liolib.c b/plugins/SmartAutoReplier/lualib/liolib.c
new file mode 100644
index 0000000000..14bd7d9909
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/liolib.c
@@ -0,0 +1,750 @@
+/*
+** $Id: liolib.c,v 2.39 2003/03/19 21:16:12 roberto Exp $
+** Standard I/O (and system) library
+** See Copyright Notice in lua.h
+*/
+
+
+#include <errno.h>
+#include <locale.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#define liolib_c
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+
+/*
+** by default, gcc does not get `tmpname'
+*/
+#ifndef USE_TMPNAME
+#ifdef __GNUC__
+#define USE_TMPNAME 0
+#else
+#define USE_TMPNAME 1
+#endif
+#endif
+
+
+/*
+** by default, posix systems get `popen'
+*/
+#ifndef USE_POPEN
+#ifdef _POSIX_C_SOURCE
+#if _POSIX_C_SOURCE >= 2
+#define USE_POPEN 1
+#endif
+#endif
+#endif
+
+#ifndef USE_POPEN
+#define USE_POPEN 0
+#endif
+
+
+
+
+/*
+** {======================================================
+** FILE Operations
+** =======================================================
+*/
+
+
+#if !USE_POPEN
+#define pclose(f) (-1)
+#endif
+
+
+#define FILEHANDLE "FILE*"
+
+#define IO_INPUT "_input"
+#define IO_OUTPUT "_output"
+
+
+static int pushresult (lua_State *L, int i, const char *filename) {
+ if (i) {
+ lua_pushboolean(L, 1);
+ return 1;
+ }
+ else {
+ lua_pushnil(L);
+ if (filename)
+ lua_pushfstring(L, "%s: %s", filename, strerror(errno));
+ else
+ lua_pushfstring(L, "%s", strerror(errno));
+ lua_pushnumber(L, errno);
+ return 3;
+ }
+}
+
+
+static FILE **topfile (lua_State *L, int findex) {
+ FILE **f = (FILE **)luaL_checkudata(L, findex, FILEHANDLE);
+ if (f == NULL) luaL_argerror(L, findex, "bad file");
+ return f;
+}
+
+
+static int io_type (lua_State *L) {
+ FILE **f = (FILE **)luaL_checkudata(L, 1, FILEHANDLE);
+ if (f == NULL) lua_pushnil(L);
+ else if (*f == NULL)
+ lua_pushliteral(L, "closed file");
+ else
+ lua_pushliteral(L, "file");
+ return 1;
+}
+
+
+static FILE *tofile (lua_State *L, int findex) {
+ FILE **f = topfile(L, findex);
+ if (*f == NULL)
+ luaL_error(L, "attempt to use a closed file");
+ return *f;
+}
+
+
+
+/*
+** When creating file handles, always creates a `closed' file handle
+** before opening the actual file; so, if there is a memory error, the
+** file is not left opened.
+*/
+static FILE **newfile (lua_State *L) {
+ FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
+ *pf = NULL; /* file handle is currently `closed' */
+ luaL_getmetatable(L, FILEHANDLE);
+ lua_setmetatable(L, -2);
+ return pf;
+}
+
+
+/*
+** assumes that top of the stack is the `io' library, and next is
+** the `io' metatable
+*/
+static void registerfile (lua_State *L, FILE *f, const char *name,
+ const char *impname) {
+ lua_pushstring(L, name);
+ *newfile(L) = f;
+ if (impname) {
+ lua_pushstring(L, impname);
+ lua_pushvalue(L, -2);
+ lua_settable(L, -6); /* metatable[impname] = file */
+ }
+ lua_settable(L, -3); /* io[name] = file */
+}
+
+
+static int aux_close (lua_State *L) {
+ FILE *f = tofile(L, 1);
+ if (f == stdin || f == stdout || f == stderr)
+ return 0; /* file cannot be closed */
+ else {
+ int ok = (pclose(f) != -1) || (fclose(f) == 0);
+ if (ok)
+ *(FILE **)lua_touserdata(L, 1) = NULL; /* mark file as closed */
+ return ok;
+ }
+}
+
+
+static int io_close (lua_State *L) {
+ if (lua_isnone(L, 1)) {
+ lua_pushstring(L, IO_OUTPUT);
+ lua_rawget(L, lua_upvalueindex(1));
+ }
+ return pushresult(L, aux_close(L), NULL);
+}
+
+
+static int io_gc (lua_State *L) {
+ FILE **f = topfile(L, 1);
+ if (*f != NULL) /* ignore closed files */
+ aux_close(L);
+ return 0;
+}
+
+
+static int io_tostring (lua_State *L) {
+ char buff[32];
+ FILE **f = topfile(L, 1);
+ if (*f == NULL)
+ strcpy(buff, "closed");
+ else
+ sprintf(buff, "%p", lua_touserdata(L, 1));
+ lua_pushfstring(L, "file (%s)", buff);
+ return 1;
+}
+
+
+static int io_open (lua_State *L) {
+ const char *filename = luaL_checkstring(L, 1);
+ const char *mode = luaL_optstring(L, 2, "r");
+ FILE **pf = newfile(L);
+ *pf = fopen(filename, mode);
+ return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
+}
+
+
+static int io_popen (lua_State *L) {
+#if !USE_POPEN
+ luaL_error(L, "`popen' not supported");
+ return 0;
+#else
+ const char *filename = luaL_checkstring(L, 1);
+ const char *mode = luaL_optstring(L, 2, "r");
+ FILE **pf = newfile(L);
+ *pf = popen(filename, mode);
+ return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
+#endif
+}
+
+
+static int io_tmpfile (lua_State *L) {
+ FILE **pf = newfile(L);
+ *pf = tmpfile();
+ return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
+}
+
+
+static FILE *getiofile (lua_State *L, const char *name) {
+ lua_pushstring(L, name);
+ lua_rawget(L, lua_upvalueindex(1));
+ return tofile(L, -1);
+}
+
+
+static int g_iofile (lua_State *L, const char *name, const char *mode) {
+ if (!lua_isnoneornil(L, 1)) {
+ const char *filename = lua_tostring(L, 1);
+ lua_pushstring(L, name);
+ if (filename) {
+ FILE **pf = newfile(L);
+ *pf = fopen(filename, mode);
+ if (*pf == NULL) {
+ lua_pushfstring(L, "%s: %s", filename, strerror(errno));
+ luaL_argerror(L, 1, lua_tostring(L, -1));
+ }
+ }
+ else {
+ tofile(L, 1); /* check that it's a valid file handle */
+ lua_pushvalue(L, 1);
+ }
+ lua_rawset(L, lua_upvalueindex(1));
+ }
+ /* return current value */
+ lua_pushstring(L, name);
+ lua_rawget(L, lua_upvalueindex(1));
+ return 1;
+}
+
+
+static int io_input (lua_State *L) {
+ return g_iofile(L, IO_INPUT, "r");
+}
+
+
+static int io_output (lua_State *L) {
+ return g_iofile(L, IO_OUTPUT, "w");
+}
+
+
+static int io_readline (lua_State *L);
+
+
+static void aux_lines (lua_State *L, int idx, int close) {
+ lua_pushliteral(L, FILEHANDLE);
+ lua_rawget(L, LUA_REGISTRYINDEX);
+ lua_pushvalue(L, idx);
+ lua_pushboolean(L, close); /* close/not close file when finished */
+ lua_pushcclosure(L, io_readline, 3);
+}
+
+
+static int f_lines (lua_State *L) {
+ tofile(L, 1); /* check that it's a valid file handle */
+ aux_lines(L, 1, 0);
+ return 1;
+}
+
+
+static int io_lines (lua_State *L) {
+ if (lua_isnoneornil(L, 1)) { /* no arguments? */
+ lua_pushstring(L, IO_INPUT);
+ lua_rawget(L, lua_upvalueindex(1)); /* will iterate over default input */
+ return f_lines(L);
+ }
+ else {
+ const char *filename = luaL_checkstring(L, 1);
+ FILE **pf = newfile(L);
+ *pf = fopen(filename, "r");
+ luaL_argcheck(L, *pf, 1, strerror(errno));
+ aux_lines(L, lua_gettop(L), 1);
+ return 1;
+ }
+}
+
+
+/*
+** {======================================================
+** READ
+** =======================================================
+*/
+
+
+static int read_number (lua_State *L, FILE *f) {
+ lua_Number d;
+ if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
+ lua_pushnumber(L, d);
+ return 1;
+ }
+ else return 0; /* read fails */
+}
+
+
+static int test_eof (lua_State *L, FILE *f) {
+ int c = getc(f);
+ ungetc(c, f);
+ lua_pushlstring(L, NULL, 0);
+ return (c != EOF);
+}
+
+
+static int read_line (lua_State *L, FILE *f) {
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
+ for (;;) {
+ size_t l;
+ char *p = luaL_prepbuffer(&b);
+ if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
+ luaL_pushresult(&b); /* close buffer */
+ return (lua_strlen(L, -1) > 0); /* check whether read something */
+ }
+ l = strlen(p);
+ if (p[l-1] != '\n')
+ luaL_addsize(&b, l);
+ else {
+ luaL_addsize(&b, l - 1); /* do not include `eol' */
+ luaL_pushresult(&b); /* close buffer */
+ return 1; /* read at least an `eol' */
+ }
+ }
+}
+
+
+static int read_chars (lua_State *L, FILE *f, size_t n) {
+ size_t rlen; /* how much to read */
+ size_t nr; /* number of chars actually read */
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
+ rlen = LUAL_BUFFERSIZE; /* try to read that much each time */
+ do {
+ char *p = luaL_prepbuffer(&b);
+ if (rlen > n) rlen = n; /* cannot read more than asked */
+ nr = fread(p, sizeof(char), rlen, f);
+ luaL_addsize(&b, nr);
+ n -= nr; /* still have to read `n' chars */
+ } while (n > 0 && nr == rlen); /* until end of count or eof */
+ luaL_pushresult(&b); /* close buffer */
+ return (n == 0 || lua_strlen(L, -1) > 0);
+}
+
+
+static int g_read (lua_State *L, FILE *f, int first) {
+ int nargs = lua_gettop(L) - 1;
+ int success;
+ int n;
+ if (nargs == 0) { /* no arguments? */
+ success = read_line(L, f);
+ n = first+1; /* to return 1 result */
+ }
+ else { /* ensure stack space for all results and for auxlib's buffer */
+ luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
+ success = 1;
+ for (n = first; nargs-- && success; n++) {
+ if (lua_type(L, n) == LUA_TNUMBER) {
+ size_t l = (size_t)lua_tonumber(L, n);
+ success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
+ }
+ else {
+ const char *p = lua_tostring(L, n);
+ luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
+ switch (p[1]) {
+ case 'n': /* number */
+ success = read_number(L, f);
+ break;
+ case 'l': /* line */
+ success = read_line(L, f);
+ break;
+ case 'a': /* file */
+ read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
+ success = 1; /* always success */
+ break;
+ case 'w': /* word */
+ return luaL_error(L, "obsolete option `*w' to `read'");
+ default:
+ return luaL_argerror(L, n, "invalid format");
+ }
+ }
+ }
+ }
+ if (!success) {
+ lua_pop(L, 1); /* remove last result */
+ lua_pushnil(L); /* push nil instead */
+ }
+ return n - first;
+}
+
+
+static int io_read (lua_State *L) {
+ return g_read(L, getiofile(L, IO_INPUT), 1);
+}
+
+
+static int f_read (lua_State *L) {
+ return g_read(L, tofile(L, 1), 2);
+}
+
+
+static int io_readline (lua_State *L) {
+ FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(2));
+ if (f == NULL) /* file is already closed? */
+ luaL_error(L, "file is already closed");
+ if (read_line(L, f)) return 1;
+ else { /* EOF */
+ if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
+ lua_settop(L, 0);
+ lua_pushvalue(L, lua_upvalueindex(2));
+ aux_close(L); /* close it */
+ }
+ return 0;
+ }
+}
+
+/* }====================================================== */
+
+
+static int g_write (lua_State *L, FILE *f, int arg) {
+ int nargs = lua_gettop(L) - 1;
+ int status = 1;
+ for (; nargs--; arg++) {
+ if (lua_type(L, arg) == LUA_TNUMBER) {
+ /* optimization: could be done exactly as for strings */
+ status = status &&
+ fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
+ }
+ else {
+ size_t l;
+ const char *s = luaL_checklstring(L, arg, &l);
+ status = status && (fwrite(s, sizeof(char), l, f) == l);
+ }
+ }
+ return pushresult(L, status, NULL);
+}
+
+
+static int io_write (lua_State *L) {
+ return g_write(L, getiofile(L, IO_OUTPUT), 1);
+}
+
+
+static int f_write (lua_State *L) {
+ return g_write(L, tofile(L, 1), 2);
+}
+
+
+static int f_seek (lua_State *L) {
+ static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
+ static const char *const modenames[] = {"set", "cur", "end", NULL};
+ FILE *f = tofile(L, 1);
+ int op = luaL_findstring(luaL_optstring(L, 2, "cur"), modenames);
+ long offset = luaL_optlong(L, 3, 0);
+ luaL_argcheck(L, op != -1, 2, "invalid mode");
+ op = fseek(f, offset, mode[op]);
+ if (op)
+ return pushresult(L, 0, NULL); /* error */
+ else {
+ lua_pushnumber(L, ftell(f));
+ return 1;
+ }
+}
+
+
+static int io_flush (lua_State *L) {
+ return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
+}
+
+
+static int f_flush (lua_State *L) {
+ return pushresult(L, fflush(tofile(L, 1)) == 0, NULL);
+}
+
+
+static const luaL_reg iolib[] = {
+ {"input", io_input},
+ {"output", io_output},
+ {"lines", io_lines},
+ {"close", io_close},
+ {"flush", io_flush},
+ {"open", io_open},
+ {"popen", io_popen},
+ {"read", io_read},
+ {"tmpfile", io_tmpfile},
+ {"type", io_type},
+ {"write", io_write},
+ {NULL, NULL}
+};
+
+
+static const luaL_reg flib[] = {
+ {"flush", f_flush},
+ {"read", f_read},
+ {"lines", f_lines},
+ {"seek", f_seek},
+ {"write", f_write},
+ {"close", io_close},
+ {"__gc", io_gc},
+ {"__tostring", io_tostring},
+ {NULL, NULL}
+};
+
+
+static void createmeta (lua_State *L) {
+ luaL_newmetatable(L, FILEHANDLE); /* create new metatable for file handles */
+ /* file methods */
+ lua_pushliteral(L, "__index");
+ lua_pushvalue(L, -2); /* push metatable */
+ lua_rawset(L, -3); /* metatable.__index = metatable */
+ luaL_openlib(L, NULL, flib, 0);
+}
+
+/* }====================================================== */
+
+
+/*
+** {======================================================
+** Other O.S. Operations
+** =======================================================
+*/
+
+static int io_execute (lua_State *L) {
+ lua_pushnumber(L, system(luaL_checkstring(L, 1)));
+ return 1;
+}
+
+
+static int io_remove (lua_State *L) {
+ const char *filename = luaL_checkstring(L, 1);
+ return pushresult(L, remove(filename) == 0, filename);
+}
+
+
+static int io_rename (lua_State *L) {
+ const char *fromname = luaL_checkstring(L, 1);
+ const char *toname = luaL_checkstring(L, 2);
+ return pushresult(L, rename(fromname, toname) == 0, fromname);
+}
+
+
+static int io_tmpname (lua_State *L) {
+#if !USE_TMPNAME
+ luaL_error(L, "`tmpname' not supported");
+ return 0;
+#else
+ char buff[L_tmpnam];
+ if (tmpnam(buff) != buff)
+ return luaL_error(L, "unable to generate a unique filename in `tmpname'");
+ lua_pushstring(L, buff);
+ return 1;
+#endif
+}
+
+
+static int io_getenv (lua_State *L) {
+ lua_pushstring(L, getenv(luaL_checkstring(L, 1))); /* if NULL push nil */
+ return 1;
+}
+
+
+static int io_clock (lua_State *L) {
+ lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
+ return 1;
+}
+
+
+/*
+** {======================================================
+** Time/Date operations
+** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
+** wday=%w+1, yday=%j, isdst=? }
+** =======================================================
+*/
+
+static void setfield (lua_State *L, const char *key, int value) {
+ lua_pushstring(L, key);
+ lua_pushnumber(L, value);
+ lua_rawset(L, -3);
+}
+
+static void setboolfield (lua_State *L, const char *key, int value) {
+ lua_pushstring(L, key);
+ lua_pushboolean(L, value);
+ lua_rawset(L, -3);
+}
+
+static int getboolfield (lua_State *L, const char *key) {
+ int res;
+ lua_pushstring(L, key);
+ lua_gettable(L, -2);
+ res = lua_toboolean(L, -1);
+ lua_pop(L, 1);
+ return res;
+}
+
+
+static int getfield (lua_State *L, const char *key, int d) {
+ int res;
+ lua_pushstring(L, key);
+ lua_gettable(L, -2);
+ if (lua_isnumber(L, -1))
+ res = (int)(lua_tonumber(L, -1));
+ else {
+ if (d == -2)
+ return luaL_error(L, "field `%s' missing in date table", key);
+ res = d;
+ }
+ lua_pop(L, 1);
+ return res;
+}
+
+
+static int io_date (lua_State *L) {
+ const char *s = luaL_optstring(L, 1, "%c");
+ time_t t = (time_t)(luaL_optnumber(L, 2, -1));
+ struct tm *stm;
+ if (t == (time_t)(-1)) /* no time given? */
+ t = time(NULL); /* use current time */
+ if (*s == '!') { /* UTC? */
+ stm = gmtime(&t);
+ s++; /* skip `!' */
+ }
+ else
+ stm = localtime(&t);
+ if (stm == NULL) /* invalid date? */
+ lua_pushnil(L);
+ else if (strcmp(s, "*t") == 0) {
+ lua_newtable(L);
+ setfield(L, "sec", stm->tm_sec);
+ setfield(L, "min", stm->tm_min);
+ setfield(L, "hour", stm->tm_hour);
+ setfield(L, "day", stm->tm_mday);
+ setfield(L, "month", stm->tm_mon+1);
+ setfield(L, "year", stm->tm_year+1900);
+ setfield(L, "wday", stm->tm_wday+1);
+ setfield(L, "yday", stm->tm_yday+1);
+ setboolfield(L, "isdst", stm->tm_isdst);
+ }
+ else {
+ char b[256];
+ if (strftime(b, sizeof(b), s, stm))
+ lua_pushstring(L, b);
+ else
+ return luaL_error(L, "`date' format too long");
+ }
+ return 1;
+}
+
+
+static int io_time (lua_State *L) {
+ if (lua_isnoneornil(L, 1)) /* called without args? */
+ lua_pushnumber(L, time(NULL)); /* return current time */
+ else {
+ time_t t;
+ struct tm ts;
+ luaL_checktype(L, 1, LUA_TTABLE);
+ lua_settop(L, 1); /* make sure table is at the top */
+ ts.tm_sec = getfield(L, "sec", 0);
+ ts.tm_min = getfield(L, "min", 0);
+ ts.tm_hour = getfield(L, "hour", 12);
+ ts.tm_mday = getfield(L, "day", -2);
+ ts.tm_mon = getfield(L, "month", -2) - 1;
+ ts.tm_year = getfield(L, "year", -2) - 1900;
+ ts.tm_isdst = getboolfield(L, "isdst");
+ t = mktime(&ts);
+ if (t == (time_t)(-1))
+ lua_pushnil(L);
+ else
+ lua_pushnumber(L, t);
+ }
+ return 1;
+}
+
+
+static int io_difftime (lua_State *L) {
+ lua_pushnumber(L, difftime((time_t)(luaL_checknumber(L, 1)),
+ (time_t)(luaL_optnumber(L, 2, 0))));
+ return 1;
+}
+
+/* }====================================================== */
+
+
+static int io_setloc (lua_State *L) {
+ static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
+ LC_NUMERIC, LC_TIME};
+ static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
+ "numeric", "time", NULL};
+ const char *l = lua_tostring(L, 1);
+ int op = luaL_findstring(luaL_optstring(L, 2, "all"), catnames);
+ luaL_argcheck(L, l || lua_isnoneornil(L, 1), 1, "string expected");
+ luaL_argcheck(L, op != -1, 2, "invalid option");
+ lua_pushstring(L, setlocale(cat[op], l));
+ return 1;
+}
+
+
+static int io_exit (lua_State *L) {
+ exit(luaL_optint(L, 1, EXIT_SUCCESS));
+ return 0; /* to avoid warnings */
+}
+
+static const luaL_reg syslib[] = {
+ {"clock", io_clock},
+ {"date", io_date},
+ {"difftime", io_difftime},
+ {"execute", io_execute},
+ {"exit", io_exit},
+ {"getenv", io_getenv},
+ {"remove", io_remove},
+ {"rename", io_rename},
+ {"setlocale", io_setloc},
+ {"time", io_time},
+ {"tmpname", io_tmpname},
+ {NULL, NULL}
+};
+
+/* }====================================================== */
+
+
+
+LUALIB_API int luaopen_io (lua_State *L) {
+ luaL_openlib(L, LUA_OSLIBNAME, syslib, 0);
+ createmeta(L);
+ lua_pushvalue(L, -1);
+ luaL_openlib(L, LUA_IOLIBNAME, iolib, 1);
+ /* put predefined file handles into `io' table */
+ registerfile(L, stdin, "stdin", IO_INPUT);
+ registerfile(L, stdout, "stdout", IO_OUTPUT);
+ registerfile(L, stderr, "stderr", NULL);
+ return 1;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/llex.c b/plugins/SmartAutoReplier/lualib/llex.c
new file mode 100644
index 0000000000..045e999443
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/llex.c
@@ -0,0 +1,417 @@
+/*
+** $Id: llex.c,v 1.119 2003/03/24 12:39:34 roberto Exp $
+** Lexical Analyzer
+** See Copyright Notice in lua.h
+*/
+
+
+#include <ctype.h>
+#include <string.h>
+
+#define llex_c
+
+#include "lua.h"
+
+#include "ldo.h"
+#include "llex.h"
+#include "lobject.h"
+#include "lparser.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "lzio.h"
+
+
+
+#define next(LS) (LS->current = zgetc(LS->z))
+
+
+
+/* ORDER RESERVED */
+static const char *const token2string [] = {
+ "and", "break", "do", "else", "elseif",
+ "end", "false", "for", "function", "if",
+ "in", "local", "nil", "not", "or", "repeat",
+ "return", "then", "true", "until", "while", "*name",
+ "..", "...", "==", ">=", "<=", "~=",
+ "*number", "*string", "<eof>"
+};
+
+
+void luaX_init (lua_State *L) {
+ int i;
+ for (i=0; i<NUM_RESERVED; i++) {
+ TString *ts = luaS_new(L, token2string[i]);
+ luaS_fix(ts); /* reserved words are never collected */
+ lua_assert(strlen(token2string[i])+1 <= TOKEN_LEN);
+ ts->tsv.reserved = cast(lu_byte, i+1); /* reserved word */
+ }
+}
+
+
+#define MAXSRC 80
+
+
+void luaX_checklimit (LexState *ls, int val, int limit, const char *msg) {
+ if (val > limit) {
+ msg = luaO_pushfstring(ls->L, "too many %s (limit=%d)", msg, limit);
+ luaX_syntaxerror(ls, msg);
+ }
+}
+
+
+void luaX_errorline (LexState *ls, const char *s, const char *token, int line) {
+ lua_State *L = ls->L;
+ char buff[MAXSRC];
+ luaO_chunkid(buff, getstr(ls->source), MAXSRC);
+ luaO_pushfstring(L, "%s:%d: %s near `%s'", buff, line, s, token);
+ luaD_throw(L, LUA_ERRSYNTAX);
+}
+
+
+static void luaX_error (LexState *ls, const char *s, const char *token) {
+ luaX_errorline(ls, s, token, ls->linenumber);
+}
+
+
+void luaX_syntaxerror (LexState *ls, const char *msg) {
+ const char *lasttoken;
+ switch (ls->t.token) {
+ case TK_NAME:
+ lasttoken = getstr(ls->t.seminfo.ts);
+ break;
+ case TK_STRING:
+ case TK_NUMBER:
+ lasttoken = luaZ_buffer(ls->buff);
+ break;
+ default:
+ lasttoken = luaX_token2str(ls, ls->t.token);
+ break;
+ }
+ luaX_error(ls, msg, lasttoken);
+}
+
+
+const char *luaX_token2str (LexState *ls, int token) {
+ if (token < FIRST_RESERVED) {
+ lua_assert(token == (unsigned char)token);
+ return luaO_pushfstring(ls->L, "%c", token);
+ }
+ else
+ return token2string[token-FIRST_RESERVED];
+}
+
+
+static void luaX_lexerror (LexState *ls, const char *s, int token) {
+ if (token == TK_EOS)
+ luaX_error(ls, s, luaX_token2str(ls, token));
+ else
+ luaX_error(ls, s, luaZ_buffer(ls->buff));
+}
+
+
+static void inclinenumber (LexState *LS) {
+ next(LS); /* skip `\n' */
+ ++LS->linenumber;
+ luaX_checklimit(LS, LS->linenumber, MAX_INT, "lines in a chunk");
+}
+
+
+void luaX_setinput (lua_State *L, LexState *LS, ZIO *z, TString *source) {
+ LS->L = L;
+ LS->lookahead.token = TK_EOS; /* no look-ahead token */
+ LS->z = z;
+ LS->fs = NULL;
+ LS->linenumber = 1;
+ LS->lastline = 1;
+ LS->source = source;
+ next(LS); /* read first char */
+ if (LS->current == '#') {
+ do { /* skip first line */
+ next(LS);
+ } while (LS->current != '\n' && LS->current != EOZ);
+ }
+}
+
+
+
+/*
+** =======================================================
+** LEXICAL ANALYZER
+** =======================================================
+*/
+
+
+/* use buffer to store names, literal strings and numbers */
+
+/* extra space to allocate when growing buffer */
+#define EXTRABUFF 32
+
+/* maximum number of chars that can be read without checking buffer size */
+#define MAXNOCHECK 5
+
+#define checkbuffer(LS, len) \
+ if (((len)+MAXNOCHECK)*sizeof(char) > luaZ_sizebuffer((LS)->buff)) \
+ luaZ_openspace((LS)->L, (LS)->buff, (len)+EXTRABUFF)
+
+#define save(LS, c, l) \
+ (luaZ_buffer((LS)->buff)[l++] = cast(char, c))
+#define save_and_next(LS, l) (save(LS, LS->current, l), next(LS))
+
+
+static size_t readname (LexState *LS) {
+ size_t l = 0;
+ checkbuffer(LS, l);
+ do {
+ checkbuffer(LS, l);
+ save_and_next(LS, l);
+ } while (isalnum(LS->current) || LS->current == '_');
+ save(LS, '\0', l);
+ return l-1;
+}
+
+
+/* LUA_NUMBER */
+static void read_numeral (LexState *LS, int comma, SemInfo *seminfo) {
+ size_t l = 0;
+ checkbuffer(LS, l);
+ if (comma) save(LS, '.', l);
+ while (isdigit(LS->current)) {
+ checkbuffer(LS, l);
+ save_and_next(LS, l);
+ }
+ if (LS->current == '.') {
+ save_and_next(LS, l);
+ if (LS->current == '.') {
+ save_and_next(LS, l);
+ save(LS, '\0', l);
+ luaX_lexerror(LS,
+ "ambiguous syntax (decimal point x string concatenation)",
+ TK_NUMBER);
+ }
+ }
+ while (isdigit(LS->current)) {
+ checkbuffer(LS, l);
+ save_and_next(LS, l);
+ }
+ if (LS->current == 'e' || LS->current == 'E') {
+ save_and_next(LS, l); /* read `E' */
+ if (LS->current == '+' || LS->current == '-')
+ save_and_next(LS, l); /* optional exponent sign */
+ while (isdigit(LS->current)) {
+ checkbuffer(LS, l);
+ save_and_next(LS, l);
+ }
+ }
+ save(LS, '\0', l);
+ if (!luaO_str2d(luaZ_buffer(LS->buff), &seminfo->r))
+ luaX_lexerror(LS, "malformed number", TK_NUMBER);
+}
+
+
+static void read_long_string (LexState *LS, SemInfo *seminfo) {
+ int cont = 0;
+ size_t l = 0;
+ checkbuffer(LS, l);
+ save(LS, '[', l); /* save first `[' */
+ save_and_next(LS, l); /* pass the second `[' */
+ if (LS->current == '\n') /* string starts with a newline? */
+ inclinenumber(LS); /* skip it */
+ for (;;) {
+ checkbuffer(LS, l);
+ switch (LS->current) {
+ case EOZ:
+ save(LS, '\0', l);
+ luaX_lexerror(LS, (seminfo) ? "unfinished long string" :
+ "unfinished long comment", TK_EOS);
+ break; /* to avoid warnings */
+ case '[':
+ save_and_next(LS, l);
+ if (LS->current == '[') {
+ cont++;
+ save_and_next(LS, l);
+ }
+ continue;
+ case ']':
+ save_and_next(LS, l);
+ if (LS->current == ']') {
+ if (cont == 0) goto endloop;
+ cont--;
+ save_and_next(LS, l);
+ }
+ continue;
+ case '\n':
+ save(LS, '\n', l);
+ inclinenumber(LS);
+ if (!seminfo) l = 0; /* reset buffer to avoid wasting space */
+ continue;
+ default:
+ save_and_next(LS, l);
+ }
+ } endloop:
+ save_and_next(LS, l); /* skip the second `]' */
+ save(LS, '\0', l);
+ if (seminfo)
+ seminfo->ts = luaS_newlstr(LS->L, luaZ_buffer(LS->buff) + 2, l - 5);
+}
+
+
+static void read_string (LexState *LS, int del, SemInfo *seminfo) {
+ size_t l = 0;
+ checkbuffer(LS, l);
+ save_and_next(LS, l);
+ while (LS->current != del) {
+ checkbuffer(LS, l);
+ switch (LS->current) {
+ case EOZ:
+ save(LS, '\0', l);
+ luaX_lexerror(LS, "unfinished string", TK_EOS);
+ break; /* to avoid warnings */
+ case '\n':
+ save(LS, '\0', l);
+ luaX_lexerror(LS, "unfinished string", TK_STRING);
+ break; /* to avoid warnings */
+ case '\\':
+ next(LS); /* do not save the `\' */
+ switch (LS->current) {
+ case 'a': save(LS, '\a', l); next(LS); break;
+ case 'b': save(LS, '\b', l); next(LS); break;
+ case 'f': save(LS, '\f', l); next(LS); break;
+ case 'n': save(LS, '\n', l); next(LS); break;
+ case 'r': save(LS, '\r', l); next(LS); break;
+ case 't': save(LS, '\t', l); next(LS); break;
+ case 'v': save(LS, '\v', l); next(LS); break;
+ case '\n': save(LS, '\n', l); inclinenumber(LS); break;
+ case EOZ: break; /* will raise an error next loop */
+ default: {
+ if (!isdigit(LS->current))
+ save_and_next(LS, l); /* handles \\, \", \', and \? */
+ else { /* \xxx */
+ int c = 0;
+ int i = 0;
+ do {
+ c = 10*c + (LS->current-'0');
+ next(LS);
+ } while (++i<3 && isdigit(LS->current));
+ if (c > UCHAR_MAX) {
+ save(LS, '\0', l);
+ luaX_lexerror(LS, "escape sequence too large", TK_STRING);
+ }
+ save(LS, c, l);
+ }
+ }
+ }
+ break;
+ default:
+ save_and_next(LS, l);
+ }
+ }
+ save_and_next(LS, l); /* skip delimiter */
+ save(LS, '\0', l);
+ seminfo->ts = luaS_newlstr(LS->L, luaZ_buffer(LS->buff) + 1, l - 3);
+}
+
+
+int luaX_lex (LexState *LS, SemInfo *seminfo) {
+ for (;;) {
+ switch (LS->current) {
+
+ case '\n': {
+ inclinenumber(LS);
+ continue;
+ }
+ case '-': {
+ next(LS);
+ if (LS->current != '-') return '-';
+ /* else is a comment */
+ next(LS);
+ if (LS->current == '[' && (next(LS), LS->current == '['))
+ read_long_string(LS, NULL); /* long comment */
+ else /* short comment */
+ while (LS->current != '\n' && LS->current != EOZ)
+ next(LS);
+ continue;
+ }
+ case '[': {
+ next(LS);
+ if (LS->current != '[') return '[';
+ else {
+ read_long_string(LS, seminfo);
+ return TK_STRING;
+ }
+ }
+ case '=': {
+ next(LS);
+ if (LS->current != '=') return '=';
+ else { next(LS); return TK_EQ; }
+ }
+ case '<': {
+ next(LS);
+ if (LS->current != '=') return '<';
+ else { next(LS); return TK_LE; }
+ }
+ case '>': {
+ next(LS);
+ if (LS->current != '=') return '>';
+ else { next(LS); return TK_GE; }
+ }
+ case '~': {
+ next(LS);
+ if (LS->current != '=') return '~';
+ else { next(LS); return TK_NE; }
+ }
+ case '"':
+ case '\'': {
+ read_string(LS, LS->current, seminfo);
+ return TK_STRING;
+ }
+ case '.': {
+ next(LS);
+ if (LS->current == '.') {
+ next(LS);
+ if (LS->current == '.') {
+ next(LS);
+ return TK_DOTS; /* ... */
+ }
+ else return TK_CONCAT; /* .. */
+ }
+ else if (!isdigit(LS->current)) return '.';
+ else {
+ read_numeral(LS, 1, seminfo);
+ return TK_NUMBER;
+ }
+ }
+ case EOZ: {
+ return TK_EOS;
+ }
+ default: {
+ if (isspace(LS->current)) {
+ next(LS);
+ continue;
+ }
+ else if (isdigit(LS->current)) {
+ read_numeral(LS, 0, seminfo);
+ return TK_NUMBER;
+ }
+ else if (isalpha(LS->current) || LS->current == '_') {
+ /* identifier or reserved word */
+ size_t l = readname(LS);
+ TString *ts = luaS_newlstr(LS->L, luaZ_buffer(LS->buff), l);
+ if (ts->tsv.reserved > 0) /* reserved word? */
+ return ts->tsv.reserved - 1 + FIRST_RESERVED;
+ seminfo->ts = ts;
+ return TK_NAME;
+ }
+ else {
+ int c = LS->current;
+ if (iscntrl(c))
+ luaX_error(LS, "invalid control char",
+ luaO_pushfstring(LS->L, "char(%d)", c));
+ next(LS);
+ return c; /* single-char tokens (+ - / ...) */
+ }
+ }
+ }
+ }
+}
+
+#undef next
diff --git a/plugins/SmartAutoReplier/lualib/llex.h b/plugins/SmartAutoReplier/lualib/llex.h
new file mode 100644
index 0000000000..740e3f6b31
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/llex.h
@@ -0,0 +1,75 @@
+/*
+** $Id: llex.h,v 1.47 2003/02/28 17:19:47 roberto Exp $
+** Lexical Analyzer
+** See Copyright Notice in lua.h
+*/
+
+#ifndef llex_h
+#define llex_h
+
+#include "lobject.h"
+#include "lzio.h"
+
+
+#define FIRST_RESERVED 257
+
+/* maximum length of a reserved word */
+#define TOKEN_LEN (sizeof("function")/sizeof(char))
+
+
+/*
+* WARNING: if you change the order of this enumeration,
+* grep "ORDER RESERVED"
+*/
+enum RESERVED {
+ /* terminal symbols denoted by reserved words */
+ TK_AND = FIRST_RESERVED, TK_BREAK,
+ TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
+ TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
+ TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
+ /* other terminal symbols */
+ TK_NAME, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER,
+ TK_STRING, TK_EOS
+};
+
+/* number of reserved words */
+#define NUM_RESERVED (cast(int, TK_WHILE-FIRST_RESERVED+1))
+
+
+typedef union {
+ lua_Number r;
+ TString *ts;
+} SemInfo; /* semantics information */
+
+
+typedef struct Token {
+ int token;
+ SemInfo seminfo;
+} Token;
+
+
+typedef struct LexState {
+ int current; /* current character (charint) */
+ int linenumber; /* input line counter */
+ int lastline; /* line of last token `consumed' */
+ Token t; /* current token */
+ Token lookahead; /* look ahead token */
+ struct FuncState *fs; /* `FuncState' is private to the parser */
+ struct lua_State *L;
+ ZIO *z; /* input stream */
+ Mbuffer *buff; /* buffer for tokens */
+ TString *source; /* current source name */
+ int nestlevel; /* level of nested non-terminals */
+} LexState;
+
+
+void luaX_init (lua_State *L);
+void luaX_setinput (lua_State *L, LexState *LS, ZIO *z, TString *source);
+int luaX_lex (LexState *LS, SemInfo *seminfo);
+void luaX_checklimit (LexState *ls, int val, int limit, const char *msg);
+void luaX_syntaxerror (LexState *ls, const char *s);
+void luaX_errorline (LexState *ls, const char *s, const char *token, int line);
+const char *luaX_token2str (LexState *ls, int token);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/llimits.h b/plugins/SmartAutoReplier/lualib/llimits.h
new file mode 100644
index 0000000000..343c922612
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/llimits.h
@@ -0,0 +1,185 @@
+/*
+** $Id: llimits.h,v 1.52 2003/02/20 19:33:23 roberto Exp $
+** Limits, basic types, and some other `installation-dependent' definitions
+** See Copyright Notice in lua.h
+*/
+
+#ifndef llimits_h
+#define llimits_h
+
+
+#include <limits.h>
+#include <stddef.h>
+
+
+#include "lua.h"
+
+
+/*
+** try to find number of bits in an integer
+*/
+#ifndef BITS_INT
+/* avoid overflows in comparison */
+#if INT_MAX-20 < 32760
+#define BITS_INT 16
+#else
+#if INT_MAX > 2147483640L
+/* machine has at least 32 bits */
+#define BITS_INT 32
+#else
+#error "you must define BITS_INT with number of bits in an integer"
+#endif
+#endif
+#endif
+
+
+/*
+** the following types define integer types for values that may not
+** fit in a `small int' (16 bits), but may waste space in a
+** `large long' (64 bits). The current definitions should work in
+** any machine, but may not be optimal.
+*/
+
+/* an unsigned integer to hold hash values */
+typedef unsigned int lu_hash;
+/* its signed equivalent */
+typedef int ls_hash;
+
+/* an unsigned integer big enough to count the total memory used by Lua; */
+/* it should be at least as large as size_t */
+typedef unsigned long lu_mem;
+
+#define MAX_LUMEM ULONG_MAX
+
+
+/* an integer big enough to count the number of strings in use */
+typedef long ls_nstr;
+
+/* chars used as small naturals (so that `char' is reserved for characters) */
+typedef unsigned char lu_byte;
+
+
+#define MAX_SIZET ((size_t)(~(size_t)0)-2)
+
+
+#define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
+
+/*
+** conversion of pointer to integer
+** this is for hashing only; there is no problem if the integer
+** cannot hold the whole pointer value
+*/
+#define IntPoint(p) ((lu_hash)(p))
+
+
+
+/* type to ensure maximum alignment */
+#ifndef LUSER_ALIGNMENT_T
+typedef union { double u; void *s; long l; } L_Umaxalign;
+#else
+typedef LUSER_ALIGNMENT_T L_Umaxalign;
+#endif
+
+
+/* result of `usual argument conversion' over lua_Number */
+#ifndef LUA_UACNUMBER
+typedef double l_uacNumber;
+#else
+typedef LUA_UACNUMBER l_uacNumber;
+#endif
+
+
+#ifndef lua_assert
+#define lua_assert(c) /* empty */
+#endif
+
+
+#ifndef check_exp
+#define check_exp(c,e) (e)
+#endif
+
+
+#ifndef UNUSED
+#define UNUSED(x) ((void)(x)) /* to avoid warnings */
+#endif
+
+
+#ifndef cast
+#define cast(t, exp) ((t)(exp))
+#endif
+
+
+
+/*
+** type for virtual-machine instructions
+** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
+*/
+typedef unsigned long Instruction;
+
+
+/* maximum depth for calls (unsigned short) */
+#ifndef LUA_MAXCALLS
+#define LUA_MAXCALLS 4096
+#endif
+
+
+/*
+** maximum depth for C calls (unsigned short): Not too big, or may
+** overflow the C stack...
+*/
+
+#ifndef LUA_MAXCCALLS
+#define LUA_MAXCCALLS 200
+#endif
+
+
+/* maximum size for the C stack */
+#ifndef LUA_MAXCSTACK
+#define LUA_MAXCSTACK 2048
+#endif
+
+
+/* maximum stack for a Lua function */
+#define MAXSTACK 250
+
+
+/* maximum number of variables declared in a function */
+#ifndef MAXVARS
+#define MAXVARS 200 /* arbitrary limit (<MAXSTACK) */
+#endif
+
+
+/* maximum number of upvalues per function */
+#ifndef MAXUPVALUES
+#define MAXUPVALUES 32
+#endif
+
+
+/* maximum number of parameters in a function */
+#ifndef MAXPARAMS
+#define MAXPARAMS 100 /* arbitrary limit (<MAXLOCALS) */
+#endif
+
+
+/* minimum size for the string table (must be power of 2) */
+#ifndef MINSTRTABSIZE
+#define MINSTRTABSIZE 32
+#endif
+
+
+/* minimum size for string buffer */
+#ifndef LUA_MINBUFFER
+#define LUA_MINBUFFER 32
+#endif
+
+
+/*
+** maximum number of syntactical nested non-terminals: Not too big,
+** or may overflow the C stack...
+*/
+#ifndef LUA_MAXPARSERLEVEL
+#define LUA_MAXPARSERLEVEL 200
+#endif
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lmathlib.c b/plugins/SmartAutoReplier/lualib/lmathlib.c
new file mode 100644
index 0000000000..f074a56ee7
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lmathlib.c
@@ -0,0 +1,246 @@
+/*
+** $Id: lmathlib.c,v 1.56 2003/03/11 12:30:37 roberto Exp $
+** Standard mathematical library
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stdlib.h>
+#include <math.h>
+
+#define lmathlib_c
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+#undef PI
+#define PI (3.14159265358979323846)
+#define RADIANS_PER_DEGREE (PI/180.0)
+
+
+
+/*
+** If you want Lua to operate in degrees (instead of radians),
+** define USE_DEGREES
+*/
+#ifdef USE_DEGREES
+#define FROMRAD(a) ((a)/RADIANS_PER_DEGREE)
+#define TORAD(a) ((a)*RADIANS_PER_DEGREE)
+#else
+#define FROMRAD(a) (a)
+#define TORAD(a) (a)
+#endif
+
+
+static int math_abs (lua_State *L) {
+ lua_pushnumber(L, fabs(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_sin (lua_State *L) {
+ lua_pushnumber(L, sin(TORAD(luaL_checknumber(L, 1))));
+ return 1;
+}
+
+static int math_cos (lua_State *L) {
+ lua_pushnumber(L, cos(TORAD(luaL_checknumber(L, 1))));
+ return 1;
+}
+
+static int math_tan (lua_State *L) {
+ lua_pushnumber(L, tan(TORAD(luaL_checknumber(L, 1))));
+ return 1;
+}
+
+static int math_asin (lua_State *L) {
+ lua_pushnumber(L, FROMRAD(asin(luaL_checknumber(L, 1))));
+ return 1;
+}
+
+static int math_acos (lua_State *L) {
+ lua_pushnumber(L, FROMRAD(acos(luaL_checknumber(L, 1))));
+ return 1;
+}
+
+static int math_atan (lua_State *L) {
+ lua_pushnumber(L, FROMRAD(atan(luaL_checknumber(L, 1))));
+ return 1;
+}
+
+static int math_atan2 (lua_State *L) {
+ lua_pushnumber(L, FROMRAD(atan2(luaL_checknumber(L, 1), luaL_checknumber(L, 2))));
+ return 1;
+}
+
+static int math_ceil (lua_State *L) {
+ lua_pushnumber(L, ceil(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_floor (lua_State *L) {
+ lua_pushnumber(L, floor(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_mod (lua_State *L) {
+ lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
+ return 1;
+}
+
+static int math_sqrt (lua_State *L) {
+ lua_pushnumber(L, sqrt(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_pow (lua_State *L) {
+ lua_pushnumber(L, pow(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
+ return 1;
+}
+
+static int math_log (lua_State *L) {
+ lua_pushnumber(L, log(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_log10 (lua_State *L) {
+ lua_pushnumber(L, log10(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_exp (lua_State *L) {
+ lua_pushnumber(L, exp(luaL_checknumber(L, 1)));
+ return 1;
+}
+
+static int math_deg (lua_State *L) {
+ lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE);
+ return 1;
+}
+
+static int math_rad (lua_State *L) {
+ lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE);
+ return 1;
+}
+
+static int math_frexp (lua_State *L) {
+ int e;
+ lua_pushnumber(L, frexp(luaL_checknumber(L, 1), &e));
+ lua_pushnumber(L, e);
+ return 2;
+}
+
+static int math_ldexp (lua_State *L) {
+ lua_pushnumber(L, ldexp(luaL_checknumber(L, 1), luaL_checkint(L, 2)));
+ return 1;
+}
+
+
+
+static int math_min (lua_State *L) {
+ int n = lua_gettop(L); /* number of arguments */
+ lua_Number dmin = luaL_checknumber(L, 1);
+ int i;
+ for (i=2; i<=n; i++) {
+ lua_Number d = luaL_checknumber(L, i);
+ if (d < dmin)
+ dmin = d;
+ }
+ lua_pushnumber(L, dmin);
+ return 1;
+}
+
+
+static int math_max (lua_State *L) {
+ int n = lua_gettop(L); /* number of arguments */
+ lua_Number dmax = luaL_checknumber(L, 1);
+ int i;
+ for (i=2; i<=n; i++) {
+ lua_Number d = luaL_checknumber(L, i);
+ if (d > dmax)
+ dmax = d;
+ }
+ lua_pushnumber(L, dmax);
+ return 1;
+}
+
+
+static int math_random (lua_State *L) {
+ /* the `%' avoids the (rare) case of r==1, and is needed also because on
+ some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
+ lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
+ switch (lua_gettop(L)) { /* check number of arguments */
+ case 0: { /* no arguments */
+ lua_pushnumber(L, r); /* Number between 0 and 1 */
+ break;
+ }
+ case 1: { /* only upper limit */
+ int u = luaL_checkint(L, 1);
+ luaL_argcheck(L, 1<=u, 1, "interval is empty");
+ lua_pushnumber(L, (int)floor(r*u)+1); /* int between 1 and `u' */
+ break;
+ }
+ case 2: { /* lower and upper limits */
+ int l = luaL_checkint(L, 1);
+ int u = luaL_checkint(L, 2);
+ luaL_argcheck(L, l<=u, 2, "interval is empty");
+ lua_pushnumber(L, (int)floor(r*(u-l+1))+l); /* int between `l' and `u' */
+ break;
+ }
+ default: return luaL_error(L, "wrong number of arguments");
+ }
+ return 1;
+}
+
+
+static int math_randomseed (lua_State *L) {
+ srand(luaL_checkint(L, 1));
+ return 0;
+}
+
+
+static const luaL_reg mathlib[] = {
+ {"abs", math_abs},
+ {"sin", math_sin},
+ {"cos", math_cos},
+ {"tan", math_tan},
+ {"asin", math_asin},
+ {"acos", math_acos},
+ {"atan", math_atan},
+ {"atan2", math_atan2},
+ {"ceil", math_ceil},
+ {"floor", math_floor},
+ {"mod", math_mod},
+ {"frexp", math_frexp},
+ {"ldexp", math_ldexp},
+ {"sqrt", math_sqrt},
+ {"min", math_min},
+ {"max", math_max},
+ {"log", math_log},
+ {"log10", math_log10},
+ {"exp", math_exp},
+ {"deg", math_deg},
+ {"pow", math_pow},
+ {"rad", math_rad},
+ {"random", math_random},
+ {"randomseed", math_randomseed},
+ {NULL, NULL}
+};
+
+
+/*
+** Open math library
+*/
+LUALIB_API int luaopen_math (lua_State *L) {
+ luaL_openlib(L, LUA_MATHLIBNAME, mathlib, 0);
+ lua_pushliteral(L, "pi");
+ lua_pushnumber(L, PI);
+ lua_settable(L, -3);
+ lua_pushliteral(L, "__pow");
+ lua_pushcfunction(L, math_pow);
+ lua_settable(L, LUA_GLOBALSINDEX);
+ return 1;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lmem.c b/plugins/SmartAutoReplier/lualib/lmem.c
new file mode 100644
index 0000000000..f977770af0
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lmem.c
@@ -0,0 +1,91 @@
+/*
+** $Id: lmem.c,v 1.61 2002/12/04 17:38:31 roberto Exp $
+** Interface to Memory Manager
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stdlib.h>
+
+#define lmem_c
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "ldo.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+
+
+
+/*
+** definition for realloc function. It must assure that l_realloc(NULL,
+** 0, x) allocates a new block (ANSI C assures that). (`os' is the old
+** block size; some allocators may use that.)
+*/
+#ifndef l_realloc
+#define l_realloc(b,os,s) realloc(b,s)
+#endif
+
+/*
+** definition for free function. (`os' is the old block size; some
+** allocators may use that.)
+*/
+#ifndef l_free
+#define l_free(b,os) free(b)
+#endif
+
+
+#define MINSIZEARRAY 4
+
+
+void *luaM_growaux (lua_State *L, void *block, int *size, int size_elems,
+ int limit, const char *errormsg) {
+ void *newblock;
+ int newsize = (*size)*2;
+ if (newsize < MINSIZEARRAY)
+ newsize = MINSIZEARRAY; /* minimum size */
+ else if (*size >= limit/2) { /* cannot double it? */
+ if (*size < limit - MINSIZEARRAY) /* try something smaller... */
+ newsize = limit; /* still have at least MINSIZEARRAY free places */
+ else luaG_runerror(L, errormsg);
+ }
+ newblock = luaM_realloc(L, block,
+ cast(lu_mem, *size)*cast(lu_mem, size_elems),
+ cast(lu_mem, newsize)*cast(lu_mem, size_elems));
+ *size = newsize; /* update only when everything else is OK */
+ return newblock;
+}
+
+
+/*
+** generic allocation routine.
+*/
+void *luaM_realloc (lua_State *L, void *block, lu_mem oldsize, lu_mem size) {
+ lua_assert((oldsize == 0) == (block == NULL));
+ if (size == 0) {
+ if (block != NULL) {
+ l_free(block, oldsize);
+ block = NULL;
+ }
+ else return NULL; /* avoid `nblocks' computations when oldsize==size==0 */
+ }
+ else if (size >= MAX_SIZET)
+ luaG_runerror(L, "memory allocation error: block too big");
+ else {
+ block = l_realloc(block, oldsize, size);
+ if (block == NULL) {
+ if (L)
+ luaD_throw(L, LUA_ERRMEM);
+ else return NULL; /* error before creating state! */
+ }
+ }
+ if (L) {
+ lua_assert(G(L) != NULL && G(L)->nblocks > 0);
+ G(L)->nblocks -= oldsize;
+ G(L)->nblocks += size;
+ }
+ return block;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lmem.h b/plugins/SmartAutoReplier/lualib/lmem.h
new file mode 100644
index 0000000000..1bb4fde0b2
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lmem.h
@@ -0,0 +1,44 @@
+/*
+** $Id: lmem.h,v 1.26 2002/05/01 20:40:42 roberto Exp $
+** Interface to Memory Manager
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lmem_h
+#define lmem_h
+
+
+#include <stddef.h>
+
+#include "llimits.h"
+#include "lua.h"
+
+#define MEMERRMSG "not enough memory"
+
+
+void *luaM_realloc (lua_State *L, void *oldblock, lu_mem oldsize, lu_mem size);
+
+void *luaM_growaux (lua_State *L, void *block, int *size, int size_elem,
+ int limit, const char *errormsg);
+
+#define luaM_free(L, b, s) luaM_realloc(L, (b), (s), 0)
+#define luaM_freelem(L, b) luaM_realloc(L, (b), sizeof(*(b)), 0)
+#define luaM_freearray(L, b, n, t) luaM_realloc(L, (b), \
+ cast(lu_mem, n)*cast(lu_mem, sizeof(t)), 0)
+
+#define luaM_malloc(L, t) luaM_realloc(L, NULL, 0, (t))
+#define luaM_new(L, t) cast(t *, luaM_malloc(L, sizeof(t)))
+#define luaM_newvector(L, n,t) cast(t *, luaM_malloc(L, \
+ cast(lu_mem, n)*cast(lu_mem, sizeof(t))))
+
+#define luaM_growvector(L,v,nelems,size,t,limit,e) \
+ if (((nelems)+1) > (size)) \
+ ((v)=cast(t *, luaM_growaux(L,v,&(size),sizeof(t),limit,e)))
+
+#define luaM_reallocvector(L, v,oldn,n,t) \
+ ((v)=cast(t *, luaM_realloc(L, v,cast(lu_mem, oldn)*cast(lu_mem, sizeof(t)), \
+ cast(lu_mem, n)*cast(lu_mem, sizeof(t)))))
+
+
+#endif
+
diff --git a/plugins/SmartAutoReplier/lualib/loadlib.c b/plugins/SmartAutoReplier/lualib/loadlib.c
new file mode 100644
index 0000000000..ac4d697a68
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/loadlib.c
@@ -0,0 +1,205 @@
+/*
+** $Id: loadlib.c,v 1.4 2003/04/07 20:11:53 roberto Exp $
+** Dynamic library loader for Lua
+** See Copyright Notice in lua.h
+*
+* This Lua library exports a single function, called loadlib, which is
+* called from Lua as loadlib(lib,init), where lib is the full name of the
+* library to be loaded (including the complete path) and init is the name
+* of a function to be called after the library is loaded. Typically, this
+* function will register other functions, thus making the complete library
+* available to Lua. The init function is *not* automatically called by
+* loadlib. Instead, loadlib returns the init function as a Lua function
+* that the client can call when it thinks is appropriate. In the case of
+* errors, loadlib returns nil and two strings describing the error.
+* The first string is supplied by the operating system; it should be
+* informative and useful for error messages. The second string is "open",
+* "init", or "absent" to identify the error and is meant to be used for
+* making decisions without having to look into the first string (whose
+* format is system-dependent).
+*
+* This module contains an implementation of loadlib for Unix systems that
+* have dlfcn, an implementation for Windows, and a stub for other systems.
+* See the list at the end of this file for some links to available
+* implementations of dlfcn and interfaces to other native dynamic loaders
+* on top of which loadlib could be implemented.
+*
+*/
+
+#include "lua.h"
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+#undef LOADLIB
+
+
+#ifdef USE_DLOPEN
+#define LOADLIB
+/*
+* This is an implementation of loadlib based on the dlfcn interface.
+* The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
+* NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
+* as an emulation layer on top of native functions.
+*/
+
+#include <dlfcn.h>
+
+static int loadlib(lua_State *L)
+{
+ const char *path=luaL_checkstring(L,1);
+ const char *init=luaL_checkstring(L,2);
+ void *lib=dlopen(path,RTLD_NOW);
+ if (lib!=NULL)
+ {
+ lua_CFunction f=(lua_CFunction) dlsym(lib,init);
+ if (f!=NULL)
+ {
+ lua_pushlightuserdata(L,lib);
+ lua_pushcclosure(L,f,1);
+ return 1;
+ }
+ }
+ /* else return appropriate error messages */
+ lua_pushnil(L);
+ lua_pushstring(L,dlerror());
+ lua_pushstring(L,(lib!=NULL) ? "init" : "open");
+ if (lib!=NULL) dlclose(lib);
+ return 3;
+}
+
+#endif
+
+
+
+/*
+** In Windows, default is to use dll; otherwise, default is not to use dll
+*/
+#ifndef USE_DLL
+#ifdef _WIN32
+#define USE_DLL 1
+#else
+#define USE_DLL 0
+#endif
+#endif
+
+
+#if USE_DLL
+#define LOADLIB
+/*
+* This is an implementation of loadlib for Windows using native functions.
+*/
+
+#include <windows.h>
+
+static void pusherror(lua_State *L)
+{
+ int error=GetLastError();
+ char buffer[128];
+ if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
+ 0, error, 0, buffer, sizeof(buffer), 0))
+ lua_pushstring(L,buffer);
+ else
+ lua_pushfstring(L,"system error %d\n",error);
+}
+
+static int loadlib(lua_State *L)
+{
+ const char *path=luaL_checkstring(L,1);
+ const char *init=luaL_checkstring(L,2);
+ HINSTANCE lib=LoadLibrary(path);
+ if (lib!=NULL)
+ {
+ lua_CFunction f=(lua_CFunction) GetProcAddress(lib,init);
+ if (f!=NULL)
+ {
+ lua_pushlightuserdata(L,lib);
+ lua_pushcclosure(L,f,1);
+ return 1;
+ }
+ }
+ lua_pushnil(L);
+ pusherror(L);
+ lua_pushstring(L,(lib!=NULL) ? "init" : "open");
+ if (lib!=NULL) FreeLibrary(lib);
+ return 3;
+}
+
+#endif
+
+
+
+#ifndef LOADLIB
+/* Fallback for other systems */
+
+/*
+** Those systems support dlopen, so they should have defined USE_DLOPEN.
+** The default (no)implementation gives them a special error message.
+*/
+#ifdef linux
+#define LOADLIB
+#endif
+
+#ifdef sun
+#define LOADLIB
+#endif
+
+#ifdef sgi
+#define LOADLIB
+#endif
+
+#ifdef BSD
+#define LOADLIB
+#endif
+
+#ifdef _WIN32
+#define LOADLIB
+#endif
+
+#ifdef LOADLIB
+#undef LOADLIB
+#define LOADLIB "`loadlib' not installed (check your Lua configuration)"
+#else
+#define LOADLIB "`loadlib' not supported"
+#endif
+
+static int loadlib(lua_State *L)
+{
+ lua_pushnil(L);
+ lua_pushliteral(L,LOADLIB);
+ lua_pushliteral(L,"absent");
+ return 3;
+}
+#endif
+
+LUALIB_API int luaopen_loadlib (lua_State *L)
+{
+ lua_register(L,"loadlib",loadlib);
+ return 0;
+}
+
+/*
+* Here are some links to available implementations of dlfcn and
+* interfaces to other native dynamic loaders on top of which loadlib
+* could be implemented. Please send contributions and corrections to us.
+*
+* AIX
+* Starting with AIX 4.2, dlfcn is included in the base OS.
+* There is also an emulation package available.
+* http://www.faqs.org/faqs/aix-faq/part4/section-21.html
+*
+* HPUX
+* HPUX 11 has dlfcn. For HPUX 10 use shl_*.
+* http://www.geda.seul.org/mailinglist/geda-dev37/msg00094.html
+* http://www.stat.umn.edu/~luke/xls/projects/dlbasics/dlbasics.html
+*
+* Macintosh, Windows
+* http://www.stat.umn.edu/~luke/xls/projects/dlbasics/dlbasics.html
+*
+* Mac OS X/Darwin
+* http://www.opendarwin.org/projects/dlcompat/
+*
+* GLIB has wrapper code for BeOS, OS2, Unix and Windows
+* http://cvs.gnome.org/lxr/source/glib/gmodule/
+*
+*/
diff --git a/plugins/SmartAutoReplier/lualib/lobject.c b/plugins/SmartAutoReplier/lualib/lobject.c
new file mode 100644
index 0000000000..9522b6e812
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lobject.c
@@ -0,0 +1,195 @@
+/*
+** $Id: lobject.c,v 1.97 2003/04/03 13:35:34 roberto Exp $
+** Some generic functions over Lua objects
+** See Copyright Notice in lua.h
+*/
+
+#include <ctype.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define lobject_c
+
+#include "lua.h"
+
+#include "ldo.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "lvm.h"
+
+
+/* function to convert a string to a lua_Number */
+#ifndef lua_str2number
+#define lua_str2number(s,p) strtod((s), (p))
+#endif
+
+
+const TObject luaO_nilobject = {LUA_TNIL, {NULL}};
+
+
+/*
+** converts an integer to a "floating point byte", represented as
+** (mmmmmxxx), where the real value is (xxx) * 2^(mmmmm)
+*/
+int luaO_int2fb (unsigned int x) {
+ int m = 0; /* mantissa */
+ while (x >= (1<<3)) {
+ x = (x+1) >> 1;
+ m++;
+ }
+ return (m << 3) | cast(int, x);
+}
+
+
+int luaO_log2 (unsigned int x) {
+ static const lu_byte log_8[255] = {
+ 0,
+ 1,1,
+ 2,2,2,2,
+ 3,3,3,3,3,3,3,3,
+ 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
+ 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
+ 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
+ };
+ if (x >= 0x00010000) {
+ if (x >= 0x01000000) return log_8[((x>>24) & 0xff) - 1]+24;
+ else return log_8[((x>>16) & 0xff) - 1]+16;
+ }
+ else {
+ if (x >= 0x00000100) return log_8[((x>>8) & 0xff) - 1]+8;
+ else if (x) return log_8[(x & 0xff) - 1];
+ return -1; /* special `log' for 0 */
+ }
+}
+
+
+int luaO_rawequalObj (const TObject *t1, const TObject *t2) {
+ if (ttype(t1) != ttype(t2)) return 0;
+ else switch (ttype(t1)) {
+ case LUA_TNIL:
+ return 1;
+ case LUA_TNUMBER:
+ return nvalue(t1) == nvalue(t2);
+ case LUA_TBOOLEAN:
+ return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */
+ case LUA_TLIGHTUSERDATA:
+ return pvalue(t1) == pvalue(t2);
+ default:
+ lua_assert(iscollectable(t1));
+ return gcvalue(t1) == gcvalue(t2);
+ }
+}
+
+
+int luaO_str2d (const char *s, lua_Number *result) {
+ char *endptr;
+ lua_Number res = lua_str2number(s, &endptr);
+ if (endptr == s) return 0; /* no conversion */
+ while (isspace((unsigned char)(*endptr))) endptr++;
+ if (*endptr != '\0') return 0; /* invalid trailing characters? */
+ *result = res;
+ return 1;
+}
+
+
+
+static void pushstr (lua_State *L, const char *str) {
+ setsvalue2s(L->top, luaS_new(L, str));
+ incr_top(L);
+}
+
+
+/* this function handles only `%d', `%c', %f, and `%s' formats */
+const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
+ int n = 1;
+ pushstr(L, "");
+ for (;;) {
+ const char *e = strchr(fmt, '%');
+ if (e == NULL) break;
+ setsvalue2s(L->top, luaS_newlstr(L, fmt, e-fmt));
+ incr_top(L);
+ switch (*(e+1)) {
+ case 's':
+ pushstr(L, va_arg(argp, char *));
+ break;
+ case 'c': {
+ char buff[2];
+ buff[0] = cast(char, va_arg(argp, int));
+ buff[1] = '\0';
+ pushstr(L, buff);
+ break;
+ }
+ case 'd':
+ setnvalue(L->top, cast(lua_Number, va_arg(argp, int)));
+ incr_top(L);
+ break;
+ case 'f':
+ setnvalue(L->top, cast(lua_Number, va_arg(argp, l_uacNumber)));
+ incr_top(L);
+ break;
+ case '%':
+ pushstr(L, "%");
+ break;
+ default: lua_assert(0);
+ }
+ n += 2;
+ fmt = e+2;
+ }
+ pushstr(L, fmt);
+ luaV_concat(L, n+1, L->top - L->base - 1);
+ L->top -= n;
+ return svalue(L->top - 1);
+}
+
+
+const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
+ const char *msg;
+ va_list argp;
+ va_start(argp, fmt);
+ msg = luaO_pushvfstring(L, fmt, argp);
+ va_end(argp);
+ return msg;
+}
+
+
+void luaO_chunkid (char *out, const char *source, int bufflen) {
+ if (*source == '=') {
+ strncpy(out, source+1, bufflen); /* remove first char */
+ out[bufflen-1] = '\0'; /* ensures null termination */
+ }
+ else { /* out = "source", or "...source" */
+ if (*source == '@') {
+ int l;
+ source++; /* skip the `@' */
+ bufflen -= sizeof(" `...' ");
+ l = strlen(source);
+ strcpy(out, "");
+ if (l>bufflen) {
+ source += (l-bufflen); /* get last part of file name */
+ strcat(out, "...");
+ }
+ strcat(out, source);
+ }
+ else { /* out = [string "string"] */
+ int len = strcspn(source, "\n"); /* stop at first newline */
+ bufflen -= sizeof(" [string \"...\"] ");
+ if (len > bufflen) len = bufflen;
+ strcpy(out, "[string \"");
+ if (source[len] != '\0') { /* must truncate? */
+ strncat(out, source, len);
+ strcat(out, "...");
+ }
+ else
+ strcat(out, source);
+ strcat(out, "\"]");
+ }
+ }
+}
diff --git a/plugins/SmartAutoReplier/lualib/lobject.h b/plugins/SmartAutoReplier/lualib/lobject.h
new file mode 100644
index 0000000000..321a7e06c1
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lobject.h
@@ -0,0 +1,336 @@
+/*
+** $Id: lobject.h,v 1.159 2003/03/18 12:50:04 roberto Exp $
+** Type definitions for Lua objects
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lobject_h
+#define lobject_h
+
+
+#include "llimits.h"
+#include "lua.h"
+
+
+/* tags for values visible from Lua */
+#define NUM_TAGS LUA_TTHREAD
+
+
+/*
+** Extra tags for non-values
+*/
+#define LUA_TPROTO (NUM_TAGS+1)
+#define LUA_TUPVAL (NUM_TAGS+2)
+
+
+/*
+** Union of all collectable objects
+*/
+typedef union GCObject GCObject;
+
+
+/*
+** Common Header for all collectable objects (in macro form, to be
+** included in other objects)
+*/
+#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked
+
+
+/*
+** Common header in struct form
+*/
+typedef struct GCheader {
+ CommonHeader;
+} GCheader;
+
+
+
+
+/*
+** Union of all Lua values
+*/
+typedef union {
+ GCObject *gc;
+ void *p;
+ lua_Number n;
+ int b;
+} Value;
+
+
+/*
+** Lua values (or `tagged objects')
+*/
+typedef struct lua_TObject {
+ int tt;
+ Value value;
+} TObject;
+
+
+/* Macros to test type */
+#define ttisnil(o) (ttype(o) == LUA_TNIL)
+#define ttisnumber(o) (ttype(o) == LUA_TNUMBER)
+#define ttisstring(o) (ttype(o) == LUA_TSTRING)
+#define ttistable(o) (ttype(o) == LUA_TTABLE)
+#define ttisfunction(o) (ttype(o) == LUA_TFUNCTION)
+#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN)
+#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA)
+#define ttisthread(o) (ttype(o) == LUA_TTHREAD)
+#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA)
+
+/* Macros to access values */
+#define ttype(o) ((o)->tt)
+#define gcvalue(o) check_exp(iscollectable(o), (o)->value.gc)
+#define pvalue(o) check_exp(ttislightuserdata(o), (o)->value.p)
+#define nvalue(o) check_exp(ttisnumber(o), (o)->value.n)
+#define tsvalue(o) check_exp(ttisstring(o), &(o)->value.gc->ts)
+#define uvalue(o) check_exp(ttisuserdata(o), &(o)->value.gc->u)
+#define clvalue(o) check_exp(ttisfunction(o), &(o)->value.gc->cl)
+#define hvalue(o) check_exp(ttistable(o), &(o)->value.gc->h)
+#define bvalue(o) check_exp(ttisboolean(o), (o)->value.b)
+#define thvalue(o) check_exp(ttisthread(o), &(o)->value.gc->th)
+
+#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
+
+/* Macros to set values */
+#define setnvalue(obj,x) \
+ { TObject *i_o=(obj); i_o->tt=LUA_TNUMBER; i_o->value.n=(x); }
+
+#define chgnvalue(obj,x) \
+ check_exp(ttype(obj)==LUA_TNUMBER, (obj)->value.n=(x))
+
+#define setpvalue(obj,x) \
+ { TObject *i_o=(obj); i_o->tt=LUA_TLIGHTUSERDATA; i_o->value.p=(x); }
+
+#define setbvalue(obj,x) \
+ { TObject *i_o=(obj); i_o->tt=LUA_TBOOLEAN; i_o->value.b=(x); }
+
+#define setsvalue(obj,x) \
+ { TObject *i_o=(obj); i_o->tt=LUA_TSTRING; \
+ i_o->value.gc=cast(GCObject *, (x)); \
+ lua_assert(i_o->value.gc->gch.tt == LUA_TSTRING); }
+
+#define setuvalue(obj,x) \
+ { TObject *i_o=(obj); i_o->tt=LUA_TUSERDATA; \
+ i_o->value.gc=cast(GCObject *, (x)); \
+ lua_assert(i_o->value.gc->gch.tt == LUA_TUSERDATA); }
+
+#define setthvalue(obj,x) \
+ { TObject *i_o=(obj); i_o->tt=LUA_TTHREAD; \
+ i_o->value.gc=cast(GCObject *, (x)); \
+ lua_assert(i_o->value.gc->gch.tt == LUA_TTHREAD); }
+
+#define setclvalue(obj,x) \
+ { TObject *i_o=(obj); i_o->tt=LUA_TFUNCTION; \
+ i_o->value.gc=cast(GCObject *, (x)); \
+ lua_assert(i_o->value.gc->gch.tt == LUA_TFUNCTION); }
+
+#define sethvalue(obj,x) \
+ { TObject *i_o=(obj); i_o->tt=LUA_TTABLE; \
+ i_o->value.gc=cast(GCObject *, (x)); \
+ lua_assert(i_o->value.gc->gch.tt == LUA_TTABLE); }
+
+#define setnilvalue(obj) ((obj)->tt=LUA_TNIL)
+
+
+
+/*
+** for internal debug only
+*/
+#define checkconsistency(obj) \
+ lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt))
+
+
+#define setobj(obj1,obj2) \
+ { const TObject *o2=(obj2); TObject *o1=(obj1); \
+ checkconsistency(o2); \
+ o1->tt=o2->tt; o1->value = o2->value; }
+
+
+/*
+** different types of sets, according to destination
+*/
+
+/* from stack to (same) stack */
+#define setobjs2s setobj
+/* to stack (not from same stack) */
+#define setobj2s setobj
+#define setsvalue2s setsvalue
+/* from table to same table */
+#define setobjt2t setobj
+/* to table */
+#define setobj2t setobj
+/* to new object */
+#define setobj2n setobj
+#define setsvalue2n setsvalue
+
+#define setttype(obj, tt) (ttype(obj) = (tt))
+
+
+#define iscollectable(o) (ttype(o) >= LUA_TSTRING)
+
+
+
+typedef TObject *StkId; /* index to stack elements */
+
+
+/*
+** String headers for string table
+*/
+typedef union TString {
+ L_Umaxalign dummy; /* ensures maximum alignment for strings */
+ struct {
+ CommonHeader;
+ lu_byte reserved;
+ lu_hash hash;
+ size_t len;
+ } tsv;
+} TString;
+
+
+#define getstr(ts) cast(const char *, (ts) + 1)
+#define svalue(o) getstr(tsvalue(o))
+
+
+
+typedef union Udata {
+ L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */
+ struct {
+ CommonHeader;
+ struct Table *metatable;
+ size_t len;
+ } uv;
+} Udata;
+
+
+
+
+/*
+** Function Prototypes
+*/
+typedef struct Proto {
+ CommonHeader;
+ TObject *k; /* constants used by the function */
+ Instruction *code;
+ struct Proto **p; /* functions defined inside the function */
+ int *lineinfo; /* map from opcodes to source lines */
+ struct LocVar *locvars; /* information about local variables */
+ TString **upvalues; /* upvalue names */
+ TString *source;
+ int sizeupvalues;
+ int sizek; /* size of `k' */
+ int sizecode;
+ int sizelineinfo;
+ int sizep; /* size of `p' */
+ int sizelocvars;
+ int lineDefined;
+ GCObject *gclist;
+ lu_byte nups; /* number of upvalues */
+ lu_byte numparams;
+ lu_byte is_vararg;
+ lu_byte maxstacksize;
+} Proto;
+
+
+typedef struct LocVar {
+ TString *varname;
+ int startpc; /* first point where variable is active */
+ int endpc; /* first point where variable is dead */
+} LocVar;
+
+
+
+/*
+** Upvalues
+*/
+
+typedef struct UpVal {
+ CommonHeader;
+ TObject *v; /* points to stack or to its own value */
+ TObject value; /* the value (when closed) */
+} UpVal;
+
+
+/*
+** Closures
+*/
+
+#define ClosureHeader \
+ CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist
+
+typedef struct CClosure {
+ ClosureHeader;
+ lua_CFunction f;
+ TObject upvalue[1];
+} CClosure;
+
+
+typedef struct LClosure {
+ ClosureHeader;
+ struct Proto *p;
+ TObject g; /* global table for this closure */
+ UpVal *upvals[1];
+} LClosure;
+
+
+typedef union Closure {
+ CClosure c;
+ LClosure l;
+} Closure;
+
+
+#define iscfunction(o) (ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC)
+#define isLfunction(o) (ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC)
+
+
+/*
+** Tables
+*/
+
+typedef struct Node {
+ TObject i_key;
+ TObject i_val;
+ struct Node *next; /* for chaining */
+} Node;
+
+
+typedef struct Table {
+ CommonHeader;
+ lu_byte flags; /* 1<<p means tagmethod(p) is not present */
+ lu_byte lsizenode; /* log2 of size of `node' array */
+ struct Table *metatable;
+ TObject *array; /* array part */
+ Node *node;
+ Node *firstfree; /* this position is free; all positions after it are full */
+ GCObject *gclist;
+ int sizearray; /* size of `array' array */
+} Table;
+
+
+
+/*
+** `module' operation for hashing (size is always a power of 2)
+*/
+#define lmod(s,size) \
+ check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1))))
+
+
+#define twoto(x) (1<<(x))
+#define sizenode(t) (twoto((t)->lsizenode))
+
+
+
+extern const TObject luaO_nilobject;
+
+int luaO_log2 (unsigned int x);
+int luaO_int2fb (unsigned int x);
+#define fb2int(x) (((x) & 7) << ((x) >> 3))
+
+int luaO_rawequalObj (const TObject *t1, const TObject *t2);
+int luaO_str2d (const char *s, lua_Number *result);
+
+const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp);
+const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
+void luaO_chunkid (char *out, const char *source, int len);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lopcodes.c b/plugins/SmartAutoReplier/lualib/lopcodes.c
new file mode 100644
index 0000000000..993e426d35
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lopcodes.c
@@ -0,0 +1,102 @@
+/*
+** $Id: lopcodes.c,v 1.22 2002/12/04 17:38:31 roberto Exp $
+** extracted automatically from lopcodes.h by mkprint.lua
+** DO NOT EDIT
+** See Copyright Notice in lua.h
+*/
+
+
+#define lopcodes_c
+
+#include "lua.h"
+
+#include "lobject.h"
+#include "lopcodes.h"
+
+
+#ifdef LUA_OPNAMES
+
+const char *const luaP_opnames[] = {
+ "MOVE",
+ "LOADK",
+ "LOADBOOL",
+ "LOADNIL",
+ "GETUPVAL",
+ "GETGLOBAL",
+ "GETTABLE",
+ "SETGLOBAL",
+ "SETUPVAL",
+ "SETTABLE",
+ "NEWTABLE",
+ "SELF",
+ "ADD",
+ "SUB",
+ "MUL",
+ "DIV",
+ "POW",
+ "UNM",
+ "NOT",
+ "CONCAT",
+ "JMP",
+ "EQ",
+ "LT",
+ "LE",
+ "TEST",
+ "CALL",
+ "TAILCALL",
+ "RETURN",
+ "FORLOOP",
+ "TFORLOOP",
+ "TFORPREP",
+ "SETLIST",
+ "SETLISTO",
+ "CLOSE",
+ "CLOSURE"
+};
+
+#endif
+
+#define opmode(t,b,bk,ck,sa,k,m) (((t)<<OpModeT) | \
+ ((b)<<OpModeBreg) | ((bk)<<OpModeBrk) | ((ck)<<OpModeCrk) | \
+ ((sa)<<OpModesetA) | ((k)<<OpModeK) | (m))
+
+
+const lu_byte luaP_opmodes[NUM_OPCODES] = {
+/* T B Bk Ck sA K mode opcode */
+ opmode(0, 1, 0, 0, 1, 0, iABC) /* OP_MOVE */
+ ,opmode(0, 0, 0, 0, 1, 1, iABx) /* OP_LOADK */
+ ,opmode(0, 0, 0, 0, 1, 0, iABC) /* OP_LOADBOOL */
+ ,opmode(0, 1, 0, 0, 1, 0, iABC) /* OP_LOADNIL */
+ ,opmode(0, 0, 0, 0, 1, 0, iABC) /* OP_GETUPVAL */
+ ,opmode(0, 0, 0, 0, 1, 1, iABx) /* OP_GETGLOBAL */
+ ,opmode(0, 1, 0, 1, 1, 0, iABC) /* OP_GETTABLE */
+ ,opmode(0, 0, 0, 0, 0, 1, iABx) /* OP_SETGLOBAL */
+ ,opmode(0, 0, 0, 0, 0, 0, iABC) /* OP_SETUPVAL */
+ ,opmode(0, 0, 1, 1, 0, 0, iABC) /* OP_SETTABLE */
+ ,opmode(0, 0, 0, 0, 1, 0, iABC) /* OP_NEWTABLE */
+ ,opmode(0, 1, 0, 1, 1, 0, iABC) /* OP_SELF */
+ ,opmode(0, 0, 1, 1, 1, 0, iABC) /* OP_ADD */
+ ,opmode(0, 0, 1, 1, 1, 0, iABC) /* OP_SUB */
+ ,opmode(0, 0, 1, 1, 1, 0, iABC) /* OP_MUL */
+ ,opmode(0, 0, 1, 1, 1, 0, iABC) /* OP_DIV */
+ ,opmode(0, 0, 1, 1, 1, 0, iABC) /* OP_POW */
+ ,opmode(0, 1, 0, 0, 1, 0, iABC) /* OP_UNM */
+ ,opmode(0, 1, 0, 0, 1, 0, iABC) /* OP_NOT */
+ ,opmode(0, 1, 0, 1, 1, 0, iABC) /* OP_CONCAT */
+ ,opmode(0, 0, 0, 0, 0, 0, iAsBx) /* OP_JMP */
+ ,opmode(1, 0, 1, 1, 0, 0, iABC) /* OP_EQ */
+ ,opmode(1, 0, 1, 1, 0, 0, iABC) /* OP_LT */
+ ,opmode(1, 0, 1, 1, 0, 0, iABC) /* OP_LE */
+ ,opmode(1, 1, 0, 0, 1, 0, iABC) /* OP_TEST */
+ ,opmode(0, 0, 0, 0, 0, 0, iABC) /* OP_CALL */
+ ,opmode(0, 0, 0, 0, 0, 0, iABC) /* OP_TAILCALL */
+ ,opmode(0, 0, 0, 0, 0, 0, iABC) /* OP_RETURN */
+ ,opmode(0, 0, 0, 0, 0, 0, iAsBx) /* OP_FORLOOP */
+ ,opmode(1, 0, 0, 0, 0, 0, iABC) /* OP_TFORLOOP */
+ ,opmode(0, 0, 0, 0, 0, 0, iAsBx) /* OP_TFORPREP */
+ ,opmode(0, 0, 0, 0, 0, 0, iABx) /* OP_SETLIST */
+ ,opmode(0, 0, 0, 0, 0, 0, iABx) /* OP_SETLISTO */
+ ,opmode(0, 0, 0, 0, 0, 0, iABC) /* OP_CLOSE */
+ ,opmode(0, 0, 0, 0, 1, 0, iABx) /* OP_CLOSURE */
+};
+
diff --git a/plugins/SmartAutoReplier/lualib/lopcodes.h b/plugins/SmartAutoReplier/lualib/lopcodes.h
new file mode 100644
index 0000000000..0b6b58f3cd
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lopcodes.h
@@ -0,0 +1,238 @@
+/*
+** $Id: lopcodes.h,v 1.102 2002/08/21 18:56:09 roberto Exp $
+** Opcodes for Lua virtual machine
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lopcodes_h
+#define lopcodes_h
+
+#include "llimits.h"
+
+
+/*===========================================================================
+ We assume that instructions are unsigned numbers.
+ All instructions have an opcode in the first 6 bits.
+ Instructions can have the following fields:
+ `A' : 8 bits
+ `B' : 9 bits
+ `C' : 9 bits
+ `Bx' : 18 bits (`B' and `C' together)
+ `sBx' : signed Bx
+
+ A signed argument is represented in excess K; that is, the number
+ value is the unsigned value minus K. K is exactly the maximum value
+ for that argument (so that -max is represented by 0, and +max is
+ represented by 2*max), which is half the maximum for the corresponding
+ unsigned argument.
+===========================================================================*/
+
+
+enum OpMode {iABC, iABx, iAsBx}; /* basic instruction format */
+
+
+/*
+** size and position of opcode arguments.
+*/
+#define SIZE_C 9
+#define SIZE_B 9
+#define SIZE_Bx (SIZE_C + SIZE_B)
+#define SIZE_A 8
+
+#define SIZE_OP 6
+
+#define POS_C SIZE_OP
+#define POS_B (POS_C + SIZE_C)
+#define POS_Bx POS_C
+#define POS_A (POS_B + SIZE_B)
+
+
+/*
+** limits for opcode arguments.
+** we use (signed) int to manipulate most arguments,
+** so they must fit in BITS_INT-1 bits (-1 for sign)
+*/
+#if SIZE_Bx < BITS_INT-1
+#define MAXARG_Bx ((1<<SIZE_Bx)-1)
+#define MAXARG_sBx (MAXARG_Bx>>1) /* `sBx' is signed */
+#else
+#define MAXARG_Bx MAX_INT
+#define MAXARG_sBx MAX_INT
+#endif
+
+
+#define MAXARG_A ((1<<SIZE_A)-1)
+#define MAXARG_B ((1<<SIZE_B)-1)
+#define MAXARG_C ((1<<SIZE_C)-1)
+
+
+/* creates a mask with `n' 1 bits at position `p' */
+#define MASK1(n,p) ((~((~(Instruction)0)<<n))<<p)
+
+/* creates a mask with `n' 0 bits at position `p' */
+#define MASK0(n,p) (~MASK1(n,p))
+
+/*
+** the following macros help to manipulate instructions
+*/
+
+#define GET_OPCODE(i) (cast(OpCode, (i)&MASK1(SIZE_OP,0)))
+#define SET_OPCODE(i,o) ((i) = (((i)&MASK0(SIZE_OP,0)) | cast(Instruction, o)))
+
+#define GETARG_A(i) (cast(int, (i)>>POS_A))
+#define SETARG_A(i,u) ((i) = (((i)&MASK0(SIZE_A,POS_A)) | \
+ ((cast(Instruction, u)<<POS_A)&MASK1(SIZE_A,POS_A))))
+
+#define GETARG_B(i) (cast(int, ((i)>>POS_B) & MASK1(SIZE_B,0)))
+#define SETARG_B(i,b) ((i) = (((i)&MASK0(SIZE_B,POS_B)) | \
+ ((cast(Instruction, b)<<POS_B)&MASK1(SIZE_B,POS_B))))
+
+#define GETARG_C(i) (cast(int, ((i)>>POS_C) & MASK1(SIZE_C,0)))
+#define SETARG_C(i,b) ((i) = (((i)&MASK0(SIZE_C,POS_C)) | \
+ ((cast(Instruction, b)<<POS_C)&MASK1(SIZE_C,POS_C))))
+
+#define GETARG_Bx(i) (cast(int, ((i)>>POS_Bx) & MASK1(SIZE_Bx,0)))
+#define SETARG_Bx(i,b) ((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \
+ ((cast(Instruction, b)<<POS_Bx)&MASK1(SIZE_Bx,POS_Bx))))
+
+#define GETARG_sBx(i) (GETARG_Bx(i)-MAXARG_sBx)
+#define SETARG_sBx(i,b) SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx))
+
+
+#define CREATE_ABC(o,a,b,c) (cast(Instruction, o) \
+ | (cast(Instruction, a)<<POS_A) \
+ | (cast(Instruction, b)<<POS_B) \
+ | (cast(Instruction, c)<<POS_C))
+
+#define CREATE_ABx(o,a,bc) (cast(Instruction, o) \
+ | (cast(Instruction, a)<<POS_A) \
+ | (cast(Instruction, bc)<<POS_Bx))
+
+
+
+
+/*
+** invalid register that fits in 8 bits
+*/
+#define NO_REG MAXARG_A
+
+
+/*
+** R(x) - register
+** Kst(x) - constant (in constant table)
+** RK(x) == if x < MAXSTACK then R(x) else Kst(x-MAXSTACK)
+*/
+
+
+/*
+** grep "ORDER OP" if you change these enums
+*/
+
+typedef enum {
+/*----------------------------------------------------------------------
+name args description
+------------------------------------------------------------------------*/
+OP_MOVE,/* A B R(A) := R(B) */
+OP_LOADK,/* A Bx R(A) := Kst(Bx) */
+OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) PC++ */
+OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */
+OP_GETUPVAL,/* A B R(A) := UpValue[B] */
+
+OP_GETGLOBAL,/* A Bx R(A) := Gbl[Kst(Bx)] */
+OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */
+
+OP_SETGLOBAL,/* A Bx Gbl[Kst(Bx)] := R(A) */
+OP_SETUPVAL,/* A B UpValue[B] := R(A) */
+OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */
+
+OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */
+
+OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */
+
+OP_ADD,/* A B C R(A) := RK(B) + RK(C) */
+OP_SUB,/* A B C R(A) := RK(B) - RK(C) */
+OP_MUL,/* A B C R(A) := RK(B) * RK(C) */
+OP_DIV,/* A B C R(A) := RK(B) / RK(C) */
+OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */
+OP_UNM,/* A B R(A) := -R(B) */
+OP_NOT,/* A B R(A) := not R(B) */
+
+OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
+
+OP_JMP,/* sBx PC += sBx */
+
+OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
+OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
+OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
+
+OP_TEST,/* A B C if (R(B) <=> C) then R(A) := R(B) else pc++ */
+
+OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
+OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
+OP_RETURN,/* A B return R(A), ... ,R(A+B-2) (see note) */
+
+OP_FORLOOP,/* A sBx R(A)+=R(A+2); if R(A) <?= R(A+1) then PC+= sBx */
+
+OP_TFORLOOP,/* A C R(A+2), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2));
+ if R(A+2) ~= nil then pc++ */
+OP_TFORPREP,/* A sBx if type(R(A)) == table then R(A+1):=R(A), R(A):=next;
+ PC += sBx */
+
+OP_SETLIST,/* A Bx R(A)[Bx-Bx%FPF+i] := R(A+i), 1 <= i <= Bx%FPF+1 */
+OP_SETLISTO,/* A Bx */
+
+OP_CLOSE,/* A close all variables in the stack up to (>=) R(A)*/
+OP_CLOSURE/* A Bx R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n)) */
+} OpCode;
+
+
+#define NUM_OPCODES (cast(int, OP_CLOSURE+1))
+
+
+
+/*===========================================================================
+ Notes:
+ (1) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1,
+ and can be 0: OP_CALL then sets `top' to last_result+1, so
+ next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'.
+
+ (2) In OP_RETURN, if (B == 0) then return up to `top'
+
+ (3) For comparisons, B specifies what conditions the test should accept.
+
+ (4) All `skips' (pc++) assume that next instruction is a jump
+===========================================================================*/
+
+
+/*
+** masks for instruction properties
+*/
+enum OpModeMask {
+ OpModeBreg = 2, /* B is a register */
+ OpModeBrk, /* B is a register/constant */
+ OpModeCrk, /* C is a register/constant */
+ OpModesetA, /* instruction set register A */
+ OpModeK, /* Bx is a constant */
+ OpModeT /* operator is a test */
+
+};
+
+
+extern const lu_byte luaP_opmodes[NUM_OPCODES];
+
+#define getOpMode(m) (cast(enum OpMode, luaP_opmodes[m] & 3))
+#define testOpMode(m, b) (luaP_opmodes[m] & (1 << (b)))
+
+
+#ifdef LUA_OPNAMES
+extern const char *const luaP_opnames[]; /* opcode names */
+#endif
+
+
+
+/* number of list items to accumulate before a SETLIST instruction */
+/* (must be a power of 2) */
+#define LFIELDS_PER_FLUSH 32
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lparser.c b/plugins/SmartAutoReplier/lualib/lparser.c
new file mode 100644
index 0000000000..c1323ecd2a
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lparser.c
@@ -0,0 +1,1329 @@
+/*
+** $Id: lparser.c,v 1.208 2003/04/03 13:35:34 roberto Exp $
+** Lua Parser
+** See Copyright Notice in lua.h
+*/
+
+
+#include <string.h>
+
+#define lparser_c
+
+#include "lua.h"
+
+#include "lcode.h"
+#include "ldebug.h"
+#include "lfunc.h"
+#include "llex.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lparser.h"
+#include "lstate.h"
+#include "lstring.h"
+
+
+
+
+#define getlocvar(fs, i) ((fs)->f->locvars[(fs)->actvar[i]])
+
+
+#define enterlevel(ls) if (++(ls)->nestlevel > LUA_MAXPARSERLEVEL) \
+ luaX_syntaxerror(ls, "too many syntax levels");
+#define leavelevel(ls) ((ls)->nestlevel--)
+
+
+/*
+** nodes for block list (list of active blocks)
+*/
+typedef struct BlockCnt {
+ struct BlockCnt *previous; /* chain */
+ int breaklist; /* list of jumps out of this loop */
+ int nactvar; /* # active local variables outside the breakable structure */
+ int upval; /* true if some variable in the block is an upvalue */
+ int isbreakable; /* true if `block' is a loop */
+} BlockCnt;
+
+
+
+/*
+** prototypes for recursive non-terminal functions
+*/
+static void chunk (LexState *ls);
+static void expr (LexState *ls, expdesc *v);
+
+
+
+static void next (LexState *ls) {
+ ls->lastline = ls->linenumber;
+ if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */
+ ls->t = ls->lookahead; /* use this one */
+ ls->lookahead.token = TK_EOS; /* and discharge it */
+ }
+ else
+ ls->t.token = luaX_lex(ls, &ls->t.seminfo); /* read next token */
+}
+
+
+static void lookahead (LexState *ls) {
+ lua_assert(ls->lookahead.token == TK_EOS);
+ ls->lookahead.token = luaX_lex(ls, &ls->lookahead.seminfo);
+}
+
+
+static void error_expected (LexState *ls, int token) {
+ luaX_syntaxerror(ls,
+ luaO_pushfstring(ls->L, "`%s' expected", luaX_token2str(ls, token)));
+}
+
+
+static int testnext (LexState *ls, int c) {
+ if (ls->t.token == c) {
+ next(ls);
+ return 1;
+ }
+ else return 0;
+}
+
+
+static void check (LexState *ls, int c) {
+ if (!testnext(ls, c))
+ error_expected(ls, c);
+}
+
+
+#define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
+
+
+
+static void check_match (LexState *ls, int what, int who, int where) {
+ if (!testnext(ls, what)) {
+ if (where == ls->linenumber)
+ error_expected(ls, what);
+ else {
+ luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
+ "`%s' expected (to close `%s' at line %d)",
+ luaX_token2str(ls, what), luaX_token2str(ls, who), where));
+ }
+ }
+}
+
+
+static TString *str_checkname (LexState *ls) {
+ TString *ts;
+ check_condition(ls, (ls->t.token == TK_NAME), "<name> expected");
+ ts = ls->t.seminfo.ts;
+ next(ls);
+ return ts;
+}
+
+
+static void init_exp (expdesc *e, expkind k, int i) {
+ e->f = e->t = NO_JUMP;
+ e->k = k;
+ e->info = i;
+}
+
+
+static void codestring (LexState *ls, expdesc *e, TString *s) {
+ init_exp(e, VK, luaK_stringK(ls->fs, s));
+}
+
+
+static void checkname(LexState *ls, expdesc *e) {
+ codestring(ls, e, str_checkname(ls));
+}
+
+
+static int luaI_registerlocalvar (LexState *ls, TString *varname) {
+ FuncState *fs = ls->fs;
+ Proto *f = fs->f;
+ luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
+ LocVar, MAX_INT, "");
+ f->locvars[fs->nlocvars].varname = varname;
+ return fs->nlocvars++;
+}
+
+
+static void new_localvar (LexState *ls, TString *name, int n) {
+ FuncState *fs = ls->fs;
+ luaX_checklimit(ls, fs->nactvar+n+1, MAXVARS, "local variables");
+ fs->actvar[fs->nactvar+n] = luaI_registerlocalvar(ls, name);
+}
+
+
+static void adjustlocalvars (LexState *ls, int nvars) {
+ FuncState *fs = ls->fs;
+ fs->nactvar += nvars;
+ for (; nvars; nvars--) {
+ getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc;
+ }
+}
+
+
+static void removevars (LexState *ls, int tolevel) {
+ FuncState *fs = ls->fs;
+ while (fs->nactvar > tolevel)
+ getlocvar(fs, --fs->nactvar).endpc = fs->pc;
+}
+
+
+static void new_localvarstr (LexState *ls, const char *name, int n) {
+ new_localvar(ls, luaS_new(ls->L, name), n);
+}
+
+
+static void create_local (LexState *ls, const char *name) {
+ new_localvarstr(ls, name, 0);
+ adjustlocalvars(ls, 1);
+}
+
+
+static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
+ int i;
+ Proto *f = fs->f;
+ for (i=0; i<f->nups; i++) {
+ if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->info) {
+ lua_assert(fs->f->upvalues[i] == name);
+ return i;
+ }
+ }
+ /* new one */
+ luaX_checklimit(fs->ls, f->nups + 1, MAXUPVALUES, "upvalues");
+ luaM_growvector(fs->L, fs->f->upvalues, f->nups, fs->f->sizeupvalues,
+ TString *, MAX_INT, "");
+ fs->f->upvalues[f->nups] = name;
+ fs->upvalues[f->nups] = *v;
+ return f->nups++;
+}
+
+
+static int searchvar (FuncState *fs, TString *n) {
+ int i;
+ for (i=fs->nactvar-1; i >= 0; i--) {
+ if (n == getlocvar(fs, i).varname)
+ return i;
+ }
+ return -1; /* not found */
+}
+
+
+static void markupval (FuncState *fs, int level) {
+ BlockCnt *bl = fs->bl;
+ while (bl && bl->nactvar > level) bl = bl->previous;
+ if (bl) bl->upval = 1;
+}
+
+
+static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
+ if (fs == NULL) /* no more levels? */
+ init_exp(var, VGLOBAL, NO_REG); /* default is global variable */
+ else {
+ int v = searchvar(fs, n); /* look up at current level */
+ if (v >= 0) {
+ init_exp(var, VLOCAL, v);
+ if (!base)
+ markupval(fs, v); /* local will be used as an upval */
+ }
+ else { /* not found at current level; try upper one */
+ singlevaraux(fs->prev, n, var, 0);
+ if (var->k == VGLOBAL) {
+ if (base)
+ var->info = luaK_stringK(fs, n); /* info points to global name */
+ }
+ else { /* LOCAL or UPVAL */
+ var->info = indexupvalue(fs, n, var);
+ var->k = VUPVAL; /* upvalue in this level */
+ }
+ }
+ }
+}
+
+
+static TString *singlevar (LexState *ls, expdesc *var, int base) {
+ TString *varname = str_checkname(ls);
+ singlevaraux(ls->fs, varname, var, base);
+ return varname;
+}
+
+
+static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
+ FuncState *fs = ls->fs;
+ int extra = nvars - nexps;
+ if (e->k == VCALL) {
+ extra++; /* includes call itself */
+ if (extra <= 0) extra = 0;
+ else luaK_reserveregs(fs, extra-1);
+ luaK_setcallreturns(fs, e, extra); /* call provides the difference */
+ }
+ else {
+ if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */
+ if (extra > 0) {
+ int reg = fs->freereg;
+ luaK_reserveregs(fs, extra);
+ luaK_nil(fs, reg, extra);
+ }
+ }
+}
+
+
+static void code_params (LexState *ls, int nparams, int dots) {
+ FuncState *fs = ls->fs;
+ adjustlocalvars(ls, nparams);
+ luaX_checklimit(ls, fs->nactvar, MAXPARAMS, "parameters");
+ fs->f->numparams = cast(lu_byte, fs->nactvar);
+ fs->f->is_vararg = cast(lu_byte, dots);
+ if (dots)
+ create_local(ls, "arg");
+ luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
+}
+
+
+static void enterblock (FuncState *fs, BlockCnt *bl, int isbreakable) {
+ bl->breaklist = NO_JUMP;
+ bl->isbreakable = isbreakable;
+ bl->nactvar = fs->nactvar;
+ bl->upval = 0;
+ bl->previous = fs->bl;
+ fs->bl = bl;
+ lua_assert(fs->freereg == fs->nactvar);
+}
+
+
+static void leaveblock (FuncState *fs) {
+ BlockCnt *bl = fs->bl;
+ fs->bl = bl->previous;
+ removevars(fs->ls, bl->nactvar);
+ if (bl->upval)
+ luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
+ lua_assert(bl->nactvar == fs->nactvar);
+ fs->freereg = fs->nactvar; /* free registers */
+ luaK_patchtohere(fs, bl->breaklist);
+}
+
+
+static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
+ FuncState *fs = ls->fs;
+ Proto *f = fs->f;
+ int i;
+ luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
+ MAXARG_Bx, "constant table overflow");
+ f->p[fs->np++] = func->f;
+ init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
+ for (i=0; i<func->f->nups; i++) {
+ OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
+ luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
+ }
+}
+
+
+static void open_func (LexState *ls, FuncState *fs) {
+ Proto *f = luaF_newproto(ls->L);
+ fs->f = f;
+ fs->prev = ls->fs; /* linked list of funcstates */
+ fs->ls = ls;
+ fs->L = ls->L;
+ ls->fs = fs;
+ fs->pc = 0;
+ fs->lasttarget = 0;
+ fs->jpc = NO_JUMP;
+ fs->freereg = 0;
+ fs->nk = 0;
+ fs->h = luaH_new(ls->L, 0, 0);
+ fs->np = 0;
+ fs->nlocvars = 0;
+ fs->nactvar = 0;
+ fs->bl = NULL;
+ f->source = ls->source;
+ f->maxstacksize = 2; /* registers 0/1 are always valid */
+}
+
+
+static void close_func (LexState *ls) {
+ lua_State *L = ls->L;
+ FuncState *fs = ls->fs;
+ Proto *f = fs->f;
+ removevars(ls, 0);
+ luaK_codeABC(fs, OP_RETURN, 0, 1, 0); /* final return */
+ luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
+ f->sizecode = fs->pc;
+ luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
+ f->sizelineinfo = fs->pc;
+ luaM_reallocvector(L, f->k, f->sizek, fs->nk, TObject);
+ f->sizek = fs->nk;
+ luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
+ f->sizep = fs->np;
+ luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
+ f->sizelocvars = fs->nlocvars;
+ luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
+ f->sizeupvalues = f->nups;
+ lua_assert(luaG_checkcode(f));
+ lua_assert(fs->bl == NULL);
+ ls->fs = fs->prev;
+}
+
+
+Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff) {
+ struct LexState lexstate;
+ struct FuncState funcstate;
+ lexstate.buff = buff;
+ lexstate.nestlevel = 0;
+ luaX_setinput(L, &lexstate, z, luaS_new(L, zname(z)));
+ open_func(&lexstate, &funcstate);
+ next(&lexstate); /* read first token */
+ chunk(&lexstate);
+ check_condition(&lexstate, (lexstate.t.token == TK_EOS), "<eof> expected");
+ close_func(&lexstate);
+ lua_assert(funcstate.prev == NULL);
+ lua_assert(funcstate.f->nups == 0);
+ lua_assert(lexstate.nestlevel == 0);
+ return funcstate.f;
+}
+
+
+
+/*============================================================*/
+/* GRAMMAR RULES */
+/*============================================================*/
+
+
+static void luaY_field (LexState *ls, expdesc *v) {
+ /* field -> ['.' | ':'] NAME */
+ FuncState *fs = ls->fs;
+ expdesc key;
+ luaK_exp2anyreg(fs, v);
+ next(ls); /* skip the dot or colon */
+ checkname(ls, &key);
+ luaK_indexed(fs, v, &key);
+}
+
+
+static void luaY_index (LexState *ls, expdesc *v) {
+ /* index -> '[' expr ']' */
+ next(ls); /* skip the '[' */
+ expr(ls, v);
+ luaK_exp2val(ls->fs, v);
+ check(ls, ']');
+}
+
+
+/*
+** {======================================================================
+** Rules for Constructors
+** =======================================================================
+*/
+
+
+struct ConsControl {
+ expdesc v; /* last list item read */
+ expdesc *t; /* table descriptor */
+ int nh; /* total number of `record' elements */
+ int na; /* total number of array elements */
+ int tostore; /* number of array elements pending to be stored */
+};
+
+
+static void recfield (LexState *ls, struct ConsControl *cc) {
+ /* recfield -> (NAME | `['exp1`]') = exp1 */
+ FuncState *fs = ls->fs;
+ int reg = ls->fs->freereg;
+ expdesc key, val;
+ if (ls->t.token == TK_NAME) {
+ luaX_checklimit(ls, cc->nh, MAX_INT, "items in a constructor");
+ cc->nh++;
+ checkname(ls, &key);
+ }
+ else /* ls->t.token == '[' */
+ luaY_index(ls, &key);
+ check(ls, '=');
+ luaK_exp2RK(fs, &key);
+ expr(ls, &val);
+ luaK_codeABC(fs, OP_SETTABLE, cc->t->info, luaK_exp2RK(fs, &key),
+ luaK_exp2RK(fs, &val));
+ fs->freereg = reg; /* free registers */
+}
+
+
+static void closelistfield (FuncState *fs, struct ConsControl *cc) {
+ if (cc->v.k == VVOID) return; /* there is no list item */
+ luaK_exp2nextreg(fs, &cc->v);
+ cc->v.k = VVOID;
+ if (cc->tostore == LFIELDS_PER_FLUSH) {
+ luaK_codeABx(fs, OP_SETLIST, cc->t->info, cc->na-1); /* flush */
+ cc->tostore = 0; /* no more items pending */
+ fs->freereg = cc->t->info + 1; /* free registers */
+ }
+}
+
+
+static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
+ if (cc->tostore == 0) return;
+ if (cc->v.k == VCALL) {
+ luaK_setcallreturns(fs, &cc->v, LUA_MULTRET);
+ luaK_codeABx(fs, OP_SETLISTO, cc->t->info, cc->na-1);
+ }
+ else {
+ if (cc->v.k != VVOID)
+ luaK_exp2nextreg(fs, &cc->v);
+ luaK_codeABx(fs, OP_SETLIST, cc->t->info, cc->na-1);
+ }
+ fs->freereg = cc->t->info + 1; /* free registers */
+}
+
+
+static void listfield (LexState *ls, struct ConsControl *cc) {
+ expr(ls, &cc->v);
+ luaX_checklimit(ls, cc->na, MAXARG_Bx, "items in a constructor");
+ cc->na++;
+ cc->tostore++;
+}
+
+
+static void constructor (LexState *ls, expdesc *t) {
+ /* constructor -> ?? */
+ FuncState *fs = ls->fs;
+ int line = ls->linenumber;
+ int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
+ struct ConsControl cc;
+ cc.na = cc.nh = cc.tostore = 0;
+ cc.t = t;
+ init_exp(t, VRELOCABLE, pc);
+ init_exp(&cc.v, VVOID, 0); /* no value (yet) */
+ luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */
+ check(ls, '{');
+ do {
+ lua_assert(cc.v.k == VVOID || cc.tostore > 0);
+ testnext(ls, ';'); /* compatibility only */
+ if (ls->t.token == '}') break;
+ closelistfield(fs, &cc);
+ switch(ls->t.token) {
+ case TK_NAME: { /* may be listfields or recfields */
+ lookahead(ls);
+ if (ls->lookahead.token != '=') /* expression? */
+ listfield(ls, &cc);
+ else
+ recfield(ls, &cc);
+ break;
+ }
+ case '[': { /* constructor_item -> recfield */
+ recfield(ls, &cc);
+ break;
+ }
+ default: { /* constructor_part -> listfield */
+ listfield(ls, &cc);
+ break;
+ }
+ }
+ } while (testnext(ls, ',') || testnext(ls, ';'));
+ check_match(ls, '}', '{', line);
+ lastlistfield(fs, &cc);
+ SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
+ SETARG_C(fs->f->code[pc], luaO_log2(cc.nh)+1); /* set initial table size */
+}
+
+/* }====================================================================== */
+
+
+
+static void parlist (LexState *ls) {
+ /* parlist -> [ param { `,' param } ] */
+ int nparams = 0;
+ int dots = 0;
+ if (ls->t.token != ')') { /* is `parlist' not empty? */
+ do {
+ switch (ls->t.token) {
+ case TK_DOTS: dots = 1; next(ls); break;
+ case TK_NAME: new_localvar(ls, str_checkname(ls), nparams++); break;
+ default: luaX_syntaxerror(ls, "<name> or `...' expected");
+ }
+ } while (!dots && testnext(ls, ','));
+ }
+ code_params(ls, nparams, dots);
+}
+
+
+static void body (LexState *ls, expdesc *e, int needself, int line) {
+ /* body -> `(' parlist `)' chunk END */
+ FuncState new_fs;
+ open_func(ls, &new_fs);
+ new_fs.f->lineDefined = line;
+ check(ls, '(');
+ if (needself)
+ create_local(ls, "self");
+ parlist(ls);
+ check(ls, ')');
+ chunk(ls);
+ check_match(ls, TK_END, TK_FUNCTION, line);
+ close_func(ls);
+ pushclosure(ls, &new_fs, e);
+}
+
+
+static int explist1 (LexState *ls, expdesc *v) {
+ /* explist1 -> expr { `,' expr } */
+ int n = 1; /* at least one expression */
+ expr(ls, v);
+ while (testnext(ls, ',')) {
+ luaK_exp2nextreg(ls->fs, v);
+ expr(ls, v);
+ n++;
+ }
+ return n;
+}
+
+
+static void funcargs (LexState *ls, expdesc *f) {
+ FuncState *fs = ls->fs;
+ expdesc args;
+ int base, nparams;
+ int line = ls->linenumber;
+ switch (ls->t.token) {
+ case '(': { /* funcargs -> `(' [ explist1 ] `)' */
+ if (line != ls->lastline)
+ luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
+ next(ls);
+ if (ls->t.token == ')') /* arg list is empty? */
+ args.k = VVOID;
+ else {
+ explist1(ls, &args);
+ luaK_setcallreturns(fs, &args, LUA_MULTRET);
+ }
+ check_match(ls, ')', '(', line);
+ break;
+ }
+ case '{': { /* funcargs -> constructor */
+ constructor(ls, &args);
+ break;
+ }
+ case TK_STRING: { /* funcargs -> STRING */
+ codestring(ls, &args, ls->t.seminfo.ts);
+ next(ls); /* must use `seminfo' before `next' */
+ break;
+ }
+ default: {
+ luaX_syntaxerror(ls, "function arguments expected");
+ return;
+ }
+ }
+ lua_assert(f->k == VNONRELOC);
+ base = f->info; /* base register for call */
+ if (args.k == VCALL)
+ nparams = LUA_MULTRET; /* open call */
+ else {
+ if (args.k != VVOID)
+ luaK_exp2nextreg(fs, &args); /* close last argument */
+ nparams = fs->freereg - (base+1);
+ }
+ init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
+ luaK_fixline(fs, line);
+ fs->freereg = base+1; /* call remove function and arguments and leaves
+ (unless changed) one result */
+}
+
+
+
+
+/*
+** {======================================================================
+** Expression parsing
+** =======================================================================
+*/
+
+
+static void prefixexp (LexState *ls, expdesc *v) {
+ /* prefixexp -> NAME | '(' expr ')' */
+ switch (ls->t.token) {
+ case '(': {
+ int line = ls->linenumber;
+ next(ls);
+ expr(ls, v);
+ check_match(ls, ')', '(', line);
+ luaK_dischargevars(ls->fs, v);
+ return;
+ }
+ case TK_NAME: {
+ singlevar(ls, v, 1);
+ return;
+ }
+#ifdef LUA_COMPATUPSYNTAX
+ case '%': { /* for compatibility only */
+ TString *varname;
+ int line = ls->linenumber;
+ next(ls); /* skip `%' */
+ varname = singlevar(ls, v, 1);
+ if (v->k != VUPVAL)
+ luaX_errorline(ls, "global upvalues are obsolete",
+ getstr(varname), line);
+ return;
+ }
+#endif
+ default: {
+ luaX_syntaxerror(ls, "unexpected symbol");
+ return;
+ }
+ }
+}
+
+
+static void primaryexp (LexState *ls, expdesc *v) {
+ /* primaryexp ->
+ prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
+ FuncState *fs = ls->fs;
+ prefixexp(ls, v);
+ for (;;) {
+ switch (ls->t.token) {
+ case '.': { /* field */
+ luaY_field(ls, v);
+ break;
+ }
+ case '[': { /* `[' exp1 `]' */
+ expdesc key;
+ luaK_exp2anyreg(fs, v);
+ luaY_index(ls, &key);
+ luaK_indexed(fs, v, &key);
+ break;
+ }
+ case ':': { /* `:' NAME funcargs */
+ expdesc key;
+ next(ls);
+ checkname(ls, &key);
+ luaK_self(fs, v, &key);
+ funcargs(ls, v);
+ break;
+ }
+ case '(': case TK_STRING: case '{': { /* funcargs */
+ luaK_exp2nextreg(fs, v);
+ funcargs(ls, v);
+ break;
+ }
+ default: return;
+ }
+ }
+}
+
+
+static void simpleexp (LexState *ls, expdesc *v) {
+ /* simpleexp -> NUMBER | STRING | NIL | constructor | FUNCTION body
+ | primaryexp */
+ switch (ls->t.token) {
+ case TK_NUMBER: {
+ init_exp(v, VK, luaK_numberK(ls->fs, ls->t.seminfo.r));
+ next(ls); /* must use `seminfo' before `next' */
+ break;
+ }
+ case TK_STRING: {
+ codestring(ls, v, ls->t.seminfo.ts);
+ next(ls); /* must use `seminfo' before `next' */
+ break;
+ }
+ case TK_NIL: {
+ init_exp(v, VNIL, 0);
+ next(ls);
+ break;
+ }
+ case TK_TRUE: {
+ init_exp(v, VTRUE, 0);
+ next(ls);
+ break;
+ }
+ case TK_FALSE: {
+ init_exp(v, VFALSE, 0);
+ next(ls);
+ break;
+ }
+ case '{': { /* constructor */
+ constructor(ls, v);
+ break;
+ }
+ case TK_FUNCTION: {
+ next(ls);
+ body(ls, v, 0, ls->linenumber);
+ break;
+ }
+ default: {
+ primaryexp(ls, v);
+ break;
+ }
+ }
+}
+
+
+static UnOpr getunopr (int op) {
+ switch (op) {
+ case TK_NOT: return OPR_NOT;
+ case '-': return OPR_MINUS;
+ default: return OPR_NOUNOPR;
+ }
+}
+
+
+static BinOpr getbinopr (int op) {
+ switch (op) {
+ case '+': return OPR_ADD;
+ case '-': return OPR_SUB;
+ case '*': return OPR_MULT;
+ case '/': return OPR_DIV;
+ case '^': return OPR_POW;
+ case TK_CONCAT: return OPR_CONCAT;
+ case TK_NE: return OPR_NE;
+ case TK_EQ: return OPR_EQ;
+ case '<': return OPR_LT;
+ case TK_LE: return OPR_LE;
+ case '>': return OPR_GT;
+ case TK_GE: return OPR_GE;
+ case TK_AND: return OPR_AND;
+ case TK_OR: return OPR_OR;
+ default: return OPR_NOBINOPR;
+ }
+}
+
+
+static const struct {
+ lu_byte left; /* left priority for each binary operator */
+ lu_byte right; /* right priority */
+} priority[] = { /* ORDER OPR */
+ {6, 6}, {6, 6}, {7, 7}, {7, 7}, /* arithmetic */
+ {10, 9}, {5, 4}, /* power and concat (right associative) */
+ {3, 3}, {3, 3}, /* equality */
+ {3, 3}, {3, 3}, {3, 3}, {3, 3}, /* order */
+ {2, 2}, {1, 1} /* logical (and/or) */
+};
+
+#define UNARY_PRIORITY 8 /* priority for unary operators */
+
+
+/*
+** subexpr -> (simplexep | unop subexpr) { binop subexpr }
+** where `binop' is any binary operator with a priority higher than `limit'
+*/
+static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
+ BinOpr op;
+ UnOpr uop;
+ enterlevel(ls);
+ uop = getunopr(ls->t.token);
+ if (uop != OPR_NOUNOPR) {
+ next(ls);
+ subexpr(ls, v, UNARY_PRIORITY);
+ luaK_prefix(ls->fs, uop, v);
+ }
+ else simpleexp(ls, v);
+ /* expand while operators have priorities higher than `limit' */
+ op = getbinopr(ls->t.token);
+ while (op != OPR_NOBINOPR && cast(int, priority[op].left) > limit) {
+ expdesc v2;
+ BinOpr nextop;
+ next(ls);
+ luaK_infix(ls->fs, op, v);
+ /* read sub-expression with higher priority */
+ nextop = subexpr(ls, &v2, cast(int, priority[op].right));
+ luaK_posfix(ls->fs, op, v, &v2);
+ op = nextop;
+ }
+ leavelevel(ls);
+ return op; /* return first untreated operator */
+}
+
+
+static void expr (LexState *ls, expdesc *v) {
+ subexpr(ls, v, -1);
+}
+
+/* }==================================================================== */
+
+
+
+/*
+** {======================================================================
+** Rules for Statements
+** =======================================================================
+*/
+
+
+static int block_follow (int token) {
+ switch (token) {
+ case TK_ELSE: case TK_ELSEIF: case TK_END:
+ case TK_UNTIL: case TK_EOS:
+ return 1;
+ default: return 0;
+ }
+}
+
+
+static void block (LexState *ls) {
+ /* block -> chunk */
+ FuncState *fs = ls->fs;
+ BlockCnt bl;
+ enterblock(fs, &bl, 0);
+ chunk(ls);
+ lua_assert(bl.breaklist == NO_JUMP);
+ leaveblock(fs);
+}
+
+
+/*
+** structure to chain all variables in the left-hand side of an
+** assignment
+*/
+struct LHS_assign {
+ struct LHS_assign *prev;
+ expdesc v; /* variable (global, local, upvalue, or indexed) */
+};
+
+
+/*
+** check whether, in an assignment to a local variable, the local variable
+** is needed in a previous assignment (to a table). If so, save original
+** local value in a safe place and use this safe copy in the previous
+** assignment.
+*/
+static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
+ FuncState *fs = ls->fs;
+ int extra = fs->freereg; /* eventual position to save local variable */
+ int conflict = 0;
+ for (; lh; lh = lh->prev) {
+ if (lh->v.k == VINDEXED) {
+ if (lh->v.info == v->info) { /* conflict? */
+ conflict = 1;
+ lh->v.info = extra; /* previous assignment will use safe copy */
+ }
+ if (lh->v.aux == v->info) { /* conflict? */
+ conflict = 1;
+ lh->v.aux = extra; /* previous assignment will use safe copy */
+ }
+ }
+ }
+ if (conflict) {
+ luaK_codeABC(fs, OP_MOVE, fs->freereg, v->info, 0); /* make copy */
+ luaK_reserveregs(fs, 1);
+ }
+}
+
+
+static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
+ expdesc e;
+ check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
+ "syntax error");
+ if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
+ struct LHS_assign nv;
+ nv.prev = lh;
+ primaryexp(ls, &nv.v);
+ if (nv.v.k == VLOCAL)
+ check_conflict(ls, lh, &nv.v);
+ assignment(ls, &nv, nvars+1);
+ }
+ else { /* assignment -> `=' explist1 */
+ int nexps;
+ check(ls, '=');
+ nexps = explist1(ls, &e);
+ if (nexps != nvars) {
+ adjust_assign(ls, nvars, nexps, &e);
+ if (nexps > nvars)
+ ls->fs->freereg -= nexps - nvars; /* remove extra values */
+ }
+ else {
+ luaK_setcallreturns(ls->fs, &e, 1); /* close last expression */
+ luaK_storevar(ls->fs, &lh->v, &e);
+ return; /* avoid default */
+ }
+ }
+ init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
+ luaK_storevar(ls->fs, &lh->v, &e);
+}
+
+
+static void cond (LexState *ls, expdesc *v) {
+ /* cond -> exp */
+ expr(ls, v); /* read condition */
+ if (v->k == VNIL) v->k = VFALSE; /* `falses' are all equal here */
+ luaK_goiftrue(ls->fs, v);
+ luaK_patchtohere(ls->fs, v->t);
+}
+
+
+/*
+** The while statement optimizes its code by coding the condition
+** after its body (and thus avoiding one jump in the loop).
+*/
+
+/*
+** maximum size of expressions for optimizing `while' code
+*/
+#ifndef MAXEXPWHILE
+#define MAXEXPWHILE 100
+#endif
+
+/*
+** the call `luaK_goiffalse' may grow the size of an expression by
+** at most this:
+*/
+#define EXTRAEXP 5
+
+static void whilestat (LexState *ls, int line) {
+ /* whilestat -> WHILE cond DO block END */
+ Instruction codeexp[MAXEXPWHILE + EXTRAEXP];
+ int lineexp;
+ int i;
+ int sizeexp;
+ FuncState *fs = ls->fs;
+ int whileinit, blockinit, expinit;
+ expdesc v;
+ BlockCnt bl;
+ next(ls); /* skip WHILE */
+ whileinit = luaK_jump(fs); /* jump to condition (which will be moved) */
+ expinit = luaK_getlabel(fs);
+ expr(ls, &v); /* parse condition */
+ if (v.k == VK) v.k = VTRUE; /* `trues' are all equal here */
+ lineexp = ls->linenumber;
+ luaK_goiffalse(fs, &v);
+ luaK_concat(fs, &v.f, fs->jpc);
+ fs->jpc = NO_JUMP;
+ sizeexp = fs->pc - expinit; /* size of expression code */
+ if (sizeexp > MAXEXPWHILE)
+ luaX_syntaxerror(ls, "`while' condition too complex");
+ for (i = 0; i < sizeexp; i++) /* save `exp' code */
+ codeexp[i] = fs->f->code[expinit + i];
+ fs->pc = expinit; /* remove `exp' code */
+ enterblock(fs, &bl, 1);
+ check(ls, TK_DO);
+ blockinit = luaK_getlabel(fs);
+ block(ls);
+ luaK_patchtohere(fs, whileinit); /* initial jump jumps to here */
+ /* move `exp' back to code */
+ if (v.t != NO_JUMP) v.t += fs->pc - expinit;
+ if (v.f != NO_JUMP) v.f += fs->pc - expinit;
+ for (i=0; i<sizeexp; i++)
+ luaK_code(fs, codeexp[i], lineexp);
+ check_match(ls, TK_END, TK_WHILE, line);
+ leaveblock(fs);
+ luaK_patchlist(fs, v.t, blockinit); /* true conditions go back to loop */
+ luaK_patchtohere(fs, v.f); /* false conditions finish the loop */
+}
+
+
+static void repeatstat (LexState *ls, int line) {
+ /* repeatstat -> REPEAT block UNTIL cond */
+ FuncState *fs = ls->fs;
+ int repeat_init = luaK_getlabel(fs);
+ expdesc v;
+ BlockCnt bl;
+ enterblock(fs, &bl, 1);
+ next(ls);
+ block(ls);
+ check_match(ls, TK_UNTIL, TK_REPEAT, line);
+ cond(ls, &v);
+ luaK_patchlist(fs, v.f, repeat_init);
+ leaveblock(fs);
+}
+
+
+static int exp1 (LexState *ls) {
+ expdesc e;
+ int k;
+ expr(ls, &e);
+ k = e.k;
+ luaK_exp2nextreg(ls->fs, &e);
+ return k;
+}
+
+
+static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
+ BlockCnt bl;
+ FuncState *fs = ls->fs;
+ int prep, endfor;
+ adjustlocalvars(ls, nvars); /* scope for all variables */
+ check(ls, TK_DO);
+ enterblock(fs, &bl, 1); /* loop block */
+ prep = luaK_getlabel(fs);
+ block(ls);
+ luaK_patchtohere(fs, prep-1);
+ endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
+ luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars - 3);
+ luaK_fixline(fs, line); /* pretend that `OP_FOR' starts the loop */
+ luaK_patchlist(fs, (isnum) ? endfor : luaK_jump(fs), prep);
+ leaveblock(fs);
+}
+
+
+static void fornum (LexState *ls, TString *varname, int line) {
+ /* fornum -> NAME = exp1,exp1[,exp1] DO body */
+ FuncState *fs = ls->fs;
+ int base = fs->freereg;
+ new_localvar(ls, varname, 0);
+ new_localvarstr(ls, "(for limit)", 1);
+ new_localvarstr(ls, "(for step)", 2);
+ check(ls, '=');
+ exp1(ls); /* initial value */
+ check(ls, ',');
+ exp1(ls); /* limit */
+ if (testnext(ls, ','))
+ exp1(ls); /* optional step */
+ else { /* default step = 1 */
+ luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
+ luaK_reserveregs(fs, 1);
+ }
+ luaK_codeABC(fs, OP_SUB, fs->freereg - 3, fs->freereg - 3, fs->freereg - 1);
+ luaK_jump(fs);
+ forbody(ls, base, line, 3, 1);
+}
+
+
+static void forlist (LexState *ls, TString *indexname) {
+ /* forlist -> NAME {,NAME} IN explist1 DO body */
+ FuncState *fs = ls->fs;
+ expdesc e;
+ int nvars = 0;
+ int line;
+ int base = fs->freereg;
+ new_localvarstr(ls, "(for generator)", nvars++);
+ new_localvarstr(ls, "(for state)", nvars++);
+ new_localvar(ls, indexname, nvars++);
+ while (testnext(ls, ','))
+ new_localvar(ls, str_checkname(ls), nvars++);
+ check(ls, TK_IN);
+ line = ls->linenumber;
+ adjust_assign(ls, nvars, explist1(ls, &e), &e);
+ luaK_checkstack(fs, 3); /* extra space to call generator */
+ luaK_codeAsBx(fs, OP_TFORPREP, base, NO_JUMP);
+ forbody(ls, base, line, nvars, 0);
+}
+
+
+static void forstat (LexState *ls, int line) {
+ /* forstat -> fornum | forlist */
+ FuncState *fs = ls->fs;
+ TString *varname;
+ BlockCnt bl;
+ enterblock(fs, &bl, 0); /* block to control variable scope */
+ next(ls); /* skip `for' */
+ varname = str_checkname(ls); /* first variable name */
+ switch (ls->t.token) {
+ case '=': fornum(ls, varname, line); break;
+ case ',': case TK_IN: forlist(ls, varname); break;
+ default: luaX_syntaxerror(ls, "`=' or `in' expected");
+ }
+ check_match(ls, TK_END, TK_FOR, line);
+ leaveblock(fs);
+}
+
+
+static void test_then_block (LexState *ls, expdesc *v) {
+ /* test_then_block -> [IF | ELSEIF] cond THEN block */
+ next(ls); /* skip IF or ELSEIF */
+ cond(ls, v);
+ check(ls, TK_THEN);
+ block(ls); /* `then' part */
+}
+
+
+static void ifstat (LexState *ls, int line) {
+ /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
+ FuncState *fs = ls->fs;
+ expdesc v;
+ int escapelist = NO_JUMP;
+ test_then_block(ls, &v); /* IF cond THEN block */
+ while (ls->t.token == TK_ELSEIF) {
+ luaK_concat(fs, &escapelist, luaK_jump(fs));
+ luaK_patchtohere(fs, v.f);
+ test_then_block(ls, &v); /* ELSEIF cond THEN block */
+ }
+ if (ls->t.token == TK_ELSE) {
+ luaK_concat(fs, &escapelist, luaK_jump(fs));
+ luaK_patchtohere(fs, v.f);
+ next(ls); /* skip ELSE (after patch, for correct line info) */
+ block(ls); /* `else' part */
+ }
+ else
+ luaK_concat(fs, &escapelist, v.f);
+ luaK_patchtohere(fs, escapelist);
+ check_match(ls, TK_END, TK_IF, line);
+}
+
+
+static void localfunc (LexState *ls) {
+ expdesc v, b;
+ new_localvar(ls, str_checkname(ls), 0);
+ init_exp(&v, VLOCAL, ls->fs->freereg++);
+ adjustlocalvars(ls, 1);
+ body(ls, &b, 0, ls->linenumber);
+ luaK_storevar(ls->fs, &v, &b);
+}
+
+
+static void localstat (LexState *ls) {
+ /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
+ int nvars = 0;
+ int nexps;
+ expdesc e;
+ do {
+ new_localvar(ls, str_checkname(ls), nvars++);
+ } while (testnext(ls, ','));
+ if (testnext(ls, '='))
+ nexps = explist1(ls, &e);
+ else {
+ e.k = VVOID;
+ nexps = 0;
+ }
+ adjust_assign(ls, nvars, nexps, &e);
+ adjustlocalvars(ls, nvars);
+}
+
+
+static int funcname (LexState *ls, expdesc *v) {
+ /* funcname -> NAME {field} [`:' NAME] */
+ int needself = 0;
+ singlevar(ls, v, 1);
+ while (ls->t.token == '.')
+ luaY_field(ls, v);
+ if (ls->t.token == ':') {
+ needself = 1;
+ luaY_field(ls, v);
+ }
+ return needself;
+}
+
+
+static void funcstat (LexState *ls, int line) {
+ /* funcstat -> FUNCTION funcname body */
+ int needself;
+ expdesc v, b;
+ next(ls); /* skip FUNCTION */
+ needself = funcname(ls, &v);
+ body(ls, &b, needself, line);
+ luaK_storevar(ls->fs, &v, &b);
+ luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
+}
+
+
+static void exprstat (LexState *ls) {
+ /* stat -> func | assignment */
+ FuncState *fs = ls->fs;
+ struct LHS_assign v;
+ primaryexp(ls, &v.v);
+ if (v.v.k == VCALL) { /* stat -> func */
+ luaK_setcallreturns(fs, &v.v, 0); /* call statement uses no results */
+ }
+ else { /* stat -> assignment */
+ v.prev = NULL;
+ assignment(ls, &v, 1);
+ }
+}
+
+
+static void retstat (LexState *ls) {
+ /* stat -> RETURN explist */
+ FuncState *fs = ls->fs;
+ expdesc e;
+ int first, nret; /* registers with returned values */
+ next(ls); /* skip RETURN */
+ if (block_follow(ls->t.token) || ls->t.token == ';')
+ first = nret = 0; /* return no values */
+ else {
+ nret = explist1(ls, &e); /* optional return values */
+ if (e.k == VCALL) {
+ luaK_setcallreturns(fs, &e, LUA_MULTRET);
+ if (nret == 1) { /* tail call? */
+ SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
+ lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
+ }
+ first = fs->nactvar;
+ nret = LUA_MULTRET; /* return all values */
+ }
+ else {
+ if (nret == 1) /* only one single value? */
+ first = luaK_exp2anyreg(fs, &e);
+ else {
+ luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */
+ first = fs->nactvar; /* return all `active' values */
+ lua_assert(nret == fs->freereg - first);
+ }
+ }
+ }
+ luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
+}
+
+
+static void breakstat (LexState *ls) {
+ /* stat -> BREAK [NAME] */
+ FuncState *fs = ls->fs;
+ BlockCnt *bl = fs->bl;
+ int upval = 0;
+ next(ls); /* skip BREAK */
+ while (bl && !bl->isbreakable) {
+ upval |= bl->upval;
+ bl = bl->previous;
+ }
+ if (!bl)
+ luaX_syntaxerror(ls, "no loop to break");
+ if (upval)
+ luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
+ luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
+}
+
+
+static int statement (LexState *ls) {
+ int line = ls->linenumber; /* may be needed for error messages */
+ switch (ls->t.token) {
+ case TK_IF: { /* stat -> ifstat */
+ ifstat(ls, line);
+ return 0;
+ }
+ case TK_WHILE: { /* stat -> whilestat */
+ whilestat(ls, line);
+ return 0;
+ }
+ case TK_DO: { /* stat -> DO block END */
+ next(ls); /* skip DO */
+ block(ls);
+ check_match(ls, TK_END, TK_DO, line);
+ return 0;
+ }
+ case TK_FOR: { /* stat -> forstat */
+ forstat(ls, line);
+ return 0;
+ }
+ case TK_REPEAT: { /* stat -> repeatstat */
+ repeatstat(ls, line);
+ return 0;
+ }
+ case TK_FUNCTION: {
+ funcstat(ls, line); /* stat -> funcstat */
+ return 0;
+ }
+ case TK_LOCAL: { /* stat -> localstat */
+ next(ls); /* skip LOCAL */
+ if (testnext(ls, TK_FUNCTION)) /* local function? */
+ localfunc(ls);
+ else
+ localstat(ls);
+ return 0;
+ }
+ case TK_RETURN: { /* stat -> retstat */
+ retstat(ls);
+ return 1; /* must be last statement */
+ }
+ case TK_BREAK: { /* stat -> breakstat */
+ breakstat(ls);
+ return 1; /* must be last statement */
+ }
+ default: {
+ exprstat(ls);
+ return 0; /* to avoid warnings */
+ }
+ }
+}
+
+
+static void chunk (LexState *ls) {
+ /* chunk -> { stat [`;'] } */
+ int islast = 0;
+ enterlevel(ls);
+ while (!islast && !block_follow(ls->t.token)) {
+ islast = statement(ls);
+ testnext(ls, ';');
+ lua_assert(ls->fs->freereg >= ls->fs->nactvar);
+ ls->fs->freereg = ls->fs->nactvar; /* free registers */
+ }
+ leavelevel(ls);
+}
+
+/* }====================================================================== */
diff --git a/plugins/SmartAutoReplier/lualib/lparser.h b/plugins/SmartAutoReplier/lualib/lparser.h
new file mode 100644
index 0000000000..d6aaaf0e7d
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lparser.h
@@ -0,0 +1,71 @@
+/*
+** $Id: lparser.h,v 1.47 2003/02/11 10:46:24 roberto Exp $
+** Lua Parser
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lparser_h
+#define lparser_h
+
+#include "llimits.h"
+#include "lobject.h"
+#include "ltable.h"
+#include "lzio.h"
+
+
+/*
+** Expression descriptor
+*/
+
+typedef enum {
+ VVOID, /* no value */
+ VNIL,
+ VTRUE,
+ VFALSE,
+ VK, /* info = index of constant in `k' */
+ VLOCAL, /* info = local register */
+ VUPVAL, /* info = index of upvalue in `upvalues' */
+ VGLOBAL, /* info = index of table; aux = index of global name in `k' */
+ VINDEXED, /* info = table register; aux = index register (or `k') */
+ VJMP, /* info = instruction pc */
+ VRELOCABLE, /* info = instruction pc */
+ VNONRELOC, /* info = result register */
+ VCALL /* info = result register */
+} expkind;
+
+typedef struct expdesc {
+ expkind k;
+ int info, aux;
+ int t; /* patch list of `exit when true' */
+ int f; /* patch list of `exit when false' */
+} expdesc;
+
+
+struct BlockCnt; /* defined in lparser.c */
+
+
+/* state needed to generate code for a given function */
+typedef struct FuncState {
+ Proto *f; /* current function header */
+ Table *h; /* table to find (and reuse) elements in `k' */
+ struct FuncState *prev; /* enclosing function */
+ struct LexState *ls; /* lexical state */
+ struct lua_State *L; /* copy of the Lua state */
+ struct BlockCnt *bl; /* chain of current blocks */
+ int pc; /* next position to code (equivalent to `ncode') */
+ int lasttarget; /* `pc' of last `jump target' */
+ int jpc; /* list of pending jumps to `pc' */
+ int freereg; /* first free register */
+ int nk; /* number of elements in `k' */
+ int np; /* number of elements in `p' */
+ int nlocvars; /* number of elements in `locvars' */
+ int nactvar; /* number of active local variables */
+ expdesc upvalues[MAXUPVALUES]; /* upvalues */
+ int actvar[MAXVARS]; /* declared-variable stack */
+} FuncState;
+
+
+Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lstate.c b/plugins/SmartAutoReplier/lualib/lstate.c
new file mode 100644
index 0000000000..b593658def
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lstate.c
@@ -0,0 +1,220 @@
+/*
+** $Id: lstate.c,v 1.123 2003/04/03 13:35:34 roberto Exp $
+** Global State
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stdlib.h>
+
+#define lstate_c
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lgc.h"
+#include "llex.h"
+#include "lmem.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+
+
+/*
+** macro to allow the inclusion of user information in Lua state
+*/
+#ifndef LUA_USERSTATE
+#define EXTRASPACE 0
+#else
+union UEXTRASPACE {L_Umaxalign a; LUA_USERSTATE b;};
+#define EXTRASPACE (sizeof(union UEXTRASPACE))
+#endif
+
+
+
+/*
+** you can change this function through the official API:
+** call `lua_setpanicf'
+*/
+static int default_panic (lua_State *L) {
+ UNUSED(L);
+ return 0;
+}
+
+
+static lua_State *mallocstate (lua_State *L) {
+ lu_byte *block = (lu_byte *)luaM_malloc(L, sizeof(lua_State) + EXTRASPACE);
+ if (block == NULL) return NULL;
+ else {
+ block += EXTRASPACE;
+ return cast(lua_State *, block);
+ }
+}
+
+
+static void freestate (lua_State *L, lua_State *L1) {
+ luaM_free(L, cast(lu_byte *, L1) - EXTRASPACE,
+ sizeof(lua_State) + EXTRASPACE);
+}
+
+
+static void stack_init (lua_State *L1, lua_State *L) {
+ L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TObject);
+ L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK;
+ L1->top = L1->stack;
+ L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1;
+ L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo);
+ L1->ci = L1->base_ci;
+ L1->ci->state = CI_C; /* not a Lua function */
+ setnilvalue(L1->top++); /* `function' entry for this `ci' */
+ L1->base = L1->ci->base = L1->top;
+ L1->ci->top = L1->top + LUA_MINSTACK;
+ L1->size_ci = BASIC_CI_SIZE;
+ L1->end_ci = L1->base_ci + L1->size_ci;
+}
+
+
+static void freestack (lua_State *L, lua_State *L1) {
+ luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo);
+ luaM_freearray(L, L1->stack, L1->stacksize, TObject);
+}
+
+
+/*
+** open parts that may cause memory-allocation errors
+*/
+static void f_luaopen (lua_State *L, void *ud) {
+ /* create a new global state */
+ global_State *g = luaM_new(NULL, global_State);
+ UNUSED(ud);
+ if (g == NULL) luaD_throw(L, LUA_ERRMEM);
+ L->l_G = g;
+ g->mainthread = L;
+ g->GCthreshold = 0; /* mark it as unfinished state */
+ g->strt.size = 0;
+ g->strt.nuse = 0;
+ g->strt.hash = NULL;
+ setnilvalue(defaultmeta(L));
+ setnilvalue(registry(L));
+ luaZ_initbuffer(L, &g->buff);
+ g->panic = default_panic;
+ g->rootgc = NULL;
+ g->rootudata = NULL;
+ g->tmudata = NULL;
+ setnilvalue(gkey(g->dummynode));
+ setnilvalue(gval(g->dummynode));
+ g->dummynode->next = NULL;
+ g->nblocks = sizeof(lua_State) + sizeof(global_State);
+ stack_init(L, L); /* init stack */
+ /* create default meta table with a dummy table, and then close the loop */
+ defaultmeta(L)->tt = LUA_TTABLE;
+ sethvalue(defaultmeta(L), luaH_new(L, 0, 0));
+ hvalue(defaultmeta(L))->metatable = hvalue(defaultmeta(L));
+ sethvalue(gt(L), luaH_new(L, 0, 4)); /* table of globals */
+ sethvalue(registry(L), luaH_new(L, 4, 4)); /* registry */
+ luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */
+ luaT_init(L);
+ luaX_init(L);
+ luaS_fix(luaS_newliteral(L, MEMERRMSG));
+ g->GCthreshold = 4*G(L)->nblocks;
+}
+
+
+static void preinit_state (lua_State *L) {
+ L->stack = NULL;
+ L->stacksize = 0;
+ L->errorJmp = NULL;
+ L->hook = NULL;
+ L->hookmask = L->hookinit = 0;
+ L->basehookcount = 0;
+ L->allowhook = 1;
+ resethookcount(L);
+ L->openupval = NULL;
+ L->size_ci = 0;
+ L->nCcalls = 0;
+ L->base_ci = L->ci = NULL;
+ L->errfunc = 0;
+ setnilvalue(gt(L));
+}
+
+
+static void close_state (lua_State *L) {
+ luaF_close(L, L->stack); /* close all upvalues for this thread */
+ if (G(L)) { /* close global state */
+ luaC_sweep(L, 1); /* collect all elements */
+ lua_assert(G(L)->rootgc == NULL);
+ lua_assert(G(L)->rootudata == NULL);
+ luaS_freeall(L);
+ luaZ_freebuffer(L, &G(L)->buff);
+ }
+ freestack(L, L);
+ if (G(L)) {
+ lua_assert(G(L)->nblocks == sizeof(lua_State) + sizeof(global_State));
+ luaM_freelem(NULL, G(L));
+ }
+ freestate(NULL, L);
+}
+
+
+lua_State *luaE_newthread (lua_State *L) {
+ lua_State *L1 = mallocstate(L);
+ luaC_link(L, valtogco(L1), LUA_TTHREAD);
+ preinit_state(L1);
+ L1->l_G = L->l_G;
+ stack_init(L1, L); /* init stack */
+ setobj2n(gt(L1), gt(L)); /* share table of globals */
+ return L1;
+}
+
+
+void luaE_freethread (lua_State *L, lua_State *L1) {
+ luaF_close(L1, L1->stack); /* close all upvalues for this thread */
+ lua_assert(L1->openupval == NULL);
+ freestack(L, L1);
+ freestate(L, L1);
+}
+
+
+LUA_API lua_State *lua_open (void) {
+ lua_State *L = mallocstate(NULL);
+ if (L) { /* allocation OK? */
+ L->tt = LUA_TTHREAD;
+ L->marked = 0;
+ L->next = L->gclist = NULL;
+ preinit_state(L);
+ L->l_G = NULL;
+ if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) {
+ /* memory allocation error: free partial state */
+ close_state(L);
+ L = NULL;
+ }
+ }
+ lua_userstateopen(L);
+ return L;
+}
+
+
+static void callallgcTM (lua_State *L, void *ud) {
+ UNUSED(ud);
+ luaC_callGCTM(L); /* call GC metamethods for all udata */
+}
+
+
+LUA_API void lua_close (lua_State *L) {
+ lua_lock(L);
+ L = G(L)->mainthread; /* only the main thread can be closed */
+ luaF_close(L, L->stack); /* close all upvalues for this thread */
+ luaC_separateudata(L); /* separate udata that have GC metamethods */
+ L->errfunc = 0; /* no error function during GC metamethods */
+ do { /* repeat until no more errors */
+ L->ci = L->base_ci;
+ L->base = L->top = L->ci->base;
+ L->nCcalls = 0;
+ } while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0);
+ lua_assert(G(L)->tmudata == NULL);
+ close_state(L);
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lstate.h b/plugins/SmartAutoReplier/lualib/lstate.h
new file mode 100644
index 0000000000..5422f1b196
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lstate.h
@@ -0,0 +1,195 @@
+/*
+** $Id: lstate.h,v 1.109 2003/02/27 11:52:30 roberto Exp $
+** Global State
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lstate_h
+#define lstate_h
+
+#include "lua.h"
+
+#include "lobject.h"
+#include "ltm.h"
+#include "lzio.h"
+
+
+/*
+** macros for thread synchronization inside Lua core machine:
+** all accesses to the global state and to global objects are synchronized.
+** Because threads can read the stack of other threads
+** (when running garbage collection),
+** a thread must also synchronize any write-access to its own stack.
+** Unsynchronized accesses are allowed only when reading its own stack,
+** or when reading immutable fields from global objects
+** (such as string values and udata values).
+*/
+#ifndef lua_lock
+#define lua_lock(L) ((void) 0)
+#endif
+
+#ifndef lua_unlock
+#define lua_unlock(L) ((void) 0)
+#endif
+
+
+#ifndef lua_userstateopen
+#define lua_userstateopen(l)
+#endif
+
+
+
+struct lua_longjmp; /* defined in ldo.c */
+
+
+/* default meta table (both for tables and udata) */
+#define defaultmeta(L) (&G(L)->_defaultmeta)
+
+/* table of globals */
+#define gt(L) (&L->_gt)
+
+/* registry */
+#define registry(L) (&G(L)->_registry)
+
+
+/* extra stack space to handle TM calls and some other extras */
+#define EXTRA_STACK 5
+
+
+#define BASIC_CI_SIZE 8
+
+#define BASIC_STACK_SIZE (2*LUA_MINSTACK)
+
+
+
+typedef struct stringtable {
+ GCObject **hash;
+ ls_nstr nuse; /* number of elements */
+ int size;
+} stringtable;
+
+
+/*
+** informations about a call
+*/
+typedef struct CallInfo {
+ StkId base; /* base for called function */
+ StkId top; /* top for this function */
+ int state; /* bit fields; see below */
+ union {
+ struct { /* for Lua functions */
+ const Instruction *savedpc;
+ const Instruction **pc; /* points to `pc' variable in `luaV_execute' */
+ int tailcalls; /* number of tail calls lost under this entry */
+ } l;
+ struct { /* for C functions */
+ int dummy; /* just to avoid an empty struct */
+ } c;
+ } u;
+} CallInfo;
+
+
+/*
+** bit fields for `CallInfo.state'
+*/
+#define CI_C (1<<0) /* 1 if function is a C function */
+/* 1 if (Lua) function has an active `luaV_execute' running it */
+#define CI_HASFRAME (1<<1)
+/* 1 if Lua function is calling another Lua function (and therefore its
+ `pc' is being used by the other, and therefore CI_SAVEDPC is 1 too) */
+#define CI_CALLING (1<<2)
+#define CI_SAVEDPC (1<<3) /* 1 if `savedpc' is updated */
+#define CI_YIELD (1<<4) /* 1 if thread is suspended */
+
+
+#define ci_func(ci) (clvalue((ci)->base - 1))
+
+
+/*
+** `global state', shared by all threads of this state
+*/
+typedef struct global_State {
+ stringtable strt; /* hash table for strings */
+ GCObject *rootgc; /* list of (almost) all collectable objects */
+ GCObject *rootudata; /* (separated) list of all userdata */
+ GCObject *tmudata; /* list of userdata to be GC */
+ Mbuffer buff; /* temporary buffer for string concatentation */
+ lu_mem GCthreshold;
+ lu_mem nblocks; /* number of `bytes' currently allocated */
+ lua_CFunction panic; /* to be called in unprotected errors */
+ TObject _registry;
+ TObject _defaultmeta;
+ struct lua_State *mainthread;
+ Node dummynode[1]; /* common node array for all empty tables */
+ TString *tmname[TM_N]; /* array with tag-method names */
+} global_State;
+
+
+/*
+** `per thread' state
+*/
+struct lua_State {
+ CommonHeader;
+ StkId top; /* first free slot in the stack */
+ StkId base; /* base of current function */
+ global_State *l_G;
+ CallInfo *ci; /* call info for current function */
+ StkId stack_last; /* last free slot in the stack */
+ StkId stack; /* stack base */
+ int stacksize;
+ CallInfo *end_ci; /* points after end of ci array*/
+ CallInfo *base_ci; /* array of CallInfo's */
+ unsigned short size_ci; /* size of array `base_ci' */
+ unsigned short nCcalls; /* number of nested C calls */
+ lu_byte hookmask;
+ lu_byte allowhook;
+ lu_byte hookinit;
+ int basehookcount;
+ int hookcount;
+ lua_Hook hook;
+ TObject _gt; /* table of globals */
+ GCObject *openupval; /* list of open upvalues in this stack */
+ GCObject *gclist;
+ struct lua_longjmp *errorJmp; /* current error recover point */
+ ptrdiff_t errfunc; /* current error handling function (stack index) */
+};
+
+
+#define G(L) (L->l_G)
+
+
+/*
+** Union of all collectable objects
+*/
+union GCObject {
+ GCheader gch;
+ union TString ts;
+ union Udata u;
+ union Closure cl;
+ struct Table h;
+ struct Proto p;
+ struct UpVal uv;
+ struct lua_State th; /* thread */
+};
+
+
+/* macros to convert a GCObject into a specific value */
+#define gcotots(o) check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts))
+#define gcotou(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u))
+#define gcotocl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl))
+#define gcotoh(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h))
+#define gcotop(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p))
+#define gcotouv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv))
+#define ngcotouv(o) \
+ check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv))
+#define gcototh(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th))
+
+/* macro to convert any value into a GCObject */
+#define valtogco(v) (cast(GCObject *, (v)))
+
+
+lua_State *luaE_newthread (lua_State *L);
+void luaE_freethread (lua_State *L, lua_State *L1);
+
+#endif
+
diff --git a/plugins/SmartAutoReplier/lualib/lstring.c b/plugins/SmartAutoReplier/lualib/lstring.c
new file mode 100644
index 0000000000..8cbddbd218
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lstring.c
@@ -0,0 +1,102 @@
+/*
+** $Id: lstring.c,v 1.78 2002/12/04 17:38:31 roberto Exp $
+** String table (keeps all strings handled by Lua)
+** See Copyright Notice in lua.h
+*/
+
+
+#include <string.h>
+
+#define lstring_c
+
+#include "lua.h"
+
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+#include "lstring.h"
+
+
+
+void luaS_freeall (lua_State *L) {
+ lua_assert(G(L)->strt.nuse==0);
+ luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *);
+}
+
+
+void luaS_resize (lua_State *L, int newsize) {
+ GCObject **newhash = luaM_newvector(L, newsize, GCObject *);
+ stringtable *tb = &G(L)->strt;
+ int i;
+ for (i=0; i<newsize; i++) newhash[i] = NULL;
+ /* rehash */
+ for (i=0; i<tb->size; i++) {
+ GCObject *p = tb->hash[i];
+ while (p) { /* for each node in the list */
+ GCObject *next = p->gch.next; /* save next */
+ lu_hash h = gcotots(p)->tsv.hash;
+ int h1 = lmod(h, newsize); /* new position */
+ lua_assert(cast(int, h%newsize) == lmod(h, newsize));
+ p->gch.next = newhash[h1]; /* chain it */
+ newhash[h1] = p;
+ p = next;
+ }
+ }
+ luaM_freearray(L, tb->hash, tb->size, TString *);
+ tb->size = newsize;
+ tb->hash = newhash;
+}
+
+
+static TString *newlstr (lua_State *L, const char *str, size_t l, lu_hash h) {
+ TString *ts = cast(TString *, luaM_malloc(L, sizestring(l)));
+ stringtable *tb;
+ ts->tsv.len = l;
+ ts->tsv.hash = h;
+ ts->tsv.marked = 0;
+ ts->tsv.tt = LUA_TSTRING;
+ ts->tsv.reserved = 0;
+ memcpy(ts+1, str, l*sizeof(char));
+ ((char *)(ts+1))[l] = '\0'; /* ending 0 */
+ tb = &G(L)->strt;
+ h = lmod(h, tb->size);
+ ts->tsv.next = tb->hash[h]; /* chain new entry */
+ tb->hash[h] = valtogco(ts);
+ tb->nuse++;
+ if (tb->nuse > cast(ls_nstr, tb->size) && tb->size <= MAX_INT/2)
+ luaS_resize(L, tb->size*2); /* too crowded */
+ return ts;
+}
+
+
+TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
+ GCObject *o;
+ lu_hash h = (lu_hash)l; /* seed */
+ size_t step = (l>>5)+1; /* if string is too long, don't hash all its chars */
+ size_t l1;
+ for (l1=l; l1>=step; l1-=step) /* compute hash */
+ h = h ^ ((h<<5)+(h>>2)+(unsigned char)(str[l1-1]));
+ for (o = G(L)->strt.hash[lmod(h, G(L)->strt.size)];
+ o != NULL;
+ o = o->gch.next) {
+ TString *ts = gcotots(o);
+ if (ts->tsv.len == l && (memcmp(str, getstr(ts), l) == 0))
+ return ts;
+ }
+ return newlstr(L, str, l, h); /* not found */
+}
+
+
+Udata *luaS_newudata (lua_State *L, size_t s) {
+ Udata *u;
+ u = cast(Udata *, luaM_malloc(L, sizeudata(s)));
+ u->uv.marked = (1<<1); /* is not finalized */
+ u->uv.tt = LUA_TUSERDATA;
+ u->uv.len = s;
+ u->uv.metatable = hvalue(defaultmeta(L));
+ /* chain it on udata list */
+ u->uv.next = G(L)->rootudata;
+ G(L)->rootudata = valtogco(u);
+ return u;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lstring.h b/plugins/SmartAutoReplier/lualib/lstring.h
new file mode 100644
index 0000000000..be5a1e3767
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lstring.h
@@ -0,0 +1,33 @@
+/*
+** $Id: lstring.h,v 1.37 2002/08/16 14:45:55 roberto Exp $
+** String table (keep all strings handled by Lua)
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lstring_h
+#define lstring_h
+
+
+#include "lobject.h"
+#include "lstate.h"
+
+
+
+#define sizestring(l) (cast(lu_mem, sizeof(union TString))+ \
+ (cast(lu_mem, l)+1)*sizeof(char))
+
+#define sizeudata(l) (cast(lu_mem, sizeof(union Udata))+(l))
+
+#define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s)))
+#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
+ (sizeof(s)/sizeof(char))-1))
+
+#define luaS_fix(s) ((s)->tsv.marked |= (1<<4))
+
+void luaS_resize (lua_State *L, int newsize);
+Udata *luaS_newudata (lua_State *L, size_t s);
+void luaS_freeall (lua_State *L);
+TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lstrlib.c b/plugins/SmartAutoReplier/lualib/lstrlib.c
new file mode 100644
index 0000000000..8752e3aba3
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lstrlib.c
@@ -0,0 +1,770 @@
+/*
+** $Id: lstrlib.c,v 1.98 2003/04/03 13:35:34 roberto Exp $
+** Standard library for string operations and pattern-matching
+** See Copyright Notice in lua.h
+*/
+
+
+#include <ctype.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define lstrlib_c
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+/* macro to `unsign' a character */
+#ifndef uchar
+#define uchar(c) ((unsigned char)(c))
+#endif
+
+
+typedef long sint32; /* a signed version for size_t */
+
+
+static int str_len (lua_State *L) {
+ size_t l;
+ luaL_checklstring(L, 1, &l);
+ lua_pushnumber(L, (lua_Number)l);
+ return 1;
+}
+
+
+static sint32 posrelat (sint32 pos, size_t len) {
+ /* relative string position: negative means back from end */
+ return (pos>=0) ? pos : (sint32)len+pos+1;
+}
+
+
+static int str_sub (lua_State *L) {
+ size_t l;
+ const char *s = luaL_checklstring(L, 1, &l);
+ sint32 start = posrelat(luaL_checklong(L, 2), l);
+ sint32 end = posrelat(luaL_optlong(L, 3, -1), l);
+ if (start < 1) start = 1;
+ if (end > (sint32)l) end = (sint32)l;
+ if (start <= end)
+ lua_pushlstring(L, s+start-1, end-start+1);
+ else lua_pushliteral(L, "");
+ return 1;
+}
+
+
+static int str_lower (lua_State *L) {
+ size_t l;
+ size_t i;
+ luaL_Buffer b;
+ const char *s = luaL_checklstring(L, 1, &l);
+ luaL_buffinit(L, &b);
+ for (i=0; i<l; i++)
+ luaL_putchar(&b, tolower(uchar(s[i])));
+ luaL_pushresult(&b);
+ return 1;
+}
+
+
+static int str_upper (lua_State *L) {
+ size_t l;
+ size_t i;
+ luaL_Buffer b;
+ const char *s = luaL_checklstring(L, 1, &l);
+ luaL_buffinit(L, &b);
+ for (i=0; i<l; i++)
+ luaL_putchar(&b, toupper(uchar(s[i])));
+ luaL_pushresult(&b);
+ return 1;
+}
+
+static int str_rep (lua_State *L) {
+ size_t l;
+ luaL_Buffer b;
+ const char *s = luaL_checklstring(L, 1, &l);
+ int n = luaL_checkint(L, 2);
+ luaL_buffinit(L, &b);
+ while (n-- > 0)
+ luaL_addlstring(&b, s, l);
+ luaL_pushresult(&b);
+ return 1;
+}
+
+
+static int str_byte (lua_State *L) {
+ size_t l;
+ const char *s = luaL_checklstring(L, 1, &l);
+ sint32 pos = posrelat(luaL_optlong(L, 2, 1), l);
+ if (pos <= 0 || (size_t)(pos) > l) /* index out of range? */
+ return 0; /* no answer */
+ lua_pushnumber(L, uchar(s[pos-1]));
+ return 1;
+}
+
+
+static int str_char (lua_State *L) {
+ int n = lua_gettop(L); /* number of arguments */
+ int i;
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
+ for (i=1; i<=n; i++) {
+ int c = luaL_checkint(L, i);
+ luaL_argcheck(L, uchar(c) == c, i, "invalid value");
+ luaL_putchar(&b, uchar(c));
+ }
+ luaL_pushresult(&b);
+ return 1;
+}
+
+
+static int writer (lua_State *L, const void* b, size_t size, void* B) {
+ (void)L;
+ luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
+ return 1;
+}
+
+
+static int str_dump (lua_State *L) {
+ luaL_Buffer b;
+ luaL_checktype(L, 1, LUA_TFUNCTION);
+ luaL_buffinit(L,&b);
+ if (!lua_dump(L, writer, &b))
+ luaL_error(L, "unable to dump given function");
+ luaL_pushresult(&b);
+ return 1;
+}
+
+
+
+/*
+** {======================================================
+** PATTERN MATCHING
+** =======================================================
+*/
+
+#ifndef MAX_CAPTURES
+#define MAX_CAPTURES 32 /* arbitrary limit */
+#endif
+
+
+#define CAP_UNFINISHED (-1)
+#define CAP_POSITION (-2)
+
+typedef struct MatchState {
+ const char *src_init; /* init of source string */
+ const char *src_end; /* end (`\0') of source string */
+ lua_State *L;
+ int level; /* total number of captures (finished or unfinished) */
+ struct {
+ const char *init;
+ sint32 len;
+ } capture[MAX_CAPTURES];
+} MatchState;
+
+
+#define ESC '%'
+#define SPECIALS "^$*+?.([%-"
+
+
+static int check_capture (MatchState *ms, int l) {
+ l -= '1';
+ if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
+ return luaL_error(ms->L, "invalid capture index");
+ return l;
+}
+
+
+static int capture_to_close (MatchState *ms) {
+ int level = ms->level;
+ for (level--; level>=0; level--)
+ if (ms->capture[level].len == CAP_UNFINISHED) return level;
+ return luaL_error(ms->L, "invalid pattern capture");
+}
+
+
+static const char *luaI_classend (MatchState *ms, const char *p) {
+ switch (*p++) {
+ case ESC: {
+ if (*p == '\0')
+ luaL_error(ms->L, "malformed pattern (ends with `%')");
+ return p+1;
+ }
+ case '[': {
+ if (*p == '^') p++;
+ do { /* look for a `]' */
+ if (*p == '\0')
+ luaL_error(ms->L, "malformed pattern (missing `]')");
+ if (*(p++) == ESC && *p != '\0')
+ p++; /* skip escapes (e.g. `%]') */
+ } while (*p != ']');
+ return p+1;
+ }
+ default: {
+ return p;
+ }
+ }
+}
+
+
+static int match_class (int c, int cl) {
+ int res;
+ switch (tolower(cl)) {
+ case 'a' : res = isalpha(c); break;
+ case 'c' : res = iscntrl(c); break;
+ case 'd' : res = isdigit(c); break;
+ case 'l' : res = islower(c); break;
+ case 'p' : res = ispunct(c); break;
+ case 's' : res = isspace(c); break;
+ case 'u' : res = isupper(c); break;
+ case 'w' : res = isalnum(c); break;
+ case 'x' : res = isxdigit(c); break;
+ case 'z' : res = (c == 0); break;
+ default: return (cl == c);
+ }
+ return (islower(cl) ? res : !res);
+}
+
+
+static int matchbracketclass (int c, const char *p, const char *ec) {
+ int sig = 1;
+ if (*(p+1) == '^') {
+ sig = 0;
+ p++; /* skip the `^' */
+ }
+ while (++p < ec) {
+ if (*p == ESC) {
+ p++;
+ if (match_class(c, *p))
+ return sig;
+ }
+ else if ((*(p+1) == '-') && (p+2 < ec)) {
+ p+=2;
+ if (uchar(*(p-2)) <= c && c <= uchar(*p))
+ return sig;
+ }
+ else if (uchar(*p) == c) return sig;
+ }
+ return !sig;
+}
+
+
+static int luaI_singlematch (int c, const char *p, const char *ep) {
+ switch (*p) {
+ case '.': return 1; /* matches any char */
+ case ESC: return match_class(c, *(p+1));
+ case '[': return matchbracketclass(c, p, ep-1);
+ default: return (uchar(*p) == c);
+ }
+}
+
+
+static const char *match (MatchState *ms, const char *s, const char *p);
+
+
+static const char *matchbalance (MatchState *ms, const char *s,
+ const char *p) {
+ if (*p == 0 || *(p+1) == 0)
+ luaL_error(ms->L, "unbalanced pattern");
+ if (*s != *p) return NULL;
+ else {
+ int b = *p;
+ int e = *(p+1);
+ int cont = 1;
+ while (++s < ms->src_end) {
+ if (*s == e) {
+ if (--cont == 0) return s+1;
+ }
+ else if (*s == b) cont++;
+ }
+ }
+ return NULL; /* string ends out of balance */
+}
+
+
+static const char *max_expand (MatchState *ms, const char *s,
+ const char *p, const char *ep) {
+ sint32 i = 0; /* counts maximum expand for item */
+ while ((s+i)<ms->src_end && luaI_singlematch(uchar(*(s+i)), p, ep))
+ i++;
+ /* keeps trying to match with the maximum repetitions */
+ while (i>=0) {
+ const char *res = match(ms, (s+i), ep+1);
+ if (res) return res;
+ i--; /* else didn't match; reduce 1 repetition to try again */
+ }
+ return NULL;
+}
+
+
+static const char *min_expand (MatchState *ms, const char *s,
+ const char *p, const char *ep) {
+ for (;;) {
+ const char *res = match(ms, s, ep+1);
+ if (res != NULL)
+ return res;
+ else if (s<ms->src_end && luaI_singlematch(uchar(*s), p, ep))
+ s++; /* try with one more repetition */
+ else return NULL;
+ }
+}
+
+
+static const char *start_capture (MatchState *ms, const char *s,
+ const char *p, int what) {
+ const char *res;
+ int level = ms->level;
+ if (level >= MAX_CAPTURES) luaL_error(ms->L, "too many captures");
+ ms->capture[level].init = s;
+ ms->capture[level].len = what;
+ ms->level = level+1;
+ if ((res=match(ms, s, p)) == NULL) /* match failed? */
+ ms->level--; /* undo capture */
+ return res;
+}
+
+
+static const char *end_capture (MatchState *ms, const char *s,
+ const char *p) {
+ int l = capture_to_close(ms);
+ const char *res;
+ ms->capture[l].len = s - ms->capture[l].init; /* close capture */
+ if ((res = match(ms, s, p)) == NULL) /* match failed? */
+ ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
+ return res;
+}
+
+
+static const char *match_capture (MatchState *ms, const char *s, int l) {
+ size_t len;
+ l = check_capture(ms, l);
+ len = ms->capture[l].len;
+ if ((size_t)(ms->src_end-s) >= len &&
+ memcmp(ms->capture[l].init, s, len) == 0)
+ return s+len;
+ else return NULL;
+}
+
+
+static const char *match (MatchState *ms, const char *s, const char *p) {
+ init: /* using goto's to optimize tail recursion */
+ switch (*p) {
+ case '(': { /* start capture */
+ if (*(p+1) == ')') /* position capture? */
+ return start_capture(ms, s, p+2, CAP_POSITION);
+ else
+ return start_capture(ms, s, p+1, CAP_UNFINISHED);
+ }
+ case ')': { /* end capture */
+ return end_capture(ms, s, p+1);
+ }
+ case ESC: {
+ switch (*(p+1)) {
+ case 'b': { /* balanced string? */
+ s = matchbalance(ms, s, p+2);
+ if (s == NULL) return NULL;
+ p+=4; goto init; /* else return match(ms, s, p+4); */
+ }
+ case 'f': { /* frontier? */
+ const char *ep; char previous;
+ p += 2;
+ if (*p != '[')
+ luaL_error(ms->L, "missing `[' after `%%f' in pattern");
+ ep = luaI_classend(ms, p); /* points to what is next */
+ previous = (s == ms->src_init) ? '\0' : *(s-1);
+ if (matchbracketclass(uchar(previous), p, ep-1) ||
+ !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
+ p=ep; goto init; /* else return match(ms, s, ep); */
+ }
+ default: {
+ if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */
+ s = match_capture(ms, s, *(p+1));
+ if (s == NULL) return NULL;
+ p+=2; goto init; /* else return match(ms, s, p+2) */
+ }
+ goto dflt; /* case default */
+ }
+ }
+ }
+ case '\0': { /* end of pattern */
+ return s; /* match succeeded */
+ }
+ case '$': {
+ if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
+ return (s == ms->src_end) ? s : NULL; /* check end of string */
+ else goto dflt;
+ }
+ default: dflt: { /* it is a pattern item */
+ const char *ep = luaI_classend(ms, p); /* points to what is next */
+ int m = s<ms->src_end && luaI_singlematch(uchar(*s), p, ep);
+ switch (*ep) {
+ case '?': { /* optional */
+ const char *res;
+ if (m && ((res=match(ms, s+1, ep+1)) != NULL))
+ return res;
+ p=ep+1; goto init; /* else return match(ms, s, ep+1); */
+ }
+ case '*': { /* 0 or more repetitions */
+ return max_expand(ms, s, p, ep);
+ }
+ case '+': { /* 1 or more repetitions */
+ return (m ? max_expand(ms, s+1, p, ep) : NULL);
+ }
+ case '-': { /* 0 or more repetitions (minimum) */
+ return min_expand(ms, s, p, ep);
+ }
+ default: {
+ if (!m) return NULL;
+ s++; p=ep; goto init; /* else return match(ms, s+1, ep); */
+ }
+ }
+ }
+ }
+}
+
+
+
+static const char *lmemfind (const char *s1, size_t l1,
+ const char *s2, size_t l2) {
+ if (l2 == 0) return s1; /* empty strings are everywhere */
+ else if (l2 > l1) return NULL; /* avoids a negative `l1' */
+ else {
+ const char *init; /* to search for a `*s2' inside `s1' */
+ l2--; /* 1st char will be checked by `memchr' */
+ l1 = l1-l2; /* `s2' cannot be found after that */
+ while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
+ init++; /* 1st char is already checked */
+ if (memcmp(init, s2+1, l2) == 0)
+ return init-1;
+ else { /* correct `l1' and `s1' to try again */
+ l1 -= init-s1;
+ s1 = init;
+ }
+ }
+ return NULL; /* not found */
+ }
+}
+
+
+static void push_onecapture (MatchState *ms, int i) {
+ int l = ms->capture[i].len;
+ if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
+ if (l == CAP_POSITION)
+ lua_pushnumber(ms->L, (lua_Number)(ms->capture[i].init - ms->src_init + 1));
+ else
+ lua_pushlstring(ms->L, ms->capture[i].init, l);
+}
+
+
+static int push_captures (MatchState *ms, const char *s, const char *e) {
+ int i;
+ luaL_checkstack(ms->L, ms->level, "too many captures");
+ if (ms->level == 0 && s) { /* no explicit captures? */
+ lua_pushlstring(ms->L, s, e-s); /* return whole match */
+ return 1;
+ }
+ else { /* return all captures */
+ for (i=0; i<ms->level; i++)
+ push_onecapture(ms, i);
+ return ms->level; /* number of strings pushed */
+ }
+}
+
+
+static int str_find (lua_State *L) {
+ size_t l1, l2;
+ const char *s = luaL_checklstring(L, 1, &l1);
+ const char *p = luaL_checklstring(L, 2, &l2);
+ sint32 init = posrelat(luaL_optlong(L, 3, 1), l1) - 1;
+ if (init < 0) init = 0;
+ else if ((size_t)(init) > l1) init = (sint32)l1;
+ if (lua_toboolean(L, 4) || /* explicit request? */
+ strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */
+ /* do a plain search */
+ const char *s2 = lmemfind(s+init, l1-init, p, l2);
+ if (s2) {
+ lua_pushnumber(L, (lua_Number)(s2-s+1));
+ lua_pushnumber(L, (lua_Number)(s2-s+l2));
+ return 2;
+ }
+ }
+ else {
+ MatchState ms;
+ int anchor = (*p == '^') ? (p++, 1) : 0;
+ const char *s1=s+init;
+ ms.L = L;
+ ms.src_init = s;
+ ms.src_end = s+l1;
+ do {
+ const char *res;
+ ms.level = 0;
+ if ((res=match(&ms, s1, p)) != NULL) {
+ lua_pushnumber(L, (lua_Number)(s1-s+1)); /* start */
+ lua_pushnumber(L, (lua_Number)(res-s)); /* end */
+ return push_captures(&ms, NULL, 0) + 2;
+ }
+ } while (s1++<ms.src_end && !anchor);
+ }
+ lua_pushnil(L); /* not found */
+ return 1;
+}
+
+
+static int gfind_aux (lua_State *L) {
+ MatchState ms;
+ const char *s = lua_tostring(L, lua_upvalueindex(1));
+ size_t ls = lua_strlen(L, lua_upvalueindex(1));
+ const char *p = lua_tostring(L, lua_upvalueindex(2));
+ const char *src;
+ ms.L = L;
+ ms.src_init = s;
+ ms.src_end = s+ls;
+ for (src = s + (size_t)lua_tonumber(L, lua_upvalueindex(3));
+ src <= ms.src_end;
+ src++) {
+ const char *e;
+ ms.level = 0;
+ if ((e = match(&ms, src, p)) != NULL) {
+ int newstart = e-s;
+ if (e == src) newstart++; /* empty match? go at least one position */
+ lua_pushnumber(L, (lua_Number)newstart);
+ lua_replace(L, lua_upvalueindex(3));
+ return push_captures(&ms, src, e);
+ }
+ }
+ return 0; /* not found */
+}
+
+
+static int gfind (lua_State *L) {
+ luaL_checkstring(L, 1);
+ luaL_checkstring(L, 2);
+ lua_settop(L, 2);
+ lua_pushnumber(L, 0);
+ lua_pushcclosure(L, gfind_aux, 3);
+ return 1;
+}
+
+
+static void add_s (MatchState *ms, luaL_Buffer *b,
+ const char *s, const char *e) {
+ lua_State *L = ms->L;
+ if (lua_isstring(L, 3)) {
+ const char *news = lua_tostring(L, 3);
+ size_t l = lua_strlen(L, 3);
+ size_t i;
+ for (i=0; i<l; i++) {
+ if (news[i] != ESC)
+ luaL_putchar(b, news[i]);
+ else {
+ i++; /* skip ESC */
+ if (!isdigit(uchar(news[i])))
+ luaL_putchar(b, news[i]);
+ else {
+ int level = check_capture(ms, news[i]);
+ push_onecapture(ms, level);
+ luaL_addvalue(b); /* add capture to accumulated result */
+ }
+ }
+ }
+ }
+ else { /* is a function */
+ int n;
+ lua_pushvalue(L, 3);
+ n = push_captures(ms, s, e);
+ lua_call(L, n, 1);
+ if (lua_isstring(L, -1))
+ luaL_addvalue(b); /* add return to accumulated result */
+ else
+ lua_pop(L, 1); /* function result is not a string: pop it */
+ }
+}
+
+
+static int str_gsub (lua_State *L) {
+ size_t srcl;
+ const char *src = luaL_checklstring(L, 1, &srcl);
+ const char *p = luaL_checkstring(L, 2);
+ int max_s = luaL_optint(L, 4, srcl+1);
+ int anchor = (*p == '^') ? (p++, 1) : 0;
+ int n = 0;
+ MatchState ms;
+ luaL_Buffer b;
+ luaL_argcheck(L,
+ lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)),
+ 3, "string or function expected");
+ luaL_buffinit(L, &b);
+ ms.L = L;
+ ms.src_init = src;
+ ms.src_end = src+srcl;
+ while (n < max_s) {
+ const char *e;
+ ms.level = 0;
+ e = match(&ms, src, p);
+ if (e) {
+ n++;
+ add_s(&ms, &b, src, e);
+ }
+ if (e && e>src) /* non empty match? */
+ src = e; /* skip it */
+ else if (src < ms.src_end)
+ luaL_putchar(&b, *src++);
+ else break;
+ if (anchor) break;
+ }
+ luaL_addlstring(&b, src, ms.src_end-src);
+ luaL_pushresult(&b);
+ lua_pushnumber(L, (lua_Number)n); /* number of substitutions */
+ return 2;
+}
+
+/* }====================================================== */
+
+
+/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
+#define MAX_ITEM 512
+/* maximum size of each format specification (such as '%-099.99d') */
+#define MAX_FORMAT 20
+
+
+static void luaI_addquoted (lua_State *L, luaL_Buffer *b, int arg) {
+ size_t l;
+ const char *s = luaL_checklstring(L, arg, &l);
+ luaL_putchar(b, '"');
+ while (l--) {
+ switch (*s) {
+ case '"': case '\\': case '\n': {
+ luaL_putchar(b, '\\');
+ luaL_putchar(b, *s);
+ break;
+ }
+ case '\0': {
+ luaL_addlstring(b, "\\000", 4);
+ break;
+ }
+ default: {
+ luaL_putchar(b, *s);
+ break;
+ }
+ }
+ s++;
+ }
+ luaL_putchar(b, '"');
+}
+
+
+static const char *scanformat (lua_State *L, const char *strfrmt,
+ char *form, int *hasprecision) {
+ const char *p = strfrmt;
+ while (strchr("-+ #0", *p)) p++; /* skip flags */
+ if (isdigit(uchar(*p))) p++; /* skip width */
+ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
+ if (*p == '.') {
+ p++;
+ *hasprecision = 1;
+ if (isdigit(uchar(*p))) p++; /* skip precision */
+ if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
+ }
+ if (isdigit(uchar(*p)))
+ luaL_error(L, "invalid format (width or precision too long)");
+ if (p-strfrmt+2 > MAX_FORMAT) /* +2 to include `%' and the specifier */
+ luaL_error(L, "invalid format (too long)");
+ form[0] = '%';
+ strncpy(form+1, strfrmt, p-strfrmt+1);
+ form[p-strfrmt+2] = 0;
+ return p;
+}
+
+
+static int str_format (lua_State *L) {
+ int arg = 1;
+ size_t sfl;
+ const char *strfrmt = luaL_checklstring(L, arg, &sfl);
+ const char *strfrmt_end = strfrmt+sfl;
+ luaL_Buffer b;
+ luaL_buffinit(L, &b);
+ while (strfrmt < strfrmt_end) {
+ if (*strfrmt != '%')
+ luaL_putchar(&b, *strfrmt++);
+ else if (*++strfrmt == '%')
+ luaL_putchar(&b, *strfrmt++); /* %% */
+ else { /* format item */
+ char form[MAX_FORMAT]; /* to store the format (`%...') */
+ char buff[MAX_ITEM]; /* to store the formatted item */
+ int hasprecision = 0;
+ if (isdigit(uchar(*strfrmt)) && *(strfrmt+1) == '$')
+ return luaL_error(L, "obsolete option (d$) to `format'");
+ arg++;
+ strfrmt = scanformat(L, strfrmt, form, &hasprecision);
+ switch (*strfrmt++) {
+ case 'c': case 'd': case 'i': {
+ sprintf(buff, form, luaL_checkint(L, arg));
+ break;
+ }
+ case 'o': case 'u': case 'x': case 'X': {
+ sprintf(buff, form, (unsigned int)(luaL_checknumber(L, arg)));
+ break;
+ }
+ case 'e': case 'E': case 'f':
+ case 'g': case 'G': {
+ sprintf(buff, form, luaL_checknumber(L, arg));
+ break;
+ }
+ case 'q': {
+ luaI_addquoted(L, &b, arg);
+ continue; /* skip the `addsize' at the end */
+ }
+ case 's': {
+ size_t l;
+ const char *s = luaL_checklstring(L, arg, &l);
+ if (!hasprecision && l >= 100) {
+ /* no precision and string is too long to be formatted;
+ keep original string */
+ lua_pushvalue(L, arg);
+ luaL_addvalue(&b);
+ continue; /* skip the `addsize' at the end */
+ }
+ else {
+ sprintf(buff, form, s);
+ break;
+ }
+ }
+ default: { /* also treat cases `pnLlh' */
+ return luaL_error(L, "invalid option to `format'");
+ }
+ }
+ luaL_addlstring(&b, buff, strlen(buff));
+ }
+ }
+ luaL_pushresult(&b);
+ return 1;
+}
+
+
+static const luaL_reg strlib[] = {
+ {"len", str_len},
+ {"sub", str_sub},
+ {"lower", str_lower},
+ {"upper", str_upper},
+ {"char", str_char},
+ {"rep", str_rep},
+ {"byte", str_byte},
+ {"format", str_format},
+ {"dump", str_dump},
+ {"find", str_find},
+ {"gfind", gfind},
+ {"gsub", str_gsub},
+ {NULL, NULL}
+};
+
+
+/*
+** Open string library
+*/
+LUALIB_API int luaopen_string (lua_State *L) {
+ luaL_openlib(L, LUA_STRLIBNAME, strlib, 0);
+ return 1;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/ltable.c b/plugins/SmartAutoReplier/lualib/ltable.c
new file mode 100644
index 0000000000..0c64adb10a
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ltable.c
@@ -0,0 +1,509 @@
+/*
+** $Id: ltable.c,v 1.132 2003/04/03 13:35:34 roberto Exp $
+** Lua tables (hash)
+** See Copyright Notice in lua.h
+*/
+
+
+/*
+** Implementation of tables (aka arrays, objects, or hash tables).
+** Tables keep its elements in two parts: an array part and a hash part.
+** Non-negative integer keys are all candidates to be kept in the array
+** part. The actual size of the array is the largest `n' such that at
+** least half the slots between 0 and n are in use.
+** Hash uses a mix of chained scatter table with Brent's variation.
+** A main invariant of these tables is that, if an element is not
+** in its main position (i.e. the `original' position that its hash gives
+** to it), then the colliding element is in its own main position.
+** In other words, there are collisions only when two elements have the
+** same main position (i.e. the same hash values for that table size).
+** Because of that, the load factor of these tables can be 100% without
+** performance penalties.
+*/
+
+#include <string.h>
+
+#define ltable_c
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "ldo.h"
+#include "lgc.h"
+#include "lmem.h"
+#include "lobject.h"
+#include "lstate.h"
+#include "ltable.h"
+
+
+/*
+** max size of array part is 2^MAXBITS
+*/
+#if BITS_INT > 26
+#define MAXBITS 24
+#else
+#define MAXBITS (BITS_INT-2)
+#endif
+
+/* check whether `x' < 2^MAXBITS */
+#define toobig(x) ((((x)-1) >> MAXBITS) != 0)
+
+
+/* function to convert a lua_Number to int (with any rounding method) */
+#ifndef lua_number2int
+#define lua_number2int(i,n) ((i)=(int)(n))
+#endif
+
+
+#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
+
+#define hashstr(t,str) hashpow2(t, (str)->tsv.hash)
+#define hashboolean(t,p) hashpow2(t, p)
+
+
+/*
+** for some types, it is better to avoid modulus by power of 2, as
+** they tend to have many 2 factors.
+*/
+#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
+
+
+#define hashpointer(t,p) hashmod(t, IntPoint(p))
+
+
+/*
+** number of ints inside a lua_Number
+*/
+#define numints cast(int, sizeof(lua_Number)/sizeof(int))
+
+
+/*
+** hash for lua_Numbers
+*/
+static Node *hashnum (const Table *t, lua_Number n) {
+ unsigned int a[numints];
+ int i;
+ n += 1; /* normalize number (avoid -0) */
+ lua_assert(sizeof(a) <= sizeof(n));
+ memcpy(a, &n, sizeof(a));
+ for (i = 1; i < numints; i++) a[0] += a[i];
+ return hashmod(t, cast(lu_hash, a[0]));
+}
+
+
+
+/*
+** returns the `main' position of an element in a table (that is, the index
+** of its hash value)
+*/
+Node *luaH_mainposition (const Table *t, const TObject *key) {
+ switch (ttype(key)) {
+ case LUA_TNUMBER:
+ return hashnum(t, nvalue(key));
+ case LUA_TSTRING:
+ return hashstr(t, tsvalue(key));
+ case LUA_TBOOLEAN:
+ return hashboolean(t, bvalue(key));
+ case LUA_TLIGHTUSERDATA:
+ return hashpointer(t, pvalue(key));
+ default:
+ return hashpointer(t, gcvalue(key));
+ }
+}
+
+
+/*
+** returns the index for `key' if `key' is an appropriate key to live in
+** the array part of the table, -1 otherwise.
+*/
+static int arrayindex (const TObject *key) {
+ if (ttisnumber(key)) {
+ int k;
+ lua_number2int(k, (nvalue(key)));
+ if (cast(lua_Number, k) == nvalue(key) && k >= 1 && !toobig(k))
+ return k;
+ }
+ return -1; /* `key' did not match some condition */
+}
+
+
+/*
+** returns the index of a `key' for table traversals. First goes all
+** elements in the array part, then elements in the hash part. The
+** beginning and end of a traversal are signalled by -1.
+*/
+static int luaH_index (lua_State *L, Table *t, StkId key) {
+ int i;
+ if (ttisnil(key)) return -1; /* first iteration */
+ i = arrayindex(key);
+ if (0 <= i && i <= t->sizearray) { /* is `key' inside array part? */
+ return i-1; /* yes; that's the index (corrected to C) */
+ }
+ else {
+ const TObject *v = luaH_get(t, key);
+ if (v == &luaO_nilobject)
+ luaG_runerror(L, "invalid key for `next'");
+ i = cast(int, (cast(const lu_byte *, v) -
+ cast(const lu_byte *, gval(gnode(t, 0)))) / sizeof(Node));
+ return i + t->sizearray; /* hash elements are numbered after array ones */
+ }
+}
+
+
+int luaH_next (lua_State *L, Table *t, StkId key) {
+ int i = luaH_index(L, t, key); /* find original element */
+ for (i++; i < t->sizearray; i++) { /* try first array part */
+ if (!ttisnil(&t->array[i])) { /* a non-nil value? */
+ setnvalue(key, cast(lua_Number, i+1));
+ setobj2s(key+1, &t->array[i]);
+ return 1;
+ }
+ }
+ for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */
+ if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */
+ setobj2s(key, gkey(gnode(t, i)));
+ setobj2s(key+1, gval(gnode(t, i)));
+ return 1;
+ }
+ }
+ return 0; /* no more elements */
+}
+
+
+/*
+** {=============================================================
+** Rehash
+** ==============================================================
+*/
+
+
+static void computesizes (int nums[], int ntotal, int *narray, int *nhash) {
+ int i;
+ int a = nums[0]; /* number of elements smaller than 2^i */
+ int na = a; /* number of elements to go to array part */
+ int n = (na == 0) ? -1 : 0; /* (log of) optimal size for array part */
+ for (i = 1; a < *narray && *narray >= twoto(i-1); i++) {
+ if (nums[i] > 0) {
+ a += nums[i];
+ if (a >= twoto(i-1)) { /* more than half elements in use? */
+ n = i;
+ na = a;
+ }
+ }
+ }
+ lua_assert(na <= *narray && *narray <= ntotal);
+ *nhash = ntotal - na;
+ *narray = (n == -1) ? 0 : twoto(n);
+ lua_assert(na <= *narray && na >= *narray/2);
+}
+
+
+static void numuse (const Table *t, int *narray, int *nhash) {
+ int nums[MAXBITS+1];
+ int i, lg;
+ int totaluse = 0;
+ /* count elements in array part */
+ for (i=0, lg=0; lg<=MAXBITS; lg++) { /* for each slice [2^(lg-1) to 2^lg) */
+ int ttlg = twoto(lg); /* 2^lg */
+ if (ttlg > t->sizearray) {
+ ttlg = t->sizearray;
+ if (i >= ttlg) break;
+ }
+ nums[lg] = 0;
+ for (; i<ttlg; i++) {
+ if (!ttisnil(&t->array[i])) {
+ nums[lg]++;
+ totaluse++;
+ }
+ }
+ }
+ for (; lg<=MAXBITS; lg++) nums[lg] = 0; /* reset other counts */
+ *narray = totaluse; /* all previous uses were in array part */
+ /* count elements in hash part */
+ i = sizenode(t);
+ while (i--) {
+ Node *n = &t->node[i];
+ if (!ttisnil(gval(n))) {
+ int k = arrayindex(gkey(n));
+ if (k >= 0) { /* is `key' an appropriate array index? */
+ nums[luaO_log2(k-1)+1]++; /* count as such */
+ (*narray)++;
+ }
+ totaluse++;
+ }
+ }
+ computesizes(nums, totaluse, narray, nhash);
+}
+
+
+static void setarrayvector (lua_State *L, Table *t, int size) {
+ int i;
+ luaM_reallocvector(L, t->array, t->sizearray, size, TObject);
+ for (i=t->sizearray; i<size; i++)
+ setnilvalue(&t->array[i]);
+ t->sizearray = size;
+}
+
+
+static void setnodevector (lua_State *L, Table *t, int lsize) {
+ int i;
+ int size = twoto(lsize);
+ if (lsize > MAXBITS)
+ luaG_runerror(L, "table overflow");
+ if (lsize == 0) { /* no elements to hash part? */
+ t->node = G(L)->dummynode; /* use common `dummynode' */
+ lua_assert(ttisnil(gkey(t->node))); /* assert invariants: */
+ lua_assert(ttisnil(gval(t->node)));
+ lua_assert(t->node->next == NULL); /* (`dummynode' must be empty) */
+ }
+ else {
+ t->node = luaM_newvector(L, size, Node);
+ for (i=0; i<size; i++) {
+ t->node[i].next = NULL;
+ setnilvalue(gkey(gnode(t, i)));
+ setnilvalue(gval(gnode(t, i)));
+ }
+ }
+ t->lsizenode = cast(lu_byte, lsize);
+ t->firstfree = gnode(t, size-1); /* first free position to be used */
+}
+
+
+static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
+ int i;
+ int oldasize = t->sizearray;
+ int oldhsize = t->lsizenode;
+ Node *nold;
+ Node temp[1];
+ if (oldhsize)
+ nold = t->node; /* save old hash ... */
+ else { /* old hash is `dummynode' */
+ lua_assert(t->node == G(L)->dummynode);
+ temp[0] = t->node[0]; /* copy it to `temp' */
+ nold = temp;
+ setnilvalue(gkey(G(L)->dummynode)); /* restate invariant */
+ setnilvalue(gval(G(L)->dummynode));
+ lua_assert(G(L)->dummynode->next == NULL);
+ }
+ if (nasize > oldasize) /* array part must grow? */
+ setarrayvector(L, t, nasize);
+ /* create new hash part with appropriate size */
+ setnodevector(L, t, nhsize);
+ /* re-insert elements */
+ if (nasize < oldasize) { /* array part must shrink? */
+ t->sizearray = nasize;
+ /* re-insert elements from vanishing slice */
+ for (i=nasize; i<oldasize; i++) {
+ if (!ttisnil(&t->array[i]))
+ setobjt2t(luaH_setnum(L, t, i+1), &t->array[i]);
+ }
+ /* shrink array */
+ luaM_reallocvector(L, t->array, oldasize, nasize, TObject);
+ }
+ /* re-insert elements in hash part */
+ for (i = twoto(oldhsize) - 1; i >= 0; i--) {
+ Node *old = nold+i;
+ if (!ttisnil(gval(old)))
+ setobjt2t(luaH_set(L, t, gkey(old)), gval(old));
+ }
+ if (oldhsize)
+ luaM_freearray(L, nold, twoto(oldhsize), Node); /* free old array */
+}
+
+
+static void rehash (lua_State *L, Table *t) {
+ int nasize, nhsize;
+ numuse(t, &nasize, &nhsize); /* compute new sizes for array and hash parts */
+ resize(L, t, nasize, luaO_log2(nhsize)+1);
+}
+
+
+
+/*
+** }=============================================================
+*/
+
+
+Table *luaH_new (lua_State *L, int narray, int lnhash) {
+ Table *t = luaM_new(L, Table);
+ luaC_link(L, valtogco(t), LUA_TTABLE);
+ t->metatable = hvalue(defaultmeta(L));
+ t->flags = cast(lu_byte, ~0);
+ /* temporary values (kept only if some malloc fails) */
+ t->array = NULL;
+ t->sizearray = 0;
+ t->lsizenode = 0;
+ t->node = NULL;
+ setarrayvector(L, t, narray);
+ setnodevector(L, t, lnhash);
+ return t;
+}
+
+
+void luaH_free (lua_State *L, Table *t) {
+ if (t->lsizenode)
+ luaM_freearray(L, t->node, sizenode(t), Node);
+ luaM_freearray(L, t->array, t->sizearray, TObject);
+ luaM_freelem(L, t);
+}
+
+
+#if 0
+/*
+** try to remove an element from a hash table; cannot move any element
+** (because gc can call `remove' during a table traversal)
+*/
+void luaH_remove (Table *t, Node *e) {
+ Node *mp = luaH_mainposition(t, gkey(e));
+ if (e != mp) { /* element not in its main position? */
+ while (mp->next != e) mp = mp->next; /* find previous */
+ mp->next = e->next; /* remove `e' from its list */
+ }
+ else {
+ if (e->next != NULL) ??
+ }
+ lua_assert(ttisnil(gval(node)));
+ setnilvalue(gkey(e)); /* clear node `e' */
+ e->next = NULL;
+}
+#endif
+
+
+/*
+** inserts a new key into a hash table; first, check whether key's main
+** position is free. If not, check whether colliding node is in its main
+** position or not: if it is not, move colliding node to an empty place and
+** put new key in its main position; otherwise (colliding node is in its main
+** position), new key goes to an empty position.
+*/
+static TObject *newkey (lua_State *L, Table *t, const TObject *key) {
+ TObject *val;
+ Node *mp = luaH_mainposition(t, key);
+ if (!ttisnil(gval(mp))) { /* main position is not free? */
+ Node *othern = luaH_mainposition(t, gkey(mp)); /* `mp' of colliding node */
+ Node *n = t->firstfree; /* get a free place */
+ if (othern != mp) { /* is colliding node out of its main position? */
+ /* yes; move colliding node into free position */
+ while (othern->next != mp) othern = othern->next; /* find previous */
+ othern->next = n; /* redo the chain with `n' in place of `mp' */
+ *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
+ mp->next = NULL; /* now `mp' is free */
+ setnilvalue(gval(mp));
+ }
+ else { /* colliding node is in its own main position */
+ /* new node will go into free position */
+ n->next = mp->next; /* chain new position */
+ mp->next = n;
+ mp = n;
+ }
+ }
+ setobj2t(gkey(mp), key); /* write barrier */
+ lua_assert(ttisnil(gval(mp)));
+ for (;;) { /* correct `firstfree' */
+ if (ttisnil(gkey(t->firstfree)))
+ return gval(mp); /* OK; table still has a free place */
+ else if (t->firstfree == t->node) break; /* cannot decrement from here */
+ else (t->firstfree)--;
+ }
+ /* no more free places; must create one */
+ setbvalue(gval(mp), 0); /* avoid new key being removed */
+ rehash(L, t); /* grow table */
+ val = cast(TObject *, luaH_get(t, key)); /* get new position */
+ lua_assert(ttisboolean(val));
+ setnilvalue(val);
+ return val;
+}
+
+
+/*
+** generic search function
+*/
+static const TObject *luaH_getany (Table *t, const TObject *key) {
+ if (ttisnil(key)) return &luaO_nilobject;
+ else {
+ Node *n = luaH_mainposition(t, key);
+ do { /* check whether `key' is somewhere in the chain */
+ if (luaO_rawequalObj(gkey(n), key)) return gval(n); /* that's it */
+ else n = n->next;
+ } while (n);
+ return &luaO_nilobject;
+ }
+}
+
+
+/*
+** search function for integers
+*/
+const TObject *luaH_getnum (Table *t, int key) {
+ if (1 <= key && key <= t->sizearray)
+ return &t->array[key-1];
+ else {
+ lua_Number nk = cast(lua_Number, key);
+ Node *n = hashnum(t, nk);
+ do { /* check whether `key' is somewhere in the chain */
+ if (ttisnumber(gkey(n)) && nvalue(gkey(n)) == nk)
+ return gval(n); /* that's it */
+ else n = n->next;
+ } while (n);
+ return &luaO_nilobject;
+ }
+}
+
+
+/*
+** search function for strings
+*/
+const TObject *luaH_getstr (Table *t, TString *key) {
+ Node *n = hashstr(t, key);
+ do { /* check whether `key' is somewhere in the chain */
+ if (ttisstring(gkey(n)) && tsvalue(gkey(n)) == key)
+ return gval(n); /* that's it */
+ else n = n->next;
+ } while (n);
+ return &luaO_nilobject;
+}
+
+
+/*
+** main search function
+*/
+const TObject *luaH_get (Table *t, const TObject *key) {
+ switch (ttype(key)) {
+ case LUA_TSTRING: return luaH_getstr(t, tsvalue(key));
+ case LUA_TNUMBER: {
+ int k;
+ lua_number2int(k, (nvalue(key)));
+ if (cast(lua_Number, k) == nvalue(key)) /* is an integer index? */
+ return luaH_getnum(t, k); /* use specialized version */
+ /* else go through */
+ }
+ default: return luaH_getany(t, key);
+ }
+}
+
+
+TObject *luaH_set (lua_State *L, Table *t, const TObject *key) {
+ const TObject *p = luaH_get(t, key);
+ t->flags = 0;
+ if (p != &luaO_nilobject)
+ return cast(TObject *, p);
+ else {
+ if (ttisnil(key)) luaG_runerror(L, "table index is nil");
+ else if (ttisnumber(key) && nvalue(key) != nvalue(key))
+ luaG_runerror(L, "table index is NaN");
+ return newkey(L, t, key);
+ }
+}
+
+
+TObject *luaH_setnum (lua_State *L, Table *t, int key) {
+ const TObject *p = luaH_getnum(t, key);
+ if (p != &luaO_nilobject)
+ return cast(TObject *, p);
+ else {
+ TObject k;
+ setnvalue(&k, cast(lua_Number, key));
+ return newkey(L, t, &k);
+ }
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/ltable.h b/plugins/SmartAutoReplier/lualib/ltable.h
new file mode 100644
index 0000000000..3d4d753c3c
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ltable.h
@@ -0,0 +1,31 @@
+/*
+** $Id: ltable.h,v 1.44 2003/03/18 12:50:04 roberto Exp $
+** Lua tables (hash)
+** See Copyright Notice in lua.h
+*/
+
+#ifndef ltable_h
+#define ltable_h
+
+#include "lobject.h"
+
+
+#define gnode(t,i) (&(t)->node[i])
+#define gkey(n) (&(n)->i_key)
+#define gval(n) (&(n)->i_val)
+
+
+const TObject *luaH_getnum (Table *t, int key);
+TObject *luaH_setnum (lua_State *L, Table *t, int key);
+const TObject *luaH_getstr (Table *t, TString *key);
+const TObject *luaH_get (Table *t, const TObject *key);
+TObject *luaH_set (lua_State *L, Table *t, const TObject *key);
+Table *luaH_new (lua_State *L, int narray, int lnhash);
+void luaH_free (lua_State *L, Table *t);
+int luaH_next (lua_State *L, Table *t, StkId key);
+
+/* exported only for debugging */
+Node *luaH_mainposition (const Table *t, const TObject *key);
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/ltablib.c b/plugins/SmartAutoReplier/lualib/ltablib.c
new file mode 100644
index 0000000000..c9bb2d1b7e
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ltablib.c
@@ -0,0 +1,250 @@
+/*
+** $Id: ltablib.c,v 1.21 2003/04/03 13:35:34 roberto Exp $
+** Library for Table Manipulation
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stddef.h>
+
+#define ltablib_c
+
+#include "lua.h"
+
+#include "lauxlib.h"
+#include "lualib.h"
+
+
+#define aux_getn(L,n) (luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n))
+
+
+static int luaB_foreachi (lua_State *L) {
+ int i;
+ int n = aux_getn(L, 1);
+ luaL_checktype(L, 2, LUA_TFUNCTION);
+ for (i=1; i<=n; i++) {
+ lua_pushvalue(L, 2); /* function */
+ lua_pushnumber(L, (lua_Number)i); /* 1st argument */
+ lua_rawgeti(L, 1, i); /* 2nd argument */
+ lua_call(L, 2, 1);
+ if (!lua_isnil(L, -1))
+ return 1;
+ lua_pop(L, 1); /* remove nil result */
+ }
+ return 0;
+}
+
+
+static int luaB_foreach (lua_State *L) {
+ luaL_checktype(L, 1, LUA_TTABLE);
+ luaL_checktype(L, 2, LUA_TFUNCTION);
+ lua_pushnil(L); /* first key */
+ for (;;) {
+ if (lua_next(L, 1) == 0)
+ return 0;
+ lua_pushvalue(L, 2); /* function */
+ lua_pushvalue(L, -3); /* key */
+ lua_pushvalue(L, -3); /* value */
+ lua_call(L, 2, 1);
+ if (!lua_isnil(L, -1))
+ return 1;
+ lua_pop(L, 2); /* remove value and result */
+ }
+}
+
+
+static int luaB_getn (lua_State *L) {
+ lua_pushnumber(L, (lua_Number)aux_getn(L, 1));
+ return 1;
+}
+
+
+static int luaB_setn (lua_State *L) {
+ luaL_checktype(L, 1, LUA_TTABLE);
+ luaL_setn(L, 1, luaL_checkint(L, 2));
+ return 0;
+}
+
+
+static int luaB_tinsert (lua_State *L) {
+ int v = lua_gettop(L); /* number of arguments */
+ int n = aux_getn(L, 1) + 1;
+ int pos; /* where to insert new element */
+ if (v == 2) /* called with only 2 arguments */
+ pos = n; /* insert new element at the end */
+ else {
+ pos = luaL_checkint(L, 2); /* 2nd argument is the position */
+ if (pos > n) n = pos; /* `grow' array if necessary */
+ v = 3; /* function may be called with more than 3 args */
+ }
+ luaL_setn(L, 1, n); /* new size */
+ while (--n >= pos) { /* move up elements */
+ lua_rawgeti(L, 1, n);
+ lua_rawseti(L, 1, n+1); /* t[n+1] = t[n] */
+ }
+ lua_pushvalue(L, v);
+ lua_rawseti(L, 1, pos); /* t[pos] = v */
+ return 0;
+}
+
+
+static int luaB_tremove (lua_State *L) {
+ int n = aux_getn(L, 1);
+ int pos = luaL_optint(L, 2, n);
+ if (n <= 0) return 0; /* table is `empty' */
+ luaL_setn(L, 1, n-1); /* t.n = n-1 */
+ lua_rawgeti(L, 1, pos); /* result = t[pos] */
+ for ( ;pos<n; pos++) {
+ lua_rawgeti(L, 1, pos+1);
+ lua_rawseti(L, 1, pos); /* t[pos] = t[pos+1] */
+ }
+ lua_pushnil(L);
+ lua_rawseti(L, 1, n); /* t[n] = nil */
+ return 1;
+}
+
+
+static int str_concat (lua_State *L) {
+ luaL_Buffer b;
+ size_t lsep;
+ const char *sep = luaL_optlstring(L, 2, "", &lsep);
+ int i = luaL_optint(L, 3, 1);
+ int n = luaL_optint(L, 4, 0);
+ luaL_checktype(L, 1, LUA_TTABLE);
+ if (n == 0) n = luaL_getn(L, 1);
+ luaL_buffinit(L, &b);
+ for (; i <= n; i++) {
+ lua_rawgeti(L, 1, i);
+ luaL_argcheck(L, lua_isstring(L, -1), 1, "table contains non-strings");
+ luaL_addvalue(&b);
+ if (i != n)
+ luaL_addlstring(&b, sep, lsep);
+ }
+ luaL_pushresult(&b);
+ return 1;
+}
+
+
+
+/*
+** {======================================================
+** Quicksort
+** (based on `Algorithms in MODULA-3', Robert Sedgewick;
+** Addison-Wesley, 1993.)
+*/
+
+
+static void set2 (lua_State *L, int i, int j) {
+ lua_rawseti(L, 1, i);
+ lua_rawseti(L, 1, j);
+}
+
+static int sort_comp (lua_State *L, int a, int b) {
+ if (!lua_isnil(L, 2)) { /* function? */
+ int res;
+ lua_pushvalue(L, 2);
+ lua_pushvalue(L, a-1); /* -1 to compensate function */
+ lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */
+ lua_call(L, 2, 1);
+ res = lua_toboolean(L, -1);
+ lua_pop(L, 1);
+ return res;
+ }
+ else /* a < b? */
+ return lua_lessthan(L, a, b);
+}
+
+static void auxsort (lua_State *L, int l, int u) {
+ while (l < u) { /* for tail recursion */
+ int i, j;
+ /* sort elements a[l], a[(l+u)/2] and a[u] */
+ lua_rawgeti(L, 1, l);
+ lua_rawgeti(L, 1, u);
+ if (sort_comp(L, -1, -2)) /* a[u] < a[l]? */
+ set2(L, l, u); /* swap a[l] - a[u] */
+ else
+ lua_pop(L, 2);
+ if (u-l == 1) break; /* only 2 elements */
+ i = (l+u)/2;
+ lua_rawgeti(L, 1, i);
+ lua_rawgeti(L, 1, l);
+ if (sort_comp(L, -2, -1)) /* a[i]<a[l]? */
+ set2(L, i, l);
+ else {
+ lua_pop(L, 1); /* remove a[l] */
+ lua_rawgeti(L, 1, u);
+ if (sort_comp(L, -1, -2)) /* a[u]<a[i]? */
+ set2(L, i, u);
+ else
+ lua_pop(L, 2);
+ }
+ if (u-l == 2) break; /* only 3 elements */
+ lua_rawgeti(L, 1, i); /* Pivot */
+ lua_pushvalue(L, -1);
+ lua_rawgeti(L, 1, u-1);
+ set2(L, i, u-1);
+ /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
+ i = l; j = u-1;
+ for (;;) { /* invariant: a[l..i] <= P <= a[j..u] */
+ /* repeat ++i until a[i] >= P */
+ while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
+ if (i>u) luaL_error(L, "invalid order function for sorting");
+ lua_pop(L, 1); /* remove a[i] */
+ }
+ /* repeat --j until a[j] <= P */
+ while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
+ if (j<l) luaL_error(L, "invalid order function for sorting");
+ lua_pop(L, 1); /* remove a[j] */
+ }
+ if (j<i) {
+ lua_pop(L, 3); /* pop pivot, a[i], a[j] */
+ break;
+ }
+ set2(L, i, j);
+ }
+ lua_rawgeti(L, 1, u-1);
+ lua_rawgeti(L, 1, i);
+ set2(L, u-1, i); /* swap pivot (a[u-1]) with a[i] */
+ /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
+ /* adjust so that smaller half is in [j..i] and larger one in [l..u] */
+ if (i-l < u-i) {
+ j=l; i=i-1; l=i+2;
+ }
+ else {
+ j=i+1; i=u; u=j-2;
+ }
+ auxsort(L, j, i); /* call recursively the smaller one */
+ } /* repeat the routine for the larger one */
+}
+
+static int luaB_sort (lua_State *L) {
+ int n = aux_getn(L, 1);
+ luaL_checkstack(L, 40, ""); /* assume array is smaller than 2^40 */
+ if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */
+ luaL_checktype(L, 2, LUA_TFUNCTION);
+ lua_settop(L, 2); /* make sure there is two arguments */
+ auxsort(L, 1, n);
+ return 0;
+}
+
+/* }====================================================== */
+
+
+static const luaL_reg tab_funcs[] = {
+ {"concat", str_concat},
+ {"foreach", luaB_foreach},
+ {"foreachi", luaB_foreachi},
+ {"getn", luaB_getn},
+ {"setn", luaB_setn},
+ {"sort", luaB_sort},
+ {"insert", luaB_tinsert},
+ {"remove", luaB_tremove},
+ {NULL, NULL}
+};
+
+
+LUALIB_API int luaopen_table (lua_State *L) {
+ luaL_openlib(L, LUA_TABLIBNAME, tab_funcs, 0);
+ return 1;
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/ltests.c b/plugins/SmartAutoReplier/lualib/ltests.c
new file mode 100644
index 0000000000..649b14e0d4
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ltests.c
@@ -0,0 +1,852 @@
+/*
+** $Id: ltests.c,v 1.158 2003/04/07 14:35:00 roberto Exp $
+** Internal Module for Debugging of the Lua Implementation
+** See Copyright Notice in lua.h
+*/
+
+
+#include <ctype.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define ltests_c
+
+#include "lua.h"
+
+#include "lapi.h"
+#include "lauxlib.h"
+#include "lcode.h"
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lmem.h"
+#include "lopcodes.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "lualib.h"
+
+
+
+/*
+** The whole module only makes sense with LUA_DEBUG on
+*/
+#ifdef LUA_DEBUG
+
+
+#define lua_pushintegral(L,i) lua_pushnumber(L, cast(lua_Number, (i)))
+
+
+static lua_State *lua_state = NULL;
+
+int islocked = 0;
+
+
+#define func_at(L,k) (L->ci->base+(k) - 1)
+
+
+static void setnameval (lua_State *L, const char *name, int val) {
+ lua_pushstring(L, name);
+ lua_pushintegral(L, val);
+ lua_settable(L, -3);
+}
+
+
+/*
+** {======================================================================
+** Controlled version for realloc.
+** =======================================================================
+*/
+
+#define MARK 0x55 /* 01010101 (a nice pattern) */
+
+#ifndef EXTERNMEMCHECK
+/* full memory check */
+#define HEADER (sizeof(L_Umaxalign)) /* ensures maximum alignment for HEADER */
+#define MARKSIZE 16 /* size of marks after each block */
+#define blockhead(b) (cast(char *, b) - HEADER)
+#define setsize(newblock, size) (*cast(size_t *, newblock) = size)
+#define checkblocksize(b, size) (size == (*cast(size_t *, blockhead(b))))
+#define fillmem(mem,size) memset(mem, -MARK, size)
+#else
+/* external memory check: don't do it twice */
+#define HEADER 0
+#define MARKSIZE 0
+#define blockhead(b) (b)
+#define setsize(newblock, size) /* empty */
+#define checkblocksize(b,size) (1)
+#define fillmem(mem,size) /* empty */
+#endif
+
+unsigned long memdebug_numblocks = 0;
+unsigned long memdebug_total = 0;
+unsigned long memdebug_maxmem = 0;
+unsigned long memdebug_memlimit = ULONG_MAX;
+
+
+static void *checkblock (void *block, size_t size) {
+ void *b = blockhead(block);
+ int i;
+ for (i=0;i<MARKSIZE;i++)
+ lua_assert(*(cast(char *, b)+HEADER+size+i) == MARK+i); /* corrupted block? */
+ return b;
+}
+
+
+static void freeblock (void *block, size_t size) {
+ if (block) {
+ lua_assert(checkblocksize(block, size));
+ block = checkblock(block, size);
+ fillmem(block, size+HEADER+MARKSIZE); /* erase block */
+ free(block); /* free original block */
+ memdebug_numblocks--;
+ memdebug_total -= size;
+ }
+}
+
+
+void *debug_realloc (void *block, size_t oldsize, size_t size) {
+ lua_assert(oldsize == 0 || checkblocksize(block, oldsize));
+ /* ISO does not specify what realloc(NULL, 0) does */
+ lua_assert(block != NULL || size > 0);
+ if (size == 0) {
+ freeblock(block, oldsize);
+ return NULL;
+ }
+ else if (size > oldsize && memdebug_total+size-oldsize > memdebug_memlimit)
+ return NULL; /* to test memory allocation errors */
+ else {
+ void *newblock;
+ int i;
+ size_t realsize = HEADER+size+MARKSIZE;
+ size_t commonsize = (oldsize < size) ? oldsize : size;
+ if (realsize < size) return NULL; /* overflow! */
+ newblock = malloc(realsize); /* alloc a new block */
+ if (newblock == NULL) return NULL;
+ if (block) {
+ memcpy(cast(char *, newblock)+HEADER, block, commonsize);
+ freeblock(block, oldsize); /* erase (and check) old copy */
+ }
+ /* initialize new part of the block with something `weird' */
+ fillmem(cast(char *, newblock)+HEADER+commonsize, size-commonsize);
+ memdebug_total += size;
+ if (memdebug_total > memdebug_maxmem)
+ memdebug_maxmem = memdebug_total;
+ memdebug_numblocks++;
+ setsize(newblock, size);
+ for (i=0;i<MARKSIZE;i++)
+ *(cast(char *, newblock)+HEADER+size+i) = cast(char, MARK+i);
+ return cast(char *, newblock)+HEADER;
+ }
+}
+
+
+/* }====================================================================== */
+
+
+
+/*
+** {======================================================
+** Disassembler
+** =======================================================
+*/
+
+
+static char *buildop (Proto *p, int pc, char *buff) {
+ Instruction i = p->code[pc];
+ OpCode o = GET_OPCODE(i);
+ const char *name = luaP_opnames[o];
+ int line = getline(p, pc);
+ sprintf(buff, "(%4d) %4d - ", line, pc);
+ switch (getOpMode(o)) {
+ case iABC:
+ sprintf(buff+strlen(buff), "%-12s%4d %4d %4d", name,
+ GETARG_A(i), GETARG_B(i), GETARG_C(i));
+ break;
+ case iABx:
+ sprintf(buff+strlen(buff), "%-12s%4d %4d", name, GETARG_A(i), GETARG_Bx(i));
+ break;
+ case iAsBx:
+ sprintf(buff+strlen(buff), "%-12s%4d %4d", name, GETARG_A(i), GETARG_sBx(i));
+ break;
+ }
+ return buff;
+}
+
+
+#if 0
+void luaI_printcode (Proto *pt, int size) {
+ int pc;
+ for (pc=0; pc<size; pc++) {
+ char buff[100];
+ printf("%s\n", buildop(pt, pc, buff));
+ }
+ printf("-------\n");
+}
+#endif
+
+
+static int listcode (lua_State *L) {
+ int pc;
+ Proto *p;
+ luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
+ 1, "Lua function expected");
+ p = clvalue(func_at(L, 1))->l.p;
+ lua_newtable(L);
+ setnameval(L, "maxstack", p->maxstacksize);
+ setnameval(L, "numparams", p->numparams);
+ for (pc=0; pc<p->sizecode; pc++) {
+ char buff[100];
+ lua_pushintegral(L, pc+1);
+ lua_pushstring(L, buildop(p, pc, buff));
+ lua_settable(L, -3);
+ }
+ return 1;
+}
+
+
+static int listk (lua_State *L) {
+ Proto *p;
+ int i;
+ luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
+ 1, "Lua function expected");
+ p = clvalue(func_at(L, 1))->l.p;
+ lua_newtable(L);
+ for (i=0; i<p->sizek; i++) {
+ lua_pushintegral(L, i+1);
+ luaA_pushobject(L, p->k+i);
+ lua_settable(L, -3);
+ }
+ return 1;
+}
+
+
+static int listlocals (lua_State *L) {
+ Proto *p;
+ int pc = luaL_checkint(L, 2) - 1;
+ int i = 0;
+ const char *name;
+ luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1),
+ 1, "Lua function expected");
+ p = clvalue(func_at(L, 1))->l.p;
+ while ((name = luaF_getlocalname(p, ++i, pc)) != NULL)
+ lua_pushstring(L, name);
+ return i-1;
+}
+
+/* }====================================================== */
+
+
+
+
+static int get_limits (lua_State *L) {
+ lua_newtable(L);
+ setnameval(L, "BITS_INT", BITS_INT);
+ setnameval(L, "LFPF", LFIELDS_PER_FLUSH);
+ setnameval(L, "MAXVARS", MAXVARS);
+ setnameval(L, "MAXPARAMS", MAXPARAMS);
+ setnameval(L, "MAXSTACK", MAXSTACK);
+ setnameval(L, "MAXUPVALUES", MAXUPVALUES);
+ return 1;
+}
+
+
+static int mem_query (lua_State *L) {
+ if (lua_isnone(L, 1)) {
+ lua_pushintegral(L, memdebug_total);
+ lua_pushintegral(L, memdebug_numblocks);
+ lua_pushintegral(L, memdebug_maxmem);
+ return 3;
+ }
+ else {
+ memdebug_memlimit = luaL_checkint(L, 1);
+ return 0;
+ }
+}
+
+
+static int hash_query (lua_State *L) {
+ if (lua_isnone(L, 2)) {
+ luaL_argcheck(L, lua_type(L, 1) == LUA_TSTRING, 1, "string expected");
+ lua_pushintegral(L, tsvalue(func_at(L, 1))->tsv.hash);
+ }
+ else {
+ TObject *o = func_at(L, 1);
+ Table *t;
+ luaL_checktype(L, 2, LUA_TTABLE);
+ t = hvalue(func_at(L, 2));
+ lua_pushintegral(L, luaH_mainposition(t, o) - t->node);
+ }
+ return 1;
+}
+
+
+static int stacklevel (lua_State *L) {
+ unsigned long a = 0;
+ lua_pushintegral(L, (int)(L->top - L->stack));
+ lua_pushintegral(L, (int)(L->stack_last - L->stack));
+ lua_pushintegral(L, (int)(L->ci - L->base_ci));
+ lua_pushintegral(L, (int)(L->end_ci - L->base_ci));
+ lua_pushintegral(L, (unsigned long)&a);
+ return 5;
+}
+
+
+static int table_query (lua_State *L) {
+ const Table *t;
+ int i = luaL_optint(L, 2, -1);
+ luaL_checktype(L, 1, LUA_TTABLE);
+ t = hvalue(func_at(L, 1));
+ if (i == -1) {
+ lua_pushintegral(L, t->sizearray);
+ lua_pushintegral(L, sizenode(t));
+ lua_pushintegral(L, t->firstfree - t->node);
+ }
+ else if (i < t->sizearray) {
+ lua_pushintegral(L, i);
+ luaA_pushobject(L, &t->array[i]);
+ lua_pushnil(L);
+ }
+ else if ((i -= t->sizearray) < sizenode(t)) {
+ if (!ttisnil(gval(gnode(t, i))) ||
+ ttisnil(gkey(gnode(t, i))) ||
+ ttisnumber(gkey(gnode(t, i)))) {
+ luaA_pushobject(L, gkey(gnode(t, i)));
+ }
+ else
+ lua_pushstring(L, "<undef>");
+ luaA_pushobject(L, gval(gnode(t, i)));
+ if (t->node[i].next)
+ lua_pushintegral(L, t->node[i].next - t->node);
+ else
+ lua_pushnil(L);
+ }
+ return 3;
+}
+
+
+static int string_query (lua_State *L) {
+ stringtable *tb = &G(L)->strt;
+ int s = luaL_optint(L, 2, 0) - 1;
+ if (s==-1) {
+ lua_pushintegral(L ,tb->nuse);
+ lua_pushintegral(L ,tb->size);
+ return 2;
+ }
+ else if (s < tb->size) {
+ GCObject *ts;
+ int n = 0;
+ for (ts = tb->hash[s]; ts; ts = ts->gch.next) {
+ setsvalue2s(L->top, gcotots(ts));
+ incr_top(L);
+ n++;
+ }
+ return n;
+ }
+ return 0;
+}
+
+
+static int tref (lua_State *L) {
+ int level = lua_gettop(L);
+ int lock = luaL_optint(L, 2, 1);
+ luaL_checkany(L, 1);
+ lua_pushvalue(L, 1);
+ lua_pushintegral(L, lua_ref(L, lock));
+ assert(lua_gettop(L) == level+1); /* +1 for result */
+ return 1;
+}
+
+static int getref (lua_State *L) {
+ int level = lua_gettop(L);
+ lua_getref(L, luaL_checkint(L, 1));
+ assert(lua_gettop(L) == level+1);
+ return 1;
+}
+
+static int unref (lua_State *L) {
+ int level = lua_gettop(L);
+ lua_unref(L, luaL_checkint(L, 1));
+ assert(lua_gettop(L) == level);
+ return 0;
+}
+
+static int metatable (lua_State *L) {
+ luaL_checkany(L, 1);
+ if (lua_isnone(L, 2)) {
+ if (lua_getmetatable(L, 1) == 0)
+ lua_pushnil(L);
+ }
+ else {
+ lua_settop(L, 2);
+ luaL_checktype(L, 2, LUA_TTABLE);
+ lua_setmetatable(L, 1);
+ }
+ return 1;
+}
+
+
+static int upvalue (lua_State *L) {
+ int n = luaL_checkint(L, 2);
+ luaL_checktype(L, 1, LUA_TFUNCTION);
+ if (lua_isnone(L, 3)) {
+ const char *name = lua_getupvalue(L, 1, n);
+ if (name == NULL) return 0;
+ lua_pushstring(L, name);
+ return 2;
+ }
+ else {
+ const char *name = lua_setupvalue(L, 1, n);
+ lua_pushstring(L, name);
+ return 1;
+ }
+}
+
+
+static int newuserdata (lua_State *L) {
+ size_t size = luaL_checkint(L, 1);
+ char *p = cast(char *, lua_newuserdata(L, size));
+ while (size--) *p++ = '\0';
+ return 1;
+}
+
+
+static int pushuserdata (lua_State *L) {
+ lua_pushlightuserdata(L, cast(void *, luaL_checkint(L, 1)));
+ return 1;
+}
+
+
+static int udataval (lua_State *L) {
+ lua_pushintegral(L, cast(int, lua_touserdata(L, 1)));
+ return 1;
+}
+
+
+static int doonnewstack (lua_State *L) {
+ lua_State *L1 = lua_newthread(L);
+ size_t l;
+ const char *s = luaL_checklstring(L, 1, &l);
+ int status = luaL_loadbuffer(L1, s, l, s);
+ if (status == 0)
+ status = lua_pcall(L1, 0, 0, 0);
+ lua_pushintegral(L, status);
+ return 1;
+}
+
+
+static int s2d (lua_State *L) {
+ lua_pushnumber(L, *cast(const double *, luaL_checkstring(L, 1)));
+ return 1;
+}
+
+static int d2s (lua_State *L) {
+ double d = luaL_checknumber(L, 1);
+ lua_pushlstring(L, cast(char *, &d), sizeof(d));
+ return 1;
+}
+
+
+static int newstate (lua_State *L) {
+ lua_State *L1 = lua_open();
+ if (L1) {
+ lua_userstateopen(L1); /* init lock */
+ lua_pushintegral(L, (unsigned long)L1);
+ }
+ else
+ lua_pushnil(L);
+ return 1;
+}
+
+
+static int loadlib (lua_State *L) {
+ static const luaL_reg libs[] = {
+ {"mathlibopen", luaopen_math},
+ {"strlibopen", luaopen_string},
+ {"iolibopen", luaopen_io},
+ {"tablibopen", luaopen_table},
+ {"dblibopen", luaopen_debug},
+ {"baselibopen", luaopen_base},
+ {NULL, NULL}
+ };
+ lua_State *L1 = cast(lua_State *,
+ cast(unsigned long, luaL_checknumber(L, 1)));
+ lua_pushvalue(L1, LUA_GLOBALSINDEX);
+ luaL_openlib(L1, NULL, libs, 0);
+ return 0;
+}
+
+static int closestate (lua_State *L) {
+ lua_State *L1 = cast(lua_State *, cast(unsigned long, luaL_checknumber(L, 1)));
+ lua_close(L1);
+ lua_unlock(L); /* close cannot unlock that */
+ return 0;
+}
+
+static int doremote (lua_State *L) {
+ lua_State *L1 = cast(lua_State *,cast(unsigned long,luaL_checknumber(L, 1)));
+ size_t lcode;
+ const char *code = luaL_checklstring(L, 2, &lcode);
+ int status;
+ lua_settop(L1, 0);
+ status = luaL_loadbuffer(L1, code, lcode, code);
+ if (status == 0)
+ status = lua_pcall(L1, 0, LUA_MULTRET, 0);
+ if (status != 0) {
+ lua_pushnil(L);
+ lua_pushintegral(L, status);
+ lua_pushstring(L, lua_tostring(L1, -1));
+ return 3;
+ }
+ else {
+ int i = 0;
+ while (!lua_isnone(L1, ++i))
+ lua_pushstring(L, lua_tostring(L1, i));
+ lua_pop(L1, i-1);
+ return i-1;
+ }
+}
+
+
+static int log2_aux (lua_State *L) {
+ lua_pushintegral(L, luaO_log2(luaL_checkint(L, 1)));
+ return 1;
+}
+
+static int int2fb_aux (lua_State *L) {
+ int b = luaO_int2fb(luaL_checkint(L, 1));
+ lua_pushintegral(L, b);
+ lua_pushintegral(L, fb2int(b));
+ return 2;
+}
+
+
+static int test_do (lua_State *L) {
+ const char *p = luaL_checkstring(L, 1);
+ if (*p == '@')
+ lua_dofile(L, p+1);
+ else
+ lua_dostring(L, p);
+ return lua_gettop(L);
+}
+
+
+
+/*
+** {======================================================
+** function to test the API with C. It interprets a kind of assembler
+** language with calls to the API, so the test can be driven by Lua code
+** =======================================================
+*/
+
+static const char *const delimits = " \t\n,;";
+
+static void skip (const char **pc) {
+ while (**pc != '\0' && strchr(delimits, **pc)) (*pc)++;
+}
+
+static int getnum_aux (lua_State *L, const char **pc) {
+ int res = 0;
+ int sig = 1;
+ skip(pc);
+ if (**pc == '.') {
+ res = cast(int, lua_tonumber(L, -1));
+ lua_pop(L, 1);
+ (*pc)++;
+ return res;
+ }
+ else if (**pc == '-') {
+ sig = -1;
+ (*pc)++;
+ }
+ while (isdigit(cast(int, **pc))) res = res*10 + (*(*pc)++) - '0';
+ return sig*res;
+}
+
+static const char *getname_aux (char *buff, const char **pc) {
+ int i = 0;
+ skip(pc);
+ while (**pc != '\0' && !strchr(delimits, **pc))
+ buff[i++] = *(*pc)++;
+ buff[i] = '\0';
+ return buff;
+}
+
+
+#define EQ(s1) (strcmp(s1, inst) == 0)
+
+#define getnum (getnum_aux(L, &pc))
+#define getname (getname_aux(buff, &pc))
+
+
+static int testC (lua_State *L) {
+ char buff[30];
+ const char *pc = luaL_checkstring(L, 1);
+ for (;;) {
+ const char *inst = getname;
+ if EQ("") return 0;
+ else if EQ("isnumber") {
+ lua_pushintegral(L, lua_isnumber(L, getnum));
+ }
+ else if EQ("isstring") {
+ lua_pushintegral(L, lua_isstring(L, getnum));
+ }
+ else if EQ("istable") {
+ lua_pushintegral(L, lua_istable(L, getnum));
+ }
+ else if EQ("iscfunction") {
+ lua_pushintegral(L, lua_iscfunction(L, getnum));
+ }
+ else if EQ("isfunction") {
+ lua_pushintegral(L, lua_isfunction(L, getnum));
+ }
+ else if EQ("isuserdata") {
+ lua_pushintegral(L, lua_isuserdata(L, getnum));
+ }
+ else if EQ("isudataval") {
+ lua_pushintegral(L, lua_islightuserdata(L, getnum));
+ }
+ else if EQ("isnil") {
+ lua_pushintegral(L, lua_isnil(L, getnum));
+ }
+ else if EQ("isnull") {
+ lua_pushintegral(L, lua_isnone(L, getnum));
+ }
+ else if EQ("tonumber") {
+ lua_pushnumber(L, lua_tonumber(L, getnum));
+ }
+ else if EQ("tostring") {
+ const char *s = lua_tostring(L, getnum);
+ lua_pushstring(L, s);
+ }
+ else if EQ("strlen") {
+ lua_pushintegral(L, lua_strlen(L, getnum));
+ }
+ else if EQ("tocfunction") {
+ lua_pushcfunction(L, lua_tocfunction(L, getnum));
+ }
+ else if EQ("return") {
+ return getnum;
+ }
+ else if EQ("gettop") {
+ lua_pushintegral(L, lua_gettop(L));
+ }
+ else if EQ("settop") {
+ lua_settop(L, getnum);
+ }
+ else if EQ("pop") {
+ lua_pop(L, getnum);
+ }
+ else if EQ("pushnum") {
+ lua_pushintegral(L, getnum);
+ }
+ else if EQ("pushnil") {
+ lua_pushnil(L);
+ }
+ else if EQ("pushbool") {
+ lua_pushboolean(L, getnum);
+ }
+ else if EQ("tobool") {
+ lua_pushintegral(L, lua_toboolean(L, getnum));
+ }
+ else if EQ("pushvalue") {
+ lua_pushvalue(L, getnum);
+ }
+ else if EQ("pushcclosure") {
+ lua_pushcclosure(L, testC, getnum);
+ }
+ else if EQ("pushupvalues") {
+ lua_pushupvalues(L);
+ }
+ else if EQ("remove") {
+ lua_remove(L, getnum);
+ }
+ else if EQ("insert") {
+ lua_insert(L, getnum);
+ }
+ else if EQ("replace") {
+ lua_replace(L, getnum);
+ }
+ else if EQ("gettable") {
+ lua_gettable(L, getnum);
+ }
+ else if EQ("settable") {
+ lua_settable(L, getnum);
+ }
+ else if EQ("next") {
+ lua_next(L, -2);
+ }
+ else if EQ("concat") {
+ lua_concat(L, getnum);
+ }
+ else if EQ("lessthan") {
+ int a = getnum;
+ lua_pushboolean(L, lua_lessthan(L, a, getnum));
+ }
+ else if EQ("equal") {
+ int a = getnum;
+ lua_pushboolean(L, lua_equal(L, a, getnum));
+ }
+ else if EQ("rawcall") {
+ int narg = getnum;
+ int nres = getnum;
+ lua_call(L, narg, nres);
+ }
+ else if EQ("call") {
+ int narg = getnum;
+ int nres = getnum;
+ lua_pcall(L, narg, nres, 0);
+ }
+ else if EQ("loadstring") {
+ size_t sl;
+ const char *s = luaL_checklstring(L, getnum, &sl);
+ luaL_loadbuffer(L, s, sl, s);
+ }
+ else if EQ("loadfile") {
+ luaL_loadfile(L, luaL_checkstring(L, getnum));
+ }
+ else if EQ("setmetatable") {
+ lua_setmetatable(L, getnum);
+ }
+ else if EQ("getmetatable") {
+ if (lua_getmetatable(L, getnum) == 0)
+ lua_pushnil(L);
+ }
+ else if EQ("type") {
+ lua_pushstring(L, lua_typename(L, lua_type(L, getnum)));
+ }
+ else if EQ("getn") {
+ int i = getnum;
+ lua_pushintegral(L, luaL_getn(L, i));
+ }
+ else if EQ("setn") {
+ int i = getnum;
+ int n = cast(int, lua_tonumber(L, -1));
+ luaL_setn(L, i, n);
+ lua_pop(L, 1);
+ }
+ else luaL_error(L, "unknown instruction %s", buff);
+ }
+ return 0;
+}
+
+/* }====================================================== */
+
+
+/*
+** {======================================================
+** tests for yield inside hooks
+** =======================================================
+*/
+
+static void yieldf (lua_State *L, lua_Debug *ar) {
+ lua_yield(L, 0);
+}
+
+static int setyhook (lua_State *L) {
+ if (lua_isnoneornil(L, 1))
+ lua_sethook(L, NULL, 0, 0); /* turn off hooks */
+ else {
+ const char *smask = luaL_checkstring(L, 1);
+ int count = luaL_optint(L, 2, 0);
+ int mask = 0;
+ if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
+ if (count > 0) mask |= LUA_MASKCOUNT;
+ lua_sethook(L, yieldf, mask, count);
+ }
+ return 0;
+}
+
+
+static int coresume (lua_State *L) {
+ int status;
+ lua_State *co = lua_tothread(L, 1);
+ luaL_argcheck(L, co, 1, "coroutine expected");
+ status = lua_resume(co, 0);
+ if (status != 0) {
+ lua_pushboolean(L, 0);
+ lua_insert(L, -2);
+ return 2; /* return false + error message */
+ }
+ else {
+ lua_pushboolean(L, 1);
+ return 1;
+ }
+}
+
+/* }====================================================== */
+
+
+
+static const struct luaL_reg tests_funcs[] = {
+ {"hash", hash_query},
+ {"limits", get_limits},
+ {"listcode", listcode},
+ {"listk", listk},
+ {"listlocals", listlocals},
+ {"loadlib", loadlib},
+ {"stacklevel", stacklevel},
+ {"querystr", string_query},
+ {"querytab", table_query},
+ {"doit", test_do},
+ {"testC", testC},
+ {"ref", tref},
+ {"getref", getref},
+ {"unref", unref},
+ {"d2s", d2s},
+ {"s2d", s2d},
+ {"metatable", metatable},
+ {"upvalue", upvalue},
+ {"newuserdata", newuserdata},
+ {"pushuserdata", pushuserdata},
+ {"udataval", udataval},
+ {"doonnewstack", doonnewstack},
+ {"newstate", newstate},
+ {"closestate", closestate},
+ {"doremote", doremote},
+ {"log2", log2_aux},
+ {"int2fb", int2fb_aux},
+ {"totalmem", mem_query},
+ {"resume", coresume},
+ {"setyhook", setyhook},
+ {NULL, NULL}
+};
+
+
+static void fim (void) {
+ if (!islocked)
+ lua_close(lua_state);
+ lua_assert(memdebug_numblocks == 0);
+ lua_assert(memdebug_total == 0);
+}
+
+
+static int l_panic (lua_State *L) {
+ UNUSED(L);
+ fprintf(stderr, "unable to recover; exiting\n");
+ return 0;
+}
+
+
+int luaB_opentests (lua_State *L) {
+ lua_atpanic(L, l_panic);
+ lua_userstateopen(L); /* init lock */
+ lua_state = L; /* keep first state to be opened */
+ luaL_openlib(L, "T", tests_funcs, 0);
+ atexit(fim);
+ return 0;
+}
+
+
+#undef main
+int main (int argc, char *argv[]) {
+ char *limit = getenv("MEMLIMIT");
+ if (limit)
+ memdebug_memlimit = strtoul(limit, NULL, 10);
+ l_main(argc, argv);
+ return 0;
+}
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/ltm.c b/plugins/SmartAutoReplier/lualib/ltm.c
new file mode 100644
index 0000000000..1b3e515e57
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ltm.c
@@ -0,0 +1,70 @@
+/*
+** $Id: ltm.c,v 1.106 2003/04/03 13:35:34 roberto Exp $
+** Tag methods
+** See Copyright Notice in lua.h
+*/
+
+
+#include <string.h>
+
+#define ltm_c
+
+#include "lua.h"
+
+#include "lobject.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+
+
+
+const char *const luaT_typenames[] = {
+ "nil", "boolean", "userdata", "number",
+ "string", "table", "function", "userdata", "thread"
+};
+
+
+void luaT_init (lua_State *L) {
+ static const char *const luaT_eventname[] = { /* ORDER TM */
+ "__index", "__newindex",
+ "__gc", "__mode", "__eq",
+ "__add", "__sub", "__mul", "__div",
+ "__pow", "__unm", "__lt", "__le",
+ "__concat", "__call"
+ };
+ int i;
+ for (i=0; i<TM_N; i++) {
+ G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
+ luaS_fix(G(L)->tmname[i]); /* never collect these names */
+ }
+}
+
+
+/*
+** function to be used with macro "fasttm": optimized for absence of
+** tag methods
+*/
+const TObject *luaT_gettm (Table *events, TMS event, TString *ename) {
+ const TObject *tm = luaH_getstr(events, ename);
+ lua_assert(event <= TM_EQ);
+ if (ttisnil(tm)) { /* no tag method? */
+ events->flags |= cast(lu_byte, 1u<<event); /* cache this fact */
+ return NULL;
+ }
+ else return tm;
+}
+
+
+const TObject *luaT_gettmbyobj (lua_State *L, const TObject *o, TMS event) {
+ TString *ename = G(L)->tmname[event];
+ switch (ttype(o)) {
+ case LUA_TTABLE:
+ return luaH_getstr(hvalue(o)->metatable, ename);
+ case LUA_TUSERDATA:
+ return luaH_getstr(uvalue(o)->uv.metatable, ename);
+ default:
+ return &luaO_nilobject;
+ }
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/ltm.h b/plugins/SmartAutoReplier/lualib/ltm.h
new file mode 100644
index 0000000000..8eebfd3dc3
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/ltm.h
@@ -0,0 +1,51 @@
+/*
+** $Id: ltm.h,v 1.41 2002/11/14 11:51:50 roberto Exp $
+** Tag methods
+** See Copyright Notice in lua.h
+*/
+
+#ifndef ltm_h
+#define ltm_h
+
+
+#include "lobject.h"
+
+
+/*
+* WARNING: if you change the order of this enumeration,
+* grep "ORDER TM"
+*/
+typedef enum {
+ TM_INDEX,
+ TM_NEWINDEX,
+ TM_GC,
+ TM_MODE,
+ TM_EQ, /* last tag method with `fast' access */
+ TM_ADD,
+ TM_SUB,
+ TM_MUL,
+ TM_DIV,
+ TM_POW,
+ TM_UNM,
+ TM_LT,
+ TM_LE,
+ TM_CONCAT,
+ TM_CALL,
+ TM_N /* number of elements in the enum */
+} TMS;
+
+
+
+#define gfasttm(g,et,e) \
+ (((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))
+
+#define fasttm(l,et,e) gfasttm(G(l), et, e)
+
+
+const TObject *luaT_gettm (Table *events, TMS event, TString *ename);
+const TObject *luaT_gettmbyobj (lua_State *L, const TObject *o, TMS event);
+void luaT_init (lua_State *L);
+
+extern const char *const luaT_typenames[];
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lua.h b/plugins/SmartAutoReplier/lualib/lua.h
new file mode 100644
index 0000000000..0d827b10c7
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lua.h
@@ -0,0 +1,391 @@
+/*
+** $Id: lua.h,v 1.175 2003/03/18 12:31:39 roberto Exp $
+** Lua - An Extensible Extension Language
+** Tecgraf: Computer Graphics Technology Group, PUC-Rio, Brazil
+** http://www.lua.org mailto:info@lua.org
+** See Copyright Notice at the end of this file
+*/
+
+
+#ifndef lua_h
+#define lua_h
+
+#include <stdarg.h>
+#include <stddef.h>
+
+
+#define LUA_VERSION "Lua 5.0"
+#define LUA_COPYRIGHT "Copyright (C) 1994-2003 Tecgraf, PUC-Rio"
+#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes"
+
+
+
+/* option for multiple returns in `lua_pcall' and `lua_call' */
+#define LUA_MULTRET (-1)
+
+
+/*
+** pseudo-indices
+*/
+#define LUA_REGISTRYINDEX (-10000)
+#define LUA_GLOBALSINDEX (-10001)
+#define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i))
+
+
+/* error codes for `lua_load' and `lua_pcall' */
+#define LUA_ERRRUN 1
+#define LUA_ERRFILE 2
+#define LUA_ERRSYNTAX 3
+#define LUA_ERRMEM 4
+#define LUA_ERRERR 5
+
+
+typedef struct lua_State lua_State;
+
+typedef int (*lua_CFunction) (lua_State *L);
+
+
+/*
+** functions that read/write blocks when loading/dumping Lua chunks
+*/
+typedef const char * (*lua_Chunkreader) (lua_State *L, void *ud, size_t *sz);
+
+typedef int (*lua_Chunkwriter) (lua_State *L, const void* p,
+ size_t sz, void* ud);
+
+
+/*
+** basic types
+*/
+#define LUA_TNONE (-1)
+
+#define LUA_TNIL 0
+#define LUA_TBOOLEAN 1
+#define LUA_TLIGHTUSERDATA 2
+#define LUA_TNUMBER 3
+#define LUA_TSTRING 4
+#define LUA_TTABLE 5
+#define LUA_TFUNCTION 6
+#define LUA_TUSERDATA 7
+#define LUA_TTHREAD 8
+
+
+/* minimum Lua stack available to a C function */
+#define LUA_MINSTACK 20
+
+
+/*
+** generic extra include file
+*/
+#ifdef LUA_USER_H
+#include LUA_USER_H
+#endif
+
+
+/* type of numbers in Lua */
+#ifndef LUA_NUMBER
+typedef double lua_Number;
+#else
+typedef LUA_NUMBER lua_Number;
+#endif
+
+
+/* mark for all API functions */
+#ifndef LUA_API
+#define LUA_API extern
+#endif
+
+
+/*
+** state manipulation
+*/
+LUA_API lua_State *lua_open (void);
+LUA_API void lua_close (lua_State *L);
+LUA_API lua_State *lua_newthread (lua_State *L);
+
+LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf);
+
+
+/*
+** basic stack manipulation
+*/
+LUA_API int lua_gettop (lua_State *L);
+LUA_API void lua_settop (lua_State *L, int idx);
+LUA_API void lua_pushvalue (lua_State *L, int idx);
+LUA_API void lua_remove (lua_State *L, int idx);
+LUA_API void lua_insert (lua_State *L, int idx);
+LUA_API void lua_replace (lua_State *L, int idx);
+LUA_API int lua_checkstack (lua_State *L, int sz);
+
+LUA_API void lua_xmove (lua_State *from, lua_State *to, int n);
+
+
+/*
+** access functions (stack -> C)
+*/
+
+LUA_API int lua_isnumber (lua_State *L, int idx);
+LUA_API int lua_isstring (lua_State *L, int idx);
+LUA_API int lua_iscfunction (lua_State *L, int idx);
+LUA_API int lua_isuserdata (lua_State *L, int idx);
+LUA_API int lua_type (lua_State *L, int idx);
+LUA_API const char *lua_typename (lua_State *L, int tp);
+
+LUA_API int lua_equal (lua_State *L, int idx1, int idx2);
+LUA_API int lua_rawequal (lua_State *L, int idx1, int idx2);
+LUA_API int lua_lessthan (lua_State *L, int idx1, int idx2);
+
+LUA_API lua_Number lua_tonumber (lua_State *L, int idx);
+LUA_API int lua_toboolean (lua_State *L, int idx);
+LUA_API const char *lua_tostring (lua_State *L, int idx);
+LUA_API size_t lua_strlen (lua_State *L, int idx);
+LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx);
+LUA_API void *lua_touserdata (lua_State *L, int idx);
+LUA_API lua_State *lua_tothread (lua_State *L, int idx);
+LUA_API const void *lua_topointer (lua_State *L, int idx);
+
+
+/*
+** push functions (C -> stack)
+*/
+LUA_API void lua_pushnil (lua_State *L);
+LUA_API void lua_pushnumber (lua_State *L, lua_Number n);
+LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t l);
+LUA_API void lua_pushstring (lua_State *L, const char *s);
+LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
+ va_list argp);
+LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...);
+LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n);
+LUA_API void lua_pushboolean (lua_State *L, int b);
+LUA_API void lua_pushlightuserdata (lua_State *L, void *p);
+
+
+/*
+** get functions (Lua -> stack)
+*/
+LUA_API void lua_gettable (lua_State *L, int idx);
+LUA_API void lua_rawget (lua_State *L, int idx);
+LUA_API void lua_rawgeti (lua_State *L, int idx, int n);
+LUA_API void lua_newtable (lua_State *L);
+LUA_API void *lua_newuserdata (lua_State *L, size_t sz);
+LUA_API int lua_getmetatable (lua_State *L, int objindex);
+LUA_API void lua_getfenv (lua_State *L, int idx);
+
+
+/*
+** set functions (stack -> Lua)
+*/
+LUA_API void lua_settable (lua_State *L, int idx);
+LUA_API void lua_rawset (lua_State *L, int idx);
+LUA_API void lua_rawseti (lua_State *L, int idx, int n);
+LUA_API int lua_setmetatable (lua_State *L, int objindex);
+LUA_API int lua_setfenv (lua_State *L, int idx);
+
+
+/*
+** `load' and `call' functions (load and run Lua code)
+*/
+LUA_API void lua_call (lua_State *L, int nargs, int nresults);
+LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc);
+LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud);
+LUA_API int lua_load (lua_State *L, lua_Chunkreader reader, void *dt,
+ const char *chunkname);
+
+LUA_API int lua_dump (lua_State *L, lua_Chunkwriter writer, void *data);
+
+
+/*
+** coroutine functions
+*/
+LUA_API int lua_yield (lua_State *L, int nresults);
+LUA_API int lua_resume (lua_State *L, int narg);
+
+/*
+** garbage-collection functions
+*/
+LUA_API int lua_getgcthreshold (lua_State *L);
+LUA_API int lua_getgccount (lua_State *L);
+LUA_API void lua_setgcthreshold (lua_State *L, int newthreshold);
+
+/*
+** miscellaneous functions
+*/
+
+LUA_API const char *lua_version (void);
+
+LUA_API int lua_error (lua_State *L);
+
+LUA_API int lua_next (lua_State *L, int idx);
+
+LUA_API void lua_concat (lua_State *L, int n);
+
+
+
+/*
+** ===============================================================
+** some useful macros
+** ===============================================================
+*/
+
+#define lua_boxpointer(L,u) \
+ (*(void **)(lua_newuserdata(L, sizeof(void *))) = (u))
+
+#define lua_unboxpointer(L,i) (*(void **)(lua_touserdata(L, i)))
+
+#define lua_pop(L,n) lua_settop(L, -(n)-1)
+
+#define lua_register(L,n,f) \
+ (lua_pushstring(L, n), \
+ lua_pushcfunction(L, f), \
+ lua_settable(L, LUA_GLOBALSINDEX))
+
+#define lua_pushcfunction(L,f) lua_pushcclosure(L, f, 0)
+
+#define lua_isfunction(L,n) (lua_type(L,n) == LUA_TFUNCTION)
+#define lua_istable(L,n) (lua_type(L,n) == LUA_TTABLE)
+#define lua_islightuserdata(L,n) (lua_type(L,n) == LUA_TLIGHTUSERDATA)
+#define lua_isnil(L,n) (lua_type(L,n) == LUA_TNIL)
+#define lua_isboolean(L,n) (lua_type(L,n) == LUA_TBOOLEAN)
+#define lua_isnone(L,n) (lua_type(L,n) == LUA_TNONE)
+#define lua_isnoneornil(L, n) (lua_type(L,n) <= 0)
+
+#define lua_pushliteral(L, s) \
+ lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1)
+
+
+
+/*
+** compatibility macros and functions
+*/
+
+
+LUA_API int lua_pushupvalues (lua_State *L);
+
+#define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX)
+#define lua_setglobal(L,s) \
+ (lua_pushstring(L, s), lua_insert(L, -2), lua_settable(L, LUA_GLOBALSINDEX))
+
+#define lua_getglobal(L,s) \
+ (lua_pushstring(L, s), lua_gettable(L, LUA_GLOBALSINDEX))
+
+
+/* compatibility with ref system */
+
+/* pre-defined references */
+#define LUA_NOREF (-2)
+#define LUA_REFNIL (-1)
+
+#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \
+ (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0))
+
+#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref))
+
+#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, ref)
+
+
+
+/*
+** {======================================================================
+** useful definitions for Lua kernel and libraries
+** =======================================================================
+*/
+
+/* formats for Lua numbers */
+#ifndef LUA_NUMBER_SCAN
+#define LUA_NUMBER_SCAN "%lf"
+#endif
+
+#ifndef LUA_NUMBER_FMT
+#define LUA_NUMBER_FMT "%.14g"
+#endif
+
+/* }====================================================================== */
+
+
+/*
+** {======================================================================
+** Debug API
+** =======================================================================
+*/
+
+
+/*
+** Event codes
+*/
+#define LUA_HOOKCALL 0
+#define LUA_HOOKRET 1
+#define LUA_HOOKLINE 2
+#define LUA_HOOKCOUNT 3
+#define LUA_HOOKTAILRET 4
+
+
+/*
+** Event masks
+*/
+#define LUA_MASKCALL (1 << LUA_HOOKCALL)
+#define LUA_MASKRET (1 << LUA_HOOKRET)
+#define LUA_MASKLINE (1 << LUA_HOOKLINE)
+#define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT)
+
+typedef struct lua_Debug lua_Debug; /* activation record */
+
+typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
+
+
+LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar);
+LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
+LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
+LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
+LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n);
+LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n);
+
+LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count);
+LUA_API lua_Hook lua_gethook (lua_State *L);
+LUA_API int lua_gethookmask (lua_State *L);
+LUA_API int lua_gethookcount (lua_State *L);
+
+
+#define LUA_IDSIZE 60
+
+struct lua_Debug {
+ int event;
+ const char *name; /* (n) */
+ const char *namewhat; /* (n) `global', `local', `field', `method' */
+ const char *what; /* (S) `Lua', `C', `main', `tail' */
+ const char *source; /* (S) */
+ int currentline; /* (l) */
+ int nups; /* (u) number of upvalues */
+ int linedefined; /* (S) */
+ char short_src[LUA_IDSIZE]; /* (S) */
+ /* private part */
+ int i_ci; /* active function */
+};
+
+/* }====================================================================== */
+
+
+/******************************************************************************
+* Copyright (C) 1994-2003 Tecgraf, PUC-Rio. All rights reserved.
+*
+* Permission is hereby granted, free of charge, to any person obtaining
+* a copy of this software and associated documentation files (the
+* "Software"), to deal in the Software without restriction, including
+* without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to
+* permit persons to whom the Software is furnished to do so, subject to
+* the following conditions:
+*
+* The above copyright notice and this permission notice shall be
+* included in all copies or substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+******************************************************************************/
+
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/luainc.h b/plugins/SmartAutoReplier/lualib/luainc.h
new file mode 100644
index 0000000000..1306197b64
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/luainc.h
@@ -0,0 +1,12 @@
+
+#ifndef __LUA_INC_H__
+#define __LUA_INC_H__
+
+extern "C"
+{
+ #include "lualib/lua.h"
+ #include "lualib/lauxlib.h"
+ #include "lualib/lualib.h"
+}
+
+#endif // __LUA_INC_H__ \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/lualib/lualib.h b/plugins/SmartAutoReplier/lualib/lualib.h
new file mode 100644
index 0000000000..e22c4c3063
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lualib.h
@@ -0,0 +1,56 @@
+/*
+** $Id: lualib.h,v 1.28 2003/03/18 12:24:26 roberto Exp $
+** Lua standard libraries
+** See Copyright Notice in lua.h
+*/
+
+
+#ifndef lualib_h
+#define lualib_h
+
+#include "lua.h"
+
+
+#ifndef LUALIB_API
+#define LUALIB_API LUA_API
+#endif
+
+
+#define LUA_COLIBNAME "coroutine"
+LUALIB_API int luaopen_base (lua_State *L);
+
+#define LUA_TABLIBNAME "table"
+LUALIB_API int luaopen_table (lua_State *L);
+
+#define LUA_IOLIBNAME "io"
+#define LUA_OSLIBNAME "os"
+LUALIB_API int luaopen_io (lua_State *L);
+
+#define LUA_STRLIBNAME "string"
+LUALIB_API int luaopen_string (lua_State *L);
+
+#define LUA_MATHLIBNAME "math"
+LUALIB_API int luaopen_math (lua_State *L);
+
+#define LUA_DBLIBNAME "debug"
+LUALIB_API int luaopen_debug (lua_State *L);
+
+
+LUALIB_API int luaopen_loadlib (lua_State *L);
+
+
+/* to help testing the libraries */
+#ifndef lua_assert
+#define lua_assert(c) /* empty */
+#endif
+
+
+/* compatibility code */
+#define lua_baselibopen luaopen_base
+#define lua_tablibopen luaopen_table
+#define lua_iolibopen luaopen_io
+#define lua_strlibopen luaopen_string
+#define lua_mathlibopen luaopen_math
+#define lua_dblibopen luaopen_debug
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lualib.vcxproj b/plugins/SmartAutoReplier/lualib/lualib.vcxproj
new file mode 100644
index 0000000000..b7618412cf
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lualib.vcxproj
@@ -0,0 +1,138 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>{6DB53D29-2EA9-407B-84F3-06E8031F3314}</ProjectGuid>
+ <Keyword>Win32Proj</Keyword>
+ <RootNamespace>lualib</RootNamespace>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <ConfigurationType>StaticLibrary</ConfigurationType>
+ <UseDebugLibraries>true</UseDebugLibraries>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <ConfigurationType>StaticLibrary</ConfigurationType>
+ <UseDebugLibraries>false</UseDebugLibraries>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup />
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ <WarningLevel>Level3</WarningLevel>
+ <Optimization>Disabled</Optimization>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_LIB</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ </ClCompile>
+ <Link>
+ <SubSystem>Windows</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <WarningLevel>Level3</WarningLevel>
+ <PrecompiledHeader>NotUsing</PrecompiledHeader>
+ <Optimization>MaxSpeed</Optimization>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <IntrinsicFunctions>true</IntrinsicFunctions>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ </ClCompile>
+ <Link>
+ <SubSystem>Windows</SubSystem>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <OptimizeReferences>true</OptimizeReferences>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <None Include="ReadMe.txt" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="lapi.h" />
+ <ClInclude Include="lauxlib.h" />
+ <ClInclude Include="lcode.h" />
+ <ClInclude Include="ldebug.h" />
+ <ClInclude Include="ldo.h" />
+ <ClInclude Include="lfunc.h" />
+ <ClInclude Include="lgc.h" />
+ <ClInclude Include="llex.h" />
+ <ClInclude Include="llimits.h" />
+ <ClInclude Include="lmem.h" />
+ <ClInclude Include="lobject.h" />
+ <ClInclude Include="lopcodes.h" />
+ <ClInclude Include="lparser.h" />
+ <ClInclude Include="lstate.h" />
+ <ClInclude Include="lstring.h" />
+ <ClInclude Include="ltable.h" />
+ <ClInclude Include="ltm.h" />
+ <ClInclude Include="lua.h" />
+ <ClInclude Include="luainc.h" />
+ <ClInclude Include="lualib.h" />
+ <ClInclude Include="lundump.h" />
+ <ClInclude Include="lvm.h" />
+ <ClInclude Include="lzio.h" />
+ <ClInclude Include="stdafx.h" />
+ <ClInclude Include="targetver.h" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="lapi.c" />
+ <ClCompile Include="lauxlib.c" />
+ <ClCompile Include="lbaselib.c" />
+ <ClCompile Include="lcode.c" />
+ <ClCompile Include="ldblib.c" />
+ <ClCompile Include="ldebug.c" />
+ <ClCompile Include="ldo.c" />
+ <ClCompile Include="ldump.c" />
+ <ClCompile Include="lfunc.c" />
+ <ClCompile Include="lgc.c" />
+ <ClCompile Include="liolib.c" />
+ <ClCompile Include="llex.c" />
+ <ClCompile Include="lmathlib.c" />
+ <ClCompile Include="lmem.c" />
+ <ClCompile Include="loadlib.c" />
+ <ClCompile Include="lobject.c" />
+ <ClCompile Include="lopcodes.c" />
+ <ClCompile Include="lparser.c" />
+ <ClCompile Include="lstate.c" />
+ <ClCompile Include="lstring.c" />
+ <ClCompile Include="lstrlib.c" />
+ <ClCompile Include="ltable.c" />
+ <ClCompile Include="ltablib.c" />
+ <ClCompile Include="ltests.c" />
+ <ClCompile Include="ltm.c" />
+ <ClCompile Include="lundump.c" />
+ <ClCompile Include="lvm.c" />
+ <ClCompile Include="lzio.c" />
+ <ClCompile Include="stdafx.cpp">
+ <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
+ <PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
+ </ClCompile>
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project> \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/lualib/lualib.vcxproj.filters b/plugins/SmartAutoReplier/lualib/lualib.vcxproj.filters
new file mode 100644
index 0000000000..a224003846
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lualib.vcxproj.filters
@@ -0,0 +1,186 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup>
+ <Filter Include="Source Files">
+ <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
+ <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
+ </Filter>
+ <Filter Include="Header Files">
+ <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
+ <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
+ </Filter>
+ <Filter Include="Resource Files">
+ <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
+ <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
+ </Filter>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="ReadMe.txt" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="stdafx.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="targetver.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lapi.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lauxlib.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lcode.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ldebug.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ldo.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lfunc.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lgc.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="llex.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="llimits.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lmem.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lobject.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lopcodes.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lparser.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lstate.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lstring.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ltable.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="ltm.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lua.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="luainc.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lualib.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lundump.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lvm.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ <ClInclude Include="lzio.h">
+ <Filter>Header Files</Filter>
+ </ClInclude>
+ </ItemGroup>
+ <ItemGroup>
+ <ClCompile Include="stdafx.cpp">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lapi.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lauxlib.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lbaselib.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lcode.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ldblib.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ldebug.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ldo.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ldump.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lfunc.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lgc.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="liolib.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="llex.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lmathlib.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lmem.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="loadlib.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lobject.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lopcodes.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lparser.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lstate.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lstring.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lstrlib.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ltable.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ltablib.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ltests.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="ltm.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lundump.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lvm.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ <ClCompile Include="lzio.c">
+ <Filter>Source Files</Filter>
+ </ClCompile>
+ </ItemGroup>
+</Project> \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/lualib/lundump.c b/plugins/SmartAutoReplier/lualib/lundump.c
new file mode 100644
index 0000000000..151a8507cc
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lundump.c
@@ -0,0 +1,286 @@
+/*
+** $Id: lundump.c,v 1.49 2003/04/07 20:34:20 lhf Exp $
+** load pre-compiled Lua chunks
+** See Copyright Notice in lua.h
+*/
+
+#define lundump_c
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "lfunc.h"
+#include "lmem.h"
+#include "lopcodes.h"
+#include "lstring.h"
+#include "lundump.h"
+#include "lzio.h"
+
+#define LoadByte (lu_byte) ezgetc
+
+typedef struct {
+ lua_State* L;
+ ZIO* Z;
+ Mbuffer* b;
+ int swap;
+ const char* name;
+} LoadState;
+
+static void unexpectedEOZ (LoadState* S)
+{
+ luaG_runerror(S->L,"unexpected end of file in %s",S->name);
+}
+
+static int ezgetc (LoadState* S)
+{
+ int c=zgetc(S->Z);
+ if (c==EOZ) unexpectedEOZ(S);
+ return c;
+}
+
+static void ezread (LoadState* S, void* b, int n)
+{
+ int r=luaZ_read(S->Z,b,n);
+ if (r!=0) unexpectedEOZ(S);
+}
+
+static void LoadBlock (LoadState* S, void* b, size_t size)
+{
+ if (S->swap)
+ {
+ char* p=(char*) b+size-1;
+ int n=size;
+ while (n--) *p--=(char)ezgetc(S);
+ }
+ else
+ ezread(S,b,size);
+}
+
+static void LoadVector (LoadState* S, void* b, int m, size_t size)
+{
+ if (S->swap)
+ {
+ char* q=(char*) b;
+ while (m--)
+ {
+ char* p=q+size-1;
+ int n=size;
+ while (n--) *p--=(char)ezgetc(S);
+ q+=size;
+ }
+ }
+ else
+ ezread(S,b,m*size);
+}
+
+static int LoadInt (LoadState* S)
+{
+ int x;
+ LoadBlock(S,&x,sizeof(x));
+ if (x<0) luaG_runerror(S->L,"bad integer in %s",S->name);
+ return x;
+}
+
+static size_t LoadSize (LoadState* S)
+{
+ size_t x;
+ LoadBlock(S,&x,sizeof(x));
+ return x;
+}
+
+static lua_Number LoadNumber (LoadState* S)
+{
+ lua_Number x;
+ LoadBlock(S,&x,sizeof(x));
+ return x;
+}
+
+static TString* LoadString (LoadState* S)
+{
+ size_t size=LoadSize(S);
+ if (size==0)
+ return NULL;
+ else
+ {
+ char* s=luaZ_openspace(S->L,S->b,size);
+ ezread(S,s,size);
+ return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */
+ }
+}
+
+static void LoadCode (LoadState* S, Proto* f)
+{
+ int size=LoadInt(S);
+ f->code=luaM_newvector(S->L,size,Instruction);
+ f->sizecode=size;
+ LoadVector(S,f->code,size,sizeof(*f->code));
+}
+
+static void LoadLocals (LoadState* S, Proto* f)
+{
+ int i,n;
+ n=LoadInt(S);
+ f->locvars=luaM_newvector(S->L,n,LocVar);
+ f->sizelocvars=n;
+ for (i=0; i<n; i++)
+ {
+ f->locvars[i].varname=LoadString(S);
+ f->locvars[i].startpc=LoadInt(S);
+ f->locvars[i].endpc=LoadInt(S);
+ }
+}
+
+static void LoadLines (LoadState* S, Proto* f)
+{
+ int size=LoadInt(S);
+ f->lineinfo=luaM_newvector(S->L,size,int);
+ f->sizelineinfo=size;
+ LoadVector(S,f->lineinfo,size,sizeof(*f->lineinfo));
+}
+
+static void LoadUpvalues (LoadState* S, Proto* f)
+{
+ int i,n;
+ n=LoadInt(S);
+ if (n!=0 && n!=f->nups)
+ luaG_runerror(S->L,"bad nupvalues in %s: read %d; expected %d",
+ S->name,n,f->nups);
+ f->upvalues=luaM_newvector(S->L,n,TString*);
+ f->sizeupvalues=n;
+ for (i=0; i<n; i++) f->upvalues[i]=LoadString(S);
+}
+
+static Proto* LoadFunction (LoadState* S, TString* p);
+
+static void LoadConstants (LoadState* S, Proto* f)
+{
+ int i,n;
+ n=LoadInt(S);
+ f->k=luaM_newvector(S->L,n,TObject);
+ f->sizek=n;
+ for (i=0; i<n; i++)
+ {
+ TObject* o=&f->k[i];
+ int t=LoadByte(S);
+ switch (t)
+ {
+ case LUA_TNUMBER:
+ setnvalue(o,LoadNumber(S));
+ break;
+ case LUA_TSTRING:
+ setsvalue2n(o,LoadString(S));
+ break;
+ case LUA_TNIL:
+ setnilvalue(o);
+ break;
+ default:
+ luaG_runerror(S->L,"bad constant type (%d) in %s",t,S->name);
+ break;
+ }
+ }
+ n=LoadInt(S);
+ f->p=luaM_newvector(S->L,n,Proto*);
+ f->sizep=n;
+ for (i=0; i<n; i++) f->p[i]=LoadFunction(S,f->source);
+}
+
+static Proto* LoadFunction (LoadState* S, TString* p)
+{
+ Proto* f=luaF_newproto(S->L);
+ f->source=LoadString(S); if (f->source==NULL) f->source=p;
+ f->lineDefined=LoadInt(S);
+ f->nups=LoadByte(S);
+ f->numparams=LoadByte(S);
+ f->is_vararg=LoadByte(S);
+ f->maxstacksize=LoadByte(S);
+ LoadLines(S,f);
+ LoadLocals(S,f);
+ LoadUpvalues(S,f);
+ LoadConstants(S,f);
+ LoadCode(S,f);
+#ifndef TRUST_BINARIES
+ if (!luaG_checkcode(f)) luaG_runerror(S->L,"bad code in %s",S->name);
+#endif
+ return f;
+}
+
+static void LoadSignature (LoadState* S)
+{
+ const char* s=LUA_SIGNATURE;
+ while (*s!=0 && ezgetc(S)==*s)
+ ++s;
+ if (*s!=0) luaG_runerror(S->L,"bad signature in %s",S->name);
+}
+
+static void TestSize (LoadState* S, int s, const char* what)
+{
+ int r=LoadByte(S);
+ if (r!=s)
+ luaG_runerror(S->L,"virtual machine mismatch in %s: "
+ "size of %s is %d but read %d",S->name,what,s,r);
+}
+
+#define TESTSIZE(s,w) TestSize(S,s,w)
+#define V(v) v/16,v%16
+
+static void LoadHeader (LoadState* S)
+{
+ int version;
+ lua_Number x,tx=TEST_NUMBER;
+ LoadSignature(S);
+ version=LoadByte(S);
+ if (version>VERSION)
+ luaG_runerror(S->L,"%s too new: "
+ "read version %d.%d; expected at most %d.%d",
+ S->name,V(version),V(VERSION));
+ if (version<VERSION0) /* check last major change */
+ luaG_runerror(S->L,"%s too old: "
+ "read version %d.%d; expected at least %d.%d",
+ S->name,V(version),V(VERSION0));
+ S->swap=(luaU_endianness()!=LoadByte(S)); /* need to swap bytes? */
+ TESTSIZE(sizeof(int),"int");
+ TESTSIZE(sizeof(size_t), "size_t");
+ TESTSIZE(sizeof(Instruction), "Instruction");
+ TESTSIZE(SIZE_OP, "OP");
+ TESTSIZE(SIZE_A, "A");
+ TESTSIZE(SIZE_B, "B");
+ TESTSIZE(SIZE_C, "C");
+ TESTSIZE(sizeof(lua_Number), "number");
+ x=LoadNumber(S);
+ if ((long)x!=(long)tx) /* disregard errors in last bits of fraction */
+ luaG_runerror(S->L,"unknown number format in %s",S->name);
+}
+
+static Proto* LoadChunk (LoadState* S)
+{
+ LoadHeader(S);
+ return LoadFunction(S,NULL);
+}
+
+/*
+** load precompiled chunk
+*/
+Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff)
+{
+ LoadState S;
+ const char* s=zname(Z);
+ if (*s=='@' || *s=='=')
+ S.name=s+1;
+ else if (*s==LUA_SIGNATURE[0])
+ S.name="binary string";
+ else
+ S.name=s;
+ S.L=L;
+ S.Z=Z;
+ S.b=buff;
+ return LoadChunk(&S);
+}
+
+/*
+** find byte order
+*/
+int luaU_endianness (void)
+{
+ int x=1;
+ return *(char*)&x;
+}
diff --git a/plugins/SmartAutoReplier/lualib/lundump.h b/plugins/SmartAutoReplier/lualib/lundump.h
new file mode 100644
index 0000000000..c7e6959b30
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lundump.h
@@ -0,0 +1,34 @@
+/*
+** $Id: lundump.h,v 1.30 2003/04/07 20:34:20 lhf Exp $
+** load pre-compiled Lua chunks
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lundump_h
+#define lundump_h
+
+#include "lobject.h"
+#include "lzio.h"
+
+/* load one chunk; from lundump.c */
+Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff);
+
+/* find byte order; from lundump.c */
+int luaU_endianness (void);
+
+/* dump one chunk; from ldump.c */
+void luaU_dump (lua_State* L, const Proto* Main, lua_Chunkwriter w, void* data);
+
+/* print one chunk; from print.c */
+void luaU_print (const Proto* Main);
+
+/* definitions for headers of binary files */
+#define LUA_SIGNATURE "\033Lua" /* binary files start with "<esc>Lua" */
+#define VERSION 0x50 /* last format change was in 5.0 */
+#define VERSION0 0x50 /* last major change was in 5.0 */
+
+/* a multiple of PI for testing native format */
+/* multiplying by 1E7 gives non-trivial integer values */
+#define TEST_NUMBER ((lua_Number)3.14159265358979323846E7)
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lvm.c b/plugins/SmartAutoReplier/lualib/lvm.c
new file mode 100644
index 0000000000..eaa5c700b0
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lvm.c
@@ -0,0 +1,780 @@
+/*
+** $Id: lvm.c,v 1.284 2003/04/03 13:35:34 roberto Exp $
+** Lua virtual machine
+** See Copyright Notice in lua.h
+*/
+
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* needed only when `lua_number2str' uses `sprintf' */
+#include <stdio.h>
+
+#define lvm_c
+
+#include "lua.h"
+
+#include "ldebug.h"
+#include "ldo.h"
+#include "lfunc.h"
+#include "lgc.h"
+#include "lobject.h"
+#include "lopcodes.h"
+#include "lstate.h"
+#include "lstring.h"
+#include "ltable.h"
+#include "ltm.h"
+#include "lvm.h"
+
+
+
+/* function to convert a lua_Number to a string */
+#ifndef lua_number2str
+#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n))
+#endif
+
+
+/* limit for table tag-method chains (to avoid loops) */
+#define MAXTAGLOOP 100
+
+
+const TObject *luaV_tonumber (const TObject *obj, TObject *n) {
+ lua_Number num;
+ if (ttisnumber(obj)) return obj;
+ if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) {
+ setnvalue(n, num);
+ return n;
+ }
+ else
+ return NULL;
+}
+
+
+int luaV_tostring (lua_State *L, StkId obj) {
+ if (!ttisnumber(obj))
+ return 0;
+ else {
+ char s[32]; /* 16 digits, sign, point and \0 (+ some extra...) */
+ lua_number2str(s, nvalue(obj));
+ setsvalue2s(obj, luaS_new(L, s));
+ return 1;
+ }
+}
+
+
+static void traceexec (lua_State *L) {
+ lu_byte mask = L->hookmask;
+ if (mask > LUA_MASKLINE) { /* instruction-hook set? */
+ if (L->hookcount == 0) {
+ resethookcount(L);
+ luaD_callhook(L, LUA_HOOKCOUNT, -1);
+ return;
+ }
+ }
+ if (mask & LUA_MASKLINE) {
+ CallInfo *ci = L->ci;
+ Proto *p = ci_func(ci)->l.p;
+ int newline = getline(p, pcRel(*ci->u.l.pc, p));
+ if (!L->hookinit) {
+ luaG_inithooks(L);
+ return;
+ }
+ lua_assert(ci->state & CI_HASFRAME);
+ if (pcRel(*ci->u.l.pc, p) == 0) /* tracing may be starting now? */
+ ci->u.l.savedpc = *ci->u.l.pc; /* initialize `savedpc' */
+ /* calls linehook when enters a new line or jumps back (loop) */
+ if (*ci->u.l.pc <= ci->u.l.savedpc ||
+ newline != getline(p, pcRel(ci->u.l.savedpc, p))) {
+ luaD_callhook(L, LUA_HOOKLINE, newline);
+ ci = L->ci; /* previous call may reallocate `ci' */
+ }
+ ci->u.l.savedpc = *ci->u.l.pc;
+ }
+}
+
+
+static void callTMres (lua_State *L, const TObject *f,
+ const TObject *p1, const TObject *p2) {
+ setobj2s(L->top, f); /* push function */
+ setobj2s(L->top+1, p1); /* 1st argument */
+ setobj2s(L->top+2, p2); /* 2nd argument */
+ luaD_checkstack(L, 3); /* cannot check before (could invalidate p1, p2) */
+ L->top += 3;
+ luaD_call(L, L->top - 3, 1);
+ L->top--; /* result will be in L->top */
+}
+
+
+
+static void callTM (lua_State *L, const TObject *f,
+ const TObject *p1, const TObject *p2, const TObject *p3) {
+ setobj2s(L->top, f); /* push function */
+ setobj2s(L->top+1, p1); /* 1st argument */
+ setobj2s(L->top+2, p2); /* 2nd argument */
+ setobj2s(L->top+3, p3); /* 3th argument */
+ luaD_checkstack(L, 4); /* cannot check before (could invalidate p1...p3) */
+ L->top += 4;
+ luaD_call(L, L->top - 4, 0);
+}
+
+
+static const TObject *luaV_index (lua_State *L, const TObject *t,
+ TObject *key, int loop) {
+ const TObject *tm = fasttm(L, hvalue(t)->metatable, TM_INDEX);
+ if (tm == NULL) return &luaO_nilobject; /* no TM */
+ if (ttisfunction(tm)) {
+ callTMres(L, tm, t, key);
+ return L->top;
+ }
+ else return luaV_gettable(L, tm, key, loop);
+}
+
+static const TObject *luaV_getnotable (lua_State *L, const TObject *t,
+ TObject *key, int loop) {
+ const TObject *tm = luaT_gettmbyobj(L, t, TM_INDEX);
+ if (ttisnil(tm))
+ luaG_typeerror(L, t, "index");
+ if (ttisfunction(tm)) {
+ callTMres(L, tm, t, key);
+ return L->top;
+ }
+ else return luaV_gettable(L, tm, key, loop);
+}
+
+
+/*
+** Function to index a table.
+** Receives the table at `t' and the key at `key'.
+** leaves the result at `res'.
+*/
+const TObject *luaV_gettable (lua_State *L, const TObject *t, TObject *key,
+ int loop) {
+ if (loop > MAXTAGLOOP)
+ luaG_runerror(L, "loop in gettable");
+ if (ttistable(t)) { /* `t' is a table? */
+ Table *h = hvalue(t);
+ const TObject *v = luaH_get(h, key); /* do a primitive get */
+ if (!ttisnil(v)) return v;
+ else return luaV_index(L, t, key, loop+1);
+ }
+ else return luaV_getnotable(L, t, key, loop+1);
+}
+
+
+/*
+** Receives table at `t', key at `key' and value at `val'.
+*/
+void luaV_settable (lua_State *L, const TObject *t, TObject *key, StkId val) {
+ const TObject *tm;
+ int loop = 0;
+ do {
+ if (ttistable(t)) { /* `t' is a table? */
+ Table *h = hvalue(t);
+ TObject *oldval = luaH_set(L, h, key); /* do a primitive set */
+ if (!ttisnil(oldval) || /* result is no nil? */
+ (tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */
+ setobj2t(oldval, val); /* write barrier */
+ return;
+ }
+ /* else will try the tag method */
+ }
+ else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
+ luaG_typeerror(L, t, "index");
+ if (ttisfunction(tm)) {
+ callTM(L, tm, t, key, val);
+ return;
+ }
+ t = tm; /* else repeat with `tm' */
+ } while (++loop <= MAXTAGLOOP);
+ luaG_runerror(L, "loop in settable");
+}
+
+
+static int call_binTM (lua_State *L, const TObject *p1, const TObject *p2,
+ StkId res, TMS event) {
+ ptrdiff_t result = savestack(L, res);
+ const TObject *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */
+ if (ttisnil(tm))
+ tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
+ if (!ttisfunction(tm)) return 0;
+ callTMres(L, tm, p1, p2);
+ res = restorestack(L, result); /* previous call may change stack */
+ setobjs2s(res, L->top);
+ return 1;
+}
+
+
+static const TObject *get_compTM (lua_State *L, Table *mt1, Table *mt2,
+ TMS event) {
+ const TObject *tm1 = fasttm(L, mt1, event);
+ const TObject *tm2;
+ if (tm1 == NULL) return NULL; /* no metamethod */
+ if (mt1 == mt2) return tm1; /* same metatables => same metamethods */
+ tm2 = fasttm(L, mt2, event);
+ if (tm2 == NULL) return NULL; /* no metamethod */
+ if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */
+ return tm1;
+ return NULL;
+}
+
+
+static int call_orderTM (lua_State *L, const TObject *p1, const TObject *p2,
+ TMS event) {
+ const TObject *tm1 = luaT_gettmbyobj(L, p1, event);
+ const TObject *tm2;
+ if (ttisnil(tm1)) return -1; /* no metamethod? */
+ tm2 = luaT_gettmbyobj(L, p2, event);
+ if (!luaO_rawequalObj(tm1, tm2)) /* different metamethods? */
+ return -1;
+ callTMres(L, tm1, p1, p2);
+ return !l_isfalse(L->top);
+}
+
+
+static int luaV_strcmp (const TString *ls, const TString *rs) {
+ const char *l = getstr(ls);
+ size_t ll = ls->tsv.len;
+ const char *r = getstr(rs);
+ size_t lr = rs->tsv.len;
+ for (;;) {
+ int temp = strcoll(l, r);
+ if (temp != 0) return temp;
+ else { /* strings are equal up to a `\0' */
+ size_t len = strlen(l); /* index of first `\0' in both strings */
+ if (len == lr) /* r is finished? */
+ return (len == ll) ? 0 : 1;
+ else if (len == ll) /* l is finished? */
+ return -1; /* l is smaller than r (because r is not finished) */
+ /* both strings longer than `len'; go on comparing (after the `\0') */
+ len++;
+ l += len; ll -= len; r += len; lr -= len;
+ }
+ }
+}
+
+
+int luaV_lessthan (lua_State *L, const TObject *l, const TObject *r) {
+ int res;
+ if (ttype(l) != ttype(r))
+ return luaG_ordererror(L, l, r);
+ else if (ttisnumber(l))
+ return nvalue(l) < nvalue(r);
+ else if (ttisstring(l))
+ return luaV_strcmp(tsvalue(l), tsvalue(r)) < 0;
+ else if ((res = call_orderTM(L, l, r, TM_LT)) != -1)
+ return res;
+ return luaG_ordererror(L, l, r);
+}
+
+
+static int luaV_lessequal (lua_State *L, const TObject *l, const TObject *r) {
+ int res;
+ if (ttype(l) != ttype(r))
+ return luaG_ordererror(L, l, r);
+ else if (ttisnumber(l))
+ return nvalue(l) <= nvalue(r);
+ else if (ttisstring(l))
+ return luaV_strcmp(tsvalue(l), tsvalue(r)) <= 0;
+ else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */
+ return res;
+ else if ((res = call_orderTM(L, r, l, TM_LT)) != -1) /* else try `lt' */
+ return !res;
+ return luaG_ordererror(L, l, r);
+}
+
+
+int luaV_equalval (lua_State *L, const TObject *t1, const TObject *t2) {
+ const TObject *tm;
+ lua_assert(ttype(t1) == ttype(t2));
+ switch (ttype(t1)) {
+ case LUA_TNIL: return 1;
+ case LUA_TNUMBER: return nvalue(t1) == nvalue(t2);
+ case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */
+ case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
+ case LUA_TUSERDATA: {
+ if (uvalue(t1) == uvalue(t2)) return 1;
+ tm = get_compTM(L, uvalue(t1)->uv.metatable, uvalue(t2)->uv.metatable,
+ TM_EQ);
+ break; /* will try TM */
+ }
+ case LUA_TTABLE: {
+ if (hvalue(t1) == hvalue(t2)) return 1;
+ tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
+ break; /* will try TM */
+ }
+ default: return gcvalue(t1) == gcvalue(t2);
+ }
+ if (tm == NULL) return 0; /* no TM? */
+ callTMres(L, tm, t1, t2); /* call TM */
+ return !l_isfalse(L->top);
+}
+
+
+void luaV_concat (lua_State *L, int total, int last) {
+ do {
+ StkId top = L->base + last + 1;
+ int n = 2; /* number of elements handled in this pass (at least 2) */
+ if (!tostring(L, top-2) || !tostring(L, top-1)) {
+ if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
+ luaG_concaterror(L, top-2, top-1);
+ } else if (tsvalue(top-1)->tsv.len > 0) { /* if len=0, do nothing */
+ /* at least two string values; get as many as possible */
+ lu_mem tl = cast(lu_mem, tsvalue(top-1)->tsv.len) +
+ cast(lu_mem, tsvalue(top-2)->tsv.len);
+ char *buffer;
+ int i;
+ while (n < total && tostring(L, top-n-1)) { /* collect total length */
+ tl += tsvalue(top-n-1)->tsv.len;
+ n++;
+ }
+ if (tl > MAX_SIZET) luaG_runerror(L, "string size overflow");
+ buffer = luaZ_openspace(L, &G(L)->buff, tl);
+ tl = 0;
+ for (i=n; i>0; i--) { /* concat all strings */
+ size_t l = tsvalue(top-i)->tsv.len;
+ memcpy(buffer+tl, svalue(top-i), l);
+ tl += l;
+ }
+ setsvalue2s(top-n, luaS_newlstr(L, buffer, tl));
+ }
+ total -= n-1; /* got `n' strings to create 1 new */
+ last -= n-1;
+ } while (total > 1); /* repeat until only 1 result left */
+}
+
+
+static void Arith (lua_State *L, StkId ra,
+ const TObject *rb, const TObject *rc, TMS op) {
+ TObject tempb, tempc;
+ const TObject *b, *c;
+ if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
+ (c = luaV_tonumber(rc, &tempc)) != NULL) {
+ switch (op) {
+ case TM_ADD: setnvalue(ra, nvalue(b) + nvalue(c)); break;
+ case TM_SUB: setnvalue(ra, nvalue(b) - nvalue(c)); break;
+ case TM_MUL: setnvalue(ra, nvalue(b) * nvalue(c)); break;
+ case TM_DIV: setnvalue(ra, nvalue(b) / nvalue(c)); break;
+ case TM_POW: {
+ const TObject *f = luaH_getstr(hvalue(gt(L)), G(L)->tmname[TM_POW]);
+ ptrdiff_t res = savestack(L, ra);
+ if (!ttisfunction(f))
+ luaG_runerror(L, "`__pow' (`^' operator) is not a function");
+ callTMres(L, f, b, c);
+ ra = restorestack(L, res); /* previous call may change stack */
+ setobjs2s(ra, L->top);
+ break;
+ }
+ default: lua_assert(0); break;
+ }
+ }
+ else if (!call_binTM(L, rb, rc, ra, op))
+ luaG_aritherror(L, rb, rc);
+}
+
+
+
+/*
+** some macros for common tasks in `luaV_execute'
+*/
+
+#define runtime_check(L, c) { if (!(c)) return 0; }
+
+#define RA(i) (base+GETARG_A(i))
+/* to be used after possible stack reallocation */
+#define XRA(i) (L->base+GETARG_A(i))
+#define RB(i) (base+GETARG_B(i))
+#define RKB(i) ((GETARG_B(i) < MAXSTACK) ? RB(i) : k+GETARG_B(i)-MAXSTACK)
+#define RC(i) (base+GETARG_C(i))
+#define RKC(i) ((GETARG_C(i) < MAXSTACK) ? RC(i) : k+GETARG_C(i)-MAXSTACK)
+#define KBx(i) (k+GETARG_Bx(i))
+
+
+#define dojump(pc, i) ((pc) += (i))
+
+
+StkId luaV_execute (lua_State *L) {
+ LClosure *cl;
+ TObject *k;
+ const Instruction *pc;
+ callentry: /* entry point when calling new functions */
+ L->ci->u.l.pc = &pc;
+ if (L->hookmask & LUA_MASKCALL)
+ luaD_callhook(L, LUA_HOOKCALL, -1);
+ retentry: /* entry point when returning to old functions */
+ lua_assert(L->ci->state == CI_SAVEDPC ||
+ L->ci->state == (CI_SAVEDPC | CI_CALLING));
+ L->ci->state = CI_HASFRAME; /* activate frame */
+ pc = L->ci->u.l.savedpc;
+ cl = &clvalue(L->base - 1)->l;
+ k = cl->p->k;
+ /* main loop of interpreter */
+ for (;;) {
+ const Instruction i = *pc++;
+ StkId base, ra;
+ if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
+ (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
+ traceexec(L);
+ if (L->ci->state & CI_YIELD) { /* did hook yield? */
+ L->ci->u.l.savedpc = pc - 1;
+ L->ci->state = CI_YIELD | CI_SAVEDPC;
+ return NULL;
+ }
+ }
+ /* warning!! several calls may realloc the stack and invalidate `ra' */
+ base = L->base;
+ ra = RA(i);
+ lua_assert(L->ci->state & CI_HASFRAME);
+ lua_assert(base == L->ci->base);
+ lua_assert(L->top <= L->stack + L->stacksize && L->top >= base);
+ lua_assert(L->top == L->ci->top ||
+ GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL ||
+ GET_OPCODE(i) == OP_RETURN || GET_OPCODE(i) == OP_SETLISTO);
+ switch (GET_OPCODE(i)) {
+ case OP_MOVE: {
+ setobjs2s(ra, RB(i));
+ break;
+ }
+ case OP_LOADK: {
+ setobj2s(ra, KBx(i));
+ break;
+ }
+ case OP_LOADBOOL: {
+ setbvalue(ra, GETARG_B(i));
+ if (GETARG_C(i)) pc++; /* skip next instruction (if C) */
+ break;
+ }
+ case OP_LOADNIL: {
+ TObject *rb = RB(i);
+ do {
+ setnilvalue(rb--);
+ } while (rb >= ra);
+ break;
+ }
+ case OP_GETUPVAL: {
+ int b = GETARG_B(i);
+ setobj2s(ra, cl->upvals[b]->v);
+ break;
+ }
+ case OP_GETGLOBAL: {
+ TObject *rb = KBx(i);
+ const TObject *v;
+ lua_assert(ttisstring(rb) && ttistable(&cl->g));
+ v = luaH_getstr(hvalue(&cl->g), tsvalue(rb));
+ if (!ttisnil(v)) { setobj2s(ra, v); }
+ else
+ setobj2s(XRA(i), luaV_index(L, &cl->g, rb, 0));
+ break;
+ }
+ case OP_GETTABLE: {
+ StkId rb = RB(i);
+ TObject *rc = RKC(i);
+ if (ttistable(rb)) {
+ const TObject *v = luaH_get(hvalue(rb), rc);
+ if (!ttisnil(v)) { setobj2s(ra, v); }
+ else
+ setobj2s(XRA(i), luaV_index(L, rb, rc, 0));
+ }
+ else
+ setobj2s(XRA(i), luaV_getnotable(L, rb, rc, 0));
+ break;
+ }
+ case OP_SETGLOBAL: {
+ lua_assert(ttisstring(KBx(i)) && ttistable(&cl->g));
+ luaV_settable(L, &cl->g, KBx(i), ra);
+ break;
+ }
+ case OP_SETUPVAL: {
+ int b = GETARG_B(i);
+ setobj(cl->upvals[b]->v, ra); /* write barrier */
+ break;
+ }
+ case OP_SETTABLE: {
+ luaV_settable(L, ra, RKB(i), RKC(i));
+ break;
+ }
+ case OP_NEWTABLE: {
+ int b = GETARG_B(i);
+ b = fb2int(b);
+ sethvalue(ra, luaH_new(L, b, GETARG_C(i)));
+ luaC_checkGC(L);
+ break;
+ }
+ case OP_SELF: {
+ StkId rb = RB(i);
+ TObject *rc = RKC(i);
+ runtime_check(L, ttisstring(rc));
+ setobjs2s(ra+1, rb);
+ if (ttistable(rb)) {
+ const TObject *v = luaH_getstr(hvalue(rb), tsvalue(rc));
+ if (!ttisnil(v)) { setobj2s(ra, v); }
+ else
+ setobj2s(XRA(i), luaV_index(L, rb, rc, 0));
+ }
+ else
+ setobj2s(XRA(i), luaV_getnotable(L, rb, rc, 0));
+ break;
+ }
+ case OP_ADD: {
+ TObject *rb = RKB(i);
+ TObject *rc = RKC(i);
+ if (ttisnumber(rb) && ttisnumber(rc)) {
+ setnvalue(ra, nvalue(rb) + nvalue(rc));
+ }
+ else
+ Arith(L, ra, rb, rc, TM_ADD);
+ break;
+ }
+ case OP_SUB: {
+ TObject *rb = RKB(i);
+ TObject *rc = RKC(i);
+ if (ttisnumber(rb) && ttisnumber(rc)) {
+ setnvalue(ra, nvalue(rb) - nvalue(rc));
+ }
+ else
+ Arith(L, ra, rb, rc, TM_SUB);
+ break;
+ }
+ case OP_MUL: {
+ TObject *rb = RKB(i);
+ TObject *rc = RKC(i);
+ if (ttisnumber(rb) && ttisnumber(rc)) {
+ setnvalue(ra, nvalue(rb) * nvalue(rc));
+ }
+ else
+ Arith(L, ra, rb, rc, TM_MUL);
+ break;
+ }
+ case OP_DIV: {
+ TObject *rb = RKB(i);
+ TObject *rc = RKC(i);
+ if (ttisnumber(rb) && ttisnumber(rc)) {
+ setnvalue(ra, nvalue(rb) / nvalue(rc));
+ }
+ else
+ Arith(L, ra, rb, rc, TM_DIV);
+ break;
+ }
+ case OP_POW: {
+ Arith(L, ra, RKB(i), RKC(i), TM_POW);
+ break;
+ }
+ case OP_UNM: {
+ const TObject *rb = RB(i);
+ TObject temp;
+ if (tonumber(rb, &temp)) {
+ setnvalue(ra, -nvalue(rb));
+ }
+ else {
+ setnilvalue(&temp);
+ if (!call_binTM(L, RB(i), &temp, ra, TM_UNM))
+ luaG_aritherror(L, RB(i), &temp);
+ }
+ break;
+ }
+ case OP_NOT: {
+ int res = l_isfalse(RB(i)); /* next assignment may change this value */
+ setbvalue(ra, res);
+ break;
+ }
+ case OP_CONCAT: {
+ int b = GETARG_B(i);
+ int c = GETARG_C(i);
+ luaV_concat(L, c-b+1, c); /* may change `base' (and `ra') */
+ base = L->base;
+ setobjs2s(RA(i), base+b);
+ luaC_checkGC(L);
+ break;
+ }
+ case OP_JMP: {
+ dojump(pc, GETARG_sBx(i));
+ break;
+ }
+ case OP_EQ: {
+ if (equalobj(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
+ else dojump(pc, GETARG_sBx(*pc) + 1);
+ break;
+ }
+ case OP_LT: {
+ if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
+ else dojump(pc, GETARG_sBx(*pc) + 1);
+ break;
+ }
+ case OP_LE: {
+ if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i)) pc++;
+ else dojump(pc, GETARG_sBx(*pc) + 1);
+ break;
+ }
+ case OP_TEST: {
+ TObject *rb = RB(i);
+ if (l_isfalse(rb) == GETARG_C(i)) pc++;
+ else {
+ setobjs2s(ra, rb);
+ dojump(pc, GETARG_sBx(*pc) + 1);
+ }
+ break;
+ }
+ case OP_CALL:
+ case OP_TAILCALL: {
+ StkId firstResult;
+ int b = GETARG_B(i);
+ int nresults;
+ if (b != 0) L->top = ra+b; /* else previous instruction set top */
+ nresults = GETARG_C(i) - 1;
+ firstResult = luaD_precall(L, ra);
+ if (firstResult) {
+ if (firstResult > L->top) { /* yield? */
+ lua_assert(L->ci->state == (CI_C | CI_YIELD));
+ (L->ci - 1)->u.l.savedpc = pc;
+ (L->ci - 1)->state = CI_SAVEDPC;
+ return NULL;
+ }
+ /* it was a C function (`precall' called it); adjust results */
+ luaD_poscall(L, nresults, firstResult);
+ if (nresults >= 0) L->top = L->ci->top;
+ }
+ else { /* it is a Lua function */
+ if (GET_OPCODE(i) == OP_CALL) { /* regular call? */
+ (L->ci-1)->u.l.savedpc = pc; /* save `pc' to return later */
+ (L->ci-1)->state = (CI_SAVEDPC | CI_CALLING);
+ }
+ else { /* tail call: put new frame in place of previous one */
+ int aux;
+ base = (L->ci - 1)->base; /* `luaD_precall' may change the stack */
+ ra = RA(i);
+ if (L->openupval) luaF_close(L, base);
+ for (aux = 0; ra+aux < L->top; aux++) /* move frame down */
+ setobjs2s(base+aux-1, ra+aux);
+ (L->ci - 1)->top = L->top = base+aux; /* correct top */
+ lua_assert(L->ci->state & CI_SAVEDPC);
+ (L->ci - 1)->u.l.savedpc = L->ci->u.l.savedpc;
+ (L->ci - 1)->u.l.tailcalls++; /* one more call lost */
+ (L->ci - 1)->state = CI_SAVEDPC;
+ L->ci--; /* remove new frame */
+ L->base = L->ci->base;
+ }
+ goto callentry;
+ }
+ break;
+ }
+ case OP_RETURN: {
+ CallInfo *ci = L->ci - 1; /* previous function frame */
+ int b = GETARG_B(i);
+ if (b != 0) L->top = ra+b-1;
+ lua_assert(L->ci->state & CI_HASFRAME);
+ if (L->openupval) luaF_close(L, base);
+ L->ci->state = CI_SAVEDPC; /* deactivate current function */
+ L->ci->u.l.savedpc = pc;
+ /* previous function was running `here'? */
+ if (!(ci->state & CI_CALLING)) {
+ lua_assert((ci->state & CI_C) || ci->u.l.pc != &pc);
+ return ra; /* no: return */
+ }
+ else { /* yes: continue its execution */
+ int nresults;
+ lua_assert(ci->u.l.pc == &pc &&
+ ttisfunction(ci->base - 1) &&
+ (ci->state & CI_SAVEDPC));
+ lua_assert(GET_OPCODE(*(ci->u.l.savedpc - 1)) == OP_CALL);
+ nresults = GETARG_C(*(ci->u.l.savedpc - 1)) - 1;
+ luaD_poscall(L, nresults, ra);
+ if (nresults >= 0) L->top = L->ci->top;
+ goto retentry;
+ }
+ }
+ case OP_FORLOOP: {
+ lua_Number step, idx, limit;
+ const TObject *plimit = ra+1;
+ const TObject *pstep = ra+2;
+ if (!ttisnumber(ra))
+ luaG_runerror(L, "`for' initial value must be a number");
+ if (!tonumber(plimit, ra+1))
+ luaG_runerror(L, "`for' limit must be a number");
+ if (!tonumber(pstep, ra+2))
+ luaG_runerror(L, "`for' step must be a number");
+ step = nvalue(pstep);
+ idx = nvalue(ra) + step; /* increment index */
+ limit = nvalue(plimit);
+ if (step > 0 ? idx <= limit : idx >= limit) {
+ dojump(pc, GETARG_sBx(i)); /* jump back */
+ chgnvalue(ra, idx); /* update index */
+ }
+ break;
+ }
+ case OP_TFORLOOP: {
+ int nvar = GETARG_C(i) + 1;
+ StkId cb = ra + nvar + 2; /* call base */
+ setobjs2s(cb, ra);
+ setobjs2s(cb+1, ra+1);
+ setobjs2s(cb+2, ra+2);
+ L->top = cb+3; /* func. + 2 args (state and index) */
+ luaD_call(L, cb, nvar);
+ L->top = L->ci->top;
+ ra = XRA(i) + 2; /* final position of first result */
+ cb = ra + nvar;
+ do { /* move results to proper positions */
+ nvar--;
+ setobjs2s(ra+nvar, cb+nvar);
+ } while (nvar > 0);
+ if (ttisnil(ra)) /* break loop? */
+ pc++; /* skip jump (break loop) */
+ else
+ dojump(pc, GETARG_sBx(*pc) + 1); /* jump back */
+ break;
+ }
+ case OP_TFORPREP: { /* for compatibility only */
+ if (ttistable(ra)) {
+ setobjs2s(ra+1, ra);
+ setobj2s(ra, luaH_getstr(hvalue(gt(L)), luaS_new(L, "next")));
+ }
+ dojump(pc, GETARG_sBx(i));
+ break;
+ }
+ case OP_SETLIST:
+ case OP_SETLISTO: {
+ int bc;
+ int n;
+ Table *h;
+ runtime_check(L, ttistable(ra));
+ h = hvalue(ra);
+ bc = GETARG_Bx(i);
+ if (GET_OPCODE(i) == OP_SETLIST)
+ n = (bc&(LFIELDS_PER_FLUSH-1)) + 1;
+ else {
+ n = L->top - ra - 1;
+ L->top = L->ci->top;
+ }
+ bc &= ~(LFIELDS_PER_FLUSH-1); /* bc = bc - bc%FPF */
+ for (; n > 0; n--)
+ setobj2t(luaH_setnum(L, h, bc+n), ra+n); /* write barrier */
+ break;
+ }
+ case OP_CLOSE: {
+ luaF_close(L, ra);
+ break;
+ }
+ case OP_CLOSURE: {
+ Proto *p;
+ Closure *ncl;
+ int nup, j;
+ p = cl->p->p[GETARG_Bx(i)];
+ nup = p->nups;
+ ncl = luaF_newLclosure(L, nup, &cl->g);
+ ncl->l.p = p;
+ for (j=0; j<nup; j++, pc++) {
+ if (GET_OPCODE(*pc) == OP_GETUPVAL)
+ ncl->l.upvals[j] = cl->upvals[GETARG_B(*pc)];
+ else {
+ lua_assert(GET_OPCODE(*pc) == OP_MOVE);
+ ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc));
+ }
+ }
+ setclvalue(ra, ncl);
+ luaC_checkGC(L);
+ break;
+ }
+ }
+ }
+}
+
diff --git a/plugins/SmartAutoReplier/lualib/lvm.h b/plugins/SmartAutoReplier/lualib/lvm.h
new file mode 100644
index 0000000000..19cce200b6
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lvm.h
@@ -0,0 +1,35 @@
+/*
+** $Id: lvm.h,v 1.47 2002/11/14 16:16:21 roberto Exp $
+** Lua virtual machine
+** See Copyright Notice in lua.h
+*/
+
+#ifndef lvm_h
+#define lvm_h
+
+
+#include "ldo.h"
+#include "lobject.h"
+#include "ltm.h"
+
+
+#define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o)))
+
+#define tonumber(o,n) (ttype(o) == LUA_TNUMBER || \
+ (((o) = luaV_tonumber(o,n)) != NULL))
+
+#define equalobj(L,o1,o2) \
+ (ttype(o1) == ttype(o2) && luaV_equalval(L, o1, o2))
+
+
+int luaV_lessthan (lua_State *L, const TObject *l, const TObject *r);
+int luaV_equalval (lua_State *L, const TObject *t1, const TObject *t2);
+const TObject *luaV_tonumber (const TObject *obj, TObject *n);
+int luaV_tostring (lua_State *L, StkId obj);
+const TObject *luaV_gettable (lua_State *L, const TObject *t, TObject *key,
+ int loop);
+void luaV_settable (lua_State *L, const TObject *t, TObject *key, StkId val);
+StkId luaV_execute (lua_State *L);
+void luaV_concat (lua_State *L, int total, int last);
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/lzio.c b/plugins/SmartAutoReplier/lualib/lzio.c
new file mode 100644
index 0000000000..3aeca1c588
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lzio.c
@@ -0,0 +1,81 @@
+/*
+** $Id: lzio.c,v 1.24 2003/03/20 16:00:56 roberto Exp $
+** a generic input stream interface
+** See Copyright Notice in lua.h
+*/
+
+
+#include <string.h>
+
+#define lzio_c
+
+#include "lua.h"
+
+#include "llimits.h"
+#include "lmem.h"
+#include "lzio.h"
+
+
+int luaZ_fill (ZIO *z) {
+ size_t size;
+ const char *buff = z->reader(NULL, z->data, &size);
+ if (buff == NULL || size == 0) return EOZ;
+ z->n = size - 1;
+ z->p = buff;
+ return char2int(*(z->p++));
+}
+
+
+int luaZ_lookahead (ZIO *z) {
+ if (z->n == 0) {
+ int c = luaZ_fill(z);
+ if (c == EOZ) return c;
+ z->n++;
+ z->p--;
+ }
+ return char2int(*z->p);
+}
+
+
+void luaZ_init (ZIO *z, lua_Chunkreader reader, void *data, const char *name) {
+ z->reader = reader;
+ z->data = data;
+ z->name = name;
+ z->n = 0;
+ z->p = NULL;
+}
+
+
+/* --------------------------------------------------------------- read --- */
+size_t luaZ_read (ZIO *z, void *b, size_t n) {
+ while (n) {
+ size_t m;
+ if (z->n == 0) {
+ if (luaZ_fill(z) == EOZ)
+ return n; /* return number of missing bytes */
+ else {
+ ++z->n; /* filbuf removed first byte; put back it */
+ --z->p;
+ }
+ }
+ m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
+ memcpy(b, z->p, m);
+ z->n -= m;
+ z->p += m;
+ b = (char *)b + m;
+ n -= m;
+ }
+ return 0;
+}
+
+/* ------------------------------------------------------------------------ */
+char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) {
+ if (n > buff->buffsize) {
+ if (n < LUA_MINBUFFER) n = LUA_MINBUFFER;
+ luaM_reallocvector(L, buff->buffer, buff->buffsize, n, char);
+ buff->buffsize = n;
+ }
+ return buff->buffer;
+}
+
+
diff --git a/plugins/SmartAutoReplier/lualib/lzio.h b/plugins/SmartAutoReplier/lualib/lzio.h
new file mode 100644
index 0000000000..5e73615cc0
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/lzio.h
@@ -0,0 +1,64 @@
+/*
+** $Id: lzio.h,v 1.15 2003/03/20 16:00:56 roberto Exp $
+** Buffered streams
+** See Copyright Notice in lua.h
+*/
+
+
+#ifndef lzio_h
+#define lzio_h
+
+#include "lua.h"
+
+
+#define EOZ (-1) /* end of stream */
+
+typedef struct Zio ZIO;
+
+
+#define char2int(c) cast(int, cast(unsigned char, (c)))
+
+#define zgetc(z) (((z)->n--)>0 ? char2int(*(z)->p++) : luaZ_fill(z))
+
+#define zname(z) ((z)->name)
+
+void luaZ_init (ZIO *z, lua_Chunkreader reader, void *data, const char *name);
+size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */
+int luaZ_lookahead (ZIO *z);
+
+
+
+typedef struct Mbuffer {
+ char *buffer;
+ size_t buffsize;
+} Mbuffer;
+
+
+char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);
+
+#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->buffsize = 0)
+
+#define luaZ_sizebuffer(buff) ((buff)->buffsize)
+#define luaZ_buffer(buff) ((buff)->buffer)
+
+#define luaZ_resizebuffer(L, buff, size) \
+ (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \
+ (buff)->buffsize = size)
+
+#define luaZ_freebuffer(L, buff) luaZ_resizebuffer(L, buff, 0)
+
+
+/* --------- Private Part ------------------ */
+
+struct Zio {
+ size_t n; /* bytes still unread */
+ const char *p; /* current position in buffer */
+ lua_Chunkreader reader;
+ void* data; /* additional data */
+ const char *name;
+};
+
+
+int luaZ_fill (ZIO *z);
+
+#endif
diff --git a/plugins/SmartAutoReplier/lualib/targetver.h b/plugins/SmartAutoReplier/lualib/targetver.h
new file mode 100644
index 0000000000..90e767bfce
--- /dev/null
+++ b/plugins/SmartAutoReplier/lualib/targetver.h
@@ -0,0 +1,8 @@
+#pragma once
+
+// Including SDKDDKVer.h defines the highest available Windows platform.
+
+// If you wish to build your application for a previous Windows platform, include WinSDKVer.h and
+// set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h.
+
+#include <SDKDDKVer.h>
diff --git a/plugins/SmartAutoReplier/resource.h b/plugins/SmartAutoReplier/resource.h
new file mode 100644
index 0000000000..38765d95fc
--- /dev/null
+++ b/plugins/SmartAutoReplier/resource.h
@@ -0,0 +1,52 @@
+//{{NO_DEPENDENCIES}}
+// Microsoft Visual C++ generated include file.
+// Used by SAR.rc
+//
+#define IDD_OPTIONS 101
+#define IDD_ADDRULE_DLG 102
+#define IDI_SAR_ICON 103
+#define IDD_SET_AURMESSAGEDLG 104
+#define IDD_SEL_USER 110
+#define IDD_HISTORYLOGS 111
+#define IDD_SDLGHOLDER 113
+#define IDC_STATIC_HEADER_TEXT 1001
+#define IDC_EDIT_HEADER 1002
+#define IDC_STATIC_MESSAGE_TEXT 1003
+#define IDC_EDIT_MESSAGE 1004
+#define IDC_EDIT_REPLAYDELAY 1006
+#define IDC_LIST_RULES 1007
+#define IDC_BTN_ADDRULE 1008
+#define IDC_BTN_DELRULE 1009
+#define IDC_ED_RULENAME 1009
+#define IDC_BTN_EDITRULE 1010
+#define IDC_ED_RULECNAME 1010
+#define IDC_ED_RULEREPLY 1011
+#define IDC_ED_RULEACTION 1012
+#define IDC_BUTTON1 1013
+#define IDC_BTN_SELUSER 1013
+#define IDC_CHECK_DISABLEWMON 1014
+#define IDC_CHECK1 1017
+#define IDC_CH_SHOW_AURDLG_WHMC 1017
+#define IDC_CH_DISWHSB 1017
+#define IDC_ED_TEXT 1019
+#define IDC_CB_DWSB 1020
+#define IDC_LIST_USERS 1021
+#define IDC_TABS 1022
+#define IDC_TABSHOLDER 1022
+#define IDC_STATUSMSG 1023
+#define IDC_CH_ENABLE_WSCH 1115
+#define IDC_CB_ENWSC 1116
+#define IDC_CH_SHOWCG 1117
+#define IDC_CH_SHOWCG2 1118
+#define IDC_CH_SAVE_AURS 1118
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NEXT_RESOURCE_VALUE 113
+#define _APS_NEXT_COMMAND_VALUE 40002
+#define _APS_NEXT_CONTROL_VALUE 1024
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/plugins/SmartAutoReplier/sar.ico b/plugins/SmartAutoReplier/sar.ico
new file mode 100644
index 0000000000..27a5d17bbb
--- /dev/null
+++ b/plugins/SmartAutoReplier/sar.ico
Binary files differ
diff --git a/plugins/SmartAutoReplier/stdafx.cpp b/plugins/SmartAutoReplier/stdafx.cpp
new file mode 100644
index 0000000000..39aa93ac1d
--- /dev/null
+++ b/plugins/SmartAutoReplier/stdafx.cpp
@@ -0,0 +1,27 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "stdafx.h"
+
+void OnRefreshSettings(void)
+{
+ SendMessage(HWND_BROADCAST, REFRESH_OPTS_MSG, 0, 0);
+} \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/stdafx.h b/plugins/SmartAutoReplier/stdafx.h
new file mode 100644
index 0000000000..76f6c5128c
--- /dev/null
+++ b/plugins/SmartAutoReplier/stdafx.h
@@ -0,0 +1,74 @@
+/*
+ * Smart Auto Replier (SAR) - auto replier plugin for Miranda IM
+ *
+ * Copyright (C) 2004 - 2012 by Volodymyr M. Shcherbyna <volodymyr@shcherbyna.com>
+ *
+ * This file is part of SAR.
+ *
+ * SAR 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * SAR 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.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with SAR. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#pragma once
+
+#include "AggressiveOptimize.h"
+
+#undef _WIN32_WINNT
+#define _WIN32_WINNT 0x0500
+
+#define WIN32_LEAN_AND_MEAN
+#define _MERGE_RDATA_
+
+/// windows and crt headers (win32 api)
+#include <windows.h>
+#include <string>
+#include <prsht.h>
+#include <crtdbg.h>
+#include "resource.h"
+#include <tchar.h>
+#include <windowsx.h>
+
+#include <commctrl.h>
+
+/// shell's headers... (windows shell)
+#include <shlwapi.h>
+#include <shellapi.h>
+
+#pragma comment(lib, "shlwapi.lib")
+#pragma comment(lib, "shell32.lib")
+
+#pragma warning(disable:4312)
+#pragma warning(disable:4267)
+#pragma warning(disable:4356)
+
+/// miranda's headers...
+#include "../miranda32/newpluginapi.h"
+#include "../miranda32/m_system.h"
+#include "../miranda32/m_protomod.h"
+#include "../miranda32/m_protosvc.h"
+#include "../miranda32/m_clist.h"
+#include "../miranda32/m_skin.h"
+#include "../miranda32/m_database.h"
+#include "../miranda32/m_options.h"
+#include "../miranda32/m_langpack.h"
+
+/// plugin's specific headers...
+#include "messageshandler.h" /// messages handler
+#include "settingshandler.h" /// settings handler
+#include "GUI/optionsDlg.h" /// options handler
+#include "comlogging.h" /// common loggin helper macroses
+#include "crushlog.h" /// crush log handler
+
+#define REFRESH_OPTS_MSG WM_USER + 666
+
+void OnRefreshSettings(void); \ No newline at end of file
diff --git a/plugins/SmartAutoReplier/wtl/atlapp.h b/plugins/SmartAutoReplier/wtl/atlapp.h
new file mode 100644
index 0000000000..e47bcd633b
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlapp.h
@@ -0,0 +1,2035 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLAPP_H__
+#define __ATLAPP_H__
+
+#pragma once
+
+#ifndef __cplusplus
+ #error WTL requires C++ compilation (use a .cpp suffix)
+#endif
+
+#ifndef __ATLBASE_H__
+ #error atlapp.h requires atlbase.h to be included first
+#endif
+
+#ifndef _WIN32_WCE
+ #if (WINVER < 0x0400)
+ #error WTL requires Windows version 4.0 or higher
+ #endif
+
+ #if (_WIN32_IE < 0x0300)
+ #error WTL requires IE version 3.0 or higher
+ #endif
+#endif
+
+#ifdef _ATL_NO_COMMODULE
+ #error WTL requires that _ATL_NO_COMMODULE is not defined
+#endif
+
+#if (_ATL_VER >= 0x0900) && defined(_ATL_MIN_CRT)
+ #error _ATL_MIN_CRT is not supported with ATL 9.0 and higher
+#endif
+
+#if defined(_WIN32_WCE) && defined(_ATL_MIN_CRT)
+ #pragma message("Warning: WTL for Windows CE doesn't use _ATL_MIN_CRT")
+#endif
+
+#include <limits.h>
+#if !defined(_ATL_MIN_CRT) && defined(_MT) && !defined(_WIN32_WCE)
+ #include <process.h> // for _beginthreadex
+#endif
+
+#if (_ATL_VER < 0x0800) && !defined(_DEBUG)
+ #include <stdio.h>
+#endif
+
+#include <commctrl.h>
+#ifndef _WIN32_WCE
+ #pragma comment(lib, "comctl32.lib")
+#endif
+
+#ifndef _WIN32_WCE
+ #include "atlres.h"
+#else // CE specific
+ #include "atlresce.h"
+#endif // _WIN32_WCE
+
+// We need to disable this warning because of template class arguments
+#pragma warning(disable: 4127)
+
+#if (_ATL_VER >= 0x0900) && !defined(_SECURE_ATL)
+ #define _SECURE_ATL 1
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// WTL version number
+
+#define _WTL_VER 0x0810
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CMessageFilter
+// CIdleHandler
+// CMessageLoop
+//
+// CAppModule
+// CServerAppModule
+//
+// CRegKeyEx
+//
+// Global functions:
+// AtlGetDefaultGuiFont()
+// AtlCreateControlFont()
+// AtlCreateBoldFont()
+// AtlInitCommonControls()
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Global support for Windows CE
+
+#ifdef _WIN32_WCE
+
+#ifndef SW_SHOWDEFAULT
+ #define SW_SHOWDEFAULT SW_SHOWNORMAL
+#endif // !SW_SHOWDEFAULT
+
+// These get's OR-ed in a constant and will have no effect.
+// Defining them reduces the number of #ifdefs required for CE.
+#define LR_DEFAULTSIZE 0
+#define LR_LOADFROMFILE 0
+
+#ifndef SM_CXCURSOR
+ #define SM_CXCURSOR 13
+#endif
+#ifndef SM_CYCURSOR
+ #define SM_CYCURSOR 14
+#endif
+
+inline BOOL IsMenu(HMENU hMenu)
+{
+ MENUITEMINFO mii = { sizeof(MENUITEMINFO) };
+ ::SetLastError(0);
+ BOOL bRet = ::GetMenuItemInfo(hMenu, 0, TRUE, &mii);
+ if(!bRet)
+ bRet = (::GetLastError() != ERROR_INVALID_MENU_HANDLE) ? TRUE : FALSE;
+ return bRet;
+}
+
+#if (_WIN32_WCE >= 410)
+extern "C" void WINAPI ListView_SetItemSpacing(HWND hwndLV, int iHeight);
+#endif // (_WIN32_WCE >= 410)
+
+inline int MulDiv(IN int nNumber, IN int nNumerator, IN int nDenominator)
+{
+ __int64 multiple = nNumber * nNumerator;
+ return static_cast<int>(multiple / nDenominator);
+}
+
+#if (_ATL_VER >= 0x0800)
+
+#ifndef _WTL_KEEP_WS_OVERLAPPEDWINDOW
+ #ifdef WS_OVERLAPPEDWINDOW
+ #undef WS_OVERLAPPEDWINDOW
+ #define WS_OVERLAPPEDWINDOW 0
+ #endif // WS_OVERLAPPEDWINDOW
+#endif // !_WTL_KEEP_WS_OVERLAPPEDWINDOW
+
+#ifndef RDW_FRAME
+ #define RDW_FRAME 0
+#endif // !RDW_FRAME
+
+#ifndef WM_WINDOWPOSCHANGING
+ #define WM_WINDOWPOSCHANGING 0
+#endif // !WM_WINDOWPOSCHANGING
+
+#define FreeResource(x)
+#define UnlockResource(x)
+
+namespace ATL
+{
+ inline HRESULT CComModule::RegisterClassObjects(DWORD /*dwClsContext*/, DWORD /*dwFlags*/) throw()
+ { return E_NOTIMPL; }
+ inline HRESULT CComModule::RevokeClassObjects() throw()
+ { return E_NOTIMPL; }
+}; // namespace ATL
+
+#ifndef lstrlenW
+ #define lstrlenW (int)ATL::lstrlenW
+#endif // lstrlenW
+
+inline int WINAPI lstrlenA(LPCSTR lpszString)
+{ return ATL::lstrlenA(lpszString); }
+
+#ifdef lstrcpyn
+ #undef lstrcpyn
+ #define lstrcpyn ATL::lstrcpynW
+#endif // lstrcpyn
+
+#ifndef SetWindowLongPtrW
+ inline LONG_PTR tmp_SetWindowLongPtrW( HWND hWnd, int nIndex, LONG_PTR dwNewLong )
+ {
+ return( ::SetWindowLongW( hWnd, nIndex, LONG( dwNewLong ) ) );
+ }
+ #define SetWindowLongPtrW tmp_SetWindowLongPtrW
+#endif
+
+#ifndef GetWindowLongPtrW
+ inline LONG_PTR tmp_GetWindowLongPtrW( HWND hWnd, int nIndex )
+ {
+ return( ::GetWindowLongW( hWnd, nIndex ) );
+ }
+ #define GetWindowLongPtrW tmp_GetWindowLongPtrW
+#endif
+
+#ifndef LongToPtr
+ #define LongToPtr(x) ((void*)x)
+#endif
+
+#ifndef PtrToInt
+ #define PtrToInt( p ) ((INT)(INT_PTR) (p) )
+#endif
+
+#else // !(_ATL_VER >= 0x0800)
+
+#ifdef lstrlenW
+ #undef lstrlenW
+ #define lstrlenW (int)::wcslen
+#endif // lstrlenW
+
+#define lstrlenA (int)strlen
+
+#ifndef lstrcpyn
+ inline LPTSTR lstrcpyn(LPTSTR lpstrDest, LPCTSTR lpstrSrc, int nLength)
+ {
+ if(lpstrDest == NULL || lpstrSrc == NULL || nLength <= 0)
+ return NULL;
+ int nLen = min(lstrlen(lpstrSrc), nLength - 1);
+ LPTSTR lpstrRet = (LPTSTR)memcpy(lpstrDest, lpstrSrc, nLen * sizeof(TCHAR));
+ lpstrDest[nLen] = 0;
+ return lpstrRet;
+ }
+#endif // !lstrcpyn
+
+#ifndef lstrcpynW
+ inline LPWSTR lstrcpynW(LPWSTR lpstrDest, LPCWSTR lpstrSrc, int nLength)
+ {
+ return lstrcpyn(lpstrDest, lpstrSrc, nLength); // WinCE is Unicode only
+ }
+#endif // !lstrcpynW
+
+#ifndef lstrcpynA
+ inline LPSTR lstrcpynA(LPSTR lpstrDest, LPCSTR lpstrSrc, int nLength)
+ {
+ if(lpstrDest == NULL || lpstrSrc == NULL || nLength <= 0)
+ return NULL;
+ int nLen = min(lstrlenA(lpstrSrc), nLength - 1);
+ LPSTR lpstrRet = (LPSTR)memcpy(lpstrDest, lpstrSrc, nLen * sizeof(char));
+ lpstrDest[nLen] = 0;
+ return lpstrRet;
+ }
+#endif // !lstrcpyn
+
+#ifdef TrackPopupMenu
+ #undef TrackPopupMenu
+#endif // TrackPopupMenu
+
+#define DECLARE_WND_CLASS_EX(WndClassName, style, bkgnd) \
+static CWndClassInfo& GetWndClassInfo() \
+{ \
+ static CWndClassInfo wc = \
+ { \
+ { style, StartWindowProc, \
+ 0, 0, NULL, NULL, NULL, (HBRUSH)(bkgnd + 1), NULL, WndClassName }, \
+ NULL, NULL, IDC_ARROW, TRUE, 0, _T("") \
+ }; \
+ return wc; \
+}
+
+#ifndef _MAX_FNAME
+ #define _MAX_FNAME _MAX_PATH
+#endif // _MAX_FNAME
+
+#if (_WIN32_WCE < 400)
+ #define MAKEINTATOM(i) (LPTSTR)((ULONG_PTR)((WORD)(i)))
+#endif // (_WIN32_WCE < 400)
+
+#if (_WIN32_WCE < 410)
+ #define WHEEL_PAGESCROLL (UINT_MAX)
+ #define WHEEL_DELTA 120
+#endif // (_WIN32_WCE < 410)
+
+#ifdef DrawIcon
+ #undef DrawIcon
+#endif
+
+#ifndef VARCMP_LT
+ #define VARCMP_LT 0
+#endif
+#ifndef VARCMP_EQ
+ #define VARCMP_EQ 1
+#endif
+#ifndef VARCMP_GT
+ #define VARCMP_GT 2
+#endif
+#ifndef VARCMP_NULL
+ #define VARCMP_NULL 3
+#endif
+
+#ifndef RDW_ALLCHILDREN
+ #define RDW_ALLCHILDREN 0
+#endif
+
+#endif // !(_ATL_VER >= 0x0800)
+
+#endif // _WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Global support for using original VC++ 6.0 headers with WTL
+
+#ifndef _ATL_NO_OLD_HEADERS_WIN64
+#if !defined(_WIN64) && (_ATL_VER < 0x0700)
+
+ #ifndef PSM_INSERTPAGE
+ #define PSM_INSERTPAGE (WM_USER + 119)
+ #endif // !PSM_INSERTPAGE
+
+ #ifndef GetClassLongPtr
+ #define GetClassLongPtrA GetClassLongA
+ #define GetClassLongPtrW GetClassLongW
+ #ifdef UNICODE
+ #define GetClassLongPtr GetClassLongPtrW
+ #else
+ #define GetClassLongPtr GetClassLongPtrA
+ #endif // !UNICODE
+ #endif // !GetClassLongPtr
+
+ #ifndef GCLP_HICONSM
+ #define GCLP_HICONSM (-34)
+ #endif // !GCLP_HICONSM
+
+ #ifndef GetWindowLongPtr
+ #define GetWindowLongPtrA GetWindowLongA
+ #define GetWindowLongPtrW GetWindowLongW
+ #ifdef UNICODE
+ #define GetWindowLongPtr GetWindowLongPtrW
+ #else
+ #define GetWindowLongPtr GetWindowLongPtrA
+ #endif // !UNICODE
+ #endif // !GetWindowLongPtr
+
+ #ifndef SetWindowLongPtr
+ #define SetWindowLongPtrA SetWindowLongA
+ #define SetWindowLongPtrW SetWindowLongW
+ #ifdef UNICODE
+ #define SetWindowLongPtr SetWindowLongPtrW
+ #else
+ #define SetWindowLongPtr SetWindowLongPtrA
+ #endif // !UNICODE
+ #endif // !SetWindowLongPtr
+
+ #ifndef GWLP_WNDPROC
+ #define GWLP_WNDPROC (-4)
+ #endif
+ #ifndef GWLP_HINSTANCE
+ #define GWLP_HINSTANCE (-6)
+ #endif
+ #ifndef GWLP_HWNDPARENT
+ #define GWLP_HWNDPARENT (-8)
+ #endif
+ #ifndef GWLP_USERDATA
+ #define GWLP_USERDATA (-21)
+ #endif
+ #ifndef GWLP_ID
+ #define GWLP_ID (-12)
+ #endif
+
+ #ifndef DWLP_MSGRESULT
+ #define DWLP_MSGRESULT 0
+ #endif
+
+ typedef long LONG_PTR;
+ typedef unsigned long ULONG_PTR;
+ typedef ULONG_PTR DWORD_PTR;
+
+ #ifndef HandleToUlong
+ #define HandleToUlong( h ) ((ULONG)(ULONG_PTR)(h) )
+ #endif
+ #ifndef HandleToLong
+ #define HandleToLong( h ) ((LONG)(LONG_PTR) (h) )
+ #endif
+ #ifndef LongToHandle
+ #define LongToHandle( h) ((HANDLE)(LONG_PTR) (h))
+ #endif
+ #ifndef PtrToUlong
+ #define PtrToUlong( p ) ((ULONG)(ULONG_PTR) (p) )
+ #endif
+ #ifndef PtrToLong
+ #define PtrToLong( p ) ((LONG)(LONG_PTR) (p) )
+ #endif
+ #ifndef PtrToUint
+ #define PtrToUint( p ) ((UINT)(UINT_PTR) (p) )
+ #endif
+ #ifndef PtrToInt
+ #define PtrToInt( p ) ((INT)(INT_PTR) (p) )
+ #endif
+ #ifndef PtrToUshort
+ #define PtrToUshort( p ) ((unsigned short)(ULONG_PTR)(p) )
+ #endif
+ #ifndef PtrToShort
+ #define PtrToShort( p ) ((short)(LONG_PTR)(p) )
+ #endif
+ #ifndef IntToPtr
+ #define IntToPtr( i ) ((VOID *)(INT_PTR)((int)i))
+ #endif
+ #ifndef UIntToPtr
+ #define UIntToPtr( ui ) ((VOID *)(UINT_PTR)((unsigned int)ui))
+ #endif
+ #ifndef LongToPtr
+ #define LongToPtr( l ) ((VOID *)(LONG_PTR)((long)l))
+ #endif
+ #ifndef ULongToPtr
+ #define ULongToPtr( ul ) ((VOID *)(ULONG_PTR)((unsigned long)ul))
+ #endif
+
+#endif // !defined(_WIN64) && (_ATL_VER < 0x0700)
+#endif // !_ATL_NO_OLD_HEADERS_WIN64
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Global support for SecureHelper functions
+
+#ifndef _TRUNCATE
+ #define _TRUNCATE ((size_t)-1)
+#endif
+
+#ifndef _ERRCODE_DEFINED
+ #define _ERRCODE_DEFINED
+ typedef int errno_t;
+#endif
+
+#ifndef _SECURECRT_ERRCODE_VALUES_DEFINED
+ #define _SECURECRT_ERRCODE_VALUES_DEFINED
+ #define EINVAL 22
+ #define STRUNCATE 80
+#endif
+
+#ifndef _countof
+ #define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0]))
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Miscellaneous global support
+
+// define useful macros from winuser.h
+#ifndef IS_INTRESOURCE
+ #define IS_INTRESOURCE(_r) (((ULONG_PTR)(_r) >> 16) == 0)
+#endif // IS_INTRESOURCE
+
+// protect template members from windowsx.h macros
+#ifdef _INC_WINDOWSX
+ #undef SubclassWindow
+#endif // _INC_WINDOWSX
+
+// define useful macros from windowsx.h
+#ifndef GET_X_LPARAM
+ #define GET_X_LPARAM(lParam) ((int)(short)LOWORD(lParam))
+#endif
+#ifndef GET_Y_LPARAM
+ #define GET_Y_LPARAM(lParam) ((int)(short)HIWORD(lParam))
+#endif
+
+// Dummy structs for compiling with /CLR
+#if (_MSC_VER >= 1300) && defined(_MANAGED)
+ __if_not_exists(_IMAGELIST::_IMAGELIST) { struct _IMAGELIST { }; }
+ __if_not_exists(_TREEITEM::_TREEITEM) { struct _TREEITEM { }; }
+ __if_not_exists(_PSP::_PSP) { struct _PSP { }; }
+#endif
+
+// Define ATLVERIFY macro for ATL3
+#if (_ATL_VER < 0x0700)
+ #ifndef ATLVERIFY
+ #ifdef _DEBUG
+ #define ATLVERIFY(expr) ATLASSERT(expr)
+ #else
+ #define ATLVERIFY(expr) (expr)
+ #endif // DEBUG
+ #endif // ATLVERIFY
+#endif // (_ATL_VER < 0x0700)
+
+// Forward declaration for ATL3 fix
+#if (_ATL_VER < 0x0700) && defined(_ATL_DLL) && !defined(_WIN32_WCE)
+ namespace ATL { HRESULT AtlGetCommCtrlVersion(LPDWORD pdwMajor, LPDWORD pdwMinor); };
+#endif
+
+
+namespace WTL
+{
+
+#if (_ATL_VER >= 0x0700)
+ DECLARE_TRACE_CATEGORY(atlTraceUI);
+ #ifdef _DEBUG
+ __declspec(selectany) ATL::CTraceCategory atlTraceUI(_T("atlTraceUI"));
+ #endif // _DEBUG
+#else // !(_ATL_VER >= 0x0700)
+ enum wtlTraceFlags
+ {
+ atlTraceUI = 0x10000000
+ };
+#endif // !(_ATL_VER >= 0x0700)
+
+// Windows version helper
+inline bool AtlIsOldWindows()
+{
+ OSVERSIONINFO ovi = { 0 };
+ ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ BOOL bRet = ::GetVersionEx(&ovi);
+ return (!bRet || !((ovi.dwMajorVersion >= 5) || (ovi.dwMajorVersion == 4 && ovi.dwMinorVersion >= 90)));
+}
+
+// Default GUI font helper - "MS Shell Dlg" stock font
+inline HFONT AtlGetDefaultGuiFont()
+{
+#ifndef _WIN32_WCE
+ return (HFONT)::GetStockObject(DEFAULT_GUI_FONT);
+#else // CE specific
+ return (HFONT)::GetStockObject(SYSTEM_FONT);
+#endif // _WIN32_WCE
+}
+
+// Control font helper - default font for controls not in a dialog
+// (NOTE: Caller owns the font, and should destroy it when it's no longer needed)
+inline HFONT AtlCreateControlFont()
+{
+#ifndef _WIN32_WCE
+ LOGFONT lf = { 0 };
+ ATLVERIFY(::SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(LOGFONT), &lf, 0) != FALSE);
+ HFONT hFont = ::CreateFontIndirect(&lf);
+ ATLASSERT(hFont != NULL);
+ return hFont;
+#else // CE specific
+ return (HFONT)::GetStockObject(SYSTEM_FONT);
+#endif // _WIN32_WCE
+}
+
+// Bold font helper
+// (NOTE: Caller owns the font, and should destroy it when it's no longer needed)
+inline HFONT AtlCreateBoldFont(HFONT hFont = NULL)
+{
+ LOGFONT lf = { 0 };
+#ifndef _WIN32_WCE
+ if(hFont == NULL)
+ ATLVERIFY(::SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(LOGFONT), &lf, 0) != FALSE);
+ else
+ ATLVERIFY(::GetObject(hFont, sizeof(LOGFONT), &lf) == sizeof(LOGFONT));
+#else // CE specific
+ if(hFont == NULL)
+ hFont = (HFONT)::GetStockObject(SYSTEM_FONT);
+ ATLVERIFY(::GetObject(hFont, sizeof(LOGFONT), &lf) == sizeof(LOGFONT));
+#endif // _WIN32_WCE
+ lf.lfWeight = FW_BOLD;
+ HFONT hFontBold = ::CreateFontIndirect(&lf);
+ ATLASSERT(hFontBold != NULL);
+ return hFontBold;
+}
+
+// Common Controls initialization helper
+inline BOOL AtlInitCommonControls(DWORD dwFlags)
+{
+ INITCOMMONCONTROLSEX iccx = { sizeof(INITCOMMONCONTROLSEX), dwFlags };
+ BOOL bRet = ::InitCommonControlsEx(&iccx);
+ ATLASSERT(bRet);
+ return bRet;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// RunTimeHelper - helper functions for Windows version and structure sizes
+
+// Not for Windows CE
+#if defined(_WIN32_WCE) && !defined(_WTL_NO_RUNTIME_STRUCT_SIZE)
+ #define _WTL_NO_RUNTIME_STRUCT_SIZE
+#endif
+
+#ifndef _WTL_NO_RUNTIME_STRUCT_SIZE
+
+#ifndef _SIZEOF_STRUCT
+ #define _SIZEOF_STRUCT(structname, member) (((int)((LPBYTE)(&((structname*)0)->member) - ((LPBYTE)((structname*)0)))) + sizeof(((structname*)0)->member))
+#endif
+
+#if (_WIN32_WINNT >= 0x0600) && !defined(REBARBANDINFO_V6_SIZE)
+ #define REBARBANDINFO_V6_SIZE _SIZEOF_STRUCT(REBARBANDINFO, cxHeader)
+#endif // (_WIN32_WINNT >= 0x0600) && !defined(REBARBANDINFO_V6_SIZE)
+
+#if (_WIN32_WINNT >= 0x0600) && !defined(LVGROUP_V5_SIZE)
+ #define LVGROUP_V5_SIZE _SIZEOF_STRUCT(LVGROUP, uAlign)
+#endif // (_WIN32_WINNT >= 0x0600) && !defined(LVGROUP_V5_SIZE)
+
+#if (_WIN32_WINNT >= 0x0600) && !defined(LVTILEINFO_V5_SIZE)
+ #define LVTILEINFO_V5_SIZE _SIZEOF_STRUCT(LVTILEINFO, puColumns)
+#endif // (_WIN32_WINNT >= 0x0600) && !defined(LVTILEINFO_V5_SIZE)
+
+#if defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN) && !defined(MCHITTESTINFO_V1_SIZE)
+ #define MCHITTESTINFO_V1_SIZE _SIZEOF_STRUCT(MCHITTESTINFO, st)
+#endif // defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN) && !defined(MCHITTESTINFO_V1_SIZE)
+
+#if !defined(_WIN32_WCE) && (WINVER >= 0x0600) && !defined(NONCLIENTMETRICS_V1_SIZE)
+ #define NONCLIENTMETRICS_V1_SIZE _SIZEOF_STRUCT(NONCLIENTMETRICS, lfMessageFont)
+#endif // !defined(_WIN32_WCE) && (WINVER >= 0x0600) && !defined(NONCLIENTMETRICS_V1_SIZE)
+
+#endif // !_WTL_NO_RUNTIME_STRUCT_SIZE
+
+namespace RunTimeHelper
+{
+#ifndef _WIN32_WCE
+ inline bool IsCommCtrl6()
+ {
+ DWORD dwMajor = 0, dwMinor = 0;
+ HRESULT hRet = ATL::AtlGetCommCtrlVersion(&dwMajor, &dwMinor);
+ return (SUCCEEDED(hRet) && (dwMajor >= 6));
+ }
+
+ inline bool IsVista()
+ {
+ OSVERSIONINFO ovi = { sizeof(OSVERSIONINFO) };
+ BOOL bRet = ::GetVersionEx(&ovi);
+ return ((bRet != FALSE) && (ovi.dwMajorVersion >= 6));
+ }
+
+ inline bool IsThemeAvailable()
+ {
+ bool bRet = false;
+
+ if(IsCommCtrl6())
+ {
+ HMODULE hThemeDLL = ::LoadLibrary(_T("uxtheme.dll"));
+ if(hThemeDLL != NULL)
+ {
+ typedef BOOL (STDAPICALLTYPE *PFN_IsThemeActive)();
+ PFN_IsThemeActive pfnIsThemeActive = (PFN_IsThemeActive)::GetProcAddress(hThemeDLL, "IsThemeActive");
+ ATLASSERT(pfnIsThemeActive != NULL);
+ bRet = (pfnIsThemeActive != NULL) && (pfnIsThemeActive() != FALSE);
+ if(bRet)
+ {
+ typedef BOOL (STDAPICALLTYPE *PFN_IsAppThemed)();
+ PFN_IsAppThemed pfnIsAppThemed = (PFN_IsAppThemed)::GetProcAddress(hThemeDLL, "IsAppThemed");
+ ATLASSERT(pfnIsAppThemed != NULL);
+ bRet = (pfnIsAppThemed != NULL) && (pfnIsAppThemed() != FALSE);
+ }
+
+ ::FreeLibrary(hThemeDLL);
+ }
+ }
+
+ return bRet;
+ }
+
+ inline bool IsWin7()
+ {
+ OSVERSIONINFO ovi = { sizeof(OSVERSIONINFO) };
+ BOOL bRet = ::GetVersionEx(&ovi);
+ return ((bRet != FALSE) && (ovi.dwMajorVersion == 6) && (ovi.dwMinorVersion >= 1));
+ }
+
+ inline bool IsRibbonUIAvailable()
+ {
+ static INT iRibbonUI = -1;
+
+#if defined(NTDDI_WIN7) && (NTDDI_VERSION >= NTDDI_WIN7)
+ if (iRibbonUI == -1)
+ {
+ HMODULE hRibbonDLL = ::LoadLibrary(_T("propsys.dll"));
+ if (hRibbonDLL != NULL)
+ {
+ const GUID CLSID_UIRibbonFramework = { 0x926749fa, 0x2615, 0x4987, { 0x88, 0x45, 0xc3, 0x3e, 0x65, 0xf2, 0xb9, 0x57 } };
+ // block - create instance
+ {
+ ATL::CComPtr<IUnknown> pIUIFramework;
+ iRibbonUI = SUCCEEDED(pIUIFramework.CoCreateInstance(CLSID_UIRibbonFramework)) ? 1 : 0;
+ }
+ ::FreeLibrary(hRibbonDLL);
+ }
+ else
+ {
+ iRibbonUI = 0;
+ }
+ }
+#endif // defined(NTDDI_WIN7) && (NTDDI_VERSION >= NTDDI_WIN7)
+
+ return (iRibbonUI == 1);
+ }
+
+#endif // !_WIN32_WCE
+
+ inline int SizeOf_REBARBANDINFO()
+ {
+ int nSize = sizeof(REBARBANDINFO);
+#if !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && (_WIN32_WINNT >= 0x0600)
+ if(!(IsVista() && IsCommCtrl6()))
+ nSize = REBARBANDINFO_V6_SIZE;
+#endif // !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && (_WIN32_WINNT >= 0x0600)
+ return nSize;
+ }
+
+#if (_WIN32_WINNT >= 0x501)
+ inline int SizeOf_LVGROUP()
+ {
+ int nSize = sizeof(LVGROUP);
+#if !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && (_WIN32_WINNT >= 0x0600)
+ if(!IsVista())
+ nSize = LVGROUP_V5_SIZE;
+#endif // !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && (_WIN32_WINNT >= 0x0600)
+ return nSize;
+ }
+
+ inline int SizeOf_LVTILEINFO()
+ {
+ int nSize = sizeof(LVTILEINFO);
+#if !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && (_WIN32_WINNT >= 0x0600)
+ if(!IsVista())
+ nSize = LVTILEINFO_V5_SIZE;
+#endif // !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && (_WIN32_WINNT >= 0x0600)
+ return nSize;
+ }
+#endif // (_WIN32_WINNT >= 0x501)
+
+ inline int SizeOf_MCHITTESTINFO()
+ {
+ int nSize = sizeof(MCHITTESTINFO);
+#if !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+ if(!(IsVista() && IsCommCtrl6()))
+ nSize = MCHITTESTINFO_V1_SIZE;
+#endif // !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+ return nSize;
+ }
+
+#ifndef _WIN32_WCE
+ inline int SizeOf_NONCLIENTMETRICS()
+ {
+ int nSize = sizeof(NONCLIENTMETRICS);
+#if !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && (WINVER >= 0x0600)
+ if(!IsVista())
+ nSize = NONCLIENTMETRICS_V1_SIZE;
+#endif // !defined(_WTL_NO_RUNTIME_STRUCT_SIZE) && (WINVER >= 0x0600)
+ return nSize;
+ }
+#endif // !_WIN32_WCE
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// ModuleHelper - helper functions for ATL3 and ATL7 module classes
+
+namespace ModuleHelper
+{
+ inline HINSTANCE GetModuleInstance()
+ {
+#if (_ATL_VER >= 0x0700)
+ return ATL::_AtlBaseModule.GetModuleInstance();
+#else // !(_ATL_VER >= 0x0700)
+ return ATL::_pModule->GetModuleInstance();
+#endif // !(_ATL_VER >= 0x0700)
+ }
+
+ inline HINSTANCE GetResourceInstance()
+ {
+#if (_ATL_VER >= 0x0700)
+ return ATL::_AtlBaseModule.GetResourceInstance();
+#else // !(_ATL_VER >= 0x0700)
+ return ATL::_pModule->GetResourceInstance();
+#endif // !(_ATL_VER >= 0x0700)
+ }
+
+ inline void AddCreateWndData(ATL::_AtlCreateWndData* pData, void* pObject)
+ {
+#if (_ATL_VER >= 0x0700)
+ ATL::_AtlWinModule.AddCreateWndData(pData, pObject);
+#else // !(_ATL_VER >= 0x0700)
+ ATL::_pModule->AddCreateWndData(pData, pObject);
+#endif // !(_ATL_VER >= 0x0700)
+ }
+
+ inline void* ExtractCreateWndData()
+ {
+#if (_ATL_VER >= 0x0700)
+ return ATL::_AtlWinModule.ExtractCreateWndData();
+#else // !(_ATL_VER >= 0x0700)
+ return ATL::_pModule->ExtractCreateWndData();
+#endif // !(_ATL_VER >= 0x0700)
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// SecureHelper - helper functions for VS2005 secure CRT
+
+namespace SecureHelper
+{
+ inline void strcpyA_x(char* lpstrDest, size_t cchDest, const char* lpstrSrc)
+ {
+#if _SECURE_ATL
+ ATL::Checked::strcpy_s(lpstrDest, cchDest, lpstrSrc);
+#else
+ if(cchDest > (size_t)lstrlenA(lpstrSrc))
+ ATLVERIFY(lstrcpyA(lpstrDest, lpstrSrc) != NULL);
+ else
+ ATLASSERT(FALSE);
+#endif
+ }
+
+ inline void strcpyW_x(wchar_t* lpstrDest, size_t cchDest, const wchar_t* lpstrSrc)
+ {
+#if _SECURE_ATL
+ ATL::Checked::wcscpy_s(lpstrDest, cchDest, lpstrSrc);
+#else
+ if(cchDest > (size_t)lstrlenW(lpstrSrc))
+ ATLVERIFY(lstrcpyW(lpstrDest, lpstrSrc) != NULL);
+ else
+ ATLASSERT(FALSE);
+#endif
+ }
+
+ inline void strcpy_x(LPTSTR lpstrDest, size_t cchDest, LPCTSTR lpstrSrc)
+ {
+#ifdef _UNICODE
+ strcpyW_x(lpstrDest, cchDest, lpstrSrc);
+#else
+ strcpyA_x(lpstrDest, cchDest, lpstrSrc);
+#endif
+ }
+
+ inline errno_t strncpyA_x(char* lpstrDest, size_t cchDest, const char* lpstrSrc, size_t cchCount)
+ {
+#if _SECURE_ATL
+ return ATL::Checked::strncpy_s(lpstrDest, cchDest, lpstrSrc, cchCount);
+#else
+ errno_t nRet = 0;
+ if(lpstrDest == NULL || cchDest == 0 || lpstrSrc == NULL)
+ {
+ nRet = EINVAL;
+ }
+ else if(cchCount == _TRUNCATE)
+ {
+ cchCount = min(cchDest - 1, size_t(lstrlenA(lpstrSrc)));
+ nRet = STRUNCATE;
+ }
+ else if(cchDest <= cchCount)
+ {
+ lpstrDest[0] = 0;
+ nRet = EINVAL;
+ }
+ if(nRet == 0 || nRet == STRUNCATE)
+ nRet = (lstrcpynA(lpstrDest, lpstrSrc, (int)cchCount + 1) != NULL) ? nRet : EINVAL;
+ ATLASSERT(nRet == 0 || nRet == STRUNCATE);
+ return nRet;
+#endif
+ }
+
+ inline errno_t strncpyW_x(wchar_t* lpstrDest, size_t cchDest, const wchar_t* lpstrSrc, size_t cchCount)
+ {
+#if _SECURE_ATL
+ return ATL::Checked::wcsncpy_s(lpstrDest, cchDest, lpstrSrc, cchCount);
+#else
+ errno_t nRet = 0;
+ if(lpstrDest == NULL || cchDest == 0 || lpstrSrc == NULL)
+ {
+ nRet = EINVAL;
+ }
+ else if(cchCount == _TRUNCATE)
+ {
+ cchCount = min(cchDest - 1, size_t(lstrlenW(lpstrSrc)));
+ nRet = STRUNCATE;
+ }
+ else if(cchDest <= cchCount)
+ {
+ lpstrDest[0] = 0;
+ nRet = EINVAL;
+ }
+ if(nRet == 0 || nRet == STRUNCATE)
+ nRet = (lstrcpynW(lpstrDest, lpstrSrc, (int)cchCount + 1) != NULL) ? nRet : EINVAL;
+ ATLASSERT(nRet == 0 || nRet == STRUNCATE);
+ return nRet;
+#endif
+ }
+
+ inline errno_t strncpy_x(LPTSTR lpstrDest, size_t cchDest, LPCTSTR lpstrSrc, size_t cchCount)
+ {
+#ifdef _UNICODE
+ return strncpyW_x(lpstrDest, cchDest, lpstrSrc, cchCount);
+#else
+ return strncpyA_x(lpstrDest, cchDest, lpstrSrc, cchCount);
+#endif
+ }
+
+ inline void strcatA_x(char* lpstrDest, size_t cchDest, const char* lpstrSrc)
+ {
+#if _SECURE_ATL
+ ATL::Checked::strcat_s(lpstrDest, cchDest, lpstrSrc);
+#else
+ if(cchDest > (size_t)lstrlenA(lpstrSrc))
+ ATLVERIFY(lstrcatA(lpstrDest, lpstrSrc) != NULL);
+ else
+ ATLASSERT(FALSE);
+#endif
+ }
+
+ inline void strcatW_x(wchar_t* lpstrDest, size_t cchDest, const wchar_t* lpstrSrc)
+ {
+#if _SECURE_ATL
+ ATL::Checked::wcscat_s(lpstrDest, cchDest, lpstrSrc);
+#else
+ if(cchDest > (size_t)lstrlenW(lpstrSrc))
+ ATLVERIFY(lstrcatW(lpstrDest, lpstrSrc) != NULL);
+ else
+ ATLASSERT(FALSE);
+#endif
+ }
+
+ inline void strcat_x(LPTSTR lpstrDest, size_t cchDest, LPCTSTR lpstrSrc)
+ {
+#ifdef _UNICODE
+ strcatW_x(lpstrDest, cchDest, lpstrSrc);
+#else
+ strcatA_x(lpstrDest, cchDest, lpstrSrc);
+#endif
+ }
+
+ inline void memcpy_x(void* pDest, size_t cbDest, const void* pSrc, size_t cbSrc)
+ {
+#if _SECURE_ATL
+ ATL::Checked::memcpy_s(pDest, cbDest, pSrc, cbSrc);
+#else
+ if(cbDest >= cbSrc)
+ memcpy(pDest, pSrc, cbSrc);
+ else
+ ATLASSERT(FALSE);
+#endif
+ }
+
+ inline void memmove_x(void* pDest, size_t cbDest, const void* pSrc, size_t cbSrc)
+ {
+#if _SECURE_ATL
+ ATL::Checked::memmove_s(pDest, cbDest, pSrc, cbSrc);
+#else
+ if(cbDest >= cbSrc)
+ memmove(pDest, pSrc, cbSrc);
+ else
+ ATLASSERT(FALSE);
+#endif
+ }
+
+ inline int vsprintf_x(LPTSTR lpstrBuff, size_t cchBuff, LPCTSTR lpstrFormat, va_list args)
+ {
+#if _SECURE_ATL && !defined(_ATL_MIN_CRT) && !defined(_WIN32_WCE)
+ return _vstprintf_s(lpstrBuff, cchBuff, lpstrFormat, args);
+#else
+ cchBuff; // Avoid unused argument warning
+#pragma warning(disable: 4996)
+ return _vstprintf(lpstrBuff, lpstrFormat, args);
+#pragma warning(default: 4996)
+#endif
+ }
+
+ inline int wvsprintf_x(LPTSTR lpstrBuff, size_t cchBuff, LPCTSTR lpstrFormat, va_list args)
+ {
+#if _SECURE_ATL && !defined(_ATL_MIN_CRT) && !defined(_WIN32_WCE)
+ return _vstprintf_s(lpstrBuff, cchBuff, lpstrFormat, args);
+#else
+ cchBuff; // Avoid unused argument warning
+ return ::wvsprintf(lpstrBuff, lpstrFormat, args);
+#endif
+ }
+
+ inline int sprintf_x(LPTSTR lpstrBuff, size_t cchBuff, LPCTSTR lpstrFormat, ...)
+ {
+ va_list args;
+ va_start(args, lpstrFormat);
+ int nRes = vsprintf_x(lpstrBuff, cchBuff, lpstrFormat, args);
+ va_end(args);
+ return nRes;
+ }
+
+ inline int wsprintf_x(LPTSTR lpstrBuff, size_t cchBuff, LPCTSTR lpstrFormat, ...)
+ {
+ va_list args;
+ va_start(args, lpstrFormat);
+ int nRes = wvsprintf_x(lpstrBuff, cchBuff, lpstrFormat, args);
+ va_end(args);
+ return nRes;
+ }
+}; // namespace SecureHelper
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMessageFilter - Interface for message filter support
+
+class CMessageFilter
+{
+public:
+ virtual BOOL PreTranslateMessage(MSG* pMsg) = 0;
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CIdleHandler - Interface for idle processing
+
+class CIdleHandler
+{
+public:
+ virtual BOOL OnIdle() = 0;
+};
+
+#ifndef _ATL_NO_OLD_NAMES
+ // for compatilibility with old names only
+ typedef CIdleHandler CUpdateUIObject;
+ #define DoUpdate OnIdle
+#endif // !_ATL_NO_OLD_NAMES
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMessageLoop - message loop implementation
+
+class CMessageLoop
+{
+public:
+ ATL::CSimpleArray<CMessageFilter*> m_aMsgFilter;
+ ATL::CSimpleArray<CIdleHandler*> m_aIdleHandler;
+ MSG m_msg;
+
+// Message filter operations
+ BOOL AddMessageFilter(CMessageFilter* pMessageFilter)
+ {
+ return m_aMsgFilter.Add(pMessageFilter);
+ }
+
+ BOOL RemoveMessageFilter(CMessageFilter* pMessageFilter)
+ {
+ return m_aMsgFilter.Remove(pMessageFilter);
+ }
+
+// Idle handler operations
+ BOOL AddIdleHandler(CIdleHandler* pIdleHandler)
+ {
+ return m_aIdleHandler.Add(pIdleHandler);
+ }
+
+ BOOL RemoveIdleHandler(CIdleHandler* pIdleHandler)
+ {
+ return m_aIdleHandler.Remove(pIdleHandler);
+ }
+
+#ifndef _ATL_NO_OLD_NAMES
+ // for compatilibility with old names only
+ BOOL AddUpdateUI(CIdleHandler* pIdleHandler)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("CUpdateUIObject and AddUpdateUI are deprecated. Please change your code to use CIdleHandler and OnIdle\n"));
+ return AddIdleHandler(pIdleHandler);
+ }
+
+ BOOL RemoveUpdateUI(CIdleHandler* pIdleHandler)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("CUpdateUIObject and RemoveUpdateUI are deprecated. Please change your code to use CIdleHandler and OnIdle\n"));
+ return RemoveIdleHandler(pIdleHandler);
+ }
+#endif // !_ATL_NO_OLD_NAMES
+
+// message loop
+ int Run()
+ {
+ BOOL bDoIdle = TRUE;
+ int nIdleCount = 0;
+ BOOL bRet;
+
+ for(;;)
+ {
+ while(bDoIdle && !::PeekMessage(&m_msg, NULL, 0, 0, PM_NOREMOVE))
+ {
+ if(!OnIdle(nIdleCount++))
+ bDoIdle = FALSE;
+ }
+
+ bRet = ::GetMessage(&m_msg, NULL, 0, 0);
+
+ if(bRet == -1)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("::GetMessage returned -1 (error)\n"));
+ continue; // error, don't process
+ }
+ else if(!bRet)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("CMessageLoop::Run - exiting\n"));
+ break; // WM_QUIT, exit message loop
+ }
+
+ if(!PreTranslateMessage(&m_msg))
+ {
+ ::TranslateMessage(&m_msg);
+ ::DispatchMessage(&m_msg);
+ }
+
+ if(IsIdleMessage(&m_msg))
+ {
+ bDoIdle = TRUE;
+ nIdleCount = 0;
+ }
+ }
+
+ return (int)m_msg.wParam;
+ }
+
+ static BOOL IsIdleMessage(MSG* pMsg)
+ {
+ // These messages should NOT cause idle processing
+ switch(pMsg->message)
+ {
+ case WM_MOUSEMOVE:
+#ifndef _WIN32_WCE
+ case WM_NCMOUSEMOVE:
+#endif // !_WIN32_WCE
+ case WM_PAINT:
+ case 0x0118: // WM_SYSTIMER (caret blink)
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+// Overrideables
+ // Override to change message filtering
+ virtual BOOL PreTranslateMessage(MSG* pMsg)
+ {
+ // loop backwards
+ for(int i = m_aMsgFilter.GetSize() - 1; i >= 0; i--)
+ {
+ CMessageFilter* pMessageFilter = m_aMsgFilter[i];
+ if(pMessageFilter != NULL && pMessageFilter->PreTranslateMessage(pMsg))
+ return TRUE;
+ }
+ return FALSE; // not translated
+ }
+
+ // override to change idle processing
+ virtual BOOL OnIdle(int /*nIdleCount*/)
+ {
+ for(int i = 0; i < m_aIdleHandler.GetSize(); i++)
+ {
+ CIdleHandler* pIdleHandler = m_aIdleHandler[i];
+ if(pIdleHandler != NULL)
+ pIdleHandler->OnIdle();
+ }
+ return FALSE; // don't continue
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CStaticDataInitCriticalSectionLock and CWindowCreateCriticalSectionLock
+// internal classes to manage critical sections for both ATL3 and ATL7
+
+class CStaticDataInitCriticalSectionLock
+{
+public:
+#if (_ATL_VER >= 0x0700)
+ ATL::CComCritSecLock<ATL::CComCriticalSection> m_cslock;
+
+ CStaticDataInitCriticalSectionLock() : m_cslock(ATL::_pAtlModule->m_csStaticDataInitAndTypeInfo, false)
+ { }
+#endif // (_ATL_VER >= 0x0700)
+
+ HRESULT Lock()
+ {
+#if (_ATL_VER >= 0x0700)
+ return m_cslock.Lock();
+#else // !(_ATL_VER >= 0x0700)
+ ::EnterCriticalSection(&ATL::_pModule->m_csStaticDataInit);
+ return S_OK;
+#endif // !(_ATL_VER >= 0x0700)
+ }
+
+ void Unlock()
+ {
+#if (_ATL_VER >= 0x0700)
+ m_cslock.Unlock();
+#else // !(_ATL_VER >= 0x0700)
+ ::LeaveCriticalSection(&ATL::_pModule->m_csStaticDataInit);
+#endif // !(_ATL_VER >= 0x0700)
+ }
+};
+
+
+class CWindowCreateCriticalSectionLock
+{
+public:
+#if (_ATL_VER >= 0x0700)
+ ATL::CComCritSecLock<ATL::CComCriticalSection> m_cslock;
+
+ CWindowCreateCriticalSectionLock() : m_cslock(ATL::_AtlWinModule.m_csWindowCreate, false)
+ { }
+#endif // (_ATL_VER >= 0x0700)
+
+ HRESULT Lock()
+ {
+#if (_ATL_VER >= 0x0700)
+ return m_cslock.Lock();
+#else // !(_ATL_VER >= 0x0700)
+ ::EnterCriticalSection(&ATL::_pModule->m_csWindowCreate);
+ return S_OK;
+#endif // !(_ATL_VER >= 0x0700)
+ }
+
+ void Unlock()
+ {
+#if (_ATL_VER >= 0x0700)
+ m_cslock.Unlock();
+#else // !(_ATL_VER >= 0x0700)
+ ::LeaveCriticalSection(&ATL::_pModule->m_csWindowCreate);
+#endif // !(_ATL_VER >= 0x0700)
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTempBuffer - helper class for stack allocations for ATL3
+
+#ifndef _WTL_STACK_ALLOC_THRESHOLD
+ #define _WTL_STACK_ALLOC_THRESHOLD 512
+#endif
+
+#if (_ATL_VER >= 0x0700)
+
+using ATL::CTempBuffer;
+
+#else // !(_ATL_VER >= 0x0700)
+
+#ifndef SIZE_MAX
+ #ifdef _WIN64
+ #define SIZE_MAX _UI64_MAX
+ #else
+ #define SIZE_MAX UINT_MAX
+ #endif
+#endif
+
+#pragma warning(disable: 4284) // warning for operator ->
+
+template<typename T, int t_nFixedBytes = 128>
+class CTempBuffer
+{
+public:
+ CTempBuffer() : m_p(NULL)
+ {
+ }
+
+ CTempBuffer(size_t nElements) : m_p(NULL)
+ {
+ Allocate(nElements);
+ }
+
+ ~CTempBuffer()
+ {
+ if(m_p != reinterpret_cast<T*>(m_abFixedBuffer))
+ free(m_p);
+ }
+
+ operator T*() const
+ {
+ return m_p;
+ }
+
+ T* operator ->() const
+ {
+ ATLASSERT(m_p != NULL);
+ return m_p;
+ }
+
+ T* Allocate(size_t nElements)
+ {
+ ATLASSERT(nElements <= (SIZE_MAX / sizeof(T)));
+ return AllocateBytes(nElements * sizeof(T));
+ }
+
+ T* AllocateBytes(size_t nBytes)
+ {
+ ATLASSERT(m_p == NULL);
+ if(nBytes > t_nFixedBytes)
+ m_p = static_cast<T*>(malloc(nBytes));
+ else
+ m_p = reinterpret_cast<T*>(m_abFixedBuffer);
+
+ return m_p;
+ }
+
+private:
+ T* m_p;
+ BYTE m_abFixedBuffer[t_nFixedBytes];
+};
+
+#pragma warning(default: 4284)
+
+#endif // !(_ATL_VER >= 0x0700)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppModule - module class for an application
+
+class CAppModule : public ATL::CComModule
+{
+public:
+ DWORD m_dwMainThreadID;
+ ATL::CSimpleMap<DWORD, CMessageLoop*>* m_pMsgLoopMap;
+ ATL::CSimpleArray<HWND>* m_pSettingChangeNotify;
+
+// Overrides of CComModule::Init and Term
+ HRESULT Init(ATL::_ATL_OBJMAP_ENTRY* pObjMap, HINSTANCE hInstance, const GUID* pLibID = NULL)
+ {
+ HRESULT hRet = CComModule::Init(pObjMap, hInstance, pLibID);
+ if(FAILED(hRet))
+ return hRet;
+
+ m_dwMainThreadID = ::GetCurrentThreadId();
+ typedef ATL::CSimpleMap<DWORD, CMessageLoop*> _mapClass;
+ m_pMsgLoopMap = NULL;
+ ATLTRY(m_pMsgLoopMap = new _mapClass);
+ if(m_pMsgLoopMap == NULL)
+ return E_OUTOFMEMORY;
+ m_pSettingChangeNotify = NULL;
+
+ return hRet;
+ }
+
+ void Term()
+ {
+ TermSettingChangeNotify();
+ delete m_pMsgLoopMap;
+ CComModule::Term();
+ }
+
+// Message loop map methods
+ BOOL AddMessageLoop(CMessageLoop* pMsgLoop)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CAppModule::AddMessageLoop.\n"));
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+ ATLASSERT(pMsgLoop != NULL);
+ ATLASSERT(m_pMsgLoopMap->Lookup(::GetCurrentThreadId()) == NULL); // not in map yet
+
+ BOOL bRet = m_pMsgLoopMap->Add(::GetCurrentThreadId(), pMsgLoop);
+
+ lock.Unlock();
+
+ return bRet;
+ }
+
+ BOOL RemoveMessageLoop()
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CAppModule::RemoveMessageLoop.\n"));
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+ BOOL bRet = m_pMsgLoopMap->Remove(::GetCurrentThreadId());
+
+ lock.Unlock();
+
+ return bRet;
+ }
+
+ CMessageLoop* GetMessageLoop(DWORD dwThreadID = ::GetCurrentThreadId()) const
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CAppModule::GetMessageLoop.\n"));
+ ATLASSERT(FALSE);
+ return NULL;
+ }
+
+ CMessageLoop* pLoop = m_pMsgLoopMap->Lookup(dwThreadID);
+
+ lock.Unlock();
+
+ return pLoop;
+ }
+
+// Setting change notify methods
+ // Note: Call this from the main thread for MSDI apps
+ BOOL InitSettingChangeNotify(DLGPROC pfnDlgProc = _SettingChangeDlgProc)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CAppModule::InitSettingChangeNotify.\n"));
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+ if(m_pSettingChangeNotify == NULL)
+ {
+ typedef ATL::CSimpleArray<HWND> _notifyClass;
+ ATLTRY(m_pSettingChangeNotify = new _notifyClass);
+ ATLASSERT(m_pSettingChangeNotify != NULL);
+ }
+
+ BOOL bRet = (m_pSettingChangeNotify != NULL);
+ if(bRet && m_pSettingChangeNotify->GetSize() == 0)
+ {
+ // init everything
+ _ATL_EMPTY_DLGTEMPLATE templ;
+ HWND hNtfWnd = ::CreateDialogIndirect(GetModuleInstance(), &templ, NULL, pfnDlgProc);
+ ATLASSERT(::IsWindow(hNtfWnd));
+ if(::IsWindow(hNtfWnd))
+ {
+// need conditional code because types don't match in winuser.h
+#ifdef _WIN64
+ ::SetWindowLongPtr(hNtfWnd, GWLP_USERDATA, (LONG_PTR)this);
+#else
+ ::SetWindowLongPtr(hNtfWnd, GWLP_USERDATA, PtrToLong(this));
+#endif
+ bRet = m_pSettingChangeNotify->Add(hNtfWnd);
+ }
+ else
+ {
+ bRet = FALSE;
+ }
+ }
+
+ lock.Unlock();
+
+ return bRet;
+ }
+
+ void TermSettingChangeNotify()
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CAppModule::TermSettingChangeNotify.\n"));
+ ATLASSERT(FALSE);
+ return;
+ }
+
+ if(m_pSettingChangeNotify != NULL && m_pSettingChangeNotify->GetSize() > 0)
+ ::DestroyWindow((*m_pSettingChangeNotify)[0]);
+ delete m_pSettingChangeNotify;
+ m_pSettingChangeNotify = NULL;
+
+ lock.Unlock();
+ }
+
+ BOOL AddSettingChangeNotify(HWND hWnd)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CAppModule::AddSettingChangeNotify.\n"));
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+ ATLASSERT(::IsWindow(hWnd));
+ BOOL bRet = FALSE;
+ if(InitSettingChangeNotify() != FALSE)
+ bRet = m_pSettingChangeNotify->Add(hWnd);
+
+ lock.Unlock();
+
+ return bRet;
+ }
+
+ BOOL RemoveSettingChangeNotify(HWND hWnd)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CAppModule::RemoveSettingChangeNotify.\n"));
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+ BOOL bRet = FALSE;
+ if(m_pSettingChangeNotify != NULL)
+ bRet = m_pSettingChangeNotify->Remove(hWnd);
+
+ lock.Unlock();
+
+ return bRet;
+ }
+
+// Implementation - setting change notify dialog template and dialog procedure
+ struct _ATL_EMPTY_DLGTEMPLATE : DLGTEMPLATE
+ {
+ _ATL_EMPTY_DLGTEMPLATE()
+ {
+ memset(this, 0, sizeof(_ATL_EMPTY_DLGTEMPLATE));
+ style = WS_POPUP;
+ }
+ WORD wMenu, wClass, wTitle;
+ };
+
+#ifdef _WIN64
+ static INT_PTR CALLBACK _SettingChangeDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+#else
+ static BOOL CALLBACK _SettingChangeDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+#endif
+ {
+ if(uMsg == WM_SETTINGCHANGE)
+ {
+// need conditional code because types don't match in winuser.h
+#ifdef _WIN64
+ CAppModule* pModule = (CAppModule*)::GetWindowLongPtr(hWnd, GWLP_USERDATA);
+#else
+ CAppModule* pModule = (CAppModule*)LongToPtr(::GetWindowLongPtr(hWnd, GWLP_USERDATA));
+#endif
+ ATLASSERT(pModule != NULL);
+ ATLASSERT(pModule->m_pSettingChangeNotify != NULL);
+ const UINT uTimeout = 1500; // ms
+ for(int i = 1; i < pModule->m_pSettingChangeNotify->GetSize(); i++)
+ {
+#if !defined(_WIN32_WCE)
+ ::SendMessageTimeout((*pModule->m_pSettingChangeNotify)[i], uMsg, wParam, lParam, SMTO_ABORTIFHUNG, uTimeout, NULL);
+#elif(_WIN32_WCE >= 400) // CE specific
+ ::SendMessageTimeout((*pModule->m_pSettingChangeNotify)[i], uMsg, wParam, lParam, SMTO_NORMAL, uTimeout, NULL);
+#else // _WIN32_WCE < 400 specific
+ uTimeout;
+ ::SendMessage((*pModule->m_pSettingChangeNotify)[i], uMsg, wParam, lParam);
+#endif
+ }
+ return TRUE;
+ }
+ return FALSE;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CServerAppModule - module class for a COM server application
+
+class CServerAppModule : public CAppModule
+{
+public:
+ HANDLE m_hEventShutdown;
+ bool m_bActivity;
+ DWORD m_dwTimeOut;
+ DWORD m_dwPause;
+
+// Override of CAppModule::Init
+ HRESULT Init(ATL::_ATL_OBJMAP_ENTRY* pObjMap, HINSTANCE hInstance, const GUID* pLibID = NULL)
+ {
+ m_dwTimeOut = 5000;
+ m_dwPause = 1000;
+ return CAppModule::Init(pObjMap, hInstance, pLibID);
+ }
+
+ void Term()
+ {
+ if(m_hEventShutdown != NULL && ::CloseHandle(m_hEventShutdown))
+ m_hEventShutdown = NULL;
+ CAppModule::Term();
+ }
+
+// COM Server methods
+ LONG Unlock()
+ {
+ LONG lRet = CComModule::Unlock();
+ if(lRet == 0)
+ {
+ m_bActivity = true;
+ ::SetEvent(m_hEventShutdown); // tell monitor that we transitioned to zero
+ }
+ return lRet;
+ }
+
+ void MonitorShutdown()
+ {
+ for(;;)
+ {
+ ::WaitForSingleObject(m_hEventShutdown, INFINITE);
+ DWORD dwWait = 0;
+ do
+ {
+ m_bActivity = false;
+ dwWait = ::WaitForSingleObject(m_hEventShutdown, m_dwTimeOut);
+ }
+ while(dwWait == WAIT_OBJECT_0);
+ // timed out
+ if(!m_bActivity && m_nLockCnt == 0) // if no activity let's really bail
+ {
+#if ((_WIN32_WINNT >= 0x0400 ) || defined(_WIN32_DCOM)) && defined(_ATL_FREE_THREADED) && !defined(_WIN32_WCE)
+ ::CoSuspendClassObjects();
+ if(!m_bActivity && m_nLockCnt == 0)
+#endif
+ break;
+ }
+ }
+ // This handle should be valid now. If it isn't,
+ // check if _Module.Term was called first (it shouldn't)
+ if(::CloseHandle(m_hEventShutdown))
+ m_hEventShutdown = NULL;
+ ::PostThreadMessage(m_dwMainThreadID, WM_QUIT, 0, 0);
+ }
+
+ bool StartMonitor()
+ {
+ m_hEventShutdown = ::CreateEvent(NULL, false, false, NULL);
+ if(m_hEventShutdown == NULL)
+ return false;
+ DWORD dwThreadID = 0;
+#if !defined(_ATL_MIN_CRT) && defined(_MT) && !defined(_WIN32_WCE)
+ HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, (UINT (WINAPI*)(void*))MonitorProc, this, 0, (UINT*)&dwThreadID);
+#else
+ HANDLE hThread = ::CreateThread(NULL, 0, MonitorProc, this, 0, &dwThreadID);
+#endif
+ bool bRet = (hThread != NULL);
+ if(bRet)
+ ::CloseHandle(hThread);
+ return bRet;
+ }
+
+ static DWORD WINAPI MonitorProc(void* pv)
+ {
+ CServerAppModule* p = (CServerAppModule*)pv;
+ p->MonitorShutdown();
+ return 0;
+ }
+
+#if (_ATL_VER < 0x0700)
+ // search for an occurence of string p2 in string p1
+ static LPCTSTR FindOneOf(LPCTSTR p1, LPCTSTR p2)
+ {
+ while(p1 != NULL && *p1 != NULL)
+ {
+ LPCTSTR p = p2;
+ while(p != NULL && *p != NULL)
+ {
+ if(*p1 == *p)
+ return ::CharNext(p1);
+ p = ::CharNext(p);
+ }
+ p1 = ::CharNext(p1);
+ }
+ return NULL;
+ }
+#endif // (_ATL_VER < 0x0700)
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRegKeyEx - adds type-specific methods to ATL3 CRegKey
+
+#if (_ATL_VER < 0x0700)
+
+class CRegKeyEx : public ATL::CRegKey
+{
+public:
+// Constructors and operators
+ CRegKeyEx(HKEY hKey = NULL)
+ {
+ m_hKey = hKey;
+ }
+
+ CRegKeyEx(CRegKeyEx& key)
+ {
+ Attach(key.Detach());
+ }
+
+ CRegKeyEx& operator =(CRegKeyEx& key)
+ {
+ Close();
+ Attach(key.Detach());
+ return *this;
+ }
+
+// Methods
+ LONG SetValue(LPCTSTR pszValueName, DWORD dwType, const void* pValue, ULONG nBytes)
+ {
+ ATLASSERT(m_hKey != NULL);
+ return ::RegSetValueEx(m_hKey, pszValueName, NULL, dwType, static_cast<const BYTE*>(pValue), nBytes);
+ }
+
+ LONG SetGUIDValue(LPCTSTR pszValueName, REFGUID guidValue)
+ {
+ ATLASSERT(m_hKey != NULL);
+
+ OLECHAR szGUID[64] = { 0 };
+ ::StringFromGUID2(guidValue, szGUID, 64);
+
+ USES_CONVERSION;
+ LPCTSTR lpstr = OLE2CT(szGUID);
+#ifndef _UNICODE
+ if(lpstr == NULL)
+ return E_OUTOFMEMORY;
+#endif
+ return SetStringValue(pszValueName, lpstr);
+ }
+
+ LONG SetBinaryValue(LPCTSTR pszValueName, const void* pValue, ULONG nBytes)
+ {
+ ATLASSERT(m_hKey != NULL);
+ return ::RegSetValueEx(m_hKey, pszValueName, NULL, REG_BINARY, reinterpret_cast<const BYTE*>(pValue), nBytes);
+ }
+
+ LONG SetDWORDValue(LPCTSTR pszValueName, DWORD dwValue)
+ {
+ ATLASSERT(m_hKey != NULL);
+ return ::RegSetValueEx(m_hKey, pszValueName, NULL, REG_DWORD, reinterpret_cast<const BYTE*>(&dwValue), sizeof(DWORD));
+ }
+
+#ifndef _WIN32_WCE
+ LONG SetQWORDValue(LPCTSTR pszValueName, ULONGLONG qwValue)
+ {
+ ATLASSERT(m_hKey != NULL);
+ return ::RegSetValueEx(m_hKey, pszValueName, NULL, REG_QWORD, reinterpret_cast<const BYTE*>(&qwValue), sizeof(ULONGLONG));
+ }
+#endif
+
+ LONG SetStringValue(LPCTSTR pszValueName, LPCTSTR pszValue, DWORD dwType = REG_SZ)
+ {
+ ATLASSERT(m_hKey != NULL);
+ if(pszValue == NULL)
+ {
+ ATLASSERT(FALSE);
+ return ERROR_INVALID_DATA;
+ }
+ ATLASSERT((dwType == REG_SZ) || (dwType == REG_EXPAND_SZ));
+
+ return ::RegSetValueEx(m_hKey, pszValueName, NULL, dwType, reinterpret_cast<const BYTE*>(pszValue), (lstrlen(pszValue) + 1) * sizeof(TCHAR));
+ }
+
+ LONG SetMultiStringValue(LPCTSTR pszValueName, LPCTSTR pszValue)
+ {
+ ATLASSERT(m_hKey != NULL);
+ if(pszValue == NULL)
+ {
+ ATLASSERT(FALSE);
+ return ERROR_INVALID_DATA;
+ }
+
+ ULONG nBytes = 0;
+ ULONG nLength = 0;
+ LPCTSTR pszTemp = pszValue;
+ do
+ {
+ nLength = lstrlen(pszTemp) + 1;
+ pszTemp += nLength;
+ nBytes += nLength * sizeof(TCHAR);
+ } while (nLength != 1);
+
+ return ::RegSetValueEx(m_hKey, pszValueName, NULL, REG_MULTI_SZ, reinterpret_cast<const BYTE*>(pszValue), nBytes);
+ }
+
+ LONG QueryValue(LPCTSTR pszValueName, DWORD* pdwType, void* pData, ULONG* pnBytes)
+ {
+ ATLASSERT(m_hKey != NULL);
+ return ::RegQueryValueEx(m_hKey, pszValueName, NULL, pdwType, static_cast<LPBYTE>(pData), pnBytes);
+ }
+
+ LONG QueryGUIDValue(LPCTSTR pszValueName, GUID& guidValue)
+ {
+ ATLASSERT(m_hKey != NULL);
+
+ guidValue = GUID_NULL;
+
+ TCHAR szGUID[64] = { 0 };
+ ULONG nCount = 64;
+ LONG lRes = QueryStringValue(pszValueName, szGUID, &nCount);
+
+ if (lRes != ERROR_SUCCESS)
+ return lRes;
+
+ if(szGUID[0] != _T('{'))
+ return ERROR_INVALID_DATA;
+
+ USES_CONVERSION;
+ LPOLESTR lpstr = T2OLE(szGUID);
+#ifndef _UNICODE
+ if(lpstr == NULL)
+ return E_OUTOFMEMORY;
+#endif
+
+ HRESULT hr = ::CLSIDFromString(lpstr, &guidValue);
+ if (FAILED(hr))
+ return ERROR_INVALID_DATA;
+
+ return ERROR_SUCCESS;
+ }
+
+ LONG QueryBinaryValue(LPCTSTR pszValueName, void* pValue, ULONG* pnBytes)
+ {
+ ATLASSERT(pnBytes != NULL);
+ ATLASSERT(m_hKey != NULL);
+
+ DWORD dwType = 0;
+ LONG lRes = ::RegQueryValueEx(m_hKey, pszValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(pValue), pnBytes);
+ if (lRes != ERROR_SUCCESS)
+ return lRes;
+ if (dwType != REG_BINARY)
+ return ERROR_INVALID_DATA;
+
+ return ERROR_SUCCESS;
+ }
+
+ LONG QueryDWORDValue(LPCTSTR pszValueName, DWORD& dwValue)
+ {
+ ATLASSERT(m_hKey != NULL);
+
+ ULONG nBytes = sizeof(DWORD);
+ DWORD dwType = 0;
+ LONG lRes = ::RegQueryValueEx(m_hKey, pszValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&dwValue), &nBytes);
+ if (lRes != ERROR_SUCCESS)
+ return lRes;
+ if (dwType != REG_DWORD)
+ return ERROR_INVALID_DATA;
+
+ return ERROR_SUCCESS;
+ }
+
+ LONG QueryQWORDValue(LPCTSTR pszValueName, ULONGLONG& qwValue)
+ {
+ ATLASSERT(m_hKey != NULL);
+
+ ULONG nBytes = sizeof(ULONGLONG);
+ DWORD dwType = 0;
+ LONG lRes = ::RegQueryValueEx(m_hKey, pszValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&qwValue), &nBytes);
+ if (lRes != ERROR_SUCCESS)
+ return lRes;
+ if (dwType != REG_QWORD)
+ return ERROR_INVALID_DATA;
+
+ return ERROR_SUCCESS;
+ }
+
+ LONG QueryStringValue(LPCTSTR pszValueName, LPTSTR pszValue, ULONG* pnChars)
+ {
+ ATLASSERT(m_hKey != NULL);
+ ATLASSERT(pnChars != NULL);
+
+ ULONG nBytes = (*pnChars) * sizeof(TCHAR);
+ DWORD dwType = 0;
+ *pnChars = 0;
+ LONG lRes = ::RegQueryValueEx(m_hKey, pszValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(pszValue), &nBytes);
+
+ if (lRes != ERROR_SUCCESS)
+ {
+ return lRes;
+ }
+
+ if(dwType != REG_SZ && dwType != REG_EXPAND_SZ)
+ {
+ return ERROR_INVALID_DATA;
+ }
+
+ if (pszValue != NULL)
+ {
+ if(nBytes != 0)
+ {
+ if ((nBytes % sizeof(TCHAR) != 0) || (pszValue[nBytes / sizeof(TCHAR) -1] != 0))
+ return ERROR_INVALID_DATA;
+ }
+ else
+ {
+ pszValue[0] = _T('\0');
+ }
+ }
+
+ *pnChars = nBytes / sizeof(TCHAR);
+
+ return ERROR_SUCCESS;
+ }
+
+ LONG QueryMultiStringValue(LPCTSTR pszValueName, LPTSTR pszValue, ULONG* pnChars)
+ {
+ ATLASSERT(m_hKey != NULL);
+ ATLASSERT(pnChars != NULL);
+
+ if (pszValue != NULL && *pnChars < 2)
+ return ERROR_INSUFFICIENT_BUFFER;
+
+ ULONG nBytes = (*pnChars) * sizeof(TCHAR);
+ DWORD dwType = 0;
+ *pnChars = 0;
+ LONG lRes = ::RegQueryValueEx(m_hKey, pszValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(pszValue), &nBytes);
+ if (lRes != ERROR_SUCCESS)
+ return lRes;
+ if (dwType != REG_MULTI_SZ)
+ return ERROR_INVALID_DATA;
+ if (pszValue != NULL && (nBytes % sizeof(TCHAR) != 0 || nBytes / sizeof(TCHAR) < 1 || pszValue[nBytes / sizeof(TCHAR) - 1] != 0 || ((nBytes / sizeof(TCHAR)) > 1 && pszValue[nBytes / sizeof(TCHAR) - 2] != 0)))
+ return ERROR_INVALID_DATA;
+
+ *pnChars = nBytes / sizeof(TCHAR);
+
+ return ERROR_SUCCESS;
+ }
+};
+
+#else // !(_ATL_VER < 0x0700)
+
+typedef ATL::CRegKey CRegKeyEx;
+
+#endif // !(_ATL_VER < 0x0700)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CString forward reference (enables CString use in atluser.h and atlgdi.h)
+
+#if defined(_WTL_FORWARD_DECLARE_CSTRING) && !defined(_WTL_USE_CSTRING)
+ #define _WTL_USE_CSTRING
+#endif // defined(_WTL_FORWARD_DECLARE_CSTRING) && !defined(_WTL_USE_CSTRING)
+
+#ifdef _WTL_USE_CSTRING
+ class CString; // forward declaration (include atlmisc.h for the whole class)
+#endif // _WTL_USE_CSTRING
+
+// CString namespace
+#ifndef _CSTRING_NS
+ #ifdef __ATLSTR_H__
+ #define _CSTRING_NS ATL
+ #else
+ #define _CSTRING_NS WTL
+ #endif
+#endif // _CSTRING_NS
+
+// Type classes namespace
+#ifndef _WTYPES_NS
+ #ifdef __ATLTYPES_H__
+ #define _WTYPES_NS
+ #else
+ #define _WTYPES_NS WTL
+ #endif
+#endif // _WTYPES_NS
+
+}; // namespace WTL
+
+
+///////////////////////////////////////////////////////////////////////////////
+// General DLL version helpers (excluded from atlbase.h if _ATL_DLL is defined)
+
+#if (_ATL_VER < 0x0700) && defined(_ATL_DLL) && !defined(_WIN32_WCE)
+
+namespace ATL
+{
+
+inline HRESULT AtlGetDllVersion(HINSTANCE hInstDLL, DLLVERSIONINFO* pDllVersionInfo)
+{
+ ATLASSERT(pDllVersionInfo != NULL);
+ if(pDllVersionInfo == NULL)
+ return E_INVALIDARG;
+
+ // We must get this function explicitly because some DLLs don't implement it.
+ DLLGETVERSIONPROC pfnDllGetVersion = (DLLGETVERSIONPROC)::GetProcAddress(hInstDLL, "DllGetVersion");
+ if(pfnDllGetVersion == NULL)
+ return E_NOTIMPL;
+
+ return (*pfnDllGetVersion)(pDllVersionInfo);
+}
+
+inline HRESULT AtlGetDllVersion(LPCTSTR lpstrDllName, DLLVERSIONINFO* pDllVersionInfo)
+{
+ HINSTANCE hInstDLL = ::LoadLibrary(lpstrDllName);
+ if(hInstDLL == NULL)
+ return E_FAIL;
+ HRESULT hRet = AtlGetDllVersion(hInstDLL, pDllVersionInfo);
+ ::FreeLibrary(hInstDLL);
+ return hRet;
+}
+
+// Common Control Versions:
+// Win95/WinNT 4.0 maj=4 min=00
+// IE 3.x maj=4 min=70
+// IE 4.0 maj=4 min=71
+inline HRESULT AtlGetCommCtrlVersion(LPDWORD pdwMajor, LPDWORD pdwMinor)
+{
+ ATLASSERT(pdwMajor != NULL && pdwMinor != NULL);
+ if(pdwMajor == NULL || pdwMinor == NULL)
+ return E_INVALIDARG;
+
+ DLLVERSIONINFO dvi;
+ ::ZeroMemory(&dvi, sizeof(dvi));
+ dvi.cbSize = sizeof(dvi);
+ HRESULT hRet = AtlGetDllVersion(_T("comctl32.dll"), &dvi);
+
+ if(SUCCEEDED(hRet))
+ {
+ *pdwMajor = dvi.dwMajorVersion;
+ *pdwMinor = dvi.dwMinorVersion;
+ }
+ else if(hRet == E_NOTIMPL)
+ {
+ // If DllGetVersion is not there, then the DLL is a version
+ // previous to the one shipped with IE 3.x
+ *pdwMajor = 4;
+ *pdwMinor = 0;
+ hRet = S_OK;
+ }
+
+ return hRet;
+}
+
+// Shell Versions:
+// Win95/WinNT 4.0 maj=4 min=00
+// IE 3.x, IE 4.0 without Web Integrated Desktop maj=4 min=00
+// IE 4.0 with Web Integrated Desktop maj=4 min=71
+// IE 4.01 with Web Integrated Desktop maj=4 min=72
+inline HRESULT AtlGetShellVersion(LPDWORD pdwMajor, LPDWORD pdwMinor)
+{
+ ATLASSERT(pdwMajor != NULL && pdwMinor != NULL);
+ if(pdwMajor == NULL || pdwMinor == NULL)
+ return E_INVALIDARG;
+
+ DLLVERSIONINFO dvi;
+ ::ZeroMemory(&dvi, sizeof(dvi));
+ dvi.cbSize = sizeof(dvi);
+ HRESULT hRet = AtlGetDllVersion(_T("shell32.dll"), &dvi);
+
+ if(SUCCEEDED(hRet))
+ {
+ *pdwMajor = dvi.dwMajorVersion;
+ *pdwMinor = dvi.dwMinorVersion;
+ }
+ else if(hRet == E_NOTIMPL)
+ {
+ // If DllGetVersion is not there, then the DLL is a version
+ // previous to the one shipped with IE 4.x
+ *pdwMajor = 4;
+ *pdwMinor = 0;
+ hRet = S_OK;
+ }
+
+ return hRet;
+}
+
+}; // namespace ATL
+
+#endif // (_ATL_VER < 0x0700) && defined(_ATL_DLL) && !defined(_WIN32_WCE)
+
+
+// These are always included
+#include "atlwinx.h"
+#include "atluser.h"
+#include "atlgdi.h"
+
+#ifndef _WTL_NO_AUTOMATIC_NAMESPACE
+using namespace WTL;
+#endif // !_WTL_NO_AUTOMATIC_NAMESPACE
+
+#endif // __ATLAPP_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlcrack.h b/plugins/SmartAutoReplier/wtl/atlcrack.h
new file mode 100644
index 0000000000..b9971b5510
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlcrack.h
@@ -0,0 +1,2384 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLCRACK_H__
+#define __ATLCRACK_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlcrack.h requires atlapp.h to be included first
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Message map macro for cracked handlers
+
+// Note about message maps with cracked handlers:
+// For ATL 3.0, a message map using cracked handlers MUST use BEGIN_MSG_MAP_EX.
+// For ATL 7.0 or higher, you can use BEGIN_MSG_MAP for CWindowImpl/CDialogImpl derived classes,
+// but must use BEGIN_MSG_MAP_EX for classes that don't derive from CWindowImpl/CDialogImpl.
+
+#define BEGIN_MSG_MAP_EX(theClass) \
+public: \
+ BOOL m_bMsgHandled; \
+ /* "handled" management for cracked handlers */ \
+ BOOL IsMsgHandled() const \
+ { \
+ return m_bMsgHandled; \
+ } \
+ void SetMsgHandled(BOOL bHandled) \
+ { \
+ m_bMsgHandled = bHandled; \
+ } \
+ BOOL ProcessWindowMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult, DWORD dwMsgMapID = 0) \
+ { \
+ BOOL bOldMsgHandled = m_bMsgHandled; \
+ BOOL bRet = _ProcessWindowMessage(hWnd, uMsg, wParam, lParam, lResult, dwMsgMapID); \
+ m_bMsgHandled = bOldMsgHandled; \
+ return bRet; \
+ } \
+ BOOL _ProcessWindowMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult, DWORD dwMsgMapID) \
+ { \
+ BOOL bHandled = TRUE; \
+ hWnd; \
+ uMsg; \
+ wParam; \
+ lParam; \
+ lResult; \
+ bHandled; \
+ switch(dwMsgMapID) \
+ { \
+ case 0:
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Standard Windows message macros
+
+// int OnCreate(LPCREATESTRUCT lpCreateStruct)
+#define MSG_WM_CREATE(func) \
+ if (uMsg == WM_CREATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((LPCREATESTRUCT)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnInitDialog(CWindow wndFocus, LPARAM lInitParam)
+#define MSG_WM_INITDIALOG(func) \
+ if (uMsg == WM_INITDIALOG) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HWND)wParam, lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnCopyData(CWindow wnd, PCOPYDATASTRUCT pCopyDataStruct)
+#define MSG_WM_COPYDATA(func) \
+ if (uMsg == WM_COPYDATA) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HWND)wParam, (PCOPYDATASTRUCT)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDestroy()
+#define MSG_WM_DESTROY(func) \
+ if (uMsg == WM_DESTROY) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMove(CPoint ptPos)
+#define MSG_WM_MOVE(func) \
+ if (uMsg == WM_MOVE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(_WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSize(UINT nType, CSize size)
+#define MSG_WM_SIZE(func) \
+ if (uMsg == WM_SIZE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CSize(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnActivate(UINT nState, BOOL bMinimized, CWindow wndOther)
+#define MSG_WM_ACTIVATE(func) \
+ if (uMsg == WM_ACTIVATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)LOWORD(wParam), (BOOL)HIWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSetFocus(CWindow wndOld)
+#define MSG_WM_SETFOCUS(func) \
+ if (uMsg == WM_SETFOCUS) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnKillFocus(CWindow wndFocus)
+#define MSG_WM_KILLFOCUS(func) \
+ if (uMsg == WM_KILLFOCUS) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnEnable(BOOL bEnable)
+#define MSG_WM_ENABLE(func) \
+ if (uMsg == WM_ENABLE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnPaint(CDCHandle dc)
+#define MSG_WM_PAINT(func) \
+ if (uMsg == WM_PAINT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HDC)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnClose()
+#define MSG_WM_CLOSE(func) \
+ if (uMsg == WM_CLOSE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnQueryEndSession(UINT nSource, UINT uLogOff)
+#define MSG_WM_QUERYENDSESSION(func) \
+ if (uMsg == WM_QUERYENDSESSION) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)wParam, (UINT)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnQueryOpen()
+#define MSG_WM_QUERYOPEN(func) \
+ if (uMsg == WM_QUERYOPEN) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func(); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnEraseBkgnd(CDCHandle dc)
+#define MSG_WM_ERASEBKGND(func) \
+ if (uMsg == WM_ERASEBKGND) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSysColorChange()
+#define MSG_WM_SYSCOLORCHANGE(func) \
+ if (uMsg == WM_SYSCOLORCHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnEndSession(BOOL bEnding, UINT uLogOff)
+#define MSG_WM_ENDSESSION(func) \
+ if (uMsg == WM_ENDSESSION) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)wParam, (UINT)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnShowWindow(BOOL bShow, UINT nStatus)
+#define MSG_WM_SHOWWINDOW(func) \
+ if (uMsg == WM_SHOWWINDOW) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)wParam, (int)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnCtlColorEdit(CDCHandle dc, CEdit edit)
+#define MSG_WM_CTLCOLOREDIT(func) \
+ if (uMsg == WM_CTLCOLOREDIT) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnCtlColorListBox(CDCHandle dc, CListBox listBox)
+#define MSG_WM_CTLCOLORLISTBOX(func) \
+ if (uMsg == WM_CTLCOLORLISTBOX) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnCtlColorBtn(CDCHandle dc, CButton button)
+#define MSG_WM_CTLCOLORBTN(func) \
+ if (uMsg == WM_CTLCOLORBTN) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnCtlColorDlg(CDCHandle dc, CWindow wnd)
+#define MSG_WM_CTLCOLORDLG(func) \
+ if (uMsg == WM_CTLCOLORDLG) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnCtlColorScrollBar(CDCHandle dc, CScrollBar scrollBar)
+#define MSG_WM_CTLCOLORSCROLLBAR(func) \
+ if (uMsg == WM_CTLCOLORSCROLLBAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnCtlColorStatic(CDCHandle dc, CStatic wndStatic)
+#define MSG_WM_CTLCOLORSTATIC(func) \
+ if (uMsg == WM_CTLCOLORSTATIC) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
+#define MSG_WM_SETTINGCHANGE(func) \
+ if (uMsg == WM_SETTINGCHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPCTSTR)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDevModeChange(LPCTSTR lpDeviceName)
+#define MSG_WM_DEVMODECHANGE(func) \
+ if (uMsg == WM_DEVMODECHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((LPCTSTR)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnActivateApp(BOOL bActive, DWORD dwThreadID)
+#define MSG_WM_ACTIVATEAPP(func) \
+ if (uMsg == WM_ACTIVATEAPP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)wParam, (DWORD)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnFontChange()
+#define MSG_WM_FONTCHANGE(func) \
+ if (uMsg == WM_FONTCHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnTimeChange()
+#define MSG_WM_TIMECHANGE(func) \
+ if (uMsg == WM_TIMECHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCancelMode()
+#define MSG_WM_CANCELMODE(func) \
+ if (uMsg == WM_CANCELMODE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnSetCursor(CWindow wnd, UINT nHitTest, UINT message)
+#define MSG_WM_SETCURSOR(func) \
+ if (uMsg == WM_SETCURSOR) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HWND)wParam, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam)); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnMouseActivate(CWindow wndTopLevel, UINT nHitTest, UINT message)
+#define MSG_WM_MOUSEACTIVATE(func) \
+ if (uMsg == WM_MOUSEACTIVATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HWND)wParam, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam)); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnChildActivate()
+#define MSG_WM_CHILDACTIVATE(func) \
+ if (uMsg == WM_CHILDACTIVATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnGetMinMaxInfo(LPMINMAXINFO lpMMI)
+#define MSG_WM_GETMINMAXINFO(func) \
+ if (uMsg == WM_GETMINMAXINFO) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((LPMINMAXINFO)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnIconEraseBkgnd(CDCHandle dc)
+#define MSG_WM_ICONERASEBKGND(func) \
+ if (uMsg == WM_ICONERASEBKGND) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HDC)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSpoolerStatus(UINT nStatus, UINT nJobs)
+#define MSG_WM_SPOOLERSTATUS(func) \
+ if (uMsg == WM_SPOOLERSTATUS) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (UINT)LOWORD(lParam)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
+#define MSG_WM_DRAWITEM(func) \
+ if (uMsg == WM_DRAWITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPDRAWITEMSTRUCT)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
+#define MSG_WM_MEASUREITEM(func) \
+ if (uMsg == WM_MEASUREITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPMEASUREITEMSTRUCT)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDeleteItem(int nIDCtl, LPDELETEITEMSTRUCT lpDeleteItemStruct)
+#define MSG_WM_DELETEITEM(func) \
+ if (uMsg == WM_DELETEITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPDELETEITEMSTRUCT)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+//int OnCharToItem(UINT nChar, UINT nIndex, CListBox listBox)
+#define MSG_WM_CHARTOITEM(func) \
+ if (uMsg == WM_CHARTOITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)LOWORD(wParam), (UINT)HIWORD(wParam), (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnVKeyToItem(UINT nKey, UINT nIndex, CListBox listBox)
+#define MSG_WM_VKEYTOITEM(func) \
+ if (uMsg == WM_VKEYTOITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)LOWORD(wParam), (UINT)HIWORD(wParam), (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HCURSOR OnQueryDragIcon()
+#define MSG_WM_QUERYDRAGICON(func) \
+ if (uMsg == WM_QUERYDRAGICON) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func(); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnCompareItem(int nIDCtl, LPCOMPAREITEMSTRUCT lpCompareItemStruct)
+#define MSG_WM_COMPAREITEM(func) \
+ if (uMsg == WM_COMPAREITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)wParam, (LPCOMPAREITEMSTRUCT)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCompacting(UINT nCpuTime)
+#define MSG_WM_COMPACTING(func) \
+ if (uMsg == WM_COMPACTING) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnNcCreate(LPCREATESTRUCT lpCreateStruct)
+#define MSG_WM_NCCREATE(func) \
+ if (uMsg == WM_NCCREATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((LPCREATESTRUCT)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcDestroy()
+#define MSG_WM_NCDESTROY(func) \
+ if (uMsg == WM_NCDESTROY) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnNcCalcSize(BOOL bCalcValidRects, LPARAM lParam)
+#define MSG_WM_NCCALCSIZE(func) \
+ if (uMsg == WM_NCCALCSIZE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((BOOL)wParam, lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// UINT OnNcHitTest(CPoint point)
+#define MSG_WM_NCHITTEST(func) \
+ if (uMsg == WM_NCHITTEST) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func(_WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcPaint(CRgnHandle rgn)
+#define MSG_WM_NCPAINT(func) \
+ if (uMsg == WM_NCPAINT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HRGN)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnNcActivate(BOOL bActive)
+#define MSG_WM_NCACTIVATE(func) \
+ if (uMsg == WM_NCACTIVATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((BOOL)wParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// UINT OnGetDlgCode(LPMSG lpMsg)
+#define MSG_WM_GETDLGCODE(func) \
+ if (uMsg == WM_GETDLGCODE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((LPMSG)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcMouseMove(UINT nHitTest, CPoint point)
+#define MSG_WM_NCMOUSEMOVE(func) \
+ if (uMsg == WM_NCMOUSEMOVE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcLButtonDown(UINT nHitTest, CPoint point)
+#define MSG_WM_NCLBUTTONDOWN(func) \
+ if (uMsg == WM_NCLBUTTONDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcLButtonUp(UINT nHitTest, CPoint point)
+#define MSG_WM_NCLBUTTONUP(func) \
+ if (uMsg == WM_NCLBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcLButtonDblClk(UINT nHitTest, CPoint point)
+#define MSG_WM_NCLBUTTONDBLCLK(func) \
+ if (uMsg == WM_NCLBUTTONDBLCLK) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcRButtonDown(UINT nHitTest, CPoint point)
+#define MSG_WM_NCRBUTTONDOWN(func) \
+ if (uMsg == WM_NCRBUTTONDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcRButtonUp(UINT nHitTest, CPoint point)
+#define MSG_WM_NCRBUTTONUP(func) \
+ if (uMsg == WM_NCRBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcRButtonDblClk(UINT nHitTest, CPoint point)
+#define MSG_WM_NCRBUTTONDBLCLK(func) \
+ if (uMsg == WM_NCRBUTTONDBLCLK) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcMButtonDown(UINT nHitTest, CPoint point)
+#define MSG_WM_NCMBUTTONDOWN(func) \
+ if (uMsg == WM_NCMBUTTONDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcMButtonUp(UINT nHitTest, CPoint point)
+#define MSG_WM_NCMBUTTONUP(func) \
+ if (uMsg == WM_NCMBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNcMButtonDblClk(UINT nHitTest, CPoint point)
+#define MSG_WM_NCMBUTTONDBLCLK(func) \
+ if (uMsg == WM_NCMBUTTONDBLCLK) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_KEYDOWN(func) \
+ if (uMsg == WM_KEYDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_KEYUP(func) \
+ if (uMsg == WM_KEYUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_CHAR(func) \
+ if (uMsg == WM_CHAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDeadChar(UINT nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_DEADCHAR(func) \
+ if (uMsg == WM_DEADCHAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSysKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_SYSKEYDOWN(func) \
+ if (uMsg == WM_SYSKEYDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSysKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_SYSKEYUP(func) \
+ if (uMsg == WM_SYSKEYUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSysChar(UINT nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_SYSCHAR(func) \
+ if (uMsg == WM_SYSCHAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSysDeadChar(UINT nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_SYSDEADCHAR(func) \
+ if (uMsg == WM_SYSDEADCHAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSysCommand(UINT nID, LPARAM lParam)
+#define MSG_WM_SYSCOMMAND(func) \
+ if (uMsg == WM_SYSCOMMAND) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnTCard(UINT idAction, DWORD dwActionData)
+#define MSG_WM_TCARD(func) \
+ if (uMsg == WM_TCARD) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (DWORD)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnTimer(UINT_PTR nIDEvent)
+#define MSG_WM_TIMER(func) \
+ if (uMsg == WM_TIMER) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT_PTR)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar pScrollBar)
+#define MSG_WM_HSCROLL(func) \
+ if (uMsg == WM_HSCROLL) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((int)LOWORD(wParam), (short)HIWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar pScrollBar)
+#define MSG_WM_VSCROLL(func) \
+ if (uMsg == WM_VSCROLL) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((int)LOWORD(wParam), (short)HIWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnInitMenu(CMenuHandle menu)
+#define MSG_WM_INITMENU(func) \
+ if (uMsg == WM_INITMENU) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HMENU)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnInitMenuPopup(CMenuHandle menuPopup, UINT nIndex, BOOL bSysMenu)
+#define MSG_WM_INITMENUPOPUP(func) \
+ if (uMsg == WM_INITMENUPOPUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HMENU)wParam, (UINT)LOWORD(lParam), (BOOL)HIWORD(lParam)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMenuSelect(UINT nItemID, UINT nFlags, CMenuHandle menu)
+#define MSG_WM_MENUSELECT(func) \
+ if (uMsg == WM_MENUSELECT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)LOWORD(wParam), (UINT)HIWORD(wParam), (HMENU)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnMenuChar(UINT nChar, UINT nFlags, CMenuHandle menu)
+#define MSG_WM_MENUCHAR(func) \
+ if (uMsg == WM_MENUCHAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((TCHAR)LOWORD(wParam), (UINT)HIWORD(wParam), (HMENU)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnNotify(int idCtrl, LPNMHDR pnmh)
+#define MSG_WM_NOTIFY(func) \
+ if (uMsg == WM_NOTIFY) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((int)wParam, (LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnEnterIdle(UINT nWhy, CWindow wndWho)
+#define MSG_WM_ENTERIDLE(func) \
+ if (uMsg == WM_ENTERIDLE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMouseMove(UINT nFlags, CPoint point)
+#define MSG_WM_MOUSEMOVE(func) \
+ if (uMsg == WM_MOUSEMOVE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
+#define MSG_WM_MOUSEWHEEL(func) \
+ if (uMsg == WM_MOUSEWHEEL) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)LOWORD(wParam), (short)HIWORD(wParam), _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnLButtonDown(UINT nFlags, CPoint point)
+#define MSG_WM_LBUTTONDOWN(func) \
+ if (uMsg == WM_LBUTTONDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnLButtonUp(UINT nFlags, CPoint point)
+#define MSG_WM_LBUTTONUP(func) \
+ if (uMsg == WM_LBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnLButtonDblClk(UINT nFlags, CPoint point)
+#define MSG_WM_LBUTTONDBLCLK(func) \
+ if (uMsg == WM_LBUTTONDBLCLK) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnRButtonDown(UINT nFlags, CPoint point)
+#define MSG_WM_RBUTTONDOWN(func) \
+ if (uMsg == WM_RBUTTONDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnRButtonUp(UINT nFlags, CPoint point)
+#define MSG_WM_RBUTTONUP(func) \
+ if (uMsg == WM_RBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnRButtonDblClk(UINT nFlags, CPoint point)
+#define MSG_WM_RBUTTONDBLCLK(func) \
+ if (uMsg == WM_RBUTTONDBLCLK) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMButtonDown(UINT nFlags, CPoint point)
+#define MSG_WM_MBUTTONDOWN(func) \
+ if (uMsg == WM_MBUTTONDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMButtonUp(UINT nFlags, CPoint point)
+#define MSG_WM_MBUTTONUP(func) \
+ if (uMsg == WM_MBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMButtonDblClk(UINT nFlags, CPoint point)
+#define MSG_WM_MBUTTONDBLCLK(func) \
+ if (uMsg == WM_MBUTTONDBLCLK) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnParentNotify(UINT message, UINT nChildID, LPARAM lParam)
+#define MSG_WM_PARENTNOTIFY(func) \
+ if (uMsg == WM_PARENTNOTIFY) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)LOWORD(wParam), (UINT)HIWORD(wParam), lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMDIActivate(CWindow wndActivate, CWindow wndDeactivate)
+#define MSG_WM_MDIACTIVATE(func) \
+ if (uMsg == WM_MDIACTIVATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam, (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnRenderFormat(UINT nFormat)
+#define MSG_WM_RENDERFORMAT(func) \
+ if (uMsg == WM_RENDERFORMAT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnRenderAllFormats()
+#define MSG_WM_RENDERALLFORMATS(func) \
+ if (uMsg == WM_RENDERALLFORMATS) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDestroyClipboard()
+#define MSG_WM_DESTROYCLIPBOARD(func) \
+ if (uMsg == WM_DESTROYCLIPBOARD) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDrawClipboard()
+#define MSG_WM_DRAWCLIPBOARD(func) \
+ if (uMsg == WM_DRAWCLIPBOARD) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnPaintClipboard(CWindow wndViewer, const LPPAINTSTRUCT lpPaintStruct)
+#define MSG_WM_PAINTCLIPBOARD(func) \
+ if (uMsg == WM_PAINTCLIPBOARD) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam, (const LPPAINTSTRUCT)::GlobalLock((HGLOBAL)lParam)); \
+ ::GlobalUnlock((HGLOBAL)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnVScrollClipboard(CWindow wndViewer, UINT nSBCode, UINT nPos)
+#define MSG_WM_VSCROLLCLIPBOARD(func) \
+ if (uMsg == WM_VSCROLLCLIPBOARD) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnContextMenu(CWindow wnd, CPoint point)
+#define MSG_WM_CONTEXTMENU(func) \
+ if (uMsg == WM_CONTEXTMENU) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSizeClipboard(CWindow wndViewer, const LPRECT lpRect)
+#define MSG_WM_SIZECLIPBOARD(func) \
+ if (uMsg == WM_SIZECLIPBOARD) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam, (const LPRECT)::GlobalLock((HGLOBAL)lParam)); \
+ ::GlobalUnlock((HGLOBAL)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnAskCbFormatName(UINT nMaxCount, LPTSTR lpszString)
+#define MSG_WM_ASKCBFORMATNAME(func) \
+ if (uMsg == WM_ASKCBFORMATNAME) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((DWORD)wParam, (LPTSTR)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnChangeCbChain(CWindow wndRemove, CWindow wndAfter)
+#define MSG_WM_CHANGECBCHAIN(func) \
+ if (uMsg == WM_CHANGECBCHAIN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam, (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnHScrollClipboard(CWindow wndViewer, UINT nSBCode, UINT nPos)
+#define MSG_WM_HSCROLLCLIPBOARD(func) \
+ if (uMsg == WM_HSCROLLCLIPBOARD) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnQueryNewPalette()
+#define MSG_WM_QUERYNEWPALETTE(func) \
+ if (uMsg == WM_QUERYNEWPALETTE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func(); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnPaletteChanged(CWindow wndFocus)
+#define MSG_WM_PALETTECHANGED(func) \
+ if (uMsg == WM_PALETTECHANGED) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnPaletteIsChanging(CWindow wndPalChg)
+#define MSG_WM_PALETTEISCHANGING(func) \
+ if (uMsg == WM_PALETTEISCHANGING) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDropFiles(HDROP hDropInfo)
+#define MSG_WM_DROPFILES(func) \
+ if (uMsg == WM_DROPFILES) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HDROP)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnWindowPosChanging(LPWINDOWPOS lpWndPos)
+#define MSG_WM_WINDOWPOSCHANGING(func) \
+ if (uMsg == WM_WINDOWPOSCHANGING) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((LPWINDOWPOS)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnWindowPosChanged(LPWINDOWPOS lpWndPos)
+#define MSG_WM_WINDOWPOSCHANGED(func) \
+ if (uMsg == WM_WINDOWPOSCHANGED) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((LPWINDOWPOS)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnExitMenuLoop(BOOL fIsTrackPopupMenu)
+#define MSG_WM_EXITMENULOOP(func) \
+ if (uMsg == WM_EXITMENULOOP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnEnterMenuLoop(BOOL fIsTrackPopupMenu)
+#define MSG_WM_ENTERMENULOOP(func) \
+ if (uMsg == WM_ENTERMENULOOP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnStyleChanged(int nStyleType, LPSTYLESTRUCT lpStyleStruct)
+#define MSG_WM_STYLECHANGED(func) \
+ if (uMsg == WM_STYLECHANGED) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPSTYLESTRUCT)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnStyleChanging(int nStyleType, LPSTYLESTRUCT lpStyleStruct)
+#define MSG_WM_STYLECHANGING(func) \
+ if (uMsg == WM_STYLECHANGING) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPSTYLESTRUCT)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSizing(UINT fwSide, LPRECT pRect)
+#define MSG_WM_SIZING(func) \
+ if (uMsg == WM_SIZING) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPRECT)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMoving(UINT fwSide, LPRECT pRect)
+#define MSG_WM_MOVING(func) \
+ if (uMsg == WM_MOVING) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPRECT)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCaptureChanged(CWindow wnd)
+#define MSG_WM_CAPTURECHANGED(func) \
+ if (uMsg == WM_CAPTURECHANGED) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnDeviceChange(UINT nEventType, DWORD dwData)
+#define MSG_WM_DEVICECHANGE(func) \
+ if (uMsg == WM_DEVICECHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)wParam, (DWORD)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCommand(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define MSG_WM_COMMAND(func) \
+ if (uMsg == WM_COMMAND) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDisplayChange(UINT uBitsPerPixel, CSize sizeScreen)
+#define MSG_WM_DISPLAYCHANGE(func) \
+ if (uMsg == WM_DISPLAYCHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, _WTYPES_NS::CSize(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnEnterSizeMove()
+#define MSG_WM_ENTERSIZEMOVE(func) \
+ if (uMsg == WM_ENTERSIZEMOVE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnExitSizeMove()
+#define MSG_WM_EXITSIZEMOVE(func) \
+ if (uMsg == WM_EXITSIZEMOVE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HFONT OnGetFont()
+#define MSG_WM_GETFONT(func) \
+ if (uMsg == WM_GETFONT) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func(); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnGetHotKey()
+#define MSG_WM_GETHOTKEY(func) \
+ if (uMsg == WM_GETHOTKEY) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func(); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HICON OnGetIcon()
+#define MSG_WM_GETICON(func) \
+ if (uMsg == WM_GETICON) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)wParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnGetText(int cchTextMax, LPTSTR lpszText)
+#define MSG_WM_GETTEXT(func) \
+ if (uMsg == WM_GETTEXT) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((int)wParam, (LPTSTR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnGetTextLength()
+#define MSG_WM_GETTEXTLENGTH(func) \
+ if (uMsg == WM_GETTEXTLENGTH) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func(); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnHelp(LPHELPINFO lpHelpInfo)
+#define MSG_WM_HELP(func) \
+ if (uMsg == WM_HELP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((LPHELPINFO)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnHotKey(int nHotKeyID, UINT uModifiers, UINT uVirtKey)
+#define MSG_WM_HOTKEY(func) \
+ if (uMsg == WM_HOTKEY) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((int)wParam, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnInputLangChange(DWORD dwCharSet, HKL hKbdLayout)
+#define MSG_WM_INPUTLANGCHANGE(func) \
+ if (uMsg == WM_INPUTLANGCHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((DWORD)wParam, (HKL)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnInputLangChangeRequest(BOOL bSysCharSet, HKL hKbdLayout)
+#define MSG_WM_INPUTLANGCHANGEREQUEST(func) \
+ if (uMsg == WM_INPUTLANGCHANGEREQUEST) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)wParam, (HKL)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNextDlgCtl(BOOL bHandle, WPARAM wCtlFocus)
+#define MSG_WM_NEXTDLGCTL(func) \
+ if (uMsg == WM_NEXTDLGCTL) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)LOWORD(lParam), wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNextMenu(int nVirtKey, LPMDINEXTMENU lpMdiNextMenu)
+#define MSG_WM_NEXTMENU(func) \
+ if (uMsg == WM_NEXTMENU) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((int)wParam, (LPMDINEXTMENU)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnNotifyFormat(CWindow wndFrom, int nCommand)
+#define MSG_WM_NOTIFYFORMAT(func) \
+ if (uMsg == WM_NOTIFYFORMAT) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HWND)wParam, (int)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// BOOL OnPowerBroadcast(DWORD dwPowerEvent, DWORD dwData)
+#define MSG_WM_POWERBROADCAST(func) \
+ if (uMsg == WM_POWERBROADCAST) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((DWORD)wParam, (DWORD)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnPrint(CDCHandle dc, UINT uFlags)
+#define MSG_WM_PRINT(func) \
+ if (uMsg == WM_PRINT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HDC)wParam, (UINT)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnPrintClient(CDCHandle dc, UINT uFlags)
+#define MSG_WM_PRINTCLIENT(func) \
+ if (uMsg == WM_PRINTCLIENT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HDC)wParam, (UINT)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnRasDialEvent(RASCONNSTATE rasconnstate, DWORD dwError)
+#define MSG_WM_RASDIALEVENT(func) \
+ if (uMsg == WM_RASDIALEVENT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((RASCONNSTATE)wParam, (DWORD)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSetFont(CFontHandle font, BOOL bRedraw)
+#define MSG_WM_SETFONT(func) \
+ if (uMsg == WM_SETFONT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((HFONT)wParam, (BOOL)LOWORD(lParam)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnSetHotKey(int nVirtKey, UINT uFlags)
+#define MSG_WM_SETHOTKEY(func) \
+ if (uMsg == WM_SETHOTKEY) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((int)LOBYTE(LOWORD(wParam)), (UINT)HIBYTE(LOWORD(wParam))); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HICON OnSetIcon(UINT uType, HICON hIcon)
+#define MSG_WM_SETICON(func) \
+ if (uMsg == WM_SETICON) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)wParam, (HICON)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnSetRedraw(BOOL bRedraw)
+#define MSG_WM_SETREDRAW(func) \
+ if (uMsg == WM_SETREDRAW) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((BOOL)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnSetText(LPCTSTR lpstrText)
+#define MSG_WM_SETTEXT(func) \
+ if (uMsg == WM_SETTEXT) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((LPCTSTR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnUserChanged()
+#define MSG_WM_USERCHANGED(func) \
+ if (uMsg == WM_USERCHANGED) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+// New NT4 & NT5 messages
+
+#if(_WIN32_WINNT >= 0x0400)
+
+// void OnMouseHover(WPARAM wParam, CPoint ptPos)
+#define MSG_WM_MOUSEHOVER(func) \
+ if (uMsg == WM_MOUSEHOVER) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(wParam, _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMouseLeave()
+#define MSG_WM_MOUSELEAVE(func) \
+ if (uMsg == WM_MOUSELEAVE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+#endif /* _WIN32_WINNT >= 0x0400 */
+
+#if(WINVER >= 0x0500)
+
+// void OnMenuRButtonUp(WPARAM wParam, CMenuHandle menu)
+#define MSG_WM_MENURBUTTONUP(func) \
+ if (uMsg == WM_MENURBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(wParam, (HMENU)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnMenuDrag(WPARAM wParam, CMenuHandle menu)
+#define MSG_WM_MENUDRAG(func) \
+ if (uMsg == WM_MENUDRAG) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func(wParam, (HMENU)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnMenuGetObject(PMENUGETOBJECTINFO info)
+#define MSG_WM_MENUGETOBJECT(func) \
+ if (uMsg == WM_MENUGETOBJECT) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((PMENUGETOBJECTINFO)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnUnInitMenuPopup(UINT nID, CMenuHandle menu)
+#define MSG_WM_UNINITMENUPOPUP(func) \
+ if (uMsg == WM_UNINITMENUPOPUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(lParam), (HMENU)wParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnMenuCommand(WPARAM nIndex, CMenuHandle menu)
+#define MSG_WM_MENUCOMMAND(func) \
+ if (uMsg == WM_MENUCOMMAND) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(wParam, (HMENU)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+#endif /* WINVER >= 0x0500 */
+
+#if(_WIN32_WINNT >= 0x0500)
+
+// BOOL OnAppCommand(CWindow wndFocus, short cmd, WORD uDevice, int dwKeys)
+#define MSG_WM_APPCOMMAND(func) \
+ if (uMsg == WM_APPCOMMAND) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HWND)wParam, GET_APPCOMMAND_LPARAM(lParam), GET_DEVICE_LPARAM(lParam), GET_KEYSTATE_LPARAM(lParam)); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNCXButtonDown(int fwButton, short nHittest, CPoint ptPos)
+#define MSG_WM_NCXBUTTONDOWN(func) \
+ if (uMsg == WM_NCXBUTTONDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(GET_XBUTTON_WPARAM(wParam), GET_NCHITTEST_WPARAM(wParam), _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNCXButtonUp(int fwButton, short nHittest, CPoint ptPos)
+#define MSG_WM_NCXBUTTONUP(func) \
+ if (uMsg == WM_NCXBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(GET_XBUTTON_WPARAM(wParam), GET_NCHITTEST_WPARAM(wParam), _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnNCXButtonDblClk(int fwButton, short nHittest, CPoint ptPos)
+#define MSG_WM_NCXBUTTONDBLCLK(func) \
+ if (uMsg == WM_NCXBUTTONDBLCLK) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(GET_XBUTTON_WPARAM(wParam), GET_NCHITTEST_WPARAM(wParam), _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnXButtonDown(int fwButton, int dwKeys, CPoint ptPos)
+#define MSG_WM_XBUTTONDOWN(func) \
+ if (uMsg == WM_XBUTTONDOWN) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(GET_XBUTTON_WPARAM(wParam), GET_KEYSTATE_WPARAM(wParam), _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnXButtonUp(int fwButton, int dwKeys, CPoint ptPos)
+#define MSG_WM_XBUTTONUP(func) \
+ if (uMsg == WM_XBUTTONUP) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(GET_XBUTTON_WPARAM(wParam), GET_KEYSTATE_WPARAM(wParam), _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnXButtonDblClk(int fwButton, int dwKeys, CPoint ptPos)
+#define MSG_WM_XBUTTONDBLCLK(func) \
+ if (uMsg == WM_XBUTTONDBLCLK) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(GET_XBUTTON_WPARAM(wParam), GET_KEYSTATE_WPARAM(wParam), _WTYPES_NS::CPoint(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam))); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnChangeUIState(WORD nAction, WORD nState)
+#define MSG_WM_CHANGEUISTATE(func) \
+ if (uMsg == WM_CHANGEUISTATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(LOWORD(wParam), HIWORD(wParam)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnUpdateUIState(WORD nAction, WORD nState)
+#define MSG_WM_UPDATEUISTATE(func) \
+ if (uMsg == WM_UPDATEUISTATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(LOWORD(wParam), HIWORD(wParam)); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnQueryUIState()
+#define MSG_WM_QUERYUISTATE(func) \
+ if (uMsg == WM_QUERYUISTATE) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func(); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+#endif // (_WIN32_WINNT >= 0x0500)
+
+#if(_WIN32_WINNT >= 0x0501)
+
+// void OnInput(WPARAM RawInputCode, HRAWINPUT hRawInput)
+#define MSG_WM_INPUT(func) \
+ if (uMsg == WM_INPUT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(GET_RAWINPUT_CODE_WPARAM(wParam), (HRAWINPUT)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnUniChar(TCHAR nChar, UINT nRepCnt, UINT nFlags)
+#define MSG_WM_UNICHAR(func) \
+ if (uMsg == WM_UNICHAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((TCHAR)wParam, (UINT)lParam & 0xFFFF, (UINT)((lParam & 0xFFFF0000) >> 16)); \
+ if(IsMsgHandled()) \
+ { \
+ lResult = (wParam == UNICODE_NOCHAR) ? TRUE : FALSE; \
+ return TRUE; \
+ } \
+ }
+
+// void OnWTSSessionChange(WPARAM nStatusCode, PWTSSESSION_NOTIFICATION nSessionID)
+#define MSG_WM_WTSSESSION_CHANGE(func) \
+ if (uMsg == WM_WTSSESSION_CHANGE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(wParam, (PWTSSESSION_NOTIFICATION)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// OnThemeChanged()
+#define MSG_WM_THEMECHANGED(func) \
+ if (uMsg == WM_THEMECHANGED) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+#endif /* _WIN32_WINNT >= 0x0501 */
+
+///////////////////////////////////////////////////////////////////////////////
+// ATL defined messages
+
+// BOOL OnForwardMsg(LPMSG Msg, DWORD nUserData)
+#define MSG_WM_FORWARDMSG(func) \
+ if (uMsg == WM_FORWARDMSG) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((LPMSG)lParam, (DWORD)wParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+// Dialog specific messages
+
+// LRESULT OnDMGetDefID()
+#define MSG_DM_GETDEFID(func) \
+ if (uMsg == DM_GETDEFID) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func(); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDMSetDefID(UINT DefID)
+#define MSG_DM_SETDEFID(func) \
+ if (uMsg == DM_SETDEFID) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnDMReposition()
+#define MSG_DM_REPOSITION(func) \
+ if (uMsg == DM_REPOSITION) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+// Reflected messages
+
+// void OnReflectedCommand(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define MSG_OCM_COMMAND(func) \
+ if (uMsg == OCM_COMMAND) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedNotify(int idCtrl, LPNMHDR pnmh)
+#define MSG_OCM_NOTIFY(func) \
+ if (uMsg == OCM_NOTIFY) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((int)wParam, (LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnReflectedParentNotify(UINT message, UINT nChildID, LPARAM lParam)
+#define MSG_OCM_PARENTNOTIFY(func) \
+ if (uMsg == OCM_PARENTNOTIFY) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)LOWORD(wParam), (UINT)HIWORD(wParam), lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnReflectedDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct)
+#define MSG_OCM_DRAWITEM(func) \
+ if (uMsg == OCM_DRAWITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPDRAWITEMSTRUCT)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnReflectedMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
+#define MSG_OCM_MEASUREITEM(func) \
+ if (uMsg == OCM_MEASUREITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPMEASUREITEMSTRUCT)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnReflectedCompareItem(int nIDCtl, LPCOMPAREITEMSTRUCT lpCompareItemStruct)
+#define MSG_OCM_COMPAREITEM(func) \
+ if (uMsg == OCM_COMPAREITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)wParam, (LPCOMPAREITEMSTRUCT)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnReflectedDeleteItem(int nIDCtl, LPDELETEITEMSTRUCT lpDeleteItemStruct)
+#define MSG_OCM_DELETEITEM(func) \
+ if (uMsg == OCM_DELETEITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)wParam, (LPDELETEITEMSTRUCT)lParam); \
+ lResult = TRUE; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// int OnReflectedVKeyToItem(UINT nKey, UINT nIndex, CListBox listBox)
+#define MSG_OCM_VKEYTOITEM(func) \
+ if (uMsg == OCM_VKEYTOITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)LOWORD(wParam), (UINT)HIWORD(wParam), (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+//int OnReflectedCharToItem(UINT nChar, UINT nIndex, CListBox listBox)
+#define MSG_OCM_CHARTOITEM(func) \
+ if (uMsg == OCM_CHARTOITEM) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((UINT)LOWORD(wParam), (UINT)HIWORD(wParam), (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnReflectedHScroll(UINT nSBCode, UINT nPos, CScrollBar pScrollBar)
+#define MSG_OCM_HSCROLL(func) \
+ if (uMsg == OCM_HSCROLL) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((int)LOWORD(wParam), (short)HIWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnReflectedVScroll(UINT nSBCode, UINT nPos, CScrollBar pScrollBar)
+#define MSG_OCM_VSCROLL(func) \
+ if (uMsg == OCM_VSCROLL) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((int)LOWORD(wParam), (short)HIWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnReflectedCtlColorEdit(CDCHandle dc, CEdit edit)
+#define MSG_OCM_CTLCOLOREDIT(func) \
+ if (uMsg == OCM_CTLCOLOREDIT) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnReflectedCtlColorListBox(CDCHandle dc, CListBox listBox)
+#define MSG_OCM_CTLCOLORLISTBOX(func) \
+ if (uMsg == OCM_CTLCOLORLISTBOX) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnReflectedCtlColorBtn(CDCHandle dc, CButton button)
+#define MSG_OCM_CTLCOLORBTN(func) \
+ if (uMsg == OCM_CTLCOLORBTN) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnReflectedCtlColorDlg(CDCHandle dc, CWindow wnd)
+#define MSG_OCM_CTLCOLORDLG(func) \
+ if (uMsg == OCM_CTLCOLORDLG) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnReflectedCtlColorScrollBar(CDCHandle dc, CScrollBar scrollBar)
+#define MSG_OCM_CTLCOLORSCROLLBAR(func) \
+ if (uMsg == OCM_CTLCOLORSCROLLBAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// HBRUSH OnReflectedCtlColorStatic(CDCHandle dc, CStatic wndStatic)
+#define MSG_OCM_CTLCOLORSTATIC(func) \
+ if (uMsg == OCM_CTLCOLORSTATIC) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = (LRESULT)func((HDC)wParam, (HWND)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+// Edit specific messages
+
+// void OnClear()
+#define MSG_WM_CLEAR(func) \
+ if (uMsg == WM_CLEAR) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCopy()
+#define MSG_WM_COPY(func) \
+ if (uMsg == WM_COPY) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCut()
+#define MSG_WM_CUT(func) \
+ if (uMsg == WM_CUT) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnPaste()
+#define MSG_WM_PASTE(func) \
+ if (uMsg == WM_PASTE) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnUndo()
+#define MSG_WM_UNDO(func) \
+ if (uMsg == WM_UNDO) \
+ { \
+ SetMsgHandled(TRUE); \
+ func(); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+// Generic message handlers
+
+// LRESULT OnMessageHandlerEX(UINT uMsg, WPARAM wParam, LPARAM lParam)
+#define MESSAGE_HANDLER_EX(msg, func) \
+ if(uMsg == msg) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func(uMsg, wParam, lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnMessageRangeHandlerEX(UINT uMsg, WPARAM wParam, LPARAM lParam)
+#define MESSAGE_RANGE_HANDLER_EX(msgFirst, msgLast, func) \
+ if(uMsg >= msgFirst && uMsg <= msgLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func(uMsg, wParam, lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+// Commands and notifications
+
+// void OnCommandHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define COMMAND_HANDLER_EX(id, code, func) \
+ if (uMsg == WM_COMMAND && code == HIWORD(wParam) && id == LOWORD(wParam)) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCommandIDHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define COMMAND_ID_HANDLER_EX(id, func) \
+ if (uMsg == WM_COMMAND && id == LOWORD(wParam)) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCommandCodeHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define COMMAND_CODE_HANDLER_EX(code, func) \
+ if (uMsg == WM_COMMAND && code == HIWORD(wParam)) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnNotifyHandlerEX(LPNMHDR pnmh)
+#define NOTIFY_HANDLER_EX(id, cd, func) \
+ if (uMsg == WM_NOTIFY && cd == ((LPNMHDR)lParam)->code && id == ((LPNMHDR)lParam)->idFrom) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnNotifyIDHandlerEX(LPNMHDR pnmh)
+#define NOTIFY_ID_HANDLER_EX(id, func) \
+ if (uMsg == WM_NOTIFY && id == ((LPNMHDR)lParam)->idFrom) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnNotifyCodeHandlerEX(LPNMHDR pnmh)
+#define NOTIFY_CODE_HANDLER_EX(cd, func) \
+ if (uMsg == WM_NOTIFY && cd == ((LPNMHDR)lParam)->code) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCommandRangeHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define COMMAND_RANGE_HANDLER_EX(idFirst, idLast, func) \
+ if(uMsg == WM_COMMAND && LOWORD(wParam) >= idFirst && LOWORD(wParam) <= idLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnCommandRangeCodeHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define COMMAND_RANGE_CODE_HANDLER_EX(idFirst, idLast, code, func) \
+ if(uMsg == WM_COMMAND && code == HIWORD(wParam) && LOWORD(wParam) >= idFirst && LOWORD(wParam) <= idLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnNotifyRangeHandlerEX(LPNMHDR pnmh)
+#define NOTIFY_RANGE_HANDLER_EX(idFirst, idLast, func) \
+ if(uMsg == WM_NOTIFY && ((LPNMHDR)lParam)->idFrom >= idFirst && ((LPNMHDR)lParam)->idFrom <= idLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnNotifyRangeCodeHandlerEX(LPNMHDR pnmh)
+#define NOTIFY_RANGE_CODE_HANDLER_EX(idFirst, idLast, cd, func) \
+ if(uMsg == WM_NOTIFY && cd == ((LPNMHDR)lParam)->code && ((LPNMHDR)lParam)->idFrom >= idFirst && ((LPNMHDR)lParam)->idFrom <= idLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedCommandHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define REFLECTED_COMMAND_HANDLER_EX(id, code, func) \
+ if (uMsg == OCM_COMMAND && code == HIWORD(wParam) && id == LOWORD(wParam)) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedCommandIDHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define REFLECTED_COMMAND_ID_HANDLER_EX(id, func) \
+ if (uMsg == OCM_COMMAND && id == LOWORD(wParam)) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedCommandCodeHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define REFLECTED_COMMAND_CODE_HANDLER_EX(code, func) \
+ if (uMsg == OCM_COMMAND && code == HIWORD(wParam)) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedNotifyHandlerEX(LPNMHDR pnmh)
+#define REFLECTED_NOTIFY_HANDLER_EX(id, cd, func) \
+ if (uMsg == OCM_NOTIFY && cd == ((LPNMHDR)lParam)->code && id == ((LPNMHDR)lParam)->idFrom) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedNotifyIDHandlerEX(LPNMHDR pnmh)
+#define REFLECTED_NOTIFY_ID_HANDLER_EX(id, func) \
+ if (uMsg == OCM_NOTIFY && id == ((LPNMHDR)lParam)->idFrom) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedNotifyCodeHandlerEX(LPNMHDR pnmh)
+#define REFLECTED_NOTIFY_CODE_HANDLER_EX(cd, func) \
+ if (uMsg == OCM_NOTIFY && cd == ((LPNMHDR)lParam)->code) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnReflectedCommandRangeHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define REFLECTED_COMMAND_RANGE_HANDLER_EX(idFirst, idLast, func) \
+ if(uMsg == OCM_COMMAND && LOWORD(wParam) >= idFirst && LOWORD(wParam) <= idLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// void OnReflectedCommandRangeCodeHandlerEX(UINT uNotifyCode, int nID, CWindow wndCtl)
+#define REFLECTED_COMMAND_RANGE_CODE_HANDLER_EX(idFirst, idLast, code, func) \
+ if(uMsg == OCM_COMMAND && code == HIWORD(wParam) && LOWORD(wParam) >= idFirst && LOWORD(wParam) <= idLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ func((UINT)HIWORD(wParam), (int)LOWORD(wParam), (HWND)lParam); \
+ lResult = 0; \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedNotifyRangeHandlerEX(LPNMHDR pnmh)
+#define REFLECTED_NOTIFY_RANGE_HANDLER_EX(idFirst, idLast, func) \
+ if(uMsg == OCM_NOTIFY && ((LPNMHDR)lParam)->idFrom >= idFirst && ((LPNMHDR)lParam)->idFrom <= idLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+// LRESULT OnReflectedNotifyRangeCodeHandlerEX(LPNMHDR pnmh)
+#define REFLECTED_NOTIFY_RANGE_CODE_HANDLER_EX(idFirst, idLast, cd, func) \
+ if(uMsg == OCM_NOTIFY && cd == ((LPNMHDR)lParam)->code && ((LPNMHDR)lParam)->idFrom >= idFirst && ((LPNMHDR)lParam)->idFrom <= idLast) \
+ { \
+ SetMsgHandled(TRUE); \
+ lResult = func((LPNMHDR)lParam); \
+ if(IsMsgHandled()) \
+ return TRUE; \
+ }
+
+#endif // __ATLCRACK_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlctrls.h b/plugins/SmartAutoReplier/wtl/atlctrls.h
new file mode 100644
index 0000000000..00df403181
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlctrls.h
@@ -0,0 +1,10041 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLCTRLS_H__
+#define __ATLCTRLS_H__
+
+#pragma once
+
+#include <commctrl.h>
+
+#ifndef __ATLAPP_H__
+ #error atlctrls.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atlctrls.h requires atlwin.h to be included first
+#endif
+
+#ifndef _WIN32_WCE
+ #include <richedit.h>
+ #include <richole.h>
+#elif defined(WIN32_PLATFORM_WFSP) && !defined(_WINUSERM_H_)
+ #include <winuserm.h>
+#endif // !_WIN32_WCE
+
+// protect template members from windowsx.h macros
+#ifdef _INC_WINDOWSX
+ #undef GetNextSibling
+ #undef GetPrevSibling
+#endif // _INC_WINDOWSX
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CStaticT<TBase> - CStatic
+// CButtonT<TBase> - CButton
+// CListBoxT<TBase> - CListBox
+// CComboBoxT<TBase> - CComboBox
+// CEditT<TBase> - CEdit
+// CEditCommands<T>
+// CScrollBarT<TBase> - CScrollBar
+//
+// CImageList
+// CListViewCtrlT<TBase> - CListViewCtrl
+// CTreeViewCtrlT<TBase> - CTreeViewCtrl
+// CTreeItemT<TBase> - CTreeItem
+// CTreeViewCtrlExT<TBase> - CTreeViewCtrlEx
+// CHeaderCtrlT<TBase> - CHeaderCtrl
+// CToolBarCtrlT<TBase> - CToolBarCtrl
+// CStatusBarCtrlT<TBase> - CStatusBarCtrl
+// CTabCtrlT<TBase> - CTabCtrl
+// CToolInfo
+// CToolTipCtrlT<TBase> - CToolTipCtrl
+// CTrackBarCtrlT<TBase> - CTrackBarCtrl
+// CUpDownCtrlT<TBase> - CUpDownCtrl
+// CProgressBarCtrlT<TBase> - CProgressBarCtrl
+// CHotKeyCtrlT<TBase> - CHotKeyCtrl
+// CAnimateCtrlT<TBase> - CAnimateCtrl
+// CRichEditCtrlT<TBase> - CRichEditCtrl
+// CRichEditCommands<T>
+// CDragListBoxT<TBase> - CDragListBox
+// CDragListNotifyImpl<T>
+// CReBarCtrlT<TBase> - CReBarCtrl
+// CComboBoxExT<TBase> - CComboBoxEx
+// CDateTimePickerCtrlT<TBase> - CDateTimePickerCtrl
+// CMonthCalendarCtrlT<TBase> - CMonthCalendarCtrl
+// CFlatScrollBarImpl<T>
+// CFlatScrollBarT<TBase> - CFlatScrollBar
+// CIPAddressCtrlT<TBase> - CIPAddressCtrl
+// CPagerCtrlT<TBase> - CPagerCtrl
+// CLinkCtrlT<TBase> - CLinkCtrl
+//
+// CCustomDraw<T>
+//
+// CCECommandBarCtrlT<TBase> - CCECommandBarCtrl
+// CCECommandBandsCtrlT<TBase> - CCECommandBandsCtrl
+
+
+namespace WTL
+{
+
+// These are wrapper classes for Windows standard and common controls.
+// To implement a window based on a control, use following:
+// Example: Implementing a window based on a list box
+//
+// class CMyListBox : CWindowImpl<CMyListBox, CListBox>
+// {
+// public:
+// BEGIN_MSG_MAP(CMyListBox)
+// // put your message handler entries here
+// END_MSG_MAP()
+// };
+
+
+
+// --- Standard Windows controls ---
+
+///////////////////////////////////////////////////////////////////////////////
+// CStatic - client side for a Windows STATIC control
+
+template <class TBase>
+class CStaticT : public TBase
+{
+public:
+// Constructors
+ CStaticT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CStaticT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return _T("STATIC");
+ }
+
+#ifndef _WIN32_WCE
+ HICON GetIcon() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HICON)::SendMessage(m_hWnd, STM_GETICON, 0, 0L);
+ }
+
+ HICON SetIcon(HICON hIcon)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HICON)::SendMessage(m_hWnd, STM_SETICON, (WPARAM)hIcon, 0L);
+ }
+
+ HENHMETAFILE GetEnhMetaFile() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HENHMETAFILE)::SendMessage(m_hWnd, STM_GETIMAGE, IMAGE_ENHMETAFILE, 0L);
+ }
+
+ HENHMETAFILE SetEnhMetaFile(HENHMETAFILE hMetaFile)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HENHMETAFILE)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_ENHMETAFILE, (LPARAM)hMetaFile);
+ }
+#else // CE specific
+ HICON GetIcon() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HICON)::SendMessage(m_hWnd, STM_GETIMAGE, IMAGE_ICON, 0L);
+ }
+
+ HICON SetIcon(HICON hIcon)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HICON)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ }
+#endif // _WIN32_WCE
+
+ CBitmapHandle GetBitmap() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CBitmapHandle((HBITMAP)::SendMessage(m_hWnd, STM_GETIMAGE, IMAGE_BITMAP, 0L));
+ }
+
+ CBitmapHandle SetBitmap(HBITMAP hBitmap)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CBitmapHandle((HBITMAP)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap));
+ }
+
+ HCURSOR GetCursor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HCURSOR)::SendMessage(m_hWnd, STM_GETIMAGE, IMAGE_CURSOR, 0L);
+ }
+
+ HCURSOR SetCursor(HCURSOR hCursor)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HCURSOR)::SendMessage(m_hWnd, STM_SETIMAGE, IMAGE_CURSOR, (LPARAM)hCursor);
+ }
+};
+
+typedef CStaticT<ATL::CWindow> CStatic;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CButton - client side for a Windows BUTTON control
+
+template <class TBase>
+class CButtonT : public TBase
+{
+public:
+// Constructors
+ CButtonT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CButtonT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return _T("BUTTON");
+ }
+
+ UINT GetState() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, BM_GETSTATE, 0, 0L);
+ }
+
+ void SetState(BOOL bHighlight)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, BM_SETSTATE, bHighlight, 0L);
+ }
+
+ int GetCheck() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, BM_GETCHECK, 0, 0L);
+ }
+
+ void SetCheck(int nCheck)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, BM_SETCHECK, nCheck, 0L);
+ }
+
+ UINT GetButtonStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::GetWindowLong(m_hWnd, GWL_STYLE) & 0xFFFF;
+ }
+
+ void SetButtonStyle(UINT nStyle, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, BM_SETSTYLE, nStyle, (LPARAM)bRedraw);
+ }
+
+#ifndef _WIN32_WCE
+ HICON GetIcon() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HICON)::SendMessage(m_hWnd, BM_GETIMAGE, IMAGE_ICON, 0L);
+ }
+
+ HICON SetIcon(HICON hIcon)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HICON)::SendMessage(m_hWnd, BM_SETIMAGE, IMAGE_ICON, (LPARAM)hIcon);
+ }
+
+ CBitmapHandle GetBitmap() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CBitmapHandle((HBITMAP)::SendMessage(m_hWnd, BM_GETIMAGE, IMAGE_BITMAP, 0L));
+ }
+
+ CBitmapHandle SetBitmap(HBITMAP hBitmap)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CBitmapHandle((HBITMAP)::SendMessage(m_hWnd, BM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap));
+ }
+#endif // !_WIN32_WCE
+
+#if (_WIN32_WINNT >= 0x0501)
+ BOOL GetIdealSize(LPSIZE lpSize) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, BCM_GETIDEALSIZE, 0, (LPARAM)lpSize);
+ }
+
+ BOOL GetImageList(PBUTTON_IMAGELIST pButtonImagelist) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, BCM_GETIMAGELIST, 0, (LPARAM)pButtonImagelist);
+ }
+
+ BOOL SetImageList(PBUTTON_IMAGELIST pButtonImagelist)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, BCM_SETIMAGELIST, 0, (LPARAM)pButtonImagelist);
+ }
+
+ BOOL GetTextMargin(LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, BCM_GETTEXTMARGIN, 0, (LPARAM)lpRect);
+ }
+
+ BOOL SetTextMargin(LPRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, BCM_SETTEXTMARGIN, 0, (LPARAM)lpRect);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+#if (WINVER >= 0x0600)
+ void SetDontClick(BOOL bDontClick)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, BM_SETDONTCLICK, (WPARAM)bDontClick, 0L);
+ }
+#endif // (WINVER >= 0x0600)
+
+#if (_WIN32_WINNT >= 0x0600)
+ BOOL SetDropDownState(BOOL bDropDown)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (BS_SPLITBUTTON | BS_DEFSPLITBUTTON)) != 0);
+ return (BOOL)::SendMessage(m_hWnd, BCM_SETDROPDOWNSTATE, (WPARAM)bDropDown, 0L);
+ }
+
+ BOOL GetSplitInfo(PBUTTON_SPLITINFO pSplitInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (BS_SPLITBUTTON | BS_DEFSPLITBUTTON)) != 0);
+ return (BOOL)::SendMessage(m_hWnd, BCM_GETSPLITINFO, 0, (LPARAM)pSplitInfo);
+ }
+
+ BOOL SetSplitInfo(PBUTTON_SPLITINFO pSplitInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (BS_SPLITBUTTON | BS_DEFSPLITBUTTON)) != 0);
+ return (BOOL)::SendMessage(m_hWnd, BCM_SETSPLITINFO, 0, (LPARAM)pSplitInfo);
+ }
+
+ int GetNoteLength() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (BS_COMMANDLINK | BS_DEFCOMMANDLINK)) != 0);
+ return (int)::SendMessage(m_hWnd, BCM_GETNOTELENGTH, 0, 0L);
+ }
+
+ BOOL GetNote(LPWSTR lpstrNoteText, int cchNoteText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (BS_COMMANDLINK | BS_DEFCOMMANDLINK)) != 0);
+ return (BOOL)::SendMessage(m_hWnd, BCM_GETNOTE, cchNoteText, (LPARAM)lpstrNoteText);
+ }
+
+ BOOL SetNote(LPCWSTR lpstrNoteText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (BS_COMMANDLINK | BS_DEFCOMMANDLINK)) != 0);
+ return (BOOL)::SendMessage(m_hWnd, BCM_SETNOTE, 0, (LPARAM)lpstrNoteText);
+ }
+
+ LRESULT SetElevationRequiredState(BOOL bSet)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::SendMessage(m_hWnd, BCM_SETSHIELD, 0, (LPARAM)bSet);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+// Operations
+ void Click()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, BM_CLICK, 0, 0L);
+ }
+};
+
+typedef CButtonT<ATL::CWindow> CButton;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CListBox - client side for a Windows LISTBOX control
+
+template <class TBase>
+class CListBoxT : public TBase
+{
+public:
+// Constructors
+ CListBoxT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CListBoxT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return _T("LISTBOX");
+ }
+
+ // for entire listbox
+ int GetCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETCOUNT, 0, 0L);
+ }
+
+#ifndef _WIN32_WCE
+ int SetCount(int cItems)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(((GetStyle() & LBS_NODATA) != 0) && ((GetStyle() & LBS_HASSTRINGS) == 0));
+ return (int)::SendMessage(m_hWnd, LB_SETCOUNT, cItems, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ int GetHorizontalExtent() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETHORIZONTALEXTENT, 0, 0L);
+ }
+
+ void SetHorizontalExtent(int cxExtent)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LB_SETHORIZONTALEXTENT, cxExtent, 0L);
+ }
+
+ int GetTopIndex() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETTOPINDEX, 0, 0L);
+ }
+
+ int SetTopIndex(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_SETTOPINDEX, nIndex, 0L);
+ }
+
+ LCID GetLocale() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LCID)::SendMessage(m_hWnd, LB_GETLOCALE, 0, 0L);
+ }
+
+ LCID SetLocale(LCID nNewLocale)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LCID)::SendMessage(m_hWnd, LB_SETLOCALE, (WPARAM)nNewLocale, 0L);
+ }
+
+#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ DWORD GetListBoxInfo() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+#if (_WIN32_WINNT >= 0x0501)
+ return (DWORD)::SendMessage(m_hWnd, LB_GETLISTBOXINFO, 0, 0L);
+#else // !(_WIN32_WINNT >= 0x0501)
+ return ::GetListBoxInfo(m_hWnd);
+#endif // !(_WIN32_WINNT >= 0x0501)
+ }
+#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+
+ // for single-selection listboxes
+ int GetCurSel() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) == 0);
+ return (int)::SendMessage(m_hWnd, LB_GETCURSEL, 0, 0L);
+ }
+
+ int SetCurSel(int nSelect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) == 0);
+ return (int)::SendMessage(m_hWnd, LB_SETCURSEL, nSelect, 0L);
+ }
+
+ // for multiple-selection listboxes
+ int GetSel(int nIndex) const // also works for single-selection
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETSEL, nIndex, 0L);
+ }
+
+ int SetSel(int nIndex, BOOL bSelect = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) != 0);
+ return (int)::SendMessage(m_hWnd, LB_SETSEL, bSelect, nIndex);
+ }
+
+ int GetSelCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) != 0);
+ return (int)::SendMessage(m_hWnd, LB_GETSELCOUNT, 0, 0L);
+ }
+
+ int GetSelItems(int nMaxItems, LPINT rgIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) != 0);
+ return (int)::SendMessage(m_hWnd, LB_GETSELITEMS, nMaxItems, (LPARAM)rgIndex);
+ }
+
+ int GetAnchorIndex() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) != 0);
+ return (int)::SendMessage(m_hWnd, LB_GETANCHORINDEX, 0, 0L);
+ }
+
+ void SetAnchorIndex(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) != 0);
+ ::SendMessage(m_hWnd, LB_SETANCHORINDEX, nIndex, 0L);
+ }
+
+ int GetCaretIndex() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETCARETINDEX, 0, 0);
+ }
+
+ int SetCaretIndex(int nIndex, BOOL bScroll = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_SETCARETINDEX, nIndex, MAKELONG(bScroll, 0));
+ }
+
+ // for listbox items
+ DWORD_PTR GetItemData(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD_PTR)::SendMessage(m_hWnd, LB_GETITEMDATA, nIndex, 0L);
+ }
+
+ int SetItemData(int nIndex, DWORD_PTR dwItemData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_SETITEMDATA, nIndex, (LPARAM)dwItemData);
+ }
+
+ void* GetItemDataPtr(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (void*)::SendMessage(m_hWnd, LB_GETITEMDATA, nIndex, 0L);
+ }
+
+ int SetItemDataPtr(int nIndex, void* pData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItemData(nIndex, (DWORD_PTR)pData);
+ }
+
+ int GetItemRect(int nIndex, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETITEMRECT, nIndex, (LPARAM)lpRect);
+ }
+
+ int GetText(int nIndex, LPTSTR lpszBuffer) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETTEXT, nIndex, (LPARAM)lpszBuffer);
+ }
+
+#ifndef _ATL_NO_COM
+#ifdef _OLEAUTO_H_
+ BOOL GetTextBSTR(int nIndex, BSTR& bstrText) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(bstrText == NULL);
+
+ int nLen = GetTextLen(nIndex);
+ if(nLen == LB_ERR)
+ return FALSE;
+
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrText = buff.Allocate(nLen + 1);
+ if(lpstrText == NULL)
+ return FALSE;
+
+ if(GetText(nIndex, lpstrText) == LB_ERR)
+ return FALSE;
+
+ bstrText = ::SysAllocString(T2OLE(lpstrText));
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+#endif // _OLEAUTO_H_
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ int GetText(int nIndex, _CSTRING_NS::CString& strText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int cchLen = GetTextLen(nIndex);
+ if(cchLen == LB_ERR)
+ return LB_ERR;
+ int nRet = LB_ERR;
+ LPTSTR lpstr = strText.GetBufferSetLength(cchLen);
+ if(lpstr != NULL)
+ {
+ nRet = GetText(nIndex, lpstr);
+ strText.ReleaseBuffer();
+ }
+ return nRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ int GetTextLen(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETTEXTLEN, nIndex, 0L);
+ }
+
+ int GetItemHeight(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_GETITEMHEIGHT, nIndex, 0L);
+ }
+
+ int SetItemHeight(int nIndex, UINT cyItemHeight)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_SETITEMHEIGHT, nIndex, MAKELONG(cyItemHeight, 0));
+ }
+
+ // Settable only attributes
+ void SetColumnWidth(int cxWidth)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LB_SETCOLUMNWIDTH, cxWidth, 0L);
+ }
+
+ BOOL SetTabStops(int nTabStops, LPINT rgTabStops)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & LBS_USETABSTOPS) != 0);
+ return (BOOL)::SendMessage(m_hWnd, LB_SETTABSTOPS, nTabStops, (LPARAM)rgTabStops);
+ }
+
+ BOOL SetTabStops()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & LBS_USETABSTOPS) != 0);
+ return (BOOL)::SendMessage(m_hWnd, LB_SETTABSTOPS, 0, 0L);
+ }
+
+ BOOL SetTabStops(const int& cxEachStop) // takes an 'int'
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & LBS_USETABSTOPS) != 0);
+ return (BOOL)::SendMessage(m_hWnd, LB_SETTABSTOPS, 1, (LPARAM)(LPINT)&cxEachStop);
+ }
+
+// Operations
+ int InitStorage(int nItems, UINT nBytes)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_INITSTORAGE, (WPARAM)nItems, nBytes);
+ }
+
+ void ResetContent()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LB_RESETCONTENT, 0, 0L);
+ }
+
+ UINT ItemFromPoint(POINT pt, BOOL& bOutside) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dw = (DWORD)::SendMessage(m_hWnd, LB_ITEMFROMPOINT, 0, MAKELPARAM(pt.x, pt.y));
+ bOutside = (BOOL)HIWORD(dw);
+ return (UINT)LOWORD(dw);
+ }
+
+ // manipulating listbox items
+ int AddString(LPCTSTR lpszItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_ADDSTRING, 0, (LPARAM)lpszItem);
+ }
+
+ int DeleteString(UINT nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_DELETESTRING, nIndex, 0L);
+ }
+
+ int InsertString(int nIndex, LPCTSTR lpszItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_INSERTSTRING, nIndex, (LPARAM)lpszItem);
+ }
+
+#ifndef _WIN32_WCE
+ int Dir(UINT attr, LPCTSTR lpszWildCard)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_DIR, attr, (LPARAM)lpszWildCard);
+ }
+
+ int AddFile(LPCTSTR lpstrFileName)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_ADDFILE, 0, (LPARAM)lpstrFileName);
+ }
+#endif // !_WIN32_WCE
+
+ // selection helpers
+ int FindString(int nStartAfter, LPCTSTR lpszItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_FINDSTRING, nStartAfter, (LPARAM)lpszItem);
+ }
+
+ int FindStringExact(int nIndexStart, LPCTSTR lpszFind) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_FINDSTRINGEXACT, nIndexStart, (LPARAM)lpszFind);
+ }
+
+ int SelectString(int nStartAfter, LPCTSTR lpszItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LB_SELECTSTRING, nStartAfter, (LPARAM)lpszItem);
+ }
+
+ int SelItemRange(BOOL bSelect, int nFirstItem, int nLastItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) != 0);
+ ATLASSERT(nFirstItem <= nLastItem);
+ return bSelect ? (int)::SendMessage(m_hWnd, LB_SELITEMRANGEEX, nFirstItem, nLastItem) : (int)::SendMessage(m_hWnd, LB_SELITEMRANGEEX, nLastItem, nFirstItem);
+ }
+
+#ifdef WIN32_PLATFORM_WFSP // SmartPhone only messages
+ DWORD GetInputMode(BOOL bCurrentMode = TRUE)
+ {
+ return SendMessage(LB_GETINPUTMODE, 0, (LPARAM)bCurrentMode);
+ }
+
+ BOOL SetInputMode(DWORD dwMode)
+ {
+ return SendMessage(LB_SETINPUTMODE, 0, (LPARAM)dwMode);
+ }
+#endif // WIN32_PLATFORM_WFSP
+};
+
+typedef CListBoxT<ATL::CWindow> CListBox;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CComboBox - client side for a Windows COMBOBOX control
+
+#ifndef WIN32_PLATFORM_WFSP // No COMBOBOX on SmartPhones
+
+template <class TBase>
+class CComboBoxT : public TBase
+{
+public:
+// Constructors
+ CComboBoxT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CComboBoxT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return _T("COMBOBOX");
+ }
+
+ // for entire combo box
+ int GetCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_GETCOUNT, 0, 0L);
+ }
+
+ int GetCurSel() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_GETCURSEL, 0, 0L);
+ }
+
+ int SetCurSel(int nSelect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_SETCURSEL, nSelect, 0L);
+ }
+
+ LCID GetLocale() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LCID)::SendMessage(m_hWnd, CB_GETLOCALE, 0, 0L);
+ }
+
+ LCID SetLocale(LCID nNewLocale)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LCID)::SendMessage(m_hWnd, CB_SETLOCALE, (WPARAM)nNewLocale, 0L);
+ }
+
+ int GetTopIndex() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_GETTOPINDEX, 0, 0L);
+ }
+
+ int SetTopIndex(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_SETTOPINDEX, nIndex, 0L);
+ }
+
+ UINT GetHorizontalExtent() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, CB_GETHORIZONTALEXTENT, 0, 0L);
+ }
+
+ void SetHorizontalExtent(UINT nExtent)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, CB_SETHORIZONTALEXTENT, nExtent, 0L);
+ }
+
+ int GetDroppedWidth() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_GETDROPPEDWIDTH, 0, 0L);
+ }
+
+ int SetDroppedWidth(UINT nWidth)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_SETDROPPEDWIDTH, nWidth, 0L);
+ }
+
+#if ((WINVER >= 0x0500) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420))
+ BOOL GetComboBoxInfo(PCOMBOBOXINFO pComboBoxInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+#if ((_WIN32_WINNT >= 0x0501) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420))
+ return (BOOL)::SendMessage(m_hWnd, CB_GETCOMBOBOXINFO, 0, (LPARAM)pComboBoxInfo);
+#else // !((_WIN32_WINNT >= 0x0501) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420))
+ return ::GetComboBoxInfo(m_hWnd, pComboBoxInfo);
+#endif // !((_WIN32_WINNT >= 0x0501) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420))
+ }
+#endif // ((WINVER >= 0x0500) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 420))
+
+ // for edit control
+ DWORD GetEditSel() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, CB_GETEDITSEL, 0, 0L);
+ }
+
+ BOOL SetEditSel(int nStartChar, int nEndChar)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CB_SETEDITSEL, 0, MAKELONG(nStartChar, nEndChar));
+ }
+
+ // for combobox item
+ DWORD_PTR GetItemData(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD_PTR)::SendMessage(m_hWnd, CB_GETITEMDATA, nIndex, 0L);
+ }
+
+ int SetItemData(int nIndex, DWORD_PTR dwItemData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_SETITEMDATA, nIndex, (LPARAM)dwItemData);
+ }
+
+ void* GetItemDataPtr(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (void*)GetItemData(nIndex);
+ }
+
+ int SetItemDataPtr(int nIndex, void* pData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItemData(nIndex, (DWORD_PTR)pData);
+ }
+
+ int GetLBText(int nIndex, LPTSTR lpszText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_GETLBTEXT, nIndex, (LPARAM)lpszText);
+ }
+
+#ifndef _ATL_NO_COM
+ BOOL GetLBTextBSTR(int nIndex, BSTR& bstrText) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(bstrText == NULL);
+
+ int nLen = GetLBTextLen(nIndex);
+ if(nLen == CB_ERR)
+ return FALSE;
+
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrText = buff.Allocate(nLen + 1);
+ if(lpstrText == NULL)
+ return FALSE;
+
+ if(GetLBText(nIndex, lpstrText) == CB_ERR)
+ return FALSE;
+
+ bstrText = ::SysAllocString(T2OLE(lpstrText));
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ int GetLBText(int nIndex, _CSTRING_NS::CString& strText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int cchLen = GetLBTextLen(nIndex);
+ if(cchLen == CB_ERR)
+ return CB_ERR;
+ int nRet = CB_ERR;
+ LPTSTR lpstr = strText.GetBufferSetLength(cchLen);
+ if(lpstr != NULL)
+ {
+ nRet = GetLBText(nIndex, lpstr);
+ strText.ReleaseBuffer();
+ }
+ return nRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ int GetLBTextLen(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_GETLBTEXTLEN, nIndex, 0L);
+ }
+
+ int GetItemHeight(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_GETITEMHEIGHT, nIndex, 0L);
+ }
+
+ int SetItemHeight(int nIndex, UINT cyItemHeight)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_SETITEMHEIGHT, nIndex, MAKELONG(cyItemHeight, 0));
+ }
+
+ BOOL GetExtendedUI() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CB_GETEXTENDEDUI, 0, 0L);
+ }
+
+ int SetExtendedUI(BOOL bExtended = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_SETEXTENDEDUI, bExtended, 0L);
+ }
+
+ void GetDroppedControlRect(LPRECT lprect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, CB_GETDROPPEDCONTROLRECT, 0, (LPARAM)lprect);
+ }
+
+ BOOL GetDroppedState() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CB_GETDROPPEDSTATE, 0, 0L);
+ }
+
+#if (_WIN32_WINNT >= 0x0501)
+ int GetMinVisible() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_GETMINVISIBLE, 0, 0L);
+ }
+
+ BOOL SetMinVisible(int nMinVisible)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CB_SETMINVISIBLE, nMinVisible, 0L);
+ }
+
+ // Vista only
+ BOOL GetCueBannerText(LPWSTR lpwText, int cchText) const
+ {
+#ifndef CB_GETCUEBANNER
+ const UINT CB_GETCUEBANNER = (CBM_FIRST + 4);
+#endif
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CB_GETCUEBANNER, (WPARAM)lpwText, cchText);
+ }
+
+ // Vista only
+ BOOL SetCueBannerText(LPCWSTR lpcwText)
+ {
+#ifndef CB_SETCUEBANNER
+ const UINT CB_SETCUEBANNER = (CBM_FIRST + 3);
+#endif
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CB_SETCUEBANNER, 0, (LPARAM)lpcwText);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+// Operations
+ int InitStorage(int nItems, UINT nBytes)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_INITSTORAGE, (WPARAM)nItems, nBytes);
+ }
+
+ void ResetContent()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, CB_RESETCONTENT, 0, 0L);
+ }
+
+ // for edit control
+ BOOL LimitText(int nMaxChars)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CB_LIMITTEXT, nMaxChars, 0L);
+ }
+
+ // for drop-down combo boxes
+ void ShowDropDown(BOOL bShowIt = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, CB_SHOWDROPDOWN, bShowIt, 0L);
+ }
+
+ // manipulating listbox items
+ int AddString(LPCTSTR lpszString)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_ADDSTRING, 0, (LPARAM)lpszString);
+ }
+
+ int DeleteString(UINT nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_DELETESTRING, nIndex, 0L);
+ }
+
+ int InsertString(int nIndex, LPCTSTR lpszString)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_INSERTSTRING, nIndex, (LPARAM)lpszString);
+ }
+
+#ifndef _WIN32_WCE
+ int Dir(UINT attr, LPCTSTR lpszWildCard)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_DIR, attr, (LPARAM)lpszWildCard);
+ }
+#endif // !_WIN32_WCE
+
+ // selection helpers
+ int FindString(int nStartAfter, LPCTSTR lpszString) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_FINDSTRING, nStartAfter, (LPARAM)lpszString);
+ }
+
+ int FindStringExact(int nIndexStart, LPCTSTR lpszFind) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_FINDSTRINGEXACT, nIndexStart, (LPARAM)lpszFind);
+ }
+
+ int SelectString(int nStartAfter, LPCTSTR lpszString)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CB_SELECTSTRING, nStartAfter, (LPARAM)lpszString);
+ }
+
+ // Clipboard operations
+ void Clear()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_CLEAR, 0, 0L);
+ }
+
+ void Copy()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_COPY, 0, 0L);
+ }
+
+ void Cut()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_CUT, 0, 0L);
+ }
+
+ void Paste()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_PASTE, 0, 0L);
+ }
+};
+
+typedef CComboBoxT<ATL::CWindow> CComboBox;
+
+#endif // !WIN32_PLATFORM_WFSP
+
+///////////////////////////////////////////////////////////////////////////////
+// CEdit - client side for a Windows EDIT control
+
+template <class TBase>
+class CEditT : public TBase
+{
+public:
+// Constructors
+ CEditT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CEditT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return _T("EDIT");
+ }
+
+ BOOL CanUndo() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_CANUNDO, 0, 0L);
+ }
+
+ int GetLineCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETLINECOUNT, 0, 0L);
+ }
+
+ BOOL GetModify() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_GETMODIFY, 0, 0L);
+ }
+
+ void SetModify(BOOL bModified = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETMODIFY, bModified, 0L);
+ }
+
+ void GetRect(LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_GETRECT, 0, (LPARAM)lpRect);
+ }
+
+ DWORD GetSel() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, EM_GETSEL, 0, 0L);
+ }
+
+ void GetSel(int& nStartChar, int& nEndChar) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_GETSEL, (WPARAM)&nStartChar, (LPARAM)&nEndChar);
+ }
+
+#ifndef _WIN32_WCE
+ HLOCAL GetHandle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HLOCAL)::SendMessage(m_hWnd, EM_GETHANDLE, 0, 0L);
+ }
+
+ void SetHandle(HLOCAL hBuffer)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETHANDLE, (WPARAM)hBuffer, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ DWORD GetMargins() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, EM_GETMARGINS, 0, 0L);
+ }
+
+ void SetMargins(UINT nLeft, UINT nRight)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETMARGINS, EC_LEFTMARGIN|EC_RIGHTMARGIN, MAKELONG(nLeft, nRight));
+ }
+
+ UINT GetLimitText() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_GETLIMITTEXT, 0, 0L);
+ }
+
+ void SetLimitText(UINT nMax)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETLIMITTEXT, nMax, 0L);
+ }
+
+ POINT PosFromChar(UINT nChar) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, EM_POSFROMCHAR, nChar, 0);
+ POINT point = { GET_X_LPARAM(dwRet), GET_Y_LPARAM(dwRet) };
+ return point;
+ }
+
+ int CharFromPos(POINT pt, int* pLine = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, EM_CHARFROMPOS, 0, MAKELPARAM(pt.x, pt.y));
+ if(pLine != NULL)
+ *pLine = (int)(short)HIWORD(dwRet);
+ return (int)(short)LOWORD(dwRet);
+ }
+
+ // NOTE: first word in lpszBuffer must contain the size of the buffer!
+ int GetLine(int nIndex, LPTSTR lpszBuffer) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETLINE, nIndex, (LPARAM)lpszBuffer);
+ }
+
+ int GetLine(int nIndex, LPTSTR lpszBuffer, int nMaxLength) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ *(LPWORD)lpszBuffer = (WORD)nMaxLength;
+ return (int)::SendMessage(m_hWnd, EM_GETLINE, nIndex, (LPARAM)lpszBuffer);
+ }
+
+ TCHAR GetPasswordChar() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (TCHAR)::SendMessage(m_hWnd, EM_GETPASSWORDCHAR, 0, 0L);
+ }
+
+ void SetPasswordChar(TCHAR ch)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETPASSWORDCHAR, ch, 0L);
+ }
+
+#ifndef _WIN32_WCE
+ EDITWORDBREAKPROC GetWordBreakProc() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (EDITWORDBREAKPROC)::SendMessage(m_hWnd, EM_GETWORDBREAKPROC, 0, 0L);
+ }
+
+ void SetWordBreakProc(EDITWORDBREAKPROC ewbprc)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETWORDBREAKPROC, 0, (LPARAM)ewbprc);
+ }
+#endif // !_WIN32_WCE
+
+ int GetFirstVisibleLine() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETFIRSTVISIBLELINE, 0, 0L);
+ }
+
+#ifndef _WIN32_WCE
+ int GetThumb() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & ES_MULTILINE) != 0);
+ return (int)::SendMessage(m_hWnd, EM_GETTHUMB, 0, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL SetReadOnly(BOOL bReadOnly = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETREADONLY, bReadOnly, 0L);
+ }
+
+#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ UINT GetImeStatus(UINT uStatus) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_GETIMESTATUS, uStatus, 0L);
+ }
+
+ UINT SetImeStatus(UINT uStatus, UINT uData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_SETIMESTATUS, uStatus, uData);
+ }
+#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+
+#if (_WIN32_WINNT >= 0x0501)
+ BOOL GetCueBannerText(LPCWSTR lpstrText, int cchText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_GETCUEBANNER, (WPARAM)lpstrText, cchText);
+ }
+
+ // bKeepWithFocus - Vista only
+ BOOL SetCueBannerText(LPCWSTR lpstrText, BOOL bKeepWithFocus = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCUEBANNER, (WPARAM)bKeepWithFocus, (LPARAM)(lpstrText));
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+// Operations
+ void EmptyUndoBuffer()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_EMPTYUNDOBUFFER, 0, 0L);
+ }
+
+ BOOL FmtLines(BOOL bAddEOL)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_FMTLINES, bAddEOL, 0L);
+ }
+
+ void LimitText(int nChars = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_LIMITTEXT, nChars, 0L);
+ }
+
+ int LineFromChar(int nIndex = -1) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_LINEFROMCHAR, nIndex, 0L);
+ }
+
+ int LineIndex(int nLine = -1) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_LINEINDEX, nLine, 0L);
+ }
+
+ int LineLength(int nLine = -1) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_LINELENGTH, nLine, 0L);
+ }
+
+ void LineScroll(int nLines, int nChars = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_LINESCROLL, nChars, nLines);
+ }
+
+ void ReplaceSel(LPCTSTR lpszNewText, BOOL bCanUndo = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_REPLACESEL, (WPARAM) bCanUndo, (LPARAM)lpszNewText);
+ }
+
+ void SetRect(LPCRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETRECT, 0, (LPARAM)lpRect);
+ }
+
+ void SetRectNP(LPCRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETRECTNP, 0, (LPARAM)lpRect);
+ }
+
+ void SetSel(DWORD dwSelection, BOOL bNoScroll = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETSEL, LOWORD(dwSelection), HIWORD(dwSelection));
+ if(!bNoScroll)
+ ::SendMessage(m_hWnd, EM_SCROLLCARET, 0, 0L);
+ }
+
+ void SetSel(int nStartChar, int nEndChar, BOOL bNoScroll = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETSEL, nStartChar, nEndChar);
+ if(!bNoScroll)
+ ::SendMessage(m_hWnd, EM_SCROLLCARET, 0, 0L);
+ }
+
+ void SetSelAll(BOOL bNoScroll = FALSE)
+ {
+ SetSel(0, -1, bNoScroll);
+ }
+
+ void SetSelNone(BOOL bNoScroll = FALSE)
+ {
+ SetSel(-1, 0, bNoScroll);
+ }
+
+ BOOL SetTabStops(int nTabStops, LPINT rgTabStops)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETTABSTOPS, nTabStops, (LPARAM)rgTabStops);
+ }
+
+ BOOL SetTabStops()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETTABSTOPS, 0, 0L);
+ }
+
+ BOOL SetTabStops(const int& cxEachStop) // takes an 'int'
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETTABSTOPS, 1, (LPARAM)(LPINT)&cxEachStop);
+ }
+
+ void ScrollCaret()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SCROLLCARET, 0, 0L);
+ }
+
+ int Scroll(int nScrollAction)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & ES_MULTILINE) != 0);
+ LRESULT lRet = ::SendMessage(m_hWnd, EM_SCROLL, nScrollAction, 0L);
+ if(!(BOOL)HIWORD(lRet))
+ return -1; // failed
+ return (int)(short)LOWORD(lRet);
+
+ }
+
+ void InsertText(int nInsertAfterChar, LPCTSTR lpstrText, BOOL bNoScroll = FALSE, BOOL bCanUndo = FALSE)
+ {
+ SetSel(nInsertAfterChar, nInsertAfterChar, bNoScroll);
+ ReplaceSel(lpstrText, bCanUndo);
+ }
+
+ void AppendText(LPCTSTR lpstrText, BOOL bNoScroll = FALSE, BOOL bCanUndo = FALSE)
+ {
+ InsertText(GetWindowTextLength(), lpstrText, bNoScroll, bCanUndo);
+ }
+
+#if (_WIN32_WINNT >= 0x0501)
+ BOOL ShowBalloonTip(PEDITBALLOONTIP pEditBaloonTip)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SHOWBALLOONTIP, 0, (LPARAM)pEditBaloonTip);
+ }
+
+ BOOL HideBalloonTip()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_HIDEBALLOONTIP, 0, 0L);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+#if (_WIN32_WINNT >= 0x0600)
+ DWORD GetHilite() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, EM_GETHILITE, 0, 0L);
+ }
+
+ void GetHilite(int& nStartChar, int& nEndChar) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, EM_GETHILITE, 0, 0L);
+ nStartChar = (int)(short)LOWORD(dwRet);
+ nEndChar = (int)(short)HIWORD(dwRet);
+ }
+
+ void SetHilite(int nStartChar, int nEndChar)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETHILITE, nStartChar, nEndChar);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+ // Clipboard operations
+ BOOL Undo()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_UNDO, 0, 0L);
+ }
+
+ void Clear()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_CLEAR, 0, 0L);
+ }
+
+ void Copy()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_COPY, 0, 0L);
+ }
+
+ void Cut()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_CUT, 0, 0L);
+ }
+
+ void Paste()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_PASTE, 0, 0L);
+ }
+
+#ifdef WIN32_PLATFORM_WFSP // SmartPhone only messages
+ DWORD GetExtendedStyle()
+ {
+ return SendMessage(EM_GETEXTENDEDSTYLE);
+ }
+
+ DWORD SetExtendedStyle(DWORD dwMask, DWORD dwExStyle)
+ {
+ return SendMessage(EM_SETEXTENDEDSTYLE, (WPARAM)dwMask, (LPARAM)dwExStyle);
+ }
+
+ DWORD GetInputMode(BOOL bCurrentMode = TRUE)
+ {
+ return SendMessage(EM_GETINPUTMODE, 0, (LPARAM)bCurrentMode);
+ }
+
+ BOOL SetInputMode(DWORD dwMode)
+ {
+ return SendMessage(EM_SETINPUTMODE, 0, (LPARAM)dwMode);
+ }
+
+ BOOL SetSymbols(LPCTSTR szSymbols)
+ {
+ return SendMessage(EM_SETSYMBOLS, 0, (LPARAM)szSymbols);
+ }
+
+ BOOL ResetSymbols()
+ {
+ return SendMessage(EM_SETSYMBOLS);
+ }
+#endif // WIN32_PLATFORM_WFSP
+};
+
+typedef CEditT<ATL::CWindow> CEdit;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CEditCommands - message handlers for standard EDIT commands
+
+// Chain to CEditCommands message map. Your class must also derive from CEdit.
+// Example:
+// class CMyEdit : public CWindowImpl<CMyEdit, CEdit>,
+// public CEditCommands<CMyEdit>
+// {
+// public:
+// BEGIN_MSG_MAP(CMyEdit)
+// // your handlers...
+// CHAIN_MSG_MAP_ALT(CEditCommands<CMyEdit>, 1)
+// END_MSG_MAP()
+// // other stuff...
+// };
+
+template <class T>
+class CEditCommands
+{
+public:
+ BEGIN_MSG_MAP(CEditCommands< T >)
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_EDIT_CLEAR, OnEditClear)
+ COMMAND_ID_HANDLER(ID_EDIT_CLEAR_ALL, OnEditClearAll)
+ COMMAND_ID_HANDLER(ID_EDIT_COPY, OnEditCopy)
+ COMMAND_ID_HANDLER(ID_EDIT_CUT, OnEditCut)
+ COMMAND_ID_HANDLER(ID_EDIT_PASTE, OnEditPaste)
+ COMMAND_ID_HANDLER(ID_EDIT_SELECT_ALL, OnEditSelectAll)
+ COMMAND_ID_HANDLER(ID_EDIT_UNDO, OnEditUndo)
+ END_MSG_MAP()
+
+ LRESULT OnEditClear(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Clear();
+ return 0;
+ }
+
+ LRESULT OnEditClearAll(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetSel(0, -1);
+ pT->Clear();
+ return 0;
+ }
+
+ LRESULT OnEditCopy(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Copy();
+ return 0;
+ }
+
+ LRESULT OnEditCut(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Cut();
+ return 0;
+ }
+
+ LRESULT OnEditPaste(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Paste();
+ return 0;
+ }
+
+ LRESULT OnEditSelectAll(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetSel(0, -1);
+ return 0;
+ }
+
+ LRESULT OnEditUndo(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Undo();
+ return 0;
+ }
+
+// State (update UI) helpers
+ BOOL CanCut() const
+ { return HasSelection(); }
+
+ BOOL CanCopy() const
+ { return HasSelection(); }
+
+ BOOL CanClear() const
+ { return HasSelection(); }
+
+ BOOL CanSelectAll() const
+ { return HasText(); }
+
+ BOOL CanFind() const
+ { return HasText(); }
+
+ BOOL CanRepeat() const
+ { return HasText(); }
+
+ BOOL CanReplace() const
+ { return HasText(); }
+
+ BOOL CanClearAll() const
+ { return HasText(); }
+
+// Implementation
+ BOOL HasSelection() const
+ {
+ const T* pT = static_cast<const T*>(this);
+ int nMin, nMax;
+ ::SendMessage(pT->m_hWnd, EM_GETSEL, (WPARAM)&nMin, (LPARAM)&nMax);
+ return (nMin != nMax);
+ }
+
+ BOOL HasText() const
+ {
+ const T* pT = static_cast<const T*>(this);
+ return (pT->GetWindowTextLength() > 0);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CScrollBar - client side for a Windows SCROLLBAR control
+
+template <class TBase>
+class CScrollBarT : public TBase
+{
+public:
+// Constructors
+ CScrollBarT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CScrollBarT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return _T("SCROLLBAR");
+ }
+
+#ifndef _WIN32_WCE
+ int GetScrollPos() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::GetScrollPos(m_hWnd, SB_CTL);
+ }
+#endif // !_WIN32_WCE
+
+ int SetScrollPos(int nPos, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::SetScrollPos(m_hWnd, SB_CTL, nPos, bRedraw);
+ }
+
+#ifndef _WIN32_WCE
+ void GetScrollRange(LPINT lpMinPos, LPINT lpMaxPos) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::GetScrollRange(m_hWnd, SB_CTL, lpMinPos, lpMaxPos);
+ }
+#endif // !_WIN32_WCE
+
+ void SetScrollRange(int nMinPos, int nMaxPos, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SetScrollRange(m_hWnd, SB_CTL, nMinPos, nMaxPos, bRedraw);
+ }
+
+ BOOL GetScrollInfo(LPSCROLLINFO lpScrollInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::GetScrollInfo(m_hWnd, SB_CTL, lpScrollInfo);
+ }
+
+ int SetScrollInfo(LPSCROLLINFO lpScrollInfo, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::SetScrollInfo(m_hWnd, SB_CTL, lpScrollInfo, bRedraw);
+ }
+
+#ifndef _WIN32_WCE
+ int GetScrollLimit() const
+ {
+ int nMin = 0, nMax = 0;
+ ::GetScrollRange(m_hWnd, SB_CTL, &nMin, &nMax);
+ SCROLLINFO info = { 0 };
+ info.cbSize = sizeof(SCROLLINFO);
+ info.fMask = SIF_PAGE;
+ if(::GetScrollInfo(m_hWnd, SB_CTL, &info))
+ nMax -= ((info.nPage - 1) > 0) ? (info.nPage - 1) : 0;
+
+ return nMax;
+ }
+
+#if (WINVER >= 0x0500)
+ BOOL GetScrollBarInfo(PSCROLLBARINFO pScrollBarInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+#if (_WIN32_WINNT >= 0x0501)
+ return (BOOL)::SendMessage(m_hWnd, SBM_GETSCROLLBARINFO, 0, (LPARAM)pScrollBarInfo);
+#else // !(_WIN32_WINNT >= 0x0501)
+ return ::GetScrollBarInfo(m_hWnd, OBJID_CLIENT, pScrollBarInfo);
+#endif // !(_WIN32_WINNT >= 0x0501)
+ }
+#endif // (WINVER >= 0x0500)
+
+// Operations
+ void ShowScrollBar(BOOL bShow = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::ShowScrollBar(m_hWnd, SB_CTL, bShow);
+ }
+
+ BOOL EnableScrollBar(UINT nArrowFlags = ESB_ENABLE_BOTH)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::EnableScrollBar(m_hWnd, SB_CTL, nArrowFlags);
+ }
+#endif // !_WIN32_WCE
+};
+
+typedef CScrollBarT<ATL::CWindow> CScrollBar;
+
+
+// --- Windows Common Controls ---
+
+///////////////////////////////////////////////////////////////////////////////
+// CImageList
+
+class CImageList
+{
+public:
+ HIMAGELIST m_hImageList;
+
+// Constructor
+ CImageList(HIMAGELIST hImageList = NULL) : m_hImageList(hImageList)
+ { }
+
+// Operators, etc.
+ CImageList& operator =(HIMAGELIST hImageList)
+ {
+ m_hImageList = hImageList;
+ return *this;
+ }
+
+ operator HIMAGELIST() const { return m_hImageList; }
+
+ void Attach(HIMAGELIST hImageList)
+ {
+ ATLASSERT(m_hImageList == NULL);
+ ATLASSERT(hImageList != NULL);
+ m_hImageList = hImageList;
+ }
+
+ HIMAGELIST Detach()
+ {
+ HIMAGELIST hImageList = m_hImageList;
+ m_hImageList = NULL;
+ return hImageList;
+ }
+
+ bool IsNull() const { return (m_hImageList == NULL); }
+
+// Attributes
+ int GetImageCount() const
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_GetImageCount(m_hImageList);
+ }
+
+ COLORREF GetBkColor() const
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_GetBkColor(m_hImageList);
+ }
+
+ COLORREF SetBkColor(COLORREF cr)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_SetBkColor(m_hImageList, cr);
+ }
+
+ BOOL GetImageInfo(int nImage, IMAGEINFO* pImageInfo) const
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_GetImageInfo(m_hImageList, nImage, pImageInfo);
+ }
+
+ HICON GetIcon(int nIndex, UINT uFlags = ILD_NORMAL) const
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_GetIcon(m_hImageList, nIndex, uFlags);
+ }
+
+ BOOL GetIconSize(int& cx, int& cy) const
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_GetIconSize(m_hImageList, &cx, &cy);
+ }
+
+ BOOL GetIconSize(SIZE& size) const
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_GetIconSize(m_hImageList, (int*)&size.cx, (int*)&size.cy);
+ }
+
+ BOOL SetIconSize(int cx, int cy)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_SetIconSize(m_hImageList, cx, cy);
+ }
+
+ BOOL SetIconSize(SIZE size)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_SetIconSize(m_hImageList, size.cx, size.cy);
+ }
+
+ BOOL SetImageCount(UINT uNewCount)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_SetImageCount(m_hImageList, uNewCount);
+ }
+
+ BOOL SetOverlayImage(int nImage, int nOverlay)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_SetOverlayImage(m_hImageList, nImage, nOverlay);
+ }
+
+// Operations
+ BOOL Create(int cx, int cy, UINT nFlags, int nInitial, int nGrow)
+ {
+ ATLASSERT(m_hImageList == NULL);
+ m_hImageList = ImageList_Create(cx, cy, nFlags, nInitial, nGrow);
+ return (m_hImageList != NULL) ? TRUE : FALSE;
+ }
+
+ BOOL Create(ATL::_U_STRINGorID bitmap, int cx, int nGrow, COLORREF crMask)
+ {
+ ATLASSERT(m_hImageList == NULL);
+ m_hImageList = ImageList_LoadBitmap(ModuleHelper::GetResourceInstance(), bitmap.m_lpstr, cx, nGrow, crMask);
+ return (m_hImageList != NULL) ? TRUE : FALSE;
+ }
+
+ BOOL CreateFromImage(ATL::_U_STRINGorID image, int cx, int nGrow, COLORREF crMask, UINT uType, UINT uFlags = LR_DEFAULTCOLOR | LR_DEFAULTSIZE)
+ {
+ ATLASSERT(m_hImageList == NULL);
+ m_hImageList = ImageList_LoadImage(ModuleHelper::GetResourceInstance(), image.m_lpstr, cx, nGrow, crMask, uType, uFlags);
+ return (m_hImageList != NULL) ? TRUE : FALSE;
+ }
+
+ BOOL Merge(HIMAGELIST hImageList1, int nImage1, HIMAGELIST hImageList2, int nImage2, int dx, int dy)
+ {
+ ATLASSERT(m_hImageList == NULL);
+ m_hImageList = ImageList_Merge(hImageList1, nImage1, hImageList2, nImage2, dx, dy);
+ return (m_hImageList != NULL) ? TRUE : FALSE;
+ }
+
+#ifndef _WIN32_WCE
+#ifdef __IStream_INTERFACE_DEFINED__
+ BOOL CreateFromStream(LPSTREAM lpStream)
+ {
+ ATLASSERT(m_hImageList == NULL);
+ m_hImageList = ImageList_Read(lpStream);
+ return (m_hImageList != NULL) ? TRUE : FALSE;
+ }
+#endif // __IStream_INTERFACE_DEFINED__
+#endif // !_WIN32_WCE
+
+ BOOL Destroy()
+ {
+ if (m_hImageList == NULL)
+ return FALSE;
+ BOOL bRet = ImageList_Destroy(m_hImageList);
+ if(bRet)
+ m_hImageList = NULL;
+ return bRet;
+ }
+
+ int Add(HBITMAP hBitmap, HBITMAP hBitmapMask = NULL)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_Add(m_hImageList, hBitmap, hBitmapMask);
+ }
+
+ int Add(HBITMAP hBitmap, COLORREF crMask)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_AddMasked(m_hImageList, hBitmap, crMask);
+ }
+
+ BOOL Remove(int nImage)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_Remove(m_hImageList, nImage);
+ }
+
+ BOOL RemoveAll()
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_RemoveAll(m_hImageList);
+ }
+
+ BOOL Replace(int nImage, HBITMAP hBitmap, HBITMAP hBitmapMask)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_Replace(m_hImageList, nImage, hBitmap, hBitmapMask);
+ }
+
+ int AddIcon(HICON hIcon)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_AddIcon(m_hImageList, hIcon);
+ }
+
+ int ReplaceIcon(int nImage, HICON hIcon)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_ReplaceIcon(m_hImageList, nImage, hIcon);
+ }
+
+ HICON ExtractIcon(int nImage)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_ExtractIcon(NULL, m_hImageList, nImage);
+ }
+
+ BOOL Draw(HDC hDC, int nImage, int x, int y, UINT nStyle)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ ATLASSERT(hDC != NULL);
+ return ImageList_Draw(m_hImageList, nImage, hDC, x, y, nStyle);
+ }
+
+ BOOL Draw(HDC hDC, int nImage, POINT pt, UINT nStyle)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ ATLASSERT(hDC != NULL);
+ return ImageList_Draw(m_hImageList, nImage, hDC, pt.x, pt.y, nStyle);
+ }
+
+ BOOL DrawEx(int nImage, HDC hDC, int x, int y, int dx, int dy, COLORREF rgbBk, COLORREF rgbFg, UINT fStyle)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ ATLASSERT(hDC != NULL);
+ return ImageList_DrawEx(m_hImageList, nImage, hDC, x, y, dx, dy, rgbBk, rgbFg, fStyle);
+ }
+
+ BOOL DrawEx(int nImage, HDC hDC, RECT& rect, COLORREF rgbBk, COLORREF rgbFg, UINT fStyle)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ ATLASSERT(hDC != NULL);
+ return ImageList_DrawEx(m_hImageList, nImage, hDC, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, rgbBk, rgbFg, fStyle);
+ }
+
+ static BOOL DrawIndirect(IMAGELISTDRAWPARAMS* pimldp)
+ {
+ return ImageList_DrawIndirect(pimldp);
+ }
+
+ BOOL Copy(int nSrc, int nDst, UINT uFlags = ILCF_MOVE)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_Copy(m_hImageList, nDst, m_hImageList, nSrc, uFlags);
+ }
+
+#ifdef __IStream_INTERFACE_DEFINED__
+#ifndef _WIN32_WCE
+ static HIMAGELIST Read(LPSTREAM lpStream)
+ {
+ return ImageList_Read(lpStream);
+ }
+
+ BOOL Write(LPSTREAM lpStream)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_Write(m_hImageList, lpStream);
+ }
+#endif // !_WIN32_WCE
+
+#if (_WIN32_WINNT >= 0x0501)
+ static HRESULT ReadEx(DWORD dwFlags, LPSTREAM lpStream, REFIID riid, PVOID* ppv)
+ {
+ DebugBreak();
+ return NULL;
+ //return ImageList_ReadEx(dwFlags, lpStream, riid, ppv);
+ }
+
+ HRESULT WriteEx(DWORD dwFlags, LPSTREAM lpStream)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ DebugBreak();
+ return NULL;
+ //return ImageList_WriteEx(m_hImageList, dwFlags, lpStream);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+#endif // __IStream_INTERFACE_DEFINED__
+
+ // Drag operations
+ BOOL BeginDrag(int nImage, POINT ptHotSpot)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_BeginDrag(m_hImageList, nImage, ptHotSpot.x, ptHotSpot.y);
+ }
+
+ BOOL BeginDrag(int nImage, int xHotSpot, int yHotSpot)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_BeginDrag(m_hImageList, nImage, xHotSpot, yHotSpot);
+ }
+
+ static void EndDrag()
+ {
+ ImageList_EndDrag();
+ }
+
+ static BOOL DragMove(POINT pt)
+ {
+ return ImageList_DragMove(pt.x, pt.y);
+ }
+
+ static BOOL DragMove(int x, int y)
+ {
+ return ImageList_DragMove(x, y);
+ }
+
+ BOOL SetDragCursorImage(int nDrag, POINT ptHotSpot)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_SetDragCursorImage(m_hImageList, nDrag, ptHotSpot.x, ptHotSpot.y);
+ }
+
+ BOOL SetDragCursorImage(int nDrag, int xHotSpot, int yHotSpot)
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return ImageList_SetDragCursorImage(m_hImageList, nDrag, xHotSpot, yHotSpot);
+ }
+
+ static BOOL DragShowNolock(BOOL bShow = TRUE)
+ {
+ return ImageList_DragShowNolock(bShow);
+ }
+
+ static CImageList GetDragImage(LPPOINT lpPoint, LPPOINT lpPointHotSpot)
+ {
+ return CImageList(ImageList_GetDragImage(lpPoint, lpPointHotSpot));
+ }
+
+ static BOOL DragEnter(HWND hWnd, POINT point)
+ {
+ return ImageList_DragEnter(hWnd, point.x, point.y);
+ }
+
+ static BOOL DragEnter(HWND hWnd, int x, int y)
+ {
+ return ImageList_DragEnter(hWnd, x, y);
+ }
+
+ static BOOL DragLeave(HWND hWnd)
+ {
+ return ImageList_DragLeave(hWnd);
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ CImageList Duplicate() const
+ {
+ ATLASSERT(m_hImageList != NULL);
+ return CImageList(ImageList_Duplicate(m_hImageList));
+ }
+
+ static CImageList Duplicate(HIMAGELIST hImageList)
+ {
+ ATLASSERT(hImageList != NULL);
+ return CImageList(ImageList_Duplicate(hImageList));
+ }
+#endif // (_WIN32_IE >= 0x0400)
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CToolTipCtrl
+
+#ifndef _WIN32_WCE
+
+class CToolInfo : public TOOLINFO
+{
+public:
+ CToolInfo(UINT nFlags, HWND hWnd, UINT nIDTool = 0, LPRECT lpRect = NULL, LPTSTR lpstrText = LPSTR_TEXTCALLBACK, LPARAM lUserParam = NULL)
+ {
+ Init(nFlags, hWnd, nIDTool, lpRect, lpstrText, lUserParam);
+ }
+
+ operator LPTOOLINFO() { return this; }
+
+ operator LPARAM() { return (LPARAM)this; }
+
+ void Init(UINT nFlags, HWND hWnd, UINT nIDTool = 0, LPRECT lpRect = NULL, LPTSTR lpstrText = LPSTR_TEXTCALLBACK, LPARAM lUserParam = NULL)
+ {
+ ATLASSERT(::IsWindow(hWnd));
+ memset(this, 0, sizeof(TOOLINFO));
+ cbSize = sizeof(TOOLINFO);
+ uFlags = nFlags;
+ if(nIDTool == 0)
+ {
+ hwnd = ::GetParent(hWnd);
+ uFlags |= TTF_IDISHWND;
+ uId = (UINT_PTR)hWnd;
+ }
+ else
+ {
+ hwnd = hWnd;
+ uId = nIDTool;
+ }
+ if(lpRect != NULL)
+ rect = *lpRect;
+ hinst = ModuleHelper::GetResourceInstance();
+ lpszText = lpstrText;
+ lParam = lUserParam;
+ }
+};
+
+template <class TBase>
+class CToolTipCtrlT : public TBase
+{
+public:
+// Constructors
+ CToolTipCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CToolTipCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return TOOLTIPS_CLASS;
+ }
+
+ void GetText(LPTOOLINFO lpToolInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_GETTEXT, 0, (LPARAM)&lpToolInfo);
+ }
+
+ void GetText(LPTSTR lpstrText, HWND hWnd, UINT nIDTool = 0) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hWnd != NULL);
+ CToolInfo ti(0, hWnd, nIDTool, NULL, lpstrText);
+ ::SendMessage(m_hWnd, TTM_GETTEXT, 0, ti);
+ }
+
+ BOOL GetToolInfo(LPTOOLINFO lpToolInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TTM_GETTOOLINFO, 0, (LPARAM)lpToolInfo);
+ }
+
+ BOOL GetToolInfo(HWND hWnd, UINT nIDTool, UINT* puFlags, LPRECT lpRect, LPTSTR lpstrText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hWnd != NULL);
+ ATLASSERT(puFlags != NULL);
+ ATLASSERT(lpRect != NULL);
+ CToolInfo ti(0, hWnd, nIDTool, NULL, lpstrText);
+ BOOL bRet = (BOOL)::SendMessage(m_hWnd, TTM_GETTOOLINFO, 0, ti);
+ if(bRet != FALSE)
+ {
+ *puFlags = ti.uFlags;
+ *lpRect = ti.rect;
+ }
+ return bRet;
+ }
+
+ void SetToolInfo(LPTOOLINFO lpToolInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_SETTOOLINFO, 0, (LPARAM)lpToolInfo);
+ }
+
+ void SetToolRect(LPTOOLINFO lpToolInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_NEWTOOLRECT, 0, (LPARAM)lpToolInfo);
+ }
+
+ void SetToolRect(HWND hWnd, UINT nIDTool, LPCRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hWnd != NULL);
+ ATLASSERT(nIDTool != 0);
+
+ CToolInfo ti(0, hWnd, nIDTool, (LPRECT)lpRect, NULL);
+ ::SendMessage(m_hWnd, TTM_NEWTOOLRECT, 0, ti);
+ }
+
+ int GetToolCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TTM_GETTOOLCOUNT, 0, 0L);
+ }
+
+ int GetDelayTime(DWORD dwType) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TTM_GETDELAYTIME, dwType, 0L);
+ }
+
+ void SetDelayTime(DWORD dwType, int nTime)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_SETDELAYTIME, dwType, MAKELPARAM(nTime, 0));
+ }
+
+ void GetMargin(LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_GETMARGIN, 0, (LPARAM)lpRect);
+ }
+
+ void SetMargin(LPRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_SETMARGIN, 0, (LPARAM)lpRect);
+ }
+
+ int GetMaxTipWidth() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TTM_GETMAXTIPWIDTH, 0, 0L);
+ }
+
+ int SetMaxTipWidth(int nWidth)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TTM_SETMAXTIPWIDTH, 0, nWidth);
+ }
+
+ COLORREF GetTipBkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TTM_GETTIPBKCOLOR, 0, 0L);
+ }
+
+ void SetTipBkColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_SETTIPBKCOLOR, (WPARAM)clr, 0L);
+ }
+
+ COLORREF GetTipTextColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TTM_GETTIPTEXTCOLOR, 0, 0L);
+ }
+
+ void SetTipTextColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_SETTIPTEXTCOLOR, (WPARAM)clr, 0L);
+ }
+
+ BOOL GetCurrentTool(LPTOOLINFO lpToolInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TTM_GETCURRENTTOOL, 0, (LPARAM)lpToolInfo);
+ }
+
+#if (_WIN32_IE >= 0x0500)
+ SIZE GetBubbleSize(LPTOOLINFO lpToolInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, TTM_GETBUBBLESIZE, 0, (LPARAM)lpToolInfo);
+ SIZE size = { GET_X_LPARAM(dwRet), GET_Y_LPARAM(dwRet) };
+ return size;
+ }
+
+ BOOL SetTitle(UINT uIcon, LPCTSTR lpstrTitle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TTM_SETTITLE, uIcon, (LPARAM)lpstrTitle);
+ }
+#endif // (_WIN32_IE >= 0x0500)
+
+#if (_WIN32_WINNT >= 0x0501)
+ void GetTitle(PTTGETTITLE pTTGetTitle) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_GETTITLE, 0, (LPARAM)pTTGetTitle);
+ }
+
+ void SetWindowTheme(LPCWSTR lpstrTheme)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_SETWINDOWTHEME, 0, (LPARAM)lpstrTheme);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+// Operations
+ void Activate(BOOL bActivate)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_ACTIVATE, bActivate, 0L);
+ }
+
+ BOOL AddTool(LPTOOLINFO lpToolInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TTM_ADDTOOL, 0, (LPARAM)lpToolInfo);
+ }
+
+ BOOL AddTool(HWND hWnd, ATL::_U_STRINGorID text = LPSTR_TEXTCALLBACK, LPCRECT lpRectTool = NULL, UINT nIDTool = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hWnd != NULL);
+ // the toolrect and toolid must both be zero or both valid
+ ATLASSERT((lpRectTool != NULL && nIDTool != 0) || (lpRectTool == NULL && nIDTool == 0));
+
+ CToolInfo ti(0, hWnd, nIDTool, (LPRECT)lpRectTool, (LPTSTR)text.m_lpstr);
+ return (BOOL)::SendMessage(m_hWnd, TTM_ADDTOOL, 0, ti);
+ }
+
+ void DelTool(LPTOOLINFO lpToolInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_DELTOOL, 0, (LPARAM)lpToolInfo);
+ }
+
+ void DelTool(HWND hWnd, UINT nIDTool = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hWnd != NULL);
+
+ CToolInfo ti(0, hWnd, nIDTool, NULL, NULL);
+ ::SendMessage(m_hWnd, TTM_DELTOOL, 0, ti);
+ }
+
+ BOOL HitTest(LPTTHITTESTINFO lpHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TTM_HITTEST, 0, (LPARAM)lpHitTestInfo);
+ }
+
+ BOOL HitTest(HWND hWnd, POINT pt, LPTOOLINFO lpToolInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hWnd != NULL);
+ ATLASSERT(lpToolInfo != NULL);
+
+ TTHITTESTINFO hti = { 0 };
+ hti.ti.cbSize = sizeof(TOOLINFO);
+ hti.hwnd = hWnd;
+ hti.pt.x = pt.x;
+ hti.pt.y = pt.y;
+ if((BOOL)::SendMessage(m_hWnd, TTM_HITTEST, 0, (LPARAM)&hti) != FALSE)
+ {
+ *lpToolInfo = hti.ti;
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ void RelayEvent(LPMSG lpMsg)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_RELAYEVENT, 0, (LPARAM)lpMsg);
+ }
+
+ void UpdateTipText(LPTOOLINFO lpToolInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_UPDATETIPTEXT, 0, (LPARAM)lpToolInfo);
+ }
+
+ void UpdateTipText(ATL::_U_STRINGorID text, HWND hWnd, UINT nIDTool = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hWnd != NULL);
+
+ CToolInfo ti(0, hWnd, nIDTool, NULL, (LPTSTR)text.m_lpstr);
+ ::SendMessage(m_hWnd, TTM_UPDATETIPTEXT, 0, ti);
+ }
+
+ BOOL EnumTools(UINT nTool, LPTOOLINFO lpToolInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TTM_ENUMTOOLS, nTool, (LPARAM)lpToolInfo);
+ }
+
+ void Pop()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_POP, 0, 0L);
+ }
+
+ void TrackActivate(LPTOOLINFO lpToolInfo, BOOL bActivate)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_TRACKACTIVATE, bActivate, (LPARAM)lpToolInfo);
+ }
+
+ void TrackPosition(int xPos, int yPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_TRACKPOSITION, 0, MAKELPARAM(xPos, yPos));
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ void Update()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_UPDATE, 0, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500)
+ BOOL AdjustRect(LPRECT lpRect, BOOL bLarger /*= TRUE*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TTM_ADJUSTRECT, bLarger, (LPARAM)lpRect);
+ }
+#endif // (_WIN32_IE >= 0x0500)
+
+#if (_WIN32_WINNT >= 0x0501)
+ void Popup()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TTM_POPUP, 0, 0L);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+};
+
+typedef CToolTipCtrlT<ATL::CWindow> CToolTipCtrl;
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CHeaderCtrl
+
+template <class TBase>
+class CHeaderCtrlT : public TBase
+{
+public:
+// Constructors
+ CHeaderCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CHeaderCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_HEADER;
+ }
+
+ int GetItemCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_GETITEMCOUNT, 0, 0L);
+ }
+
+ BOOL GetItem(int nIndex, LPHDITEM pHeaderItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_GETITEM, nIndex, (LPARAM)pHeaderItem);
+ }
+
+ BOOL SetItem(int nIndex, LPHDITEM pHeaderItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_SETITEM, nIndex, (LPARAM)pHeaderItem);
+ }
+
+ CImageList GetImageList() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, HDM_GETIMAGELIST, 0, 0L));
+ }
+
+ CImageList SetImageList(HIMAGELIST hImageList)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, HDM_SETIMAGELIST, 0, (LPARAM)hImageList));
+ }
+
+ BOOL GetOrderArray(int nSize, int* lpnArray) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_GETORDERARRAY, nSize, (LPARAM)lpnArray);
+ }
+
+ BOOL SetOrderArray(int nSize, int* lpnArray)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_SETORDERARRAY, nSize, (LPARAM)lpnArray);
+ }
+
+ BOOL GetItemRect(int nIndex, LPRECT lpItemRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_GETITEMRECT, nIndex, (LPARAM)lpItemRect);
+ }
+
+ int SetHotDivider(BOOL bPos, DWORD dwInputValue)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_SETHOTDIVIDER, bPos, dwInputValue);
+ }
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ int GetBitmapMargin() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_GETBITMAPMARGIN, 0, 0L);
+ }
+
+ int SetBitmapMargin(int nWidth)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_SETBITMAPMARGIN, nWidth, 0L);
+ }
+
+ int SetFilterChangeTimeout(DWORD dwTimeOut)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_SETFILTERCHANGETIMEOUT, 0, dwTimeOut);
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+#if (_WIN32_WINNT >= 0x0600)
+ BOOL GetItemDropDownRect(int nIndex, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_GETITEMDROPDOWNRECT, nIndex, (LPARAM)lpRect);
+ }
+
+ BOOL GetOverflowRect(LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_GETOVERFLOWRECT, 0, (LPARAM)lpRect);
+ }
+
+ int GetFocusedItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_GETFOCUSEDITEM, 0, 0L);
+ }
+
+ BOOL SetFocusedItem(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_SETFOCUSEDITEM, 0, nIndex);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+// Operations
+ int InsertItem(int nIndex, LPHDITEM phdi)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_INSERTITEM, nIndex, (LPARAM)phdi);
+ }
+
+ int AddItem(LPHDITEM phdi)
+ {
+ return InsertItem(GetItemCount(), phdi);
+ }
+
+ BOOL DeleteItem(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_DELETEITEM, nIndex, 0L);
+ }
+
+ BOOL Layout(HD_LAYOUT* pHeaderLayout)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, HDM_LAYOUT, 0, (LPARAM)pHeaderLayout);
+ }
+
+ int HitTest(LPHDHITTESTINFO lpHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_HITTEST, 0, (LPARAM)lpHitTestInfo);
+ }
+
+ int OrderToIndex(int nOrder)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_ORDERTOINDEX, nOrder, 0L);
+ }
+
+ CImageList CreateDragImage(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, HDM_CREATEDRAGIMAGE, nIndex, 0L));
+ }
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ int EditFilter(int nColumn, BOOL bDiscardChanges)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_EDITFILTER, nColumn, MAKELPARAM(bDiscardChanges, 0));
+ }
+
+ int ClearFilter(int nColumn)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_CLEARFILTER, nColumn, 0L);
+ }
+
+ int ClearAllFilters()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, HDM_CLEARFILTER, (WPARAM)-1, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+};
+
+typedef CHeaderCtrlT<ATL::CWindow> CHeaderCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CListViewCtrl
+
+template <class TBase>
+class CListViewCtrlT : public TBase
+{
+public:
+// Constructors
+ CListViewCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CListViewCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_LISTVIEW;
+ }
+
+ COLORREF GetBkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, LVM_GETBKCOLOR, 0, 0L);
+ }
+
+ BOOL SetBkColor(COLORREF cr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETBKCOLOR, 0, cr);
+ }
+
+ CImageList GetImageList(int nImageListType) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, LVM_GETIMAGELIST, nImageListType, 0L));
+ }
+
+ CImageList SetImageList(HIMAGELIST hImageList, int nImageList)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, LVM_SETIMAGELIST, nImageList, (LPARAM)hImageList));
+ }
+
+ int GetItemCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETITEMCOUNT, 0, 0L);
+ }
+
+ BOOL SetItemCount(int nItems)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEMCOUNT, nItems, 0L);
+ }
+
+ BOOL GetItem(LPLVITEM pItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETITEM, 0, (LPARAM)pItem);
+ }
+
+ BOOL SetItem(const LVITEM* pItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEM, 0, (LPARAM)pItem);
+ }
+
+ BOOL SetItem(int nItem, int nSubItem, UINT nMask, LPCTSTR lpszItem,
+ int nImage, UINT nState, UINT nStateMask, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVITEM lvi = { 0 };
+ lvi.mask = nMask;
+ lvi.iItem = nItem;
+ lvi.iSubItem = nSubItem;
+ lvi.stateMask = nStateMask;
+ lvi.state = nState;
+ lvi.pszText = (LPTSTR) lpszItem;
+ lvi.iImage = nImage;
+ lvi.lParam = lParam;
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEM, 0, (LPARAM)&lvi);
+ }
+
+ UINT GetItemState(int nItem, UINT nMask) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, LVM_GETITEMSTATE, nItem, nMask);
+ }
+
+ BOOL SetItemState(int nItem, UINT nState, UINT nStateMask)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVITEM lvi = { 0 };
+ lvi.state = nState;
+ lvi.stateMask = nStateMask;
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEMSTATE, nItem, (LPARAM)&lvi);
+ }
+
+ BOOL SetItemState(int nItem, LPLVITEM pItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEMSTATE, nItem, (LPARAM)pItem);
+ }
+
+#ifndef _ATL_NO_COM
+ BOOL GetItemText(int nItem, int nSubItem, BSTR& bstrText) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(bstrText == NULL);
+ LVITEM lvi = { 0 };
+ lvi.iSubItem = nSubItem;
+
+ LPTSTR lpstrText = NULL;
+ int nRes = 0;
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ ATLTRY(lpstrText = new TCHAR[nLen]);
+ if(lpstrText == NULL)
+ break;
+ lpstrText[0] = NULL;
+ lvi.cchTextMax = nLen;
+ lvi.pszText = lpstrText;
+ nRes = (int)::SendMessage(m_hWnd, LVM_GETITEMTEXT, (WPARAM)nItem, (LPARAM)&lvi);
+ if(nRes < nLen - 1)
+ break;
+ delete [] lpstrText;
+ lpstrText = NULL;
+ }
+
+ if(lpstrText != NULL)
+ {
+ if(nRes != 0)
+ bstrText = ::SysAllocString(T2OLE(lpstrText));
+ delete [] lpstrText;
+ }
+
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ int GetItemText(int nItem, int nSubItem, _CSTRING_NS::CString& strText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVITEM lvi = { 0 };
+ lvi.iSubItem = nSubItem;
+
+ strText.Empty();
+ int nRes = 0;
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ lvi.cchTextMax = nLen;
+ lvi.pszText = strText.GetBufferSetLength(nLen);
+ if(lvi.pszText == NULL)
+ {
+ nRes = 0;
+ break;
+ }
+ nRes = (int)::SendMessage(m_hWnd, LVM_GETITEMTEXT, (WPARAM)nItem, (LPARAM)&lvi);
+ if(nRes < nLen - 1)
+ break;
+ }
+ strText.ReleaseBuffer();
+ return nRes;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ int GetItemText(int nItem, int nSubItem, LPTSTR lpszText, int nLen) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVITEM lvi = { 0 };
+ lvi.iSubItem = nSubItem;
+ lvi.cchTextMax = nLen;
+ lvi.pszText = lpszText;
+ return (int)::SendMessage(m_hWnd, LVM_GETITEMTEXT, (WPARAM)nItem, (LPARAM)&lvi);
+ }
+
+ BOOL SetItemText(int nItem, int nSubItem, LPCTSTR lpszText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItem(nItem, nSubItem, LVIF_TEXT, lpszText, 0, 0, 0, 0);
+ }
+
+ DWORD_PTR GetItemData(int nItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVITEM lvi = { 0 };
+ lvi.iItem = nItem;
+ lvi.mask = LVIF_PARAM;
+ BOOL bRet = (BOOL)::SendMessage(m_hWnd, LVM_GETITEM, 0, (LPARAM)&lvi);
+ return (DWORD_PTR)(bRet ? lvi.lParam : NULL);
+ }
+
+ BOOL SetItemData(int nItem, DWORD_PTR dwData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItem(nItem, 0, LVIF_PARAM, NULL, 0, 0, 0, (LPARAM)dwData);
+ }
+
+ UINT GetCallbackMask() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, LVM_GETCALLBACKMASK, 0, 0L);
+ }
+
+ BOOL SetCallbackMask(UINT nMask)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETCALLBACKMASK, nMask, 0L);
+ }
+
+ BOOL GetItemPosition(int nItem, LPPOINT lpPoint) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETITEMPOSITION, nItem, (LPARAM)lpPoint);
+ }
+
+ BOOL SetItemPosition(int nItem, POINT pt)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(((GetStyle() & LVS_TYPEMASK) == LVS_ICON) || ((GetStyle() & LVS_TYPEMASK) == LVS_SMALLICON));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEMPOSITION32, nItem, (LPARAM)&pt);
+ }
+
+ BOOL SetItemPosition(int nItem, int x, int y)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(((GetStyle() & LVS_TYPEMASK) == LVS_ICON) || ((GetStyle() & LVS_TYPEMASK) == LVS_SMALLICON));
+ POINT pt = { x, y };
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEMPOSITION32, nItem, (LPARAM)&pt);
+ }
+
+ int GetStringWidth(LPCTSTR lpsz) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETSTRINGWIDTH, 0, (LPARAM)lpsz);
+ }
+
+ CEdit GetEditControl() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CEdit((HWND)::SendMessage(m_hWnd, LVM_GETEDITCONTROL, 0, 0L));
+ }
+
+ BOOL GetColumn(int nCol, LVCOLUMN* pColumn) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETCOLUMN, nCol, (LPARAM)pColumn);
+ }
+
+ BOOL SetColumn(int nCol, const LVCOLUMN* pColumn)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETCOLUMN, nCol, (LPARAM)pColumn);
+ }
+
+ int GetColumnWidth(int nCol) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETCOLUMNWIDTH, nCol, 0L);
+ }
+
+ BOOL SetColumnWidth(int nCol, int cx)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETCOLUMNWIDTH, nCol, MAKELPARAM(cx, 0));
+ }
+
+ BOOL GetViewRect(LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETVIEWRECT, 0, (LPARAM)lpRect);
+ }
+
+ COLORREF GetTextColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, LVM_GETTEXTCOLOR, 0, 0L);
+ }
+
+ BOOL SetTextColor(COLORREF cr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETTEXTCOLOR, 0, cr);
+ }
+
+ COLORREF GetTextBkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, LVM_GETTEXTBKCOLOR, 0, 0L);
+ }
+
+ BOOL SetTextBkColor(COLORREF cr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETTEXTBKCOLOR, 0, cr);
+ }
+
+ int GetTopIndex() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETTOPINDEX, 0, 0L);
+ }
+
+ int GetCountPerPage() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETCOUNTPERPAGE, 0, 0L);
+ }
+
+ BOOL GetOrigin(LPPOINT lpPoint) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETORIGIN, 0, (LPARAM)lpPoint);
+ }
+
+ UINT GetSelectedCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, LVM_GETSELECTEDCOUNT, 0, 0L);
+ }
+
+ BOOL GetItemRect(int nItem, LPRECT lpRect, UINT nCode) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ lpRect->left = nCode;
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETITEMRECT, (WPARAM)nItem, (LPARAM)lpRect);
+ }
+
+#ifndef _WIN32_WCE
+ HCURSOR GetHotCursor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HCURSOR)::SendMessage(m_hWnd, LVM_GETHOTCURSOR, 0, 0L);
+ }
+
+ HCURSOR SetHotCursor(HCURSOR hHotCursor)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HCURSOR)::SendMessage(m_hWnd, LVM_SETHOTCURSOR, 0, (LPARAM)hHotCursor);
+ }
+
+ int GetHotItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETHOTITEM, 0, 0L);
+ }
+
+ int SetHotItem(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_SETHOTITEM, nIndex, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL GetColumnOrderArray(int nCount, int* lpnArray) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETCOLUMNORDERARRAY, nCount, (LPARAM)lpnArray);
+ }
+
+ BOOL SetColumnOrderArray(int nCount, int* lpnArray)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETCOLUMNORDERARRAY, nCount, (LPARAM)lpnArray);
+ }
+
+ CHeaderCtrl GetHeader() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CHeaderCtrl((HWND)::SendMessage(m_hWnd, LVM_GETHEADER, 0, 0L));
+ }
+
+ BOOL GetSubItemRect(int nItem, int nSubItem, int nFlag, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & LVS_TYPEMASK) == LVS_REPORT);
+ ATLASSERT(lpRect != NULL);
+ lpRect->top = nSubItem;
+ lpRect->left = nFlag;
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETSUBITEMRECT, nItem, (LPARAM)lpRect);
+ }
+
+ DWORD SetIconSpacing(int cx, int cy)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & LVS_TYPEMASK) == LVS_ICON);
+ return (DWORD)::SendMessage(m_hWnd, LVM_SETICONSPACING, 0, MAKELPARAM(cx, cy));
+ }
+
+ int GetISearchString(LPTSTR lpstr) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETISEARCHSTRING, 0, (LPARAM)lpstr);
+ }
+
+ void GetItemSpacing(SIZE& sizeSpacing, BOOL bSmallIconView = FALSE) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, LVM_GETITEMSPACING, bSmallIconView, 0L);
+ sizeSpacing.cx = GET_X_LPARAM(dwRet);
+ sizeSpacing.cy = GET_Y_LPARAM(dwRet);
+ }
+
+#if (_WIN32_WCE >= 410)
+ void SetItemSpacing(INT cySpacing)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ListView_SetItemSpacing(m_hWnd, cySpacing);
+ }
+#endif // (_WIN32_WCE >= 410)
+
+ // single-selection only
+ int GetSelectedIndex() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & LVS_SINGLESEL) != 0);
+ return (int)::SendMessage(m_hWnd, LVM_GETNEXTITEM, (WPARAM)-1, MAKELPARAM(LVNI_ALL | LVNI_SELECTED, 0));
+ }
+
+ BOOL GetSelectedItem(LPLVITEM pItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & LVS_SINGLESEL) != 0);
+ ATLASSERT(pItem != NULL);
+ pItem->iItem = (int)::SendMessage(m_hWnd, LVM_GETNEXTITEM, (WPARAM)-1, MAKELPARAM(LVNI_ALL | LVNI_SELECTED, 0));
+ if(pItem->iItem == -1)
+ return FALSE;
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETITEM, 0, (LPARAM)pItem);
+ }
+
+ // extended list view styles
+ DWORD GetExtendedListViewStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0L);
+ }
+
+ // dwExMask = 0 means all styles
+ DWORD SetExtendedListViewStyle(DWORD dwExStyle, DWORD dwExMask = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, LVM_SETEXTENDEDLISTVIEWSTYLE, dwExMask, dwExStyle);
+ }
+
+ // checkboxes only
+ BOOL GetCheckState(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetExtendedListViewStyle() & LVS_EX_CHECKBOXES) != 0);
+ UINT uRet = GetItemState(nIndex, LVIS_STATEIMAGEMASK);
+ return (uRet >> 12) - 1;
+ }
+
+ BOOL SetCheckState(int nItem, BOOL bCheck)
+ {
+ int nCheck = bCheck ? 2 : 1; // one based index
+ return SetItemState(nItem, INDEXTOSTATEIMAGEMASK(nCheck), LVIS_STATEIMAGEMASK);
+ }
+
+ // view type
+ DWORD GetViewType() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (GetStyle() & LVS_TYPEMASK);
+ }
+
+ DWORD SetViewType(DWORD dwType)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(dwType == LVS_ICON || dwType == LVS_SMALLICON || dwType == LVS_LIST || dwType == LVS_REPORT);
+ DWORD dwOldType = GetViewType();
+ if(dwType != dwOldType)
+ ModifyStyle(LVS_TYPEMASK, (dwType & LVS_TYPEMASK));
+ return dwOldType;
+ }
+
+#if (_WIN32_IE >= 0x0400)
+#ifndef _WIN32_WCE
+ BOOL GetBkImage(LPLVBKIMAGE plvbki) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETBKIMAGE, 0, (LPARAM)plvbki);
+ }
+
+ BOOL SetBkImage(LPLVBKIMAGE plvbki)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETBKIMAGE, 0, (LPARAM)plvbki);
+ }
+#endif // !_WIN32_WCE
+
+ int GetSelectionMark() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETSELECTIONMARK, 0, 0L);
+ }
+
+ int SetSelectionMark(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_SETSELECTIONMARK, 0, nIndex);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetWorkAreas(int nWorkAreas, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETWORKAREAS, nWorkAreas, (LPARAM)lpRect);
+ }
+
+ BOOL SetWorkAreas(int nWorkAreas, LPRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETWORKAREAS, nWorkAreas, (LPARAM)lpRect);
+ }
+
+ DWORD GetHoverTime() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetExtendedListViewStyle() & (LVS_EX_TRACKSELECT | LVS_EX_ONECLICKACTIVATE | LVS_EX_TWOCLICKACTIVATE)) != 0);
+ return (DWORD)::SendMessage(m_hWnd, LVM_GETHOVERTIME, 0, 0L);
+ }
+
+ DWORD SetHoverTime(DWORD dwHoverTime)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetExtendedListViewStyle() & (LVS_EX_TRACKSELECT | LVS_EX_ONECLICKACTIVATE | LVS_EX_TWOCLICKACTIVATE)) != 0);
+ return (DWORD)::SendMessage(m_hWnd, LVM_SETHOVERTIME, 0, dwHoverTime);
+ }
+
+ BOOL GetNumberOfWorkAreas(int* pnWorkAreas) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETNUMBEROFWORKAREAS, 0, (LPARAM)pnWorkAreas);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL SetItemCountEx(int nItems, DWORD dwFlags)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(((GetStyle() & LVS_OWNERDATA) != 0) && (((GetStyle() & LVS_TYPEMASK) == LVS_REPORT) || ((GetStyle() & LVS_TYPEMASK) == LVS_LIST)));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEMCOUNT, nItems, dwFlags);
+ }
+
+#ifndef _WIN32_WCE
+ CToolTipCtrl GetToolTips() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CToolTipCtrl((HWND)::SendMessage(m_hWnd, LVM_GETTOOLTIPS, 0, 0L));
+ }
+
+ CToolTipCtrl SetToolTips(HWND hWndTT)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CToolTipCtrl((HWND)::SendMessage(m_hWnd, LVM_SETTOOLTIPS, (WPARAM)hWndTT, 0L));
+ }
+
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // !_WIN32_WCE
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_WINNT >= 0x0501)
+ int GetSelectedColumn() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETSELECTEDCOLUMN, 0, 0L);
+ }
+
+ void SetSelectedColumn(int nColumn)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_SETSELECTEDCOLUMN, nColumn, 0L);
+ }
+
+ DWORD GetView() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, LVM_GETVIEW, 0, 0L);
+ }
+
+ int SetView(DWORD dwView)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_SETVIEW, dwView, 0L);
+ }
+
+ BOOL IsGroupViewEnabled() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_ISGROUPVIEWENABLED, 0, 0L);
+ }
+
+ int GetGroupInfo(int nGroupID, PLVGROUP pGroup) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETGROUPINFO, nGroupID, (LPARAM)pGroup);
+ }
+
+ int SetGroupInfo(int nGroupID, PLVGROUP pGroup)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_SETGROUPINFO, nGroupID, (LPARAM)pGroup);
+ }
+
+ void GetGroupMetrics(PLVGROUPMETRICS pGroupMetrics) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_GETGROUPMETRICS, 0, (LPARAM)pGroupMetrics);
+ }
+
+ void SetGroupMetrics(PLVGROUPMETRICS pGroupMetrics)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_SETGROUPMETRICS, 0, (LPARAM)pGroupMetrics);
+ }
+
+ void GetTileViewInfo(PLVTILEVIEWINFO pTileViewInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_GETTILEVIEWINFO, 0, (LPARAM)pTileViewInfo);
+ }
+
+ BOOL SetTileViewInfo(PLVTILEVIEWINFO pTileViewInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETTILEVIEWINFO, 0, (LPARAM)pTileViewInfo);
+ }
+
+ void GetTileInfo(PLVTILEINFO pTileInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_GETTILEINFO, 0, (LPARAM)pTileInfo);
+ }
+
+ BOOL SetTileInfo(PLVTILEINFO pTileInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETTILEINFO, 0, (LPARAM)pTileInfo);
+ }
+
+ BOOL GetInsertMark(LPLVINSERTMARK pInsertMark) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETINSERTMARK, 0, (LPARAM)pInsertMark);
+ }
+
+ BOOL SetInsertMark(LPLVINSERTMARK pInsertMark)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETINSERTMARK, 0, (LPARAM)pInsertMark);
+ }
+
+ int GetInsertMarkRect(LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETINSERTMARKRECT, 0, (LPARAM)lpRect);
+ }
+
+ COLORREF GetInsertMarkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, LVM_GETINSERTMARKCOLOR, 0, 0L);
+ }
+
+ COLORREF SetInsertMarkColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, LVM_SETINSERTMARKCOLOR, 0, clr);
+ }
+
+ COLORREF GetOutlineColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, LVM_GETOUTLINECOLOR, 0, 0L);
+ }
+
+ COLORREF SetOutlineColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, LVM_SETOUTLINECOLOR, 0, clr);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+#if (_WIN32_WINNT >= 0x0600)
+ int GetGroupCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETGROUPCOUNT, 0, 0L);
+ }
+
+ BOOL GetGroupInfoByIndex(int nIndex, PLVGROUP pGroup) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETGROUPINFOBYINDEX, nIndex, (LPARAM)pGroup);
+ }
+
+ BOOL GetGroupRect(int nGroupID, int nType, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpRect != NULL);
+ if(lpRect != NULL)
+ lpRect->top = nType;
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETGROUPRECT, nGroupID, (LPARAM)lpRect);
+ }
+
+ UINT GetGroupState(int nGroupID, UINT uMask) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, LVM_GETGROUPSTATE, nGroupID, (LPARAM)uMask);
+ }
+
+ int GetFocusedGroup() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETFOCUSEDGROUP, 0, 0L);
+ }
+
+ BOOL GetEmptyText(LPWSTR lpstrText, int cchText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETEMPTYTEXT, cchText, (LPARAM)lpstrText);
+ }
+
+ BOOL GetFooterRect(LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETFOOTERRECT, 0, (LPARAM)lpRect);
+ }
+
+ BOOL GetFooterInfo(LPLVFOOTERINFO lpFooterInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETFOOTERINFO, 0, (LPARAM)lpFooterInfo);
+ }
+
+ BOOL GetFooterItemRect(int nItem, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETFOOTERITEMRECT, nItem, (LPARAM)lpRect);
+ }
+
+ BOOL GetFooterItem(int nItem, LPLVFOOTERITEM lpFooterItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETFOOTERITEM, nItem, (LPARAM)lpFooterItem);
+ }
+
+ BOOL GetItemIndexRect(PLVITEMINDEX pItemIndex, int nSubItem, int nType, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pItemIndex != NULL);
+ ATLASSERT(lpRect != NULL);
+ if(lpRect != NULL)
+ {
+ lpRect->top = nSubItem;
+ lpRect->left = nType;
+ }
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETITEMINDEXRECT, (WPARAM)pItemIndex, (LPARAM)lpRect);
+ }
+
+ BOOL SetItemIndexState(PLVITEMINDEX pItemIndex, UINT uState, UINT dwMask)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVITEM lvi = { 0 };
+ lvi.state = uState;
+ lvi.stateMask = dwMask;
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETITEMINDEXSTATE, (WPARAM)pItemIndex, (LPARAM)&lvi);
+ }
+
+ BOOL GetNextItemIndex(PLVITEMINDEX pItemIndex, WORD wFlags) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_GETNEXTITEMINDEX, (WPARAM)pItemIndex, MAKELPARAM(wFlags, 0));
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+// Operations
+ int InsertColumn(int nCol, const LVCOLUMN* pColumn)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_INSERTCOLUMN, nCol, (LPARAM)pColumn);
+ }
+
+ int InsertColumn(int nCol, LPCTSTR lpszColumnHeading, int nFormat = LVCFMT_LEFT,
+ int nWidth = -1, int nSubItem = -1, int iImage = -1, int iOrder = -1)
+ {
+ LVCOLUMN column = { 0 };
+ column.mask = LVCF_TEXT|LVCF_FMT;
+ column.pszText = (LPTSTR)lpszColumnHeading;
+ column.fmt = nFormat;
+ if (nWidth != -1)
+ {
+ column.mask |= LVCF_WIDTH;
+ column.cx = nWidth;
+ }
+ if (nSubItem != -1)
+ {
+ column.mask |= LVCF_SUBITEM;
+ column.iSubItem = nSubItem;
+ }
+ if (iImage != -1)
+ {
+ column.mask |= LVCF_IMAGE;
+ column.iImage = iImage;
+ }
+ if (iOrder != -1)
+ {
+ column.mask |= LVCF_ORDER;
+ column.iOrder = iOrder;
+ }
+ return InsertColumn(nCol, &column);
+ }
+
+ BOOL DeleteColumn(int nCol)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_DELETECOLUMN, nCol, 0L);
+ }
+
+ int InsertItem(UINT nMask, int nItem, LPCTSTR lpszItem, UINT nState, UINT nStateMask, int nImage, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVITEM item = { 0 };
+ item.mask = nMask;
+ item.iItem = nItem;
+ item.iSubItem = 0;
+ item.pszText = (LPTSTR)lpszItem;
+ item.state = nState;
+ item.stateMask = nStateMask;
+ item.iImage = nImage;
+ item.lParam = lParam;
+ return InsertItem(&item);
+ }
+
+ int InsertItem(const LVITEM* pItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_INSERTITEM, 0, (LPARAM)pItem);
+ }
+
+ int InsertItem(int nItem, LPCTSTR lpszItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return InsertItem(LVIF_TEXT, nItem, lpszItem, 0, 0, 0, 0);
+ }
+
+ int InsertItem(int nItem, LPCTSTR lpszItem, int nImage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return InsertItem(LVIF_TEXT|LVIF_IMAGE, nItem, lpszItem, 0, 0, nImage, 0);
+ }
+
+ int GetNextItem(int nItem, int nFlags) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_GETNEXTITEM, nItem, MAKELPARAM(nFlags, 0));
+ }
+
+ BOOL DeleteItem(int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_DELETEITEM, nItem, 0L);
+ }
+
+ BOOL DeleteAllItems()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_DELETEALLITEMS, 0, 0L);
+ }
+
+ int FindItem(LVFINDINFO* pFindInfo, int nStart) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_FINDITEM, nStart, (LPARAM)pFindInfo);
+ }
+
+ int HitTest(LVHITTESTINFO* pHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_HITTEST, 0, (LPARAM)pHitTestInfo);
+ }
+
+ int HitTest(POINT pt, UINT* pFlags) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVHITTESTINFO hti = { 0 };
+ hti.pt = pt;
+ int nRes = (int)::SendMessage(m_hWnd, LVM_HITTEST, 0, (LPARAM)&hti);
+ if (pFlags != NULL)
+ *pFlags = hti.flags;
+ return nRes;
+ }
+
+ BOOL EnsureVisible(int nItem, BOOL bPartialOK)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_ENSUREVISIBLE, nItem, MAKELPARAM(bPartialOK, 0));
+ }
+
+ BOOL Scroll(SIZE size)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SCROLL, size.cx, size.cy);
+ }
+
+ BOOL RedrawItems(int nFirst, int nLast)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_REDRAWITEMS, nFirst, nLast);
+ }
+
+ BOOL Arrange(UINT nCode)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_ARRANGE, nCode, 0L);
+ }
+
+ CEdit EditLabel(int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CEdit((HWND)::SendMessage(m_hWnd, LVM_EDITLABEL, nItem, 0L));
+ }
+
+ BOOL Update(int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_UPDATE, nItem, 0L);
+ }
+
+ BOOL SortItems(PFNLVCOMPARE pfnCompare, LPARAM lParamSort)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SORTITEMS, (WPARAM)lParamSort, (LPARAM)pfnCompare);
+ }
+
+ CImageList RemoveImageList(int nImageList)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, LVM_SETIMAGELIST, (WPARAM)nImageList, NULL));
+ }
+
+ CImageList CreateDragImage(int nItem, LPPOINT lpPoint)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, LVM_CREATEDRAGIMAGE, nItem, (LPARAM)lpPoint));
+ }
+
+ DWORD ApproximateViewRect(int cx = -1, int cy = -1, int nCount = -1)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, LVM_APPROXIMATEVIEWRECT, nCount, MAKELPARAM(cx, cy));
+ }
+
+ int SubItemHitTest(LPLVHITTESTINFO lpInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_SUBITEMHITTEST, 0, (LPARAM)lpInfo);
+ }
+
+ int AddColumn(LPCTSTR strItem, int nItem, int nSubItem = -1,
+ int nMask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM,
+ int nFmt = LVCFMT_LEFT)
+ {
+ const int cxOffset = 15;
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVCOLUMN lvc = { 0 };
+ lvc.mask = nMask;
+ lvc.fmt = nFmt;
+ lvc.pszText = (LPTSTR)strItem;
+ lvc.cx = GetStringWidth(lvc.pszText) + cxOffset;
+ if(nMask & LVCF_SUBITEM)
+ lvc.iSubItem = (nSubItem != -1) ? nSubItem : nItem;
+ return InsertColumn(nItem, &lvc);
+ }
+
+ int AddItem(int nItem, int nSubItem, LPCTSTR strItem, int nImageIndex = -1)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVITEM lvItem = { 0 };
+ lvItem.mask = LVIF_TEXT;
+ lvItem.iItem = nItem;
+ lvItem.iSubItem = nSubItem;
+ lvItem.pszText = (LPTSTR)strItem;
+ if(nImageIndex != -1)
+ {
+ lvItem.mask |= LVIF_IMAGE;
+ lvItem.iImage = nImageIndex;
+ }
+ if(nSubItem == 0)
+ return InsertItem(&lvItem);
+ return SetItem(&lvItem) ? nItem : -1;
+ }
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ BOOL SortItemsEx(PFNLVCOMPARE pfnCompare, LPARAM lParamSort)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SORTITEMSEX, (WPARAM)lParamSort, (LPARAM)pfnCompare);
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+#if (_WIN32_WINNT >= 0x0501)
+ int InsertGroup(int nItem, PLVGROUP pGroup)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_INSERTGROUP, nItem, (LPARAM)pGroup);
+ }
+
+ int AddGroup(PLVGROUP pGroup)
+ {
+ return InsertGroup(-1, pGroup);
+ }
+
+ int RemoveGroup(int nGroupID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_REMOVEGROUP, nGroupID, 0L);
+ }
+
+ void MoveGroup(int nGroupID, int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_MOVEGROUP, nGroupID, nItem);
+ }
+
+ void MoveItemToGroup(int nItem, int nGroupID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_MOVEITEMTOGROUP, nItem, nGroupID);
+ }
+
+ int EnableGroupView(BOOL bEnable)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_ENABLEGROUPVIEW, bEnable, 0L);
+ }
+
+ int SortGroups(PFNLVGROUPCOMPARE pCompareFunc, LPVOID lpVoid = NULL)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_SORTGROUPS, (WPARAM)pCompareFunc, (LPARAM)lpVoid);
+ }
+
+ void InsertGroupSorted(PLVINSERTGROUPSORTED pInsertGroupSorted)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_INSERTGROUPSORTED, (WPARAM)pInsertGroupSorted, 0L);
+ }
+
+ void RemoveAllGroups()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_REMOVEALLGROUPS, 0, 0L);
+ }
+
+ BOOL HasGroup(int nGroupID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_HASGROUP, nGroupID, 0L);
+ }
+
+ BOOL InsertMarkHitTest(LPPOINT lpPoint, LPLVINSERTMARK pInsertMark) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_INSERTMARKHITTEST, (WPARAM)lpPoint, (LPARAM)pInsertMark);
+ }
+
+ BOOL SetInfoTip(PLVSETINFOTIP pSetInfoTip)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LVM_SETINFOTIP, 0, (LPARAM)pSetInfoTip);
+ }
+
+ void CancelEditLabel()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, LVM_CANCELEDITLABEL, 0, 0L);
+ }
+
+ UINT MapIndexToID(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, LVM_MAPINDEXTOID, nIndex, 0L);
+ }
+
+ int MapIDToIndex(UINT uID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_MAPIDTOINDEX, uID, 0L);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+#if (_WIN32_WINNT >= 0x0600)
+ int HitTestEx(LPLVHITTESTINFO lpHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_HITTEST, (WPARAM)-1, (LPARAM)lpHitTestInfo);
+ }
+
+ int HitTestEx(POINT pt, UINT* pFlags) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LVHITTESTINFO hti = { 0 };
+ hti.pt = pt;
+ int nRes = (int)::SendMessage(m_hWnd, LVM_HITTEST, (WPARAM)-1, (LPARAM)&hti);
+ if (pFlags != NULL)
+ *pFlags = hti.flags;
+ return nRes;
+ }
+
+ int SubItemHitTestEx(LPLVHITTESTINFO lpHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LVM_SUBITEMHITTEST, (WPARAM)-1, (LPARAM)lpHitTestInfo);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+ // Note: selects only one item
+ BOOL SelectItem(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ // multi-selection only: de-select all items
+ if((GetStyle() & LVS_SINGLESEL) == 0)
+ SetItemState(-1, 0, LVIS_SELECTED);
+
+ BOOL bRet = SetItemState(nIndex, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
+ if(bRet)
+ bRet = EnsureVisible(nIndex, FALSE);
+
+ return bRet;
+ }
+};
+
+typedef CListViewCtrlT<ATL::CWindow> CListViewCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTreeViewCtrl
+
+template <class TBase>
+class CTreeViewCtrlT : public TBase
+{
+public:
+// Constructors
+ CTreeViewCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CTreeViewCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_TREEVIEW;
+ }
+
+ UINT GetCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, TVM_GETCOUNT, 0, 0L);
+ }
+
+ UINT GetIndent() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, TVM_GETINDENT, 0, 0L);
+ }
+
+ void SetIndent(UINT nIndent)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TVM_SETINDENT, nIndent, 0L);
+ }
+
+ CImageList GetImageList(int nImageListType = TVSIL_NORMAL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TVM_GETIMAGELIST, (WPARAM)nImageListType, 0L));
+ }
+
+ CImageList SetImageList(HIMAGELIST hImageList, int nImageListType = TVSIL_NORMAL)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TVM_SETIMAGELIST, (WPARAM)nImageListType, (LPARAM)hImageList));
+ }
+
+ BOOL GetItem(LPTVITEM pItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)pItem);
+ }
+
+ BOOL SetItem(LPTVITEM pItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SETITEM, 0, (LPARAM)pItem);
+ }
+
+ BOOL SetItem(HTREEITEM hItem, UINT nMask, LPCTSTR lpszItem, int nImage,
+ int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVITEM item = { 0 };
+ item.hItem = hItem;
+ item.mask = nMask;
+ item.pszText = (LPTSTR) lpszItem;
+ item.iImage = nImage;
+ item.iSelectedImage = nSelectedImage;
+ item.state = nState;
+ item.stateMask = nStateMask;
+ item.lParam = lParam;
+ return (BOOL)::SendMessage(m_hWnd, TVM_SETITEM, 0, (LPARAM)&item);
+ }
+
+ BOOL GetItemText(HTREEITEM hItem, LPTSTR lpstrText, int nLen) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpstrText != NULL);
+
+ TVITEM item = { 0 };
+ item.hItem = hItem;
+ item.mask = TVIF_TEXT;
+ item.pszText = lpstrText;
+ item.cchTextMax = nLen;
+
+ return (BOOL)::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)&item);
+ }
+
+#ifndef _ATL_NO_COM
+ BOOL GetItemText(HTREEITEM hItem, BSTR& bstrText) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(bstrText == NULL);
+ TVITEM item = { 0 };
+ item.hItem = hItem;
+ item.mask = TVIF_TEXT;
+
+ LPTSTR lpstrText = NULL;
+ BOOL bRet = FALSE;
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ ATLTRY(lpstrText = new TCHAR[nLen]);
+ if(lpstrText == NULL)
+ break;
+ lpstrText[0] = NULL;
+ item.pszText = lpstrText;
+ item.cchTextMax = nLen;
+ bRet = (BOOL)::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)&item);
+ if(!bRet || (lstrlen(item.pszText) < nLen - 1))
+ break;
+ delete [] lpstrText;
+ lpstrText = NULL;
+ }
+
+ if(lpstrText != NULL)
+ {
+ if(bRet)
+ bstrText = ::SysAllocString(T2OLE(lpstrText));
+ delete [] lpstrText;
+ }
+
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ BOOL GetItemText(HTREEITEM hItem, _CSTRING_NS::CString& strText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVITEM item = { 0 };
+ item.hItem = hItem;
+ item.mask = TVIF_TEXT;
+
+ strText.Empty();
+ BOOL bRet = FALSE;
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ item.pszText = strText.GetBufferSetLength(nLen);
+ if(item.pszText == NULL)
+ {
+ bRet = FALSE;
+ break;
+ }
+ item.cchTextMax = nLen;
+ bRet = (BOOL)::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)&item);
+ if(!bRet || (lstrlen(item.pszText) < nLen - 1))
+ break;
+ }
+ strText.ReleaseBuffer();
+ return bRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ BOOL SetItemText(HTREEITEM hItem, LPCTSTR lpszItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItem(hItem, TVIF_TEXT, lpszItem, 0, 0, 0, 0, NULL);
+ }
+
+ BOOL GetItemImage(HTREEITEM hItem, int& nImage, int& nSelectedImage) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVITEM item = { 0 };
+ item.hItem = hItem;
+ item.mask = TVIF_IMAGE|TVIF_SELECTEDIMAGE;
+ BOOL bRes = (BOOL)::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)&item);
+ if (bRes)
+ {
+ nImage = item.iImage;
+ nSelectedImage = item.iSelectedImage;
+ }
+ return bRes;
+ }
+
+ BOOL SetItemImage(HTREEITEM hItem, int nImage, int nSelectedImage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItem(hItem, TVIF_IMAGE|TVIF_SELECTEDIMAGE, NULL, nImage, nSelectedImage, 0, 0, NULL);
+ }
+
+ UINT GetItemState(HTREEITEM hItem, UINT nStateMask) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ return (((UINT)::SendMessage(m_hWnd, TVM_GETITEMSTATE, (WPARAM)hItem, (LPARAM)nStateMask)) & nStateMask);
+#else // !((_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE))
+ TVITEM item = { 0 };
+ item.hItem = hItem;
+ item.mask = TVIF_STATE;
+ item.state = 0;
+ item.stateMask = nStateMask;
+ ::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)&item);
+ return (item.state & nStateMask);
+#endif // !((_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE))
+ }
+
+ BOOL SetItemState(HTREEITEM hItem, UINT nState, UINT nStateMask)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItem(hItem, TVIF_STATE, NULL, 0, 0, nState, nStateMask, NULL);
+ }
+
+ DWORD_PTR GetItemData(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVITEM item = { 0 };
+ item.hItem = hItem;
+ item.mask = TVIF_PARAM;
+ BOOL bRet = (BOOL)::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)&item);
+ return (DWORD_PTR)(bRet ? item.lParam : NULL);
+ }
+
+ BOOL SetItemData(HTREEITEM hItem, DWORD_PTR dwData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItem(hItem, TVIF_PARAM, NULL, 0, 0, 0, 0, (LPARAM)dwData);
+ }
+
+ CEdit GetEditControl() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CEdit((HWND)::SendMessage(m_hWnd, TVM_GETEDITCONTROL, 0, 0L));
+ }
+
+ UINT GetVisibleCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, TVM_GETVISIBLECOUNT, 0, 0L);
+ }
+
+ BOOL GetItemRect(HTREEITEM hItem, LPRECT lpRect, BOOL bTextOnly) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ *(HTREEITEM*)lpRect = hItem;
+ return (BOOL)::SendMessage(m_hWnd, TVM_GETITEMRECT, (WPARAM)bTextOnly, (LPARAM)lpRect);
+ }
+
+ BOOL ItemHasChildren(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVITEM item = { 0 };
+ item.hItem = hItem;
+ item.mask = TVIF_CHILDREN;
+ ::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)&item);
+ return item.cChildren;
+ }
+
+#ifndef _WIN32_WCE
+ CToolTipCtrl GetToolTips() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CToolTipCtrl((HWND)::SendMessage(m_hWnd, TVM_GETTOOLTIPS, 0, 0L));
+ }
+
+ CToolTipCtrl SetToolTips(HWND hWndTT)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CToolTipCtrl((HWND)::SendMessage(m_hWnd, TVM_SETTOOLTIPS, (WPARAM)hWndTT, 0L));
+ }
+#endif // !_WIN32_WCE
+
+ int GetISearchString(LPTSTR lpstr) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TVM_GETISEARCHSTRING, 0, (LPARAM)lpstr);
+ }
+
+ // checkboxes only
+ BOOL GetCheckState(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & TVS_CHECKBOXES) != 0);
+ UINT uRet = GetItemState(hItem, TVIS_STATEIMAGEMASK);
+ return (uRet >> 12) - 1;
+ }
+
+ BOOL SetCheckState(HTREEITEM hItem, BOOL bCheck)
+ {
+ int nCheck = bCheck ? 2 : 1; // one based index
+ return SetItemState(hItem, INDEXTOSTATEIMAGEMASK(nCheck), TVIS_STATEIMAGEMASK);
+ }
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ COLORREF GetBkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TVM_GETBKCOLOR, 0, 0L);
+ }
+
+ COLORREF SetBkColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TVM_SETBKCOLOR, 0, (LPARAM)clr);
+ }
+
+ COLORREF GetInsertMarkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TVM_GETINSERTMARKCOLOR, 0, 0L);
+ }
+
+ COLORREF SetInsertMarkColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TVM_SETINSERTMARKCOLOR, 0, (LPARAM)clr);
+ }
+
+ int GetItemHeight() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TVM_GETITEMHEIGHT, 0, 0L);
+ }
+
+ int SetItemHeight(int cyHeight)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TVM_SETITEMHEIGHT, cyHeight, 0L);
+ }
+
+ int GetScrollTime() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TVM_GETSCROLLTIME, 0, 0L);
+ }
+
+ int SetScrollTime(int nScrollTime)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TVM_SETSCROLLTIME, nScrollTime, 0L);
+ }
+
+ COLORREF GetTextColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TVM_GETTEXTCOLOR, 0, 0L);
+ }
+
+ COLORREF SetTextColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TVM_SETTEXTCOLOR, 0, (LPARAM)clr);
+ }
+
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ COLORREF GetLineColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TVM_GETLINECOLOR, 0, 0L);
+ }
+
+ COLORREF SetLineColor(COLORREF clrNew /*= CLR_DEFAULT*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TVM_SETLINECOLOR, 0, (LPARAM)clrNew);
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ BOOL GetItem(LPTVITEMEX pItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_GETITEM, 0, (LPARAM)pItem);
+ }
+
+ BOOL SetItem(LPTVITEMEX pItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SETITEM, 0, (LPARAM)pItem);
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+ DWORD GetExtendedStyle() const
+ {
+#ifndef TVM_GETEXTENDEDSTYLE
+ const UINT TVM_GETEXTENDEDSTYLE = (TV_FIRST + 45);
+#endif
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TVM_GETEXTENDEDSTYLE, 0, 0L);
+ }
+
+ DWORD SetExtendedStyle(DWORD dwStyle, DWORD dwMask)
+ {
+#ifndef TVM_SETEXTENDEDSTYLE
+ const UINT TVM_SETEXTENDEDSTYLE = (TV_FIRST + 44);
+#endif
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TVM_SETEXTENDEDSTYLE, dwMask, dwStyle);
+ }
+
+#if (_WIN32_WINNT >= 0x0600)
+ BOOL SetAutoScrollInfo(UINT uPixPerSec, UINT uUpdateTime)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SETAUTOSCROLLINFO, (WPARAM)uPixPerSec, (LPARAM)uUpdateTime);
+ }
+
+ DWORD GetSelectedCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TVM_GETSELECTEDCOUNT, 0, 0L);
+ }
+
+ BOOL GetItemPartRect(HTREEITEM hItem, TVITEMPART partID, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVGETITEMPARTRECTINFO gipri = { hItem, lpRect, partID };
+ return (BOOL)::SendMessage(m_hWnd, TVM_GETITEMPARTRECT, 0, (LPARAM)&gipri);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+// Operations
+ HTREEITEM InsertItem(LPTVINSERTSTRUCT lpInsertStruct)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_INSERTITEM, 0, (LPARAM)lpInsertStruct);
+ }
+
+ HTREEITEM InsertItem(LPCTSTR lpszItem, int nImage,
+ int nSelectedImage, HTREEITEM hParent, HTREEITEM hInsertAfter)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return InsertItem(TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE, lpszItem, nImage, nSelectedImage, 0, 0, 0, hParent, hInsertAfter);
+ }
+
+ HTREEITEM InsertItem(LPCTSTR lpszItem, HTREEITEM hParent, HTREEITEM hInsertAfter)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return InsertItem(TVIF_TEXT, lpszItem, 0, 0, 0, 0, 0, hParent, hInsertAfter);
+ }
+
+ HTREEITEM InsertItem(UINT nMask, LPCTSTR lpszItem, int nImage,
+ int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam,
+ HTREEITEM hParent, HTREEITEM hInsertAfter)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVINSERTSTRUCT tvis = { 0 };
+ tvis.hParent = hParent;
+ tvis.hInsertAfter = hInsertAfter;
+ tvis.item.mask = nMask;
+ tvis.item.pszText = (LPTSTR) lpszItem;
+ tvis.item.iImage = nImage;
+ tvis.item.iSelectedImage = nSelectedImage;
+ tvis.item.state = nState;
+ tvis.item.stateMask = nStateMask;
+ tvis.item.lParam = lParam;
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_INSERTITEM, 0, (LPARAM)&tvis);
+ }
+
+ BOOL DeleteItem(HTREEITEM hItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_DELETEITEM, 0, (LPARAM)hItem);
+ }
+
+ BOOL DeleteAllItems()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_DELETEITEM, 0, (LPARAM)TVI_ROOT);
+ }
+
+ BOOL Expand(HTREEITEM hItem, UINT nCode = TVE_EXPAND)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_EXPAND, nCode, (LPARAM)hItem);
+ }
+
+ HTREEITEM GetNextItem(HTREEITEM hItem, UINT nCode) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, nCode, (LPARAM)hItem);
+ }
+
+ HTREEITEM GetChildItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_CHILD, (LPARAM)hItem);
+ }
+
+ HTREEITEM GetNextSiblingItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_NEXT, (LPARAM)hItem);
+ }
+
+ HTREEITEM GetPrevSiblingItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_PREVIOUS, (LPARAM)hItem);
+ }
+
+ HTREEITEM GetParentItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_PARENT, (LPARAM)hItem);
+ }
+
+ HTREEITEM GetFirstVisibleItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_FIRSTVISIBLE, 0L);
+ }
+
+ HTREEITEM GetNextVisibleItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_NEXTVISIBLE, (LPARAM)hItem);
+ }
+
+ HTREEITEM GetPrevVisibleItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_PREVIOUSVISIBLE, (LPARAM)hItem);
+ }
+
+ HTREEITEM GetSelectedItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_CARET, 0L);
+ }
+
+ HTREEITEM GetDropHilightItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_DROPHILITE, 0L);
+ }
+
+ HTREEITEM GetRootItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_ROOT, 0L);
+ }
+
+#if !defined(_WIN32_WCE) && (_WIN32_IE >= 0x0400)
+ HTREEITEM GetLastVisibleItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_LASTVISIBLE, 0L);
+ }
+#endif // !defined(_WIN32_WCE) && (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0600)
+ HTREEITEM GetNextSelectedItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_NEXTSELECTED, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0600)
+
+ BOOL Select(HTREEITEM hItem, UINT nCode)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SELECTITEM, nCode, (LPARAM)hItem);
+ }
+
+ BOOL SelectItem(HTREEITEM hItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SELECTITEM, TVGN_CARET, (LPARAM)hItem);
+ }
+
+ BOOL SelectDropTarget(HTREEITEM hItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SELECTITEM, TVGN_DROPHILITE, (LPARAM)hItem);
+ }
+
+ BOOL SelectSetFirstVisible(HTREEITEM hItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SELECTITEM, TVGN_FIRSTVISIBLE, (LPARAM)hItem);
+ }
+
+ CEdit EditLabel(HTREEITEM hItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CEdit((HWND)::SendMessage(m_hWnd, TVM_EDITLABEL, 0, (LPARAM)hItem));
+ }
+
+ BOOL EndEditLabelNow(BOOL bCancel)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_ENDEDITLABELNOW, bCancel, 0L);
+ }
+
+ HTREEITEM HitTest(TVHITTESTINFO* pHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_HITTEST, 0, (LPARAM)pHitTestInfo);
+ }
+
+ HTREEITEM HitTest(POINT pt, UINT* pFlags) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVHITTESTINFO hti = { 0 };
+ hti.pt = pt;
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_HITTEST, 0, (LPARAM)&hti);
+ if (pFlags != NULL)
+ *pFlags = hti.flags;
+ return hTreeItem;
+ }
+
+ BOOL SortChildren(HTREEITEM hItem, BOOL bRecurse = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SORTCHILDREN, (WPARAM)bRecurse, (LPARAM)hItem);
+ }
+
+ BOOL EnsureVisible(HTREEITEM hItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_ENSUREVISIBLE, 0, (LPARAM)hItem);
+ }
+
+ BOOL SortChildrenCB(LPTVSORTCB pSort, BOOL bRecurse = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SORTCHILDRENCB, (WPARAM)bRecurse, (LPARAM)pSort);
+ }
+
+ CImageList RemoveImageList(int nImageList)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TVM_SETIMAGELIST, (WPARAM)nImageList, NULL));
+ }
+
+ CImageList CreateDragImage(HTREEITEM hItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TVM_CREATEDRAGIMAGE, 0, (LPARAM)hItem));
+ }
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ BOOL SetInsertMark(HTREEITEM hTreeItem, BOOL bAfter)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SETINSERTMARK, bAfter, (LPARAM)hTreeItem);
+ }
+
+ BOOL RemoveInsertMark()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TVM_SETINSERTMARK, 0, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+#if (_WIN32_WINNT >= 0x0501)
+ HTREEITEM MapAccIDToHTREEITEM(UINT uID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HTREEITEM)::SendMessage(m_hWnd, TVM_MAPACCIDTOHTREEITEM, uID, 0L);
+ }
+
+ UINT MapHTREEITEMToAccID(HTREEITEM hTreeItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, TVM_MAPHTREEITEMTOACCID, (WPARAM)hTreeItem, 0L);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+#if (_WIN32_WINNT >= 0x0600)
+ void ShowInfoTip(HTREEITEM hItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TVM_SHOWINFOTIP, 0, (LPARAM)hItem);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+};
+
+typedef CTreeViewCtrlT<ATL::CWindow> CTreeViewCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTreeViewCtrlEx
+
+// forward declaration
+template <class TBase> class CTreeViewCtrlExT;
+
+// Note: TBase here is for CTreeViewCtrlExT, and not for CTreeItemT itself
+template <class TBase>
+class CTreeItemT
+{
+public:
+ HTREEITEM m_hTreeItem;
+ CTreeViewCtrlExT<TBase>* m_pTreeView;
+
+// Construction
+ CTreeItemT(HTREEITEM hTreeItem = NULL, CTreeViewCtrlExT<TBase>* pTreeView = NULL) : m_hTreeItem(hTreeItem), m_pTreeView(pTreeView)
+ { }
+
+ CTreeItemT(const CTreeItemT<TBase>& posSrc)
+ {
+ *this = posSrc;
+ }
+
+ operator HTREEITEM() { return m_hTreeItem; }
+
+ CTreeItemT<TBase>& operator =(const CTreeItemT<TBase>& itemSrc)
+ {
+ m_hTreeItem = itemSrc.m_hTreeItem;
+ m_pTreeView = itemSrc.m_pTreeView;
+ return *this;
+ }
+
+// Attributes
+ CTreeViewCtrlExT<TBase>* GetTreeView() const { return m_pTreeView; }
+
+ BOOL operator !() const { return m_hTreeItem == NULL; }
+
+ BOOL IsNull() const { return m_hTreeItem == NULL; }
+
+ BOOL GetRect(LPRECT lpRect, BOOL bTextOnly) const;
+ BOOL GetText(LPTSTR lpstrText, int nLen) const;
+#ifndef _ATL_NO_COM
+ BOOL GetText(BSTR& bstrText) const;
+#endif // !_ATL_NO_COM
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ BOOL GetText(_CSTRING_NS::CString& strText) const;
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ BOOL SetText(LPCTSTR lpszItem);
+ BOOL GetImage(int& nImage, int& nSelectedImage) const;
+ BOOL SetImage(int nImage, int nSelectedImage);
+ UINT GetState(UINT nStateMask) const;
+ BOOL SetState(UINT nState, UINT nStateMask);
+ DWORD_PTR GetData() const;
+ BOOL SetData(DWORD_PTR dwData);
+ BOOL SetItem(UINT nMask, LPCTSTR lpszItem, int nImage, int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam);
+
+// Operations
+ CTreeItemT<TBase> InsertAfter(LPCTSTR lpstrItem, HTREEITEM hItemAfter, int nImageIndex)
+ {
+ return _Insert(lpstrItem, nImageIndex, hItemAfter);
+ }
+
+ CTreeItemT<TBase> AddHead(LPCTSTR lpstrItem, int nImageIndex)
+ {
+ return _Insert(lpstrItem, nImageIndex, TVI_FIRST);
+ }
+
+ CTreeItemT<TBase> AddTail(LPCTSTR lpstrItem, int nImageIndex)
+ {
+ return _Insert(lpstrItem, nImageIndex, TVI_LAST);
+ }
+
+ CTreeItemT<TBase> GetChild() const;
+ CTreeItemT<TBase> GetNext(UINT nCode) const;
+ CTreeItemT<TBase> GetNextSibling() const;
+ CTreeItemT<TBase> GetPrevSibling() const;
+ CTreeItemT<TBase> GetParent() const;
+ CTreeItemT<TBase> GetFirstVisible() const;
+ CTreeItemT<TBase> GetNextVisible() const;
+ CTreeItemT<TBase> GetPrevVisible() const;
+ CTreeItemT<TBase> GetSelected() const;
+ CTreeItemT<TBase> GetDropHilight() const;
+ CTreeItemT<TBase> GetRoot() const;
+#if !defined(_WIN32_WCE) && (_WIN32_IE >= 0x0400)
+ CTreeItemT<TBase> GetLastVisible() const;
+#endif // !defined(_WIN32_WCE) && (_WIN32_IE >= 0x0400)
+#if (_WIN32_IE >= 0x0600)
+ CTreeItemT<TBase> GetNextSelected() const;
+#endif // (_WIN32_IE >= 0x0600)
+ BOOL HasChildren() const;
+ BOOL Delete();
+ BOOL Expand(UINT nCode = TVE_EXPAND);
+ BOOL Select(UINT nCode);
+ BOOL Select();
+ BOOL SelectDropTarget();
+ BOOL SelectSetFirstVisible();
+ HWND EditLabel();
+ HIMAGELIST CreateDragImage();
+ BOOL SortChildren(BOOL bRecurse = FALSE);
+ BOOL EnsureVisible();
+ CTreeItemT<TBase> _Insert(LPCTSTR lpstrItem, int nImageIndex, HTREEITEM hItemAfter);
+ int GetImageIndex() const;
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ BOOL SetInsertMark(BOOL bAfter);
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+#if (_WIN32_WINNT >= 0x0501)
+ UINT MapHTREEITEMToAccID() const;
+#endif // (_WIN32_WINNT >= 0x0501)
+#if (_WIN32_WINNT >= 0x0600)
+ void ShowInfoTip();
+ BOOL GetPartRect(TVITEMPART partID, LPRECT lpRect) const;
+#endif // (_WIN32_WINNT >= 0x0600)
+};
+
+typedef CTreeItemT<ATL::CWindow> CTreeItem;
+
+
+template <class TBase>
+class CTreeViewCtrlExT : public CTreeViewCtrlT< TBase >
+{
+public:
+// Constructors
+ CTreeViewCtrlExT(HWND hWnd = NULL) : CTreeViewCtrlT< TBase >(hWnd)
+ { }
+
+ CTreeViewCtrlExT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Operations (overides that return CTreeItem)
+ CTreeItemT<TBase> InsertItem(LPTVINSERTSTRUCT lpInsertStruct)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_INSERTITEM, 0, (LPARAM)lpInsertStruct);
+ return CTreeItemT<TBase>(hTreeItem, this);
+ }
+
+ CTreeItemT<TBase> InsertItem(LPCTSTR lpszItem, int nImage,
+ int nSelectedImage, HTREEITEM hParent, HTREEITEM hInsertAfter)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return InsertItem(TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE, lpszItem, nImage, nSelectedImage, 0, 0, 0, hParent, hInsertAfter);
+ }
+
+ CTreeItemT<TBase> InsertItem(LPCTSTR lpszItem, HTREEITEM hParent, HTREEITEM hInsertAfter)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return InsertItem(TVIF_TEXT, lpszItem, 0, 0, 0, 0, 0, hParent, hInsertAfter);
+ }
+
+ CTreeItemT<TBase> GetNextItem(HTREEITEM hItem, UINT nCode) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, nCode, (LPARAM)hItem);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetChildItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_CHILD, (LPARAM)hItem);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetNextSiblingItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_NEXT, (LPARAM)hItem);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetPrevSiblingItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_PREVIOUS, (LPARAM)hItem);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetParentItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_PARENT, (LPARAM)hItem);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetFirstVisibleItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_FIRSTVISIBLE, 0L);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetNextVisibleItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_NEXTVISIBLE, (LPARAM)hItem);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetPrevVisibleItem(HTREEITEM hItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_PREVIOUSVISIBLE, (LPARAM)hItem);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetSelectedItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_CARET, 0L);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetDropHilightItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_DROPHILITE, 0L);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> GetRootItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_ROOT, 0L);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+#if !defined(_WIN32_WCE) && (_WIN32_IE >= 0x0400)
+ CTreeItemT<TBase> GetLastVisibleItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_LASTVISIBLE, 0L);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+#endif // !defined(_WIN32_WCE) && (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0600)
+ CTreeItemT<TBase> GetNextSelectedItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_GETNEXTITEM, TVGN_NEXTSELECTED, 0L);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+#endif // (_WIN32_IE >= 0x0600)
+
+ CTreeItemT<TBase> HitTest(TVHITTESTINFO* pHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_HITTEST, 0, (LPARAM)pHitTestInfo);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+ CTreeItemT<TBase> InsertItem(UINT nMask, LPCTSTR lpszItem, int nImage,
+ int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam,
+ HTREEITEM hParent, HTREEITEM hInsertAfter)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVINSERTSTRUCT tvis = { 0 };
+ tvis.hParent = hParent;
+ tvis.hInsertAfter = hInsertAfter;
+ tvis.item.mask = nMask;
+ tvis.item.pszText = (LPTSTR) lpszItem;
+ tvis.item.iImage = nImage;
+ tvis.item.iSelectedImage = nSelectedImage;
+ tvis.item.state = nState;
+ tvis.item.stateMask = nStateMask;
+ tvis.item.lParam = lParam;
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_INSERTITEM, 0, (LPARAM)&tvis);
+ return CTreeItemT<TBase>(hTreeItem, this);
+ }
+
+ CTreeItemT<TBase> HitTest(POINT pt, UINT* pFlags) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TVHITTESTINFO hti = { 0 };
+ hti.pt = pt;
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_HITTEST, 0, (LPARAM)&hti);
+ if (pFlags != NULL)
+ *pFlags = hti.flags;
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+
+#if (_WIN32_WINNT >= 0x0501)
+ CTreeItemT<TBase> MapAccIDToHTREEITEM(UINT uID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HTREEITEM hTreeItem = (HTREEITEM)::SendMessage(m_hWnd, TVM_MAPACCIDTOHTREEITEM, uID, 0L);
+ return CTreeItemT<TBase>(hTreeItem, (CTreeViewCtrlExT<TBase>*)this);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+};
+
+typedef CTreeViewCtrlExT<ATL::CWindow> CTreeViewCtrlEx;
+
+
+// CTreeItem inline methods
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::GetRect(LPRECT lpRect, BOOL bTextOnly) const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetItemRect(m_hTreeItem,lpRect,bTextOnly);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetNext(UINT nCode) const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetNextItem(m_hTreeItem,nCode);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetChild() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetChildItem(m_hTreeItem);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetNextSibling() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetNextSiblingItem(m_hTreeItem);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetPrevSibling() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetPrevSiblingItem(m_hTreeItem);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetParent() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetParentItem(m_hTreeItem);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetFirstVisible() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetFirstVisibleItem();
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetNextVisible() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetNextVisibleItem(m_hTreeItem);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetPrevVisible() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetPrevVisibleItem(m_hTreeItem);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetSelected() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetSelectedItem();
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetDropHilight() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetDropHilightItem();
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetRoot() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetRootItem();
+}
+
+#if !defined(_WIN32_WCE) && (_WIN32_IE >= 0x0400)
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetLastVisible() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetLastVisibleItem();
+}
+#endif // !defined(_WIN32_WCE) && (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0600)
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::GetNextSelected() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetNextSelectedItem();
+}
+#endif // (_WIN32_IE >= 0x0600)
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::GetText(LPTSTR lpstrText, int nLen) const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetItemText(m_hTreeItem, lpstrText, nLen);
+}
+
+#ifndef _ATL_NO_COM
+#ifdef _OLEAUTO_H_
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::GetText(BSTR& bstrText) const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetItemText(m_hTreeItem, bstrText);
+}
+#endif // _OLEAUTO_H_
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::GetText(_CSTRING_NS::CString& strText) const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetItemText(m_hTreeItem, strText);
+}
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::GetImage(int& nImage, int& nSelectedImage) const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetItemImage(m_hTreeItem,nImage,nSelectedImage);
+}
+
+template <class TBase>
+inline UINT CTreeItemT<TBase>::GetState(UINT nStateMask) const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetItemState(m_hTreeItem,nStateMask);
+}
+
+template <class TBase>
+inline DWORD_PTR CTreeItemT<TBase>::GetData() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetItemData(m_hTreeItem);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SetItem(UINT nMask, LPCTSTR lpszItem, int nImage,
+ int nSelectedImage, UINT nState, UINT nStateMask, LPARAM lParam)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SetItem(m_hTreeItem, nMask, lpszItem, nImage, nSelectedImage, nState, nStateMask, lParam);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SetText(LPCTSTR lpszItem)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SetItemText(m_hTreeItem,lpszItem);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SetImage(int nImage, int nSelectedImage)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SetItemImage(m_hTreeItem,nImage,nSelectedImage);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SetState(UINT nState, UINT nStateMask)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SetItemState(m_hTreeItem,nState,nStateMask);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SetData(DWORD_PTR dwData)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SetItemData(m_hTreeItem,dwData);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::HasChildren() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->ItemHasChildren(m_hTreeItem);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::Delete()
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->DeleteItem(m_hTreeItem);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::Expand(UINT nCode /*= TVE_EXPAND*/)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->Expand(m_hTreeItem,nCode);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::Select(UINT nCode)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->Select(m_hTreeItem,nCode);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::Select()
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SelectItem(m_hTreeItem);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SelectDropTarget()
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SelectDropTarget(m_hTreeItem);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SelectSetFirstVisible()
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SelectSetFirstVisible(m_hTreeItem);
+}
+
+template <class TBase>
+inline HWND CTreeItemT<TBase>::EditLabel()
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->EditLabel(m_hTreeItem);
+}
+
+template <class TBase>
+inline HIMAGELIST CTreeItemT<TBase>::CreateDragImage()
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->CreateDragImage(m_hTreeItem);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SortChildren(BOOL bRecurse /*= FALSE*/)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SortChildren(m_hTreeItem, bRecurse);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::EnsureVisible()
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->EnsureVisible(m_hTreeItem);
+}
+
+template <class TBase>
+inline CTreeItemT<TBase> CTreeItemT<TBase>::_Insert(LPCTSTR lpstrItem, int nImageIndex, HTREEITEM hItemAfter)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ TVINSERTSTRUCT ins = { 0 };
+ ins.hParent = m_hTreeItem;
+ ins.hInsertAfter = hItemAfter;
+ ins.item.mask = TVIF_TEXT;
+ ins.item.pszText = (LPTSTR)lpstrItem;
+ if(nImageIndex != -1)
+ {
+ ins.item.mask |= TVIF_IMAGE | TVIF_SELECTEDIMAGE;
+ ins.item.iImage = nImageIndex;
+ ins.item.iSelectedImage = nImageIndex;
+ }
+ return CTreeItemT<TBase>(m_pTreeView->InsertItem(&ins), m_pTreeView);
+}
+
+template <class TBase>
+inline int CTreeItemT<TBase>::GetImageIndex() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ TVITEM item = { 0 };
+ item.mask = TVIF_HANDLE | TVIF_IMAGE;
+ item.hItem = m_hTreeItem;
+ m_pTreeView->GetItem(&item);
+ return item.iImage;
+}
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::SetInsertMark(BOOL bAfter)
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->SetInsertMark(m_hTreeItem, bAfter);
+}
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+#if (_WIN32_WINNT >= 0x0501)
+template <class TBase>
+inline UINT CTreeItemT<TBase>::MapHTREEITEMToAccID() const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->MapHTREEITEMToAccID(m_hTreeItem);
+}
+#endif // (_WIN32_WINNT >= 0x0501)
+
+#if (_WIN32_WINNT >= 0x0600)
+template <class TBase>
+inline void CTreeItemT<TBase>::ShowInfoTip()
+{
+ ATLASSERT(m_pTreeView != NULL);
+ m_pTreeView->ShowInfoTip(m_hTreeItem);
+}
+
+template <class TBase>
+inline BOOL CTreeItemT<TBase>::GetPartRect(TVITEMPART partID, LPRECT lpRect) const
+{
+ ATLASSERT(m_pTreeView != NULL);
+ return m_pTreeView->GetItemPartRect(m_hTreeItem, partID, lpRect);
+}
+#endif // (_WIN32_WINNT >= 0x0600)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CToolBarCtrl
+
+template <class TBase>
+class CToolBarCtrlT : public TBase
+{
+public:
+// Construction
+ CToolBarCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CToolBarCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return TOOLBARCLASSNAME;
+ }
+
+ BOOL IsButtonEnabled(int nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_ISBUTTONENABLED, nID, 0L);
+ }
+
+ BOOL IsButtonChecked(int nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_ISBUTTONCHECKED, nID, 0L);
+ }
+
+ BOOL IsButtonPressed(int nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_ISBUTTONPRESSED, nID, 0L);
+ }
+
+ BOOL IsButtonHidden(int nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return(BOOL) ::SendMessage(m_hWnd, TB_ISBUTTONHIDDEN, nID, 0L);
+ }
+
+ BOOL IsButtonIndeterminate(int nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_ISBUTTONINDETERMINATE, nID, 0L);
+ }
+
+ int GetState(int nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_GETSTATE, nID, 0L);
+ }
+
+ BOOL SetState(int nID, UINT nState)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETSTATE, nID, MAKELPARAM(nState, 0));
+ }
+
+ BOOL GetButton(int nIndex, LPTBBUTTON lpButton) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_GETBUTTON, nIndex, (LPARAM)lpButton);
+ }
+
+ int GetButtonCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_BUTTONCOUNT, 0, 0L);
+ }
+
+ BOOL GetItemRect(int nIndex, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_GETITEMRECT, nIndex, (LPARAM)lpRect);
+ }
+
+ void SetButtonStructSize(int nSize = sizeof(TBBUTTON))
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_BUTTONSTRUCTSIZE, nSize, 0L);
+ }
+
+ BOOL SetButtonSize(SIZE size)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETBUTTONSIZE, 0, MAKELPARAM(size.cx, size.cy));
+ }
+
+ BOOL SetButtonSize(int cx, int cy)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETBUTTONSIZE, 0, MAKELPARAM(cx, cy));
+ }
+
+ BOOL SetBitmapSize(SIZE size)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETBITMAPSIZE, 0, MAKELPARAM(size.cx, size.cy));
+ }
+
+ BOOL SetBitmapSize(int cx, int cy)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETBITMAPSIZE, 0, MAKELPARAM(cx, cy));
+ }
+
+#ifndef _WIN32_WCE
+ CToolTipCtrl GetToolTips() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CToolTipCtrl((HWND)::SendMessage(m_hWnd, TB_GETTOOLTIPS, 0, 0L));
+ }
+
+ void SetToolTips(HWND hWndToolTip)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_SETTOOLTIPS, (WPARAM)hWndToolTip, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ void SetNotifyWnd(HWND hWnd)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_SETPARENT, (WPARAM)hWnd, 0L);
+ }
+
+ int GetRows() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_GETROWS, 0, 0L);
+ }
+
+ void SetRows(int nRows, BOOL bLarger, LPRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_SETROWS, MAKELPARAM(nRows, bLarger), (LPARAM)lpRect);
+ }
+
+ BOOL SetCmdID(int nIndex, UINT nID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETCMDID, nIndex, nID);
+ }
+
+ DWORD GetBitmapFlags() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TB_GETBITMAPFLAGS, 0, 0L);
+ }
+
+ int GetBitmap(int nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_GETBITMAP, nID, 0L);
+ }
+
+ int GetButtonText(int nID, LPTSTR lpstrText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_GETBUTTONTEXT, nID, (LPARAM)lpstrText);
+ }
+
+ // nIndex - IE5 or higher only
+ CImageList GetImageList(int nIndex = 0) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TB_GETIMAGELIST, nIndex, 0L));
+ }
+
+ // nIndex - IE5 or higher only
+ CImageList SetImageList(HIMAGELIST hImageList, int nIndex = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TB_SETIMAGELIST, nIndex, (LPARAM)hImageList));
+ }
+
+ // nIndex - IE5 or higher only
+ CImageList GetDisabledImageList(int nIndex = 0) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TB_GETDISABLEDIMAGELIST, nIndex, 0L));
+ }
+
+ // nIndex - IE5 or higher only
+ CImageList SetDisabledImageList(HIMAGELIST hImageList, int nIndex = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TB_SETDISABLEDIMAGELIST, nIndex, (LPARAM)hImageList));
+ }
+
+#ifndef _WIN32_WCE
+ // nIndex - IE5 or higher only
+ CImageList GetHotImageList(int nIndex = 0) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TB_GETHOTIMAGELIST, nIndex, 0L));
+ }
+
+ // nIndex - IE5 or higher only
+ CImageList SetHotImageList(HIMAGELIST hImageList, int nIndex = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TB_SETHOTIMAGELIST, nIndex, (LPARAM)hImageList));
+ }
+#endif // !_WIN32_WCE
+
+ DWORD GetStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TB_GETSTYLE, 0, 0L);
+ }
+
+ void SetStyle(DWORD dwStyle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_SETSTYLE, 0, dwStyle);
+ }
+
+ DWORD GetButtonSize() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TB_GETBUTTONSIZE, 0, 0L);
+ }
+
+ void GetButtonSize(SIZE& size) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, TB_GETBUTTONSIZE, 0, 0L);
+ size.cx = LOWORD(dwRet);
+ size.cy = HIWORD(dwRet);
+ }
+
+ BOOL GetRect(int nID, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_GETRECT, nID, (LPARAM)lpRect);
+ }
+
+ int GetTextRows() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_GETTEXTROWS, 0, 0L);
+ }
+
+ BOOL SetButtonWidth(int cxMin, int cxMax)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETBUTTONWIDTH, 0, MAKELPARAM(cxMin, cxMax));
+ }
+
+ BOOL SetIndent(int nIndent)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETINDENT, nIndent, 0L);
+ }
+
+ BOOL SetMaxTextRows(int nMaxTextRows)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETMAXTEXTROWS, nMaxTextRows, 0L);
+ }
+
+#if (_WIN32_IE >= 0x0400)
+#ifndef _WIN32_WCE
+ BOOL GetAnchorHighlight() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_GETANCHORHIGHLIGHT, 0, 0L);
+ }
+
+ BOOL SetAnchorHighlight(BOOL bEnable = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETANCHORHIGHLIGHT, bEnable, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ int GetButtonInfo(int nID, LPTBBUTTONINFO lptbbi) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_GETBUTTONINFO, nID, (LPARAM)lptbbi);
+ }
+
+ BOOL SetButtonInfo(int nID, LPTBBUTTONINFO lptbbi)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETBUTTONINFO, nID, (LPARAM)lptbbi);
+ }
+
+ BOOL SetButtonInfo(int nID, DWORD dwMask, BYTE Style, BYTE State, LPCTSTR lpszItem,
+ int iImage, WORD cx, int iCommand, DWORD_PTR lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TBBUTTONINFO tbbi = { 0 };
+ tbbi.cbSize = sizeof(TBBUTTONINFO);
+ tbbi.dwMask = dwMask;
+ tbbi.idCommand = iCommand;
+ tbbi.iImage = iImage;
+ tbbi.fsState = State;
+ tbbi.fsStyle = Style;
+ tbbi.cx = cx;
+ tbbi.pszText = (LPTSTR) lpszItem;
+ tbbi.lParam = lParam;
+ return (BOOL)::SendMessage(m_hWnd, TB_SETBUTTONINFO, nID, (LPARAM)&tbbi);
+ }
+
+#ifndef _WIN32_WCE
+ int GetHotItem() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_GETHOTITEM, 0, 0L);
+ }
+
+ int SetHotItem(int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_SETHOTITEM, nItem, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL IsButtonHighlighted(int nButtonID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_ISBUTTONHIGHLIGHTED, nButtonID, 0L);
+ }
+
+ DWORD SetDrawTextFlags(DWORD dwMask, DWORD dwFlags)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TB_SETDRAWTEXTFLAGS, dwMask, dwFlags);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetColorScheme(LPCOLORSCHEME lpcs) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_GETCOLORSCHEME, 0, (LPARAM)lpcs);
+ }
+
+ void SetColorScheme(LPCOLORSCHEME lpcs)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_SETCOLORSCHEME, 0, (LPARAM)lpcs);
+ }
+
+ DWORD GetExtendedStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TB_GETEXTENDEDSTYLE, 0, 0L);
+ }
+
+ DWORD SetExtendedStyle(DWORD dwStyle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TB_SETEXTENDEDSTYLE, 0, dwStyle);
+ }
+
+ void GetInsertMark(LPTBINSERTMARK lptbim) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_GETINSERTMARK, 0, (LPARAM)lptbim);
+ }
+
+ void SetInsertMark(LPTBINSERTMARK lptbim)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_SETINSERTMARK, 0, (LPARAM)lptbim);
+ }
+
+ COLORREF GetInsertMarkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TB_GETINSERTMARKCOLOR, 0, 0L);
+ }
+
+ COLORREF SetInsertMarkColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, TB_SETINSERTMARKCOLOR, 0, (LPARAM)clr);
+ }
+
+ BOOL GetMaxSize(LPSIZE lpSize) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_GETMAXSIZE, 0, (LPARAM)lpSize);
+ }
+
+ void GetPadding(LPSIZE lpSizePadding) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpSizePadding != NULL);
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, TB_GETPADDING, 0, 0L);
+ lpSizePadding->cx = GET_X_LPARAM(dwRet);
+ lpSizePadding->cy = GET_Y_LPARAM(dwRet);
+ }
+
+ void SetPadding(int cx, int cy, LPSIZE lpSizePadding = NULL)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, TB_SETPADDING, 0, MAKELPARAM(cx, cy));
+ if(lpSizePadding != NULL)
+ {
+ lpSizePadding->cx = GET_X_LPARAM(dwRet);
+ lpSizePadding->cy = GET_Y_LPARAM(dwRet);
+ }
+ }
+
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // !_WIN32_WCE
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ int GetString(int nString, LPTSTR lpstrString, int cchMaxLen) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_GETSTRING, MAKEWPARAM(cchMaxLen, nString), (LPARAM)lpstrString);
+ }
+
+ int GetStringBSTR(int nString, BSTR& bstrString) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(bstrString == NULL);
+ int nLength = (int)(short)LOWORD(::SendMessage(m_hWnd, TB_GETSTRING, MAKEWPARAM(0, nString), NULL));
+ if(nLength != -1)
+ {
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrText = buff.Allocate(nLength + 1);
+ if(lpstrText != NULL)
+ {
+ nLength = (int)::SendMessage(m_hWnd, TB_GETSTRING, MAKEWPARAM(nLength + 1, nString), (LPARAM)lpstrText);
+ if(nLength != -1)
+ bstrString = ::SysAllocString(T2OLE(lpstrText));
+ }
+ else
+ {
+ nLength = -1;
+ }
+ }
+
+ return nLength;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ int GetString(int nString, _CSTRING_NS::CString& str) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nLength = (int)(short)LOWORD(::SendMessage(m_hWnd, TB_GETSTRING, MAKEWPARAM(0, nString), NULL));
+ if(nLength != -1)
+ {
+ LPTSTR lpstr = str.GetBufferSetLength(nLength + 1);
+ if(lpstr != NULL)
+ nLength = (int)::SendMessage(m_hWnd, TB_GETSTRING, MAKEWPARAM(nLength + 1, nString), (LPARAM)lpstr);
+ else
+ nLength = -1;
+ str.ReleaseBuffer();
+ }
+ return nLength;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+#if (_WIN32_WINNT >= 0x0501)
+ void GetMetrics(LPTBMETRICS lptbm) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_GETMETRICS, 0, (LPARAM)lptbm);
+ }
+
+ void SetMetrics(LPTBMETRICS lptbm)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_SETMETRICS, 0, (LPARAM)lptbm);
+ }
+
+ void SetWindowTheme(LPCWSTR lpstrTheme)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_SETWINDOWTHEME, 0, (LPARAM)lpstrTheme);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+#if (_WIN32_WINNT >= 0x0600)
+ CImageList GetPressedImageList(int nIndex = 0) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TB_GETPRESSEDIMAGELIST, nIndex, 0L));
+ }
+
+ CImageList SetPressedImageList(HIMAGELIST hImageList, int nIndex = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TB_SETPRESSEDIMAGELIST, nIndex, (LPARAM)hImageList));
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+// Operations
+ BOOL EnableButton(int nID, BOOL bEnable = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_ENABLEBUTTON, nID, MAKELPARAM(bEnable, 0));
+ }
+
+ BOOL CheckButton(int nID, BOOL bCheck = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_CHECKBUTTON, nID, MAKELPARAM(bCheck, 0));
+ }
+
+ BOOL PressButton(int nID, BOOL bPress = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_PRESSBUTTON, nID, MAKELPARAM(bPress, 0));
+ }
+
+ BOOL HideButton(int nID, BOOL bHide = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_HIDEBUTTON, nID, MAKELPARAM(bHide, 0));
+ }
+
+ BOOL Indeterminate(int nID, BOOL bIndeterminate = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_INDETERMINATE, nID, MAKELPARAM(bIndeterminate, 0));
+ }
+
+ int AddBitmap(int nNumButtons, UINT nBitmapID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TBADDBITMAP tbab = { 0 };
+ tbab.hInst = ModuleHelper::GetResourceInstance();
+ ATLASSERT(tbab.hInst != NULL);
+ tbab.nID = nBitmapID;
+ return (int)::SendMessage(m_hWnd, TB_ADDBITMAP, (WPARAM)nNumButtons, (LPARAM)&tbab);
+ }
+
+ int AddBitmap(int nNumButtons, HBITMAP hBitmap)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TBADDBITMAP tbab = { 0 };
+ tbab.hInst = NULL;
+ tbab.nID = (UINT_PTR)hBitmap;
+ return (int)::SendMessage(m_hWnd, TB_ADDBITMAP, (WPARAM)nNumButtons, (LPARAM)&tbab);
+ }
+
+ BOOL AddButtons(int nNumButtons, LPTBBUTTON lpButtons)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_ADDBUTTONS, nNumButtons, (LPARAM)lpButtons);
+ }
+
+ BOOL InsertButton(int nIndex, LPTBBUTTON lpButton)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_INSERTBUTTON, nIndex, (LPARAM)lpButton);
+ }
+
+ BOOL InsertButton(int nIndex, int iCommand, BYTE Style, BYTE State, int iBitmap,
+ INT_PTR iString, DWORD_PTR lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TBBUTTON tbb = { 0 };
+ tbb.fsStyle = Style;
+ tbb.fsState = State;
+ tbb.idCommand = iCommand;
+ tbb.iBitmap = iBitmap;
+ tbb.iString = iString;
+ tbb.dwData = lParam;
+ return (BOOL)::SendMessage(m_hWnd, TB_INSERTBUTTON, nIndex, (LPARAM)&tbb);
+ }
+
+ BOOL InsertButton(int nIndex, int iCommand, BYTE Style, BYTE State, int iBitmap,
+ LPCTSTR lpszItem, DWORD_PTR lParam)
+ {
+ return InsertButton(nIndex, iCommand, Style, State, iBitmap, (INT_PTR)lpszItem, lParam);
+ }
+
+ BOOL AddButton(LPTBBUTTON lpButton)
+ {
+ return InsertButton(-1, lpButton);
+ }
+
+ BOOL AddButton(int iCommand, BYTE Style, BYTE State, int iBitmap, INT_PTR iString, DWORD_PTR lParam)
+ {
+ return InsertButton(-1, iCommand, Style, State, iBitmap, iString, lParam);
+ }
+
+ BOOL AddButton(int iCommand, BYTE Style, BYTE State, int iBitmap, LPCTSTR lpszItem, DWORD_PTR lParam)
+ {
+ return InsertButton(-1, iCommand, Style, State, iBitmap, lpszItem, lParam);
+ }
+
+ BOOL DeleteButton(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_DELETEBUTTON, nIndex, 0L);
+ }
+
+ UINT CommandToIndex(UINT nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, TB_COMMANDTOINDEX, nID, 0L);
+ }
+
+#ifndef _WIN32_WCE
+ void SaveState(HKEY hKeyRoot, LPCTSTR lpszSubKey, LPCTSTR lpszValueName)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TBSAVEPARAMS tbs = { 0 };
+ tbs.hkr = hKeyRoot;
+ tbs.pszSubKey = lpszSubKey;
+ tbs.pszValueName = lpszValueName;
+ ::SendMessage(m_hWnd, TB_SAVERESTORE, (WPARAM)TRUE, (LPARAM)&tbs);
+ }
+
+ void RestoreState(HKEY hKeyRoot, LPCTSTR lpszSubKey, LPCTSTR lpszValueName)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TBSAVEPARAMS tbs = { 0 };
+ tbs.hkr = hKeyRoot;
+ tbs.pszSubKey = lpszSubKey;
+ tbs.pszValueName = lpszValueName;
+ ::SendMessage(m_hWnd, TB_SAVERESTORE, (WPARAM)FALSE, (LPARAM)&tbs);
+ }
+
+ void Customize()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_CUSTOMIZE, 0, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ int AddString(UINT nStringID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_ADDSTRING, (WPARAM)ModuleHelper::GetResourceInstance(), (LPARAM)nStringID);
+ }
+
+ int AddStrings(LPCTSTR lpszStrings)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_ADDSTRING, 0, (LPARAM)lpszStrings);
+ }
+
+ void AutoSize()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TB_AUTOSIZE, 0, 0L);
+ }
+
+ BOOL ChangeBitmap(int nID, int nBitmap)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_CHANGEBITMAP, nID, MAKELPARAM(nBitmap, 0));
+ }
+
+ int LoadImages(int nBitmapID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_LOADIMAGES, nBitmapID, (LPARAM)ModuleHelper::GetResourceInstance());
+ }
+
+ int LoadStdImages(int nBitmapID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_LOADIMAGES, nBitmapID, (LPARAM)HINST_COMMCTRL);
+ }
+
+ BOOL ReplaceBitmap(LPTBREPLACEBITMAP ptbrb)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_REPLACEBITMAP, 0, (LPARAM)ptbrb);
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ int HitTest(LPPOINT lpPoint) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TB_HITTEST, 0, (LPARAM)lpPoint);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL InsertMarkHitTest(LPPOINT lpPoint, LPTBINSERTMARK lptbim) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_INSERTMARKHITTEST, (WPARAM)lpPoint, (LPARAM)lptbim);
+ }
+
+ BOOL InsertMarkHitTest(int x, int y, LPTBINSERTMARK lptbim) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ POINT pt = { x, y };
+ return (BOOL)::SendMessage(m_hWnd, TB_INSERTMARKHITTEST, (WPARAM)&pt, (LPARAM)lptbim);
+ }
+
+ BOOL MapAccelerator(TCHAR chAccel, int& nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_MAPACCELERATOR, (WPARAM)chAccel, (LPARAM)&nID);
+ }
+
+ BOOL MarkButton(int nID, BOOL bHighlight = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_MARKBUTTON, nID, MAKELPARAM(bHighlight, 0));
+ }
+
+ BOOL MoveButton(int nOldPos, int nNewPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TB_MOVEBUTTON, nOldPos, nNewPos);
+ }
+
+ HRESULT GetObject(REFIID iid, LPVOID* ppvObject)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HRESULT)::SendMessage(m_hWnd, TB_GETOBJECT, (WPARAM)&iid, (LPARAM)ppvObject);
+ }
+#endif // !_WIN32_WCE
+#endif // (_WIN32_IE >= 0x0400)
+};
+
+typedef CToolBarCtrlT<ATL::CWindow> CToolBarCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CStatusBarCtrl
+
+template <class TBase>
+class CStatusBarCtrlT : public TBase
+{
+public:
+// Constructors
+ CStatusBarCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CStatusBarCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Methods
+ static LPCTSTR GetWndClassName()
+ {
+ return STATUSCLASSNAME;
+ }
+
+ int GetParts(int nParts, int* pParts) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, SB_GETPARTS, nParts, (LPARAM)pParts);
+ }
+
+ BOOL SetParts(int nParts, int* pWidths)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, SB_SETPARTS, nParts, (LPARAM)pWidths);
+ }
+
+ int GetTextLength(int nPane, int* pType = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, SB_GETTEXTLENGTH, (WPARAM)nPane, 0L);
+ if (pType != NULL)
+ *pType = (int)(short)HIWORD(dwRet);
+ return (int)(short)LOWORD(dwRet);
+ }
+
+ int GetText(int nPane, LPTSTR lpszText, int* pType = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, SB_GETTEXT, (WPARAM)nPane, (LPARAM)lpszText);
+ if(pType != NULL)
+ *pType = (int)(short)HIWORD(dwRet);
+ return (int)(short)LOWORD(dwRet);
+ }
+
+#ifndef _ATL_NO_COM
+ BOOL GetTextBSTR(int nPane, BSTR& bstrText, int* pType = NULL) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ ATLASSERT(bstrText == NULL);
+ int nLength = (int)(short)LOWORD(::SendMessage(m_hWnd, SB_GETTEXTLENGTH, (WPARAM)nPane, 0L));
+ if(nLength == 0)
+ return FALSE;
+
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrText = buff.Allocate(nLength + 1);
+ if(lpstrText == NULL)
+ return FALSE;
+
+ if(!GetText(nPane, lpstrText, pType))
+ return FALSE;
+
+ bstrText = ::SysAllocString(T2OLE(lpstrText));
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ int GetText(int nPane, _CSTRING_NS::CString& strText, int* pType = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ int nLength = (int)(short)LOWORD(::SendMessage(m_hWnd, SB_GETTEXTLENGTH, (WPARAM)nPane, 0L));
+ if(nLength == 0)
+ return 0;
+
+ LPTSTR lpstr = strText.GetBufferSetLength(nLength);
+ if(lpstr == NULL)
+ return 0;
+ return GetText(nPane, lpstr, pType);
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ BOOL SetText(int nPane, LPCTSTR lpszText, int nType = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ return (BOOL)::SendMessage(m_hWnd, SB_SETTEXT, (nPane | nType), (LPARAM)lpszText);
+ }
+
+ BOOL GetRect(int nPane, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ return (BOOL)::SendMessage(m_hWnd, SB_GETRECT, nPane, (LPARAM)lpRect);
+ }
+
+ BOOL GetBorders(int* pBorders) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, SB_GETBORDERS, 0, (LPARAM)pBorders);
+ }
+
+ BOOL GetBorders(int& nHorz, int& nVert, int& nSpacing) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int borders[3] = { 0, 0, 0 };
+ BOOL bResult = (BOOL)::SendMessage(m_hWnd, SB_GETBORDERS, 0, (LPARAM)&borders);
+ if(bResult)
+ {
+ nHorz = borders[0];
+ nVert = borders[1];
+ nSpacing = borders[2];
+ }
+ return bResult;
+ }
+
+ void SetMinHeight(int nMin)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, SB_SETMINHEIGHT, nMin, 0L);
+ }
+
+ BOOL SetSimple(BOOL bSimple = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, SB_SIMPLE, bSimple, 0L);
+ }
+
+ BOOL IsSimple() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, SB_ISSIMPLE, 0, 0L);
+ }
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, SB_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, SB_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+
+ void GetTipText(int nPane, LPTSTR lpstrText, int nSize) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ ::SendMessage(m_hWnd, SB_GETTIPTEXT, MAKEWPARAM(nPane, nSize), (LPARAM)lpstrText);
+ }
+
+ void SetTipText(int nPane, LPCTSTR lpstrText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ ::SendMessage(m_hWnd, SB_SETTIPTEXT, nPane, (LPARAM)lpstrText);
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+#if ((_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 0x0500))
+ COLORREF SetBkColor(COLORREF clrBk)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, SB_SETBKCOLOR, 0, (LPARAM)clrBk);
+ }
+
+ HICON GetIcon(int nPane) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ return (HICON)::SendMessage(m_hWnd, SB_GETICON, nPane, 0L);
+ }
+
+ BOOL SetIcon(int nPane, HICON hIcon)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPane < 256);
+ return (BOOL)::SendMessage(m_hWnd, SB_SETICON, nPane, (LPARAM)hIcon);
+ }
+#endif // ((_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 0x0500))
+};
+
+typedef CStatusBarCtrlT<ATL::CWindow> CStatusBarCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTabCtrl
+
+template <class TBase>
+class CTabCtrlT : public TBase
+{
+public:
+// Constructors
+ CTabCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CTabCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_TABCONTROL;
+ }
+
+ CImageList GetImageList() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TCM_GETIMAGELIST, 0, 0L));
+ }
+
+ CImageList SetImageList(HIMAGELIST hImageList)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, TCM_SETIMAGELIST, 0, (LPARAM)hImageList));
+ }
+
+ int GetItemCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TCM_GETITEMCOUNT, 0, 0L);
+ }
+
+ BOOL GetItem(int nItem, LPTCITEM pTabCtrlItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TCM_GETITEM, nItem, (LPARAM)pTabCtrlItem);
+ }
+
+ BOOL SetItem(int nItem, LPTCITEM pTabCtrlItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TCM_SETITEM, nItem, (LPARAM)pTabCtrlItem);
+ }
+
+ int SetItem(int nItem, UINT mask, LPCTSTR lpszItem, DWORD dwState, DWORD dwStateMask, int iImage, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TCITEM tci = { 0 };
+ tci.mask = mask;
+ tci.pszText = (LPTSTR) lpszItem;
+ tci.dwState = dwState;
+ tci.dwStateMask = dwStateMask;
+ tci.iImage = iImage;
+ tci.lParam = lParam;
+ return (int)::SendMessage(m_hWnd, TCM_SETITEM, nItem, (LPARAM)&tci);
+ }
+
+ BOOL GetItemRect(int nItem, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TCM_GETITEMRECT, nItem, (LPARAM)lpRect);
+ }
+
+ int GetCurSel() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TCM_GETCURSEL, 0, 0L);
+ }
+
+ int SetCurSel(int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TCM_SETCURSEL, nItem, 0L);
+ }
+
+ SIZE SetItemSize(SIZE size)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwSize = (DWORD)::SendMessage(m_hWnd, TCM_SETITEMSIZE, 0, MAKELPARAM(size.cx, size.cy));
+ SIZE sizeRet = { GET_X_LPARAM(dwSize), GET_Y_LPARAM(dwSize) };
+ return sizeRet;
+ }
+
+ void SetItemSize(int cx, int cy)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TCM_SETITEMSIZE, 0, MAKELPARAM(cx, cy));
+ }
+
+ void SetPadding(SIZE size)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TCM_SETPADDING, 0, MAKELPARAM(size.cx, size.cy));
+ }
+
+ int GetRowCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TCM_GETROWCOUNT, 0, 0L);
+ }
+
+#ifndef _WIN32_WCE
+ CToolTipCtrl GetTooltips() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CToolTipCtrl((HWND)::SendMessage(m_hWnd, TCM_GETTOOLTIPS, 0, 0L));
+ }
+
+ void SetTooltips(HWND hWndToolTip)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TCM_SETTOOLTIPS, (WPARAM)hWndToolTip, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ int GetCurFocus() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TCM_GETCURFOCUS, 0, 0L);
+ }
+
+ void SetCurFocus(int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TCM_SETCURFOCUS, nItem, 0L);
+ }
+
+ BOOL SetItemExtra(int cbExtra)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetItemCount() == 0); // must be empty
+ return (BOOL)::SendMessage(m_hWnd, TCM_SETITEMEXTRA, cbExtra, 0L);
+ }
+
+ int SetMinTabWidth(int nWidth = -1)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TCM_SETMINTABWIDTH, 0, nWidth);
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ DWORD GetExtendedStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TCM_GETEXTENDEDSTYLE, 0, 0L);
+ }
+
+ DWORD SetExtendedStyle(DWORD dwExMask, DWORD dwExStyle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, TCM_SETEXTENDEDSTYLE, dwExMask, dwExStyle);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TCM_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TCM_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // !_WIN32_WCE
+#endif // (_WIN32_IE >= 0x0400)
+
+// Operations
+ int InsertItem(int nItem, LPTCITEM pTabCtrlItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TCM_INSERTITEM, nItem, (LPARAM)pTabCtrlItem);
+ }
+
+ int InsertItem(int nItem, UINT mask, LPCTSTR lpszItem, int iImage, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TCITEM tci = { 0 };
+ tci.mask = mask;
+ tci.pszText = (LPTSTR) lpszItem;
+ tci.iImage = iImage;
+ tci.lParam = lParam;
+ return (int)::SendMessage(m_hWnd, TCM_INSERTITEM, nItem, (LPARAM)&tci);
+ }
+
+ int InsertItem(int nItem, LPCTSTR lpszItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TCITEM tci = { 0 };
+ tci.mask = TCIF_TEXT;
+ tci.pszText = (LPTSTR) lpszItem;
+ return (int)::SendMessage(m_hWnd, TCM_INSERTITEM, nItem, (LPARAM)&tci);
+ }
+
+ int AddItem(LPTCITEM pTabCtrlItem)
+ {
+ return InsertItem(GetItemCount(), pTabCtrlItem);
+ }
+
+ int AddItem(UINT mask, LPCTSTR lpszItem, int iImage, LPARAM lParam)
+ {
+ return InsertItem(GetItemCount(), mask, lpszItem, iImage, lParam);
+ }
+
+ int AddItem(LPCTSTR lpszItem)
+ {
+ return InsertItem(GetItemCount(), lpszItem);
+ }
+
+ BOOL DeleteItem(int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TCM_DELETEITEM, nItem, 0L);
+ }
+
+ BOOL DeleteAllItems()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TCM_DELETEALLITEMS, 0, 0L);
+ }
+
+ void AdjustRect(BOOL bLarger, LPRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TCM_ADJUSTRECT, bLarger, (LPARAM)lpRect);
+ }
+
+ void RemoveImage(int nImage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TCM_REMOVEIMAGE, nImage, 0L);
+ }
+
+ int HitTest(TC_HITTESTINFO* pHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TCM_HITTEST, 0, (LPARAM)pHitTestInfo);
+ }
+
+ void DeselectAll(BOOL bExcludeFocus = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TCM_DESELECTALL, bExcludeFocus, 0L);
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ BOOL HighlightItem(int nIndex, BOOL bHighlight = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TCM_HIGHLIGHTITEM, nIndex, MAKELPARAM(bHighlight, 0));
+ }
+#endif // (_WIN32_IE >= 0x0400)
+};
+
+typedef CTabCtrlT<ATL::CWindow> CTabCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTrackBarCtrl
+
+template <class TBase>
+class CTrackBarCtrlT : public TBase
+{
+public:
+// Constructors
+ CTrackBarCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CTrackBarCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return TRACKBAR_CLASS;
+ }
+
+ int GetLineSize() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETLINESIZE, 0, 0L);
+ }
+
+ int SetLineSize(int nSize)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_SETLINESIZE, 0, nSize);
+ }
+
+ int GetPageSize() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETPAGESIZE, 0, 0L);
+ }
+
+ int SetPageSize(int nSize)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_SETPAGESIZE, 0, nSize);
+ }
+
+ int GetRangeMin() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETRANGEMIN, 0, 0L);
+ }
+
+ void SetRangeMin(int nMin, BOOL bRedraw = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETRANGEMIN, bRedraw, nMin);
+ }
+
+ int GetRangeMax() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETRANGEMAX, 0, 0L);
+ }
+
+ void SetRangeMax(int nMax, BOOL bRedraw = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETRANGEMAX, bRedraw, nMax);
+ }
+
+ void GetRange(int& nMin, int& nMax) const
+ {
+ nMin = GetRangeMin();
+ nMax = GetRangeMax();
+ }
+
+ void SetRange(int nMin, int nMax, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETRANGE, bRedraw, MAKELPARAM(nMin, nMax));
+ }
+
+ int GetSelStart() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETSELSTART, 0, 0L);
+ }
+
+ void SetSelStart(int nMin)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETSELSTART, 0, (LPARAM)nMin);
+ }
+
+ int GetSelEnd() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETSELEND, 0, 0L);
+ }
+
+ void SetSelEnd(int nMax)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETSELEND, 0, (LPARAM)nMax);
+ }
+
+ void GetSelection(int& nMin, int& nMax) const
+ {
+ nMin = GetSelStart();
+ nMax = GetSelEnd();
+ }
+
+ void SetSelection(int nMin, int nMax)
+ {
+ SetSelStart(nMin);
+ SetSelEnd(nMax);
+ }
+
+ void GetChannelRect(LPRECT lprc) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_GETCHANNELRECT, 0, (LPARAM)lprc);
+ }
+
+ void GetThumbRect(LPRECT lprc) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_GETTHUMBRECT, 0, (LPARAM)lprc);
+ }
+
+ int GetPos() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETPOS, 0, 0L);
+ }
+
+ void SetPos(int nPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETPOS, TRUE, nPos);
+ }
+
+ UINT GetNumTics() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, TBM_GETNUMTICS, 0, 0L);
+ }
+
+ DWORD* GetTicArray() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD*)::SendMessage(m_hWnd, TBM_GETPTICS, 0, 0L);
+ }
+
+ int GetTic(int nTic) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETTIC, nTic, 0L);
+ }
+
+ BOOL SetTic(int nTic)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TBM_SETTIC, 0, nTic);
+ }
+
+ int GetTicPos(int nTic) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETTICPOS, nTic, 0L);
+ }
+
+ void SetTicFreq(int nFreq)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETTICFREQ, nFreq, 0L);
+ }
+
+ int GetThumbLength() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_GETTHUMBLENGTH, 0, 0L);
+ }
+
+ void SetThumbLength(int nLength)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETTHUMBLENGTH, nLength, 0L);
+ }
+
+ void SetSel(int nStart, int nEnd, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & TBS_ENABLESELRANGE) != 0);
+ ::SendMessage(m_hWnd, TBM_SETSEL, bRedraw, MAKELPARAM(nStart, nEnd));
+ }
+
+ ATL::CWindow GetBuddy(BOOL bLeft = TRUE) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ATL::CWindow((HWND)::SendMessage(m_hWnd, TBM_GETBUDDY, bLeft, 0L));
+ }
+
+ ATL::CWindow SetBuddy(HWND hWndBuddy, BOOL bLeft = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ATL::CWindow((HWND)::SendMessage(m_hWnd, TBM_SETBUDDY, bLeft, (LPARAM)hWndBuddy));
+ }
+
+#ifndef _WIN32_WCE
+ CToolTipCtrl GetToolTips() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CToolTipCtrl((HWND)::SendMessage(m_hWnd, TBM_GETTOOLTIPS, 0, 0L));
+ }
+
+ void SetToolTips(HWND hWndTT)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETTOOLTIPS, (WPARAM)hWndTT, 0L);
+ }
+
+ int SetTipSide(int nSide)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, TBM_SETTIPSIDE, nSide, 0L);
+ }
+#endif // !_WIN32_WCE
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TBM_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, TBM_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+// Operations
+ void ClearSel(BOOL bRedraw = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_CLEARSEL, bRedraw, 0L);
+ }
+
+ void VerifyPos()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_SETPOS, FALSE, 0L);
+ }
+
+ void ClearTics(BOOL bRedraw = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, TBM_CLEARTICS, bRedraw, 0L);
+ }
+};
+
+typedef CTrackBarCtrlT<ATL::CWindow> CTrackBarCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CUpDownCtrl
+
+template <class TBase>
+class CUpDownCtrlT : public TBase
+{
+public:
+// Constructors
+ CUpDownCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CUpDownCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return UPDOWN_CLASS;
+ }
+
+ UINT GetAccel(int nAccel, UDACCEL* pAccel) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)LOWORD(::SendMessage(m_hWnd, UDM_GETACCEL, nAccel, (LPARAM)pAccel));
+ }
+
+ BOOL SetAccel(int nAccel, UDACCEL* pAccel)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)LOWORD(::SendMessage(m_hWnd, UDM_SETACCEL, nAccel, (LPARAM)pAccel));
+ }
+
+ UINT GetBase() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)LOWORD(::SendMessage(m_hWnd, UDM_GETBASE, 0, 0L));
+ }
+
+ int SetBase(int nBase)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, UDM_SETBASE, nBase, 0L);
+ }
+
+ ATL::CWindow GetBuddy() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ATL::CWindow((HWND)::SendMessage(m_hWnd, UDM_GETBUDDY, 0, 0L));
+ }
+
+ ATL::CWindow SetBuddy(HWND hWndBuddy)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ATL::CWindow((HWND)::SendMessage(m_hWnd, UDM_SETBUDDY, (WPARAM)hWndBuddy, 0L));
+ }
+
+ int GetPos(LPBOOL lpbError = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, UDM_GETPOS, 0, 0L);
+ // Note: Seems that Windows always sets error to TRUE if
+ // UDS_SETBUDDYINT style is not used
+ if(lpbError != NULL)
+ *lpbError = (HIWORD(dwRet) != 0) ? TRUE : FALSE;
+ return (int)(short)LOWORD(dwRet);
+ }
+
+ int SetPos(int nPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)(short)LOWORD(::SendMessage(m_hWnd, UDM_SETPOS, 0, MAKELPARAM(nPos, 0)));
+ }
+
+ DWORD GetRange() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, UDM_GETRANGE, 0, 0L);
+ }
+
+ void GetRange(int& nLower, int& nUpper) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, UDM_GETRANGE, 0, 0L);
+ nLower = (int)(short)HIWORD(dwRet);
+ nUpper = (int)(short)LOWORD(dwRet);
+ }
+
+ void SetRange(int nLower, int nUpper)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, UDM_SETRANGE, 0, MAKELPARAM(nUpper, nLower));
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ void SetRange32(int nLower, int nUpper)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, UDM_SETRANGE32, nLower, nUpper);
+ }
+
+ void GetRange32(int& nLower, int& nUpper) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, UDM_GETRANGE32, (WPARAM)&nLower, (LPARAM)&nUpper);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, UDM_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, UDM_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // !_WIN32_WCE
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ int GetPos32(LPBOOL lpbError = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ // Note: Seems that Windows always sets error to TRUE if
+ // UDS_SETBUDDYINT style is not used
+ return (int)::SendMessage(m_hWnd, UDM_GETPOS32, 0, (LPARAM)lpbError);
+ }
+
+ int SetPos32(int nPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, UDM_SETPOS32, 0, (LPARAM)nPos);
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+};
+
+typedef CUpDownCtrlT<ATL::CWindow> CUpDownCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CProgressBarCtrl
+
+template <class TBase>
+class CProgressBarCtrlT : public TBase
+{
+public:
+// Constructors
+ CProgressBarCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CProgressBarCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return PROGRESS_CLASS;
+ }
+
+ DWORD SetRange(int nLower, int nUpper)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, PBM_SETRANGE, 0, MAKELPARAM(nLower, nUpper));
+ }
+
+ int SetPos(int nPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)(short)LOWORD(::SendMessage(m_hWnd, PBM_SETPOS, nPos, 0L));
+ }
+
+ int OffsetPos(int nPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)(short)LOWORD(::SendMessage(m_hWnd, PBM_DELTAPOS, nPos, 0L));
+ }
+
+ int SetStep(int nStep)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)(short)LOWORD(::SendMessage(m_hWnd, PBM_SETSTEP, nStep, 0L));
+ }
+
+ UINT GetPos() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, PBM_GETPOS, 0, 0L);
+ }
+
+ void GetRange(PPBRANGE pPBRange) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pPBRange != NULL);
+ ::SendMessage(m_hWnd, PBM_GETRANGE, TRUE, (LPARAM)pPBRange);
+ }
+
+ void GetRange(int& nLower, int& nUpper) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ PBRANGE range = { 0 };
+ ::SendMessage(m_hWnd, PBM_GETRANGE, TRUE, (LPARAM)&range);
+ nLower = range.iLow;
+ nUpper = range.iHigh;
+ }
+
+ int GetRangeLimit(BOOL bLowLimit) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PBM_GETRANGE, bLowLimit, (LPARAM)NULL);
+ }
+
+ DWORD SetRange32(int nMin, int nMax)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, PBM_SETRANGE32, nMin, nMax);
+ }
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ COLORREF SetBarColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, PBM_SETBARCOLOR, 0, (LPARAM)clr);
+ }
+
+ COLORREF SetBkColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, PBM_SETBKCOLOR, 0, (LPARAM)clr);
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+#if (_WIN32_WINNT >= 0x0501) && defined(PBM_SETMARQUEE)
+ BOOL SetMarquee(BOOL bMarquee, UINT uUpdateTime = 0U)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, PBM_SETMARQUEE, (WPARAM)bMarquee, (LPARAM)uUpdateTime);
+ }
+#endif // (_WIN32_WINNT >= 0x0501) && defined(PBM_SETMARQUEE)
+
+#if (_WIN32_WINNT >= 0x0600)
+ int GetStep() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PBM_GETSTEP, 0, 0L);
+ }
+
+ COLORREF GetBkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, PBM_GETBKCOLOR, 0, 0L);
+ }
+
+ COLORREF GetBarColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, PBM_GETBARCOLOR, 0, 0L);
+ }
+
+ int GetState() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PBM_GETSTATE, 0, 0L);
+ }
+
+ int SetState(int nState)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PBM_SETSTATE, nState, 0L);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+// Operations
+ int StepIt()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)(short)LOWORD(::SendMessage(m_hWnd, PBM_STEPIT, 0, 0L));
+ }
+};
+
+typedef CProgressBarCtrlT<ATL::CWindow> CProgressBarCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CHotKeyCtrl
+
+#ifndef _WIN32_WCE
+
+template <class TBase>
+class CHotKeyCtrlT : public TBase
+{
+public:
+// Constructors
+ CHotKeyCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CHotKeyCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return HOTKEY_CLASS;
+ }
+
+ DWORD GetHotKey() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, HKM_GETHOTKEY, 0, 0L);
+ }
+
+ void GetHotKey(WORD &wVirtualKeyCode, WORD &wModifiers) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dw = (DWORD)::SendMessage(m_hWnd, HKM_GETHOTKEY, 0, 0L);
+ wVirtualKeyCode = LOBYTE(LOWORD(dw));
+ wModifiers = HIBYTE(LOWORD(dw));
+ }
+
+ void SetHotKey(WORD wVirtualKeyCode, WORD wModifiers)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, HKM_SETHOTKEY, MAKEWORD(wVirtualKeyCode, wModifiers), 0L);
+ }
+
+ void SetRules(WORD wInvalidComb, WORD wModifiers)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, HKM_SETRULES, wInvalidComb, MAKELPARAM(wModifiers, 0));
+ }
+};
+
+typedef CHotKeyCtrlT<ATL::CWindow> CHotKeyCtrl;
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAnimateCtrl
+
+#ifndef _WIN32_WCE
+
+template <class TBase>
+class CAnimateCtrlT : public TBase
+{
+public:
+// Constructors
+ CAnimateCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CAnimateCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return ANIMATE_CLASS;
+ }
+
+// Operations
+ BOOL Open(ATL::_U_STRINGorID FileName)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, ACM_OPEN, 0, (LPARAM)FileName.m_lpstr);
+ }
+
+ BOOL Play(UINT nFrom, UINT nTo, UINT nRep)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, ACM_PLAY, nRep, MAKELPARAM(nFrom, nTo));
+ }
+
+ BOOL Stop()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, ACM_STOP, 0, 0L);
+ }
+
+ BOOL Close()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, ACM_OPEN, 0, 0L);
+ }
+
+ BOOL Seek(UINT nTo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, ACM_PLAY, 0, MAKELPARAM(nTo, nTo));
+ }
+
+ // Vista only
+ BOOL IsPlaying() const
+ {
+#ifndef ACM_ISPLAYING
+ const UINT ACM_ISPLAYING = (WM_USER+104);
+#endif
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, ACM_ISPLAYING, 0, 0L);
+ }
+};
+
+typedef CAnimateCtrlT<ATL::CWindow> CAnimateCtrl;
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRichEditCtrl
+
+#ifndef _WIN32_WCE
+
+#ifdef _UNICODE
+#if (_RICHEDIT_VER == 0x0100)
+#undef RICHEDIT_CLASS
+#define RICHEDIT_CLASS L"RICHEDIT"
+#endif // (_RICHEDIT_VER == 0x0100)
+#endif // _UNICODE
+
+template <class TBase>
+class CRichEditCtrlT : public TBase
+{
+public:
+// Constructors
+ CRichEditCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CRichEditCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return RICHEDIT_CLASS;
+ }
+
+ static LPCTSTR GetLibraryName()
+ {
+#if (_RICHEDIT_VER >= 0x0200)
+ return _T("RICHED20.DLL");
+#else
+ return _T("RICHED32.DLL");
+#endif
+ }
+
+ int GetLineCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETLINECOUNT, 0, 0L);
+ }
+
+ BOOL GetModify() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_GETMODIFY, 0, 0L);
+ }
+
+ void SetModify(BOOL bModified = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETMODIFY, bModified, 0L);
+ }
+
+ void GetRect(LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_GETRECT, 0, (LPARAM)lpRect);
+ }
+
+ DWORD GetOptions() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, EM_GETOPTIONS, 0, 0L);
+ }
+
+ DWORD SetOptions(WORD wOperation, DWORD dwOptions)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, EM_SETOPTIONS, wOperation, dwOptions);
+ }
+
+ // NOTE: first word in lpszBuffer must contain the size of the buffer!
+ int GetLine(int nIndex, LPTSTR lpszBuffer) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETLINE, nIndex, (LPARAM)lpszBuffer);
+ }
+
+ int GetLine(int nIndex, LPTSTR lpszBuffer, int nMaxLength) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ *(LPWORD)lpszBuffer = (WORD)nMaxLength;
+ return (int)::SendMessage(m_hWnd, EM_GETLINE, nIndex, (LPARAM)lpszBuffer);
+ }
+
+ BOOL CanUndo() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_CANUNDO, 0, 0L);
+ }
+
+ BOOL CanPaste(UINT nFormat = 0) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_CANPASTE, nFormat, 0L);
+ }
+
+ void GetSel(LONG& nStartChar, LONG& nEndChar) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ CHARRANGE cr = { 0, 0 };
+ ::SendMessage(m_hWnd, EM_EXGETSEL, 0, (LPARAM)&cr);
+ nStartChar = cr.cpMin;
+ nEndChar = cr.cpMax;
+ }
+
+ void GetSel(CHARRANGE &cr) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_EXGETSEL, 0, (LPARAM)&cr);
+ }
+
+ int SetSel(LONG nStartChar, LONG nEndChar)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ CHARRANGE cr = { nStartChar, nEndChar };
+ return (int)::SendMessage(m_hWnd, EM_EXSETSEL, 0, (LPARAM)&cr);
+ }
+
+ int SetSel(CHARRANGE &cr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_EXSETSEL, 0, (LPARAM)&cr);
+ }
+
+ int SetSelAll()
+ {
+ return SetSel(0, -1);
+ }
+
+ int SetSelNone()
+ {
+ return SetSel(-1, 0);
+ }
+
+ DWORD GetDefaultCharFormat(CHARFORMAT& cf) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT);
+ return (DWORD)::SendMessage(m_hWnd, EM_GETCHARFORMAT, 0, (LPARAM)&cf);
+ }
+
+ DWORD GetSelectionCharFormat(CHARFORMAT& cf) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT);
+ return (DWORD)::SendMessage(m_hWnd, EM_GETCHARFORMAT, 1, (LPARAM)&cf);
+ }
+
+ DWORD GetEventMask() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, EM_GETEVENTMASK, 0, 0L);
+ }
+
+ LONG GetLimitText() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_GETLIMITTEXT, 0, 0L);
+ }
+
+ DWORD GetParaFormat(PARAFORMAT& pf) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ pf.cbSize = sizeof(PARAFORMAT);
+ return (DWORD)::SendMessage(m_hWnd, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
+ }
+
+#if (_RICHEDIT_VER >= 0x0200)
+ LONG GetSelText(LPTSTR lpstrBuff) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_GETSELTEXT, 0, (LPARAM)lpstrBuff);
+ }
+#else // !(_RICHEDIT_VER >= 0x0200)
+ // RichEdit 1.0 EM_GETSELTEXT is ANSI only
+ LONG GetSelText(LPSTR lpstrBuff) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_GETSELTEXT, 0, (LPARAM)lpstrBuff);
+ }
+#endif // !(_RICHEDIT_VER >= 0x0200)
+
+#ifndef _ATL_NO_COM
+ BOOL GetSelTextBSTR(BSTR& bstrText) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(bstrText == NULL);
+
+ CHARRANGE cr = { 0, 0 };
+ ::SendMessage(m_hWnd, EM_EXGETSEL, 0, (LPARAM)&cr);
+
+#if (_RICHEDIT_VER >= 0x0200)
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrText = buff.Allocate(cr.cpMax - cr.cpMin + 1);
+ if(lpstrText == NULL)
+ return FALSE;
+ if(::SendMessage(m_hWnd, EM_GETSELTEXT, 0, (LPARAM)lpstrText) == 0)
+ return FALSE;
+
+ bstrText = ::SysAllocString(T2W(lpstrText));
+#else // !(_RICHEDIT_VER >= 0x0200)
+ CTempBuffer<char, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPSTR lpstrText = buff.Allocate(cr.cpMax - cr.cpMin + 1);
+ if(lpstrText == NULL)
+ return FALSE;
+ if(::SendMessage(m_hWnd, EM_GETSELTEXT, 0, (LPARAM)lpstrText) == 0)
+ return FALSE;
+
+ bstrText = ::SysAllocString(A2W(lpstrText));
+#endif // !(_RICHEDIT_VER >= 0x0200)
+
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ LONG GetSelText(_CSTRING_NS::CString& strText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ CHARRANGE cr = { 0, 0 };
+ ::SendMessage(m_hWnd, EM_EXGETSEL, 0, (LPARAM)&cr);
+
+#if (_RICHEDIT_VER >= 0x0200)
+ LONG lLen = 0;
+ LPTSTR lpstrText = strText.GetBufferSetLength(cr.cpMax - cr.cpMin);
+ if(lpstrText != NULL)
+ {
+ lLen = (LONG)::SendMessage(m_hWnd, EM_GETSELTEXT, 0, (LPARAM)lpstrText);
+ strText.ReleaseBuffer();
+ }
+#else // !(_RICHEDIT_VER >= 0x0200)
+ CTempBuffer<char, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPSTR lpstrText = buff.Allocate(cr.cpMax - cr.cpMin + 1);
+ if(lpstrText == NULL)
+ return 0;
+ LONG lLen = (LONG)::SendMessage(m_hWnd, EM_GETSELTEXT, 0, (LPARAM)lpstrText);
+ if(lLen == 0)
+ return 0;
+
+ USES_CONVERSION;
+ strText = A2T(lpstrText);
+#endif // !(_RICHEDIT_VER >= 0x0200)
+
+ return lLen;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ WORD GetSelectionType() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (WORD)::SendMessage(m_hWnd, EM_SELECTIONTYPE, 0, 0L);
+ }
+
+ COLORREF SetBackgroundColor(COLORREF cr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, EM_SETBKGNDCOLOR, 0, cr);
+ }
+
+ COLORREF SetBackgroundColor() // sets to system background
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, EM_SETBKGNDCOLOR, 1, 0);
+ }
+
+ BOOL SetCharFormat(CHARFORMAT& cf, WORD wFlags)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCHARFORMAT, (WPARAM)wFlags, (LPARAM)&cf);
+ }
+
+ BOOL SetDefaultCharFormat(CHARFORMAT& cf)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCHARFORMAT, 0, (LPARAM)&cf);
+ }
+
+ BOOL SetSelectionCharFormat(CHARFORMAT& cf)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf);
+ }
+
+ BOOL SetWordCharFormat(CHARFORMAT& cf)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCHARFORMAT, SCF_SELECTION | SCF_WORD, (LPARAM)&cf);
+ }
+
+ DWORD SetEventMask(DWORD dwEventMask)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, EM_SETEVENTMASK, 0, dwEventMask);
+ }
+
+ BOOL SetParaFormat(PARAFORMAT& pf)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ pf.cbSize = sizeof(PARAFORMAT);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
+ }
+
+ BOOL SetTargetDevice(HDC hDC, int cxLineWidth)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETTARGETDEVICE, (WPARAM)hDC, cxLineWidth);
+ }
+
+ int GetTextLength() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, WM_GETTEXTLENGTH, 0, 0L);
+ }
+
+ BOOL SetReadOnly(BOOL bReadOnly = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETREADONLY, bReadOnly, 0L);
+ }
+
+ int GetFirstVisibleLine() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETFIRSTVISIBLELINE, 0, 0L);
+ }
+
+ EDITWORDBREAKPROCEX GetWordBreakProcEx() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (EDITWORDBREAKPROCEX)::SendMessage(m_hWnd, EM_GETWORDBREAKPROCEX, 0, 0L);
+ }
+
+ EDITWORDBREAKPROCEX SetWordBreakProcEx(EDITWORDBREAKPROCEX pfnEditWordBreakProcEx)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (EDITWORDBREAKPROCEX)::SendMessage(m_hWnd, EM_SETWORDBREAKPROCEX, 0, (LPARAM)pfnEditWordBreakProcEx);
+ }
+
+ int GetTextRange(TEXTRANGE* pTextRange) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETTEXTRANGE, 0, (LPARAM)pTextRange);
+ }
+
+#if (_RICHEDIT_VER >= 0x0200)
+ int GetTextRange(LONG nStartChar, LONG nEndChar, LPTSTR lpstrText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TEXTRANGE tr = { 0 };
+ tr.chrg.cpMin = nStartChar;
+ tr.chrg.cpMax = nEndChar;
+ tr.lpstrText = lpstrText;
+ return (int)::SendMessage(m_hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
+ }
+#else // !(_RICHEDIT_VER >= 0x0200)
+
+ int GetTextRange(LONG nStartChar, LONG nEndChar, LPSTR lpstrText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ TEXTRANGE tr = { 0 };
+ tr.chrg.cpMin = nStartChar;
+ tr.chrg.cpMax = nEndChar;
+ tr.lpstrText = lpstrText;
+ return (int)::SendMessage(m_hWnd, EM_GETTEXTRANGE, 0, (LPARAM)&tr);
+ }
+#endif // !(_RICHEDIT_VER >= 0x0200)
+
+#if (_RICHEDIT_VER >= 0x0200)
+ DWORD GetDefaultCharFormat(CHARFORMAT2& cf) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT2);
+ return (DWORD)::SendMessage(m_hWnd, EM_GETCHARFORMAT, 0, (LPARAM)&cf);
+ }
+
+ BOOL SetCharFormat(CHARFORMAT2& cf, WORD wFlags)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT2);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCHARFORMAT, (WPARAM)wFlags, (LPARAM)&cf);
+ }
+
+ BOOL SetDefaultCharFormat(CHARFORMAT2& cf)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT2);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCHARFORMAT, 0, (LPARAM)&cf);
+ }
+
+ DWORD GetSelectionCharFormat(CHARFORMAT2& cf) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT2);
+ return (DWORD)::SendMessage(m_hWnd, EM_GETCHARFORMAT, 1, (LPARAM)&cf);
+ }
+
+ BOOL SetSelectionCharFormat(CHARFORMAT2& cf)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT2);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf);
+ }
+
+ BOOL SetWordCharFormat(CHARFORMAT2& cf)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ cf.cbSize = sizeof(CHARFORMAT2);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETCHARFORMAT, SCF_SELECTION | SCF_WORD, (LPARAM)&cf);
+ }
+
+ DWORD GetParaFormat(PARAFORMAT2& pf) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ pf.cbSize = sizeof(PARAFORMAT2);
+ return (DWORD)::SendMessage(m_hWnd, EM_GETPARAFORMAT, 0, (LPARAM)&pf);
+ }
+
+ BOOL SetParaFormat(PARAFORMAT2& pf)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ pf.cbSize = sizeof(PARAFORMAT2);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
+ }
+
+ TEXTMODE GetTextMode() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (TEXTMODE)::SendMessage(m_hWnd, EM_GETTEXTMODE, 0, 0L);
+ }
+
+ BOOL SetTextMode(TEXTMODE enumTextMode)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return !(BOOL)::SendMessage(m_hWnd, EM_SETTEXTMODE, enumTextMode, 0L);
+ }
+
+ UNDONAMEID GetUndoName() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UNDONAMEID)::SendMessage(m_hWnd, EM_GETUNDONAME, 0, 0L);
+ }
+
+ UNDONAMEID GetRedoName() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UNDONAMEID)::SendMessage(m_hWnd, EM_GETREDONAME, 0, 0L);
+ }
+
+ BOOL CanRedo() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_CANREDO, 0, 0L);
+ }
+
+ BOOL GetAutoURLDetect() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_GETAUTOURLDETECT, 0, 0L);
+ }
+
+ BOOL SetAutoURLDetect(BOOL bAutoDetect = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return !(BOOL)::SendMessage(m_hWnd, EM_AUTOURLDETECT, bAutoDetect, 0L);
+ }
+
+ // this method is deprecated, please use SetAutoURLDetect
+ BOOL EnableAutoURLDetect(BOOL bEnable = TRUE) { return SetAutoURLDetect(bEnable); }
+
+ UINT SetUndoLimit(UINT uUndoLimit)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_SETUNDOLIMIT, uUndoLimit, 0L);
+ }
+
+ void SetPalette(HPALETTE hPalette)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETPALETTE, (WPARAM)hPalette, 0L);
+ }
+
+ int GetTextEx(GETTEXTEX* pGetTextEx, LPTSTR lpstrText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETTEXTEX, (WPARAM)pGetTextEx, (LPARAM)lpstrText);
+ }
+
+ int GetTextEx(LPTSTR lpstrText, int nTextLen, DWORD dwFlags = GT_DEFAULT, UINT uCodePage = CP_ACP, LPCSTR lpDefaultChar = NULL, LPBOOL lpUsedDefChar = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ GETTEXTEX gte = { 0 };
+ gte.cb = nTextLen * sizeof(TCHAR);
+ gte.codepage = uCodePage;
+ gte.flags = dwFlags;
+ gte.lpDefaultChar = lpDefaultChar;
+ gte.lpUsedDefChar = lpUsedDefChar;
+ return (int)::SendMessage(m_hWnd, EM_GETTEXTEX, (WPARAM)&gte, (LPARAM)lpstrText);
+ }
+
+ int GetTextLengthEx(GETTEXTLENGTHEX* pGetTextLengthEx) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETTEXTLENGTHEX, (WPARAM)pGetTextLengthEx, 0L);
+ }
+
+ int GetTextLengthEx(DWORD dwFlags = GTL_DEFAULT, UINT uCodePage = CP_ACP) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ GETTEXTLENGTHEX gtle = { 0 };
+ gtle.codepage = uCodePage;
+ gtle.flags = dwFlags;
+ return (int)::SendMessage(m_hWnd, EM_GETTEXTLENGTHEX, (WPARAM)&gtle, 0L);
+ }
+#endif // (_RICHEDIT_VER >= 0x0200)
+
+#if (_RICHEDIT_VER >= 0x0300)
+ int SetTextEx(SETTEXTEX* pSetTextEx, LPCTSTR lpstrText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_SETTEXTEX, (WPARAM)pSetTextEx, (LPARAM)lpstrText);
+ }
+
+ int SetTextEx(LPCTSTR lpstrText, DWORD dwFlags = ST_DEFAULT, UINT uCodePage = CP_ACP)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ SETTEXTEX ste = { 0 };
+ ste.flags = dwFlags;
+ ste.codepage = uCodePage;
+ return (int)::SendMessage(m_hWnd, EM_SETTEXTEX, (WPARAM)&ste, (LPARAM)lpstrText);
+ }
+
+ int GetEditStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_GETEDITSTYLE, 0, 0L);
+ }
+
+ int SetEditStyle(int nStyle, int nMask = -1)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ if(nMask == -1)
+ nMask = nStyle; // set everything specified
+ return (int)::SendMessage(m_hWnd, EM_SETEDITSTYLE, nStyle, nMask);
+ }
+
+ BOOL SetFontSize(int nFontSizeDelta)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nFontSizeDelta >= -1637 && nFontSizeDelta <= 1638);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETFONTSIZE, nFontSizeDelta, 0L);
+ }
+
+ void GetScrollPos(LPPOINT lpPoint) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpPoint != NULL);
+ ::SendMessage(m_hWnd, EM_GETSCROLLPOS, 0, (LPARAM)lpPoint);
+ }
+
+ void SetScrollPos(LPPOINT lpPoint)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpPoint != NULL);
+ ::SendMessage(m_hWnd, EM_SETSCROLLPOS, 0, (LPARAM)lpPoint);
+ }
+
+ BOOL GetZoom(int& nNum, int& nDen) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_GETZOOM, (WPARAM)&nNum, (LPARAM)&nDen);
+ }
+
+ BOOL SetZoom(int nNum, int nDen)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nNum >= 0 && nNum <= 64);
+ ATLASSERT(nDen >= 0 && nDen <= 64);
+ return (BOOL)::SendMessage(m_hWnd, EM_SETZOOM, nNum, nDen);
+ }
+
+ BOOL SetZoomOff()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETZOOM, 0, 0L);
+ }
+#endif // (_RICHEDIT_VER >= 0x0300)
+
+// Operations
+ void LimitText(LONG nChars = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_EXLIMITTEXT, 0, nChars);
+ }
+
+ int LineFromChar(LONG nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_EXLINEFROMCHAR, 0, nIndex);
+ }
+
+ POINT PosFromChar(LONG nChar) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ POINT point = { 0, 0 };
+ ::SendMessage(m_hWnd, EM_POSFROMCHAR, (WPARAM)&point, nChar);
+ return point;
+ }
+
+ int CharFromPos(POINT pt) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ POINTL ptl = { pt.x, pt.y };
+ return (int)::SendMessage(m_hWnd, EM_CHARFROMPOS, 0, (LPARAM)&ptl);
+ }
+
+ void EmptyUndoBuffer()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_EMPTYUNDOBUFFER, 0, 0L);
+ }
+
+ int LineIndex(int nLine = -1) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_LINEINDEX, nLine, 0L);
+ }
+
+ int LineLength(int nLine = -1) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, EM_LINELENGTH, nLine, 0L);
+ }
+
+ BOOL LineScroll(int nLines, int nChars = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_LINESCROLL, nChars, nLines);
+ }
+
+ void ReplaceSel(LPCTSTR lpszNewText, BOOL bCanUndo = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_REPLACESEL, (WPARAM) bCanUndo, (LPARAM)lpszNewText);
+ }
+
+ void SetRect(LPCRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETRECT, 0, (LPARAM)lpRect);
+ }
+
+ BOOL DisplayBand(LPRECT pDisplayRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_DISPLAYBAND, 0, (LPARAM)pDisplayRect);
+ }
+
+ LONG FindText(DWORD dwFlags, FINDTEXT& ft) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+#if (_RICHEDIT_VER >= 0x0200) && defined(_UNICODE)
+ return (LONG)::SendMessage(m_hWnd, EM_FINDTEXTW, dwFlags, (LPARAM)&ft);
+#else
+ return (LONG)::SendMessage(m_hWnd, EM_FINDTEXT, dwFlags, (LPARAM)&ft);
+#endif
+ }
+
+ LONG FindText(DWORD dwFlags, FINDTEXTEX& ft) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+#if (_RICHEDIT_VER >= 0x0200) && defined(_UNICODE)
+ return (LONG)::SendMessage(m_hWnd, EM_FINDTEXTEXW, dwFlags, (LPARAM)&ft);
+#else
+ return (LONG)::SendMessage(m_hWnd, EM_FINDTEXTEX, dwFlags, (LPARAM)&ft);
+#endif
+ }
+
+ LONG FormatRange(FORMATRANGE& fr, BOOL bDisplay = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_FORMATRANGE, bDisplay, (LPARAM)&fr);
+ }
+
+ LONG FormatRange(FORMATRANGE* pFormatRange, BOOL bDisplay = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_FORMATRANGE, bDisplay, (LPARAM)pFormatRange);
+ }
+
+ void HideSelection(BOOL bHide = TRUE, BOOL bChangeStyle = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_HIDESELECTION, bHide, bChangeStyle);
+ }
+
+ void PasteSpecial(UINT uClipFormat, DWORD dwAspect = 0, HMETAFILE hMF = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ REPASTESPECIAL reps = { dwAspect, (DWORD_PTR)hMF };
+ ::SendMessage(m_hWnd, EM_PASTESPECIAL, uClipFormat, (LPARAM)&reps);
+ }
+
+ void RequestResize()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_REQUESTRESIZE, 0, 0L);
+ }
+
+ LONG StreamIn(UINT uFormat, EDITSTREAM& es)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_STREAMIN, uFormat, (LPARAM)&es);
+ }
+
+ LONG StreamOut(UINT uFormat, EDITSTREAM& es)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_STREAMOUT, uFormat, (LPARAM)&es);
+ }
+
+ DWORD FindWordBreak(int nCode, LONG nStartChar)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, EM_FINDWORDBREAK, nCode, nStartChar);
+ }
+
+ // Additional operations
+ void ScrollCaret()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SCROLLCARET, 0, 0L);
+ }
+
+ int InsertText(long nInsertAfterChar, LPCTSTR lpstrText, BOOL bCanUndo = FALSE)
+ {
+ int nRet = SetSel(nInsertAfterChar, nInsertAfterChar);
+ ReplaceSel(lpstrText, bCanUndo);
+ return nRet;
+ }
+
+ int AppendText(LPCTSTR lpstrText, BOOL bCanUndo = FALSE)
+ {
+ return InsertText(GetWindowTextLength(), lpstrText, bCanUndo);
+ }
+
+ // Clipboard operations
+ BOOL Undo()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_UNDO, 0, 0L);
+ }
+
+ void Clear()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_CLEAR, 0, 0L);
+ }
+
+ void Copy()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_COPY, 0, 0L);
+ }
+
+ void Cut()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_CUT, 0, 0L);
+ }
+
+ void Paste()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_PASTE, 0, 0L);
+ }
+
+ // OLE support
+ IRichEditOle* GetOleInterface() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ IRichEditOle *pRichEditOle = NULL;
+ ::SendMessage(m_hWnd, EM_GETOLEINTERFACE, 0, (LPARAM)&pRichEditOle);
+ return pRichEditOle;
+ }
+
+ BOOL SetOleCallback(IRichEditOleCallback* pCallback)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETOLECALLBACK, 0, (LPARAM)pCallback);
+ }
+
+#if (_RICHEDIT_VER >= 0x0200)
+ BOOL Redo()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_REDO, 0, 0L);
+ }
+
+ void StopGroupTyping()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_STOPGROUPTYPING, 0, 0L);
+ }
+
+ void ShowScrollBar(int nBarType, BOOL bVisible = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SHOWSCROLLBAR, nBarType, bVisible);
+ }
+#endif // (_RICHEDIT_VER >= 0x0200)
+
+#if (_RICHEDIT_VER >= 0x0300)
+ BOOL SetTabStops(int nTabStops, LPINT rgTabStops)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETTABSTOPS, nTabStops, (LPARAM)rgTabStops);
+ }
+
+ BOOL SetTabStops()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETTABSTOPS, 0, 0L);
+ }
+
+ BOOL SetTabStops(const int& cxEachStop) // takes an 'int'
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_SETTABSTOPS, 1, (LPARAM)(LPINT)&cxEachStop);
+ }
+#endif // (_RICHEDIT_VER >= 0x0300)
+};
+
+typedef CRichEditCtrlT<ATL::CWindow> CRichEditCtrl;
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRichEditCommands - message handlers for standard EDIT commands
+
+#ifndef _WIN32_WCE
+
+// Chain to CRichEditCommands message map. Your class must also derive from CRichEditCtrl.
+// Example:
+// class CMyRichEdit : public CWindowImpl<CMyRichEdit, CRichEditCtrl>,
+// public CRichEditCommands<CMyRichEdit>
+// {
+// public:
+// BEGIN_MSG_MAP(CMyRichEdit)
+// // your handlers...
+// CHAIN_MSG_MAP_ALT(CRichEditCommands<CMyRichEdit>, 1)
+// END_MSG_MAP()
+// // other stuff...
+// };
+
+template <class T>
+class CRichEditCommands : public CEditCommands< T >
+{
+public:
+ BEGIN_MSG_MAP(CRichEditCommands< T >)
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_EDIT_CLEAR, CEditCommands< T >::OnEditClear)
+ COMMAND_ID_HANDLER(ID_EDIT_CLEAR_ALL, CEditCommands< T >::OnEditClearAll)
+ COMMAND_ID_HANDLER(ID_EDIT_COPY, CEditCommands< T >::OnEditCopy)
+ COMMAND_ID_HANDLER(ID_EDIT_CUT, CEditCommands< T >::OnEditCut)
+ COMMAND_ID_HANDLER(ID_EDIT_PASTE, CEditCommands< T >::OnEditPaste)
+ COMMAND_ID_HANDLER(ID_EDIT_SELECT_ALL, CEditCommands< T >::OnEditSelectAll)
+ COMMAND_ID_HANDLER(ID_EDIT_UNDO, CEditCommands< T >::OnEditUndo)
+#if (_RICHEDIT_VER >= 0x0200)
+ COMMAND_ID_HANDLER(ID_EDIT_REDO, OnEditRedo)
+#endif // (_RICHEDIT_VER >= 0x0200)
+ END_MSG_MAP()
+
+#if (_RICHEDIT_VER >= 0x0200)
+ LRESULT OnEditRedo(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Redo();
+ return 0;
+ }
+#endif // (_RICHEDIT_VER >= 0x0200)
+
+// State (update UI) helpers
+ BOOL CanCut() const
+ { return HasSelection(); }
+
+ BOOL CanCopy() const
+ { return HasSelection(); }
+
+ BOOL CanClear() const
+ { return HasSelection(); }
+
+// Implementation
+ BOOL HasSelection() const
+ {
+ const T* pT = static_cast<const T*>(this);
+ return (pT->GetSelectionType() != SEL_EMPTY);
+ }
+};
+
+#endif // _WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDragListBox
+
+#ifndef _WIN32_WCE
+
+template <class TBase>
+class CDragListBoxT : public CListBoxT< TBase >
+{
+public:
+// Constructors
+ CDragListBoxT(HWND hWnd = NULL) : CListBoxT< TBase >(hWnd)
+ { }
+
+ CDragListBoxT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ if(hWnd != NULL)
+ MakeDragList();
+ return hWnd;
+ }
+
+// Operations
+ BOOL MakeDragList()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((GetStyle() & (LBS_MULTIPLESEL | LBS_EXTENDEDSEL)) == 0);
+ return ::MakeDragList(m_hWnd);
+ }
+
+ int LBItemFromPt(POINT pt, BOOL bAutoScroll = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::LBItemFromPt(m_hWnd, pt, bAutoScroll);
+ }
+
+ void DrawInsert(int nItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::DrawInsert(GetParent(), m_hWnd, nItem);
+ }
+
+ static UINT GetDragListMessage()
+ {
+ static UINT uDragListMessage = 0;
+ if(uDragListMessage == 0)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CDragListBox::GetDragListMessage.\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(uDragListMessage == 0)
+ uDragListMessage = ::RegisterWindowMessage(DRAGLISTMSGSTRING);
+
+ lock.Unlock();
+ }
+ ATLASSERT(uDragListMessage != 0);
+ return uDragListMessage;
+ }
+};
+
+typedef CDragListBoxT<ATL::CWindow> CDragListBox;
+
+template <class T>
+class CDragListNotifyImpl
+{
+public:
+ BEGIN_MSG_MAP(CDragListNotifyImpl< T >)
+ MESSAGE_HANDLER(CDragListBox::GetDragListMessage(), OnDragListNotify)
+ END_MSG_MAP()
+
+ LRESULT OnDragListNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ uMsg; // avoid level 4 warning
+ ATLASSERT(uMsg == CDragListBox::GetDragListMessage());
+ T* pT = static_cast<T*>(this);
+ LPDRAGLISTINFO lpDragListInfo = (LPDRAGLISTINFO)lParam;
+ LRESULT lRet = 0;
+ switch(lpDragListInfo->uNotification)
+ {
+ case DL_BEGINDRAG:
+ lRet = (LPARAM)pT->OnBeginDrag((int)wParam, lpDragListInfo->hWnd, lpDragListInfo->ptCursor);
+ break;
+ case DL_CANCELDRAG:
+ pT->OnCancelDrag((int)wParam, lpDragListInfo->hWnd, lpDragListInfo->ptCursor);
+ break;
+ case DL_DRAGGING:
+ lRet = (LPARAM)pT->OnDragging((int)wParam, lpDragListInfo->hWnd, lpDragListInfo->ptCursor);
+ break;
+ case DL_DROPPED:
+ pT->OnDropped((int)wParam, lpDragListInfo->hWnd, lpDragListInfo->ptCursor);
+ break;
+ default:
+ ATLTRACE2(atlTraceUI, 0, _T("Unknown DragListBox notification\n"));
+ bHandled = FALSE; // don't handle it
+ break;
+ }
+ return lRet;
+ }
+
+// Overrideables
+ BOOL OnBeginDrag(int /*nCtlID*/, HWND /*hWndDragList*/, POINT /*ptCursor*/)
+ {
+ return TRUE; // allow dragging
+ }
+
+ void OnCancelDrag(int /*nCtlID*/, HWND /*hWndDragList*/, POINT /*ptCursor*/)
+ {
+ // nothing to do
+ }
+
+ int OnDragging(int /*nCtlID*/, HWND /*hWndDragList*/, POINT /*ptCursor*/)
+ {
+ return 0; // don't change cursor
+ }
+
+ void OnDropped(int /*nCtlID*/, HWND /*hWndDragList*/, POINT /*ptCursor*/)
+ {
+ // nothing to do
+ }
+};
+
+#endif // _WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CReBarCtrl
+
+template <class TBase>
+class CReBarCtrlT : public TBase
+{
+public:
+// Constructors
+ CReBarCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CReBarCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return REBARCLASSNAME;
+ }
+
+ UINT GetBandCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, RB_GETBANDCOUNT, 0, 0L);
+ }
+
+ BOOL GetBandInfo(int nBand, LPREBARBANDINFO lprbbi) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_GETBANDINFO, nBand, (LPARAM)lprbbi);
+ }
+
+ BOOL SetBandInfo(int nBand, LPREBARBANDINFO lprbbi)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_SETBANDINFO, nBand, (LPARAM)lprbbi);
+ }
+
+ BOOL GetBarInfo(LPREBARINFO lprbi) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_GETBARINFO, 0, (LPARAM)lprbi);
+ }
+
+ BOOL SetBarInfo(LPREBARINFO lprbi)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_SETBARINFO, 0, (LPARAM)lprbi);
+ }
+
+ CImageList GetImageList() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ REBARINFO rbi = { 0 };
+ rbi.cbSize = sizeof(REBARINFO);
+ rbi.fMask = RBIM_IMAGELIST;
+ if( (BOOL)::SendMessage(m_hWnd, RB_GETBARINFO, 0, (LPARAM)&rbi) == FALSE ) return CImageList();
+ return CImageList(rbi.himl);
+ }
+
+ BOOL SetImageList(HIMAGELIST hImageList)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ REBARINFO rbi = { 0 };
+ rbi.cbSize = sizeof(REBARINFO);
+ rbi.fMask = RBIM_IMAGELIST;
+ rbi.himl = hImageList;
+ return (BOOL)::SendMessage(m_hWnd, RB_SETBARINFO, 0, (LPARAM)&rbi);
+ }
+
+ UINT GetRowCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, RB_GETROWCOUNT, 0, 0L);
+ }
+
+ UINT GetRowHeight(int nBand) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, RB_GETROWHEIGHT, nBand, 0L);
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ COLORREF GetTextColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, RB_GETTEXTCOLOR, 0, 0L);
+ }
+
+ COLORREF SetTextColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, RB_SETTEXTCOLOR, 0, (LPARAM)clr);
+ }
+
+ COLORREF GetBkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, RB_GETBKCOLOR, 0, 0L);
+ }
+
+ COLORREF SetBkColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, RB_SETBKCOLOR, 0, (LPARAM)clr);
+ }
+
+ UINT GetBarHeight() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, RB_GETBARHEIGHT, 0, 0L);
+ }
+
+ BOOL GetRect(int nBand, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_GETRECT, nBand, (LPARAM)lpRect);
+ }
+
+#ifndef _WIN32_WCE
+ CToolTipCtrl GetToolTips() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CToolTipCtrl((HWND)::SendMessage(m_hWnd, RB_GETTOOLTIPS, 0, 0L));
+ }
+
+ void SetToolTips(HWND hwndToolTip)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_SETTOOLTIPS, (WPARAM)hwndToolTip, 0L);
+ }
+#endif // !_WIN32_WCE
+
+ void GetBandBorders(int nBand, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpRect != NULL);
+ ::SendMessage(m_hWnd, RB_GETBANDBORDERS, nBand, (LPARAM)lpRect);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetColorScheme(LPCOLORSCHEME lpColorScheme) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpColorScheme != NULL);
+ return (BOOL)::SendMessage(m_hWnd, RB_GETCOLORSCHEME, 0, (LPARAM)lpColorScheme);
+ }
+
+ void SetColorScheme(LPCOLORSCHEME lpColorScheme)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpColorScheme != NULL);
+ ::SendMessage(m_hWnd, RB_SETCOLORSCHEME, 0, (LPARAM)lpColorScheme);
+ }
+
+ HPALETTE GetPalette() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HPALETTE)::SendMessage(m_hWnd, RB_GETPALETTE, 0, 0L);
+ }
+
+ HPALETTE SetPalette(HPALETTE hPalette)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HPALETTE)::SendMessage(m_hWnd, RB_SETPALETTE, 0, (LPARAM)hPalette);
+ }
+
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // !_WIN32_WCE
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_WINNT >= 0x0501)
+ // requires uxtheme.h to be included to use MARGINS struct
+#ifndef _UXTHEME_H_
+ typedef struct _MARGINS* PMARGINS;
+#endif // !_UXTHEME_H_
+ void GetBandMargins(PMARGINS pMargins) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_GETBANDMARGINS, 0, (LPARAM)pMargins);
+ }
+
+ void SetWindowTheme(LPCWSTR lpstrTheme)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_SETWINDOWTHEME, 0, (LPARAM)lpstrTheme);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+#if (_WIN32_IE >= 0x0600)
+ DWORD GetExtendedStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, RB_GETEXTENDEDSTYLE, 0, 0L);
+ }
+
+ DWORD SetExtendedStyle(DWORD dwStyle, DWORD dwMask)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, RB_SETEXTENDEDSTYLE, dwMask, dwStyle);
+ }
+#endif // (_WIN32_IE >= 0x0600)
+
+// Operations
+ BOOL InsertBand(int nBand, LPREBARBANDINFO lprbbi)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_INSERTBAND, nBand, (LPARAM)lprbbi);
+ }
+
+ BOOL AddBand(LPREBARBANDINFO lprbbi)
+ {
+ return InsertBand(-1, lprbbi);
+ }
+
+ BOOL DeleteBand(int nBand)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_DELETEBAND, nBand, 0L);
+ }
+
+ ATL::CWindow SetNotifyWnd(HWND hWnd)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ATL::CWindow((HWND)::SendMessage(m_hWnd, RB_SETPARENT, (WPARAM)hWnd, 0L));
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ void BeginDrag(int nBand, DWORD dwPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_BEGINDRAG, nBand, dwPos);
+ }
+
+ void BeginDrag(int nBand, int xPos, int yPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_BEGINDRAG, nBand, MAKELPARAM(xPos, yPos));
+ }
+
+ void EndDrag()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_ENDDRAG, 0, 0L);
+ }
+
+ void DragMove(DWORD dwPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_DRAGMOVE, 0, dwPos);
+ }
+
+ void DragMove(int xPos, int yPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_DRAGMOVE, 0, MAKELPARAM(xPos, yPos));
+ }
+
+#ifndef _WIN32_WCE
+ void GetDropTarget(IDropTarget** ppDropTarget) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_GETDROPTARGET, 0, (LPARAM)ppDropTarget);
+ }
+#endif // !_WIN32_WCE
+
+ void MaximizeBand(int nBand, BOOL bIdeal = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_MAXIMIZEBAND, nBand, bIdeal);
+ }
+
+ void MinimizeBand(int nBand)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_MINIMIZEBAND, nBand, 0L);
+ }
+
+ BOOL SizeToRect(LPRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_SIZETORECT, 0, (LPARAM)lpRect);
+ }
+
+ int IdToIndex(UINT uBandID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, RB_IDTOINDEX, uBandID, 0L);
+ }
+
+ int HitTest(LPRBHITTESTINFO lprbht) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, RB_HITTEST, 0, (LPARAM)lprbht);
+ }
+
+ BOOL ShowBand(int nBand, BOOL bShow)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_SHOWBAND, nBand, bShow);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL MoveBand(int nBand, int nNewPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nNewPos >= 0 && nNewPos <= ((int)GetBandCount() - 1));
+ return (BOOL)::SendMessage(m_hWnd, RB_MOVEBAND, nBand, nNewPos);
+ }
+#endif // !_WIN32_WCE
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ void PushChevron(int nBand, LPARAM lAppValue)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, RB_PUSHCHEVRON, nBand, lAppValue);
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+// Extra operations
+#if (_WIN32_IE >= 0x0400)
+ void LockBands(bool bLock)
+ {
+ int nBandCount = GetBandCount();
+ for(int i =0; i < nBandCount; i++)
+ {
+ REBARBANDINFO rbbi = { RunTimeHelper::SizeOf_REBARBANDINFO() };
+ rbbi.fMask = RBBIM_STYLE;
+ BOOL bRet = GetBandInfo(i, &rbbi);
+ ATLASSERT(bRet);
+
+ if((rbbi.fStyle & RBBS_GRIPPERALWAYS) == 0)
+ {
+ rbbi.fStyle |= RBBS_GRIPPERALWAYS;
+ bRet = SetBandInfo(i, &rbbi);
+ ATLASSERT(bRet);
+ rbbi.fStyle &= ~RBBS_GRIPPERALWAYS;
+ }
+
+ if(bLock)
+ rbbi.fStyle |= RBBS_NOGRIPPER;
+ else
+ rbbi.fStyle &= ~RBBS_NOGRIPPER;
+
+ bRet = SetBandInfo(i, &rbbi);
+ ATLASSERT(bRet);
+ }
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_WINNT >= 0x0600)
+ BOOL SetBandWidth(int nBand, int cxWidth)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, RB_SETBANDWIDTH, nBand, cxWidth);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+};
+
+typedef CReBarCtrlT<ATL::CWindow> CReBarCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CComboBoxEx
+
+#ifndef _WIN32_WCE
+
+template <class TBase>
+class CComboBoxExT : public CComboBoxT< TBase >
+{
+public:
+// Constructors
+ CComboBoxExT(HWND hWnd = NULL) : CComboBoxT< TBase >(hWnd)
+ { }
+
+ CComboBoxExT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_COMBOBOXEX;
+ }
+
+ CImageList GetImageList() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, CBEM_GETIMAGELIST, 0, 0L));
+ }
+
+ CImageList SetImageList(HIMAGELIST hImageList)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CImageList((HIMAGELIST)::SendMessage(m_hWnd, CBEM_SETIMAGELIST, 0, (LPARAM)hImageList));
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ DWORD GetExtendedStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, CBEM_GETEXTENDEDSTYLE, 0, 0L);
+ }
+
+ DWORD SetExtendedStyle(DWORD dwExMask, DWORD dwExStyle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, CBEM_SETEXTENDEDSTYLE, dwExMask, dwExStyle);
+ }
+
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CBEM_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CBEM_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_WINNT >= 0x0501)
+ void SetWindowTheme(LPCWSTR lpstrTheme)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, CBEM_SETWINDOWTHEME, 0, (LPARAM)lpstrTheme);
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+// Operations
+ int InsertItem(const COMBOBOXEXITEM* lpcCBItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CBEM_INSERTITEM, 0, (LPARAM)lpcCBItem);
+ }
+
+ int InsertItem(UINT nMask, int nIndex, LPCTSTR lpszItem, int nImage, int nSelImage,
+ int iIndent, int iOverlay, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ COMBOBOXEXITEM cbex = { 0 };
+ cbex.mask = nMask;
+ cbex.iItem = nIndex;
+ cbex.pszText = (LPTSTR) lpszItem;
+ cbex.iImage = nImage;
+ cbex.iSelectedImage = nSelImage;
+ cbex.iIndent = iIndent;
+ cbex.iOverlay = iOverlay;
+ cbex.lParam = lParam;
+ return (int)::SendMessage(m_hWnd, CBEM_INSERTITEM, 0, (LPARAM)&cbex);
+ }
+
+ int InsertItem(int nIndex, LPCTSTR lpszItem, int nImage, int nSelImage, int iIndent, LPARAM lParam = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ COMBOBOXEXITEM cbex = { 0 };
+ cbex.mask = CBEIF_TEXT | CBEIF_IMAGE | CBEIF_SELECTEDIMAGE | CBEIF_INDENT | CBEIF_LPARAM;
+ cbex.iItem = nIndex;
+ cbex.pszText = (LPTSTR) lpszItem;
+ cbex.iImage = nImage;
+ cbex.iSelectedImage = nSelImage;
+ cbex.iIndent = iIndent;
+ cbex.lParam = lParam;
+ return (int)::SendMessage(m_hWnd, CBEM_INSERTITEM, 0, (LPARAM)&cbex);
+ }
+
+ int AddItem(UINT nMask, LPCTSTR lpszItem, int nImage, int nSelImage, int iIndent, int iOverlay, LPARAM lParam)
+ {
+ return InsertItem(nMask, -1, lpszItem, nImage, nSelImage, iIndent, iOverlay, lParam);
+ }
+
+ int AddItem(LPCTSTR lpszItem, int nImage, int nSelImage, int iIndent, LPARAM lParam = 0)
+ {
+ return InsertItem(-1, lpszItem, nImage, nSelImage, iIndent, lParam);
+ }
+
+ int DeleteItem(int nIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, CBEM_DELETEITEM, nIndex, 0L);
+ }
+
+ BOOL GetItem(PCOMBOBOXEXITEM pCBItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CBEM_GETITEM, 0, (LPARAM)pCBItem);
+ }
+
+ BOOL SetItem(const COMBOBOXEXITEM* lpcCBItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CBEM_SETITEM, 0, (LPARAM)lpcCBItem);
+ }
+
+ int SetItem(int nIndex, UINT nMask, LPCTSTR lpszItem, int nImage, int nSelImage,
+ int iIndent, int iOverlay, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ COMBOBOXEXITEM cbex = { 0 };
+ cbex.mask = nMask;
+ cbex.iItem = nIndex;
+ cbex.pszText = (LPTSTR) lpszItem;
+ cbex.iImage = nImage;
+ cbex.iSelectedImage = nSelImage;
+ cbex.iIndent = iIndent;
+ cbex.iOverlay = iOverlay;
+ cbex.lParam = lParam;
+ return (int)::SendMessage(m_hWnd, CBEM_SETITEM, 0, (LPARAM)&cbex);
+ }
+
+ BOOL GetItemText(int nIndex, LPTSTR lpszItem, int nLen) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpszItem != NULL);
+
+ COMBOBOXEXITEM cbex = { 0 };
+ cbex.mask = CBEIF_TEXT;
+ cbex.iItem = nIndex;
+ cbex.pszText = lpszItem;
+ cbex.cchTextMax = nLen;
+
+ return (BOOL)::SendMessage(m_hWnd, CBEM_GETITEM, 0, (LPARAM)&cbex);
+ }
+
+#ifndef _ATL_NO_COM
+ BOOL GetItemText(int nIndex, BSTR& bstrText) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(bstrText == NULL);
+
+ COMBOBOXEXITEM cbex = { 0 };
+ cbex.mask = CBEIF_TEXT;
+ cbex.iItem = nIndex;
+
+ LPTSTR lpstrText = NULL;
+ BOOL bRet = FALSE;
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ ATLTRY(lpstrText = new TCHAR[nLen]);
+ if(lpstrText == NULL)
+ break;
+ lpstrText[0] = NULL;
+ cbex.pszText = lpstrText;
+ cbex.cchTextMax = nLen;
+ bRet = (BOOL)::SendMessage(m_hWnd, CBEM_GETITEM, 0, (LPARAM)&cbex);
+ if(!bRet || (lstrlen(cbex.pszText) < nLen - 1))
+ break;
+ delete [] lpstrText;
+ lpstrText = NULL;
+ }
+
+ if(lpstrText != NULL)
+ {
+ if(bRet)
+ bstrText = ::SysAllocString(T2OLE(lpstrText));
+ delete [] lpstrText;
+ }
+
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ BOOL GetItemText(int nIndex, _CSTRING_NS::CString& strText) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ COMBOBOXEXITEM cbex = { 0 };
+ cbex.mask = CBEIF_TEXT;
+ cbex.iItem = nIndex;
+
+ strText.Empty();
+ BOOL bRet = FALSE;
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ cbex.pszText = strText.GetBufferSetLength(nLen);
+ if(cbex.pszText == NULL)
+ {
+ bRet = FALSE;
+ break;
+ }
+ cbex.cchTextMax = nLen;
+ bRet = (BOOL)::SendMessage(m_hWnd, CBEM_GETITEM, 0, (LPARAM)&cbex);
+ if(!bRet || (lstrlen(cbex.pszText) < nLen - 1))
+ break;
+ }
+ strText.ReleaseBuffer();
+ return bRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ BOOL SetItemText(int nIndex, LPCTSTR lpszItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return SetItem(nIndex, CBEIF_TEXT, lpszItem, 0, 0, 0, 0, 0);
+ }
+
+ CComboBox GetComboCtrl() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CComboBox((HWND)::SendMessage(m_hWnd, CBEM_GETCOMBOCONTROL, 0, 0L));
+ }
+
+ CEdit GetEditCtrl() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CEdit((HWND)::SendMessage(m_hWnd, CBEM_GETEDITCONTROL, 0, 0L));
+ }
+
+ BOOL HasEditChanged() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, CBEM_HASEDITCHANGED, 0, 0L);
+ }
+
+// Non-functional
+ int AddString(LPCTSTR /*lpszItem*/)
+ {
+ ATLASSERT(FALSE); // Not available in CComboBoxEx; use InsertItem
+ return 0;
+ }
+
+ int InsertString(int /*nIndex*/, LPCTSTR /*lpszString*/)
+ {
+ ATLASSERT(FALSE); // Not available in CComboBoxEx; use InsertItem
+ return 0;
+ }
+
+ int Dir(UINT /*attr*/, LPCTSTR /*lpszWildCard*/)
+ {
+ ATLASSERT(FALSE); // Not available in CComboBoxEx
+ return 0;
+ }
+
+ int FindString(int /*nStartAfter*/, LPCTSTR /*lpszString*/) const
+ {
+ ATLASSERT(FALSE); // Not available in CComboBoxEx; try FindStringExact
+ return 0;
+ }
+};
+
+typedef CComboBoxExT<ATL::CWindow> CComboBoxEx;
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMonthCalendarCtrl
+
+template <class TBase>
+class CMonthCalendarCtrlT : public TBase
+{
+public:
+// Constructors
+ CMonthCalendarCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CMonthCalendarCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return MONTHCAL_CLASS;
+ }
+
+ COLORREF GetColor(int nColorType) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, MCM_GETCOLOR, nColorType, 0L);
+ }
+
+ COLORREF SetColor(int nColorType, COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, MCM_SETCOLOR, nColorType, clr);
+ }
+
+ BOOL GetCurSel(LPSYSTEMTIME lpSysTime) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_GETCURSEL, 0, (LPARAM)lpSysTime);
+ }
+
+ BOOL SetCurSel(LPSYSTEMTIME lpSysTime)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_SETCURSEL, 0, (LPARAM)lpSysTime);
+ }
+
+ int GetFirstDayOfWeek(BOOL* pbLocaleVal = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, MCM_GETFIRSTDAYOFWEEK, 0, 0L);
+ if(pbLocaleVal != NULL)
+ *pbLocaleVal = (BOOL)HIWORD(dwRet);
+ return (int)(short)LOWORD(dwRet);
+ }
+
+ int SetFirstDayOfWeek(int nDay, BOOL* pbLocaleVal = NULL)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ DWORD dwRet = (DWORD)::SendMessage(m_hWnd, MCM_SETFIRSTDAYOFWEEK, 0, nDay);
+ if(pbLocaleVal != NULL)
+ *pbLocaleVal = (BOOL)HIWORD(dwRet);
+ return (int)(short)LOWORD(dwRet);
+ }
+
+ int GetMaxSelCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, MCM_GETMAXSELCOUNT, 0, 0L);
+ }
+
+ BOOL SetMaxSelCount(int nMax)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_SETMAXSELCOUNT, nMax, 0L);
+ }
+
+ int GetMonthDelta() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, MCM_GETMONTHDELTA, 0, 0L);
+ }
+
+ int SetMonthDelta(int nDelta)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, MCM_SETMONTHDELTA, nDelta, 0L);
+ }
+
+ DWORD GetRange(LPSYSTEMTIME lprgSysTimeArray) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, MCM_GETRANGE, 0, (LPARAM)lprgSysTimeArray);
+ }
+
+ BOOL SetRange(DWORD dwFlags, LPSYSTEMTIME lprgSysTimeArray)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_SETRANGE, dwFlags, (LPARAM)lprgSysTimeArray);
+ }
+
+ BOOL GetSelRange(LPSYSTEMTIME lprgSysTimeArray) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_GETSELRANGE, 0, (LPARAM)lprgSysTimeArray);
+ }
+
+ BOOL SetSelRange(LPSYSTEMTIME lprgSysTimeArray)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_SETSELRANGE, 0, (LPARAM)lprgSysTimeArray);
+ }
+
+ BOOL GetToday(LPSYSTEMTIME lpSysTime) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_GETTODAY, 0, (LPARAM)lpSysTime);
+ }
+
+ void SetToday(LPSYSTEMTIME lpSysTime)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, MCM_SETTODAY, 0, (LPARAM)lpSysTime);
+ }
+
+ BOOL GetMinReqRect(LPRECT lpRectInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_GETMINREQRECT, 0, (LPARAM)lpRectInfo);
+ }
+
+ int GetMaxTodayWidth() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, MCM_GETMAXTODAYWIDTH, 0, 0L);
+ }
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ BOOL GetUnicodeFormat() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_GETUNICODEFORMAT, 0, 0L);
+ }
+
+ BOOL SetUnicodeFormat(BOOL bUnicode = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_SETUNICODEFORMAT, bUnicode, 0L);
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+#if defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+ DWORD GetCurrentView() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, MCM_GETCURRENTVIEW, 0, 0L);
+ }
+
+ BOOL SetCurrentView(DWORD dwView)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_SETCURRENTVIEW, 0, dwView);
+ }
+
+ DWORD GetCalendarCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, MCM_GETCALENDARCOUNT, 0, 0L);
+ }
+
+ BOOL GetCalendarGridInfo(PMCGRIDINFO pGridInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_GETCALENDARGRIDINFO, 0, (LPARAM)pGridInfo);
+ }
+
+ CALID GetCALID() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (CALID)::SendMessage(m_hWnd, MCM_GETCALID, 0, 0L);
+ }
+
+ void SetCALID(CALID calid)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, MCM_SETCALID, (LPARAM)calid, 0L);
+ }
+
+ int GetCalendarBorder() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, MCM_GETCALENDARBORDER, 0, 0L);
+ }
+
+ void SetCalendarBorder(int cxyBorder, BOOL bSet = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, MCM_SETCALENDARBORDER, (WPARAM)bSet, (LPARAM)cxyBorder);
+ }
+#endif // defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+
+// Operations
+ int GetMonthRange(DWORD dwFlags, LPSYSTEMTIME lprgSysTimeArray) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, MCM_GETMONTHRANGE, dwFlags, (LPARAM)lprgSysTimeArray);
+ }
+
+ BOOL SetDayState(int nMonths, LPMONTHDAYSTATE lpDayStateArray)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, MCM_SETDAYSTATE, nMonths, (LPARAM)lpDayStateArray);
+ }
+
+ DWORD HitTest(PMCHITTESTINFO pMCHitTest) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, MCM_HITTEST, 0, (LPARAM)pMCHitTest);
+ }
+
+#if defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+ void SizeRectToMin(LPRECT lpRect)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, MCM_SIZERECTTOMIN, 0, (LPARAM)lpRect);
+ }
+#endif // defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+};
+
+typedef CMonthCalendarCtrlT<ATL::CWindow> CMonthCalendarCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDateTimePickerCtrl
+
+template <class TBase>
+class CDateTimePickerCtrlT : public TBase
+{
+public:
+// Constructors
+ CDateTimePickerCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CDateTimePickerCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Operations
+ static LPCTSTR GetWndClassName()
+ {
+ return DATETIMEPICK_CLASS;
+ }
+
+ BOOL SetFormat(LPCTSTR lpszFormat)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, DTM_SETFORMAT, 0, (LPARAM)lpszFormat);
+ }
+
+ COLORREF GetMonthCalColor(int nColorType) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, DTM_GETMCCOLOR, nColorType, 0L);
+ }
+
+ COLORREF SetMonthCalColor(int nColorType, COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, DTM_SETMCCOLOR, nColorType, clr);
+ }
+
+ DWORD GetRange(LPSYSTEMTIME lpSysTimeArray) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, DTM_GETRANGE, 0, (LPARAM)lpSysTimeArray);
+ }
+
+ BOOL SetRange(DWORD dwFlags, LPSYSTEMTIME lpSysTimeArray)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, DTM_SETRANGE, dwFlags, (LPARAM)lpSysTimeArray);
+ }
+
+ DWORD GetSystemTime(LPSYSTEMTIME lpSysTime) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, DTM_GETSYSTEMTIME, 0, (LPARAM)lpSysTime);
+ }
+
+ BOOL SetSystemTime(DWORD dwFlags, LPSYSTEMTIME lpSysTime)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, DTM_SETSYSTEMTIME, dwFlags, (LPARAM)lpSysTime);
+ }
+
+ CMonthCalendarCtrl GetMonthCal() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CMonthCalendarCtrl((HWND)::SendMessage(m_hWnd, DTM_GETMONTHCAL, 0, 0L));
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ CFontHandle GetMonthCalFont() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CFontHandle((HFONT)::SendMessage(m_hWnd, DTM_GETMCFONT, 0, 0L));
+ }
+
+ void SetMonthCalFont(HFONT hFont, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_SETMCFONT, (WPARAM)hFont, MAKELPARAM(bRedraw, 0));
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+ DWORD GetMonthCalStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, DTM_GETMCSTYLE, 0, 0L);
+ }
+
+ DWORD SetMonthCalStyle(DWORD dwStyle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (DWORD)::SendMessage(m_hWnd, DTM_SETMCSTYLE, 0, (LPARAM)dwStyle);
+ }
+
+ void GetDateTimePickerInfo(LPDATETIMEPICKERINFO lpPickerInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_GETDATETIMEPICKERINFO, 0, (LPARAM)lpPickerInfo);
+ }
+
+ BOOL GetIdealSize(LPSIZE lpSize) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, DTM_GETIDEALSIZE, 0, (LPARAM)lpSize);
+ }
+
+ void CloseMonthCal()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_CLOSEMONTHCAL, 0, 0L);
+ }
+#endif // defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+};
+
+typedef CDateTimePickerCtrlT<ATL::CWindow> CDateTimePickerCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CFlatScrollBarImpl - support for flat scroll bars
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+template <class T>
+class CFlatScrollBarImpl
+{
+public:
+// Initialization
+ BOOL FlatSB_Initialize()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::InitializeFlatSB(pT->m_hWnd);
+ }
+
+ HRESULT FlatSB_Uninitialize()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::UninitializeFlatSB(pT->m_hWnd);
+ }
+
+// Flat scroll bar properties
+ BOOL FlatSB_GetScrollProp(UINT uIndex, LPINT lpnValue) const
+ {
+ const T* pT = static_cast<const T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_GetScrollProp(pT->m_hWnd, uIndex, lpnValue);
+ }
+
+ BOOL FlatSB_SetScrollProp(UINT uIndex, int nValue, BOOL bRedraw = TRUE)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_SetScrollProp(pT->m_hWnd, uIndex, nValue, bRedraw);
+ }
+
+// Attributes
+ int FlatSB_GetScrollPos(int nBar) const
+ {
+ const T* pT = static_cast<const T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_GetScrollPos(pT->m_hWnd, nBar);
+ }
+
+ int FlatSB_SetScrollPos(int nBar, int nPos, BOOL bRedraw = TRUE)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_SetScrollPos(pT->m_hWnd, nBar, nPos, bRedraw);
+ }
+
+ BOOL FlatSB_GetScrollRange(int nBar, LPINT lpMinPos, LPINT lpMaxPos) const
+ {
+ const T* pT = static_cast<const T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_GetScrollRange(pT->m_hWnd, nBar, lpMinPos, lpMaxPos);
+ }
+
+ BOOL FlatSB_SetScrollRange(int nBar, int nMinPos, int nMaxPos, BOOL bRedraw = TRUE)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_SetScrollRange(pT->m_hWnd, nBar, nMinPos, nMaxPos, bRedraw);
+ }
+
+ BOOL FlatSB_GetScrollInfo(int nBar, LPSCROLLINFO lpScrollInfo) const
+ {
+ const T* pT = static_cast<const T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_GetScrollInfo(pT->m_hWnd, nBar, lpScrollInfo);
+ }
+
+ int FlatSB_SetScrollInfo(int nBar, LPSCROLLINFO lpScrollInfo, BOOL bRedraw = TRUE)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_SetScrollInfo(pT->m_hWnd, nBar, lpScrollInfo, bRedraw);
+ }
+
+// Operations
+ BOOL FlatSB_ShowScrollBar(UINT nBar, BOOL bShow = TRUE)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_ShowScrollBar(pT->m_hWnd, nBar, bShow);
+ }
+
+ BOOL FlatSB_EnableScrollBar(UINT uSBFlags, UINT uArrowFlags = ESB_ENABLE_BOTH)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::FlatSB_EnableScrollBar(pT->m_hWnd, uSBFlags, uArrowFlags);
+ }
+};
+
+template <class TBase>
+class CFlatScrollBarT : public TBase, public CFlatScrollBarImpl<CFlatScrollBarT< TBase > >
+{
+public:
+ CFlatScrollBarT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CFlatScrollBarT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+};
+
+typedef CFlatScrollBarT<ATL::CWindow> CFlatScrollBar;
+
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CIPAddressCtrl
+
+#if (_WIN32_IE >= 0x0400)
+
+template <class TBase>
+class CIPAddressCtrlT : public TBase
+{
+public:
+// Constructors
+ CIPAddressCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CIPAddressCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Atteributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_IPADDRESS;
+ }
+
+ BOOL IsBlank() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, IPM_ISBLANK, 0, 0L);
+ }
+
+ int GetAddress(LPDWORD lpdwAddress) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, IPM_GETADDRESS, 0, (LPARAM)lpdwAddress);
+ }
+
+ void SetAddress(DWORD dwAddress)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IPM_SETADDRESS, 0, dwAddress);
+ }
+
+ void ClearAddress()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IPM_CLEARADDRESS, 0, 0L);
+ }
+
+ void SetRange(int nField, WORD wRange)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IPM_SETRANGE, nField, wRange);
+ }
+
+ void SetRange(int nField, BYTE nMin, BYTE nMax)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IPM_SETRANGE, nField, MAKEIPRANGE(nMin, nMax));
+ }
+
+ void SetFocus(int nField)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IPM_SETFOCUS, nField, 0L);
+ }
+};
+
+typedef CIPAddressCtrlT<ATL::CWindow> CIPAddressCtrl;
+
+#endif // (_WIN32_IE >= 0x0400)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPagerCtrl
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+template <class TBase>
+class CPagerCtrlT : public TBase
+{
+public:
+// Constructors
+ CPagerCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CPagerCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_PAGESCROLLER;
+ }
+
+ int GetButtonSize() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PGM_GETBUTTONSIZE, 0, 0L);
+ }
+
+ int SetButtonSize(int nButtonSize)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PGM_SETBUTTONSIZE, 0, nButtonSize);
+ }
+
+ DWORD GetButtonState(int nButton) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nButton == PGB_TOPORLEFT || nButton == PGB_BOTTOMORRIGHT);
+ return (DWORD)::SendMessage(m_hWnd, PGM_GETBUTTONSTATE, 0, nButton);
+ }
+
+ COLORREF GetBkColor() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, PGM_GETBKCOLOR, 0, 0L);
+ }
+
+ COLORREF SetBkColor(COLORREF clrBk)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (COLORREF)::SendMessage(m_hWnd, PGM_SETBKCOLOR, 0, (LPARAM)clrBk);
+ }
+
+ int GetBorder() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PGM_GETBORDER, 0, 0L);
+ }
+
+ int SetBorder(int nBorderSize)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PGM_SETBORDER, 0, nBorderSize);
+ }
+
+ int GetPos() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PGM_GETPOS, 0, 0L);
+ }
+
+ int SetPos(int nPos)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PGM_SETPOS, 0, nPos);
+ }
+
+// Operations
+ void SetChild(HWND hWndChild)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PGM_SETCHILD, 0, (LPARAM)hWndChild);
+ }
+
+ void ForwardMouse(BOOL bForward = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PGM_FORWARDMOUSE, bForward, 0L);
+ }
+
+ void RecalcSize()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PGM_RECALCSIZE, 0, 0L);
+ }
+
+ void GetDropTarget(IDropTarget** ppDropTarget)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(ppDropTarget != NULL);
+ ::SendMessage(m_hWnd, PGM_GETDROPTARGET, 0, (LPARAM)ppDropTarget);
+ }
+};
+
+typedef CPagerCtrlT<ATL::CWindow> CPagerCtrl;
+
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CLinkCtrl - Windows SYSLINK control
+
+#if (_WIN32_WINNT >= 0x0501) && !defined(_WIN32_WCE)
+
+template <class TBase>
+class CLinkCtrlT : public TBase
+{
+public:
+// Constructors
+ CLinkCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CLinkCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ return TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+#ifdef _UNICODE
+ return WC_LINK;
+#else // !_UNICODE
+ return "SysLink";
+#endif // !_UNICODE
+ }
+
+ int GetIdealHeight(int cxMaxWidth = 0) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LM_GETIDEALHEIGHT, cxMaxWidth, 0L);
+ }
+
+ BOOL GetItem(PLITEM pLItem) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LM_GETITEM, 0, (LPARAM)pLItem);
+ }
+
+ BOOL SetItem(PLITEM pLItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LM_SETITEM, 0, (LPARAM)pLItem);
+ }
+
+ // Vista only
+ int GetIdealSize(SIZE& size, int cxMaxWidth = 0) const
+ {
+#ifndef LM_GETIDEALSIZE
+ const UINT LM_GETIDEALSIZE = LM_GETIDEALHEIGHT;
+#endif
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, LM_GETIDEALSIZE, cxMaxWidth, (LPARAM)&size);
+ }
+
+// Operations
+ BOOL HitTest(PLHITTESTINFO pLHitTestInfo) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, LM_HITTEST, 0, (LPARAM)pLHitTestInfo);
+ }
+};
+
+typedef CLinkCtrlT<ATL::CWindow> CLinkCtrl;
+
+#endif // (_WIN32_WINNT >= 0x0501) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CCustomDraw - MI class for custom-draw support
+
+template <class T>
+class CCustomDraw
+{
+public:
+#if (_ATL_VER < 0x0700)
+ BOOL m_bHandledCD;
+
+ BOOL IsMsgHandled() const
+ {
+ return m_bHandledCD;
+ }
+
+ void SetMsgHandled(BOOL bHandled)
+ {
+ m_bHandledCD = bHandled;
+ }
+#endif // !(_ATL_VER < 0x0700)
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CCustomDraw< T >)
+ NOTIFY_CODE_HANDLER(NM_CUSTOMDRAW, OnCustomDraw)
+ ALT_MSG_MAP(1)
+ REFLECTED_NOTIFY_CODE_HANDLER(NM_CUSTOMDRAW, OnCustomDraw)
+ END_MSG_MAP()
+
+// message handler
+ LRESULT OnCustomDraw(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetMsgHandled(TRUE);
+ LPNMCUSTOMDRAW lpNMCustomDraw = (LPNMCUSTOMDRAW)pnmh;
+ DWORD dwRet = 0;
+ switch(lpNMCustomDraw->dwDrawStage)
+ {
+ case CDDS_PREPAINT:
+ dwRet = pT->OnPrePaint(idCtrl, lpNMCustomDraw);
+ break;
+ case CDDS_POSTPAINT:
+ dwRet = pT->OnPostPaint(idCtrl, lpNMCustomDraw);
+ break;
+ case CDDS_PREERASE:
+ dwRet = pT->OnPreErase(idCtrl, lpNMCustomDraw);
+ break;
+ case CDDS_POSTERASE:
+ dwRet = pT->OnPostErase(idCtrl, lpNMCustomDraw);
+ break;
+ case CDDS_ITEMPREPAINT:
+ dwRet = pT->OnItemPrePaint(idCtrl, lpNMCustomDraw);
+ break;
+ case CDDS_ITEMPOSTPAINT:
+ dwRet = pT->OnItemPostPaint(idCtrl, lpNMCustomDraw);
+ break;
+ case CDDS_ITEMPREERASE:
+ dwRet = pT->OnItemPreErase(idCtrl, lpNMCustomDraw);
+ break;
+ case CDDS_ITEMPOSTERASE:
+ dwRet = pT->OnItemPostErase(idCtrl, lpNMCustomDraw);
+ break;
+#if (_WIN32_IE >= 0x0400)
+ case (CDDS_ITEMPREPAINT | CDDS_SUBITEM):
+ dwRet = pT->OnSubItemPrePaint(idCtrl, lpNMCustomDraw);
+ break;
+#endif // (_WIN32_IE >= 0x0400)
+ default:
+ pT->SetMsgHandled(FALSE);
+ break;
+ }
+ bHandled = pT->IsMsgHandled();
+ return dwRet;
+ }
+
+// Overrideables
+ DWORD OnPrePaint(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+
+ DWORD OnPostPaint(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+
+ DWORD OnPreErase(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+
+ DWORD OnPostErase(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+
+ DWORD OnItemPrePaint(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+
+ DWORD OnItemPostPaint(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+
+ DWORD OnItemPreErase(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+
+ DWORD OnItemPostErase(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ DWORD OnSubItemPrePaint(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_DODEFAULT;
+ }
+#endif // (_WIN32_IE >= 0x0400)
+};
+
+
+// --- Windows CE common controls ---
+
+#ifdef _WIN32_WCE
+
+///////////////////////////////////////////////////////////////////////////////
+// CCECommandBarCtrl
+
+template <class TBase>
+class CCECommandBarCtrlT : public TBase
+{
+public:
+// Constructors
+ CCECommandBarCtrlT(HWND hWnd = NULL) : TBase(hWnd) { }
+
+ CCECommandBarCtrlT< TBase >& operator=(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Attributes
+ BOOL IsVisible() const
+ {
+ return IsWindowVisible();
+ }
+
+ int GetHeight() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_Height(m_hWnd);
+ }
+
+ HMENU GetMenu(WORD wButton) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_GetMenu(m_hWnd, wButton);
+ }
+
+// Operations
+ HWND Create(HWND hWndParent, int nCmdBarID)
+ {
+ m_hWnd = ::CommandBar_Create(ModuleHelper::GetModuleInstance(), hWndParent, nCmdBarID);
+ ATLASSERT(::IsWindow(m_hWnd));
+ return m_hWnd;
+ }
+
+ void Destroy()
+ {
+ DestroyWindow();
+ }
+
+ BOOL Show(BOOL bShow = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_Show(m_hWnd, bShow);
+ }
+
+ BOOL DrawMenuBar(WORD wButton)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_DrawMenuBar(m_hWnd, wButton);
+ }
+
+ BOOL AddAdornments(DWORD dwFlags = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_AddAdornments(m_hWnd, dwFlags, 0);
+ }
+
+ int AddBitmap(int nBitmapID, int nNumImages)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_AddBitmap(m_hWnd, ModuleHelper::GetResourceInstance(), nBitmapID, nNumImages, 16, 16);
+ }
+
+ BOOL AddButtons(UINT uNumButtons, LPTBBUTTON lpButtons)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CommandBar_AddButtons(m_hWnd, uNumButtons, lpButtons);
+ }
+
+ BOOL AddToolTips(UINT uNumToolTips, LPTSTR lpToolTips)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CommandBar_AddToolTips(m_hWnd, uNumToolTips, lpToolTips);
+ }
+
+ BOOL InsertButton(int nButton, LPTBBUTTON lpButton)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CommandBar_InsertButton(m_hWnd, nButton, lpButton);
+ }
+
+ HWND InsertComboBox(int nWidth, UINT dwStyle, WORD wComboBoxID, WORD wButton)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_InsertComboBox(m_hWnd, ModuleHelper::GetModuleInstance(), nWidth, dwStyle, wComboBoxID, wButton);
+ }
+
+ BOOL InsertMenubar(WORD wMenuID, WORD wButton)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_InsertMenubar(m_hWnd, ModuleHelper::GetResourceInstance(), wMenuID, wButton);
+ }
+
+ BOOL InsertMenubarEx(ATL::_U_STRINGorID menu, WORD wButton)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBar_InsertMenubarEx(m_hWnd, ModuleHelper::GetResourceInstance(), (LPTSTR)menu.m_lpstr, wButton);
+ }
+
+ BOOL IsCommandBarMessage(LPMSG lpMsg)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::IsCommandBarMessage(m_hWnd, lpMsg);
+ }
+};
+
+#if defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__) // PPC MenuBar
+ typedef CCECommandBarCtrlT<CToolBarCtrl> CMenuBarCtrl;
+#else
+ typedef CCECommandBarCtrlT<CToolBarCtrl> CCECommandBarCtrl;
+#endif // defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__)
+
+///////////////////////////////////////////////////////////////////////////////
+// CCECommandBandsCtrl
+
+template <class TBase>
+class CCECommandBandsCtrlT : public TBase
+{
+public:
+// Constructors
+ CCECommandBandsCtrlT(HWND hWnd = NULL) : TBase(hWnd) { }
+
+ CCECommandBandsCtrlT< TBase >& operator=(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Attributes
+ BOOL IsVisible() const
+ {
+ return IsWindowVisible();
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ UINT GetHeight() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CommandBands_Height(m_hWnd);
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+ HWND GetCommandBar(UINT uBand) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBands_GetCommandBar(m_hWnd, uBand);
+ }
+
+ BOOL GetRestoreInformation(UINT uBand, LPCOMMANDBANDSRESTOREINFO pcbr) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBands_GetRestoreInformation(m_hWnd, uBand, pcbr);
+ }
+
+// Operations
+ HWND Create(HWND hWndParent, UINT wID, DWORD dwStyles, HIMAGELIST hImageList = NULL)
+ {
+ m_hWnd = ::CommandBands_Create(ModuleHelper::GetModuleInstance(), hWndParent, wID, dwStyles, hImageList);
+ ATLASSERT(::IsWindow(m_hWnd));
+ return m_hWnd;
+ }
+
+ BOOL AddAdornments(DWORD dwFlags = 0, LPREBARBANDINFO prbbi = NULL)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBands_AddAdornments(m_hWnd, ModuleHelper::GetModuleInstance(), dwFlags, prbbi);
+ }
+
+ BOOL AddBands(UINT uBandCount, LPREBARBANDINFO prbbi)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBands_AddBands(m_hWnd, ModuleHelper::GetModuleInstance(), uBandCount, prbbi);
+ }
+
+ BOOL Show(BOOL bShow = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::CommandBands_Show(m_hWnd, bShow);
+ }
+};
+
+typedef CCECommandBandsCtrlT<ATL::CWindow> CCECommandBandsCtrl;
+
+#endif // _WIN32_WCE
+
+}; // namespace WTL
+
+#endif // __ATLCTRLS_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlctrlw.h b/plugins/SmartAutoReplier/wtl/atlctrlw.h
new file mode 100644
index 0000000000..7f95bdfda1
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlctrlw.h
@@ -0,0 +1,4157 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLCTRLW_H__
+#define __ATLCTRLW_H__
+
+#pragma once
+
+#ifdef _WIN32_WCE
+ #error atlctrlw.h is not supported on Windows CE
+#endif
+
+#ifndef __ATLAPP_H__
+ #error atlctrlw.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLCTRLS_H__
+ #error atlctrlw.h requires atlctrls.h to be included first
+#endif
+
+#if (_WIN32_IE < 0x0400)
+ #error atlctrlw.h requires _WIN32_IE >= 0x0400
+#endif
+
+// Define _WTL_CMDBAR_VISTA_MENUS as 0 to exclude Vista menus support
+#if !defined(_WTL_CMDBAR_VISTA_MENUS) && (WINVER >= 0x0500) && (_WIN32_WINNT >= 0x0501) && (_WIN32_IE >= 0x0501)
+ #define _WTL_CMDBAR_VISTA_MENUS 1
+#endif
+
+#if _WTL_CMDBAR_VISTA_MENUS
+ #if !((_WIN32_WINNT >= 0x0501) && (_WIN32_IE >= 0x0501))
+ #error _WTL_CMDBAR_VISTA_MENUS requires (_WIN32_WINNT >= 0x0501) && (_WIN32_IE >= 0x0501)
+ #endif
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CCommandBarCtrlImpl<T, TBase, TWinTraits>
+// CCommandBarCtrl
+// CMDICommandBarCtrlImpl<T, TBase, TWinTraits>
+// CMDICommandBarCtrl
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// Command Bars
+
+// Window Styles:
+#define CBRWS_TOP CCS_TOP
+#define CBRWS_BOTTOM CCS_BOTTOM
+#define CBRWS_NORESIZE CCS_NORESIZE
+#define CBRWS_NOPARENTALIGN CCS_NOPARENTALIGN
+#define CBRWS_NODIVIDER CCS_NODIVIDER
+
+// Extended styles
+#define CBR_EX_TRANSPARENT 0x00000001L
+#define CBR_EX_SHAREMENU 0x00000002L
+#define CBR_EX_ALTFOCUSMODE 0x00000004L
+#define CBR_EX_TRACKALWAYS 0x00000008L
+#define CBR_EX_NOVISTAMENUS 0x00000010L
+
+// standard command bar styles
+#define ATL_SIMPLE_CMDBAR_PANE_STYLE \
+ (WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | CBRWS_NODIVIDER | CBRWS_NORESIZE | CBRWS_NOPARENTALIGN)
+
+// Messages - support chevrons for frame windows
+#define CBRM_GETCMDBAR (WM_USER + 301) // returns command bar HWND
+#define CBRM_GETMENU (WM_USER + 302) // returns loaded or attached menu
+#define CBRM_TRACKPOPUPMENU (WM_USER + 303) // displays a popup menu
+
+typedef struct tagCBRPOPUPMENU
+{
+ int cbSize;
+ HMENU hMenu; // popup menu do display
+ UINT uFlags; // TPM_* flags for ::TrackPopupMenuEx
+ int x;
+ int y;
+ LPTPMPARAMS lptpm; // ptr to TPMPARAMS for ::TrackPopupMenuEx
+} CBRPOPUPMENU, *LPCBRPOPUPMENU;
+
+// helper class
+template <class T>
+class CSimpleStack : public ATL::CSimpleArray< T >
+{
+public:
+ BOOL Push(T t)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - STACK-PUSH (%8.8X) size = %i\n"), t, GetSize());
+#endif
+ return Add(t);
+ }
+
+ T Pop()
+ {
+ int nLast = GetSize() - 1;
+ if(nLast < 0)
+ return NULL; // must be able to convert to NULL
+ T t = m_aT[nLast];
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - STACK-POP (%8.8X) size = %i\n"), t, GetSize());
+#endif
+ if(!RemoveAt(nLast))
+ return NULL;
+ return t;
+ }
+
+ T GetCurrent()
+ {
+ int nLast = GetSize() - 1;
+ if(nLast < 0)
+ return NULL; // must be able to convert to NULL
+ return m_aT[nLast];
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CCommandBarCtrlBase - base class for the Command Bar implementation
+
+class CCommandBarCtrlBase : public CToolBarCtrl
+{
+public:
+ struct _MsgHookData
+ {
+ HHOOK hMsgHook;
+ DWORD dwUsage;
+
+ _MsgHookData() : hMsgHook(NULL), dwUsage(0)
+ { }
+ };
+
+ typedef ATL::CSimpleMap<DWORD, _MsgHookData*> CMsgHookMap;
+ static CMsgHookMap* s_pmapMsgHook;
+
+ static HHOOK s_hCreateHook;
+ static bool s_bW2K; // For animation flag
+ static CCommandBarCtrlBase* s_pCurrentBar;
+ static bool s_bStaticInit;
+
+ CSimpleStack<HWND> m_stackMenuWnd;
+ CSimpleStack<HMENU> m_stackMenuHandle;
+
+ HWND m_hWndHook;
+ DWORD m_dwMagic;
+
+
+ CCommandBarCtrlBase() : m_hWndHook(NULL), m_dwMagic(1314)
+ {
+ // init static variables
+ if(!s_bStaticInit)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CCommandBarCtrlBase::CCommandBarCtrlBase.\n"));
+ ATLASSERT(FALSE);
+ return;
+ }
+
+ if(!s_bStaticInit)
+ {
+ // Just in case...
+ AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES);
+ // Animation on Win2000 only
+ s_bW2K = !AtlIsOldWindows();
+ // done
+ s_bStaticInit = true;
+ }
+
+ lock.Unlock();
+ }
+ }
+
+ bool IsCommandBarBase() const { return m_dwMagic == 1314; }
+};
+
+__declspec(selectany) CCommandBarCtrlBase::CMsgHookMap* CCommandBarCtrlBase::s_pmapMsgHook = NULL;
+__declspec(selectany) HHOOK CCommandBarCtrlBase::s_hCreateHook = NULL;
+__declspec(selectany) CCommandBarCtrlBase* CCommandBarCtrlBase::s_pCurrentBar = NULL;
+__declspec(selectany) bool CCommandBarCtrlBase::s_bW2K = false;
+__declspec(selectany) bool CCommandBarCtrlBase::s_bStaticInit = false;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CCommandBarCtrl - ATL implementation of Command Bars
+
+template <class T, class TBase = CCommandBarCtrlBase, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CCommandBarCtrlImpl : public ATL::CWindowImpl< T, TBase, TWinTraits >
+{
+public:
+ DECLARE_WND_SUPERCLASS(NULL, TBase::GetWndClassName())
+
+// Declarations
+ struct _MenuItemData // menu item data
+ {
+ DWORD dwMagic;
+ LPTSTR lpstrText;
+ UINT fType;
+ UINT fState;
+ int iButton;
+
+ _MenuItemData() { dwMagic = 0x1313; }
+ bool IsCmdBarMenuItem() { return (dwMagic == 0x1313); }
+ };
+
+ struct _ToolBarData // toolbar resource data
+ {
+ WORD wVersion;
+ WORD wWidth;
+ WORD wHeight;
+ WORD wItemCount;
+ //WORD aItems[wItemCount]
+
+ WORD* items()
+ { return (WORD*)(this+1); }
+ };
+
+// Constants
+ enum _CmdBarDrawConstants
+ {
+ s_kcxGap = 1,
+ s_kcxTextMargin = 2,
+ s_kcxButtonMargin = 3,
+ s_kcyButtonMargin = 3
+ };
+
+ enum
+ {
+ _nMaxMenuItemTextLength = 100,
+ _chChevronShortcut = _T('/')
+ };
+
+#ifndef DT_HIDEPREFIX
+ enum { DT_HIDEPREFIX = 0x00100000 };
+#endif // !DT_HIDEPREFIX
+
+// Data members
+ HMENU m_hMenu;
+ HIMAGELIST m_hImageList;
+ ATL::CSimpleValArray<WORD> m_arrCommand;
+
+ DWORD m_dwExtendedStyle; // Command Bar specific extended styles
+
+ ATL::CContainedWindow m_wndParent;
+
+ bool m_bMenuActive:1;
+ bool m_bAttachedMenu:1;
+ bool m_bImagesVisible:1;
+ bool m_bPopupItem:1;
+ bool m_bContextMenu:1;
+ bool m_bEscapePressed:1;
+ bool m_bSkipMsg:1;
+ bool m_bParentActive:1;
+ bool m_bFlatMenus:1;
+ bool m_bUseKeyboardCues:1;
+ bool m_bShowKeyboardCues:1;
+ bool m_bAllowKeyboardCues:1;
+ bool m_bKeyboardInput:1;
+ bool m_bAlphaImages:1;
+ bool m_bLayoutRTL:1;
+ bool m_bSkipPostDown:1;
+ bool m_bVistaMenus:1;
+
+ int m_nPopBtn;
+ int m_nNextPopBtn;
+
+ SIZE m_szBitmap;
+ SIZE m_szButton;
+
+ COLORREF m_clrMask;
+ CFont m_fontMenu; // used internally, only to measure text
+
+ UINT m_uSysKey;
+
+ HWND m_hWndFocus; // Alternate focus mode
+
+ int m_cxExtraSpacing;
+
+#if _WTL_CMDBAR_VISTA_MENUS
+ ATL::CSimpleValArray<HBITMAP> m_arrVistaBitmap; // Bitmaps for Vista menus
+#endif // _WTL_CMDBAR_VISTA_MENUS
+
+// Constructor/destructor
+ CCommandBarCtrlImpl() :
+ m_hMenu(NULL),
+ m_hImageList(NULL),
+ m_wndParent(this, 1),
+ m_bMenuActive(false),
+ m_bAttachedMenu(false),
+ m_nPopBtn(-1),
+ m_nNextPopBtn(-1),
+ m_bPopupItem(false),
+ m_bImagesVisible(true),
+ m_bSkipMsg(false),
+ m_uSysKey(0),
+ m_hWndFocus(NULL),
+ m_bContextMenu(false),
+ m_bEscapePressed(false),
+ m_clrMask(RGB(192, 192, 192)),
+ m_dwExtendedStyle(CBR_EX_TRANSPARENT | CBR_EX_SHAREMENU | CBR_EX_TRACKALWAYS),
+ m_bParentActive(true),
+ m_bFlatMenus(false),
+ m_bUseKeyboardCues(false),
+ m_bShowKeyboardCues(false),
+ m_bAllowKeyboardCues(true),
+ m_bKeyboardInput(false),
+ m_cxExtraSpacing(0),
+ m_bAlphaImages(false),
+ m_bLayoutRTL(false),
+ m_bSkipPostDown(false),
+ m_bVistaMenus(false)
+ {
+ SetImageSize(16, 15); // default
+ }
+
+ ~CCommandBarCtrlImpl()
+ {
+ if(m_wndParent.IsWindow())
+/*scary!*/ m_wndParent.UnsubclassWindow();
+
+ if(m_hMenu != NULL && (m_dwExtendedStyle & CBR_EX_SHAREMENU) == 0)
+ ::DestroyMenu(m_hMenu);
+
+ if(m_hImageList != NULL)
+ ::ImageList_Destroy(m_hImageList);
+ }
+
+// Attributes
+ DWORD GetCommandBarExtendedStyle() const
+ {
+ return m_dwExtendedStyle;
+ }
+
+ DWORD SetCommandBarExtendedStyle(DWORD dwExtendedStyle, DWORD dwMask = 0)
+ {
+ DWORD dwPrevStyle = m_dwExtendedStyle;
+ if(dwMask == 0)
+ m_dwExtendedStyle = dwExtendedStyle;
+ else
+ m_dwExtendedStyle = (m_dwExtendedStyle & ~dwMask) | (dwExtendedStyle & dwMask);
+ return dwPrevStyle;
+ }
+
+ CMenuHandle GetMenu() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return m_hMenu;
+ }
+
+ COLORREF GetImageMaskColor() const
+ {
+ return m_clrMask;
+ }
+
+ COLORREF SetImageMaskColor(COLORREF clrMask)
+ {
+ COLORREF clrOld = m_clrMask;
+ m_clrMask = clrMask;
+ return clrOld;
+ }
+
+ bool GetImagesVisible() const
+ {
+ return m_bImagesVisible;
+ }
+
+ bool SetImagesVisible(bool bVisible)
+ {
+ bool bOld = m_bImagesVisible;
+ m_bImagesVisible = bVisible;
+ return bOld;
+ }
+
+ void GetImageSize(SIZE& size) const
+ {
+ size = m_szBitmap;
+ }
+
+ bool SetImageSize(SIZE& size)
+ {
+ return SetImageSize(size.cx, size.cy);
+ }
+
+ bool SetImageSize(int cx, int cy)
+ {
+ if(m_hImageList != NULL)
+ {
+ if(::ImageList_GetImageCount(m_hImageList) == 0) // empty
+ {
+ ::ImageList_Destroy(m_hImageList);
+ m_hImageList = NULL;
+ }
+ else
+ {
+ return false; // can't set, image list exists
+ }
+ }
+
+ if(cx == 0 || cy == 0)
+ return false;
+
+ m_szBitmap.cx = cx;
+ m_szBitmap.cy = cy;
+ m_szButton.cx = m_szBitmap.cx + 2 * s_kcxButtonMargin;
+ m_szButton.cy = m_szBitmap.cy + 2 * s_kcyButtonMargin;
+
+ return true;
+ }
+
+ bool GetAlphaImages() const
+ {
+ return m_bAlphaImages;
+ }
+
+ bool SetAlphaImages(bool bAlphaImages)
+ {
+ if(m_hImageList != NULL)
+ {
+ if(::ImageList_GetImageCount(m_hImageList) == 0) // empty
+ {
+ ::ImageList_Destroy(m_hImageList);
+ m_hImageList = NULL;
+ }
+ else
+ {
+ return false; // can't set, image list exists
+ }
+ }
+
+ m_bAlphaImages = bAlphaImages;
+ return true;
+ }
+
+ HWND GetCmdBar() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HWND)::SendMessage(m_hWnd, CBRM_GETCMDBAR, 0, 0L);
+ }
+
+// Methods
+ HWND Create(HWND hWndParent, RECT& rcPos, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ UINT nID = 0, LPVOID lpCreateParam = NULL)
+ {
+ // These styles are required for command bars
+ dwStyle |= TBSTYLE_LIST | TBSTYLE_FLAT;
+#if (_MSC_VER >= 1300)
+ return ATL::CWindowImpl< T, TBase, TWinTraits >::Create(hWndParent, rcPos, szWindowName, dwStyle, dwExStyle, nID, lpCreateParam);
+#else // !(_MSC_VER >= 1300)
+ typedef ATL::CWindowImpl< T, TBase, TWinTraits > _baseClass;
+ return _baseClass::Create(hWndParent, rcPos, szWindowName, dwStyle, dwExStyle, nID, lpCreateParam);
+#endif // !(_MSC_VER >= 1300)
+ }
+
+ BOOL AttachToWindow(HWND hWnd)
+ {
+ ATLASSERT(m_hWnd == NULL);
+ ATLASSERT(::IsWindow(hWnd));
+ BOOL bRet = SubclassWindow(hWnd);
+ if(bRet)
+ {
+ m_bAttachedMenu = true;
+ T* pT = static_cast<T*>(this);
+ pT->GetSystemSettings();
+ }
+ return bRet;
+ }
+
+ BOOL LoadMenu(ATL::_U_STRINGorID menu)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ if(m_bAttachedMenu) // doesn't work in this mode
+ return FALSE;
+ if(menu.m_lpstr == NULL)
+ return FALSE;
+
+ HMENU hMenu = ::LoadMenu(ModuleHelper::GetResourceInstance(), menu.m_lpstr);
+ if(hMenu == NULL)
+ return FALSE;
+
+ return AttachMenu(hMenu);
+ }
+
+ BOOL AttachMenu(HMENU hMenu)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hMenu == NULL || ::IsMenu(hMenu));
+ if(hMenu != NULL && !::IsMenu(hMenu))
+ return FALSE;
+
+#if _WTL_CMDBAR_VISTA_MENUS
+ // remove Vista bitmaps if used
+ if(m_bVistaMenus && (m_hMenu != NULL))
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_RemoveVistaBitmapsFromMenu();
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+
+ // destroy old menu, if needed, and set new one
+ if(m_hMenu != NULL && (m_dwExtendedStyle & CBR_EX_SHAREMENU) == 0)
+ ::DestroyMenu(m_hMenu);
+
+ m_hMenu = hMenu;
+
+ if(m_bAttachedMenu) // Nothing else in this mode
+ return TRUE;
+
+ // Build buttons according to menu
+ SetRedraw(FALSE);
+
+ // Clear all buttons
+ int nCount = GetButtonCount();
+ for(int i = 0; i < nCount; i++)
+ ATLVERIFY(DeleteButton(0) != FALSE);
+
+ // Add buttons for each menu item
+ if(m_hMenu != NULL)
+ {
+ int nItems = ::GetMenuItemCount(m_hMenu);
+
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ TCHAR szString[pT->_nMaxMenuItemTextLength];
+ for(int i = 0; i < nItems; i++)
+ {
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_TYPE | MIIM_STATE | MIIM_SUBMENU;
+ mii.fType = MFT_STRING;
+ mii.dwTypeData = szString;
+ mii.cch = pT->_nMaxMenuItemTextLength;
+ BOOL bRet = ::GetMenuItemInfo(m_hMenu, i, TRUE, &mii);
+ ATLASSERT(bRet);
+ // If we have more than the buffer, we assume we have bitmaps bits
+ if(lstrlen(szString) > pT->_nMaxMenuItemTextLength - 1)
+ {
+ mii.fType = MFT_BITMAP;
+ ::SetMenuItemInfo(m_hMenu, i, TRUE, &mii);
+ szString[0] = 0;
+ }
+
+ // NOTE: Command Bar currently supports only drop-down menu items
+ ATLASSERT(mii.hSubMenu != NULL);
+
+ TBBUTTON btn = { 0 };
+ btn.iBitmap = 0;
+ btn.idCommand = i;
+ btn.fsState = (BYTE)(((mii.fState & MFS_DISABLED) == 0) ? TBSTATE_ENABLED : 0);
+ btn.fsStyle = TBSTYLE_BUTTON | TBSTYLE_AUTOSIZE | TBSTYLE_DROPDOWN;
+ btn.dwData = 0;
+ btn.iString = 0;
+
+ bRet = InsertButton(-1, &btn);
+ ATLASSERT(bRet);
+
+ TBBUTTONINFO bi = { 0 };
+ bi.cbSize = sizeof(TBBUTTONINFO);
+ bi.dwMask = TBIF_TEXT;
+ bi.pszText = szString;
+
+ bRet = SetButtonInfo(i, &bi);
+ ATLASSERT(bRet);
+ }
+ }
+
+ SetRedraw(TRUE);
+ Invalidate();
+ UpdateWindow();
+
+ return TRUE;
+ }
+
+ BOOL LoadImages(ATL::_U_STRINGorID image)
+ {
+ return _LoadImagesHelper(image, false);
+ }
+
+ BOOL LoadMappedImages(UINT nIDImage, UINT nFlags = 0, LPCOLORMAP lpColorMap = NULL, int nMapSize = 0)
+ {
+ return _LoadImagesHelper(nIDImage, true, nFlags , lpColorMap, nMapSize);
+ }
+
+ BOOL _LoadImagesHelper(ATL::_U_STRINGorID image, bool bMapped, UINT nFlags = 0, LPCOLORMAP lpColorMap = NULL, int nMapSize = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HINSTANCE hInstance = ModuleHelper::GetResourceInstance();
+
+ HRSRC hRsrc = ::FindResource(hInstance, image.m_lpstr, (LPTSTR)RT_TOOLBAR);
+ if(hRsrc == NULL)
+ return FALSE;
+
+ HGLOBAL hGlobal = ::LoadResource(hInstance, hRsrc);
+ if(hGlobal == NULL)
+ return FALSE;
+
+ _ToolBarData* pData = (_ToolBarData*)::LockResource(hGlobal);
+ if(pData == NULL)
+ return FALSE;
+ ATLASSERT(pData->wVersion == 1);
+
+ WORD* pItems = pData->items();
+ int nItems = pData->wItemCount;
+
+ // Set internal data
+ SetImageSize(pData->wWidth, pData->wHeight);
+
+ // Create image list if needed
+ if(m_hImageList == NULL)
+ {
+ // Check if the bitmap is 32-bit (alpha channel) bitmap (valid for Windows XP only)
+ T* pT = static_cast<T*>(this);
+ m_bAlphaImages = AtlIsAlphaBitmapResource(image);
+
+ if(!pT->CreateInternalImageList(pData->wItemCount))
+ return FALSE;
+ }
+
+#if _WTL_CMDBAR_VISTA_MENUS
+ int nOldImageCount = ::ImageList_GetImageCount(m_hImageList);
+#endif // _WTL_CMDBAR_VISTA_MENUS
+
+ // Add bitmap to our image list
+ CBitmap bmp;
+ if(bMapped)
+ {
+ ATLASSERT(HIWORD(PtrToUlong(image.m_lpstr)) == 0); // if mapped, must be a numeric ID
+ int nIDImage = (int)(short)LOWORD(PtrToUlong(image.m_lpstr));
+ bmp.LoadMappedBitmap(nIDImage, (WORD)nFlags, lpColorMap, nMapSize);
+ }
+ else
+ {
+ if(m_bAlphaImages)
+ bmp = (HBITMAP)::LoadImage(ModuleHelper::GetResourceInstance(), image.m_lpstr, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION | LR_DEFAULTSIZE);
+ else
+ bmp.LoadBitmap(image.m_lpstr);
+ }
+ ATLASSERT(bmp.m_hBitmap != NULL);
+ if(bmp.m_hBitmap == NULL)
+ return FALSE;
+ if(::ImageList_AddMasked(m_hImageList, bmp, m_clrMask) == -1)
+ return FALSE;
+
+ // Fill the array with command IDs
+ for(int i = 0; i < nItems; i++)
+ {
+ if(pItems[i] != 0)
+ m_arrCommand.Add(pItems[i]);
+ }
+
+ int nImageCount = ::ImageList_GetImageCount(m_hImageList);
+ ATLASSERT(nImageCount == m_arrCommand.GetSize());
+ if(nImageCount != m_arrCommand.GetSize())
+ return FALSE;
+
+#if _WTL_CMDBAR_VISTA_MENUS
+ if(RunTimeHelper::IsVista())
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_AddVistaBitmapsFromImageList(nOldImageCount, nImageCount - nOldImageCount);
+ ATLASSERT(nImageCount == m_arrVistaBitmap.GetSize());
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+
+ return TRUE;
+ }
+
+ BOOL AddBitmap(ATL::_U_STRINGorID bitmap, int nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ CBitmap bmp;
+ bmp.LoadBitmap(bitmap.m_lpstr);
+ if(bmp.m_hBitmap == NULL)
+ return FALSE;
+ return AddBitmap(bmp, nCommandID);
+ }
+
+ BOOL AddBitmap(HBITMAP hBitmap, UINT nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ // Create image list if it doesn't exist
+ if(m_hImageList == NULL)
+ {
+ if(!pT->CreateInternalImageList(1))
+ return FALSE;
+ }
+ // check bitmap size
+ CBitmapHandle bmp = hBitmap;
+ SIZE size = { 0, 0 };
+ bmp.GetSize(size);
+ if(size.cx != m_szBitmap.cx || size.cy != m_szBitmap.cy)
+ {
+ ATLASSERT(FALSE); // must match size!
+ return FALSE;
+ }
+ // add bitmap
+ int nRet = ::ImageList_AddMasked(m_hImageList, hBitmap, m_clrMask);
+ if(nRet == -1)
+ return FALSE;
+ BOOL bRet = m_arrCommand.Add((WORD)nCommandID);
+ ATLASSERT(::ImageList_GetImageCount(m_hImageList) == m_arrCommand.GetSize());
+#if _WTL_CMDBAR_VISTA_MENUS
+ if(RunTimeHelper::IsVista())
+ {
+ pT->_AddVistaBitmapFromImageList(m_arrCommand.GetSize() - 1);
+ ATLASSERT(m_arrVistaBitmap.GetSize() == m_arrCommand.GetSize());
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+ return bRet;
+ }
+
+ BOOL AddIcon(ATL::_U_STRINGorID icon, UINT nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HICON hIcon = ::LoadIcon(ModuleHelper::GetResourceInstance(), icon.m_lpstr);
+ if(hIcon == NULL)
+ return FALSE;
+ return AddIcon(hIcon, nCommandID);
+ }
+
+ BOOL AddIcon(HICON hIcon, UINT nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ // create image list if it doesn't exist
+ if(m_hImageList == NULL)
+ {
+ if(!pT->CreateInternalImageList(1))
+ return FALSE;
+ }
+
+ int nRet = ::ImageList_AddIcon(m_hImageList, hIcon);
+ if(nRet == -1)
+ return FALSE;
+ BOOL bRet = m_arrCommand.Add((WORD)nCommandID);
+ ATLASSERT(::ImageList_GetImageCount(m_hImageList) == m_arrCommand.GetSize());
+#if _WTL_CMDBAR_VISTA_MENUS
+ if(RunTimeHelper::IsVista())
+ {
+ pT->_AddVistaBitmapFromImageList(m_arrCommand.GetSize() - 1);
+ ATLASSERT(m_arrVistaBitmap.GetSize() == m_arrCommand.GetSize());
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+ return bRet;
+ }
+
+ BOOL ReplaceBitmap(ATL::_U_STRINGorID bitmap, int nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ CBitmap bmp;
+ bmp.LoadBitmap(bitmap.m_lpstr);
+ if(bmp.m_hBitmap == NULL)
+ return FALSE;
+ return ReplaceBitmap(bmp, nCommandID);
+ }
+
+ BOOL ReplaceBitmap(HBITMAP hBitmap, UINT nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ BOOL bRet = FALSE;
+ for(int i = 0; i < m_arrCommand.GetSize(); i++)
+ {
+ if(m_arrCommand[i] == nCommandID)
+ {
+ bRet = ::ImageList_Remove(m_hImageList, i);
+ if(bRet)
+ {
+ m_arrCommand.RemoveAt(i);
+#if _WTL_CMDBAR_VISTA_MENUS
+ if(RunTimeHelper::IsVista())
+ {
+ if(m_arrVistaBitmap[i] != NULL)
+ ::DeleteObject(m_arrVistaBitmap[i]);
+ m_arrVistaBitmap.RemoveAt(i);
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+ }
+ break;
+ }
+ }
+ if(bRet)
+ bRet = AddBitmap(hBitmap, nCommandID);
+ return bRet;
+ }
+
+ BOOL ReplaceIcon(ATL::_U_STRINGorID icon, UINT nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HICON hIcon = ::LoadIcon(ModuleHelper::GetResourceInstance(), icon.m_lpstr);
+ if(hIcon == NULL)
+ return FALSE;
+ return ReplaceIcon(hIcon, nCommandID);
+ }
+
+ BOOL ReplaceIcon(HICON hIcon, UINT nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ BOOL bRet = FALSE;
+ for(int i = 0; i < m_arrCommand.GetSize(); i++)
+ {
+ if(m_arrCommand[i] == nCommandID)
+ {
+ bRet = (::ImageList_ReplaceIcon(m_hImageList, i, hIcon) != -1);
+#if _WTL_CMDBAR_VISTA_MENUS
+ if(RunTimeHelper::IsVista() && bRet != FALSE)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_ReplaceVistaBitmapFromImageList(i);
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+ break;
+ }
+ }
+ return bRet;
+ }
+
+ BOOL RemoveImage(int nCommandID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ BOOL bRet = FALSE;
+ for(int i = 0; i < m_arrCommand.GetSize(); i++)
+ {
+ if(m_arrCommand[i] == nCommandID)
+ {
+ bRet = ::ImageList_Remove(m_hImageList, i);
+ if(bRet)
+ {
+ m_arrCommand.RemoveAt(i);
+#if _WTL_CMDBAR_VISTA_MENUS
+ if(RunTimeHelper::IsVista())
+ {
+ if(m_arrVistaBitmap[i] != NULL)
+ ::DeleteObject(m_arrVistaBitmap[i]);
+ m_arrVistaBitmap.RemoveAt(i);
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+ }
+ break;
+ }
+ }
+ return bRet;
+ }
+
+ BOOL RemoveAllImages()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Removing all images\n"));
+ BOOL bRet = ::ImageList_RemoveAll(m_hImageList);
+ if(bRet)
+ {
+ m_arrCommand.RemoveAll();
+#if _WTL_CMDBAR_VISTA_MENUS
+ for(int i = 0; i < m_arrVistaBitmap.GetSize(); i++)
+ {
+ if(m_arrVistaBitmap[i] != NULL)
+ ::DeleteObject(m_arrVistaBitmap[i]);
+ }
+ m_arrVistaBitmap.RemoveAll();
+#endif // _WTL_CMDBAR_VISTA_MENUS
+ }
+ return bRet;
+ }
+
+ BOOL TrackPopupMenu(HMENU hMenu, UINT uFlags, int x, int y, LPTPMPARAMS lpParams = NULL)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(::IsMenu(hMenu));
+ if(!::IsMenu(hMenu))
+ return FALSE;
+ m_bContextMenu = true;
+ if(m_bUseKeyboardCues)
+ m_bShowKeyboardCues = m_bKeyboardInput;
+ T* pT = static_cast<T*>(this);
+ return pT->DoTrackPopupMenu(hMenu, uFlags, x, y, lpParams);
+ }
+
+ BOOL SetMDIClient(HWND /*hWndMDIClient*/)
+ {
+ // Use CMDICommandBarCtrl for MDI support
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CCommandBarCtrlImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_INITMENU, OnInitMenu)
+ MESSAGE_HANDLER(WM_INITMENUPOPUP, OnInitMenuPopup)
+ MESSAGE_HANDLER(WM_MENUSELECT, OnMenuSelect)
+ MESSAGE_HANDLER(GetAutoPopupMessage(), OnInternalAutoPopup)
+ MESSAGE_HANDLER(GetGetBarMessage(), OnInternalGetBar)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
+ MESSAGE_HANDLER(WM_MENUCHAR, OnMenuChar)
+
+ MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
+ MESSAGE_HANDLER(WM_KEYUP, OnKeyUp)
+ MESSAGE_HANDLER(WM_CHAR, OnChar)
+ MESSAGE_HANDLER(WM_SYSKEYDOWN, OnSysKeyDown)
+ MESSAGE_HANDLER(WM_SYSKEYUP, OnSysKeyUp)
+ MESSAGE_HANDLER(WM_SYSCHAR, OnSysChar)
+// public API handlers - these stay to support chevrons in atlframe.h
+ MESSAGE_HANDLER(CBRM_GETMENU, OnAPIGetMenu)
+ MESSAGE_HANDLER(CBRM_TRACKPOPUPMENU, OnAPITrackPopupMenu)
+ MESSAGE_HANDLER(CBRM_GETCMDBAR, OnAPIGetCmdBar)
+
+ MESSAGE_HANDLER(WM_DRAWITEM, OnDrawItem)
+ MESSAGE_HANDLER(WM_MEASUREITEM, OnMeasureItem)
+
+ MESSAGE_HANDLER(WM_FORWARDMSG, OnForwardMsg)
+ ALT_MSG_MAP(1) // Parent window messages
+ NOTIFY_CODE_HANDLER(TBN_HOTITEMCHANGE, OnParentHotItemChange)
+ NOTIFY_CODE_HANDLER(TBN_DROPDOWN, OnParentDropDown)
+ MESSAGE_HANDLER(WM_INITMENUPOPUP, OnParentInitMenuPopup)
+ MESSAGE_HANDLER(GetGetBarMessage(), OnParentInternalGetBar)
+ MESSAGE_HANDLER(WM_SYSCOMMAND, OnParentSysCommand)
+ MESSAGE_HANDLER(CBRM_GETMENU, OnParentAPIGetMenu)
+ MESSAGE_HANDLER(WM_MENUCHAR, OnParentMenuChar)
+ MESSAGE_HANDLER(CBRM_TRACKPOPUPMENU, OnParentAPITrackPopupMenu)
+ MESSAGE_HANDLER(CBRM_GETCMDBAR, OnParentAPIGetCmdBar)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnParentSettingChange)
+
+ MESSAGE_HANDLER(WM_DRAWITEM, OnParentDrawItem)
+ MESSAGE_HANDLER(WM_MEASUREITEM, OnParentMeasureItem)
+
+ MESSAGE_HANDLER(WM_ACTIVATE, OnParentActivate)
+ NOTIFY_CODE_HANDLER(NM_CUSTOMDRAW, OnParentCustomDraw)
+ ALT_MSG_MAP(2) // MDI client window messages
+ // Use CMDICommandBarCtrl for MDI support
+ ALT_MSG_MAP(3) // Message hook messages
+ MESSAGE_HANDLER(WM_MOUSEMOVE, OnHookMouseMove)
+ MESSAGE_HANDLER(WM_SYSKEYDOWN, OnHookSysKeyDown)
+ MESSAGE_HANDLER(WM_SYSKEYUP, OnHookSysKeyUp)
+ MESSAGE_HANDLER(WM_SYSCHAR, OnHookSysChar)
+ MESSAGE_HANDLER(WM_KEYDOWN, OnHookKeyDown)
+ MESSAGE_HANDLER(WM_NEXTMENU, OnHookNextMenu)
+ MESSAGE_HANDLER(WM_CHAR, OnHookChar)
+ END_MSG_MAP()
+
+ LRESULT OnForwardMsg(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LPMSG pMsg = (LPMSG)lParam;
+ if(pMsg->message >= WM_MOUSEFIRST && pMsg->message <= WM_MOUSELAST)
+ m_bKeyboardInput = false;
+ else if(pMsg->message >= WM_KEYFIRST && pMsg->message <= WM_KEYLAST)
+ m_bKeyboardInput = true;
+ LRESULT lRet = 0;
+ ProcessWindowMessage(pMsg->hwnd, pMsg->message, pMsg->wParam, pMsg->lParam, lRet, 3);
+ return lRet;
+ }
+
+ LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ // Let the toolbar initialize itself
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+ // get and use system settings
+ T* pT = static_cast<T*>(this);
+ pT->GetSystemSettings();
+ // Parent init
+ ATL::CWindow wndParent = GetParent();
+ ATL::CWindow wndTopLevelParent = wndParent.GetTopLevelParent();
+ m_wndParent.SubclassWindow(wndTopLevelParent);
+ // Toolbar Init
+ SetButtonStructSize();
+ SetImageList(NULL);
+
+ // Create message hook if needed
+ CWindowCreateCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CCommandBarCtrlImpl::OnCreate.\n"));
+ ATLASSERT(FALSE);
+ return -1;
+ }
+
+ if(s_pmapMsgHook == NULL)
+ {
+ ATLTRY(s_pmapMsgHook = new CMsgHookMap);
+ ATLASSERT(s_pmapMsgHook != NULL);
+ }
+
+ if(s_pmapMsgHook != NULL)
+ {
+ DWORD dwThreadID = ::GetCurrentThreadId();
+ _MsgHookData* pData = s_pmapMsgHook->Lookup(dwThreadID);
+ if(pData == NULL)
+ {
+ ATLTRY(pData = new _MsgHookData);
+ ATLASSERT(pData != NULL);
+ HHOOK hMsgHook = ::SetWindowsHookEx(WH_GETMESSAGE, MessageHookProc, ModuleHelper::GetModuleInstance(), dwThreadID);
+ ATLASSERT(hMsgHook != NULL);
+ if(pData != NULL && hMsgHook != NULL)
+ {
+ pData->hMsgHook = hMsgHook;
+ pData->dwUsage = 1;
+ BOOL bRet = s_pmapMsgHook->Add(dwThreadID, pData);
+ bRet;
+ ATLASSERT(bRet);
+ }
+ }
+ else
+ {
+ (pData->dwUsage)++;
+ }
+ }
+ lock.Unlock();
+
+ // Get layout
+#if (WINVER >= 0x0500)
+ m_bLayoutRTL = ((GetExStyle() & WS_EX_LAYOUTRTL) != 0);
+#endif // (WINVER >= 0x0500)
+
+ return lRet;
+ }
+
+ LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+
+#if _WTL_CMDBAR_VISTA_MENUS
+ if(m_bVistaMenus && (m_hMenu != NULL))
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_RemoveVistaBitmapsFromMenu();
+ }
+
+ for(int i = 0; i < m_arrVistaBitmap.GetSize(); i++)
+ {
+ if(m_arrVistaBitmap[i] != NULL)
+ ::DeleteObject(m_arrVistaBitmap[i]);
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+
+ if(m_bAttachedMenu) // nothing to do in this mode
+ return lRet;
+
+ CWindowCreateCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CCommandBarCtrlImpl::OnDestroy.\n"));
+ ATLASSERT(FALSE);
+ return lRet;
+ }
+
+ if(s_pmapMsgHook != NULL)
+ {
+ DWORD dwThreadID = ::GetCurrentThreadId();
+ _MsgHookData* pData = s_pmapMsgHook->Lookup(dwThreadID);
+ if(pData != NULL)
+ {
+ (pData->dwUsage)--;
+ if(pData->dwUsage == 0)
+ {
+ BOOL bRet = ::UnhookWindowsHookEx(pData->hMsgHook);
+ ATLASSERT(bRet);
+ bRet = s_pmapMsgHook->Remove(dwThreadID);
+ ATLASSERT(bRet);
+ if(bRet)
+ delete pData;
+ }
+
+ if(s_pmapMsgHook->GetSize() == 0)
+ {
+ delete s_pmapMsgHook;
+ s_pmapMsgHook = NULL;
+ }
+ }
+ }
+
+ lock.Unlock();
+
+ return lRet;
+ }
+
+ LRESULT OnKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnKeyDown\n"));
+#endif
+ bHandled = FALSE;
+ // Simulate Alt+Space for the parent
+ if(wParam == VK_SPACE)
+ {
+ m_wndParent.PostMessage(WM_SYSKEYDOWN, wParam, lParam | (1 << 29));
+ bHandled = TRUE;
+ }
+#if (_WIN32_IE >= 0x0500)
+ else if(wParam == VK_LEFT || wParam == VK_RIGHT)
+ {
+ WPARAM wpNext = m_bLayoutRTL ? VK_LEFT : VK_RIGHT;
+
+ if(!m_bMenuActive)
+ {
+ T* pT = static_cast<T*>(this);
+ int nBtn = GetHotItem();
+ int nNextBtn = (wParam == wpNext) ? pT->GetNextMenuItem(nBtn) : pT->GetPreviousMenuItem(nBtn);
+ if(nNextBtn == -2)
+ {
+ SetHotItem(-1);
+ if(pT->DisplayChevronMenu())
+ bHandled = TRUE;
+ }
+ }
+ }
+#endif // (_WIN32_IE >= 0x0500)
+ return 0;
+ }
+
+ LRESULT OnKeyUp(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnKeyUp\n"));
+#endif
+ if(wParam != VK_SPACE)
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnChar(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnChar\n"));
+#endif
+ if(wParam != VK_SPACE)
+ bHandled = FALSE;
+ else
+ return 0;
+ // Security
+ if(!m_wndParent.IsWindowEnabled() || ::GetFocus() != m_hWnd)
+ return 0;
+
+ // Handle mnemonic press when we have focus
+ int nBtn = 0;
+ if(wParam != VK_RETURN && !MapAccelerator((TCHAR)LOWORD(wParam), nBtn))
+ {
+#if (_WIN32_IE >= 0x0500)
+ if((TCHAR)LOWORD(wParam) != _chChevronShortcut)
+#endif // (_WIN32_IE >= 0x0500)
+ ::MessageBeep(0);
+ }
+ else
+ {
+#if (_WIN32_IE >= 0x0500)
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+ RECT rcBtn = { 0 };
+ GetItemRect(nBtn, &rcBtn);
+ TBBUTTON tbb = { 0 };
+ GetButton(nBtn, &tbb);
+ if((tbb.fsState & TBSTATE_ENABLED) != 0 && (tbb.fsState & TBSTATE_HIDDEN) == 0 && rcBtn.right <= rcClient.right)
+ {
+#endif // (_WIN32_IE >= 0x0500)
+ PostMessage(WM_KEYDOWN, VK_DOWN, 0L);
+ if(wParam != VK_RETURN)
+ SetHotItem(nBtn);
+#if (_WIN32_IE >= 0x0500)
+ }
+ else
+ {
+ ::MessageBeep(0);
+ bHandled = TRUE;
+ }
+#endif // (_WIN32_IE >= 0x0500)
+ }
+ return 0;
+ }
+
+ LRESULT OnSysKeyDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnSysKeyDown\n"));
+#endif
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnSysKeyUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnSysKeyUp\n"));
+#endif
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnSysChar(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnSysChar\n"));
+#endif
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_bAttachedMenu || (m_dwExtendedStyle & CBR_EX_TRANSPARENT))
+ {
+ bHandled = FALSE;
+ return 0;
+ }
+
+ CDCHandle dc = (HDC)wParam;
+ RECT rect = { 0 };
+ GetClientRect(&rect);
+ dc.FillRect(&rect, COLOR_MENU);
+
+ return 1; // don't do the default erase
+ }
+
+ LRESULT OnInitMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ int nIndex = GetHotItem();
+ SendMessage(WM_MENUSELECT, MAKEWPARAM(nIndex, MF_POPUP|MF_HILITE), (LPARAM)m_hMenu);
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnInitMenuPopup(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ if((BOOL)HIWORD(lParam)) // System menu, do nothing
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+ if(!(m_bAttachedMenu || m_bMenuActive)) // Not attached or ours, do nothing
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnInitMenuPopup\n"));
+#endif
+ // forward to the parent or subclassed window, so it can handle update UI
+ LRESULT lRet = 0;
+ if(m_bAttachedMenu)
+ lRet = DefWindowProc(uMsg, wParam, (lParam || m_bContextMenu) ? lParam : GetHotItem());
+ else
+ lRet = m_wndParent.DefWindowProc(uMsg, wParam, (lParam || m_bContextMenu) ? lParam : GetHotItem());
+
+#if _WTL_CMDBAR_VISTA_MENUS
+ // If Vista menus are active, just set bitmaps and return
+ if(m_bVistaMenus)
+ {
+ CMenuHandle menu = (HMENU)wParam;
+ ATLASSERT(menu.m_hMenu != NULL);
+
+ for(int i = 0; i < menu.GetMenuItemCount(); i++)
+ {
+ WORD nID = (WORD)menu.GetMenuItemID(i);
+ int nIndex = m_arrCommand.Find(nID);
+
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_BITMAP;
+ mii.hbmpItem = (m_bImagesVisible && (nIndex != -1)) ? m_arrVistaBitmap[nIndex] : NULL;
+ menu.SetMenuItemInfo(i, TRUE, &mii);
+ }
+
+ return lRet;
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+
+ // Convert menu items to ownerdraw, add our data
+ if(m_bImagesVisible)
+ {
+ CMenuHandle menuPopup = (HMENU)wParam;
+ ATLASSERT(menuPopup.m_hMenu != NULL);
+
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ TCHAR szString[pT->_nMaxMenuItemTextLength];
+ BOOL bRet = FALSE;
+ for(int i = 0; i < menuPopup.GetMenuItemCount(); i++)
+ {
+ CMenuItemInfo mii;
+ mii.cch = pT->_nMaxMenuItemTextLength;
+ mii.fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_ID | MIIM_STATE | MIIM_SUBMENU | MIIM_TYPE;
+ mii.dwTypeData = szString;
+ bRet = menuPopup.GetMenuItemInfo(i, TRUE, &mii);
+ ATLASSERT(bRet);
+
+ if(!(mii.fType & MFT_OWNERDRAW)) // Not already an ownerdraw item
+ {
+ mii.fMask = MIIM_DATA | MIIM_TYPE | MIIM_STATE;
+ _MenuItemData* pMI = NULL;
+ ATLTRY(pMI = new _MenuItemData);
+ ATLASSERT(pMI != NULL);
+ if(pMI != NULL)
+ {
+ pMI->fType = mii.fType;
+ pMI->fState = mii.fState;
+ mii.fType |= MFT_OWNERDRAW;
+ pMI->iButton = -1;
+ for(int j = 0; j < m_arrCommand.GetSize(); j++)
+ {
+ if(m_arrCommand[j] == mii.wID)
+ {
+ pMI->iButton = j;
+ break;
+ }
+ }
+ int cchLen = lstrlen(szString) + 1;
+ pMI->lpstrText = NULL;
+ ATLTRY(pMI->lpstrText = new TCHAR[cchLen]);
+ ATLASSERT(pMI->lpstrText != NULL);
+ if(pMI->lpstrText != NULL)
+ SecureHelper::strcpy_x(pMI->lpstrText, cchLen, szString);
+ mii.dwItemData = (ULONG_PTR)pMI;
+ bRet = menuPopup.SetMenuItemInfo(i, TRUE, &mii);
+ ATLASSERT(bRet);
+ }
+ }
+ }
+
+ // Add it to the list
+ m_stackMenuHandle.Push(menuPopup.m_hMenu);
+ }
+
+ return lRet;
+ }
+
+ LRESULT OnMenuSelect(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ if(!m_bAttachedMenu) // Not attached, do nothing, forward to parent
+ {
+ m_bPopupItem = (lParam != NULL) && ((HMENU)lParam != m_hMenu) && (HIWORD(wParam) & MF_POPUP);
+ if(m_wndParent.IsWindow())
+ m_wndParent.SendMessage(uMsg, wParam, lParam);
+ bHandled = FALSE;
+ return 1;
+ }
+
+ // Check if a menu is closing, do a cleanup
+ if(HIWORD(wParam) == 0xFFFF && lParam == NULL) // Menu closing
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnMenuSelect - CLOSING!!!!\n"));
+#endif
+ ATLASSERT(m_stackMenuWnd.GetSize() == 0);
+ // Restore the menu items to the previous state for all menus that were converted
+ if(m_bImagesVisible)
+ {
+ HMENU hMenu = NULL;
+ while((hMenu = m_stackMenuHandle.Pop()) != NULL)
+ {
+ CMenuHandle menuPopup = hMenu;
+ ATLASSERT(menuPopup.m_hMenu != NULL);
+ // Restore state and delete menu item data
+ BOOL bRet = FALSE;
+ for(int i = 0; i < menuPopup.GetMenuItemCount(); i++)
+ {
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_DATA | MIIM_TYPE;
+ bRet = menuPopup.GetMenuItemInfo(i, TRUE, &mii);
+ ATLASSERT(bRet);
+
+ _MenuItemData* pMI = (_MenuItemData*)mii.dwItemData;
+ if(pMI != NULL && pMI->IsCmdBarMenuItem())
+ {
+ mii.fMask = MIIM_DATA | MIIM_TYPE | MIIM_STATE;
+ mii.fType = pMI->fType;
+ mii.dwTypeData = pMI->lpstrText;
+ mii.cch = lstrlen(pMI->lpstrText);
+ mii.dwItemData = NULL;
+
+ bRet = menuPopup.SetMenuItemInfo(i, TRUE, &mii);
+ ATLASSERT(bRet);
+
+ delete [] pMI->lpstrText;
+ pMI->dwMagic = 0x6666;
+ delete pMI;
+ }
+ }
+ }
+ }
+ }
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnInternalAutoPopup(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ int nIndex = (int)wParam;
+ T* pT = static_cast<T*>(this);
+ pT->DoPopupMenu(nIndex, false);
+ return 0;
+ }
+
+ LRESULT OnInternalGetBar(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ // Let's make sure we're not embedded in another process
+ if((LPVOID)wParam != NULL)
+ *((DWORD*)wParam) = GetCurrentProcessId();
+ if(IsWindowVisible())
+ return (LRESULT)static_cast<CCommandBarCtrlBase*>(this);
+ else
+ return NULL;
+ }
+
+ LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+#ifndef SPI_GETKEYBOARDCUES
+ const UINT SPI_SETKEYBOARDCUES = 0x100B;
+#endif // !SPI_GETKEYBOARDCUES
+#ifndef SPI_GETFLATMENU
+ const UINT SPI_SETFLATMENU = 0x1023;
+#endif // !SPI_GETFLATMENU
+
+ if(wParam == SPI_SETNONCLIENTMETRICS || wParam == SPI_SETKEYBOARDCUES || wParam == SPI_SETFLATMENU)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->GetSystemSettings();
+ }
+
+ return 0;
+ }
+
+ LRESULT OnWindowPosChanging(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+
+ LPWINDOWPOS lpWP = (LPWINDOWPOS)lParam;
+ int cyMin = ::GetSystemMetrics(SM_CYMENU);
+ if(lpWP->cy < cyMin)
+ lpWP->cy = cyMin;
+
+ return lRet;
+ }
+
+ LRESULT OnMenuChar(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - OnMenuChar\n"));
+#endif
+ bHandled = TRUE;
+ T* pT = static_cast<T*>(this);
+
+ LRESULT lRet;
+ if(m_bMenuActive && LOWORD(wParam) != 0x0D)
+ lRet = 0;
+ else
+ lRet = MAKELRESULT(1, 1);
+
+ if(m_bMenuActive && HIWORD(wParam) == MF_POPUP)
+ {
+ // Convert character to lower/uppercase and possibly Unicode, using current keyboard layout
+ TCHAR ch = (TCHAR)LOWORD(wParam);
+ CMenuHandle menu = (HMENU)lParam;
+ int nCount = ::GetMenuItemCount(menu);
+ int nRetCode = MNC_EXECUTE;
+ BOOL bRet = FALSE;
+ TCHAR szString[pT->_nMaxMenuItemTextLength];
+ WORD wMnem = 0;
+ bool bFound = false;
+ for(int i = 0; i < nCount; i++)
+ {
+ CMenuItemInfo mii;
+ mii.cch = pT->_nMaxMenuItemTextLength;
+ mii.fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_ID | MIIM_STATE | MIIM_SUBMENU | MIIM_TYPE;
+ mii.dwTypeData = szString;
+ bRet = menu.GetMenuItemInfo(i, TRUE, &mii);
+ if(!bRet || (mii.fType & MFT_SEPARATOR))
+ continue;
+ _MenuItemData* pmd = (_MenuItemData*)mii.dwItemData;
+ if(pmd != NULL && pmd->IsCmdBarMenuItem())
+ {
+ LPTSTR p = pmd->lpstrText;
+
+ if(p != NULL)
+ {
+ while(*p && *p != _T('&'))
+ p = ::CharNext(p);
+ if(p != NULL && *p)
+ {
+ DWORD dwP = MAKELONG(*(++p), 0);
+ DWORD dwC = MAKELONG(ch, 0);
+ if(::CharLower((LPTSTR)ULongToPtr(dwP)) == ::CharLower((LPTSTR)ULongToPtr(dwC)))
+ {
+ if(!bFound)
+ {
+ wMnem = (WORD)i;
+ bFound = true;
+ }
+ else
+ {
+ nRetCode = MNC_SELECT;
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ if(bFound)
+ {
+ if(nRetCode == MNC_EXECUTE)
+ {
+ PostMessage(TB_SETHOTITEM, (WPARAM)-1, 0L);
+ pT->GiveFocusBack();
+ }
+ bHandled = TRUE;
+ lRet = MAKELRESULT(wMnem, nRetCode);
+ }
+ }
+ else if(!m_bMenuActive)
+ {
+ int nBtn = 0;
+ if(!MapAccelerator((TCHAR)LOWORD(wParam), nBtn))
+ {
+ bHandled = FALSE;
+ PostMessage(TB_SETHOTITEM, (WPARAM)-1, 0L);
+ pT->GiveFocusBack();
+
+#if (_WIN32_IE >= 0x0500)
+ // check if we should display chevron menu
+ if((TCHAR)LOWORD(wParam) == pT->_chChevronShortcut)
+ {
+ if(pT->DisplayChevronMenu())
+ bHandled = TRUE;
+ }
+#endif // (_WIN32_IE >= 0x0500)
+ }
+ else if(m_wndParent.IsWindowEnabled())
+ {
+#if (_WIN32_IE >= 0x0500)
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+ RECT rcBtn = { 0 };
+ GetItemRect(nBtn, &rcBtn);
+ TBBUTTON tbb = { 0 };
+ GetButton(nBtn, &tbb);
+ if((tbb.fsState & TBSTATE_ENABLED) != 0 && (tbb.fsState & TBSTATE_HIDDEN) == 0 && rcBtn.right <= rcClient.right)
+ {
+#endif // (_WIN32_IE >= 0x0500)
+ if(m_bUseKeyboardCues && !m_bShowKeyboardCues)
+ {
+ m_bAllowKeyboardCues = true;
+ ShowKeyboardCues(true);
+ }
+ pT->TakeFocus();
+ PostMessage(WM_KEYDOWN, VK_DOWN, 0L);
+ SetHotItem(nBtn);
+#if (_WIN32_IE >= 0x0500)
+ }
+ else
+ {
+ ::MessageBeep(0);
+ }
+#endif // (_WIN32_IE >= 0x0500)
+ }
+ }
+
+ return lRet;
+ }
+
+ LRESULT OnDrawItem(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ LPDRAWITEMSTRUCT lpDrawItemStruct = (LPDRAWITEMSTRUCT)lParam;
+ _MenuItemData* pmd = (_MenuItemData*)lpDrawItemStruct->itemData;
+ if(lpDrawItemStruct->CtlType == ODT_MENU && pmd != NULL && pmd->IsCmdBarMenuItem())
+ {
+ T* pT = static_cast<T*>(this);
+ pT->DrawItem(lpDrawItemStruct);
+ }
+ else
+ {
+ bHandled = FALSE;
+ }
+ return (LRESULT)TRUE;
+ }
+
+ LRESULT OnMeasureItem(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ LPMEASUREITEMSTRUCT lpMeasureItemStruct = (LPMEASUREITEMSTRUCT)lParam;
+ _MenuItemData* pmd = (_MenuItemData*)lpMeasureItemStruct->itemData;
+ if(lpMeasureItemStruct->CtlType == ODT_MENU && pmd != NULL && pmd->IsCmdBarMenuItem())
+ {
+ T* pT = static_cast<T*>(this);
+ pT->MeasureItem(lpMeasureItemStruct);
+ }
+ else
+ {
+ bHandled = FALSE;
+ }
+ return (LRESULT)TRUE;
+ }
+
+// API message handlers
+ LRESULT OnAPIGetMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return (LRESULT)m_hMenu;
+ }
+
+ LRESULT OnAPITrackPopupMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ if(lParam == NULL)
+ return FALSE;
+ LPCBRPOPUPMENU lpCBRPopupMenu = (LPCBRPOPUPMENU)lParam;
+ if(lpCBRPopupMenu->cbSize != sizeof(CBRPOPUPMENU))
+ return FALSE;
+
+ T* pT = static_cast<T*>(this);
+ return pT->TrackPopupMenu(lpCBRPopupMenu->hMenu, lpCBRPopupMenu->uFlags, lpCBRPopupMenu->x, lpCBRPopupMenu->y, lpCBRPopupMenu->lptpm);
+ }
+
+ LRESULT OnAPIGetCmdBar(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return (LRESULT)m_hWnd;
+ }
+
+// Parent window message handlers
+ LRESULT OnParentHotItemChange(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ LPNMTBHOTITEM lpNMHT = (LPNMTBHOTITEM)pnmh;
+
+ // Check if this comes from us
+ if(pnmh->hwndFrom != m_hWnd)
+ {
+ bHandled = FALSE;
+ return 0;
+ }
+
+ bool bBlockTracking = false;
+ if((m_dwExtendedStyle & CBR_EX_TRACKALWAYS) == 0)
+ {
+ DWORD dwProcessID;
+ ::GetWindowThreadProcessId(::GetActiveWindow(), &dwProcessID);
+ bBlockTracking = (::GetCurrentProcessId() != dwProcessID);
+ }
+
+ if((!m_wndParent.IsWindowEnabled() || bBlockTracking) && (lpNMHT->dwFlags & HICF_MOUSE))
+ {
+ return 1;
+ }
+ else
+ {
+#ifndef HICF_LMOUSE
+ const DWORD HICF_LMOUSE = 0x00000080; // left mouse button selected
+#endif
+ bHandled = FALSE;
+
+ // Send WM_MENUSELECT to the app if it needs to display a status text
+ if(!(lpNMHT->dwFlags & HICF_MOUSE)
+ && !(lpNMHT->dwFlags & HICF_ACCELERATOR)
+ && !(lpNMHT->dwFlags & HICF_LMOUSE))
+ {
+ if(lpNMHT->dwFlags & HICF_ENTERING)
+ m_wndParent.SendMessage(WM_MENUSELECT, 0, (LPARAM)m_hMenu);
+ if(lpNMHT->dwFlags & HICF_LEAVING)
+ m_wndParent.SendMessage(WM_MENUSELECT, MAKEWPARAM(0, 0xFFFF), NULL);
+ }
+
+ return 0;
+ }
+ }
+
+ LRESULT OnParentDropDown(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ // Check if this comes from us
+ if(pnmh->hwndFrom != m_hWnd)
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+ T* pT = static_cast<T*>(this);
+ if(::GetFocus() != m_hWnd)
+ pT->TakeFocus();
+ LPNMTOOLBAR pNMToolBar = (LPNMTOOLBAR)pnmh;
+ int nIndex = CommandToIndex(pNMToolBar->iItem);
+ m_bContextMenu = false;
+ m_bEscapePressed = false;
+ pT->DoPopupMenu(nIndex, true);
+
+ return TBDDRET_DEFAULT;
+ }
+
+ LRESULT OnParentInitMenuPopup(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ return OnInitMenuPopup(uMsg, wParam, lParam, bHandled);
+ }
+
+ LRESULT OnParentInternalGetBar(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ return OnInternalGetBar(uMsg, wParam, lParam, bHandled);
+ }
+
+ LRESULT OnParentSysCommand(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ bHandled = FALSE;
+ if((m_uSysKey == VK_MENU
+ || (m_uSysKey == VK_F10 && !(::GetKeyState(VK_SHIFT) & 0x80))
+ || m_uSysKey == VK_SPACE)
+ && wParam == SC_KEYMENU)
+ {
+ T* pT = static_cast<T*>(this);
+ if(::GetFocus() == m_hWnd)
+ {
+ pT->GiveFocusBack(); // exit menu "loop"
+ PostMessage(TB_SETHOTITEM, (WPARAM)-1, 0L);
+ }
+ else if(m_uSysKey != VK_SPACE && !m_bSkipMsg)
+ {
+ if(m_bUseKeyboardCues && !m_bShowKeyboardCues && m_bAllowKeyboardCues)
+ ShowKeyboardCues(true);
+
+ pT->TakeFocus(); // enter menu "loop"
+ bHandled = TRUE;
+ }
+ else if(m_uSysKey != VK_SPACE)
+ {
+ bHandled = TRUE;
+ }
+ }
+ m_bSkipMsg = false;
+ return 0;
+ }
+
+ LRESULT OnParentAPIGetMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ return OnAPIGetMenu(uMsg, wParam, lParam, bHandled);
+ }
+
+ LRESULT OnParentMenuChar(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ return OnMenuChar(uMsg, wParam, lParam, bHandled);
+ }
+
+ LRESULT OnParentAPITrackPopupMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ return OnAPITrackPopupMenu(uMsg, wParam, lParam, bHandled);
+ }
+
+ LRESULT OnParentAPIGetCmdBar(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ return OnAPIGetCmdBar(uMsg, wParam, lParam, bHandled);
+ }
+
+ LRESULT OnParentSettingChange(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ OnSettingChange(uMsg, wParam, lParam, bHandled);
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnParentDrawItem(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ return OnDrawItem(uMsg, wParam, lParam, bHandled);
+ }
+
+ LRESULT OnParentMeasureItem(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ return OnMeasureItem(uMsg, wParam, lParam, bHandled);
+ }
+
+ LRESULT OnParentActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ m_bParentActive = (LOWORD(wParam) != WA_INACTIVE);
+ if(!m_bParentActive && m_bUseKeyboardCues && m_bShowKeyboardCues)
+ {
+ ShowKeyboardCues(false); // this will repaint our window
+ }
+ else
+ {
+ Invalidate();
+ UpdateWindow();
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnParentCustomDraw(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ LRESULT lRet = CDRF_DODEFAULT;
+ bHandled = FALSE;
+ if(pnmh->hwndFrom == m_hWnd)
+ {
+ LPNMTBCUSTOMDRAW lpTBCustomDraw = (LPNMTBCUSTOMDRAW)pnmh;
+ if(lpTBCustomDraw->nmcd.dwDrawStage == CDDS_PREPAINT)
+ {
+ lRet = CDRF_NOTIFYITEMDRAW;
+ bHandled = TRUE;
+ }
+ else if(lpTBCustomDraw->nmcd.dwDrawStage == CDDS_ITEMPREPAINT)
+ {
+ if(m_bFlatMenus)
+ {
+#ifndef COLOR_MENUHILIGHT
+ const int COLOR_MENUHILIGHT = 29;
+#endif // !COLOR_MENUHILIGHT
+ bool bDisabled = ((lpTBCustomDraw->nmcd.uItemState & CDIS_DISABLED) == CDIS_DISABLED);
+ if(!bDisabled && ((lpTBCustomDraw->nmcd.uItemState & CDIS_HOT) == CDIS_HOT ||
+ (lpTBCustomDraw->nmcd.uItemState & CDIS_SELECTED) == CDIS_SELECTED))
+ {
+ ::FillRect(lpTBCustomDraw->nmcd.hdc, &lpTBCustomDraw->nmcd.rc, ::GetSysColorBrush(COLOR_MENUHILIGHT));
+ ::FrameRect(lpTBCustomDraw->nmcd.hdc, &lpTBCustomDraw->nmcd.rc, ::GetSysColorBrush(COLOR_HIGHLIGHT));
+ lpTBCustomDraw->clrText = ::GetSysColor(m_bParentActive ? COLOR_HIGHLIGHTTEXT : COLOR_GRAYTEXT);
+ }
+ else if(bDisabled || !m_bParentActive)
+ {
+ lpTBCustomDraw->clrText = ::GetSysColor(COLOR_GRAYTEXT);
+ }
+ CDCHandle dc = lpTBCustomDraw->nmcd.hdc;
+ dc.SetTextColor(lpTBCustomDraw->clrText);
+ dc.SetBkMode(lpTBCustomDraw->nStringBkMode);
+ HFONT hFont = GetFont();
+ HFONT hFontOld = NULL;
+ if(hFont != NULL)
+ hFontOld = dc.SelectFont(hFont);
+ const int cchText = 200;
+ TCHAR szText[cchText] = { 0 };
+ TBBUTTONINFO tbbi = { 0 };
+ tbbi.cbSize = sizeof(TBBUTTONINFO);
+ tbbi.dwMask = TBIF_TEXT;
+ tbbi.pszText = szText;
+ tbbi.cchText = cchText;
+ GetButtonInfo((int)lpTBCustomDraw->nmcd.dwItemSpec, &tbbi);
+ dc.DrawText(szText, -1, &lpTBCustomDraw->nmcd.rc, DT_SINGLELINE | DT_CENTER | DT_VCENTER | (m_bShowKeyboardCues ? 0 : DT_HIDEPREFIX));
+ if(hFont != NULL)
+ dc.SelectFont(hFontOld);
+ lRet = CDRF_SKIPDEFAULT;
+ bHandled = TRUE;
+ }
+ else if(!m_bParentActive)
+ {
+ lpTBCustomDraw->clrText = ::GetSysColor(COLOR_GRAYTEXT);
+ bHandled = TRUE;
+ }
+ }
+ }
+ return lRet;
+ }
+
+// Message hook handlers
+ LRESULT OnHookMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ static POINT s_point = { -1, -1 };
+ DWORD dwPoint = ::GetMessagePos();
+ POINT point = { GET_X_LPARAM(dwPoint), GET_Y_LPARAM(dwPoint) };
+
+ bHandled = FALSE;
+ if(m_bMenuActive)
+ {
+ if(::WindowFromPoint(point) == m_hWnd)
+ {
+ ScreenToClient(&point);
+ int nHit = HitTest(&point);
+
+ if((point.x != s_point.x || point.y != s_point.y) && nHit >= 0 && nHit < ::GetMenuItemCount(m_hMenu) && nHit != m_nPopBtn && m_nPopBtn != -1)
+ {
+ TBBUTTON tbb = { 0 };
+ GetButton(nHit, &tbb);
+ if((tbb.fsState & TBSTATE_ENABLED) != 0)
+ {
+ m_nNextPopBtn = nHit | 0xFFFF0000;
+ HWND hWndMenu = m_stackMenuWnd.GetCurrent();
+ ATLASSERT(hWndMenu != NULL);
+
+ // this one is needed to close a menu if mouse button was down
+ ::PostMessage(hWndMenu, WM_LBUTTONUP, 0, MAKELPARAM(point.x, point.y));
+ // this one closes a popup menu
+ ::PostMessage(hWndMenu, WM_KEYDOWN, VK_ESCAPE, 0L);
+
+ bHandled = TRUE;
+ }
+ }
+ }
+ }
+ else
+ {
+ ScreenToClient(&point);
+ }
+
+ s_point = point;
+ return 0;
+ }
+
+ LRESULT OnHookSysKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ bHandled = FALSE;
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Hook WM_SYSKEYDOWN (0x%2.2X)\n"), wParam);
+#endif
+
+ if(wParam == VK_MENU && m_bParentActive && m_bUseKeyboardCues && !m_bShowKeyboardCues && m_bAllowKeyboardCues)
+ ShowKeyboardCues(true);
+
+ if(wParam != VK_SPACE && !m_bMenuActive && ::GetFocus() == m_hWnd)
+ {
+ m_bAllowKeyboardCues = false;
+ PostMessage(TB_SETHOTITEM, (WPARAM)-1, 0L);
+ T* pT = static_cast<T*>(this);
+ pT->GiveFocusBack();
+ m_bSkipMsg = true;
+ }
+ else
+ {
+ if(wParam == VK_SPACE && m_bUseKeyboardCues && m_bShowKeyboardCues)
+ {
+ m_bAllowKeyboardCues = true;
+ ShowKeyboardCues(false);
+ }
+ m_uSysKey = (UINT)wParam;
+ }
+ return 0;
+ }
+
+ LRESULT OnHookSysKeyUp(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(!m_bAllowKeyboardCues)
+ m_bAllowKeyboardCues = true;
+ bHandled = FALSE;
+ wParam;
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Hook WM_SYSKEYUP (0x%2.2X)\n"), wParam);
+#endif
+ return 0;
+ }
+
+ LRESULT OnHookSysChar(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ bHandled = FALSE;
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Hook WM_SYSCHAR (0x%2.2X)\n"), wParam);
+#endif
+
+ if(!m_bMenuActive && m_hWndHook != m_hWnd && wParam != VK_SPACE)
+ bHandled = TRUE;
+ return 0;
+ }
+
+ LRESULT OnHookKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Hook WM_KEYDOWN (0x%2.2X)\n"), wParam);
+#endif
+ bHandled = FALSE;
+ T* pT = static_cast<T*>(this);
+
+ if(wParam == VK_ESCAPE && m_stackMenuWnd.GetSize() <= 1)
+ {
+ if(m_bMenuActive && !m_bContextMenu)
+ {
+ int nHot = GetHotItem();
+ if(nHot == -1)
+ nHot = m_nPopBtn;
+ if(nHot == -1)
+ nHot = 0;
+ SetHotItem(nHot);
+ bHandled = TRUE;
+ pT->TakeFocus();
+ m_bEscapePressed = true; // To keep focus
+ m_bSkipPostDown = false;
+ }
+ else if(::GetFocus() == m_hWnd && m_wndParent.IsWindow())
+ {
+ SetHotItem(-1);
+ pT->GiveFocusBack();
+ bHandled = TRUE;
+ }
+ }
+ else if(wParam == VK_RETURN || wParam == VK_UP || wParam == VK_DOWN)
+ {
+ if(!m_bMenuActive && ::GetFocus() == m_hWnd && m_wndParent.IsWindow())
+ {
+ int nHot = GetHotItem();
+ if(nHot != -1)
+ {
+ if(wParam != VK_RETURN)
+ {
+ if(!m_bSkipPostDown)
+ {
+// IE4 only: WM_KEYDOWN doesn't generate TBN_DROPDOWN, we need to simulate a mouse click
+#if (_WIN32_IE < 0x0500)
+ DWORD dwMajor = 0, dwMinor = 0;
+ ATL::AtlGetCommCtrlVersion(&dwMajor, &dwMinor);
+ if(dwMajor <= 4 || (dwMajor == 5 && dwMinor < 80))
+ {
+ RECT rect;
+ GetItemRect(nHot, &rect);
+ PostMessage(WM_LBUTTONDOWN, MK_LBUTTON, MAKELPARAM(rect.left, rect.top));
+ }
+#endif // (_WIN32_IE < 0x0500)
+ PostMessage(WM_KEYDOWN, VK_DOWN, 0L);
+ m_bSkipPostDown = true;
+ }
+ else
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - skipping posting another VK_DOWN\n"));
+ m_bSkipPostDown = false;
+ }
+ }
+ }
+ else
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Can't find hot button\n"));
+ }
+ }
+ if(wParam == VK_RETURN && m_bMenuActive)
+ {
+ PostMessage(TB_SETHOTITEM, (WPARAM)-1, 0L);
+ m_nNextPopBtn = -1;
+ pT->GiveFocusBack();
+ }
+ }
+ else if(wParam == VK_LEFT || wParam == VK_RIGHT)
+ {
+ WPARAM wpNext = m_bLayoutRTL ? VK_LEFT : VK_RIGHT;
+ WPARAM wpPrev = m_bLayoutRTL ? VK_RIGHT : VK_LEFT;
+
+ if(m_bMenuActive && !m_bContextMenu && !(wParam == wpNext && m_bPopupItem))
+ {
+ bool bAction = false;
+ if(wParam == wpPrev && s_pCurrentBar->m_stackMenuWnd.GetSize() == 1)
+ {
+ m_nNextPopBtn = pT->GetPreviousMenuItem(m_nPopBtn);
+ if(m_nNextPopBtn != -1)
+ bAction = true;
+ }
+ else if(wParam == wpNext)
+ {
+ m_nNextPopBtn = pT->GetNextMenuItem(m_nPopBtn);
+ if(m_nNextPopBtn != -1)
+ bAction = true;
+ }
+ HWND hWndMenu = m_stackMenuWnd.GetCurrent();
+ ATLASSERT(hWndMenu != NULL);
+
+ // Close the popup menu
+ if(bAction)
+ {
+ ::PostMessage(hWndMenu, WM_KEYDOWN, VK_ESCAPE, 0L);
+ if(wParam == wpNext)
+ {
+ int cItem = m_stackMenuWnd.GetSize() - 1;
+ while(cItem >= 0)
+ {
+ hWndMenu = m_stackMenuWnd[cItem];
+ if(hWndMenu != NULL)
+ ::PostMessage(hWndMenu, WM_KEYDOWN, VK_ESCAPE, 0L);
+ cItem--;
+ }
+ }
+#if (_WIN32_IE >= 0x0500)
+ if(m_nNextPopBtn == -2)
+ {
+ m_nNextPopBtn = -1;
+ pT->DisplayChevronMenu();
+ }
+#endif // (_WIN32_IE >= 0x0500)
+ bHandled = TRUE;
+ }
+ }
+ }
+ return 0;
+ }
+
+ LRESULT OnHookNextMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Hook WM_NEXTMENU\n"));
+#endif
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnHookChar(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Hook WM_CHAR (0x%2.2X)\n"), wParam);
+#endif
+ bHandled = (wParam == VK_ESCAPE);
+ return 0;
+ }
+
+// Implementation - ownerdraw overrideables and helpers
+ void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
+ {
+ T* pT = static_cast<T*>(this);
+ if(m_bFlatMenus)
+ pT->DrawItemFlat(lpDrawItemStruct);
+ else
+ pT->DrawItem3D(lpDrawItemStruct);
+
+ }
+
+ void DrawItem3D(LPDRAWITEMSTRUCT lpDrawItemStruct)
+ {
+ _MenuItemData* pmd = (_MenuItemData*)lpDrawItemStruct->itemData;
+ CDCHandle dc = lpDrawItemStruct->hDC;
+ const RECT& rcItem = lpDrawItemStruct->rcItem;
+ T* pT = static_cast<T*>(this);
+
+ if(pmd->fType & MFT_SEPARATOR)
+ {
+ // draw separator
+ RECT rc = rcItem;
+ rc.top += (rc.bottom - rc.top) / 2; // vertical center
+ dc.DrawEdge(&rc, EDGE_ETCHED, BF_TOP); // draw separator line
+ }
+ else // not a separator
+ {
+ BOOL bDisabled = lpDrawItemStruct->itemState & ODS_GRAYED;
+ BOOL bSelected = lpDrawItemStruct->itemState & ODS_SELECTED;
+ BOOL bChecked = lpDrawItemStruct->itemState & ODS_CHECKED;
+ BOOL bHasImage = FALSE;
+
+ if(LOWORD(lpDrawItemStruct->itemID) == (WORD)-1)
+ bSelected = FALSE;
+ RECT rcButn = { rcItem.left, rcItem.top, rcItem.left + m_szButton.cx, rcItem.top + m_szButton.cy }; // button rect
+ ::OffsetRect(&rcButn, 0, ((rcItem.bottom - rcItem.top) - (rcButn.bottom - rcButn.top)) / 2); // center vertically
+
+ int iButton = pmd->iButton;
+ if(iButton >= 0)
+ {
+ bHasImage = TRUE;
+
+ // calc drawing point
+ SIZE sz = { rcButn.right - rcButn.left - m_szBitmap.cx, rcButn.bottom - rcButn.top - m_szBitmap.cy };
+ sz.cx /= 2;
+ sz.cy /= 2;
+ POINT point = { rcButn.left + sz.cx, rcButn.top + sz.cy };
+
+ // fill background depending on state
+ if(!bChecked || (bSelected && !bDisabled))
+ {
+ if(!bDisabled)
+ dc.FillRect(&rcButn, (bChecked && !bSelected) ? COLOR_3DLIGHT : COLOR_MENU);
+ else
+ dc.FillRect(&rcButn, COLOR_MENU);
+ }
+ else
+ {
+ COLORREF crTxt = dc.SetTextColor(::GetSysColor(COLOR_BTNFACE));
+ COLORREF crBk = dc.SetBkColor(::GetSysColor(COLOR_BTNHILIGHT));
+ CBrush hbr(CDCHandle::GetHalftoneBrush());
+ dc.SetBrushOrg(rcButn.left, rcButn.top);
+ dc.FillRect(&rcButn, hbr);
+ dc.SetTextColor(crTxt);
+ dc.SetBkColor(crBk);
+ }
+
+ // draw disabled or normal
+ if(!bDisabled)
+ {
+ // draw pushed-in or popped-out edge
+ if(bSelected || bChecked)
+ {
+ RECT rc2 = rcButn;
+ dc.DrawEdge(&rc2, bChecked ? BDR_SUNKENOUTER : BDR_RAISEDINNER, BF_RECT);
+ }
+ // draw the image
+ ::ImageList_Draw(m_hImageList, iButton, dc, point.x, point.y, ILD_TRANSPARENT);
+ }
+ else
+ {
+ HBRUSH hBrushBackground = bChecked ? NULL : ::GetSysColorBrush(COLOR_MENU);
+ pT->DrawBitmapDisabled(dc, iButton, point, hBrushBackground);
+ }
+ }
+ else
+ {
+ // no image - look for custom checked/unchecked bitmaps
+ CMenuItemInfo info;
+ info.fMask = MIIM_CHECKMARKS | MIIM_TYPE;
+ ::GetMenuItemInfo((HMENU)lpDrawItemStruct->hwndItem, lpDrawItemStruct->itemID, MF_BYCOMMAND, &info);
+ if(bChecked || info.hbmpUnchecked != NULL)
+ {
+ BOOL bRadio = ((info.fType & MFT_RADIOCHECK) != 0);
+ bHasImage = pT->DrawCheckmark(dc, rcButn, bSelected, bDisabled, bRadio, bChecked ? info.hbmpChecked : info.hbmpUnchecked);
+ }
+ }
+
+ // draw item text
+ int cxButn = m_szButton.cx;
+ COLORREF colorBG = ::GetSysColor(bSelected ? COLOR_HIGHLIGHT : COLOR_MENU);
+ if(bSelected || lpDrawItemStruct->itemAction == ODA_SELECT)
+ {
+ RECT rcBG = rcItem;
+ if(bHasImage)
+ rcBG.left += cxButn + s_kcxGap;
+ dc.FillRect(&rcBG, bSelected ? COLOR_HIGHLIGHT : COLOR_MENU);
+ }
+
+ // calc text rectangle and colors
+ RECT rcText = rcItem;
+ rcText.left += cxButn + s_kcxGap + s_kcxTextMargin;
+ rcText.right -= cxButn;
+ dc.SetBkMode(TRANSPARENT);
+ COLORREF colorText = ::GetSysColor(bDisabled ? (bSelected ? COLOR_GRAYTEXT : COLOR_3DSHADOW) : (bSelected ? COLOR_HIGHLIGHTTEXT : COLOR_MENUTEXT));
+
+ // font already selected by Windows
+ if(bDisabled && (!bSelected || colorText == colorBG))
+ {
+ // disabled - draw shadow text shifted down and right 1 pixel (unles selected)
+ RECT rcDisabled = rcText;
+ ::OffsetRect(&rcDisabled, 1, 1);
+ pT->DrawMenuText(dc, rcDisabled, pmd->lpstrText, ::GetSysColor(COLOR_3DHILIGHT));
+ }
+ pT->DrawMenuText(dc, rcText, pmd->lpstrText, colorText); // finally!
+ }
+ }
+
+ void DrawItemFlat(LPDRAWITEMSTRUCT lpDrawItemStruct)
+ {
+ _MenuItemData* pmd = (_MenuItemData*)lpDrawItemStruct->itemData;
+ CDCHandle dc = lpDrawItemStruct->hDC;
+ const RECT& rcItem = lpDrawItemStruct->rcItem;
+ T* pT = static_cast<T*>(this);
+
+#ifndef COLOR_MENUHILIGHT
+ const int COLOR_MENUHILIGHT = 29;
+#endif // !COLOR_MENUHILIGHT
+
+ BOOL bDisabled = lpDrawItemStruct->itemState & ODS_GRAYED;
+ BOOL bSelected = lpDrawItemStruct->itemState & ODS_SELECTED;
+ BOOL bChecked = lpDrawItemStruct->itemState & ODS_CHECKED;
+
+ // paint background
+ if(bSelected || lpDrawItemStruct->itemAction == ODA_SELECT)
+ {
+ if(bSelected)
+ {
+ dc.FillRect(&rcItem, ::GetSysColorBrush(COLOR_MENUHILIGHT));
+ dc.FrameRect(&rcItem, ::GetSysColorBrush(COLOR_HIGHLIGHT));
+ }
+ else
+ {
+ dc.FillRect(&rcItem, ::GetSysColorBrush(COLOR_MENU));
+ }
+ }
+
+ if(pmd->fType & MFT_SEPARATOR)
+ {
+ // draw separator
+ RECT rc = rcItem;
+ rc.top += (rc.bottom - rc.top) / 2; // vertical center
+ dc.DrawEdge(&rc, EDGE_ETCHED, BF_TOP); // draw separator line
+ }
+ else // not a separator
+ {
+ if(LOWORD(lpDrawItemStruct->itemID) == (WORD)-1)
+ bSelected = FALSE;
+ RECT rcButn = { rcItem.left, rcItem.top, rcItem.left + m_szButton.cx, rcItem.top + m_szButton.cy }; // button rect
+ ::OffsetRect(&rcButn, 0, ((rcItem.bottom - rcItem.top) - (rcButn.bottom - rcButn.top)) / 2); // center vertically
+
+ // draw background and border for checked items
+ if(bChecked)
+ {
+ RECT rcCheck = rcButn;
+ ::InflateRect(&rcCheck, -1, -1);
+ if(bSelected)
+ dc.FillRect(&rcCheck, ::GetSysColorBrush(COLOR_MENU));
+ dc.FrameRect(&rcCheck, ::GetSysColorBrush(COLOR_HIGHLIGHT));
+ }
+
+ int iButton = pmd->iButton;
+ if(iButton >= 0)
+ {
+ // calc drawing point
+ SIZE sz = { rcButn.right - rcButn.left - m_szBitmap.cx, rcButn.bottom - rcButn.top - m_szBitmap.cy };
+ sz.cx /= 2;
+ sz.cy /= 2;
+ POINT point = { rcButn.left + sz.cx, rcButn.top + sz.cy };
+
+ // draw disabled or normal
+ if(!bDisabled)
+ {
+ ::ImageList_Draw(m_hImageList, iButton, dc, point.x, point.y, ILD_TRANSPARENT);
+ }
+ else
+ {
+ HBRUSH hBrushBackground = ::GetSysColorBrush((bSelected && !(bDisabled && bChecked)) ? COLOR_MENUHILIGHT : COLOR_MENU);
+ HBRUSH hBrushDisabledImage = ::GetSysColorBrush(COLOR_3DSHADOW);
+ pT->DrawBitmapDisabled(dc, iButton, point, hBrushBackground, hBrushBackground, hBrushDisabledImage);
+ }
+ }
+ else
+ {
+ // no image - look for custom checked/unchecked bitmaps
+ CMenuItemInfo info;
+ info.fMask = MIIM_CHECKMARKS | MIIM_TYPE;
+ ::GetMenuItemInfo((HMENU)lpDrawItemStruct->hwndItem, lpDrawItemStruct->itemID, MF_BYCOMMAND, &info);
+ if(bChecked || info.hbmpUnchecked != NULL)
+ {
+ BOOL bRadio = ((info.fType & MFT_RADIOCHECK) != 0);
+ pT->DrawCheckmark(dc, rcButn, bSelected, bDisabled, bRadio, bChecked ? info.hbmpChecked : info.hbmpUnchecked);
+ }
+ }
+
+ // draw item text
+ int cxButn = m_szButton.cx;
+ // calc text rectangle and colors
+ RECT rcText = rcItem;
+ rcText.left += cxButn + s_kcxGap + s_kcxTextMargin;
+ rcText.right -= cxButn;
+ dc.SetBkMode(TRANSPARENT);
+ COLORREF colorText = ::GetSysColor(bDisabled ? (bSelected ? COLOR_GRAYTEXT : COLOR_3DSHADOW) : (bSelected ? COLOR_HIGHLIGHTTEXT : COLOR_MENUTEXT));
+
+ pT->DrawMenuText(dc, rcText, pmd->lpstrText, colorText); // finally!
+ }
+ }
+
+ void DrawMenuText(CDCHandle& dc, RECT& rc, LPCTSTR lpstrText, COLORREF color)
+ {
+ int nTab = -1;
+ for(int i = 0; i < lstrlen(lpstrText); i++)
+ {
+ if(lpstrText[i] == _T('\t'))
+ {
+ nTab = i;
+ break;
+ }
+ }
+ dc.SetTextColor(color);
+ dc.DrawText(lpstrText, nTab, &rc, DT_SINGLELINE | DT_LEFT | DT_VCENTER | (m_bShowKeyboardCues ? 0 : DT_HIDEPREFIX));
+ if(nTab != -1)
+ dc.DrawText(&lpstrText[nTab + 1], -1, &rc, DT_SINGLELINE | DT_RIGHT | DT_VCENTER | (m_bShowKeyboardCues ? 0 : DT_HIDEPREFIX));
+ }
+
+ void DrawBitmapDisabled(CDCHandle& dc, int nImage, POINT point,
+ HBRUSH hBrushBackground = ::GetSysColorBrush(COLOR_3DFACE),
+ HBRUSH hBrush3DEffect = ::GetSysColorBrush(COLOR_3DHILIGHT),
+ HBRUSH hBrushDisabledImage = ::GetSysColorBrush(COLOR_3DSHADOW))
+ {
+#if (_WIN32_WINNT >= 0x0501) && (_WIN32_IE >= 0x0501)
+ if(m_bAlphaImages)
+ {
+ IMAGELISTDRAWPARAMS ildp = { 0 };
+ ildp.cbSize = sizeof(IMAGELISTDRAWPARAMS);
+ ildp.himl = m_hImageList;
+ ildp.i = nImage;
+ ildp.hdcDst = dc;
+ ildp.x = point.x;
+ ildp.y = point.y;
+ ildp.cx = 0;
+ ildp.cy = 0;
+ ildp.xBitmap = 0;
+ ildp.yBitmap = 0;
+ ildp.fStyle = ILD_TRANSPARENT;
+ ildp.fState = ILS_SATURATE;
+ ildp.Frame = 0;
+ ::ImageList_DrawIndirect(&ildp);
+ }
+ else
+#endif // (_WIN32_WINNT >= 0x0501) && (_WIN32_IE >= 0x0501)
+ {
+ // create memory DC
+ CDC dcMem;
+ dcMem.CreateCompatibleDC(dc);
+ // create mono or color bitmap
+ CBitmap bmp;
+ bmp.CreateCompatibleBitmap(dc, m_szBitmap.cx, m_szBitmap.cy);
+ ATLASSERT(bmp.m_hBitmap != NULL);
+ // draw image into memory DC--fill BG white first
+ HBITMAP hBmpOld = dcMem.SelectBitmap(bmp);
+ dcMem.PatBlt(0, 0, m_szBitmap.cx, m_szBitmap.cy, WHITENESS);
+ // If white is the text color, we can't use the normal painting since
+ // it would blend with the WHITENESS, but the mask is OK
+ UINT uDrawStyle = (::GetSysColor(COLOR_BTNTEXT) == RGB(255, 255, 255)) ? ILD_MASK : ILD_NORMAL;
+ ::ImageList_Draw(m_hImageList, nImage, dcMem, 0, 0, uDrawStyle);
+ dc.DitherBlt(point.x, point.y, m_szBitmap.cx, m_szBitmap.cy, dcMem, NULL, 0, 0, hBrushBackground, hBrush3DEffect, hBrushDisabledImage);
+ dcMem.SelectBitmap(hBmpOld); // restore
+ }
+ }
+
+ // old name
+ BOOL Draw3DCheckmark(CDCHandle& dc, const RECT& rc, BOOL bSelected, BOOL bDisabled, BOOL bRadio, HBITMAP hBmpCheck)
+ {
+ return DrawCheckmark(dc, rc, bSelected, bDisabled, bRadio, hBmpCheck);
+ }
+
+ BOOL DrawCheckmark(CDCHandle& dc, const RECT& rc, BOOL bSelected, BOOL bDisabled, BOOL bRadio, HBITMAP hBmpCheck)
+ {
+ // get checkmark bitmap, if none, use Windows standard
+ SIZE size = { 0, 0 };
+ CBitmapHandle bmp = hBmpCheck;
+ if(hBmpCheck != NULL)
+ {
+ bmp.GetSize(size);
+ }
+ else
+ {
+ size.cx = ::GetSystemMetrics(SM_CXMENUCHECK);
+ size.cy = ::GetSystemMetrics(SM_CYMENUCHECK);
+ bmp.CreateCompatibleBitmap(dc, size.cx, size.cy);
+ ATLASSERT(bmp.m_hBitmap != NULL);
+ }
+ // center bitmap in caller's rectangle
+ RECT rcDest = rc;
+ if((rc.right - rc.left) > size.cx)
+ {
+ rcDest.left = rc.left + (rc.right - rc.left - size.cx) / 2;
+ rcDest.right = rcDest.left + size.cx;
+ }
+ if((rc.bottom - rc.top) > size.cy)
+ {
+ rcDest.top = rc.top + (rc.bottom - rc.top - size.cy) / 2;
+ rcDest.bottom = rcDest.top + size.cy;
+ }
+ // paint background
+ if(!m_bFlatMenus)
+ {
+ if(bSelected && !bDisabled)
+ {
+ dc.FillRect(&rcDest, COLOR_MENU);
+ }
+ else
+ {
+ COLORREF clrTextOld = dc.SetTextColor(::GetSysColor(COLOR_BTNFACE));
+ COLORREF clrBkOld = dc.SetBkColor(::GetSysColor(COLOR_BTNHILIGHT));
+ CBrush hbr(CDCHandle::GetHalftoneBrush());
+ dc.SetBrushOrg(rcDest.left, rcDest.top);
+ dc.FillRect(&rcDest, hbr);
+ dc.SetTextColor(clrTextOld);
+ dc.SetBkColor(clrBkOld);
+ }
+ }
+
+ // create source image
+ CDC dcSource;
+ dcSource.CreateCompatibleDC(dc);
+ HBITMAP hBmpOld = dcSource.SelectBitmap(bmp);
+ // set colors
+ const COLORREF clrBlack = RGB(0, 0, 0);
+ const COLORREF clrWhite = RGB(255, 255, 255);
+ COLORREF clrTextOld = dc.SetTextColor(clrBlack);
+ COLORREF clrBkOld = dc.SetBkColor(clrWhite);
+ // create mask
+ CDC dcMask;
+ dcMask.CreateCompatibleDC(dc);
+ CBitmap bmpMask;
+ bmpMask.CreateBitmap(size.cx, size.cy, 1, 1, NULL);
+ HBITMAP hBmpOld1 = dcMask.SelectBitmap(bmpMask);
+
+ // draw the checkmark transparently
+ int cx = rcDest.right - rcDest.left;
+ int cy = rcDest.bottom - rcDest.top;
+ if(hBmpCheck != NULL)
+ {
+ // build mask based on transparent color
+ dcSource.SetBkColor(m_clrMask);
+ dcMask.SetBkColor(clrBlack);
+ dcMask.SetTextColor(clrWhite);
+ dcMask.BitBlt(0, 0, size.cx, size.cy, dcSource, 0, 0, SRCCOPY);
+ // draw bitmap using the mask
+ dc.BitBlt(rcDest.left, rcDest.top, cx, cy, dcSource, 0, 0, SRCINVERT);
+ dc.BitBlt(rcDest.left, rcDest.top, cx, cy, dcMask, 0, 0, SRCAND);
+ dc.BitBlt(rcDest.left, rcDest.top, cx, cy, dcSource, 0, 0, SRCINVERT);
+ }
+ else
+ {
+ const DWORD ROP_DSno = 0x00BB0226L;
+ const DWORD ROP_DSa = 0x008800C6L;
+ const DWORD ROP_DSo = 0x00EE0086L;
+ const DWORD ROP_DSna = 0x00220326L;
+
+ // draw mask
+ RECT rcSource = { 0, 0, min(size.cx, rc.right - rc.left), min(size.cy, rc.bottom - rc.top) };
+ dcMask.DrawFrameControl(&rcSource, DFC_MENU, bRadio ? DFCS_MENUBULLET : DFCS_MENUCHECK);
+
+ // draw shadow if disabled
+ if(!m_bFlatMenus && bDisabled)
+ {
+ // offset by one pixel
+ int x = rcDest.left + 1;
+ int y = rcDest.top + 1;
+ // paint source bitmap
+ const int nColor = COLOR_3DHILIGHT;
+ dcSource.FillRect(&rcSource, nColor);
+ // draw checkmark - special case black and white colors
+ COLORREF clrCheck = ::GetSysColor(nColor);
+ if(clrCheck == clrWhite)
+ {
+ dc.BitBlt(x, y, cx, cy, dcMask, 0, 0, ROP_DSno);
+ dc.BitBlt(x, y, cx, cy, dcSource, 0, 0, ROP_DSa);
+ }
+ else
+ {
+ if(clrCheck != clrBlack)
+ {
+ ATLASSERT(dcSource.GetTextColor() == clrBlack);
+ ATLASSERT(dcSource.GetBkColor() == clrWhite);
+ dcSource.BitBlt(0, 0, size.cx, size.cy, dcMask, 0, 0, ROP_DSna);
+ }
+ dc.BitBlt(x, y, cx, cy, dcMask, 0, 0, ROP_DSa);
+ dc.BitBlt(x, y, cx, cy, dcSource, 0, 0, ROP_DSo);
+ }
+ }
+
+ // paint source bitmap
+ const int nColor = bDisabled ? COLOR_BTNSHADOW : COLOR_MENUTEXT;
+ dcSource.FillRect(&rcSource, nColor);
+ // draw checkmark - special case black and white colors
+ COLORREF clrCheck = ::GetSysColor(nColor);
+ if(clrCheck == clrWhite)
+ {
+ dc.BitBlt(rcDest.left, rcDest.top, cx, cy, dcMask, 0, 0, ROP_DSno);
+ dc.BitBlt(rcDest.left, rcDest.top, cx, cy, dcSource, 0, 0, ROP_DSa);
+ }
+ else
+ {
+ if(clrCheck != clrBlack)
+ {
+ ATLASSERT(dcSource.GetTextColor() == clrBlack);
+ ATLASSERT(dcSource.GetBkColor() == clrWhite);
+ dcSource.BitBlt(0, 0, size.cx, size.cy, dcMask, 0, 0, ROP_DSna);
+ }
+ dc.BitBlt(rcDest.left, rcDest.top, cx, cy, dcMask, 0, 0, ROP_DSa);
+ dc.BitBlt(rcDest.left, rcDest.top, cx, cy, dcSource, 0, 0, ROP_DSo);
+ }
+ }
+ // restore all
+ dc.SetTextColor(clrTextOld);
+ dc.SetBkColor(clrBkOld);
+ dcSource.SelectBitmap(hBmpOld);
+ dcMask.SelectBitmap(hBmpOld1);
+ if(hBmpCheck == NULL)
+ bmp.DeleteObject();
+ // draw pushed-in hilight
+ if(!m_bFlatMenus && !bDisabled)
+ {
+ if(rc.right - rc.left > size.cx)
+ ::InflateRect(&rcDest, 1,1); // inflate checkmark by one pixel all around
+ dc.DrawEdge(&rcDest, BDR_SUNKENOUTER, BF_RECT);
+ }
+
+ return TRUE;
+ }
+
+ void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
+ {
+ _MenuItemData* pmd = (_MenuItemData*)lpMeasureItemStruct->itemData;
+
+ if(pmd->fType & MFT_SEPARATOR) // separator - use half system height and zero width
+ {
+ lpMeasureItemStruct->itemHeight = ::GetSystemMetrics(SM_CYMENU) / 2;
+ lpMeasureItemStruct->itemWidth = 0;
+ }
+ else
+ {
+ // compute size of text - use DrawText with DT_CALCRECT
+ CWindowDC dc(NULL);
+ CFont fontBold;
+ HFONT hOldFont = NULL;
+ if(pmd->fState & MFS_DEFAULT)
+ {
+ // need bold version of font
+ LOGFONT lf = { 0 };
+ m_fontMenu.GetLogFont(lf);
+ lf.lfWeight += 200;
+ fontBold.CreateFontIndirect(&lf);
+ ATLASSERT(fontBold.m_hFont != NULL);
+ hOldFont = dc.SelectFont(fontBold);
+ }
+ else
+ {
+ hOldFont = dc.SelectFont(m_fontMenu);
+ }
+
+ RECT rcText = { 0, 0, 0, 0 };
+ dc.DrawText(pmd->lpstrText, -1, &rcText, DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_CALCRECT);
+ int cx = rcText.right - rcText.left;
+ dc.SelectFont(hOldFont);
+
+ LOGFONT lf = { 0 };
+ m_fontMenu.GetLogFont(lf);
+ int cy = lf.lfHeight;
+ if(cy < 0)
+ cy = -cy;
+ const int cyMargin = 8;
+ cy += cyMargin;
+
+ // height of item is the bigger of these two
+ lpMeasureItemStruct->itemHeight = max(cy, (int)m_szButton.cy);
+
+ // width is width of text plus a bunch of stuff
+ cx += 2 * s_kcxTextMargin; // L/R margin for readability
+ cx += s_kcxGap; // space between button and menu text
+ cx += 2 * m_szButton.cx; // button width (L=button; R=empty margin)
+ cx += m_cxExtraSpacing; // extra between item text and accelerator keys
+
+ // Windows adds 1 to returned value
+ cx -= ::GetSystemMetrics(SM_CXMENUCHECK) - 1;
+ lpMeasureItemStruct->itemWidth = cx; // done deal
+ }
+ }
+
+// Implementation - Hook procs
+ static LRESULT CALLBACK CreateHookProc(int nCode, WPARAM wParam, LPARAM lParam)
+ {
+ const int cchClassName = 7;
+ TCHAR szClassName[cchClassName] = { 0 };
+
+ if(nCode == HCBT_CREATEWND)
+ {
+ HWND hWndMenu = (HWND)wParam;
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - HCBT_CREATEWND (HWND = %8.8X)\n"), hWndMenu);
+#endif
+
+ ::GetClassName(hWndMenu, szClassName, cchClassName);
+ if(!lstrcmp(_T("#32768"), szClassName))
+ s_pCurrentBar->m_stackMenuWnd.Push(hWndMenu);
+ }
+ else if(nCode == HCBT_DESTROYWND)
+ {
+ HWND hWndMenu = (HWND)wParam;
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - HCBT_DESTROYWND (HWND = %8.8X)\n"), hWndMenu);
+#endif
+
+ ::GetClassName(hWndMenu, szClassName, cchClassName);
+ if(!lstrcmp(_T("#32768"), szClassName))
+ {
+ ATLASSERT(hWndMenu == s_pCurrentBar->m_stackMenuWnd.GetCurrent());
+ s_pCurrentBar->m_stackMenuWnd.Pop();
+ }
+ }
+
+ return ::CallNextHookEx(s_hCreateHook, nCode, wParam, lParam);
+ }
+
+ static LRESULT CALLBACK MessageHookProc(int nCode, WPARAM wParam, LPARAM lParam)
+ {
+ LPMSG pMsg = (LPMSG)lParam;
+
+ if(nCode == HC_ACTION && wParam == PM_REMOVE && pMsg->message != GetGetBarMessage() && pMsg->message != WM_FORWARDMSG)
+ {
+ CCommandBarCtrlBase* pCmdBar = NULL;
+ HWND hWnd = pMsg->hwnd;
+ DWORD dwPID = 0;
+ while(pCmdBar == NULL && hWnd != NULL)
+ {
+ pCmdBar = (CCommandBarCtrlBase*)::SendMessage(hWnd, GetGetBarMessage(), (WPARAM)&dwPID, 0L);
+ hWnd = ::GetParent(hWnd);
+ }
+
+ if(pCmdBar != NULL && dwPID == GetCurrentProcessId())
+ {
+ pCmdBar->m_hWndHook = pMsg->hwnd;
+ ATLASSERT(pCmdBar->IsCommandBarBase());
+
+ if(::IsWindow(pCmdBar->m_hWnd))
+ pCmdBar->SendMessage(WM_FORWARDMSG, 0, (LPARAM)pMsg);
+ else
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - Hook skipping message, can't find command bar!\n"));
+ }
+ }
+
+ LRESULT lRet = 0;
+ ATLASSERT(s_pmapMsgHook != NULL);
+ if(s_pmapMsgHook != NULL)
+ {
+ DWORD dwThreadID = ::GetCurrentThreadId();
+ _MsgHookData* pData = s_pmapMsgHook->Lookup(dwThreadID);
+ if(pData != NULL)
+ {
+ lRet = ::CallNextHookEx(pData->hMsgHook, nCode, wParam, lParam);
+ }
+ }
+ return lRet;
+ }
+
+// Implementation
+ void DoPopupMenu(int nIndex, bool bAnimate)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - DoPopupMenu, bAnimate = %s\n"), bAnimate ? "true" : "false");
+#endif
+
+ // Menu animation flags
+#ifndef TPM_VERPOSANIMATION
+ const UINT TPM_VERPOSANIMATION = 0x1000L;
+#endif
+#ifndef TPM_NOANIMATION
+ const UINT TPM_NOANIMATION = 0x4000L;
+#endif
+ T* pT = static_cast<T*>(this);
+
+ // get popup menu and it's position
+ RECT rect = { 0 };
+ GetItemRect(nIndex, &rect);
+ POINT pt = { rect.left, rect.bottom };
+ MapWindowPoints(NULL, &pt, 1);
+ MapWindowPoints(NULL, &rect);
+ TPMPARAMS TPMParams = { 0 };
+ TPMParams.cbSize = sizeof(TPMPARAMS);
+ TPMParams.rcExclude = rect;
+ HMENU hMenuPopup = ::GetSubMenu(m_hMenu, nIndex);
+ ATLASSERT(hMenuPopup != NULL);
+
+ // get button ID
+ TBBUTTON tbb = { 0 };
+ GetButton(nIndex, &tbb);
+ int nCmdID = tbb.idCommand;
+
+ m_nPopBtn = nIndex; // remember current button's index
+
+ // press button and display popup menu
+ PressButton(nCmdID, TRUE);
+ SetHotItem(nCmdID);
+ pT->DoTrackPopupMenu(hMenuPopup, TPM_LEFTBUTTON | TPM_VERTICAL | TPM_LEFTALIGN | TPM_TOPALIGN |
+ (s_bW2K ? (bAnimate ? TPM_VERPOSANIMATION : TPM_NOANIMATION) : 0), pt.x, pt.y, &TPMParams);
+ PressButton(nCmdID, FALSE);
+ if(::GetFocus() != m_hWnd)
+ SetHotItem(-1);
+
+ m_nPopBtn = -1; // restore
+
+ // eat next message if click is on the same button
+ MSG msg = { 0 };
+ if(::PeekMessage(&msg, m_hWnd, WM_LBUTTONDOWN, WM_LBUTTONDOWN, PM_NOREMOVE) && ::PtInRect(&rect, msg.pt))
+ ::PeekMessage(&msg, m_hWnd, WM_LBUTTONDOWN, WM_LBUTTONDOWN, PM_REMOVE);
+
+ // check if another popup menu should be displayed
+ if(m_nNextPopBtn != -1)
+ {
+ PostMessage(GetAutoPopupMessage(), m_nNextPopBtn & 0xFFFF);
+ if(!(m_nNextPopBtn & 0xFFFF0000) && !m_bPopupItem)
+ PostMessage(WM_KEYDOWN, VK_DOWN, 0);
+ m_nNextPopBtn = -1;
+ }
+ else
+ {
+ m_bContextMenu = false;
+ // If user didn't hit escape, give focus back
+ if(!m_bEscapePressed)
+ {
+ if(m_bUseKeyboardCues && m_bShowKeyboardCues)
+ m_bAllowKeyboardCues = false;
+ pT->GiveFocusBack();
+ }
+ else
+ {
+ SetHotItem(nCmdID);
+ SetAnchorHighlight(TRUE);
+ }
+ }
+ }
+
+ BOOL DoTrackPopupMenu(HMENU hMenu, UINT uFlags, int x, int y, LPTPMPARAMS lpParams = NULL)
+ {
+ CMenuHandle menuPopup = hMenu;
+
+ CWindowCreateCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CCommandBarCtrlImpl::DoTrackPopupMenu.\n"));
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+ ATLASSERT(s_hCreateHook == NULL);
+
+ s_pCurrentBar = static_cast<CCommandBarCtrlBase*>(this);
+
+ s_hCreateHook = ::SetWindowsHookEx(WH_CBT, CreateHookProc, ModuleHelper::GetModuleInstance(), GetCurrentThreadId());
+ ATLASSERT(s_hCreateHook != NULL);
+
+ m_bPopupItem = false;
+ m_bMenuActive = true;
+
+ BOOL bTrackRet = menuPopup.TrackPopupMenuEx(uFlags, x, y, m_hWnd, lpParams);
+ m_bMenuActive = false;
+
+ ::UnhookWindowsHookEx(s_hCreateHook);
+
+ s_hCreateHook = NULL;
+ s_pCurrentBar = NULL;
+
+ lock.Unlock();
+
+ // cleanup - convert menus back to original state
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - TrackPopupMenu - cleanup\n"));
+#endif
+
+ ATLASSERT(m_stackMenuWnd.GetSize() == 0);
+
+ UpdateWindow();
+ ATL::CWindow wndTL = GetTopLevelParent();
+ wndTL.UpdateWindow();
+
+ // restore the menu items to the previous state for all menus that were converted
+ if(m_bImagesVisible)
+ {
+ HMENU hMenuSav = NULL;
+ while((hMenuSav = m_stackMenuHandle.Pop()) != NULL)
+ {
+ menuPopup = hMenuSav;
+ BOOL bRet = FALSE;
+ // restore state and delete menu item data
+ for(int i = 0; i < menuPopup.GetMenuItemCount(); i++)
+ {
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_DATA | MIIM_TYPE | MIIM_ID;
+ bRet = menuPopup.GetMenuItemInfo(i, TRUE, &mii);
+ ATLASSERT(bRet);
+
+ _MenuItemData* pMI = (_MenuItemData*)mii.dwItemData;
+ if(pMI != NULL && pMI->IsCmdBarMenuItem())
+ {
+ mii.fMask = MIIM_DATA | MIIM_TYPE | MIIM_STATE;
+ mii.fType = pMI->fType;
+ mii.fState = pMI->fState;
+ mii.dwTypeData = pMI->lpstrText;
+ mii.cch = lstrlen(pMI->lpstrText);
+ mii.dwItemData = NULL;
+
+ bRet = menuPopup.SetMenuItemInfo(i, TRUE, &mii);
+ // this one triggers WM_MEASUREITEM
+ menuPopup.ModifyMenu(i, MF_BYPOSITION | mii.fType | mii.fState, mii.wID, pMI->lpstrText);
+ ATLASSERT(bRet);
+
+ delete [] pMI->lpstrText;
+ delete pMI;
+ }
+ }
+ }
+ }
+ return bTrackRet;
+ }
+
+ int GetPreviousMenuItem(int nBtn) const
+ {
+ if(nBtn == -1)
+ return -1;
+#if (_WIN32_IE >= 0x0500)
+ RECT rcClient;
+ GetClientRect(&rcClient);
+#endif // (_WIN32_IE >= 0x0500)
+ int nNextBtn;
+ for(nNextBtn = nBtn - 1; nNextBtn != nBtn; nNextBtn--)
+ {
+ if(nNextBtn < 0)
+ nNextBtn = ::GetMenuItemCount(m_hMenu) - 1;
+ TBBUTTON tbb = { 0 };
+ GetButton(nNextBtn, &tbb);
+#if (_WIN32_IE >= 0x0500)
+ RECT rcBtn;
+ GetItemRect(nNextBtn, &rcBtn);
+ if(rcBtn.right > rcClient.right)
+ {
+ nNextBtn = -2; // chevron
+ break;
+ }
+#endif // (_WIN32_IE >= 0x0500)
+ if((tbb.fsState & TBSTATE_ENABLED) != 0 && (tbb.fsState & TBSTATE_HIDDEN) == 0)
+ break;
+ }
+ return (nNextBtn != nBtn) ? nNextBtn : -1;
+ }
+
+ int GetNextMenuItem(int nBtn) const
+ {
+ if(nBtn == -1)
+ return -1;
+#if (_WIN32_IE >= 0x0500)
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+#endif // (_WIN32_IE >= 0x0500)
+ int nNextBtn = 0;
+ int nCount = ::GetMenuItemCount(m_hMenu);
+ for(nNextBtn = nBtn + 1; nNextBtn != nBtn; nNextBtn++)
+ {
+ if(nNextBtn >= nCount)
+ nNextBtn = 0;
+ TBBUTTON tbb = { 0 };
+ GetButton(nNextBtn, &tbb);
+#if (_WIN32_IE >= 0x0500)
+ RECT rcBtn = { 0 };
+ GetItemRect(nNextBtn, &rcBtn);
+ if(rcBtn.right > rcClient.right)
+ {
+ nNextBtn = -2; // chevron
+ break;
+ }
+#endif // (_WIN32_IE >= 0x0500)
+ if((tbb.fsState & TBSTATE_ENABLED) != 0 && (tbb.fsState & TBSTATE_HIDDEN) == 0)
+ break;
+ }
+ return (nNextBtn != nBtn) ? nNextBtn : -1;
+ }
+
+#if (_WIN32_IE >= 0x0500)
+ bool DisplayChevronMenu()
+ {
+ // assume we are in a rebar
+ HWND hWndReBar = GetParent();
+ int nCount = (int)::SendMessage(hWndReBar, RB_GETBANDCOUNT, 0, 0L);
+ bool bRet = false;
+ for(int i = 0; i < nCount; i++)
+ {
+ REBARBANDINFO rbbi = { RunTimeHelper::SizeOf_REBARBANDINFO(), RBBIM_CHILD | RBBIM_STYLE };
+ BOOL bRetBandInfo = (BOOL)::SendMessage(hWndReBar, RB_GETBANDINFO, i, (LPARAM)&rbbi);
+ if(bRetBandInfo && rbbi.hwndChild == m_hWnd)
+ {
+ if((rbbi.fStyle & RBBS_USECHEVRON) != 0)
+ {
+ ::PostMessage(hWndReBar, RB_PUSHCHEVRON, i, 0L);
+ PostMessage(WM_KEYDOWN, VK_DOWN, 0L);
+ bRet = true;
+ }
+ break;
+ }
+ }
+ return bRet;
+ }
+#endif // (_WIN32_IE >= 0x0500)
+
+ void GetSystemSettings()
+ {
+ // refresh our font
+ NONCLIENTMETRICS info = { RunTimeHelper::SizeOf_NONCLIENTMETRICS() };
+ BOOL bRet = ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(info), &info, 0);
+ ATLASSERT(bRet);
+ if(bRet)
+ {
+ LOGFONT logfont = { 0 };
+ if(m_fontMenu.m_hFont != NULL)
+ m_fontMenu.GetLogFont(logfont);
+ if(logfont.lfHeight != info.lfMenuFont.lfHeight ||
+ logfont.lfWidth != info.lfMenuFont.lfWidth ||
+ logfont.lfEscapement != info.lfMenuFont.lfEscapement ||
+ logfont.lfOrientation != info.lfMenuFont.lfOrientation ||
+ logfont.lfWeight != info.lfMenuFont.lfWeight ||
+ logfont.lfItalic != info.lfMenuFont.lfItalic ||
+ logfont.lfUnderline != info.lfMenuFont.lfUnderline ||
+ logfont.lfStrikeOut != info.lfMenuFont.lfStrikeOut ||
+ logfont.lfCharSet != info.lfMenuFont.lfCharSet ||
+ logfont.lfOutPrecision != info.lfMenuFont.lfOutPrecision ||
+ logfont.lfClipPrecision != info.lfMenuFont.lfClipPrecision ||
+ logfont.lfQuality != info.lfMenuFont.lfQuality ||
+ logfont.lfPitchAndFamily != info.lfMenuFont.lfPitchAndFamily ||
+ lstrcmp(logfont.lfFaceName, info.lfMenuFont.lfFaceName) != 0)
+ {
+ HFONT hFontMenu = ::CreateFontIndirect(&info.lfMenuFont);
+ ATLASSERT(hFontMenu != NULL);
+ if(hFontMenu != NULL)
+ {
+ if(m_fontMenu.m_hFont != NULL)
+ m_fontMenu.DeleteObject();
+ m_fontMenu.Attach(hFontMenu);
+ SetFont(m_fontMenu);
+ AddStrings(_T("NS\0")); // for proper item height
+ AutoSize();
+ }
+ }
+ }
+
+ // check if we need extra spacing for menu item text
+ CWindowDC dc(m_hWnd);
+ HFONT hFontOld = dc.SelectFont(m_fontMenu);
+ RECT rcText = { 0, 0, 0, 0 };
+ dc.DrawText(_T("\t"), -1, &rcText, DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_CALCRECT);
+ if((rcText.right - rcText.left) < 4)
+ {
+ ::SetRectEmpty(&rcText);
+ dc.DrawText(_T("x"), -1, &rcText, DT_SINGLELINE | DT_LEFT | DT_VCENTER | DT_CALCRECT);
+ m_cxExtraSpacing = rcText.right - rcText.left;
+ }
+ else
+ {
+ m_cxExtraSpacing = 0;
+ }
+ dc.SelectFont(hFontOld);
+
+ // get Windows version
+ OSVERSIONINFO ovi = { sizeof(OSVERSIONINFO) };
+ ::GetVersionEx(&ovi);
+
+ // query keyboard cues mode (Windows 2000 or later)
+ if(ovi.dwMajorVersion >= 5)
+ {
+#ifndef SPI_GETKEYBOARDCUES
+ const UINT SPI_GETKEYBOARDCUES = 0x100A;
+#endif // !SPI_GETKEYBOARDCUES
+ BOOL bRetVal = TRUE;
+ bRet = ::SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &bRetVal, 0);
+ m_bUseKeyboardCues = (bRet && !bRetVal);
+ m_bAllowKeyboardCues = true;
+ ShowKeyboardCues(!m_bUseKeyboardCues);
+ }
+
+ // query flat menu mode (Windows XP or later)
+ if((ovi.dwMajorVersion == 5 && ovi.dwMinorVersion >= 1) || (ovi.dwMajorVersion > 5))
+ {
+#ifndef SPI_GETFLATMENU
+ const UINT SPI_GETFLATMENU = 0x1022;
+#endif // !SPI_GETFLATMENU
+ BOOL bRetVal = FALSE;
+ bRet = ::SystemParametersInfo(SPI_GETFLATMENU, 0, &bRetVal, 0);
+ m_bFlatMenus = (bRet && bRetVal);
+ }
+
+#if _WTL_CMDBAR_VISTA_MENUS
+ // check if we should use Vista menus
+ bool bVistaMenus = (RunTimeHelper::IsVista() && RunTimeHelper::IsCommCtrl6() && ((m_dwExtendedStyle & CBR_EX_NOVISTAMENUS) == 0));
+
+ if(bVistaMenus)
+ {
+ HMODULE hThemeDLL = ::LoadLibrary(_T("uxtheme.dll"));
+ if(hThemeDLL != NULL)
+ {
+ typedef BOOL (STDAPICALLTYPE *PFN_IsThemeActive)();
+ PFN_IsThemeActive pfnIsThemeActive = (PFN_IsThemeActive)::GetProcAddress(hThemeDLL, "IsThemeActive");
+ ATLASSERT(pfnIsThemeActive != NULL);
+ bVistaMenus = bVistaMenus && (pfnIsThemeActive != NULL) && (pfnIsThemeActive() != FALSE);
+
+ typedef BOOL (STDAPICALLTYPE *PFN_IsAppThemed)();
+ PFN_IsAppThemed pfnIsAppThemed = (PFN_IsAppThemed)::GetProcAddress(hThemeDLL, "IsAppThemed");
+ ATLASSERT(pfnIsAppThemed != NULL);
+ bVistaMenus = bVistaMenus && (pfnIsAppThemed != NULL) && (pfnIsAppThemed() != FALSE);
+
+ ::FreeLibrary(hThemeDLL);
+ }
+ }
+
+ if(!bVistaMenus && m_bVistaMenus && (m_hMenu != NULL) && (m_arrCommand.GetSize() > 0))
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_RemoveVistaBitmapsFromMenu();
+ }
+
+ m_bVistaMenus = bVistaMenus;
+#endif // _WTL_CMDBAR_VISTA_MENUS
+
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("CmdBar - GetSystemSettings:\n m_bFlatMenus = %s\n m_bUseKeyboardCues = %s m_bVistaMenus = %s\n"),
+ m_bFlatMenus ? "true" : "false", m_bUseKeyboardCues ? "true" : "false", m_bVistaMenus ? "true" : "false");
+#endif
+ }
+
+// Implementation - alternate focus mode support
+ void TakeFocus()
+ {
+ if((m_dwExtendedStyle & CBR_EX_ALTFOCUSMODE) && m_hWndFocus == NULL)
+ m_hWndFocus = ::GetFocus();
+ SetFocus();
+ }
+
+ void GiveFocusBack()
+ {
+ if(m_bParentActive)
+ {
+ if((m_dwExtendedStyle & CBR_EX_ALTFOCUSMODE) && ::IsWindow(m_hWndFocus))
+ ::SetFocus(m_hWndFocus);
+ else if(!(m_dwExtendedStyle & CBR_EX_ALTFOCUSMODE) && m_wndParent.IsWindow())
+ m_wndParent.SetFocus();
+ }
+ m_hWndFocus = NULL;
+ SetAnchorHighlight(FALSE);
+ if(m_bUseKeyboardCues && m_bShowKeyboardCues)
+ ShowKeyboardCues(false);
+ m_bSkipPostDown = false;
+ }
+
+ void ShowKeyboardCues(bool bShow)
+ {
+ m_bShowKeyboardCues = bShow;
+ SetDrawTextFlags(DT_HIDEPREFIX, m_bShowKeyboardCues ? 0 : DT_HIDEPREFIX);
+ Invalidate();
+ UpdateWindow();
+ }
+
+// Implementation - internal message helpers
+ static UINT GetAutoPopupMessage()
+ {
+ static UINT uAutoPopupMessage = 0;
+ if(uAutoPopupMessage == 0)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CCommandBarCtrlImpl::GetAutoPopupMessage.\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(uAutoPopupMessage == 0)
+ uAutoPopupMessage = ::RegisterWindowMessage(_T("WTL_CmdBar_InternalAutoPopupMsg"));
+
+ lock.Unlock();
+ }
+ ATLASSERT(uAutoPopupMessage != 0);
+ return uAutoPopupMessage;
+ }
+
+ static UINT GetGetBarMessage()
+ {
+ static UINT uGetBarMessage = 0;
+ if(uGetBarMessage == 0)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CCommandBarCtrlImpl::GetGetBarMessage.\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(uGetBarMessage == 0)
+ uGetBarMessage = ::RegisterWindowMessage(_T("WTL_CmdBar_InternalGetBarMsg"));
+
+ lock.Unlock();
+ }
+ ATLASSERT(uGetBarMessage != 0);
+ return uGetBarMessage;
+ }
+
+// Implementation
+ bool CreateInternalImageList(int cImages)
+ {
+ UINT uFlags = (m_bAlphaImages ? ILC_COLOR32 : ILC_COLOR24) | ILC_MASK;
+ m_hImageList = ::ImageList_Create(m_szBitmap.cx, m_szBitmap.cy, uFlags, cImages, 1);
+ ATLASSERT(m_hImageList != NULL);
+ return (m_hImageList != NULL);
+ }
+
+// Implementation - support for Vista menus
+#if _WTL_CMDBAR_VISTA_MENUS
+ void _AddVistaBitmapsFromImageList(int nStartIndex, int nCount)
+ {
+ // Create display compatible memory DC
+ CClientDC dc(NULL);
+ CDC dcMem;
+ dcMem.CreateCompatibleDC(dc);
+ HBITMAP hBitmapSave = dcMem.GetCurrentBitmap();
+
+ T* pT = static_cast<T*>(this);
+ // Create bitmaps for all menu items
+ for(int i = 0; i < nCount; i++)
+ {
+ HBITMAP hBitmap = pT->_CreateVistaBitmapHelper(nStartIndex + i, dc, dcMem);
+ dcMem.SelectBitmap(hBitmapSave);
+ m_arrVistaBitmap.Add(hBitmap);
+ }
+ }
+
+ void _AddVistaBitmapFromImageList(int nIndex)
+ {
+ // Create display compatible memory DC
+ CClientDC dc(NULL);
+ CDC dcMem;
+ dcMem.CreateCompatibleDC(dc);
+ HBITMAP hBitmapSave = dcMem.GetCurrentBitmap();
+
+ // Create bitmap for menu item
+ T* pT = static_cast<T*>(this);
+ HBITMAP hBitmap = pT->_CreateVistaBitmapHelper(nIndex, dc, dcMem);
+
+ // Select saved bitmap back and add bitmap to the array
+ dcMem.SelectBitmap(hBitmapSave);
+ m_arrVistaBitmap.Add(hBitmap);
+ }
+
+ void _ReplaceVistaBitmapFromImageList(int nIndex)
+ {
+ // Delete existing bitmap
+ if(m_arrVistaBitmap[nIndex] != NULL)
+ ::DeleteObject(m_arrVistaBitmap[nIndex]);
+
+ // Create display compatible memory DC
+ CClientDC dc(NULL);
+ CDC dcMem;
+ dcMem.CreateCompatibleDC(dc);
+ HBITMAP hBitmapSave = dcMem.GetCurrentBitmap();
+
+ // Create bitmap for menu item
+ T* pT = static_cast<T*>(this);
+ HBITMAP hBitmap = pT->_CreateVistaBitmapHelper(nIndex, dc, dcMem);
+
+ // Select saved bitmap back and replace bitmap in the array
+ dcMem.SelectBitmap(hBitmapSave);
+ m_arrVistaBitmap.SetAtIndex(nIndex, hBitmap);
+ }
+
+ HBITMAP _CreateVistaBitmapHelper(int nIndex, HDC hDCSource, HDC hDCTarget)
+ {
+ // Create 32-bit bitmap
+ BITMAPINFO bi = { 0 };
+ bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ bi.bmiHeader.biWidth = m_szBitmap.cx;
+ bi.bmiHeader.biHeight = m_szBitmap.cy;
+ bi.bmiHeader.biPlanes = 1;
+ bi.bmiHeader.biBitCount = 32;
+ bi.bmiHeader.biCompression = BI_RGB;
+ bi.bmiHeader.biSizeImage = 0;
+ bi.bmiHeader.biXPelsPerMeter = 0;
+ bi.bmiHeader.biYPelsPerMeter = 0;
+ bi.bmiHeader.biClrUsed = 0;
+ bi.bmiHeader.biClrImportant = 0;
+ HBITMAP hBitmap = ::CreateDIBSection(hDCSource, &bi, DIB_RGB_COLORS, NULL, NULL, 0);
+ ATLASSERT(hBitmap != NULL);
+
+ // Select bitmap into target DC and draw from image list to it
+ if(hBitmap != NULL)
+ {
+ ::SelectObject(hDCTarget, hBitmap);
+
+ IMAGELISTDRAWPARAMS ildp = { 0 };
+ ildp.cbSize = sizeof(IMAGELISTDRAWPARAMS);
+ ildp.himl = m_hImageList;
+ ildp.i = nIndex;
+ ildp.hdcDst = hDCTarget;
+ ildp.x = 0;
+ ildp.y = 0;
+ ildp.cx = 0;
+ ildp.cy = 0;
+ ildp.xBitmap = 0;
+ ildp.yBitmap = 0;
+ ildp.fStyle = ILD_TRANSPARENT;
+ ildp.fState = ILS_ALPHA;
+ ildp.Frame = 255;
+ ::ImageList_DrawIndirect(&ildp);
+ }
+
+ return hBitmap;
+ }
+
+ void _RemoveVistaBitmapsFromMenu()
+ {
+ CMenuHandle menu = m_hMenu;
+ for(int i = 0; i < m_arrCommand.GetSize(); i++)
+ {
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_BITMAP;
+ mii.hbmpItem = NULL;
+ menu.SetMenuItemInfo(m_arrCommand[i], FALSE, &mii);
+ }
+ }
+#endif // _WTL_CMDBAR_VISTA_MENUS
+};
+
+
+class CCommandBarCtrl : public CCommandBarCtrlImpl<CCommandBarCtrl>
+{
+public:
+ DECLARE_WND_SUPERCLASS(_T("WTL_CommandBar"), GetWndClassName())
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMDICommandBarCtrl - ATL implementation of Command Bars for MDI apps
+
+template <class T, class TBase = CCommandBarCtrlBase, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CMDICommandBarCtrlImpl : public CCommandBarCtrlImpl< T, TBase, TWinTraits>
+{
+public:
+// Data members
+ ATL::CContainedWindow m_wndMDIClient;
+ bool m_bChildMaximized;
+ HWND m_hWndChildMaximized;
+ HICON m_hIconChildMaximized;
+ int m_nBtnPressed;
+ int m_nBtnWasPressed;
+
+ int m_cxyOffset; // offset between nonclient elements
+ int m_cxIconWidth; // small icon width
+ int m_cyIconHeight; // small icon height
+ int m_cxBtnWidth; // nonclient button width
+ int m_cyBtnHeight; // nonclient button height
+ int m_cxLeft; // left nonclient area width
+ int m_cxRight; // right nonclient area width
+
+// Theme declarations and data members
+#ifndef _WTL_NO_AUTO_THEME
+#ifndef _UXTHEME_H_
+ typedef HANDLE HTHEME;
+#endif // !_UXTHEME_H_
+ typedef HTHEME (STDAPICALLTYPE *PFN_OpenThemeData)(HWND hwnd, LPCWSTR pszClassList);
+ typedef HRESULT (STDAPICALLTYPE *PFN_CloseThemeData)(HTHEME hTheme);
+ typedef HRESULT (STDAPICALLTYPE *PFN_DrawThemeBackground)(HTHEME hTheme, HDC hdc, int iPartId, int iStateId, const RECT *pRect, OPTIONAL const RECT *pClipRect);
+ typedef HRESULT (STDAPICALLTYPE *PFN_DrawThemeParentBackground)(HWND hwnd, HDC hdc, OPTIONAL RECT* prc);
+
+ HMODULE m_hThemeDLL;
+ HTHEME m_hTheme;
+ PFN_DrawThemeBackground m_pfnDrawThemeBackground;
+ PFN_DrawThemeParentBackground m_pfnDrawThemeParentBackground;
+#endif // !_WTL_NO_AUTO_THEME
+
+// Constructor/destructor
+ CMDICommandBarCtrlImpl() :
+ m_wndMDIClient(this, 2), m_bChildMaximized(false),
+ m_hWndChildMaximized(NULL), m_hIconChildMaximized(NULL),
+ m_nBtnPressed(-1), m_nBtnWasPressed(-1),
+#ifndef _WTL_NO_AUTO_THEME
+ m_hThemeDLL(NULL), m_hTheme(NULL), m_pfnDrawThemeBackground(NULL), m_pfnDrawThemeParentBackground(NULL),
+#endif // !_WTL_NO_AUTO_THEME
+ m_cxyOffset(2),
+ m_cxIconWidth(16), m_cyIconHeight(16),
+ m_cxBtnWidth(16), m_cyBtnHeight(14),
+ m_cxLeft(20), m_cxRight(55)
+ { }
+
+ ~CMDICommandBarCtrlImpl()
+ {
+ if(m_wndMDIClient.IsWindow())
+/*scary!*/ m_wndMDIClient.UnsubclassWindow();
+ }
+
+// Operations
+ BOOL SetMDIClient(HWND hWndMDIClient)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(::IsWindow(hWndMDIClient));
+ if(!::IsWindow(hWndMDIClient))
+ return FALSE;
+
+#ifdef _DEBUG
+ // BLOCK: Test if the passed window is MDICLIENT
+ {
+ LPCTSTR lpszMDIClientClass = _T("MDICLIENT");
+ const int nNameLen = 9 + 1; // "MDICLIENT" + NULL
+ TCHAR szClassName[nNameLen] = { 0 };
+ ::GetClassName(hWndMDIClient, szClassName, nNameLen);
+ ATLASSERT(lstrcmpi(szClassName, lpszMDIClientClass) == 0);
+ }
+#endif // _DEBUG
+
+ if(m_wndMDIClient.IsWindow())
+/*scary!*/ m_wndMDIClient.UnsubclassWindow();
+
+ return m_wndMDIClient.SubclassWindow(hWndMDIClient);
+ }
+
+// Message maps
+ typedef CCommandBarCtrlImpl< T, TBase, TWinTraits > _baseClass;
+ BEGIN_MSG_MAP(CMDICommandBarCtrlImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+#ifndef _WTL_NO_AUTO_THEME
+ MESSAGE_HANDLER(_GetThemeChangedMsg(), OnThemeChanged)
+#endif // !_WTL_NO_AUTO_THEME
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ MESSAGE_HANDLER(WM_NCCALCSIZE, OnNcCalcSize)
+ MESSAGE_HANDLER(WM_NCPAINT, OnNcPaint)
+ MESSAGE_HANDLER(WM_NCHITTEST, OnNcHitTest)
+ MESSAGE_HANDLER(WM_NCLBUTTONDOWN, OnNcLButtonDown)
+ MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
+ MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
+ MESSAGE_HANDLER(WM_NCLBUTTONDBLCLK, OnNcLButtonDblClk)
+ MESSAGE_HANDLER(WM_CAPTURECHANGED, OnCaptureChanged)
+ CHAIN_MSG_MAP(_baseClass)
+ ALT_MSG_MAP(1) // Parent window messages
+ MESSAGE_HANDLER(WM_ACTIVATE, OnParentActivate)
+ CHAIN_MSG_MAP_ALT(_baseClass, 1)
+ ALT_MSG_MAP(2) // MDI client window messages
+ MESSAGE_HANDLER(WM_MDISETMENU, OnMDISetMenu)
+ // no chaining needed since this was moved from the base class here
+ ALT_MSG_MAP(3) // Message hook messages
+ MESSAGE_RANGE_HANDLER(0, 0xFFFF, OnAllHookMessages)
+ CHAIN_MSG_MAP_ALT(_baseClass, 3)
+ END_MSG_MAP()
+
+// Additional MDI message handlers
+ LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ LRESULT lRet = _baseClass::OnCreate(uMsg, wParam, lParam, bHandled);
+ if(lRet == (LRESULT)-1)
+ return lRet;
+
+#ifndef _WTL_NO_AUTO_THEME
+ // this will fail if theming is not supported
+ m_hThemeDLL = ::LoadLibrary(_T("uxtheme.dll"));
+ if(m_hThemeDLL != NULL)
+ {
+ m_pfnDrawThemeBackground = (PFN_DrawThemeBackground)::GetProcAddress(m_hThemeDLL, "DrawThemeBackground");
+ ATLASSERT(m_pfnDrawThemeBackground != NULL);
+ if(m_pfnDrawThemeBackground != NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_OpenThemeData();
+ }
+ else
+ {
+ ::FreeLibrary(m_hThemeDLL);
+ m_hThemeDLL = NULL;
+ }
+ m_pfnDrawThemeParentBackground = (PFN_DrawThemeParentBackground)::GetProcAddress(m_hThemeDLL, "DrawThemeParentBackground");
+ ATLASSERT(m_pfnDrawThemeParentBackground != NULL);
+ }
+#endif // !_WTL_NO_AUTO_THEME
+
+ return lRet;
+ }
+
+ LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ LRESULT lRet = _baseClass::OnDestroy(uMsg, wParam, lParam, bHandled);
+
+#ifndef _WTL_NO_AUTO_THEME
+ if(m_hThemeDLL != NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_CloseThemeData();
+ ::FreeLibrary(m_hThemeDLL);
+ m_hThemeDLL = NULL;
+ }
+#endif // !_WTL_NO_AUTO_THEME
+
+ return lRet;
+ }
+
+#ifndef _WTL_NO_AUTO_THEME
+ LRESULT OnThemeChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(m_hThemeDLL != NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_CloseThemeData();
+ pT->_OpenThemeData();
+ }
+ return 0;
+ }
+#endif // !_WTL_NO_AUTO_THEME
+
+ LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+ T* pT = static_cast<T*>(this);
+ pT->_AdjustBtnSize(GET_Y_LPARAM(lParam));
+ return lRet;
+ }
+
+ LRESULT OnNcCalcSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+
+ if(m_bChildMaximized && (BOOL)wParam)
+ {
+ LPNCCALCSIZE_PARAMS lpParams = (LPNCCALCSIZE_PARAMS)lParam;
+ if(m_bLayoutRTL)
+ {
+ lpParams->rgrc[0].left += m_cxRight;
+ lpParams->rgrc[0].right -= m_cxLeft;
+ }
+ else
+ {
+ lpParams->rgrc[0].left += m_cxLeft;
+ lpParams->rgrc[0].right -= m_cxRight;
+ }
+ }
+
+ return lRet;
+ }
+
+ LRESULT OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+
+ if(!m_bChildMaximized)
+ return lRet;
+
+ ATLASSERT(m_hWndChildMaximized != NULL && m_hIconChildMaximized != NULL);
+
+ // get DC and window rectangle
+ CWindowDC dc(m_hWnd);
+ RECT rect;
+ GetWindowRect(&rect);
+ int cxWidth = rect.right - rect.left;
+ int cyHeight = rect.bottom - rect.top;
+
+ // paint left side nonclient background and draw icon
+ ::SetRect(&rect, 0, 0, m_cxLeft, cyHeight);
+#ifndef _WTL_NO_AUTO_THEME
+ if(m_hTheme != NULL)
+ {
+ if(m_pfnDrawThemeParentBackground != NULL)
+ m_pfnDrawThemeParentBackground(m_hWnd, dc, &rect);
+ else
+ dc.FillRect(&rect, COLOR_WINDOW);
+ }
+ else
+#endif // !_WTL_NO_AUTO_THEME
+ {
+ if((m_dwExtendedStyle & CBR_EX_TRANSPARENT) != 0)
+ dc.FillRect(&rect, COLOR_3DFACE);
+ else
+ dc.FillRect(&rect, COLOR_MENU);
+ }
+
+ RECT rcIcon = { 0 };
+ T* pT = static_cast<T*>(this);
+ pT->_CalcIconRect(cxWidth, cyHeight, rcIcon);
+ dc.DrawIconEx(rcIcon.left, rcIcon.top, m_hIconChildMaximized, m_cxIconWidth, m_cyIconHeight);
+
+ // paint right side nonclient background
+ ::SetRect(&rect, cxWidth - m_cxRight, 0, cxWidth, cyHeight);
+#ifndef _WTL_NO_AUTO_THEME
+ if(m_hTheme != NULL)
+ {
+ if(m_pfnDrawThemeParentBackground != NULL)
+ {
+ // this is to account for the left non-client area
+ POINT ptOrg = { 0, 0 };
+ dc.GetViewportOrg(&ptOrg);
+ dc.SetViewportOrg(ptOrg.x + m_cxLeft, ptOrg.y);
+ ::OffsetRect(&rect, -m_cxLeft, 0);
+
+ m_pfnDrawThemeParentBackground(m_hWnd, dc, &rect);
+
+ // restore
+ dc.SetViewportOrg(ptOrg);
+ ::OffsetRect(&rect, m_cxLeft, 0);
+ }
+ else
+ {
+ dc.FillRect(&rect, COLOR_3DFACE);
+ }
+ }
+ else
+#endif // !_WTL_NO_AUTO_THEME
+ {
+ if((m_dwExtendedStyle & CBR_EX_TRANSPARENT) != 0)
+ dc.FillRect(&rect, COLOR_3DFACE);
+ else
+ dc.FillRect(&rect, COLOR_MENU);
+ }
+
+ // draw buttons
+ RECT arrRect[3] = { 0 };
+ pT->_CalcBtnRects(cxWidth, cyHeight, arrRect);
+ pT->_DrawMDIButton(dc, arrRect, -1); // draw all buttons
+
+ return lRet;
+ }
+
+ LRESULT OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+ if(m_bChildMaximized)
+ {
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ POINT pt = { GET_X_LPARAM(lParam) - rect.left, GET_Y_LPARAM(lParam) - rect.top };
+ if(m_bLayoutRTL)
+ {
+ if((pt.x < m_cxRight) || (pt.x > ((rect.right - rect.left) - m_cxLeft)))
+ lRet = HTBORDER;
+ }
+ else
+ {
+ if((pt.x < m_cxLeft) || (pt.x > ((rect.right - rect.left) - m_cxRight)))
+ lRet = HTBORDER;
+ }
+ }
+ return lRet;
+ }
+
+ LRESULT OnNcLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(!m_bChildMaximized)
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+ ATLASSERT(_DebugCheckChild());
+
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ pt.x -= rect.left;
+ pt.y -= rect.top;
+
+ RECT rcIcon = { 0 };
+ T* pT = static_cast<T*>(this);
+ pT->_CalcIconRect(rect.right - rect.left, rect.bottom - rect.top, rcIcon, m_bLayoutRTL);
+ RECT arrRect[3] = { 0 };
+ pT->_CalcBtnRects(rect.right - rect.left, rect.bottom - rect.top, arrRect, m_bLayoutRTL);
+
+ if(::PtInRect(&rcIcon, pt))
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - LButtonDown: icon\n"));
+#endif
+#ifndef TPM_VERPOSANIMATION
+ const UINT TPM_VERPOSANIMATION = 0x1000L; // Menu animation flag
+#endif
+ CMenuHandle menu = ::GetSystemMenu(m_hWndChildMaximized, FALSE);
+ UINT uRet = (UINT)menu.TrackPopupMenu(TPM_LEFTBUTTON | TPM_VERTICAL | TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RETURNCMD |
+ (s_bW2K ? TPM_VERPOSANIMATION : 0), m_bLayoutRTL ? rect.right : rect.left, rect.bottom, m_hWndChildMaximized);
+
+ // eat next message if click is on the same button
+ ::OffsetRect(&rcIcon, rect.left, rect.top);
+ MSG msg = { 0 };
+ if(::PeekMessage(&msg, m_hWnd, WM_NCLBUTTONDOWN, WM_NCLBUTTONDOWN, PM_NOREMOVE) && ::PtInRect(&rcIcon, msg.pt))
+ ::PeekMessage(&msg, m_hWnd, WM_NCLBUTTONDOWN, WM_NCLBUTTONDOWN, PM_REMOVE);
+
+ if(uRet != 0)
+ ::SendMessage(m_hWndChildMaximized, WM_SYSCOMMAND, uRet, 0L);
+ }
+ else if(::PtInRect(&arrRect[0], pt))
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - LButtonDown: close button\n"));
+#endif
+ m_nBtnWasPressed = m_nBtnPressed = 0;
+ }
+ else if(::PtInRect(&arrRect[1], pt))
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - LButtonDown: restore button\n"));
+#endif
+ m_nBtnWasPressed = m_nBtnPressed = 1;
+ }
+ else if(::PtInRect(&arrRect[2], pt))
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - LButtonDown: minimize button\n"));
+#endif
+ m_nBtnWasPressed = m_nBtnPressed = 2;
+ }
+ else
+ {
+ bHandled = FALSE;
+ }
+
+ // draw the button state if it was pressed
+ if(m_nBtnPressed != -1)
+ {
+ SetCapture();
+ CWindowDC dc(m_hWnd);
+ pT->_CalcBtnRects(rect.right - rect.left, rect.bottom - rect.top, arrRect);
+ pT->_DrawMDIButton(dc, arrRect, m_nBtnPressed);
+ }
+
+ return 0;
+ }
+
+ LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(!m_bChildMaximized || ::GetCapture() != m_hWnd || m_nBtnWasPressed == -1)
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ ClientToScreen(&pt);
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ pt.x -= rect.left;
+ pt.y -= rect.top;
+ RECT arrRect[3] = { 0 };
+ T* pT = static_cast<T*>(this);
+ pT->_CalcBtnRects(rect.right - rect.left, rect.bottom - rect.top, arrRect, m_bLayoutRTL);
+ int nOldBtnPressed = m_nBtnPressed;
+ m_nBtnPressed = ::PtInRect(&arrRect[m_nBtnWasPressed], pt) ? m_nBtnWasPressed : -1;
+ if(nOldBtnPressed != m_nBtnPressed)
+ {
+ CWindowDC dc(m_hWnd);
+ pT->_CalcBtnRects(rect.right - rect.left, rect.bottom - rect.top, arrRect);
+ pT->_DrawMDIButton(dc, arrRect, (m_nBtnPressed != -1) ? m_nBtnPressed : nOldBtnPressed);
+ }
+
+ return 0;
+ }
+
+ LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(!m_bChildMaximized || ::GetCapture() != m_hWnd || m_nBtnWasPressed == -1)
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+ ATLASSERT(_DebugCheckChild());
+
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ ClientToScreen(&pt);
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ pt.x -= rect.left;
+ pt.y -= rect.top;
+
+ int nBtn = m_nBtnWasPressed;
+ ReleaseCapture();
+
+ RECT arrRect[3] = { 0 };
+ T* pT = static_cast<T*>(this);
+ pT->_CalcBtnRects(rect.right - rect.left, rect.bottom - rect.top, arrRect, m_bLayoutRTL);
+ if(::PtInRect(&arrRect[nBtn], pt))
+ {
+ switch(nBtn)
+ {
+ case 0: // close
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - LButtonUp: close button\n"));
+#endif
+ ::SendMessage(m_hWndChildMaximized, WM_SYSCOMMAND, SC_CLOSE, 0L);
+ break;
+ case 1: // restore
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - LButtonUp: restore button\n"));
+#endif
+ ::SendMessage(m_hWndChildMaximized, WM_SYSCOMMAND, SC_RESTORE, 0L);
+ break;
+ case 2: // minimize
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - LButtonUp: minimize button\n"));
+#endif
+ ::SendMessage(m_hWndChildMaximized, WM_SYSCOMMAND, SC_MINIMIZE, 0L);
+ break;
+ default:
+ break;
+ }
+ }
+
+ return 0;
+ }
+
+ LRESULT OnNcLButtonDblClk(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(!m_bChildMaximized || m_nBtnWasPressed != -1)
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+ ATLASSERT(_DebugCheckChild());
+
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ pt.x -= rect.left;
+ pt.y -= rect.top;
+
+ RECT rcIcon = { 0 };
+ T* pT = static_cast<T*>(this);
+ pT->_CalcIconRect(rect.right - rect.left, rect.bottom - rect.top, rcIcon, m_bLayoutRTL);
+ RECT arrRect[3] = { 0 };
+ pT->_CalcBtnRects(rect.right - rect.left, rect.bottom - rect.top, arrRect, m_bLayoutRTL);
+
+ if(::PtInRect(&rcIcon, pt))
+ {
+ CMenuHandle menu = ::GetSystemMenu(m_hWndChildMaximized, FALSE);
+ UINT uDefID = menu.GetMenuDefaultItem();
+ if(uDefID == (UINT)-1)
+ uDefID = SC_CLOSE;
+ ::SendMessage(m_hWndChildMaximized, WM_SYSCOMMAND, uDefID, 0L);
+ }
+
+ return 0;
+ }
+
+ LRESULT OnCaptureChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_bChildMaximized)
+ {
+ if(m_nBtnPressed != -1)
+ {
+ ATLASSERT(m_nBtnPressed == m_nBtnWasPressed); // must be
+ m_nBtnPressed = -1;
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ RECT arrRect[3] = { 0 };
+ T* pT = static_cast<T*>(this);
+ pT->_CalcBtnRects(rect.right - rect.left, rect.bottom - rect.top, arrRect);
+ CWindowDC dc(m_hWnd);
+ pT->_DrawMDIButton(dc, arrRect, m_nBtnWasPressed);
+ }
+ m_nBtnWasPressed = -1;
+ }
+ else
+ {
+ bHandled = FALSE;
+ }
+ return 0;
+ }
+
+// Parent window message handlers
+ LRESULT OnParentActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ m_bParentActive = (LOWORD(wParam) != WA_INACTIVE);
+ RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_FRAME | RDW_UPDATENOW);
+ bHandled = FALSE;
+ return 1;
+ }
+
+// MDI client window message handlers
+ LRESULT OnMDISetMenu(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ m_wndMDIClient.DefWindowProc(uMsg, NULL, lParam);
+ HMENU hOldMenu = GetMenu();
+ BOOL bRet = AttachMenu((HMENU)wParam);
+ bRet; // avoid level 4 warning
+ ATLASSERT(bRet);
+
+#if (_WIN32_IE >= 0x0400)
+ T* pT = static_cast<T*>(this);
+ pT->UpdateRebarBandIdealSize();
+#endif // (_WIN32_IE >= 0x0400)
+
+ return (LRESULT)hOldMenu;
+ }
+
+// All messages from the message hook
+ LRESULT OnAllHookMessages(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_ProcessAllHookMessages(uMsg, wParam, lParam);
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+// Overrideables
+ // override this to provide different ideal size
+ void UpdateRebarBandIdealSize()
+ {
+ // assuming we are in a rebar, change ideal size to our size
+ // we hope that if we are not in a rebar, nCount will be 0
+ int nCount = (int)::SendMessage(GetParent(), RB_GETBANDCOUNT, 0, 0L);
+ for(int i = 0; i < nCount; i++)
+ {
+ REBARBANDINFO rbi = { RunTimeHelper::SizeOf_REBARBANDINFO(), RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_IDEALSIZE };
+ ::SendMessage(GetParent(), RB_GETBANDINFO, i, (LPARAM)&rbi);
+ if(rbi.hwndChild == m_hWnd)
+ {
+ rbi.fMask = RBBIM_IDEALSIZE;
+ rbi.cxIdeal = m_bChildMaximized ? m_cxLeft + m_cxRight : 0;
+ int nBtnCount = GetButtonCount();
+ if(nBtnCount > 0)
+ {
+ RECT rect = { 0 };
+ GetItemRect(nBtnCount - 1, &rect);
+ rbi.cxIdeal += rect.right;
+ }
+ ::SendMessage(GetParent(), RB_SETBANDINFO, i, (LPARAM)&rbi);
+ break;
+ }
+ }
+ }
+
+ // all hook messages - check for the maximized MDI child window change
+ void _ProcessAllHookMessages(UINT uMsg, WPARAM /*wParam*/, LPARAM /*lParam*/)
+ {
+ if(uMsg == WM_MDIGETACTIVE || uMsg == WM_MDISETMENU)
+ return;
+
+ BOOL bMaximized = FALSE;
+ HWND hWndChild = (HWND)::SendMessage(m_wndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized);
+ bool bMaxOld = m_bChildMaximized;
+ m_bChildMaximized = (hWndChild != NULL && bMaximized);
+ HICON hIconOld = m_hIconChildMaximized;
+
+ if(m_bChildMaximized)
+ {
+ if(m_hWndChildMaximized != hWndChild)
+ {
+ ATL::CWindow wnd = m_hWndChildMaximized = hWndChild;
+ m_hIconChildMaximized = wnd.GetIcon(FALSE);
+ if(m_hIconChildMaximized == NULL)
+ {
+ m_hIconChildMaximized = wnd.GetIcon(TRUE);
+ if(m_hIconChildMaximized == NULL)
+ {
+ // no icon set with WM_SETICON, get the class one
+// need conditional code because types don't match in winuser.h
+#ifdef _WIN64
+ m_hIconChildMaximized = (HICON)::GetClassLongPtr(wnd, GCLP_HICONSM);
+#else
+ m_hIconChildMaximized = (HICON)LongToHandle(::GetClassLongPtr(wnd, GCLP_HICONSM));
+#endif
+ }
+ }
+ }
+ }
+ else
+ {
+ m_hWndChildMaximized = NULL;
+ m_hIconChildMaximized = NULL;
+ }
+
+ if(bMaxOld != m_bChildMaximized)
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - All messages hook change: m_bChildMaximized = %s\n"), m_bChildMaximized ? "true" : "false");
+#endif
+ // assuming we are in a rebar, change our size to accomodate new state
+ // we hope that if we are not in a rebar, nCount will be 0
+ int nCount = (int)::SendMessage(GetParent(), RB_GETBANDCOUNT, 0, 0L);
+ int cxDiff = (m_bChildMaximized ? 1 : -1) * (m_cxLeft + m_cxRight);
+ for(int i = 0; i < nCount; i++)
+ {
+#if (_WIN32_IE >= 0x0500)
+ REBARBANDINFO rbi = { RunTimeHelper::SizeOf_REBARBANDINFO(), RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_IDEALSIZE | RBBIM_STYLE };
+ ::SendMessage(GetParent(), RB_GETBANDINFO, i, (LPARAM)&rbi);
+ if(rbi.hwndChild == m_hWnd)
+ {
+ if((rbi.fStyle & RBBS_USECHEVRON) != 0)
+ {
+ rbi.fMask = RBBIM_CHILDSIZE | RBBIM_IDEALSIZE;
+ rbi.cxMinChild += cxDiff;
+ rbi.cxIdeal += cxDiff;
+ ::SendMessage(GetParent(), RB_SETBANDINFO, i, (LPARAM)&rbi);
+ }
+ break;
+ }
+#elif (_WIN32_IE >= 0x0400)
+ REBARBANDINFO rbi = { RunTimeHelper::SizeOf_REBARBANDINFO(), RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_IDEALSIZE };
+ ::SendMessage(GetParent(), RB_GETBANDINFO, i, (LPARAM)&rbi);
+ if(rbi.hwndChild == m_hWnd)
+ {
+ rbi.fMask = RBBIM_CHILDSIZE | RBBIM_IDEALSIZE;
+ rbi.cxMinChild += cxDiff;
+ rbi.cxIdeal += cxDiff;
+ ::SendMessage(GetParent(), RB_SETBANDINFO, i, (LPARAM)&rbi);
+ break;
+ }
+#else // (_WIN32_IE < 0x0400)
+ REBARBANDINFO rbi = { RunTimeHelper::SizeOf_REBARBANDINFO(), RBBIM_CHILD | RBBIM_CHILDSIZE };
+ ::SendMessage(GetParent(), RB_GETBANDINFO, i, (LPARAM)&rbi);
+ if(rbi.hwndChild == m_hWnd)
+ {
+ rbi.fMask = RBBIM_CHILDSIZE;
+ rbi.cxMinChild += cxDiff;
+ ::SendMessage(GetParent(), RB_SETBANDINFO, i, (LPARAM)&rbi);
+ break;
+ }
+#endif // (_WIN32_IE < 0x0400)
+ }
+ }
+
+ if(bMaxOld != m_bChildMaximized || hIconOld != m_hIconChildMaximized)
+ {
+ // force size change and redraw everything
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ ::MapWindowPoints(NULL, GetParent(), (LPPOINT)&rect, 2);
+ SetRedraw(FALSE);
+ SetWindowPos(NULL, 0, 0, 1, 1, SWP_NOZORDER | SWP_NOMOVE);
+ SetWindowPos(NULL, &rect, SWP_NOZORDER | SWP_NOMOVE);
+ SetRedraw(TRUE);
+ RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW);
+ }
+ }
+
+// Implementation
+ void GetSystemSettings()
+ {
+#ifdef _CMDBAR_EXTRA_TRACE
+ ATLTRACE2(atlTraceUI, 0, _T("MDI CmdBar - GetSystemSettings\n"));
+#endif
+ _baseClass::GetSystemSettings();
+
+ NONCLIENTMETRICS info = { RunTimeHelper::SizeOf_NONCLIENTMETRICS() };
+ BOOL bRet = ::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(info), &info, 0);
+ ATLASSERT(bRet);
+ if(bRet)
+ {
+ m_cxIconWidth = ::GetSystemMetrics(SM_CXSMICON);
+ m_cyIconHeight = ::GetSystemMetrics(SM_CYSMICON);
+ m_cxLeft = m_cxIconWidth;
+
+#ifndef _WTL_NO_AUTO_THEME
+ if(m_hTheme != NULL)
+ {
+ m_cxBtnWidth = info.iCaptionWidth - 2 * m_cxyOffset;
+ m_cyBtnHeight = info.iCaptionHeight - 2 * m_cxyOffset;
+ m_cxRight = 3 * m_cxBtnWidth;
+ }
+ else
+#endif // !_WTL_NO_AUTO_THEME
+ {
+ m_cxBtnWidth = info.iCaptionWidth - m_cxyOffset;
+ m_cyBtnHeight = info.iCaptionHeight - 2 * m_cxyOffset;
+ m_cxRight = 3 * m_cxBtnWidth + m_cxyOffset;
+ }
+ }
+
+ RECT rect = { 0 };
+ GetClientRect(&rect);
+ T* pT = static_cast<T*>(this);
+ pT->_AdjustBtnSize(rect.bottom);
+ }
+
+ void _AdjustBtnSize(int cyHeight)
+ {
+ if(cyHeight > 1 && m_cyBtnHeight > cyHeight)
+ {
+#ifndef _WTL_NO_AUTO_THEME
+ if(m_hTheme != NULL)
+ {
+ m_cyBtnHeight = cyHeight;
+ m_cxBtnWidth = cyHeight;
+ m_cxRight = 3 * m_cxBtnWidth;
+ }
+ else
+#endif // !_WTL_NO_AUTO_THEME
+ {
+ m_cyBtnHeight = cyHeight;
+ m_cxBtnWidth = cyHeight + m_cxyOffset;
+ m_cxRight = 3 * m_cxBtnWidth + m_cxyOffset;
+ }
+ }
+ }
+
+ void _CalcIconRect(int cxWidth, int cyHeight, RECT& rect, bool bInvertX = false) const
+ {
+ int xStart = (m_cxLeft - m_cxIconWidth) / 2;
+ if(xStart < 0)
+ xStart = 0;
+ int yStart = (cyHeight - m_cyIconHeight) / 2;
+ if(yStart < 0)
+ yStart = 0;
+
+ if(bInvertX)
+ ::SetRect(&rect, cxWidth - (xStart + m_cxBtnWidth), yStart, cxWidth - xStart, yStart + m_cyBtnHeight);
+ else
+ ::SetRect(&rect, xStart, yStart, xStart + m_cxBtnWidth, yStart + m_cyBtnHeight);
+ }
+
+ void _CalcBtnRects(int cxWidth, int cyHeight, RECT arrRect[3], bool bInvertX = false) const
+ {
+ int yStart = (cyHeight - m_cyBtnHeight) / 2;
+ if(yStart < 0)
+ yStart = 0;
+
+ RECT rcBtn = { cxWidth - m_cxBtnWidth, yStart, cxWidth, yStart + m_cyBtnHeight };
+ int nDirection = -1;
+ if(bInvertX)
+ {
+ ::SetRect(&rcBtn, 0, yStart, m_cxBtnWidth, yStart + m_cyBtnHeight);
+ nDirection = 1;
+ }
+
+ arrRect[0] = rcBtn;
+#ifndef _WTL_NO_AUTO_THEME
+ if(m_hTheme != NULL)
+ ::OffsetRect(&rcBtn, nDirection * m_cxBtnWidth, 0);
+ else
+#endif // !_WTL_NO_AUTO_THEME
+ ::OffsetRect(&rcBtn, nDirection * (m_cxBtnWidth + m_cxyOffset), 0);
+ arrRect[1] = rcBtn;
+ ::OffsetRect(&rcBtn, nDirection * m_cxBtnWidth, 0);
+ arrRect[2] = rcBtn;
+ }
+
+ void _DrawMDIButton(CWindowDC& dc, LPRECT pRects, int nBtn)
+ {
+#ifndef _WTL_NO_AUTO_THEME
+ if(m_hTheme != NULL)
+ {
+#ifndef TMSCHEMA_H
+ const int WP_MDICLOSEBUTTON = 20;
+ const int CBS_NORMAL = 1;
+ const int CBS_PUSHED = 3;
+ const int CBS_DISABLED = 4;
+ const int WP_MDIRESTOREBUTTON = 22;
+ const int RBS_NORMAL = 1;
+ const int RBS_PUSHED = 3;
+ const int RBS_DISABLED = 4;
+ const int WP_MDIMINBUTTON = 16;
+ const int MINBS_NORMAL = 1;
+ const int MINBS_PUSHED = 3;
+ const int MINBS_DISABLED = 4;
+#endif // TMSCHEMA_H
+ if(nBtn == -1 || nBtn == 0)
+ m_pfnDrawThemeBackground(m_hTheme, dc, WP_MDICLOSEBUTTON, m_bParentActive ? ((m_nBtnPressed == 0) ? CBS_PUSHED : CBS_NORMAL) : CBS_DISABLED, &pRects[0], NULL);
+ if(nBtn == -1 || nBtn == 1)
+ m_pfnDrawThemeBackground(m_hTheme, dc, WP_MDIRESTOREBUTTON, m_bParentActive ? ((m_nBtnPressed == 1) ? RBS_PUSHED : RBS_NORMAL) : RBS_DISABLED, &pRects[1], NULL);
+ if(nBtn == -1 || nBtn == 2)
+ m_pfnDrawThemeBackground(m_hTheme, dc, WP_MDIMINBUTTON, m_bParentActive ? ((m_nBtnPressed == 2) ? MINBS_PUSHED : MINBS_NORMAL) : MINBS_DISABLED, &pRects[2], NULL);
+ }
+ else
+#endif // !_WTL_NO_AUTO_THEME
+ {
+ if(nBtn == -1 || nBtn == 0)
+ dc.DrawFrameControl(&pRects[0], DFC_CAPTION, DFCS_CAPTIONCLOSE | ((m_nBtnPressed == 0) ? DFCS_PUSHED : 0));
+ if(nBtn == -1 || nBtn == 1)
+ dc.DrawFrameControl(&pRects[1], DFC_CAPTION, DFCS_CAPTIONRESTORE | ((m_nBtnPressed == 1) ? DFCS_PUSHED : 0));
+ if(nBtn == -1 || nBtn == 2)
+ dc.DrawFrameControl(&pRects[2], DFC_CAPTION, DFCS_CAPTIONMIN | ((m_nBtnPressed == 2) ? DFCS_PUSHED : 0));
+ }
+ }
+
+#ifndef _WTL_NO_AUTO_THEME
+ static UINT _GetThemeChangedMsg()
+ {
+#ifndef WM_THEMECHANGED
+ static const UINT WM_THEMECHANGED = 0x031A;
+#endif // !WM_THEMECHANGED
+ return WM_THEMECHANGED;
+ }
+
+ void _OpenThemeData()
+ {
+ ATLASSERT(m_hThemeDLL != NULL);
+
+ PFN_OpenThemeData pfnOpenThemeData = (PFN_OpenThemeData)::GetProcAddress(m_hThemeDLL, "OpenThemeData");
+ ATLASSERT(pfnOpenThemeData != NULL);
+ if(pfnOpenThemeData != NULL)
+ m_hTheme = pfnOpenThemeData(m_hWnd, L"Window");
+ }
+
+ void _CloseThemeData()
+ {
+ ATLASSERT(m_hThemeDLL != NULL);
+
+ if(m_hTheme == NULL)
+ return; // nothing to do
+
+ PFN_CloseThemeData pfnCloseThemeData = (PFN_CloseThemeData)::GetProcAddress(m_hThemeDLL, "CloseThemeData");
+ ATLASSERT(pfnCloseThemeData != NULL);
+ if(pfnCloseThemeData != NULL)
+ {
+ pfnCloseThemeData(m_hTheme);
+ m_hTheme = NULL;
+ }
+ }
+#endif // !_WTL_NO_AUTO_THEME
+
+ bool _DebugCheckChild()
+ {
+#ifdef _DEBUG
+ BOOL bMaximized = FALSE;
+ HWND hWndChild = (HWND)::SendMessage(m_wndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized);
+ return (bMaximized && hWndChild == m_hWndChildMaximized);
+#else // !_DEBUG
+ return true;
+#endif // !_DEBUG
+ }
+};
+
+class CMDICommandBarCtrl : public CMDICommandBarCtrlImpl<CMDICommandBarCtrl>
+{
+public:
+ DECLARE_WND_SUPERCLASS(_T("WTL_MDICommandBar"), GetWndClassName())
+};
+
+}; // namespace WTL
+
+#endif // __ATLCTRLW_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlctrlx.h b/plugins/SmartAutoReplier/wtl/atlctrlx.h
new file mode 100644
index 0000000000..65d8f934a5
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlctrlx.h
@@ -0,0 +1,5004 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLCTRLX_H__
+#define __ATLCTRLX_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlctrlx.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLCTRLS_H__
+ #error atlctrlx.h requires atlctrls.h to be included first
+#endif
+
+#ifndef WM_UPDATEUISTATE
+ #define WM_UPDATEUISTATE 0x0128
+#endif // !WM_UPDATEUISTATE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CBitmapButtonImpl<T, TBase, TWinTraits>
+// CBitmapButton
+// CCheckListViewCtrlImpl<T, TBase, TWinTraits>
+// CCheckListViewCtrl
+// CHyperLinkImpl<T, TBase, TWinTraits>
+// CHyperLink
+// CWaitCursor
+// CCustomWaitCursor
+// CMultiPaneStatusBarCtrlImpl<T, TBase>
+// CMultiPaneStatusBarCtrl
+// CPaneContainerImpl<T, TBase, TWinTraits>
+// CPaneContainer
+// CSortListViewImpl<T>
+// CSortListViewCtrlImpl<T, TBase, TWinTraits>
+// CSortListViewCtrl
+// CTabViewImpl<T, TBase, TWinTraits>
+// CTabView
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CBitmapButton - bitmap button implementation
+
+#ifndef _WIN32_WCE
+
+// bitmap button extended styles
+#define BMPBTN_HOVER 0x00000001
+#define BMPBTN_AUTO3D_SINGLE 0x00000002
+#define BMPBTN_AUTO3D_DOUBLE 0x00000004
+#define BMPBTN_AUTOSIZE 0x00000008
+#define BMPBTN_SHAREIMAGELISTS 0x00000010
+#define BMPBTN_AUTOFIRE 0x00000020
+
+template <class T, class TBase = CButton, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CBitmapButtonImpl : public ATL::CWindowImpl< T, TBase, TWinTraits>
+{
+public:
+ DECLARE_WND_SUPERCLASS(NULL, TBase::GetWndClassName())
+
+ enum
+ {
+ _nImageNormal = 0,
+ _nImagePushed,
+ _nImageFocusOrHover,
+ _nImageDisabled,
+
+ _nImageCount = 4,
+ };
+
+ enum
+ {
+ ID_TIMER_FIRST = 1000,
+ ID_TIMER_REPEAT = 1001
+ };
+
+ // Bitmap button specific extended styles
+ DWORD m_dwExtendedStyle;
+
+ CImageList m_ImageList;
+ int m_nImage[_nImageCount];
+
+ CToolTipCtrl m_tip;
+ LPTSTR m_lpstrToolTipText;
+
+ // Internal states
+ unsigned m_fMouseOver:1;
+ unsigned m_fFocus:1;
+ unsigned m_fPressed:1;
+
+
+// Constructor/Destructor
+ CBitmapButtonImpl(DWORD dwExtendedStyle = BMPBTN_AUTOSIZE, HIMAGELIST hImageList = NULL) :
+ m_ImageList(hImageList), m_dwExtendedStyle(dwExtendedStyle),
+ m_lpstrToolTipText(NULL),
+ m_fMouseOver(0), m_fFocus(0), m_fPressed(0)
+ {
+ m_nImage[_nImageNormal] = -1;
+ m_nImage[_nImagePushed] = -1;
+ m_nImage[_nImageFocusOrHover] = -1;
+ m_nImage[_nImageDisabled] = -1;
+ }
+
+ ~CBitmapButtonImpl()
+ {
+ if((m_dwExtendedStyle & BMPBTN_SHAREIMAGELISTS) == 0)
+ m_ImageList.Destroy();
+ delete [] m_lpstrToolTipText;
+ }
+
+ // overridden to provide proper initialization
+ BOOL SubclassWindow(HWND hWnd)
+ {
+#if (_MSC_VER >= 1300)
+ BOOL bRet = ATL::CWindowImpl< T, TBase, TWinTraits>::SubclassWindow(hWnd);
+#else // !(_MSC_VER >= 1300)
+ typedef ATL::CWindowImpl< T, TBase, TWinTraits> _baseClass;
+ BOOL bRet = _baseClass::SubclassWindow(hWnd);
+#endif // !(_MSC_VER >= 1300)
+ if(bRet)
+ Init();
+ return bRet;
+ }
+
+// Attributes
+ DWORD GetBitmapButtonExtendedStyle() const
+ {
+ return m_dwExtendedStyle;
+ }
+
+ DWORD SetBitmapButtonExtendedStyle(DWORD dwExtendedStyle, DWORD dwMask = 0)
+ {
+ DWORD dwPrevStyle = m_dwExtendedStyle;
+ if(dwMask == 0)
+ m_dwExtendedStyle = dwExtendedStyle;
+ else
+ m_dwExtendedStyle = (m_dwExtendedStyle & ~dwMask) | (dwExtendedStyle & dwMask);
+ return dwPrevStyle;
+ }
+
+ HIMAGELIST GetImageList() const
+ {
+ return m_ImageList;
+ }
+
+ HIMAGELIST SetImageList(HIMAGELIST hImageList)
+ {
+ HIMAGELIST hImageListPrev = m_ImageList;
+ m_ImageList = hImageList;
+ if((m_dwExtendedStyle & BMPBTN_AUTOSIZE) != 0 && ::IsWindow(m_hWnd))
+ SizeToImage();
+ return hImageListPrev;
+ }
+
+ int GetToolTipTextLength() const
+ {
+ return (m_lpstrToolTipText == NULL) ? -1 : lstrlen(m_lpstrToolTipText);
+ }
+
+ bool GetToolTipText(LPTSTR lpstrText, int nLength) const
+ {
+ ATLASSERT(lpstrText != NULL);
+ if(m_lpstrToolTipText == NULL)
+ return false;
+
+ errno_t nRet = SecureHelper::strncpy_x(lpstrText, nLength, m_lpstrToolTipText, _TRUNCATE);
+
+ return (nRet == 0 || nRet == STRUNCATE);
+ }
+
+ bool SetToolTipText(LPCTSTR lpstrText)
+ {
+ if(m_lpstrToolTipText != NULL)
+ {
+ delete [] m_lpstrToolTipText;
+ m_lpstrToolTipText = NULL;
+ }
+
+ if(lpstrText == NULL)
+ {
+ if(m_tip.IsWindow())
+ m_tip.Activate(FALSE);
+ return true;
+ }
+
+ int cchLen = lstrlen(lpstrText) + 1;
+ ATLTRY(m_lpstrToolTipText = new TCHAR[cchLen]);
+ if(m_lpstrToolTipText == NULL)
+ return false;
+
+ SecureHelper::strcpy_x(m_lpstrToolTipText, cchLen, lpstrText);
+ if(m_tip.IsWindow())
+ {
+ m_tip.Activate(TRUE);
+ m_tip.AddTool(m_hWnd, m_lpstrToolTipText);
+ }
+
+ return true;
+ }
+
+// Operations
+ void SetImages(int nNormal, int nPushed = -1, int nFocusOrHover = -1, int nDisabled = -1)
+ {
+ if(nNormal != -1)
+ m_nImage[_nImageNormal] = nNormal;
+ if(nPushed != -1)
+ m_nImage[_nImagePushed] = nPushed;
+ if(nFocusOrHover != -1)
+ m_nImage[_nImageFocusOrHover] = nFocusOrHover;
+ if(nDisabled != -1)
+ m_nImage[_nImageDisabled] = nDisabled;
+ }
+
+ BOOL SizeToImage()
+ {
+ ATLASSERT(::IsWindow(m_hWnd) && m_ImageList.m_hImageList != NULL);
+ int cx = 0;
+ int cy = 0;
+ if(!m_ImageList.GetIconSize(cx, cy))
+ return FALSE;
+ return ResizeClient(cx, cy);
+ }
+
+// Overrideables
+ void DoPaint(CDCHandle dc)
+ {
+ ATLASSERT(m_ImageList.m_hImageList != NULL); // image list must be set
+ ATLASSERT(m_nImage[0] != -1); // main bitmap must be set
+
+ // set bitmap according to the current button state
+ int nImage = -1;
+ bool bHover = IsHoverMode();
+ if(!IsWindowEnabled())
+ nImage = m_nImage[_nImageDisabled];
+ else if(m_fPressed == 1)
+ nImage = m_nImage[_nImagePushed];
+ else if((!bHover && m_fFocus == 1) || (bHover && m_fMouseOver == 1))
+ nImage = m_nImage[_nImageFocusOrHover];
+ if(nImage == -1) // not there, use default one
+ nImage = m_nImage[_nImageNormal];
+
+ // draw the button image
+ int xyPos = 0;
+ if((m_fPressed == 1) && ((m_dwExtendedStyle & (BMPBTN_AUTO3D_SINGLE | BMPBTN_AUTO3D_DOUBLE)) != 0) && (m_nImage[_nImagePushed] == -1))
+ xyPos = 1;
+ m_ImageList.Draw(dc, nImage, xyPos, xyPos, ILD_NORMAL);
+
+ // draw 3D border if required
+ if((m_dwExtendedStyle & (BMPBTN_AUTO3D_SINGLE | BMPBTN_AUTO3D_DOUBLE)) != 0)
+ {
+ RECT rect;
+ GetClientRect(&rect);
+
+ if(m_fPressed == 1)
+ dc.DrawEdge(&rect, ((m_dwExtendedStyle & BMPBTN_AUTO3D_SINGLE) != 0) ? BDR_SUNKENOUTER : EDGE_SUNKEN, BF_RECT);
+ else if(!bHover || m_fMouseOver == 1)
+ dc.DrawEdge(&rect, ((m_dwExtendedStyle & BMPBTN_AUTO3D_SINGLE) != 0) ? BDR_RAISEDINNER : EDGE_RAISED, BF_RECT);
+
+ if(!bHover && m_fFocus == 1)
+ {
+ ::InflateRect(&rect, -2 * ::GetSystemMetrics(SM_CXEDGE), -2 * ::GetSystemMetrics(SM_CYEDGE));
+ dc.DrawFocusRect(&rect);
+ }
+ }
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CBitmapButtonImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseMessage)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+ MESSAGE_HANDLER(WM_SETFOCUS, OnFocus)
+ MESSAGE_HANDLER(WM_KILLFOCUS, OnFocus)
+ MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
+ MESSAGE_HANDLER(WM_LBUTTONDBLCLK, OnLButtonDblClk)
+ MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
+ MESSAGE_HANDLER(WM_CAPTURECHANGED, OnCaptureChanged)
+ MESSAGE_HANDLER(WM_ENABLE, OnEnable)
+ MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
+ MESSAGE_HANDLER(WM_MOUSELEAVE, OnMouseLeave)
+ MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
+ MESSAGE_HANDLER(WM_KEYUP, OnKeyUp)
+ MESSAGE_HANDLER(WM_TIMER, OnTimer)
+ MESSAGE_HANDLER(WM_UPDATEUISTATE, OnUpdateUiState)
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ Init();
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_tip.IsWindow())
+ {
+ m_tip.DestroyWindow();
+ m_tip.m_hWnd = NULL;
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnMouseMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ MSG msg = { m_hWnd, uMsg, wParam, lParam };
+ if(m_tip.IsWindow())
+ m_tip.RelayEvent(&msg);
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1; // no background needed
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ if(wParam != NULL)
+ {
+ pT->DoPaint((HDC)wParam);
+ }
+ else
+ {
+ CPaintDC dc(m_hWnd);
+ pT->DoPaint(dc.m_hDC);
+ }
+ return 0;
+ }
+
+ LRESULT OnFocus(UINT uMsg, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ m_fFocus = (uMsg == WM_SETFOCUS) ? 1 : 0;
+ Invalidate();
+ UpdateWindow();
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = 0;
+ if(IsHoverMode())
+ SetCapture();
+ else
+ lRet = DefWindowProc(uMsg, wParam, lParam);
+ if(::GetCapture() == m_hWnd)
+ {
+ m_fPressed = 1;
+ Invalidate();
+ UpdateWindow();
+ }
+ if((m_dwExtendedStyle & BMPBTN_AUTOFIRE) != 0)
+ {
+ int nElapse = 250;
+ int nDelay = 0;
+ if(::SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &nDelay, 0))
+ nElapse += nDelay * 250; // all milli-seconds
+ SetTimer(ID_TIMER_FIRST, nElapse);
+ }
+ return lRet;
+ }
+
+ LRESULT OnLButtonDblClk(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = 0;
+ if(!IsHoverMode())
+ lRet = DefWindowProc(uMsg, wParam, lParam);
+ if(::GetCapture() != m_hWnd)
+ SetCapture();
+ if(m_fPressed == 0)
+ {
+ m_fPressed = 1;
+ Invalidate();
+ UpdateWindow();
+ }
+ return lRet;
+ }
+
+ LRESULT OnLButtonUp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = 0;
+ bool bHover = IsHoverMode();
+ if(!bHover)
+ lRet = DefWindowProc(uMsg, wParam, lParam);
+ if(::GetCapture() == m_hWnd)
+ {
+ if(bHover && m_fPressed == 1)
+ ::SendMessage(GetParent(), WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), BN_CLICKED), (LPARAM)m_hWnd);
+ ::ReleaseCapture();
+ }
+ return lRet;
+ }
+
+ LRESULT OnCaptureChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_fPressed == 1)
+ {
+ m_fPressed = 0;
+ Invalidate();
+ UpdateWindow();
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnEnable(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ Invalidate();
+ UpdateWindow();
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(::GetCapture() == m_hWnd)
+ {
+ POINT ptCursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ ClientToScreen(&ptCursor);
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ unsigned int uPressed = ::PtInRect(&rect, ptCursor) ? 1 : 0;
+ if(m_fPressed != uPressed)
+ {
+ m_fPressed = uPressed;
+ Invalidate();
+ UpdateWindow();
+ }
+ }
+ else if(IsHoverMode() && m_fMouseOver == 0)
+ {
+ m_fMouseOver = 1;
+ Invalidate();
+ UpdateWindow();
+ StartTrackMouseLeave();
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnMouseLeave(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(m_fMouseOver == 1)
+ {
+ m_fMouseOver = 0;
+ Invalidate();
+ UpdateWindow();
+ }
+ return 0;
+ }
+
+ LRESULT OnKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(wParam == VK_SPACE && IsHoverMode())
+ return 0; // ignore if in hover mode
+ if(wParam == VK_SPACE && m_fPressed == 0)
+ {
+ m_fPressed = 1;
+ Invalidate();
+ UpdateWindow();
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnKeyUp(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(wParam == VK_SPACE && IsHoverMode())
+ return 0; // ignore if in hover mode
+ if(wParam == VK_SPACE && m_fPressed == 1)
+ {
+ m_fPressed = 0;
+ Invalidate();
+ UpdateWindow();
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ ATLASSERT((m_dwExtendedStyle & BMPBTN_AUTOFIRE) != 0);
+ switch(wParam) // timer ID
+ {
+ case ID_TIMER_FIRST:
+ KillTimer(ID_TIMER_FIRST);
+ if(m_fPressed == 1)
+ {
+ ::SendMessage(GetParent(), WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), BN_CLICKED), (LPARAM)m_hWnd);
+ int nElapse = 250;
+ int nRepeat = 40;
+ if(::SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &nRepeat, 0))
+ nElapse = 10000 / (10 * nRepeat + 25); // milli-seconds, approximated
+ SetTimer(ID_TIMER_REPEAT, nElapse);
+ }
+ break;
+ case ID_TIMER_REPEAT:
+ if(m_fPressed == 1)
+ ::SendMessage(GetParent(), WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), BN_CLICKED), (LPARAM)m_hWnd);
+ else if(::GetCapture() != m_hWnd)
+ KillTimer(ID_TIMER_REPEAT);
+ break;
+ default: // not our timer
+ break;
+ }
+ return 0;
+ }
+
+ LRESULT OnUpdateUiState(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ // If the control is subclassed or superclassed, this message can cause
+ // repainting without WM_PAINT. We don't use this state, so just do nothing.
+ return 0;
+ }
+
+// Implementation
+ void Init()
+ {
+ // We need this style to prevent Windows from painting the button
+ ModifyStyle(0, BS_OWNERDRAW);
+
+ // create a tool tip
+ m_tip.Create(m_hWnd);
+ ATLASSERT(m_tip.IsWindow());
+ if(m_tip.IsWindow() && m_lpstrToolTipText != NULL)
+ {
+ m_tip.Activate(TRUE);
+ m_tip.AddTool(m_hWnd, m_lpstrToolTipText);
+ }
+
+ if(m_ImageList.m_hImageList != NULL && (m_dwExtendedStyle & BMPBTN_AUTOSIZE) != 0)
+ SizeToImage();
+ }
+
+ BOOL StartTrackMouseLeave()
+ {
+ TRACKMOUSEEVENT tme = { 0 };
+ tme.cbSize = sizeof(tme);
+ tme.dwFlags = TME_LEAVE;
+ tme.hwndTrack = m_hWnd;
+ return _TrackMouseEvent(&tme);
+ }
+
+ bool IsHoverMode() const
+ {
+ return ((m_dwExtendedStyle & BMPBTN_HOVER) != 0);
+ }
+};
+
+class CBitmapButton : public CBitmapButtonImpl<CBitmapButton>
+{
+public:
+ DECLARE_WND_SUPERCLASS(_T("WTL_BitmapButton"), GetWndClassName())
+
+ CBitmapButton(DWORD dwExtendedStyle = BMPBTN_AUTOSIZE, HIMAGELIST hImageList = NULL) :
+ CBitmapButtonImpl<CBitmapButton>(dwExtendedStyle, hImageList)
+ { }
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CCheckListCtrlView - list view control with check boxes
+
+template <DWORD t_dwStyle, DWORD t_dwExStyle, DWORD t_dwExListViewStyle>
+class CCheckListViewCtrlImplTraits
+{
+public:
+ static DWORD GetWndStyle(DWORD dwStyle)
+ {
+ return (dwStyle == 0) ? t_dwStyle : dwStyle;
+ }
+
+ static DWORD GetWndExStyle(DWORD dwExStyle)
+ {
+ return (dwExStyle == 0) ? t_dwExStyle : dwExStyle;
+ }
+
+ static DWORD GetExtendedLVStyle()
+ {
+ return t_dwExListViewStyle;
+ }
+};
+
+typedef CCheckListViewCtrlImplTraits<WS_CHILD | WS_VISIBLE | LVS_REPORT | LVS_SHOWSELALWAYS, WS_EX_CLIENTEDGE, LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT> CCheckListViewCtrlTraits;
+
+template <class T, class TBase = CListViewCtrl, class TWinTraits = CCheckListViewCtrlTraits>
+class ATL_NO_VTABLE CCheckListViewCtrlImpl : public ATL::CWindowImpl<T, TBase, TWinTraits>
+{
+public:
+ DECLARE_WND_SUPERCLASS(NULL, TBase::GetWndClassName())
+
+// Attributes
+ static DWORD GetExtendedLVStyle()
+ {
+ return TWinTraits::GetExtendedLVStyle();
+ }
+
+// Operations
+ BOOL SubclassWindow(HWND hWnd)
+ {
+#if (_MSC_VER >= 1300)
+ BOOL bRet = ATL::CWindowImplBaseT< TBase, TWinTraits>::SubclassWindow(hWnd);
+#else // !(_MSC_VER >= 1300)
+ typedef ATL::CWindowImplBaseT< TBase, TWinTraits> _baseClass;
+ BOOL bRet = _baseClass::SubclassWindow(hWnd);
+#endif // !(_MSC_VER >= 1300)
+ if(bRet)
+ {
+ T* pT = static_cast<T*>(this);
+ pT;
+ ATLASSERT((pT->GetExtendedLVStyle() & LVS_EX_CHECKBOXES) != 0);
+ SetExtendedListViewStyle(pT->GetExtendedLVStyle());
+ }
+ return bRet;
+ }
+
+ void CheckSelectedItems(int nCurrItem)
+ {
+ // first check if this item is selected
+ LVITEM lvi = { 0 };
+ lvi.iItem = nCurrItem;
+ lvi.iSubItem = 0;
+ lvi.mask = LVIF_STATE;
+ lvi.stateMask = LVIS_SELECTED;
+ GetItem(&lvi);
+ // if item is not selected, don't do anything
+ if(!(lvi.state & LVIS_SELECTED))
+ return;
+ // new check state will be reverse of the current state,
+ BOOL bCheck = !GetCheckState(nCurrItem);
+ int nItem = -1;
+ int nOldItem = -1;
+ while((nItem = GetNextItem(nOldItem, LVNI_SELECTED)) != -1)
+ {
+ if(nItem != nCurrItem)
+ SetCheckState(nItem, bCheck);
+ nOldItem = nItem;
+ }
+ }
+
+// Implementation
+ BEGIN_MSG_MAP(CCheckListViewCtrlImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
+ MESSAGE_HANDLER(WM_LBUTTONDBLCLK, OnLButtonDown)
+ MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ // first let list view control initialize everything
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+ T* pT = static_cast<T*>(this);
+ pT;
+ ATLASSERT((pT->GetExtendedLVStyle() & LVS_EX_CHECKBOXES) != 0);
+ SetExtendedListViewStyle(pT->GetExtendedLVStyle());
+ return lRet;
+ }
+
+ LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ POINT ptMsg = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ LVHITTESTINFO lvh = { 0 };
+ lvh.pt = ptMsg;
+ if(HitTest(&lvh) != -1 && lvh.flags == LVHT_ONITEMSTATEICON && ::GetKeyState(VK_CONTROL) >= 0)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->CheckSelectedItems(lvh.iItem);
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(wParam == VK_SPACE)
+ {
+ int nCurrItem = GetNextItem(-1, LVNI_FOCUSED);
+ if(nCurrItem != -1 && ::GetKeyState(VK_CONTROL) >= 0)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->CheckSelectedItems(nCurrItem);
+ }
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+};
+
+class CCheckListViewCtrl : public CCheckListViewCtrlImpl<CCheckListViewCtrl>
+{
+public:
+ DECLARE_WND_SUPERCLASS(_T("WTL_CheckListView"), GetWndClassName())
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CHyperLink - hyper link control implementation
+
+#if (WINVER < 0x0500) && !defined(_WIN32_WCE)
+__declspec(selectany) struct
+{
+ enum { cxWidth = 32, cyHeight = 32 };
+ int xHotSpot;
+ int yHotSpot;
+ unsigned char arrANDPlane[cxWidth * cyHeight / 8];
+ unsigned char arrXORPlane[cxWidth * cyHeight / 8];
+} _AtlHyperLink_CursorData =
+{
+ 5, 0,
+ {
+ 0xF9, 0xFF, 0xFF, 0xFF, 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0xFF, 0xFF, 0xFF,
+ 0xF0, 0xFF, 0xFF, 0xFF, 0xF0, 0x3F, 0xFF, 0xFF, 0xF0, 0x07, 0xFF, 0xFF, 0xF0, 0x01, 0xFF, 0xFF,
+ 0xF0, 0x00, 0xFF, 0xFF, 0x10, 0x00, 0x7F, 0xFF, 0x00, 0x00, 0x7F, 0xFF, 0x00, 0x00, 0x7F, 0xFF,
+ 0x80, 0x00, 0x7F, 0xFF, 0xC0, 0x00, 0x7F, 0xFF, 0xC0, 0x00, 0x7F, 0xFF, 0xE0, 0x00, 0x7F, 0xFF,
+ 0xE0, 0x00, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xF0, 0x00, 0xFF, 0xFF, 0xF8, 0x01, 0xFF, 0xFF,
+ 0xF8, 0x01, 0xFF, 0xFF, 0xF8, 0x01, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
+ },
+ {
+ 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
+ 0x06, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x06, 0xC0, 0x00, 0x00, 0x06, 0xD8, 0x00, 0x00,
+ 0x06, 0xDA, 0x00, 0x00, 0x06, 0xDB, 0x00, 0x00, 0x67, 0xFB, 0x00, 0x00, 0x77, 0xFF, 0x00, 0x00,
+ 0x37, 0xFF, 0x00, 0x00, 0x17, 0xFF, 0x00, 0x00, 0x1F, 0xFF, 0x00, 0x00, 0x0F, 0xFF, 0x00, 0x00,
+ 0x0F, 0xFE, 0x00, 0x00, 0x07, 0xFE, 0x00, 0x00, 0x07, 0xFE, 0x00, 0x00, 0x03, 0xFC, 0x00, 0x00,
+ 0x03, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+ }
+};
+#endif // (WINVER < 0x0500) && !defined(_WIN32_WCE)
+
+#define HLINK_UNDERLINED 0x00000000
+#define HLINK_NOTUNDERLINED 0x00000001
+#define HLINK_UNDERLINEHOVER 0x00000002
+#define HLINK_COMMANDBUTTON 0x00000004
+#define HLINK_NOTIFYBUTTON 0x0000000C
+#define HLINK_USETAGS 0x00000010
+#define HLINK_USETAGSBOLD 0x00000030
+#define HLINK_NOTOOLTIP 0x00000040
+#define HLINK_AUTOCREATELINKFONT 0x00000080
+#define HLINK_SINGLELINE 0x00000100
+
+// Notes:
+// - HLINK_USETAGS and HLINK_USETAGSBOLD are always left-aligned
+// - When HLINK_USETAGSBOLD is used, the underlined styles will be ignored
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CHyperLinkImpl : public ATL::CWindowImpl< T, TBase, TWinTraits >
+{
+public:
+ LPTSTR m_lpstrLabel;
+ LPTSTR m_lpstrHyperLink;
+
+ HCURSOR m_hCursor;
+ HFONT m_hFontLink;
+ HFONT m_hFontNormal;
+
+ RECT m_rcLink;
+#ifndef _WIN32_WCE
+ CToolTipCtrl m_tip;
+#endif // !_WIN32_WCE
+
+ COLORREF m_clrLink;
+ COLORREF m_clrVisited;
+
+ DWORD m_dwExtendedStyle; // Hyper Link specific extended styles
+
+ bool m_bPaintLabel:1;
+ bool m_bVisited:1;
+ bool m_bHover:1;
+ bool m_bInternalLinkFont:1;
+ bool m_bInternalNormalFont:1;
+
+
+// Constructor/Destructor
+ CHyperLinkImpl(DWORD dwExtendedStyle = HLINK_UNDERLINED) :
+ m_lpstrLabel(NULL), m_lpstrHyperLink(NULL),
+ m_hCursor(NULL), m_hFontLink(NULL), m_hFontNormal(NULL),
+ m_clrLink(RGB(0, 0, 255)), m_clrVisited(RGB(128, 0, 128)),
+ m_dwExtendedStyle(dwExtendedStyle),
+ m_bPaintLabel(true), m_bVisited(false),
+ m_bHover(false), m_bInternalLinkFont(false), m_bInternalNormalFont(false)
+ {
+ ::SetRectEmpty(&m_rcLink);
+ }
+
+ ~CHyperLinkImpl()
+ {
+ delete [] m_lpstrLabel;
+ delete [] m_lpstrHyperLink;
+#if (WINVER < 0x0500) && !defined(_WIN32_WCE)
+ // It was created, not loaded, so we have to destroy it
+ if(m_hCursor != NULL)
+ ::DestroyCursor(m_hCursor);
+#endif // (WINVER < 0x0500) && !defined(_WIN32_WCE)
+ }
+
+// Attributes
+ DWORD GetHyperLinkExtendedStyle() const
+ {
+ return m_dwExtendedStyle;
+ }
+
+ DWORD SetHyperLinkExtendedStyle(DWORD dwExtendedStyle, DWORD dwMask = 0)
+ {
+ DWORD dwPrevStyle = m_dwExtendedStyle;
+ if(dwMask == 0)
+ m_dwExtendedStyle = dwExtendedStyle;
+ else
+ m_dwExtendedStyle = (m_dwExtendedStyle & ~dwMask) | (dwExtendedStyle & dwMask);
+ return dwPrevStyle;
+ }
+
+ bool GetLabel(LPTSTR lpstrBuffer, int nLength) const
+ {
+ if(m_lpstrLabel == NULL)
+ return false;
+ ATLASSERT(lpstrBuffer != NULL);
+ if(nLength <= lstrlen(m_lpstrLabel))
+ return false;
+
+ SecureHelper::strcpy_x(lpstrBuffer, nLength, m_lpstrLabel);
+
+ return true;
+ }
+
+ bool SetLabel(LPCTSTR lpstrLabel)
+ {
+ delete [] m_lpstrLabel;
+ m_lpstrLabel = NULL;
+ int cchLen = lstrlen(lpstrLabel) + 1;
+ ATLTRY(m_lpstrLabel = new TCHAR[cchLen]);
+ if(m_lpstrLabel == NULL)
+ return false;
+
+ SecureHelper::strcpy_x(m_lpstrLabel, cchLen, lpstrLabel);
+ T* pT = static_cast<T*>(this);
+ pT->CalcLabelRect();
+
+ if(m_hWnd != NULL)
+ SetWindowText(lpstrLabel); // Set this for accessibility
+
+ return true;
+ }
+
+ bool GetHyperLink(LPTSTR lpstrBuffer, int nLength) const
+ {
+ if(m_lpstrHyperLink == NULL)
+ return false;
+ ATLASSERT(lpstrBuffer != NULL);
+ if(nLength <= lstrlen(m_lpstrHyperLink))
+ return false;
+
+ SecureHelper::strcpy_x(lpstrBuffer, nLength, m_lpstrHyperLink);
+
+ return true;
+ }
+
+ bool SetHyperLink(LPCTSTR lpstrLink)
+ {
+ delete [] m_lpstrHyperLink;
+ m_lpstrHyperLink = NULL;
+ int cchLen = lstrlen(lpstrLink) + 1;
+ ATLTRY(m_lpstrHyperLink = new TCHAR[cchLen]);
+ if(m_lpstrHyperLink == NULL)
+ return false;
+
+ SecureHelper::strcpy_x(m_lpstrHyperLink, cchLen, lpstrLink);
+ if(m_lpstrLabel == NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->CalcLabelRect();
+ }
+#ifndef _WIN32_WCE
+ if(m_tip.IsWindow())
+ {
+ m_tip.Activate(TRUE);
+ m_tip.AddTool(m_hWnd, m_lpstrHyperLink, &m_rcLink, 1);
+ }
+#endif // !_WIN32_WCE
+ return true;
+ }
+
+ HFONT GetLinkFont() const
+ {
+ return m_hFontLink;
+ }
+
+ void SetLinkFont(HFONT hFont)
+ {
+ if(m_bInternalLinkFont)
+ {
+ ::DeleteObject(m_hFontLink);
+ m_bInternalLinkFont = false;
+ }
+
+ m_hFontLink = hFont;
+
+ T* pT = static_cast<T*>(this);
+ pT->CalcLabelRect();
+ }
+
+ int GetIdealHeight() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ if(m_lpstrLabel == NULL && m_lpstrHyperLink == NULL)
+ return -1;
+ if(!m_bPaintLabel)
+ return -1;
+
+ UINT uFormat = IsSingleLine() ? DT_SINGLELINE : DT_WORDBREAK;
+
+ CClientDC dc(m_hWnd);
+ RECT rect = { 0 };
+ GetClientRect(&rect);
+ HFONT hFontOld = dc.SelectFont(m_hFontNormal);
+ RECT rcText = rect;
+ dc.DrawText(_T("NS"), -1, &rcText, DT_LEFT | uFormat | DT_CALCRECT);
+ dc.SelectFont(m_hFontLink);
+ RECT rcLink = rect;
+ dc.DrawText(_T("NS"), -1, &rcLink, DT_LEFT | uFormat | DT_CALCRECT);
+ dc.SelectFont(hFontOld);
+ return max(rcText.bottom - rcText.top, rcLink.bottom - rcLink.top);
+ }
+
+ bool GetIdealSize(SIZE& size) const
+ {
+ int cx = 0, cy = 0;
+ bool bRet = GetIdealSize(cx, cy);
+ if(bRet)
+ {
+ size.cx = cx;
+ size.cy = cy;
+ }
+ return bRet;
+ }
+
+ bool GetIdealSize(int& cx, int& cy) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ if(m_lpstrLabel == NULL && m_lpstrHyperLink == NULL)
+ return false;
+ if(!m_bPaintLabel)
+ return false;
+
+ CClientDC dc(m_hWnd);
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+ RECT rcAll = rcClient;
+
+ if(IsUsingTags())
+ {
+ // find tags and label parts
+ LPTSTR lpstrLeft = NULL;
+ int cchLeft = 0;
+ LPTSTR lpstrLink = NULL;
+ int cchLink = 0;
+ LPTSTR lpstrRight = NULL;
+ int cchRight = 0;
+
+ const T* pT = static_cast<const T*>(this);
+ pT->CalcLabelParts(lpstrLeft, cchLeft, lpstrLink, cchLink, lpstrRight, cchRight);
+
+ // get label part rects
+ UINT uFormat = IsSingleLine() ? DT_SINGLELINE : DT_WORDBREAK;
+
+ HFONT hFontOld = dc.SelectFont(m_hFontNormal);
+ RECT rcLeft = rcClient;
+ dc.DrawText(lpstrLeft, cchLeft, &rcLeft, DT_LEFT | uFormat | DT_CALCRECT);
+
+ dc.SelectFont(m_hFontLink);
+ RECT rcLink = { rcLeft.right, rcLeft.top, rcClient.right, rcClient.bottom };
+ dc.DrawText(lpstrLink, cchLink, &rcLink, DT_LEFT | uFormat | DT_CALCRECT);
+
+ dc.SelectFont(m_hFontNormal);
+ RECT rcRight = { rcLink.right, rcLink.top, rcClient.right, rcClient.bottom };
+ dc.DrawText(lpstrRight, cchRight, &rcRight, DT_LEFT | uFormat | DT_CALCRECT);
+
+ dc.SelectFont(hFontOld);
+
+ int cyMax = max(rcLeft.bottom, max(rcLink.bottom, rcRight.bottom));
+ ::SetRect(&rcAll, rcLeft.left, rcLeft.top, rcRight.right, cyMax);
+ }
+ else
+ {
+ HFONT hOldFont = NULL;
+ if(m_hFontLink != NULL)
+ hOldFont = dc.SelectFont(m_hFontLink);
+ LPTSTR lpstrText = (m_lpstrLabel != NULL) ? m_lpstrLabel : m_lpstrHyperLink;
+ DWORD dwStyle = GetStyle();
+ UINT uFormat = DT_LEFT;
+ if (dwStyle & SS_CENTER)
+ uFormat = DT_CENTER;
+ else if (dwStyle & SS_RIGHT)
+ uFormat = DT_RIGHT;
+ uFormat |= IsSingleLine() ? DT_SINGLELINE : DT_WORDBREAK;
+ dc.DrawText(lpstrText, -1, &rcAll, uFormat | DT_CALCRECT);
+ if(m_hFontLink != NULL)
+ dc.SelectFont(hOldFont);
+ if (dwStyle & SS_CENTER)
+ {
+ int dx = (rcClient.right - rcAll.right) / 2;
+ ::OffsetRect(&rcAll, dx, 0);
+ }
+ else if (dwStyle & SS_RIGHT)
+ {
+ int dx = rcClient.right - rcAll.right;
+ ::OffsetRect(&rcAll, dx, 0);
+ }
+ }
+
+ cx = rcAll.right - rcAll.left;
+ cy = rcAll.bottom - rcAll.top;
+
+ return true;
+ }
+
+ // for command buttons only
+ bool GetToolTipText(LPTSTR lpstrBuffer, int nLength) const
+ {
+ ATLASSERT(IsCommandButton());
+ return GetHyperLink(lpstrBuffer, nLength);
+ }
+
+ bool SetToolTipText(LPCTSTR lpstrToolTipText)
+ {
+ ATLASSERT(IsCommandButton());
+ return SetHyperLink(lpstrToolTipText);
+ }
+
+// Operations
+ BOOL SubclassWindow(HWND hWnd)
+ {
+ ATLASSERT(m_hWnd == NULL);
+ ATLASSERT(::IsWindow(hWnd));
+ if(m_hFontNormal == NULL)
+ m_hFontNormal = (HFONT)::SendMessage(hWnd, WM_GETFONT, 0, 0L);
+#if (_MSC_VER >= 1300)
+ BOOL bRet = ATL::CWindowImpl< T, TBase, TWinTraits>::SubclassWindow(hWnd);
+#else // !(_MSC_VER >= 1300)
+ typedef ATL::CWindowImpl< T, TBase, TWinTraits> _baseClass;
+ BOOL bRet = _baseClass::SubclassWindow(hWnd);
+#endif // !(_MSC_VER >= 1300)
+ if(bRet)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Init();
+ }
+ return bRet;
+ }
+
+ bool Navigate()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ bool bRet = true;
+ if(IsNotifyButton())
+ {
+ NMHDR nmhdr = { m_hWnd, GetDlgCtrlID(), NM_CLICK };
+ ::SendMessage(GetParent(), WM_NOTIFY, GetDlgCtrlID(), (LPARAM)&nmhdr);
+ }
+ else if(IsCommandButton())
+ {
+ ::SendMessage(GetParent(), WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), BN_CLICKED), (LPARAM)m_hWnd);
+ }
+ else
+ {
+ ATLASSERT(m_lpstrHyperLink != NULL);
+#ifndef _WIN32_WCE
+ DWORD_PTR dwRet = (DWORD_PTR)::ShellExecute(0, _T("open"), m_lpstrHyperLink, 0, 0, SW_SHOWNORMAL);
+ bRet = (dwRet > 32);
+#else // CE specific
+ SHELLEXECUTEINFO shExeInfo = { sizeof(SHELLEXECUTEINFO), 0, 0, L"open", m_lpstrHyperLink, 0, 0, SW_SHOWNORMAL, 0, 0, 0, 0, 0, 0, 0 };
+ ::ShellExecuteEx(&shExeInfo);
+ DWORD_PTR dwRet = (DWORD_PTR)shExeInfo.hInstApp;
+ bRet = (dwRet == 0) || (dwRet > 32);
+#endif // _WIN32_WCE
+ ATLASSERT(bRet);
+ if(bRet)
+ {
+ m_bVisited = true;
+ Invalidate();
+ }
+ }
+ return bRet;
+ }
+
+ void CreateLinkFontFromNormal()
+ {
+ if(m_bInternalLinkFont)
+ {
+ ::DeleteObject(m_hFontLink);
+ m_bInternalLinkFont = false;
+ }
+
+ CFontHandle font = (m_hFontNormal != NULL) ? m_hFontNormal : (HFONT)::GetStockObject(SYSTEM_FONT);
+ LOGFONT lf = { 0 };
+ font.GetLogFont(&lf);
+
+ if(IsUsingTagsBold())
+ lf.lfWeight = FW_BOLD;
+ else if(!IsNotUnderlined())
+ lf.lfUnderline = TRUE;
+
+ m_hFontLink = ::CreateFontIndirect(&lf);
+ m_bInternalLinkFont = true;
+ ATLASSERT(m_hFontLink != NULL);
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CHyperLinkImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_RANGE_HANDLER(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseMessage)
+#endif // !_WIN32_WCE
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+#endif // !_WIN32_WCE
+ MESSAGE_HANDLER(WM_SETFOCUS, OnFocus)
+ MESSAGE_HANDLER(WM_KILLFOCUS, OnFocus)
+ MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_MOUSELEAVE, OnMouseLeave)
+#endif // !_WIN32_WCE
+ MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
+ MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
+ MESSAGE_HANDLER(WM_CHAR, OnChar)
+ MESSAGE_HANDLER(WM_GETDLGCODE, OnGetDlgCode)
+ MESSAGE_HANDLER(WM_SETCURSOR, OnSetCursor)
+ MESSAGE_HANDLER(WM_ENABLE, OnEnable)
+ MESSAGE_HANDLER(WM_GETFONT, OnGetFont)
+ MESSAGE_HANDLER(WM_SETFONT, OnSetFont)
+ MESSAGE_HANDLER(WM_UPDATEUISTATE, OnUpdateUiState)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Init();
+ return 0;
+ }
+
+#ifndef _WIN32_WCE
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_tip.IsWindow())
+ {
+ m_tip.DestroyWindow();
+ m_tip.m_hWnd = NULL;
+ }
+
+ if(m_bInternalLinkFont)
+ {
+ ::DeleteObject(m_hFontLink);
+ m_hFontLink = NULL;
+ m_bInternalLinkFont = false;
+ }
+
+ if(m_bInternalNormalFont)
+ {
+ ::DeleteObject(m_hFontNormal);
+ m_hFontNormal = NULL;
+ m_bInternalNormalFont = false;
+ }
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnMouseMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ MSG msg = { m_hWnd, uMsg, wParam, lParam };
+ if(m_tip.IsWindow() && IsUsingToolTip())
+ m_tip.RelayEvent(&msg);
+ bHandled = FALSE;
+ return 1;
+ }
+#endif // !_WIN32_WCE
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1; // no background painting needed (we do it all during WM_PAINT)
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(!m_bPaintLabel)
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+ T* pT = static_cast<T*>(this);
+ if(wParam != NULL)
+ {
+ pT->DoEraseBackground((HDC)wParam);
+ pT->DoPaint((HDC)wParam);
+ }
+ else
+ {
+ CPaintDC dc(m_hWnd);
+ pT->DoEraseBackground(dc.m_hDC);
+ pT->DoPaint(dc.m_hDC);
+ }
+
+ return 0;
+ }
+
+ LRESULT OnFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_bPaintLabel)
+ Invalidate();
+ else
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ if((m_lpstrHyperLink != NULL || IsCommandButton()) && ::PtInRect(&m_rcLink, pt))
+ {
+ ::SetCursor(m_hCursor);
+ if(IsUnderlineHover())
+ {
+ if(!m_bHover)
+ {
+ m_bHover = true;
+ InvalidateRect(&m_rcLink);
+ UpdateWindow();
+#ifndef _WIN32_WCE
+ StartTrackMouseLeave();
+#endif // !_WIN32_WCE
+ }
+ }
+ }
+ else
+ {
+ if(IsUnderlineHover())
+ {
+ if(m_bHover)
+ {
+ m_bHover = false;
+ InvalidateRect(&m_rcLink);
+ UpdateWindow();
+ }
+ }
+ bHandled = FALSE;
+ }
+ return 0;
+ }
+
+#ifndef _WIN32_WCE
+ LRESULT OnMouseLeave(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(IsUnderlineHover() && m_bHover)
+ {
+ m_bHover = false;
+ InvalidateRect(&m_rcLink);
+ UpdateWindow();
+ }
+ return 0;
+ }
+#endif // !_WIN32_WCE
+
+ LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ if(::PtInRect(&m_rcLink, pt))
+ {
+ SetFocus();
+ SetCapture();
+ }
+ return 0;
+ }
+
+ LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ if(GetCapture() == m_hWnd)
+ {
+ ReleaseCapture();
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ if(::PtInRect(&m_rcLink, pt))
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Navigate();
+ }
+ }
+ return 0;
+ }
+
+ LRESULT OnChar(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(wParam == VK_RETURN || wParam == VK_SPACE)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Navigate();
+ }
+ return 0;
+ }
+
+ LRESULT OnGetDlgCode(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return DLGC_WANTCHARS;
+ }
+
+ LRESULT OnSetCursor(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ POINT pt = { 0, 0 };
+ GetCursorPos(&pt);
+ ScreenToClient(&pt);
+ if((m_lpstrHyperLink != NULL || IsCommandButton()) && ::PtInRect(&m_rcLink, pt))
+ {
+ return TRUE;
+ }
+ bHandled = FALSE;
+ return FALSE;
+ }
+
+ LRESULT OnEnable(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ Invalidate();
+ UpdateWindow();
+ return 0;
+ }
+
+ LRESULT OnGetFont(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return (LRESULT)m_hFontNormal;
+ }
+
+ LRESULT OnSetFont(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ if(m_bInternalNormalFont)
+ {
+ ::DeleteObject(m_hFontNormal);
+ m_bInternalNormalFont = false;
+ }
+
+ bool bCreateLinkFont = m_bInternalLinkFont;
+
+ m_hFontNormal = (HFONT)wParam;
+
+ if(bCreateLinkFont || IsAutoCreateLinkFont())
+ CreateLinkFontFromNormal();
+
+ T* pT = static_cast<T*>(this);
+ pT->CalcLabelRect();
+
+ if((BOOL)lParam)
+ {
+ Invalidate();
+ UpdateWindow();
+ }
+
+ return 0;
+ }
+
+ LRESULT OnUpdateUiState(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ // If the control is subclassed or superclassed, this message can cause
+ // repainting without WM_PAINT. We don't use this state, so just do nothing.
+ return 0;
+ }
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->CalcLabelRect();
+ pT->Invalidate();
+ return 0;
+ }
+
+// Implementation
+ void Init()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ // Check if we should paint a label
+ const int cchBuff = 8;
+ TCHAR szBuffer[cchBuff] = { 0 };
+ if(::GetClassName(m_hWnd, szBuffer, cchBuff))
+ {
+ if(lstrcmpi(szBuffer, _T("static")) == 0)
+ {
+ ModifyStyle(0, SS_NOTIFY); // we need this
+ DWORD dwStyle = GetStyle() & 0x000000FF;
+#ifndef _WIN32_WCE
+ if(dwStyle == SS_ICON || dwStyle == SS_BLACKRECT || dwStyle == SS_GRAYRECT ||
+ dwStyle == SS_WHITERECT || dwStyle == SS_BLACKFRAME || dwStyle == SS_GRAYFRAME ||
+ dwStyle == SS_WHITEFRAME || dwStyle == SS_OWNERDRAW ||
+ dwStyle == SS_BITMAP || dwStyle == SS_ENHMETAFILE)
+#else // CE specific
+ if(dwStyle == SS_ICON || dwStyle == SS_BITMAP)
+#endif // _WIN32_WCE
+ m_bPaintLabel = false;
+ }
+ }
+
+ // create or load a cursor
+#if (WINVER >= 0x0500) || defined(_WIN32_WCE)
+ m_hCursor = ::LoadCursor(NULL, IDC_HAND);
+#else
+ m_hCursor = ::CreateCursor(ModuleHelper::GetModuleInstance(), _AtlHyperLink_CursorData.xHotSpot, _AtlHyperLink_CursorData.yHotSpot, _AtlHyperLink_CursorData.cxWidth, _AtlHyperLink_CursorData.cyHeight, _AtlHyperLink_CursorData.arrANDPlane, _AtlHyperLink_CursorData.arrXORPlane);
+#endif
+ ATLASSERT(m_hCursor != NULL);
+
+ // set fonts
+ if(m_bPaintLabel)
+ {
+ if(m_hFontNormal == NULL)
+ {
+ m_hFontNormal = AtlCreateControlFont();
+ m_bInternalNormalFont = true;
+ }
+
+ if(m_hFontLink == NULL)
+ CreateLinkFontFromNormal();
+ }
+
+#ifndef _WIN32_WCE
+ // create a tool tip
+ m_tip.Create(m_hWnd);
+ ATLASSERT(m_tip.IsWindow());
+#endif // !_WIN32_WCE
+
+ // set label (defaults to window text)
+ if(m_lpstrLabel == NULL)
+ {
+ int nLen = GetWindowTextLength();
+ if(nLen > 0)
+ {
+ ATLTRY(m_lpstrLabel = new TCHAR[nLen + 1]);
+ if(m_lpstrLabel != NULL)
+ ATLVERIFY(GetWindowText(m_lpstrLabel, nLen + 1) > 0);
+ }
+ }
+
+ T* pT = static_cast<T*>(this);
+ pT->CalcLabelRect();
+
+ // set hyperlink (defaults to label), or just activate tool tip if already set
+ if(m_lpstrHyperLink == NULL && !IsCommandButton())
+ {
+ if(m_lpstrLabel != NULL)
+ SetHyperLink(m_lpstrLabel);
+ }
+#ifndef _WIN32_WCE
+ else
+ {
+ m_tip.Activate(TRUE);
+ m_tip.AddTool(m_hWnd, m_lpstrHyperLink, &m_rcLink, 1);
+ }
+#endif // !_WIN32_WCE
+
+ // set link colors
+ if(m_bPaintLabel)
+ {
+ CRegKeyEx rk;
+ LONG lRet = rk.Open(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Internet Explorer\\Settings"));
+ if(lRet == ERROR_SUCCESS)
+ {
+ const int cchValue = 12;
+ TCHAR szValue[cchValue] = { 0 };
+ ULONG ulCount = cchValue;
+ lRet = rk.QueryStringValue(_T("Anchor Color"), szValue, &ulCount);
+ if(lRet == ERROR_SUCCESS)
+ {
+ COLORREF clr = pT->_ParseColorString(szValue);
+ ATLASSERT(clr != CLR_INVALID);
+ if(clr != CLR_INVALID)
+ m_clrLink = clr;
+ }
+
+ ulCount = cchValue;
+ lRet = rk.QueryStringValue(_T("Anchor Color Visited"), szValue, &ulCount);
+ if(lRet == ERROR_SUCCESS)
+ {
+ COLORREF clr = pT->_ParseColorString(szValue);
+ ATLASSERT(clr != CLR_INVALID);
+ if(clr != CLR_INVALID)
+ m_clrVisited = clr;
+ }
+ }
+ }
+ }
+
+ static COLORREF _ParseColorString(LPTSTR lpstr)
+ {
+ int c[3] = { -1, -1, -1 };
+ LPTSTR p = NULL;
+ for(int i = 0; i < 2; i++)
+ {
+ for(p = lpstr; *p != _T('\0'); p = ::CharNext(p))
+ {
+ if(*p == _T(','))
+ {
+ *p = _T('\0');
+ c[i] = T::_xttoi(lpstr);
+ lpstr = &p[1];
+ break;
+ }
+ }
+ if(c[i] == -1)
+ return CLR_INVALID;
+ }
+ if(*lpstr == _T('\0'))
+ return CLR_INVALID;
+ c[2] = T::_xttoi(lpstr);
+
+ return RGB(c[0], c[1], c[2]);
+ }
+
+ bool CalcLabelRect()
+ {
+ if(!::IsWindow(m_hWnd))
+ return false;
+ if(m_lpstrLabel == NULL && m_lpstrHyperLink == NULL)
+ return false;
+
+ CClientDC dc(m_hWnd);
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+ m_rcLink = rcClient;
+ if(!m_bPaintLabel)
+ return true;
+
+ if(IsUsingTags())
+ {
+ // find tags and label parts
+ LPTSTR lpstrLeft = NULL;
+ int cchLeft = 0;
+ LPTSTR lpstrLink = NULL;
+ int cchLink = 0;
+ LPTSTR lpstrRight = NULL;
+ int cchRight = 0;
+
+ T* pT = static_cast<T*>(this);
+ pT->CalcLabelParts(lpstrLeft, cchLeft, lpstrLink, cchLink, lpstrRight, cchRight);
+ ATLASSERT(lpstrLink != NULL);
+ ATLASSERT(cchLink > 0);
+
+ // get label part rects
+ HFONT hFontOld = dc.SelectFont(m_hFontNormal);
+
+ UINT uFormat = IsSingleLine() ? DT_SINGLELINE : DT_WORDBREAK;
+
+ RECT rcLeft = rcClient;
+ if(lpstrLeft != NULL)
+ dc.DrawText(lpstrLeft, cchLeft, &rcLeft, DT_LEFT | uFormat | DT_CALCRECT);
+
+ dc.SelectFont(m_hFontLink);
+ RECT rcLink = rcClient;
+ if(lpstrLeft != NULL)
+ rcLink.left = rcLeft.right;
+ dc.DrawText(lpstrLink, cchLink, &rcLink, DT_LEFT | uFormat | DT_CALCRECT);
+
+ dc.SelectFont(hFontOld);
+
+ m_rcLink = rcLink;
+ }
+ else
+ {
+ HFONT hOldFont = NULL;
+ if(m_hFontLink != NULL)
+ hOldFont = dc.SelectFont(m_hFontLink);
+ LPTSTR lpstrText = (m_lpstrLabel != NULL) ? m_lpstrLabel : m_lpstrHyperLink;
+ DWORD dwStyle = GetStyle();
+ UINT uFormat = DT_LEFT;
+ if (dwStyle & SS_CENTER)
+ uFormat = DT_CENTER;
+ else if (dwStyle & SS_RIGHT)
+ uFormat = DT_RIGHT;
+ uFormat |= IsSingleLine() ? DT_SINGLELINE : DT_WORDBREAK;
+ dc.DrawText(lpstrText, -1, &m_rcLink, uFormat | DT_CALCRECT);
+ if(m_hFontLink != NULL)
+ dc.SelectFont(hOldFont);
+ if (dwStyle & SS_CENTER)
+ {
+ int dx = (rcClient.right - m_rcLink.right) / 2;
+ ::OffsetRect(&m_rcLink, dx, 0);
+ }
+ else if (dwStyle & SS_RIGHT)
+ {
+ int dx = rcClient.right - m_rcLink.right;
+ ::OffsetRect(&m_rcLink, dx, 0);
+ }
+ }
+
+ return true;
+ }
+
+ void CalcLabelParts(LPTSTR& lpstrLeft, int& cchLeft, LPTSTR& lpstrLink, int& cchLink, LPTSTR& lpstrRight, int& cchRight) const
+ {
+ lpstrLeft = NULL;
+ cchLeft = 0;
+ lpstrLink = NULL;
+ cchLink = 0;
+ lpstrRight = NULL;
+ cchRight = 0;
+
+ LPTSTR lpstrText = (m_lpstrLabel != NULL) ? m_lpstrLabel : m_lpstrHyperLink;
+ int cchText = lstrlen(lpstrText);
+ bool bOutsideLink = true;
+ for(int i = 0; i < cchText; i++)
+ {
+ if(lpstrText[i] != _T('<'))
+ continue;
+
+ if(bOutsideLink)
+ {
+ if(::CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, &lpstrText[i], 3, _T("<A>"), 3) == CSTR_EQUAL)
+ {
+ if(i > 0)
+ {
+ lpstrLeft = lpstrText;
+ cchLeft = i;
+ }
+ lpstrLink = &lpstrText[i + 3];
+ bOutsideLink = false;
+ }
+ }
+ else
+ {
+ if(::CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, &lpstrText[i], 4, _T("</A>"), 4) == CSTR_EQUAL)
+ {
+ cchLink = i - 3 - cchLeft;
+ if(lpstrText[i + 4] != 0)
+ {
+ lpstrRight = &lpstrText[i + 4];
+ cchRight = cchText - (i + 4);
+ break;
+ }
+ }
+ }
+ }
+
+ }
+
+ void DoEraseBackground(CDCHandle dc)
+ {
+ HBRUSH hBrush = (HBRUSH)::SendMessage(GetParent(), WM_CTLCOLORSTATIC, (WPARAM)dc.m_hDC, (LPARAM)m_hWnd);
+ if(hBrush != NULL)
+ {
+ RECT rect = { 0 };
+ GetClientRect(&rect);
+ dc.FillRect(&rect, hBrush);
+ }
+ }
+
+ void DoPaint(CDCHandle dc)
+ {
+ if(IsUsingTags())
+ {
+ // find tags and label parts
+ LPTSTR lpstrLeft = NULL;
+ int cchLeft = 0;
+ LPTSTR lpstrLink = NULL;
+ int cchLink = 0;
+ LPTSTR lpstrRight = NULL;
+ int cchRight = 0;
+
+ T* pT = static_cast<T*>(this);
+ pT->CalcLabelParts(lpstrLeft, cchLeft, lpstrLink, cchLink, lpstrRight, cchRight);
+
+ // get label part rects
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+
+ dc.SetBkMode(TRANSPARENT);
+ HFONT hFontOld = dc.SelectFont(m_hFontNormal);
+
+ UINT uFormat = IsSingleLine() ? DT_SINGLELINE : DT_WORDBREAK;
+
+ if(lpstrLeft != NULL)
+ dc.DrawText(lpstrLeft, cchLeft, &rcClient, DT_LEFT | uFormat);
+
+ COLORREF clrOld = dc.SetTextColor(IsWindowEnabled() ? (m_bVisited ? m_clrVisited : m_clrLink) : (::GetSysColor(COLOR_GRAYTEXT)));
+ if(m_hFontLink != NULL && (!IsUnderlineHover() || (IsUnderlineHover() && m_bHover)))
+ dc.SelectFont(m_hFontLink);
+ else
+ dc.SelectFont(m_hFontNormal);
+
+ dc.DrawText(lpstrLink, cchLink, &m_rcLink, DT_LEFT | uFormat);
+
+ dc.SetTextColor(clrOld);
+ dc.SelectFont(m_hFontNormal);
+ if(lpstrRight != NULL)
+ {
+ RECT rcRight = { m_rcLink.right, m_rcLink.top, rcClient.right, rcClient.bottom };
+ dc.DrawText(lpstrRight, cchRight, &rcRight, DT_LEFT | uFormat);
+ }
+
+ if(GetFocus() == m_hWnd)
+ dc.DrawFocusRect(&m_rcLink);
+
+ dc.SelectFont(hFontOld);
+ }
+ else
+ {
+ dc.SetBkMode(TRANSPARENT);
+ COLORREF clrOld = dc.SetTextColor(IsWindowEnabled() ? (m_bVisited ? m_clrVisited : m_clrLink) : (::GetSysColor(COLOR_GRAYTEXT)));
+
+ HFONT hFontOld = NULL;
+ if(m_hFontLink != NULL && (!IsUnderlineHover() || (IsUnderlineHover() && m_bHover)))
+ hFontOld = dc.SelectFont(m_hFontLink);
+ else
+ hFontOld = dc.SelectFont(m_hFontNormal);
+
+ LPTSTR lpstrText = (m_lpstrLabel != NULL) ? m_lpstrLabel : m_lpstrHyperLink;
+
+ DWORD dwStyle = GetStyle();
+ UINT uFormat = DT_LEFT;
+ if (dwStyle & SS_CENTER)
+ uFormat = DT_CENTER;
+ else if (dwStyle & SS_RIGHT)
+ uFormat = DT_RIGHT;
+ uFormat |= IsSingleLine() ? DT_SINGLELINE : DT_WORDBREAK;
+
+ dc.DrawText(lpstrText, -1, &m_rcLink, uFormat);
+
+ if(GetFocus() == m_hWnd)
+ dc.DrawFocusRect(&m_rcLink);
+
+ dc.SetTextColor(clrOld);
+ dc.SelectFont(hFontOld);
+ }
+ }
+
+#ifndef _WIN32_WCE
+ BOOL StartTrackMouseLeave()
+ {
+ TRACKMOUSEEVENT tme = { 0 };
+ tme.cbSize = sizeof(tme);
+ tme.dwFlags = TME_LEAVE;
+ tme.hwndTrack = m_hWnd;
+ return _TrackMouseEvent(&tme);
+ }
+#endif // !_WIN32_WCE
+
+// Implementation helpers
+ bool IsUnderlined() const
+ {
+ return ((m_dwExtendedStyle & (HLINK_NOTUNDERLINED | HLINK_UNDERLINEHOVER)) == 0);
+ }
+
+ bool IsNotUnderlined() const
+ {
+ return ((m_dwExtendedStyle & HLINK_NOTUNDERLINED) != 0);
+ }
+
+ bool IsUnderlineHover() const
+ {
+ return ((m_dwExtendedStyle & HLINK_UNDERLINEHOVER) != 0);
+ }
+
+ bool IsCommandButton() const
+ {
+ return ((m_dwExtendedStyle & HLINK_COMMANDBUTTON) != 0);
+ }
+
+ bool IsNotifyButton() const
+ {
+ return ((m_dwExtendedStyle & HLINK_NOTIFYBUTTON) == HLINK_NOTIFYBUTTON);
+ }
+
+ bool IsUsingTags() const
+ {
+ return ((m_dwExtendedStyle & HLINK_USETAGS) != 0);
+ }
+
+ bool IsUsingTagsBold() const
+ {
+ return ((m_dwExtendedStyle & HLINK_USETAGSBOLD) == HLINK_USETAGSBOLD);
+ }
+
+ bool IsUsingToolTip() const
+ {
+ return ((m_dwExtendedStyle & HLINK_NOTOOLTIP) == 0);
+ }
+
+ bool IsAutoCreateLinkFont() const
+ {
+ return ((m_dwExtendedStyle & HLINK_AUTOCREATELINKFONT) == HLINK_AUTOCREATELINKFONT);
+ }
+
+ bool IsSingleLine() const
+ {
+ return ((m_dwExtendedStyle & HLINK_SINGLELINE) == HLINK_SINGLELINE);
+ }
+
+ static int _xttoi(const TCHAR* nptr)
+ {
+#ifndef _ATL_MIN_CRT
+ return _ttoi(nptr);
+#else // _ATL_MIN_CRT
+ while(*nptr == _T(' ')) // skip spaces
+ ++nptr;
+
+ int c = (int)(_TUCHAR)*nptr++;
+ int sign = c; // save sign indication
+ if (c == _T('-') || c == _T('+'))
+ c = (int)(_TUCHAR)*nptr++; // skip sign
+
+ int total = 0;
+ while((TCHAR)c >= _T('0') && (TCHAR)c <= _T('9'))
+ {
+ total = 10 * total + ((TCHAR)c - _T('0')); // accumulate digit
+ c = (int)(_TUCHAR)*nptr++; // get next char
+ }
+
+ // return result, negated if necessary
+ return ((TCHAR)sign != _T('-')) ? total : -total;
+#endif // _ATL_MIN_CRT
+ }
+};
+
+class CHyperLink : public CHyperLinkImpl<CHyperLink>
+{
+public:
+ DECLARE_WND_CLASS(_T("WTL_HyperLink"))
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CWaitCursor - displays a wait cursor
+
+class CWaitCursor
+{
+public:
+// Data
+ HCURSOR m_hWaitCursor;
+ HCURSOR m_hOldCursor;
+ bool m_bInUse;
+
+// Constructor/destructor
+ CWaitCursor(bool bSet = true, LPCTSTR lpstrCursor = IDC_WAIT, bool bSys = true) : m_hOldCursor(NULL), m_bInUse(false)
+ {
+ HINSTANCE hInstance = bSys ? NULL : ModuleHelper::GetResourceInstance();
+ m_hWaitCursor = ::LoadCursor(hInstance, lpstrCursor);
+ ATLASSERT(m_hWaitCursor != NULL);
+
+ if(bSet)
+ Set();
+ }
+
+ ~CWaitCursor()
+ {
+ Restore();
+ }
+
+// Methods
+ bool Set()
+ {
+ if(m_bInUse)
+ return false;
+ m_hOldCursor = ::SetCursor(m_hWaitCursor);
+ m_bInUse = true;
+ return true;
+ }
+
+ bool Restore()
+ {
+ if(!m_bInUse)
+ return false;
+ ::SetCursor(m_hOldCursor);
+ m_bInUse = false;
+ return true;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CCustomWaitCursor - for custom and animated cursors
+
+class CCustomWaitCursor : public CWaitCursor
+{
+public:
+// Constructor/destructor
+ CCustomWaitCursor(ATL::_U_STRINGorID cursor, bool bSet = true, HINSTANCE hInstance = NULL) :
+ CWaitCursor(false, IDC_WAIT, true)
+ {
+ if(hInstance == NULL)
+ hInstance = ModuleHelper::GetResourceInstance();
+ m_hWaitCursor = (HCURSOR)::LoadImage(hInstance, cursor.m_lpstr, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE);
+
+ if(bSet)
+ Set();
+ }
+
+ ~CCustomWaitCursor()
+ {
+ Restore();
+#if !defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)))
+ ::DestroyCursor(m_hWaitCursor);
+#endif // !defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)))
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMultiPaneStatusBarCtrl - Status Bar with multiple panes
+
+template <class T, class TBase = CStatusBarCtrl>
+class ATL_NO_VTABLE CMultiPaneStatusBarCtrlImpl : public ATL::CWindowImpl< T, TBase >
+{
+public:
+ DECLARE_WND_SUPERCLASS(NULL, TBase::GetWndClassName())
+
+// Data
+ enum { m_cxPaneMargin = 3 };
+
+ int m_nPanes;
+ int* m_pPane;
+
+// Constructor/destructor
+ CMultiPaneStatusBarCtrlImpl() : m_nPanes(0), m_pPane(NULL)
+ { }
+
+ ~CMultiPaneStatusBarCtrlImpl()
+ {
+ delete [] m_pPane;
+ }
+
+// Methods
+ HWND Create(HWND hWndParent, LPCTSTR lpstrText, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | SBARS_SIZEGRIP, UINT nID = ATL_IDW_STATUS_BAR)
+ {
+#if (_MSC_VER >= 1300)
+ return ATL::CWindowImpl< T, TBase >::Create(hWndParent, rcDefault, lpstrText, dwStyle, 0, nID);
+#else // !(_MSC_VER >= 1300)
+ typedef ATL::CWindowImpl< T, TBase > _baseClass;
+ return _baseClass::Create(hWndParent, rcDefault, lpstrText, dwStyle, 0, nID);
+#endif // !(_MSC_VER >= 1300)
+ }
+
+ HWND Create(HWND hWndParent, UINT nTextID = ATL_IDS_IDLEMESSAGE, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | SBARS_SIZEGRIP, UINT nID = ATL_IDW_STATUS_BAR)
+ {
+ const int cchMax = 128; // max text length is 127 for status bars (+1 for null)
+ TCHAR szText[cchMax];
+ szText[0] = 0;
+ ::LoadString(ModuleHelper::GetResourceInstance(), nTextID, szText, cchMax);
+ return Create(hWndParent, szText, dwStyle, nID);
+ }
+
+ BOOL SetPanes(int* pPanes, int nPanes, bool bSetText = true)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPanes > 0);
+
+ m_nPanes = nPanes;
+ delete [] m_pPane;
+ m_pPane = NULL;
+
+ ATLTRY(m_pPane = new int[nPanes]);
+ ATLASSERT(m_pPane != NULL);
+ if(m_pPane == NULL)
+ return FALSE;
+
+ CTempBuffer<int, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ int* pPanesPos = buff.Allocate(nPanes);
+ ATLASSERT(pPanesPos != NULL);
+ if(pPanesPos == NULL)
+ return FALSE;
+
+ SecureHelper::memcpy_x(m_pPane, nPanes * sizeof(int), pPanes, nPanes * sizeof(int));
+
+ // get status bar DC and set font
+ CClientDC dc(m_hWnd);
+ HFONT hOldFont = dc.SelectFont(GetFont());
+
+ // get status bar borders
+ int arrBorders[3] = { 0 };
+ GetBorders(arrBorders);
+
+ const int cchBuff = 128;
+ TCHAR szBuff[cchBuff] = { 0 };
+ SIZE size = { 0, 0 };
+ int cxLeft = arrBorders[0];
+
+ // calculate right edge of each part
+ for(int i = 0; i < nPanes; i++)
+ {
+ if(pPanes[i] == ID_DEFAULT_PANE)
+ {
+ // make very large, will be resized later
+ pPanesPos[i] = INT_MAX / 2;
+ }
+ else
+ {
+ ::LoadString(ModuleHelper::GetResourceInstance(), pPanes[i], szBuff, cchBuff);
+ dc.GetTextExtent(szBuff, lstrlen(szBuff), &size);
+ T* pT = static_cast<T*>(this);
+ pT;
+ pPanesPos[i] = cxLeft + size.cx + arrBorders[2] + 2 * pT->m_cxPaneMargin;
+ }
+ cxLeft = pPanesPos[i];
+ }
+
+ BOOL bRet = SetParts(nPanes, pPanesPos);
+
+ if(bRet && bSetText)
+ {
+ for(int i = 0; i < nPanes; i++)
+ {
+ if(pPanes[i] != ID_DEFAULT_PANE)
+ {
+ ::LoadString(ModuleHelper::GetResourceInstance(), pPanes[i], szBuff, cchBuff);
+ SetPaneText(m_pPane[i], szBuff);
+ }
+ }
+ }
+
+ dc.SelectFont(hOldFont);
+ return bRet;
+ }
+
+ bool GetPaneTextLength(int nPaneID, int* pcchLength = NULL, int* pnType = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return false;
+
+ int nLength = GetTextLength(nIndex, pnType);
+ if(pcchLength != NULL)
+ *pcchLength = nLength;
+
+ return true;
+ }
+
+ BOOL GetPaneText(int nPaneID, LPTSTR lpstrText, int* pcchLength = NULL, int* pnType = NULL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return FALSE;
+
+ int nLength = GetText(nIndex, lpstrText, pnType);
+ if(pcchLength != NULL)
+ *pcchLength = nLength;
+
+ return TRUE;
+ }
+
+ BOOL SetPaneText(int nPaneID, LPCTSTR lpstrText, int nType = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return FALSE;
+
+ return SetText(nIndex, lpstrText, nType);
+ }
+
+ BOOL GetPaneRect(int nPaneID, LPRECT lpRect) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return FALSE;
+
+ return GetRect(nIndex, lpRect);
+ }
+
+ BOOL SetPaneWidth(int nPaneID, int cxWidth)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPaneID != ID_DEFAULT_PANE); // Can't resize this one
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return FALSE;
+
+ // get pane positions
+ CTempBuffer<int, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ int* pPanesPos = buff.Allocate(m_nPanes);
+ if(pPanesPos == NULL)
+ return FALSE;
+ GetParts(m_nPanes, pPanesPos);
+ // calculate offset
+ int cxPaneWidth = pPanesPos[nIndex] - ((nIndex == 0) ? 0 : pPanesPos[nIndex - 1]);
+ int cxOff = cxWidth - cxPaneWidth;
+ // find variable width pane
+ int nDef = m_nPanes;
+ for(int i = 0; i < m_nPanes; i++)
+ {
+ if(m_pPane[i] == ID_DEFAULT_PANE)
+ {
+ nDef = i;
+ break;
+ }
+ }
+ // resize
+ if(nIndex < nDef) // before default pane
+ {
+ for(int i = nIndex; i < nDef; i++)
+ pPanesPos[i] += cxOff;
+
+ }
+ else // after default one
+ {
+ for(int i = nDef; i < nIndex; i++)
+ pPanesPos[i] -= cxOff;
+ }
+ // set pane postions
+ return SetParts(m_nPanes, pPanesPos);
+ }
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ BOOL GetPaneTipText(int nPaneID, LPTSTR lpstrText, int nSize) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return FALSE;
+
+ GetTipText(nIndex, lpstrText, nSize);
+ return TRUE;
+ }
+
+ BOOL SetPaneTipText(int nPaneID, LPCTSTR lpstrText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return FALSE;
+
+ SetTipText(nIndex, lpstrText);
+ return TRUE;
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+#if ((_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 0x0500))
+ BOOL GetPaneIcon(int nPaneID, HICON& hIcon) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return FALSE;
+
+ hIcon = GetIcon(nIndex);
+ return TRUE;
+ }
+
+ BOOL SetPaneIcon(int nPaneID, HICON hIcon)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ int nIndex = GetPaneIndexFromID(nPaneID);
+ if(nIndex == -1)
+ return FALSE;
+
+ return SetIcon(nIndex, hIcon);
+ }
+#endif // ((_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)) || (defined(_WIN32_WCE) && (_WIN32_WCE >= 0x0500))
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CMultiPaneStatusBarCtrlImpl< T >)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ END_MSG_MAP()
+
+ LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+ if(wParam != SIZE_MINIMIZED && m_nPanes > 0)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdatePanesLayout();
+ }
+ return lRet;
+ }
+
+// Implementation
+ BOOL UpdatePanesLayout()
+ {
+ // get pane positions
+ CTempBuffer<int, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ int* pPanesPos = buff.Allocate(m_nPanes);
+ ATLASSERT(pPanesPos != NULL);
+ if(pPanesPos == NULL)
+ return FALSE;
+ int nRet = GetParts(m_nPanes, pPanesPos);
+ ATLASSERT(nRet == m_nPanes);
+ if(nRet != m_nPanes)
+ return FALSE;
+ // calculate offset
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+ int cxOff = rcClient.right - pPanesPos[m_nPanes - 1];
+#ifndef _WIN32_WCE
+ // Move panes left if size grip box is present
+ if((GetStyle() & SBARS_SIZEGRIP) != 0)
+ cxOff -= ::GetSystemMetrics(SM_CXVSCROLL) + ::GetSystemMetrics(SM_CXEDGE);
+#endif // !_WIN32_WCE
+ // find variable width pane
+ int i;
+ for(i = 0; i < m_nPanes; i++)
+ {
+ if(m_pPane[i] == ID_DEFAULT_PANE)
+ break;
+ }
+ // resize all panes from the variable one to the right
+ if((i < m_nPanes) && (pPanesPos[i] + cxOff) > ((i == 0) ? 0 : pPanesPos[i - 1]))
+ {
+ for(; i < m_nPanes; i++)
+ pPanesPos[i] += cxOff;
+ }
+ // set pane postions
+ return SetParts(m_nPanes, pPanesPos);
+ }
+
+ int GetPaneIndexFromID(int nPaneID) const
+ {
+ for(int i = 0; i < m_nPanes; i++)
+ {
+ if(m_pPane[i] == nPaneID)
+ return i;
+ }
+
+ return -1; // not found
+ }
+};
+
+class CMultiPaneStatusBarCtrl : public CMultiPaneStatusBarCtrlImpl<CMultiPaneStatusBarCtrl>
+{
+public:
+ DECLARE_WND_SUPERCLASS(_T("WTL_MultiPaneStatusBar"), GetWndClassName())
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPaneContainer - provides header with title and close button for panes
+
+// pane container extended styles
+#define PANECNT_NOCLOSEBUTTON 0x00000001
+#define PANECNT_VERTICAL 0x00000002
+#define PANECNT_FLATBORDER 0x00000004
+#define PANECNT_NOBORDER 0x00000008
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CPaneContainerImpl : public ATL::CWindowImpl< T, TBase, TWinTraits >, public CCustomDraw< T >
+{
+public:
+ DECLARE_WND_CLASS_EX(NULL, 0, -1)
+
+// Constants
+ enum
+ {
+ m_cxyBorder = 2,
+ m_cxyTextOffset = 4,
+ m_cxyBtnOffset = 1,
+
+ m_cchTitle = 80,
+
+ m_cxImageTB = 13,
+ m_cyImageTB = 11,
+ m_cxyBtnAddTB = 7,
+
+ m_cxToolBar = m_cxImageTB + m_cxyBtnAddTB + m_cxyBorder + m_cxyBtnOffset,
+
+ m_xBtnImageLeft = 6,
+ m_yBtnImageTop = 5,
+ m_xBtnImageRight = 12,
+ m_yBtnImageBottom = 11,
+
+ m_nCloseBtnID = ID_PANE_CLOSE
+ };
+
+// Data members
+ CToolBarCtrl m_tb;
+ ATL::CWindow m_wndClient;
+ int m_cxyHeader;
+ TCHAR m_szTitle[m_cchTitle];
+ DWORD m_dwExtendedStyle; // Pane container specific extended styles
+ HFONT m_hFont;
+ bool m_bInternalFont;
+
+
+// Constructor
+ CPaneContainerImpl() : m_cxyHeader(0), m_dwExtendedStyle(0), m_hFont(NULL), m_bInternalFont(false)
+ {
+ m_szTitle[0] = 0;
+ }
+
+// Attributes
+ DWORD GetPaneContainerExtendedStyle() const
+ {
+ return m_dwExtendedStyle;
+ }
+
+ DWORD SetPaneContainerExtendedStyle(DWORD dwExtendedStyle, DWORD dwMask = 0)
+ {
+ DWORD dwPrevStyle = m_dwExtendedStyle;
+ if(dwMask == 0)
+ m_dwExtendedStyle = dwExtendedStyle;
+ else
+ m_dwExtendedStyle = (m_dwExtendedStyle & ~dwMask) | (dwExtendedStyle & dwMask);
+ if(m_hWnd != NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ bool bUpdate = false;
+
+ if(((dwPrevStyle & PANECNT_NOCLOSEBUTTON) != 0) && ((m_dwExtendedStyle & PANECNT_NOCLOSEBUTTON) == 0)) // add close button
+ {
+ pT->CreateCloseButton();
+ bUpdate = true;
+ }
+ else if(((dwPrevStyle & PANECNT_NOCLOSEBUTTON) == 0) && ((m_dwExtendedStyle & PANECNT_NOCLOSEBUTTON) != 0)) // remove close button
+ {
+ pT->DestroyCloseButton();
+ bUpdate = true;
+ }
+
+ if((dwPrevStyle & PANECNT_VERTICAL) != (m_dwExtendedStyle & PANECNT_VERTICAL)) // change orientation
+ {
+ pT->CalcSize();
+ bUpdate = true;
+ }
+
+ if((dwPrevStyle & (PANECNT_FLATBORDER | PANECNT_NOBORDER)) !=
+ (m_dwExtendedStyle & (PANECNT_FLATBORDER | PANECNT_NOBORDER))) // change border
+ {
+ bUpdate = true;
+ }
+
+ if(bUpdate)
+ pT->UpdateLayout();
+ }
+ return dwPrevStyle;
+ }
+
+ HWND GetClient() const
+ {
+ return m_wndClient;
+ }
+
+ HWND SetClient(HWND hWndClient)
+ {
+ HWND hWndOldClient = m_wndClient;
+ m_wndClient = hWndClient;
+ if(m_hWnd != NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+ }
+ return hWndOldClient;
+ }
+
+ BOOL GetTitle(LPTSTR lpstrTitle, int cchLength) const
+ {
+ ATLASSERT(lpstrTitle != NULL);
+
+ errno_t nRet = SecureHelper::strncpy_x(lpstrTitle, cchLength, m_szTitle, _TRUNCATE);
+
+ return (nRet == 0 || nRet == STRUNCATE);
+ }
+
+ BOOL SetTitle(LPCTSTR lpstrTitle)
+ {
+ ATLASSERT(lpstrTitle != NULL);
+
+ errno_t nRet = SecureHelper::strncpy_x(m_szTitle, m_cchTitle, lpstrTitle, _TRUNCATE);
+ bool bRet = (nRet == 0 || nRet == STRUNCATE);
+ if(bRet && m_hWnd != NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+ }
+
+ return bRet;
+ }
+
+ int GetTitleLength() const
+ {
+ return lstrlen(m_szTitle);
+ }
+
+// Methods
+ HWND Create(HWND hWndParent, LPCTSTR lpstrTitle = NULL, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
+ DWORD dwExStyle = 0, UINT nID = 0, LPVOID lpCreateParam = NULL)
+ {
+ if(lpstrTitle != NULL)
+ SecureHelper::strncpy_x(m_szTitle, m_cchTitle, lpstrTitle, _TRUNCATE);
+#if (_MSC_VER >= 1300)
+ return ATL::CWindowImpl< T, TBase, TWinTraits >::Create(hWndParent, rcDefault, NULL, dwStyle, dwExStyle, nID, lpCreateParam);
+#else // !(_MSC_VER >= 1300)
+ typedef ATL::CWindowImpl< T, TBase, TWinTraits > _baseClass;
+ return _baseClass::Create(hWndParent, rcDefault, NULL, dwStyle, dwExStyle, nID, lpCreateParam);
+#endif // !(_MSC_VER >= 1300)
+ }
+
+ HWND Create(HWND hWndParent, UINT uTitleID, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN,
+ DWORD dwExStyle = 0, UINT nID = 0, LPVOID lpCreateParam = NULL)
+ {
+ if(uTitleID != 0U)
+ ::LoadString(ModuleHelper::GetResourceInstance(), uTitleID, m_szTitle, m_cchTitle);
+#if (_MSC_VER >= 1300)
+ return ATL::CWindowImpl< T, TBase, TWinTraits >::Create(hWndParent, rcDefault, NULL, dwStyle, dwExStyle, nID, lpCreateParam);
+#else // !(_MSC_VER >= 1300)
+ typedef ATL::CWindowImpl< T, TBase, TWinTraits > _baseClass;
+ return _baseClass::Create(hWndParent, rcDefault, NULL, dwStyle, dwExStyle, nID, lpCreateParam);
+#endif // !(_MSC_VER >= 1300)
+ }
+
+ BOOL EnableCloseButton(BOOL bEnable)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ return (m_tb.m_hWnd != NULL) ? m_tb.EnableButton(pT->m_nCloseBtnID, bEnable) : FALSE;
+ }
+
+ void UpdateLayout()
+ {
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout(rcClient.right, rcClient.bottom);
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CPaneContainerImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
+ MESSAGE_HANDLER(WM_GETFONT, OnGetFont)
+ MESSAGE_HANDLER(WM_SETFONT, OnSetFont)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+#endif // !_WIN32_WCE
+ MESSAGE_HANDLER(WM_NOTIFY, OnNotify)
+ MESSAGE_HANDLER(WM_COMMAND, OnCommand)
+ FORWARD_NOTIFICATIONS()
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(m_hFont == NULL)
+ {
+ // The same as AtlCreateControlFont() for horizontal pane
+#ifndef _WIN32_WCE
+ LOGFONT lf = { 0 };
+ ATLVERIFY(::SystemParametersInfo(SPI_GETICONTITLELOGFONT, sizeof(LOGFONT), &lf, 0) != FALSE);
+ if(IsVertical())
+ lf.lfEscapement = 900; // 90 degrees
+ m_hFont = ::CreateFontIndirect(&lf);
+#else // CE specific
+ m_hFont = (HFONT)::GetStockObject(SYSTEM_FONT);
+ if(IsVertical())
+ {
+ CLogFont lf(m_hFont);
+ lf.lfEscapement = 900; // 90 degrees
+ m_hFont = ::CreateFontIndirect(&lf);
+ }
+#endif // _WIN32_WCE
+ m_bInternalFont = true;
+ }
+
+ T* pT = static_cast<T*>(this);
+ pT->CalcSize();
+
+ if((m_dwExtendedStyle & PANECNT_NOCLOSEBUTTON) == 0)
+ pT->CreateCloseButton();
+
+ return 0;
+ }
+
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(m_bInternalFont)
+ {
+ ::DeleteObject(m_hFont);
+ m_hFont = NULL;
+ m_bInternalFont = false;
+ }
+
+ return 0;
+ }
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
+ return 0;
+ }
+
+ LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(m_wndClient.m_hWnd != NULL)
+ m_wndClient.SetFocus();
+ return 0;
+ }
+
+ LRESULT OnGetFont(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return (LRESULT)m_hFont;
+ }
+
+ LRESULT OnSetFont(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ if(m_bInternalFont)
+ {
+ ::DeleteObject(m_hFont);
+ m_bInternalFont = false;
+ }
+
+ m_hFont = (HFONT)wParam;
+
+ T* pT = static_cast<T*>(this);
+ pT->CalcSize();
+
+ if((BOOL)lParam != FALSE)
+ pT->UpdateLayout();
+
+ return 0;
+ }
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1; // no background needed
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ if(wParam != NULL)
+ {
+ pT->DrawPaneTitle((HDC)wParam);
+
+ if(m_wndClient.m_hWnd == NULL) // no client window
+ pT->DrawPane((HDC)wParam);
+ }
+ else
+ {
+ CPaintDC dc(m_hWnd);
+ pT->DrawPaneTitle(dc.m_hDC);
+
+ if(m_wndClient.m_hWnd == NULL) // no client window
+ pT->DrawPane(dc.m_hDC);
+ }
+
+ return 0;
+ }
+
+ LRESULT OnNotify(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(m_tb.m_hWnd == NULL)
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+
+ T* pT = static_cast<T*>(this);
+ pT;
+ LPNMHDR lpnmh = (LPNMHDR)lParam;
+ LRESULT lRet = 0;
+
+ // pass toolbar custom draw notifications to the base class
+ if(lpnmh->code == NM_CUSTOMDRAW && lpnmh->hwndFrom == m_tb.m_hWnd)
+ lRet = CCustomDraw< T >::OnCustomDraw(0, lpnmh, bHandled);
+#ifndef _WIN32_WCE
+ // tooltip notifications come with the tooltip window handle and button ID,
+ // pass them to the parent if we don't handle them
+ else if(lpnmh->code == TTN_GETDISPINFO && lpnmh->idFrom == pT->m_nCloseBtnID)
+ bHandled = pT->GetToolTipText(lpnmh);
+#endif // !_WIN32_WCE
+ // only let notifications not from the toolbar go to the parent
+ else if(lpnmh->hwndFrom != m_tb.m_hWnd && lpnmh->idFrom != pT->m_nCloseBtnID)
+ bHandled = FALSE;
+
+ return lRet;
+ }
+
+ LRESULT OnCommand(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ // if command comes from the close button, substitute HWND of the pane container instead
+ if(m_tb.m_hWnd != NULL && (HWND)lParam == m_tb.m_hWnd)
+ return ::SendMessage(GetParent(), WM_COMMAND, wParam, (LPARAM)m_hWnd);
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+// Custom draw overrides
+ DWORD OnPrePaint(int /*idCtrl*/, LPNMCUSTOMDRAW /*lpNMCustomDraw*/)
+ {
+ return CDRF_NOTIFYITEMDRAW; // we need per-item notifications
+ }
+
+ DWORD OnItemPrePaint(int /*idCtrl*/, LPNMCUSTOMDRAW lpNMCustomDraw)
+ {
+ CDCHandle dc = lpNMCustomDraw->hdc;
+#if (_WIN32_IE >= 0x0400)
+ RECT& rc = lpNMCustomDraw->rc;
+#else // !(_WIN32_IE >= 0x0400)
+ RECT rc;
+ m_tb.GetItemRect(0, &rc);
+#endif // !(_WIN32_IE >= 0x0400)
+
+ dc.FillRect(&rc, COLOR_3DFACE);
+
+ return CDRF_NOTIFYPOSTPAINT;
+ }
+
+ DWORD OnItemPostPaint(int /*idCtrl*/, LPNMCUSTOMDRAW lpNMCustomDraw)
+ {
+ CDCHandle dc = lpNMCustomDraw->hdc;
+#if (_WIN32_IE >= 0x0400)
+ RECT& rc = lpNMCustomDraw->rc;
+#else // !(_WIN32_IE >= 0x0400)
+ RECT rc = { 0 };
+ m_tb.GetItemRect(0, &rc);
+#endif // !(_WIN32_IE >= 0x0400)
+
+ RECT rcImage = { m_xBtnImageLeft, m_yBtnImageTop, m_xBtnImageRight + 1, m_yBtnImageBottom + 1 };
+ ::OffsetRect(&rcImage, rc.left, rc.top);
+ T* pT = static_cast<T*>(this);
+
+ if((lpNMCustomDraw->uItemState & CDIS_DISABLED) != 0)
+ {
+ RECT rcShadow = rcImage;
+ ::OffsetRect(&rcShadow, 1, 1);
+ CPen pen1;
+ pen1.CreatePen(PS_SOLID, 0, ::GetSysColor(COLOR_3DHILIGHT));
+ pT->DrawButtonImage(dc, rcShadow, pen1);
+ CPen pen2;
+ pen2.CreatePen(PS_SOLID, 0, ::GetSysColor(COLOR_3DSHADOW));
+ pT->DrawButtonImage(dc, rcImage, pen2);
+ }
+ else
+ {
+ if((lpNMCustomDraw->uItemState & CDIS_SELECTED) != 0)
+ ::OffsetRect(&rcImage, 1, 1);
+ CPen pen;
+ pen.CreatePen(PS_SOLID, 0, ::GetSysColor(COLOR_BTNTEXT));
+ pT->DrawButtonImage(dc, rcImage, pen);
+ }
+
+ return CDRF_DODEFAULT; // continue with the default item painting
+ }
+
+// Implementation - overrideable methods
+ void UpdateLayout(int cxWidth, int cyHeight)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ RECT rect = { 0 };
+
+ if(IsVertical())
+ {
+ ::SetRect(&rect, 0, 0, m_cxyHeader, cyHeight);
+ if(m_tb.m_hWnd != NULL)
+ m_tb.SetWindowPos(NULL, m_cxyBorder, m_cxyBorder + m_cxyBtnOffset, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
+
+ if(m_wndClient.m_hWnd != NULL)
+ m_wndClient.SetWindowPos(NULL, m_cxyHeader, 0, cxWidth - m_cxyHeader, cyHeight, SWP_NOZORDER);
+ else
+ rect.right = cxWidth;
+ }
+ else
+ {
+ ::SetRect(&rect, 0, 0, cxWidth, m_cxyHeader);
+ if(m_tb.m_hWnd != NULL)
+ m_tb.SetWindowPos(NULL, rect.right - m_cxToolBar, m_cxyBorder + m_cxyBtnOffset, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
+
+ if(m_wndClient.m_hWnd != NULL)
+ m_wndClient.SetWindowPos(NULL, 0, m_cxyHeader, cxWidth, cyHeight - m_cxyHeader, SWP_NOZORDER);
+ else
+ rect.bottom = cyHeight;
+ }
+
+ InvalidateRect(&rect);
+ }
+
+ void CreateCloseButton()
+ {
+ ATLASSERT(m_tb.m_hWnd == NULL);
+ // create toolbar for the "x" button
+ m_tb.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | CCS_NODIVIDER | CCS_NORESIZE | CCS_NOPARENTALIGN | CCS_NOMOVEY | TBSTYLE_TOOLTIPS | TBSTYLE_FLAT, 0);
+ ATLASSERT(m_tb.IsWindow());
+
+ if(m_tb.m_hWnd != NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+
+ m_tb.SetButtonStructSize();
+
+ TBBUTTON tbbtn = { 0 };
+ tbbtn.idCommand = pT->m_nCloseBtnID;
+ tbbtn.fsState = TBSTATE_ENABLED;
+ tbbtn.fsStyle = TBSTYLE_BUTTON;
+ m_tb.AddButtons(1, &tbbtn);
+
+ m_tb.SetBitmapSize(m_cxImageTB, m_cyImageTB);
+ m_tb.SetButtonSize(m_cxImageTB + m_cxyBtnAddTB, m_cyImageTB + m_cxyBtnAddTB);
+
+ if(IsVertical())
+ m_tb.SetWindowPos(NULL, m_cxyBorder + m_cxyBtnOffset, m_cxyBorder + m_cxyBtnOffset, m_cxImageTB + m_cxyBtnAddTB, m_cyImageTB + m_cxyBtnAddTB, SWP_NOZORDER | SWP_NOACTIVATE);
+ else
+ m_tb.SetWindowPos(NULL, 0, 0, m_cxImageTB + m_cxyBtnAddTB, m_cyImageTB + m_cxyBtnAddTB, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
+ }
+ }
+
+ void DestroyCloseButton()
+ {
+ if(m_tb.m_hWnd != NULL)
+ m_tb.DestroyWindow();
+ }
+
+ void CalcSize()
+ {
+ T* pT = static_cast<T*>(this);
+ CFontHandle font = pT->GetTitleFont();
+ if(font.IsNull())
+ font = (HFONT)::GetStockObject(SYSTEM_FONT);
+ LOGFONT lf = { 0 };
+ font.GetLogFont(lf);
+ if(IsVertical())
+ {
+ m_cxyHeader = m_cxImageTB + m_cxyBtnAddTB + m_cxyBorder;
+ }
+ else
+ {
+ int cyFont = abs(lf.lfHeight) + m_cxyBorder + 2 * m_cxyTextOffset;
+ int cyBtn = m_cyImageTB + m_cxyBtnAddTB + m_cxyBorder + 2 * m_cxyBtnOffset;
+ m_cxyHeader = max(cyFont, cyBtn);
+ }
+ }
+
+ HFONT GetTitleFont() const
+ {
+ return m_hFont;
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetToolTipText(LPNMHDR /*lpnmh*/)
+ {
+ return FALSE;
+ }
+#endif // !_WIN32_WCE
+
+ void DrawPaneTitle(CDCHandle dc)
+ {
+ RECT rect = { 0 };
+ GetClientRect(&rect);
+
+ UINT uBorder = BF_LEFT | BF_TOP | BF_ADJUST;
+ if(IsVertical())
+ {
+ rect.right = rect.left + m_cxyHeader;
+ uBorder |= BF_BOTTOM;
+ }
+ else
+ {
+ rect.bottom = rect.top + m_cxyHeader;
+ uBorder |= BF_RIGHT;
+ }
+
+ if((m_dwExtendedStyle & PANECNT_NOBORDER) == 0)
+ {
+ if((m_dwExtendedStyle & PANECNT_FLATBORDER) != 0)
+ uBorder |= BF_FLAT;
+ dc.DrawEdge(&rect, EDGE_ETCHED, uBorder);
+ }
+ dc.FillRect(&rect, COLOR_3DFACE);
+
+ // draw title text
+ dc.SetTextColor(::GetSysColor(COLOR_WINDOWTEXT));
+ dc.SetBkMode(TRANSPARENT);
+ T* pT = static_cast<T*>(this);
+ HFONT hFontOld = dc.SelectFont(pT->GetTitleFont());
+#ifdef _WIN32_WCE
+ const UINT DT_END_ELLIPSIS = 0;
+#endif // _WIN32_WCE
+
+ if(IsVertical())
+ {
+ rect.top += m_cxyTextOffset;
+ rect.bottom -= m_cxyTextOffset;
+ if(m_tb.m_hWnd != NULL)
+ rect.top += m_cxToolBar;;
+
+ RECT rcCalc = { rect.left, rect.bottom, rect.right, rect.top };
+ int cxFont = dc.DrawText(m_szTitle, -1, &rcCalc, DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS | DT_CALCRECT);
+ RECT rcText = { 0 };
+ rcText.left = (rect.right - rect.left - cxFont) / 2;
+ rcText.right = rcText.left + (rect.bottom - rect.top);
+ rcText.top = rect.bottom;
+ rcText.bottom = rect.top;
+ dc.DrawText(m_szTitle, -1, &rcText, DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS);
+ }
+ else
+ {
+ rect.left += m_cxyTextOffset;
+ rect.right -= m_cxyTextOffset;
+ if(m_tb.m_hWnd != NULL)
+ rect.right -= m_cxToolBar;;
+
+ dc.DrawText(m_szTitle, -1, &rect, DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS);
+ }
+
+ dc.SelectFont(hFontOld);
+ }
+
+ // called only if pane is empty
+ void DrawPane(CDCHandle dc)
+ {
+ RECT rect = { 0 };
+ GetClientRect(&rect);
+ if(IsVertical())
+ rect.left += m_cxyHeader;
+ else
+ rect.top += m_cxyHeader;
+ if((GetExStyle() & WS_EX_CLIENTEDGE) == 0)
+ dc.DrawEdge(&rect, EDGE_SUNKEN, BF_RECT | BF_ADJUST);
+ dc.FillRect(&rect, COLOR_APPWORKSPACE);
+ }
+
+ // drawing helper - draws "x" button image
+ void DrawButtonImage(CDCHandle dc, RECT& rcImage, HPEN hPen)
+ {
+#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
+ HPEN hPenOld = dc.SelectPen(hPen);
+
+ dc.MoveTo(rcImage.left, rcImage.top);
+ dc.LineTo(rcImage.right, rcImage.bottom);
+ dc.MoveTo(rcImage.left + 1, rcImage.top);
+ dc.LineTo(rcImage.right + 1, rcImage.bottom);
+
+ dc.MoveTo(rcImage.left, rcImage.bottom - 1);
+ dc.LineTo(rcImage.right, rcImage.top - 1);
+ dc.MoveTo(rcImage.left + 1, rcImage.bottom - 1);
+ dc.LineTo(rcImage.right + 1, rcImage.top - 1);
+
+ dc.SelectPen(hPenOld);
+#else // (_WIN32_WCE < 400)
+ rcImage;
+ hPen;
+ // no support for the "x" button image
+#endif // (_WIN32_WCE < 400)
+ }
+
+ bool IsVertical() const
+ {
+ return ((m_dwExtendedStyle & PANECNT_VERTICAL) != 0);
+ }
+};
+
+class CPaneContainer : public CPaneContainerImpl<CPaneContainer>
+{
+public:
+ DECLARE_WND_CLASS_EX(_T("WTL_PaneContainer"), 0, -1)
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CSortListViewCtrl - implements sorting for a listview control
+
+// sort listview extended styles
+#define SORTLV_USESHELLBITMAPS 0x00000001
+
+// Notification sent to parent when sort column is changed by user clicking header.
+#define SLVN_SORTCHANGED LVN_LAST
+
+// A LPNMSORTLISTVIEW is sent with the SLVN_SORTCHANGED notification
+typedef struct tagNMSORTLISTVIEW
+{
+ NMHDR hdr;
+ int iNewSortColumn;
+ int iOldSortColumn;
+} NMSORTLISTVIEW, *LPNMSORTLISTVIEW;
+
+// Column sort types. Can be set on a per-column basis with the SetColumnSortType method.
+enum
+{
+ LVCOLSORT_NONE,
+ LVCOLSORT_TEXT, // default
+ LVCOLSORT_TEXTNOCASE,
+ LVCOLSORT_LONG,
+ LVCOLSORT_DOUBLE,
+ LVCOLSORT_DECIMAL,
+ LVCOLSORT_DATETIME,
+ LVCOLSORT_DATE,
+ LVCOLSORT_TIME,
+ LVCOLSORT_CUSTOM,
+ LVCOLSORT_LAST = LVCOLSORT_CUSTOM
+};
+
+
+template <class T>
+class CSortListViewImpl
+{
+public:
+ enum
+ {
+ m_cchCmpTextMax = 32, // overrideable
+ m_cxSortImage = 16,
+ m_cySortImage = 15,
+ m_cxSortArrow = 11,
+ m_cySortArrow = 6,
+ m_iSortUp = 0, // index of sort bitmaps
+ m_iSortDown = 1,
+ m_nShellSortUpID = 133
+ };
+
+ // passed to LVCompare functions as lParam1 and lParam2
+ struct LVCompareParam
+ {
+ int iItem;
+ DWORD_PTR dwItemData;
+ union
+ {
+ long lValue;
+ double dblValue;
+ DECIMAL decValue;
+ LPCTSTR pszValue;
+ };
+ };
+
+ // passed to LVCompare functions as the lParamSort parameter
+ struct LVSortInfo
+ {
+ T* pT;
+ int iSortCol;
+ bool bDescending;
+ };
+
+ bool m_bSortDescending;
+ bool m_bCommCtrl6;
+ int m_iSortColumn;
+ CBitmap m_bmSort[2];
+ int m_fmtOldSortCol;
+ HBITMAP m_hbmOldSortCol;
+ DWORD m_dwSortLVExtendedStyle;
+ ATL::CSimpleArray<WORD> m_arrColSortType;
+ bool m_bUseWaitCursor;
+
+ CSortListViewImpl() :
+ m_bSortDescending(false),
+ m_bCommCtrl6(false),
+ m_iSortColumn(-1),
+ m_fmtOldSortCol(0),
+ m_hbmOldSortCol(NULL),
+ m_dwSortLVExtendedStyle(SORTLV_USESHELLBITMAPS),
+ m_bUseWaitCursor(true)
+ {
+#ifndef _WIN32_WCE
+ DWORD dwMajor = 0;
+ DWORD dwMinor = 0;
+ HRESULT hRet = ATL::AtlGetCommCtrlVersion(&dwMajor, &dwMinor);
+ m_bCommCtrl6 = SUCCEEDED(hRet) && dwMajor >= 6;
+#endif // !_WIN32_WCE
+ }
+
+// Attributes
+ void SetSortColumn(int iCol)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ CHeaderCtrl header = pT->GetHeader();
+ ATLASSERT(header.m_hWnd != NULL);
+ ATLASSERT(iCol >= -1 && iCol < m_arrColSortType.GetSize());
+
+ int iOldSortCol = m_iSortColumn;
+ m_iSortColumn = iCol;
+ if(m_bCommCtrl6)
+ {
+#ifndef HDF_SORTUP
+ const int HDF_SORTUP = 0x0400;
+#endif // HDF_SORTUP
+#ifndef HDF_SORTDOWN
+ const int HDF_SORTDOWN = 0x0200;
+#endif // HDF_SORTDOWN
+ const int nMask = HDF_SORTUP | HDF_SORTDOWN;
+ HDITEM hditem = { HDI_FORMAT };
+ if(iOldSortCol != iCol && iOldSortCol >= 0 && header.GetItem(iOldSortCol, &hditem))
+ {
+ hditem.fmt &= ~nMask;
+ header.SetItem(iOldSortCol, &hditem);
+ }
+ if(iCol >= 0 && header.GetItem(iCol, &hditem))
+ {
+ hditem.fmt &= ~nMask;
+ hditem.fmt |= m_bSortDescending ? HDF_SORTDOWN : HDF_SORTUP;
+ header.SetItem(iCol, &hditem);
+ }
+ return;
+ }
+
+ if(m_bmSort[m_iSortUp].IsNull())
+ pT->CreateSortBitmaps();
+
+ // restore previous sort column's bitmap, if any, and format
+ HDITEM hditem = { HDI_BITMAP | HDI_FORMAT };
+ if(iOldSortCol != iCol && iOldSortCol >= 0)
+ {
+ hditem.hbm = m_hbmOldSortCol;
+ hditem.fmt = m_fmtOldSortCol;
+ header.SetItem(iOldSortCol, &hditem);
+ }
+
+ // save new sort column's bitmap and format, and add our sort bitmap
+ if(iCol >= 0 && header.GetItem(iCol, &hditem))
+ {
+ if(iOldSortCol != iCol)
+ {
+ m_fmtOldSortCol = hditem.fmt;
+ m_hbmOldSortCol = hditem.hbm;
+ }
+ hditem.fmt &= ~HDF_IMAGE;
+ hditem.fmt |= HDF_BITMAP | HDF_BITMAP_ON_RIGHT;
+ int i = m_bSortDescending ? m_iSortDown : m_iSortUp;
+ hditem.hbm = m_bmSort[i];
+ header.SetItem(iCol, &hditem);
+ }
+ }
+
+ int GetSortColumn() const
+ {
+ return m_iSortColumn;
+ }
+
+ void SetColumnSortType(int iCol, WORD wType)
+ {
+ ATLASSERT(iCol >= 0 && iCol < m_arrColSortType.GetSize());
+ ATLASSERT(wType >= LVCOLSORT_NONE && wType <= LVCOLSORT_LAST);
+ m_arrColSortType[iCol] = wType;
+ }
+
+ WORD GetColumnSortType(int iCol) const
+ {
+ ATLASSERT((iCol >= 0) && iCol < m_arrColSortType.GetSize());
+ return m_arrColSortType[iCol];
+ }
+
+ int GetColumnCount() const
+ {
+ const T* pT = static_cast<const T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ CHeaderCtrl header = pT->GetHeader();
+ return header.m_hWnd != NULL ? header.GetItemCount() : 0;
+ }
+
+ bool IsSortDescending() const
+ {
+ return m_bSortDescending;
+ }
+
+ DWORD GetSortListViewExtendedStyle() const
+ {
+ return m_dwSortLVExtendedStyle;
+ }
+
+ DWORD SetSortListViewExtendedStyle(DWORD dwExtendedStyle, DWORD dwMask = 0)
+ {
+ DWORD dwPrevStyle = m_dwSortLVExtendedStyle;
+ if(dwMask == 0)
+ m_dwSortLVExtendedStyle = dwExtendedStyle;
+ else
+ m_dwSortLVExtendedStyle = (m_dwSortLVExtendedStyle & ~dwMask) | (dwExtendedStyle & dwMask);
+ return dwPrevStyle;
+ }
+
+// Operations
+ bool DoSortItems(int iCol, bool bDescending = false)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ ATLASSERT(iCol >= 0 && iCol < m_arrColSortType.GetSize());
+
+ WORD wType = m_arrColSortType[iCol];
+ if(wType == LVCOLSORT_NONE)
+ return false;
+
+ int nCount = pT->GetItemCount();
+ if(nCount < 2)
+ {
+ m_bSortDescending = bDescending;
+ SetSortColumn(iCol);
+ return true;
+ }
+
+ CWaitCursor waitCursor(false);
+ if(m_bUseWaitCursor)
+ waitCursor.Set();
+
+ LVCompareParam* pParam = NULL;
+ ATLTRY(pParam = new LVCompareParam[nCount]);
+ PFNLVCOMPARE pFunc = NULL;
+ TCHAR pszTemp[pT->m_cchCmpTextMax];
+ bool bStrValue = false;
+
+ switch(wType)
+ {
+ case LVCOLSORT_TEXT:
+ pFunc = (PFNLVCOMPARE)pT->LVCompareText;
+ case LVCOLSORT_TEXTNOCASE:
+ if(pFunc == NULL)
+ pFunc = (PFNLVCOMPARE)pT->LVCompareTextNoCase;
+ case LVCOLSORT_CUSTOM:
+ {
+ if(pFunc == NULL)
+ pFunc = (PFNLVCOMPARE)pT->LVCompareCustom;
+
+ for(int i = 0; i < nCount; i++)
+ {
+ pParam[i].iItem = i;
+ pParam[i].dwItemData = pT->GetItemData(i);
+ pParam[i].pszValue = new TCHAR[pT->m_cchCmpTextMax];
+ pT->GetItemText(i, iCol, (LPTSTR)pParam[i].pszValue, pT->m_cchCmpTextMax);
+ pT->SetItemData(i, (DWORD_PTR)&pParam[i]);
+ }
+ bStrValue = true;
+ }
+ break;
+ case LVCOLSORT_LONG:
+ {
+ pFunc = (PFNLVCOMPARE)pT->LVCompareLong;
+ for(int i = 0; i < nCount; i++)
+ {
+ pParam[i].iItem = i;
+ pParam[i].dwItemData = pT->GetItemData(i);
+ pT->GetItemText(i, iCol, pszTemp, pT->m_cchCmpTextMax);
+ pParam[i].lValue = pT->StrToLong(pszTemp);
+ pT->SetItemData(i, (DWORD_PTR)&pParam[i]);
+ }
+ }
+ break;
+ case LVCOLSORT_DOUBLE:
+ {
+ pFunc = (PFNLVCOMPARE)pT->LVCompareDouble;
+ for(int i = 0; i < nCount; i++)
+ {
+ pParam[i].iItem = i;
+ pParam[i].dwItemData = pT->GetItemData(i);
+ pT->GetItemText(i, iCol, pszTemp, pT->m_cchCmpTextMax);
+ pParam[i].dblValue = pT->StrToDouble(pszTemp);
+ pT->SetItemData(i, (DWORD_PTR)&pParam[i]);
+ }
+ }
+ break;
+ case LVCOLSORT_DECIMAL:
+ {
+ pFunc = (PFNLVCOMPARE)pT->LVCompareDecimal;
+ for(int i = 0; i < nCount; i++)
+ {
+ pParam[i].iItem = i;
+ pParam[i].dwItemData = pT->GetItemData(i);
+ pT->GetItemText(i, iCol, pszTemp, pT->m_cchCmpTextMax);
+ pT->StrToDecimal(pszTemp, &pParam[i].decValue);
+ pT->SetItemData(i, (DWORD_PTR)&pParam[i]);
+ }
+ }
+ break;
+ case LVCOLSORT_DATETIME:
+ case LVCOLSORT_DATE:
+ case LVCOLSORT_TIME:
+ {
+ pFunc = (PFNLVCOMPARE)pT->LVCompareDouble;
+ DWORD dwFlags = LOCALE_NOUSEROVERRIDE;
+ if(wType == LVCOLSORT_DATE)
+ dwFlags |= VAR_DATEVALUEONLY;
+ else if(wType == LVCOLSORT_TIME)
+ dwFlags |= VAR_TIMEVALUEONLY;
+ for(int i = 0; i < nCount; i++)
+ {
+ pParam[i].iItem = i;
+ pParam[i].dwItemData = pT->GetItemData(i);
+ pT->GetItemText(i, iCol, pszTemp, pT->m_cchCmpTextMax);
+ pParam[i].dblValue = pT->DateStrToDouble(pszTemp, dwFlags);
+ pT->SetItemData(i, (DWORD_PTR)&pParam[i]);
+ }
+ }
+ break;
+ default:
+ ATLTRACE2(atlTraceUI, 0, _T("Unknown value for sort type in CSortListViewImpl::DoSortItems()\n"));
+ break;
+ } // switch(wType)
+
+ ATLASSERT(pFunc != NULL);
+ LVSortInfo lvsi = { pT, iCol, bDescending };
+ bool bRet = ((BOOL)pT->DefWindowProc(LVM_SORTITEMS, (WPARAM)&lvsi, (LPARAM)pFunc) != FALSE);
+ for(int i = 0; i < nCount; i++)
+ {
+ DWORD_PTR dwItemData = pT->GetItemData(i);
+ LVCompareParam* p = (LVCompareParam*)dwItemData;
+ ATLASSERT(p != NULL);
+ if(bStrValue)
+ delete [] (TCHAR*)p->pszValue;
+ pT->SetItemData(i, p->dwItemData);
+ }
+ delete [] pParam;
+
+ if(bRet)
+ {
+ m_bSortDescending = bDescending;
+ SetSortColumn(iCol);
+ }
+
+ if(m_bUseWaitCursor)
+ waitCursor.Restore();
+
+ return bRet;
+ }
+
+ void CreateSortBitmaps()
+ {
+ if((m_dwSortLVExtendedStyle & SORTLV_USESHELLBITMAPS) != 0)
+ {
+ bool bFree = false;
+ LPCTSTR pszModule = _T("shell32.dll");
+ HINSTANCE hShell = ::GetModuleHandle(pszModule);
+
+ if (hShell == NULL)
+ {
+ hShell = ::LoadLibrary(pszModule);
+ bFree = true;
+ }
+
+ if (hShell != NULL)
+ {
+ bool bSuccess = true;
+ for(int i = m_iSortUp; i <= m_iSortDown; i++)
+ {
+ if(!m_bmSort[i].IsNull())
+ m_bmSort[i].DeleteObject();
+ m_bmSort[i] = (HBITMAP)::LoadImage(hShell, MAKEINTRESOURCE(m_nShellSortUpID + i),
+#ifndef _WIN32_WCE
+ IMAGE_BITMAP, 0, 0, LR_LOADMAP3DCOLORS);
+#else // CE specific
+ IMAGE_BITMAP, 0, 0, 0);
+#endif // _WIN32_WCE
+ if(m_bmSort[i].IsNull())
+ {
+ bSuccess = false;
+ break;
+ }
+ }
+ if(bFree)
+ ::FreeLibrary(hShell);
+ if(bSuccess)
+ return;
+ }
+ }
+
+ T* pT = static_cast<T*>(this);
+ for(int i = m_iSortUp; i <= m_iSortDown; i++)
+ {
+ if(!m_bmSort[i].IsNull())
+ m_bmSort[i].DeleteObject();
+
+ CDC dcMem;
+ CClientDC dc(::GetDesktopWindow());
+ dcMem.CreateCompatibleDC(dc.m_hDC);
+ m_bmSort[i].CreateCompatibleBitmap(dc.m_hDC, m_cxSortImage, m_cySortImage);
+ HBITMAP hbmOld = dcMem.SelectBitmap(m_bmSort[i]);
+ RECT rc = {0,0,m_cxSortImage, m_cySortImage};
+ pT->DrawSortBitmap(dcMem.m_hDC, i, &rc);
+ dcMem.SelectBitmap(hbmOld);
+ dcMem.DeleteDC();
+ }
+ }
+
+ void NotifyParentSortChanged(int iNewSortCol, int iOldSortCol)
+ {
+ T* pT = static_cast<T*>(this);
+ int nID = pT->GetDlgCtrlID();
+ NMSORTLISTVIEW nm = { { pT->m_hWnd, nID, SLVN_SORTCHANGED }, iNewSortCol, iOldSortCol };
+ ::SendMessage(pT->GetParent(), WM_NOTIFY, (WPARAM)nID, (LPARAM)&nm);
+ }
+
+// Overrideables
+ int CompareItemsCustom(LVCompareParam* /*pItem1*/, LVCompareParam* /*pItem2*/, int /*iSortCol*/)
+ {
+ // pItem1 and pItem2 contain valid iItem, dwItemData, and pszValue members.
+ // If item1 > item2 return 1, if item1 < item2 return -1, else return 0.
+ return 0;
+ }
+
+ void DrawSortBitmap(CDCHandle dc, int iBitmap, LPRECT prc)
+ {
+ dc.FillRect(prc, ::GetSysColorBrush(COLOR_BTNFACE));
+ HBRUSH hbrOld = dc.SelectBrush(::GetSysColorBrush(COLOR_BTNSHADOW));
+ CPen pen;
+ pen.CreatePen(PS_SOLID, 0, ::GetSysColor(COLOR_BTNSHADOW));
+ HPEN hpenOld = dc.SelectPen(pen);
+ POINT ptOrg = { (m_cxSortImage - m_cxSortArrow) / 2, (m_cySortImage - m_cySortArrow) / 2 };
+ if(iBitmap == m_iSortUp)
+ {
+ POINT pts[3] =
+ {
+ { ptOrg.x + m_cxSortArrow / 2, ptOrg.y },
+ { ptOrg.x, ptOrg.y + m_cySortArrow - 1 },
+ { ptOrg.x + m_cxSortArrow - 1, ptOrg.y + m_cySortArrow - 1 }
+ };
+ dc.Polygon(pts, 3);
+ }
+ else
+ {
+ POINT pts[3] =
+ {
+ { ptOrg.x, ptOrg.y },
+ { ptOrg.x + m_cxSortArrow / 2, ptOrg.y + m_cySortArrow - 1 },
+ { ptOrg.x + m_cxSortArrow - 1, ptOrg.y }
+ };
+ dc.Polygon(pts, 3);
+ }
+ dc.SelectBrush(hbrOld);
+ dc.SelectPen(hpenOld);
+ }
+
+ double DateStrToDouble(LPCTSTR lpstr, DWORD dwFlags)
+ {
+ ATLASSERT(lpstr != NULL);
+ if(lpstr == NULL || lpstr[0] == _T('\0'))
+ return 0;
+
+ USES_CONVERSION;
+ HRESULT hRet = E_FAIL;
+ DATE dRet = 0;
+ if (FAILED(hRet = ::VarDateFromStr((LPOLESTR)T2COLE(lpstr), LANG_USER_DEFAULT, dwFlags, &dRet)))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("VarDateFromStr failed with result of 0x%8.8X\n"), hRet);
+ dRet = 0;
+ }
+ return dRet;
+ }
+
+ long StrToLong(LPCTSTR lpstr)
+ {
+ ATLASSERT(lpstr != NULL);
+ if(lpstr == NULL || lpstr[0] == _T('\0'))
+ return 0;
+
+ USES_CONVERSION;
+ HRESULT hRet = E_FAIL;
+ long lRet = 0;
+ if (FAILED(hRet = ::VarI4FromStr((LPOLESTR)T2COLE(lpstr), LANG_USER_DEFAULT, LOCALE_NOUSEROVERRIDE, &lRet)))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("VarI4FromStr failed with result of 0x%8.8X\n"), hRet);
+ lRet = 0;
+ }
+ return lRet;
+ }
+
+ double StrToDouble(LPCTSTR lpstr)
+ {
+ ATLASSERT(lpstr != NULL);
+ if(lpstr == NULL || lpstr[0] == _T('\0'))
+ return 0;
+
+ USES_CONVERSION;
+ HRESULT hRet = E_FAIL;
+ double dblRet = 0;
+ if (FAILED(hRet = ::VarR8FromStr((LPOLESTR)T2COLE(lpstr), LANG_USER_DEFAULT, LOCALE_NOUSEROVERRIDE, &dblRet)))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("VarR8FromStr failed with result of 0x%8.8X\n"), hRet);
+ dblRet = 0;
+ }
+ return dblRet;
+ }
+
+ bool StrToDecimal(LPCTSTR lpstr, DECIMAL* pDecimal)
+ {
+ ATLASSERT(lpstr != NULL);
+ ATLASSERT(pDecimal != NULL);
+ if(lpstr == NULL || pDecimal == NULL)
+ return false;
+
+ USES_CONVERSION;
+ HRESULT hRet = E_FAIL;
+ if (FAILED(hRet = ::VarDecFromStr((LPOLESTR)T2COLE(lpstr), LANG_USER_DEFAULT, LOCALE_NOUSEROVERRIDE, pDecimal)))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("VarDecFromStr failed with result of 0x%8.8X\n"), hRet);
+ pDecimal->Lo64 = 0;
+ pDecimal->Hi32 = 0;
+ pDecimal->signscale = 0;
+ return false;
+ }
+ return true;
+ }
+
+// Overrideable PFNLVCOMPARE functions
+ static int CALLBACK LVCompareText(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
+ {
+ ATLASSERT(lParam1 != NULL && lParam2 != NULL && lParamSort != NULL);
+
+ LVCompareParam* pParam1 = (LVCompareParam*)lParam1;
+ LVCompareParam* pParam2 = (LVCompareParam*)lParam2;
+ LVSortInfo* pInfo = (LVSortInfo*)lParamSort;
+
+ int nRet = lstrcmp(pParam1->pszValue, pParam2->pszValue);
+ return pInfo->bDescending ? -nRet : nRet;
+ }
+
+ static int CALLBACK LVCompareTextNoCase(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
+ {
+ ATLASSERT(lParam1 != NULL && lParam2 != NULL && lParamSort != NULL);
+
+ LVCompareParam* pParam1 = (LVCompareParam*)lParam1;
+ LVCompareParam* pParam2 = (LVCompareParam*)lParam2;
+ LVSortInfo* pInfo = (LVSortInfo*)lParamSort;
+
+ int nRet = lstrcmpi(pParam1->pszValue, pParam2->pszValue);
+ return pInfo->bDescending ? -nRet : nRet;
+ }
+
+ static int CALLBACK LVCompareLong(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
+ {
+ ATLASSERT(lParam1 != NULL && lParam2 != NULL && lParamSort != NULL);
+
+ LVCompareParam* pParam1 = (LVCompareParam*)lParam1;
+ LVCompareParam* pParam2 = (LVCompareParam*)lParam2;
+ LVSortInfo* pInfo = (LVSortInfo*)lParamSort;
+
+ int nRet = 0;
+ if(pParam1->lValue > pParam2->lValue)
+ nRet = 1;
+ else if(pParam1->lValue < pParam2->lValue)
+ nRet = -1;
+ return pInfo->bDescending ? -nRet : nRet;
+ }
+
+ static int CALLBACK LVCompareDouble(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
+ {
+ ATLASSERT(lParam1 != NULL && lParam2 != NULL && lParamSort != NULL);
+
+ LVCompareParam* pParam1 = (LVCompareParam*)lParam1;
+ LVCompareParam* pParam2 = (LVCompareParam*)lParam2;
+ LVSortInfo* pInfo = (LVSortInfo*)lParamSort;
+
+ int nRet = 0;
+ if(pParam1->dblValue > pParam2->dblValue)
+ nRet = 1;
+ else if(pParam1->dblValue < pParam2->dblValue)
+ nRet = -1;
+ return pInfo->bDescending ? -nRet : nRet;
+ }
+
+ static int CALLBACK LVCompareCustom(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
+ {
+ ATLASSERT(lParam1 != NULL && lParam2 != NULL && lParamSort != NULL);
+
+ LVCompareParam* pParam1 = (LVCompareParam*)lParam1;
+ LVCompareParam* pParam2 = (LVCompareParam*)lParam2;
+ LVSortInfo* pInfo = (LVSortInfo*)lParamSort;
+
+ int nRet = pInfo->pT->CompareItemsCustom(pParam1, pParam2, pInfo->iSortCol);
+ return pInfo->bDescending ? -nRet : nRet;
+ }
+
+#ifndef _WIN32_WCE
+ static int CALLBACK LVCompareDecimal(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
+ {
+ ATLASSERT(lParam1 != NULL && lParam2 != NULL && lParamSort != NULL);
+
+ LVCompareParam* pParam1 = (LVCompareParam*)lParam1;
+ LVCompareParam* pParam2 = (LVCompareParam*)lParam2;
+ LVSortInfo* pInfo = (LVSortInfo*)lParamSort;
+
+ int nRet = (int)::VarDecCmp(&pParam1->decValue, &pParam2->decValue);
+ nRet--;
+ return pInfo->bDescending ? -nRet : nRet;
+ }
+#else
+ // Compare mantissas, ignore sign and scale
+ static int CompareMantissas(const DECIMAL& decLeft, const DECIMAL& decRight)
+ {
+ if (decLeft.Hi32 < decRight.Hi32)
+ {
+ return -1;
+ }
+ if (decLeft.Hi32 > decRight.Hi32)
+ {
+ return 1;
+ }
+ // Here, decLeft.Hi32 == decRight.Hi32
+ if (decLeft.Lo64 < decRight.Lo64)
+ {
+ return -1;
+ }
+ if (decLeft.Lo64 > decRight.Lo64)
+ {
+ return 1;
+ }
+ return 0;
+ }
+
+ // return values: VARCMP_LT, VARCMP_EQ, VARCMP_GT, VARCMP_NULL
+ static HRESULT VarDecCmp(const DECIMAL* pdecLeft, const DECIMAL* pdecRight)
+ {
+ static const ULONG powersOfTen[] =
+ {
+ 10ul,
+ 100ul,
+ 1000ul,
+ 10000ul,
+ 100000ul,
+ 1000000ul,
+ 10000000ul,
+ 100000000ul,
+ 1000000000ul
+ };
+ static const int largestPower = sizeof(powersOfTen) / sizeof(powersOfTen[0]);
+ if (!pdecLeft || !pdecRight)
+ {
+ return VARCMP_NULL;
+ }
+
+ // Degenerate case - at least one comparand is of the form
+ // [+-]0*10^N (denormalized zero)
+ bool bLeftZero = (!pdecLeft->Lo64 && !pdecLeft->Hi32);
+ bool bRightZero = (!pdecRight->Lo64 && !pdecRight->Hi32);
+ if (bLeftZero && bRightZero)
+ {
+ return VARCMP_EQ;
+ }
+ bool bLeftNeg = ((pdecLeft->sign & DECIMAL_NEG) != 0);
+ bool bRightNeg = ((pdecRight->sign & DECIMAL_NEG) != 0);
+ if (bLeftZero)
+ {
+ return (bRightNeg ? VARCMP_GT : VARCMP_LT);
+ }
+ // This also covers the case where the comparands have different signs
+ if (bRightZero || bLeftNeg != bRightNeg)
+ {
+ return (bLeftNeg ? VARCMP_LT : VARCMP_GT);
+ }
+
+ // Here both comparands have the same sign and need to be compared
+ // on mantissa and scale. The result is obvious when
+ // 1. Scales are equal (then compare mantissas)
+ // 2. A number with smaller scale is also the one with larger mantissa
+ // (then this number is obviously larger)
+ // In the remaining case, we would multiply the number with smaller
+ // scale by 10 and simultaneously increment its scale (which amounts to
+ // adding trailing zeros after decimal point), until the numbers fall under
+ // one of the two cases above
+ DECIMAL temp;
+ bool bInvert = bLeftNeg; // the final result needs to be inverted
+ if (pdecLeft->scale < pdecRight->scale)
+ {
+ temp = *pdecLeft;
+ }
+ else
+ {
+ temp = *pdecRight;
+ pdecRight = pdecLeft;
+ bInvert = !bInvert;
+ }
+
+ // Now temp is the number with smaller (or equal) scale, and
+ // we can modify it freely without touching original parameters
+ int comp;
+ while ((comp = CompareMantissas(temp, *pdecRight)) < 0 &&
+ temp.scale < pdecRight->scale)
+ {
+ // Multiply by an appropriate power of 10
+ int scaleDiff = pdecRight->scale - temp.scale;
+ if (scaleDiff > largestPower)
+ {
+ // Keep the multiplier representable in 32bit
+ scaleDiff = largestPower;
+ }
+ DWORDLONG power = powersOfTen[scaleDiff - 1];
+ // Multiply temp's mantissa by power
+ DWORDLONG product = temp.Lo32 * power;
+ ULONG carry = static_cast<ULONG>(product >> 32);
+ temp.Lo32 = static_cast<ULONG>(product);
+ product = temp.Mid32 * power + carry;
+ carry = static_cast<ULONG>(product >> 32);
+ temp.Mid32 = static_cast<ULONG>(product);
+ product = temp.Hi32 * power + carry;
+ if (static_cast<ULONG>(product >> 32))
+ {
+ // Multiplication overflowed - pdecLeft is clearly larger
+ break;
+ }
+ temp.Hi32 = static_cast<ULONG>(product);
+ temp.scale = (BYTE)(temp.scale + scaleDiff);
+ }
+ if (temp.scale < pdecRight->scale)
+ {
+ comp = 1;
+ }
+ if (bInvert)
+ {
+ comp = -comp;
+ }
+ return (comp > 0 ? VARCMP_GT : comp < 0 ? VARCMP_LT : VARCMP_EQ);
+ }
+
+ static int CALLBACK LVCompareDecimal(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
+ {
+ ATLASSERT(lParam1 != NULL && lParam2 != NULL && lParamSort != NULL);
+
+ LVCompareParam* pParam1 = (LVCompareParam*)lParam1;
+ LVCompareParam* pParam2 = (LVCompareParam*)lParam2;
+ LVSortInfo* pInfo = (LVSortInfo*)lParamSort;
+
+ int nRet = (int)VarDecCmp(&pParam1->decValue, &pParam2->decValue);
+ nRet--;
+ return pInfo->bDescending ? -nRet : nRet;
+ }
+#endif // !_WIN32_WCE
+
+ BEGIN_MSG_MAP(CSortListViewImpl)
+ MESSAGE_HANDLER(LVM_INSERTCOLUMN, OnInsertColumn)
+ MESSAGE_HANDLER(LVM_DELETECOLUMN, OnDeleteColumn)
+ NOTIFY_CODE_HANDLER(HDN_ITEMCLICKA, OnHeaderItemClick)
+ NOTIFY_CODE_HANDLER(HDN_ITEMCLICKW, OnHeaderItemClick)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
+ END_MSG_MAP()
+
+ LRESULT OnInsertColumn(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ LRESULT lRet = pT->DefWindowProc(uMsg, wParam, lParam);
+ if(lRet == -1)
+ return -1;
+
+ WORD wType = 0;
+ m_arrColSortType.Add(wType);
+ int nCount = m_arrColSortType.GetSize();
+ ATLASSERT(nCount == GetColumnCount());
+
+ for(int i = nCount - 1; i > lRet; i--)
+ m_arrColSortType[i] = m_arrColSortType[i - 1];
+ m_arrColSortType[(int)lRet] = LVCOLSORT_TEXT;
+
+ if(lRet <= m_iSortColumn)
+ m_iSortColumn++;
+
+ return lRet;
+ }
+
+ LRESULT OnDeleteColumn(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ LRESULT lRet = pT->DefWindowProc(uMsg, wParam, lParam);
+ if(lRet == 0)
+ return 0;
+
+ int iCol = (int)wParam;
+ if(m_iSortColumn == iCol)
+ m_iSortColumn = -1;
+ else if(m_iSortColumn > iCol)
+ m_iSortColumn--;
+ m_arrColSortType.RemoveAt(iCol);
+
+ return lRet;
+ }
+
+ LRESULT OnHeaderItemClick(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ LPNMHEADER p = (LPNMHEADER)pnmh;
+ if(p->iButton == 0)
+ {
+ int iOld = m_iSortColumn;
+ bool bDescending = (m_iSortColumn == p->iItem) ? !m_bSortDescending : false;
+ if(DoSortItems(p->iItem, bDescending))
+ NotifyParentSortChanged(p->iItem, iOld);
+ }
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifndef _WIN32_WCE
+ if(wParam == SPI_SETNONCLIENTMETRICS)
+ GetSystemSettings();
+#else // CE specific
+ wParam; // avoid level 4 warning
+ GetSystemSettings();
+#endif // _WIN32_WCE
+ bHandled = FALSE;
+ return 0;
+ }
+
+ void GetSystemSettings()
+ {
+ if(!m_bCommCtrl6 && !m_bmSort[m_iSortUp].IsNull())
+ {
+ T* pT = static_cast<T*>(this);
+ pT->CreateSortBitmaps();
+ if(m_iSortColumn != -1)
+ SetSortColumn(m_iSortColumn);
+ }
+ }
+
+};
+
+
+typedef ATL::CWinTraits<WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | LVS_REPORT | LVS_SHOWSELALWAYS , WS_EX_CLIENTEDGE> CSortListViewCtrlTraits;
+
+template <class T, class TBase = CListViewCtrl, class TWinTraits = CSortListViewCtrlTraits>
+class ATL_NO_VTABLE CSortListViewCtrlImpl: public ATL::CWindowImpl<T, TBase, TWinTraits>, public CSortListViewImpl<T>
+{
+public:
+ DECLARE_WND_SUPERCLASS(NULL, TBase::GetWndClassName())
+
+ bool SortItems(int iCol, bool bDescending = false)
+ {
+ return DoSortItems(iCol, bDescending);
+ }
+
+ BEGIN_MSG_MAP(CSortListViewCtrlImpl)
+ MESSAGE_HANDLER(LVM_INSERTCOLUMN, CSortListViewImpl<T>::OnInsertColumn)
+ MESSAGE_HANDLER(LVM_DELETECOLUMN, CSortListViewImpl<T>::OnDeleteColumn)
+ NOTIFY_CODE_HANDLER(HDN_ITEMCLICKA, CSortListViewImpl<T>::OnHeaderItemClick)
+ NOTIFY_CODE_HANDLER(HDN_ITEMCLICKW, CSortListViewImpl<T>::OnHeaderItemClick)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, CSortListViewImpl<T>::OnSettingChange)
+ END_MSG_MAP()
+};
+
+class CSortListViewCtrl : public CSortListViewCtrlImpl<CSortListViewCtrl>
+{
+public:
+ DECLARE_WND_SUPERCLASS(_T("WTL_SortListViewCtrl"), GetWndClassName())
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTabView - implements tab view window
+
+// TabView Notifications
+#define TBVN_PAGEACTIVATED (0U-741)
+#define TBVN_CONTEXTMENU (0U-742)
+
+// Notification data for TBVN_CONTEXTMENU
+struct TBVCONTEXTMENUINFO
+{
+ NMHDR hdr;
+ POINT pt;
+};
+
+typedef TBVCONTEXTMENUINFO* LPTBVCONTEXTMENUINFO;
+
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CTabViewImpl : public ATL::CWindowImpl<T, TBase, TWinTraits>
+{
+public:
+ DECLARE_WND_CLASS_EX(NULL, 0, COLOR_APPWORKSPACE)
+
+// Declarations and enums
+ struct TABVIEWPAGE
+ {
+ HWND hWnd;
+ LPTSTR lpstrTitle;
+ LPVOID pData;
+ };
+
+ struct TCITEMEXTRA
+ {
+ TCITEMHEADER tciheader;
+ TABVIEWPAGE tvpage;
+
+ operator LPTCITEM() { return (LPTCITEM)this; }
+ };
+
+ enum
+ {
+ m_nTabID = 1313,
+ m_cxMoveMark = 6,
+ m_cyMoveMark = 3,
+ m_nMenuItemsMax = (ID_WINDOW_TABLAST - ID_WINDOW_TABFIRST + 1)
+ };
+
+// Data members
+ ATL::CContainedWindowT<CTabCtrl> m_tab;
+ int m_cyTabHeight;
+
+ int m_nActivePage;
+
+ int m_nInsertItem;
+ POINT m_ptStartDrag;
+
+ CMenuHandle m_menu;
+
+ int m_cchTabTextLength;
+
+ int m_nMenuItemsCount;
+
+ ATL::CWindow m_wndTitleBar;
+ LPTSTR m_lpstrTitleBarBase;
+ int m_cchTitleBarLength;
+
+ CImageList m_ilDrag;
+
+ bool m_bDestroyPageOnRemove:1;
+ bool m_bDestroyImageList:1;
+ bool m_bActivePageMenuItem:1;
+ bool m_bActiveAsDefaultMenuItem:1;
+ bool m_bEmptyMenuItem:1;
+ bool m_bWindowsMenuItem:1;
+ bool m_bNoTabDrag:1;
+ // internal
+ bool m_bTabCapture:1;
+ bool m_bTabDrag:1;
+ bool m_bInternalFont:1;
+
+// Constructor/destructor
+ CTabViewImpl() :
+ m_nActivePage(-1),
+ m_cyTabHeight(0),
+ m_tab(this, 1),
+ m_nInsertItem(-1),
+ m_cchTabTextLength(30),
+ m_nMenuItemsCount(10),
+ m_lpstrTitleBarBase(NULL),
+ m_cchTitleBarLength(100),
+ m_bDestroyPageOnRemove(true),
+ m_bDestroyImageList(true),
+ m_bActivePageMenuItem(true),
+ m_bActiveAsDefaultMenuItem(false),
+ m_bEmptyMenuItem(false),
+ m_bWindowsMenuItem(false),
+ m_bNoTabDrag(false),
+ m_bTabCapture(false),
+ m_bTabDrag(false),
+ m_bInternalFont(false)
+ {
+ m_ptStartDrag.x = 0;
+ m_ptStartDrag.y = 0;
+ }
+
+ ~CTabViewImpl()
+ {
+ delete [] m_lpstrTitleBarBase;
+ }
+
+// Message filter function - to be called from PreTranslateMessage of the main window
+ BOOL PreTranslateMessage(MSG* pMsg)
+ {
+ if(IsWindow() == FALSE)
+ return FALSE;
+
+ BOOL bRet = FALSE;
+
+ // Check for TabView built-in accelerators (Ctrl+Tab/Ctrl+Shift+Tab - next/previous page)
+ int nCount = GetPageCount();
+ if(nCount > 0)
+ {
+ bool bControl = (::GetKeyState(VK_CONTROL) < 0);
+ if((pMsg->message == WM_KEYDOWN) && (pMsg->wParam == VK_TAB) && bControl)
+ {
+ if(nCount > 1)
+ {
+ int nPage = m_nActivePage;
+ bool bShift = (::GetKeyState(VK_SHIFT) < 0);
+ if(bShift)
+ nPage = (nPage > 0) ? (nPage - 1) : (nCount - 1);
+ else
+ nPage = ((nPage >= 0) && (nPage < (nCount - 1))) ? (nPage + 1) : 0;
+
+ SetActivePage(nPage);
+ T* pT = static_cast<T*>(this);
+ pT->OnPageActivated(m_nActivePage);
+ }
+
+ bRet = TRUE;
+ }
+ }
+
+ // If we are doing drag-drop, check for Escape key that cancels it
+ if(bRet == FALSE)
+ {
+ if(m_bTabCapture && pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_ESCAPE)
+ {
+ ::ReleaseCapture();
+ bRet = TRUE;
+ }
+ }
+
+ // Pass the message to the active page
+ if(bRet == FALSE)
+ {
+ if(m_nActivePage != -1)
+ bRet = (BOOL)::SendMessage(GetPageHWND(m_nActivePage), WM_FORWARDMSG, 0, (LPARAM)pMsg);
+ }
+
+ return bRet;
+ }
+
+// Attributes
+ int GetPageCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return m_tab.GetItemCount();
+ }
+
+ int GetActivePage() const
+ {
+ return m_nActivePage;
+ }
+
+ void SetActivePage(int nPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ T* pT = static_cast<T*>(this);
+
+ SetRedraw(FALSE);
+
+ if(m_nActivePage != -1)
+ ::ShowWindow(GetPageHWND(m_nActivePage), FALSE);
+ m_nActivePage = nPage;
+ m_tab.SetCurSel(m_nActivePage);
+ ::ShowWindow(GetPageHWND(m_nActivePage), TRUE);
+
+ pT->UpdateLayout();
+
+ SetRedraw(TRUE);
+ RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
+
+ if(::GetFocus() != m_tab.m_hWnd)
+ ::SetFocus(GetPageHWND(m_nActivePage));
+
+ pT->UpdateTitleBar();
+ pT->UpdateMenu();
+ }
+
+ HIMAGELIST GetImageList() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return m_tab.GetImageList();
+ }
+
+ HIMAGELIST SetImageList(HIMAGELIST hImageList)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return m_tab.SetImageList(hImageList);
+ }
+
+ void SetWindowMenu(HMENU hMenu)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ m_menu = hMenu;
+
+ T* pT = static_cast<T*>(this);
+ pT->UpdateMenu();
+ }
+
+ void SetTitleBarWindow(HWND hWnd)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ delete [] m_lpstrTitleBarBase;
+ m_lpstrTitleBarBase = NULL;
+
+ m_wndTitleBar = hWnd;
+ if(hWnd == NULL)
+ return;
+
+ int cchLen = m_wndTitleBar.GetWindowTextLength() + 1;
+ ATLTRY(m_lpstrTitleBarBase = new TCHAR[cchLen]);
+ if(m_lpstrTitleBarBase != NULL)
+ {
+ m_wndTitleBar.GetWindowText(m_lpstrTitleBarBase, cchLen);
+ T* pT = static_cast<T*>(this);
+ pT->UpdateTitleBar();
+ }
+ }
+
+// Page attributes
+ HWND GetPageHWND(int nPage) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_PARAM;
+ m_tab.GetItem(nPage, tcix);
+
+ return tcix.tvpage.hWnd;
+ }
+
+ LPCTSTR GetPageTitle(int nPage) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_PARAM;
+ if(m_tab.GetItem(nPage, tcix) == FALSE)
+ return NULL;
+
+ return tcix.tvpage.lpstrTitle;
+ }
+
+ bool SetPageTitle(int nPage, LPCTSTR lpstrTitle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ T* pT = static_cast<T*>(this);
+
+ int cchBuff = lstrlen(lpstrTitle) + 1;
+ LPTSTR lpstrBuff = NULL;
+ ATLTRY(lpstrBuff = new TCHAR[cchBuff]);
+ if(lpstrBuff == NULL)
+ return false;
+
+ SecureHelper::strcpy_x(lpstrBuff, cchBuff, lpstrTitle);
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_PARAM;
+ if(m_tab.GetItem(nPage, tcix) == FALSE)
+ return false;
+
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrTabText = buff.Allocate(m_cchTabTextLength + 1);
+ if(lpstrTabText == NULL)
+ return false;
+
+ delete [] tcix.tvpage.lpstrTitle;
+
+ pT->ShortenTitle(lpstrTitle, lpstrTabText, m_cchTabTextLength + 1);
+
+ tcix.tciheader.mask = TCIF_TEXT | TCIF_PARAM;
+ tcix.tciheader.pszText = lpstrTabText;
+ tcix.tvpage.lpstrTitle = lpstrBuff;
+ if(m_tab.SetItem(nPage, tcix) == FALSE)
+ return false;
+
+ pT->UpdateTitleBar();
+ pT->UpdateMenu();
+
+ return true;
+ }
+
+ LPVOID GetPageData(int nPage) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_PARAM;
+ m_tab.GetItem(nPage, tcix);
+
+ return tcix.tvpage.pData;
+ }
+
+ LPVOID SetPageData(int nPage, LPVOID pData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_PARAM;
+ m_tab.GetItem(nPage, tcix);
+ LPVOID pDataOld = tcix.tvpage.pData;
+
+ tcix.tvpage.pData = pData;
+ m_tab.SetItem(nPage, tcix);
+
+ return pDataOld;
+ }
+
+ int GetPageImage(int nPage) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_IMAGE;
+ m_tab.GetItem(nPage, tcix);
+
+ return tcix.tciheader.iImage;
+ }
+
+ int SetPageImage(int nPage, int nImage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_IMAGE;
+ m_tab.GetItem(nPage, tcix);
+ int nImageOld = tcix.tciheader.iImage;
+
+ tcix.tciheader.iImage = nImage;
+ m_tab.SetItem(nPage, tcix);
+
+ return nImageOld;
+ }
+
+// Operations
+ bool AddPage(HWND hWndView, LPCTSTR lpstrTitle, int nImage = -1, LPVOID pData = NULL)
+ {
+ return InsertPage(GetPageCount(), hWndView, lpstrTitle, nImage, pData);
+ }
+
+ bool InsertPage(int nPage, HWND hWndView, LPCTSTR lpstrTitle, int nImage = -1, LPVOID pData = NULL)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(nPage == GetPageCount() || IsValidPageIndex(nPage));
+
+ T* pT = static_cast<T*>(this);
+
+ int cchBuff = lstrlen(lpstrTitle) + 1;
+ LPTSTR lpstrBuff = NULL;
+ ATLTRY(lpstrBuff = new TCHAR[cchBuff]);
+ if(lpstrBuff == NULL)
+ return false;
+
+ SecureHelper::strcpy_x(lpstrBuff, cchBuff, lpstrTitle);
+
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrTabText = buff.Allocate(m_cchTabTextLength + 1);
+ if(lpstrTabText == NULL)
+ return false;
+
+ pT->ShortenTitle(lpstrTitle, lpstrTabText, m_cchTabTextLength + 1);
+
+ SetRedraw(FALSE);
+
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_PARAM;
+ tcix.tciheader.pszText = lpstrTabText;
+ tcix.tciheader.iImage = nImage;
+ tcix.tvpage.hWnd = hWndView;
+ tcix.tvpage.lpstrTitle = lpstrBuff;
+ tcix.tvpage.pData = pData;
+ int nItem = m_tab.InsertItem(nPage, tcix);
+ if(nItem == -1)
+ {
+ delete [] lpstrBuff;
+ SetRedraw(TRUE);
+ return false;
+ }
+
+ SetActivePage(nItem);
+ pT->OnPageActivated(m_nActivePage);
+
+ if(GetPageCount() == 1)
+ pT->ShowTabControl(true);
+
+ pT->UpdateLayout();
+
+ SetRedraw(TRUE);
+ RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
+
+ return true;
+ }
+
+ void RemovePage(int nPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(IsValidPageIndex(nPage));
+
+ T* pT = static_cast<T*>(this);
+
+ SetRedraw(FALSE);
+
+ if(GetPageCount() == 1)
+ pT->ShowTabControl(false);
+
+ if(m_bDestroyPageOnRemove)
+ ::DestroyWindow(GetPageHWND(nPage));
+ else
+ ::ShowWindow(GetPageHWND(nPage), FALSE);
+ LPTSTR lpstrTitle = (LPTSTR)GetPageTitle(nPage);
+ delete [] lpstrTitle;
+
+ ATLVERIFY(m_tab.DeleteItem(nPage) != FALSE);
+
+ if(m_nActivePage == nPage)
+ {
+ m_nActivePage = -1;
+
+ if(nPage > 0)
+ {
+ SetActivePage(nPage - 1);
+ }
+ else if(GetPageCount() > 0)
+ {
+ SetActivePage(nPage);
+ }
+ else
+ {
+ SetRedraw(TRUE);
+ Invalidate();
+ UpdateWindow();
+ pT->UpdateTitleBar();
+ pT->UpdateMenu();
+ }
+ }
+ else
+ {
+ nPage = (nPage < m_nActivePage) ? (m_nActivePage - 1) : m_nActivePage;
+ m_nActivePage = -1;
+ SetActivePage(nPage);
+ }
+
+ pT->OnPageActivated(m_nActivePage);
+ }
+
+ void RemoveAllPages()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ if(GetPageCount() == 0)
+ return;
+
+ T* pT = static_cast<T*>(this);
+
+ SetRedraw(FALSE);
+
+ pT->ShowTabControl(false);
+
+ for(int i = 0; i < GetPageCount(); i++)
+ {
+ if(m_bDestroyPageOnRemove)
+ ::DestroyWindow(GetPageHWND(i));
+ else
+ ::ShowWindow(GetPageHWND(i), FALSE);
+ LPTSTR lpstrTitle = (LPTSTR)GetPageTitle(i);
+ delete [] lpstrTitle;
+ }
+ m_tab.DeleteAllItems();
+
+ m_nActivePage = -1;
+ pT->OnPageActivated(m_nActivePage);
+
+ SetRedraw(TRUE);
+ Invalidate();
+ UpdateWindow();
+
+ pT->UpdateTitleBar();
+ pT->UpdateMenu();
+ }
+
+ int PageIndexFromHwnd(HWND hWnd) const
+ {
+ int nIndex = -1;
+
+ for(int i = 0; i < GetPageCount(); i++)
+ {
+ if(GetPageHWND(i) == hWnd)
+ {
+ nIndex = i;
+ break;
+ }
+ }
+
+ return nIndex;
+ }
+
+ void BuildWindowMenu(HMENU hMenu, int nMenuItemsCount = 10, bool bEmptyMenuItem = true, bool bWindowsMenuItem = true, bool bActivePageMenuItem = true, bool bActiveAsDefaultMenuItem = false)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ CMenuHandle menu = hMenu;
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ int nFirstPos = 0;
+
+ // Find first menu item in our range
+#ifndef _WIN32_WCE
+ for(nFirstPos = 0; nFirstPos < menu.GetMenuItemCount(); nFirstPos++)
+ {
+ UINT nID = menu.GetMenuItemID(nFirstPos);
+ if((nID >= ID_WINDOW_TABFIRST && nID <= ID_WINDOW_TABLAST) || nID == ID_WINDOW_SHOWTABLIST)
+ break;
+ }
+#else // CE specific
+ for(nFirstPos = 0; ; nFirstPos++)
+ {
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_ID;
+ BOOL bRet = menu.GetMenuItemInfo(nFirstPos, TRUE, &mii);
+ if(bRet == FALSE)
+ break;
+ if((mii.wID >= ID_WINDOW_TABFIRST && mii.wID <= ID_WINDOW_TABLAST) || mii.wID == ID_WINDOW_SHOWTABLIST)
+ break;
+ }
+#endif // _WIN32_WCE
+
+ // Remove all menu items for tab pages
+ BOOL bRet = TRUE;
+ while(bRet != FALSE)
+ bRet = menu.DeleteMenu(nFirstPos, MF_BYPOSITION);
+
+ // Add separator if it's not already there
+ int nPageCount = GetPageCount();
+ if((bWindowsMenuItem || (nPageCount > 0)) && (nFirstPos > 0))
+ {
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_TYPE;
+ menu.GetMenuItemInfo(nFirstPos - 1, TRUE, &mii);
+ if((nFirstPos <= 0) || ((mii.fType & MFT_SEPARATOR) == 0))
+ {
+ menu.AppendMenu(MF_SEPARATOR);
+ nFirstPos++;
+ }
+ }
+
+ // Add menu items for all pages
+ if(nPageCount > 0)
+ {
+ // Append menu items for all pages
+ const int cchPrefix = 3; // 2 digits + space
+ nMenuItemsCount = min(min(nPageCount, nMenuItemsCount), (int)m_nMenuItemsMax);
+ ATLASSERT(nMenuItemsCount < 100); // 2 digits only
+ if(nMenuItemsCount >= 100)
+ nMenuItemsCount = 99;
+
+ for(int i = 0; i < nMenuItemsCount; i++)
+ {
+ LPCTSTR lpstrTitle = GetPageTitle(i);
+ int nLen = lstrlen(lpstrTitle);
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrText = buff.Allocate(cchPrefix + nLen + 1);
+ ATLASSERT(lpstrText != NULL);
+ if(lpstrText != NULL)
+ {
+ LPCTSTR lpstrFormat = (i < 9) ? _T("&%i %s") : _T("%i %s");
+ SecureHelper::wsprintf_x(lpstrText, cchPrefix + nLen + 1, lpstrFormat, i + 1, lpstrTitle);
+ menu.AppendMenu(MF_STRING, ID_WINDOW_TABFIRST + i, lpstrText);
+ }
+ }
+
+ // Mark active page
+ if(bActivePageMenuItem && (m_nActivePage != -1))
+ {
+#ifndef _WIN32_WCE
+ if(bActiveAsDefaultMenuItem)
+ {
+ menu.SetMenuDefaultItem((UINT)-1, TRUE);
+ menu.SetMenuDefaultItem(nFirstPos + m_nActivePage, TRUE);
+ }
+ else
+#else // CE specific
+ bActiveAsDefaultMenuItem; // avoid level 4 warning
+#endif // _WIN32_WCE
+ {
+ menu.CheckMenuRadioItem(nFirstPos, nFirstPos + nMenuItemsCount, nFirstPos + m_nActivePage, MF_BYPOSITION);
+ }
+ }
+ }
+ else
+ {
+ if(bEmptyMenuItem)
+ {
+ menu.AppendMenu(MF_BYPOSITION | MF_STRING, ID_WINDOW_TABFIRST, pT->GetEmptyListText());
+ menu.EnableMenuItem(ID_WINDOW_TABFIRST, MF_GRAYED);
+ }
+
+ // Remove separator if nothing else is there
+ if(!bEmptyMenuItem && !bWindowsMenuItem && (nFirstPos > 0))
+ {
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_TYPE;
+ menu.GetMenuItemInfo(nFirstPos - 1, TRUE, &mii);
+ if((mii.fType & MFT_SEPARATOR) != 0)
+ menu.DeleteMenu(nFirstPos - 1, MF_BYPOSITION);
+ }
+ }
+
+ // Add "Windows..." menu item
+ if(bWindowsMenuItem)
+ menu.AppendMenu(MF_BYPOSITION | MF_STRING, ID_WINDOW_SHOWTABLIST, pT->GetWindowsMenuItemText());
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CTabViewImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
+ MESSAGE_HANDLER(WM_GETFONT, OnGetFont)
+ MESSAGE_HANDLER(WM_SETFONT, OnSetFont)
+ NOTIFY_HANDLER(m_nTabID, TCN_SELCHANGE, OnTabChanged)
+ NOTIFY_ID_HANDLER(m_nTabID, OnTabNotification)
+#ifndef _WIN32_WCE
+ NOTIFY_CODE_HANDLER(TTN_GETDISPINFO, OnTabGetDispInfo)
+#endif // !_WIN32_WCE
+ FORWARD_NOTIFICATIONS()
+ ALT_MSG_MAP(1) // tab control
+ MESSAGE_HANDLER(WM_LBUTTONDOWN, OnTabLButtonDown)
+ MESSAGE_HANDLER(WM_LBUTTONUP, OnTabLButtonUp)
+ MESSAGE_HANDLER(WM_CAPTURECHANGED, OnTabCaptureChanged)
+ MESSAGE_HANDLER(WM_MOUSEMOVE, OnTabMouseMove)
+ MESSAGE_HANDLER(WM_RBUTTONUP, OnTabRButtonUp)
+ MESSAGE_HANDLER(WM_SYSKEYDOWN, OnTabSysKeyDown)
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->CreateTabControl();
+
+ return 0;
+ }
+
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ RemoveAllPages();
+
+ if(m_bDestroyImageList)
+ {
+ CImageList il = m_tab.SetImageList(NULL);
+ if(il.m_hImageList != NULL)
+ il.Destroy();
+ }
+
+ if(m_bInternalFont)
+ {
+ HFONT hFont = m_tab.GetFont();
+ m_tab.SetFont(NULL, FALSE);
+ ::DeleteObject(hFont);
+ m_bInternalFont = false;
+ }
+
+ return 0;
+ }
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+ return 0;
+ }
+
+ LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(m_nActivePage != -1)
+ ::SetFocus(GetPageHWND(m_nActivePage));
+ return 0;
+ }
+
+ LRESULT OnGetFont(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return m_tab.SendMessage(WM_GETFONT);
+ }
+
+ LRESULT OnSetFont(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ if(m_bInternalFont)
+ {
+ HFONT hFont = m_tab.GetFont();
+ m_tab.SetFont(NULL, FALSE);
+ ::DeleteObject(hFont);
+ m_bInternalFont = false;
+ }
+
+ m_tab.SendMessage(WM_SETFONT, wParam, lParam);
+
+ T* pT = static_cast<T*>(this);
+ m_cyTabHeight = pT->CalcTabHeight();
+
+ if((BOOL)lParam != FALSE)
+ pT->UpdateLayout();
+
+ return 0;
+ }
+
+ LRESULT OnTabChanged(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
+ {
+ SetActivePage(m_tab.GetCurSel());
+ T* pT = static_cast<T*>(this);
+ pT->OnPageActivated(m_nActivePage);
+
+ return 0;
+ }
+
+ LRESULT OnTabNotification(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
+ {
+ // nothing to do - this just blocks all tab control
+ // notifications from being propagated further
+ return 0;
+ }
+
+#ifndef _WIN32_WCE
+ LRESULT OnTabGetDispInfo(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ LPNMTTDISPINFO pTTDI = (LPNMTTDISPINFO)pnmh;
+ if(pTTDI->hdr.hwndFrom == m_tab.GetTooltips())
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateTooltipText(pTTDI);
+ }
+ else
+ {
+ bHandled = FALSE;
+ }
+
+ return 0;
+ }
+#endif // !_WIN32_WCE
+
+// Tab control message handlers
+ LRESULT OnTabLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(!m_bNoTabDrag && (m_tab.GetItemCount() > 1))
+ {
+ m_bTabCapture = true;
+ m_tab.SetCapture();
+
+ m_ptStartDrag.x = GET_X_LPARAM(lParam);
+ m_ptStartDrag.y = GET_Y_LPARAM(lParam);
+ }
+
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnTabLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(m_bTabCapture)
+ {
+ if(m_bTabDrag)
+ {
+ TCHITTESTINFO hti = { 0 };
+ hti.pt.x = GET_X_LPARAM(lParam);
+ hti.pt.y = GET_Y_LPARAM(lParam);
+ int nItem = m_tab.HitTest(&hti);
+ if(nItem != -1)
+ MovePage(m_nActivePage, nItem);
+ }
+
+ ::ReleaseCapture();
+ }
+
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnTabCaptureChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_bTabCapture)
+ {
+ m_bTabCapture = false;
+
+ if(m_bTabDrag)
+ {
+ m_bTabDrag = false;
+ T* pT = static_cast<T*>(this);
+ pT->DrawMoveMark(-1);
+
+#ifndef _WIN32_WCE
+ m_ilDrag.DragLeave(GetDesktopWindow());
+#endif // !_WIN32_WCE
+ m_ilDrag.EndDrag();
+
+ m_ilDrag.Destroy();
+ m_ilDrag.m_hImageList = NULL;
+ }
+ }
+
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnTabMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ bHandled = FALSE;
+
+ if(m_bTabCapture)
+ {
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+
+ if(!m_bTabDrag)
+ {
+#ifndef _WIN32_WCE
+ if(abs(m_ptStartDrag.x - GET_X_LPARAM(lParam)) >= ::GetSystemMetrics(SM_CXDRAG) ||
+ abs(m_ptStartDrag.y - GET_Y_LPARAM(lParam)) >= ::GetSystemMetrics(SM_CYDRAG))
+#else // CE specific
+ if(abs(m_ptStartDrag.x - GET_X_LPARAM(lParam)) >= 4 ||
+ abs(m_ptStartDrag.y - GET_Y_LPARAM(lParam)) >= 4)
+#endif // _WIN32_WCE
+ {
+ T* pT = static_cast<T*>(this);
+ pT->GenerateDragImage(m_nActivePage);
+
+ int cxCursor = ::GetSystemMetrics(SM_CXCURSOR);
+ int cyCursor = ::GetSystemMetrics(SM_CYCURSOR);
+ m_ilDrag.BeginDrag(0, -(cxCursor / 2), -(cyCursor / 2));
+#ifndef _WIN32_WCE
+ POINT ptEnter = m_ptStartDrag;
+ m_tab.ClientToScreen(&ptEnter);
+ m_ilDrag.DragEnter(GetDesktopWindow(), ptEnter);
+#endif // !_WIN32_WCE
+
+ m_bTabDrag = true;
+ }
+ }
+
+ if(m_bTabDrag)
+ {
+ TCHITTESTINFO hti = { 0 };
+ hti.pt = pt;
+ int nItem = m_tab.HitTest(&hti);
+
+ T* pT = static_cast<T*>(this);
+ pT->SetMoveCursor(nItem != -1);
+
+ if(m_nInsertItem != nItem)
+ pT->DrawMoveMark(nItem);
+
+ m_ilDrag.DragShowNolock((nItem != -1) ? TRUE : FALSE);
+ m_tab.ClientToScreen(&pt);
+ m_ilDrag.DragMove(pt);
+
+ bHandled = TRUE;
+ }
+ }
+
+ return 0;
+ }
+
+ LRESULT OnTabRButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ TCHITTESTINFO hti = { 0 };
+ hti.pt.x = GET_X_LPARAM(lParam);
+ hti.pt.y = GET_Y_LPARAM(lParam);
+ int nItem = m_tab.HitTest(&hti);
+ if(nItem != -1)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->OnContextMenu(nItem, hti.pt);
+ }
+
+ return 0;
+ }
+
+ LRESULT OnTabSysKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ bool bShift = (::GetKeyState(VK_SHIFT) < 0);
+ if(wParam == VK_F10 && bShift)
+ {
+ if(m_nActivePage != -1)
+ {
+ RECT rect = { 0 };
+ m_tab.GetItemRect(m_nActivePage, &rect);
+ POINT pt = { rect.left, rect.bottom };
+ T* pT = static_cast<T*>(this);
+ pT->OnContextMenu(m_nActivePage, pt);
+ }
+ }
+ else
+ {
+ bHandled = FALSE;
+ }
+
+ return 0;
+ }
+
+// Implementation helpers
+ bool IsValidPageIndex(int nPage) const
+ {
+ return (nPage >= 0 && nPage < GetPageCount());
+ }
+
+ bool MovePage(int nMovePage, int nInsertBeforePage)
+ {
+ ATLASSERT(IsValidPageIndex(nMovePage));
+ ATLASSERT(IsValidPageIndex(nInsertBeforePage));
+
+ if(!IsValidPageIndex(nMovePage) || !IsValidPageIndex(nInsertBeforePage))
+ return false;
+
+ if(nMovePage == nInsertBeforePage)
+ return true; // nothing to do
+
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrTabText = buff.Allocate(m_cchTabTextLength + 1);
+ if(lpstrTabText == NULL)
+ return false;
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_PARAM;
+ tcix.tciheader.pszText = lpstrTabText;
+ tcix.tciheader.cchTextMax = m_cchTabTextLength + 1;
+ BOOL bRet = m_tab.GetItem(nMovePage, tcix);
+ ATLASSERT(bRet != FALSE);
+ if(bRet == FALSE)
+ return false;
+
+ int nInsertItem = (nInsertBeforePage > nMovePage) ? nInsertBeforePage + 1 : nInsertBeforePage;
+ int nNewItem = m_tab.InsertItem(nInsertItem, tcix);
+ ATLASSERT(nNewItem == nInsertItem);
+ if(nNewItem != nInsertItem)
+ {
+ ATLVERIFY(m_tab.DeleteItem(nNewItem));
+ return false;
+ }
+
+ if(nMovePage > nInsertBeforePage)
+ ATLVERIFY(m_tab.DeleteItem(nMovePage + 1) != FALSE);
+ else if(nMovePage < nInsertBeforePage)
+ ATLVERIFY(m_tab.DeleteItem(nMovePage) != FALSE);
+
+ SetActivePage(nInsertBeforePage);
+ T* pT = static_cast<T*>(this);
+ pT->OnPageActivated(m_nActivePage);
+
+ return true;
+ }
+
+// Implementation overrideables
+ bool CreateTabControl()
+ {
+#ifndef _WIN32_WCE
+ m_tab.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | TCS_TOOLTIPS, 0, m_nTabID);
+#else // CE specific
+ m_tab.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, m_nTabID);
+#endif // _WIN32_WCE
+ ATLASSERT(m_tab.m_hWnd != NULL);
+ if(m_tab.m_hWnd == NULL)
+ return false;
+
+ m_tab.SetFont(AtlCreateControlFont());
+ m_bInternalFont = true;
+
+ m_tab.SetItemExtra(sizeof(TABVIEWPAGE));
+
+ T* pT = static_cast<T*>(this);
+ m_cyTabHeight = pT->CalcTabHeight();
+
+ return true;
+ }
+
+ int CalcTabHeight()
+ {
+ int nCount = m_tab.GetItemCount();
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_TEXT;
+ tcix.tciheader.pszText = _T("NS");
+ int nIndex = m_tab.InsertItem(nCount, tcix);
+
+ RECT rect = { 0, 0, 1000, 1000 };
+ m_tab.AdjustRect(FALSE, &rect);
+
+ RECT rcWnd = { 0, 0, 1000, rect.top };
+ ::AdjustWindowRectEx(&rcWnd, m_tab.GetStyle(), FALSE, m_tab.GetExStyle());
+
+ int nHeight = rcWnd.bottom - rcWnd.top;
+
+ m_tab.DeleteItem(nIndex);
+
+ return nHeight;
+ }
+
+ void ShowTabControl(bool bShow)
+ {
+ m_tab.ShowWindow(bShow ? SW_SHOWNOACTIVATE : SW_HIDE);
+ }
+
+ void UpdateLayout()
+ {
+ RECT rect;
+ GetClientRect(&rect);
+
+ if(m_tab.IsWindow() && ((m_tab.GetStyle() & WS_VISIBLE) != 0))
+ m_tab.SetWindowPos(NULL, 0, 0, rect.right - rect.left, m_cyTabHeight, SWP_NOZORDER);
+
+ if(m_nActivePage != -1)
+ ::SetWindowPos(GetPageHWND(m_nActivePage), NULL, 0, m_cyTabHeight, rect.right - rect.left, rect.bottom - rect.top - m_cyTabHeight, SWP_NOZORDER);
+ }
+
+ void UpdateMenu()
+ {
+ if(m_menu.m_hMenu != NULL)
+ BuildWindowMenu(m_menu, m_nMenuItemsCount, m_bEmptyMenuItem, m_bWindowsMenuItem, m_bActivePageMenuItem, m_bActiveAsDefaultMenuItem);
+ }
+
+ void UpdateTitleBar()
+ {
+ if(!m_wndTitleBar.IsWindow() || m_lpstrTitleBarBase == NULL)
+ return; // nothing to do
+
+ if(m_nActivePage != -1)
+ {
+ T* pT = static_cast<T*>(this);
+ LPCTSTR lpstrTitle = pT->GetPageTitle(m_nActivePage);
+ LPCTSTR lpstrDivider = pT->GetTitleDividerText();
+ int cchBuffer = m_cchTitleBarLength + lstrlen(lpstrDivider) + lstrlen(m_lpstrTitleBarBase) + 1;
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpstrPageTitle = buff.Allocate(cchBuffer);
+ ATLASSERT(lpstrPageTitle != NULL);
+ if(lpstrPageTitle != NULL)
+ {
+ pT->ShortenTitle(lpstrTitle, lpstrPageTitle, m_cchTitleBarLength + 1);
+ SecureHelper::strcat_x(lpstrPageTitle, cchBuffer, lpstrDivider);
+ SecureHelper::strcat_x(lpstrPageTitle, cchBuffer, m_lpstrTitleBarBase);
+ }
+ else
+ {
+ lpstrPageTitle = m_lpstrTitleBarBase;
+ }
+
+ m_wndTitleBar.SetWindowText(lpstrPageTitle);
+ }
+ else
+ {
+ m_wndTitleBar.SetWindowText(m_lpstrTitleBarBase);
+ }
+ }
+
+ void DrawMoveMark(int nItem)
+ {
+ T* pT = static_cast<T*>(this);
+
+ if(m_nInsertItem != -1)
+ {
+ RECT rect = { 0 };
+ pT->GetMoveMarkRect(rect);
+ m_tab.InvalidateRect(&rect);
+ }
+
+ m_nInsertItem = nItem;
+
+ if(m_nInsertItem != -1)
+ {
+ CClientDC dc(m_tab.m_hWnd);
+
+ RECT rect = { 0 };
+ pT->GetMoveMarkRect(rect);
+
+ CPen pen;
+ pen.CreatePen(PS_SOLID, 1, ::GetSysColor(COLOR_WINDOWTEXT));
+ CBrush brush;
+ brush.CreateSolidBrush(::GetSysColor(COLOR_WINDOWTEXT));
+
+ HPEN hPenOld = dc.SelectPen(pen);
+ HBRUSH hBrushOld = dc.SelectBrush(brush);
+
+ int x = rect.left;
+ int y = rect.top;
+ POINT ptsTop[3] = { { x, y }, { x + m_cxMoveMark, y }, { x + (m_cxMoveMark / 2), y + m_cyMoveMark } };
+ dc.Polygon(ptsTop, 3);
+
+ y = rect.bottom - 1;
+ POINT ptsBottom[3] = { { x, y }, { x + m_cxMoveMark, y }, { x + (m_cxMoveMark / 2), y - m_cyMoveMark } };
+ dc.Polygon(ptsBottom, 3);
+
+ dc.SelectPen(hPenOld);
+ dc.SelectBrush(hBrushOld);
+ }
+ }
+
+ void GetMoveMarkRect(RECT& rect) const
+ {
+ m_tab.GetClientRect(&rect);
+
+ RECT rcItem = { 0 };
+ m_tab.GetItemRect(m_nInsertItem, &rcItem);
+
+ if(m_nInsertItem <= m_nActivePage)
+ {
+ rect.left = rcItem.left - m_cxMoveMark / 2 - 1;
+ rect.right = rcItem.left + m_cxMoveMark / 2;
+ }
+ else
+ {
+ rect.left = rcItem.right - m_cxMoveMark / 2 - 1;
+ rect.right = rcItem.right + m_cxMoveMark / 2;
+ }
+ }
+
+ void SetMoveCursor(bool bCanMove)
+ {
+ ::SetCursor(::LoadCursor(NULL, bCanMove ? IDC_ARROW : IDC_NO));
+ }
+
+ void GenerateDragImage(int nItem)
+ {
+ ATLASSERT(IsValidPageIndex(nItem));
+
+#ifndef _WIN32_WCE
+ RECT rcItem = { 0 };
+ m_tab.GetItemRect(nItem, &rcItem);
+ ::InflateRect(&rcItem, 2, 2); // make bigger to cover selected item
+#else // CE specific
+ nItem; // avoid level 4 warning
+ RECT rcItem = { 0, 0, 40, 20 };
+#endif // _WIN32_WCE
+
+ ATLASSERT(m_ilDrag.m_hImageList == NULL);
+ m_ilDrag.Create(rcItem.right - rcItem.left, rcItem.bottom - rcItem.top, ILC_COLORDDB | ILC_MASK, 1, 1);
+
+ CClientDC dc(m_hWnd);
+ CDC dcMem;
+ dcMem.CreateCompatibleDC(dc);
+ ATLASSERT(dcMem.m_hDC != NULL);
+ dcMem.SetViewportOrg(-rcItem.left, -rcItem.top);
+
+ CBitmap bmp;
+ bmp.CreateCompatibleBitmap(dc, rcItem.right - rcItem.left, rcItem.bottom - rcItem.top);
+ ATLASSERT(bmp.m_hBitmap != NULL);
+
+ HBITMAP hBmpOld = dcMem.SelectBitmap(bmp);
+#ifndef _WIN32_WCE
+ m_tab.SendMessage(WM_PRINTCLIENT, (WPARAM)dcMem.m_hDC);
+#else // CE specific
+ dcMem.Rectangle(&rcItem);
+#endif // _WIN32_WCE
+ dcMem.SelectBitmap(hBmpOld);
+
+ ATLVERIFY(m_ilDrag.Add(bmp.m_hBitmap, RGB(255, 0, 255)) != -1);
+ }
+
+ void ShortenTitle(LPCTSTR lpstrTitle, LPTSTR lpstrShortTitle, int cchShortTitle)
+ {
+ if(lstrlen(lpstrTitle) >= cchShortTitle)
+ {
+ LPCTSTR lpstrEllipsis = _T("...");
+ int cchEllipsis = lstrlen(lpstrEllipsis);
+ SecureHelper::strncpy_x(lpstrShortTitle, cchShortTitle, lpstrTitle, cchShortTitle - cchEllipsis - 1);
+ SecureHelper::strcat_x(lpstrShortTitle, cchShortTitle, lpstrEllipsis);
+ }
+ else
+ {
+ SecureHelper::strcpy_x(lpstrShortTitle, cchShortTitle, lpstrTitle);
+ }
+ }
+
+#ifndef _WIN32_WCE
+ void UpdateTooltipText(LPNMTTDISPINFO pTTDI)
+ {
+ ATLASSERT(pTTDI != NULL);
+ pTTDI->lpszText = (LPTSTR)GetPageTitle((int)pTTDI->hdr.idFrom);
+ }
+#endif // !_WIN32_WCE
+
+// Text for menu items and title bar - override to provide different strings
+ static LPCTSTR GetEmptyListText()
+ {
+ return _T("(Empty)");
+ }
+
+ static LPCTSTR GetWindowsMenuItemText()
+ {
+ return _T("&Windows...");
+ }
+
+ static LPCTSTR GetTitleDividerText()
+ {
+ return _T(" - ");
+ }
+
+// Notifications - override to provide different behavior
+ void OnPageActivated(int nPage)
+ {
+ NMHDR nmhdr = { 0 };
+ nmhdr.hwndFrom = m_hWnd;
+ nmhdr.idFrom = nPage;
+ nmhdr.code = TBVN_PAGEACTIVATED;
+ ::SendMessage(GetParent(), WM_NOTIFY, GetDlgCtrlID(), (LPARAM)&nmhdr);
+ }
+
+ void OnContextMenu(int nPage, POINT pt)
+ {
+ m_tab.ClientToScreen(&pt);
+
+ TBVCONTEXTMENUINFO cmi = { 0 };
+ cmi.hdr.hwndFrom = m_hWnd;
+ cmi.hdr.idFrom = nPage;
+ cmi.hdr.code = TBVN_CONTEXTMENU;
+ cmi.pt = pt;
+ ::SendMessage(GetParent(), WM_NOTIFY, GetDlgCtrlID(), (LPARAM)&cmi);
+ }
+};
+
+class CTabView : public CTabViewImpl<CTabView>
+{
+public:
+ DECLARE_WND_CLASS_EX(_T("WTL_TabView"), 0, COLOR_APPWORKSPACE)
+};
+
+}; // namespace WTL
+
+#endif // __ATLCTRLX_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlddx.h b/plugins/SmartAutoReplier/wtl/atlddx.h
new file mode 100644
index 0000000000..ecaf0adb01
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlddx.h
@@ -0,0 +1,679 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLDDX_H__
+#define __ATLDDX_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlddx.h requires atlapp.h to be included first
+#endif
+
+#if defined(_ATL_USE_DDX_FLOAT) && defined(_ATL_MIN_CRT)
+ #error Cannot use floating point DDX with _ATL_MIN_CRT defined
+#endif // defined(_ATL_USE_DDX_FLOAT) && defined(_ATL_MIN_CRT)
+
+#ifdef _ATL_USE_DDX_FLOAT
+ #include <float.h>
+#endif // _ATL_USE_DDX_FLOAT
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CWinDataExchange<T>
+
+
+namespace WTL
+{
+
+// Constants
+#define DDX_LOAD FALSE
+#define DDX_SAVE TRUE
+
+// DDX map macros
+#define BEGIN_DDX_MAP(thisClass) \
+ BOOL DoDataExchange(BOOL bSaveAndValidate = FALSE, UINT nCtlID = (UINT)-1) \
+ { \
+ bSaveAndValidate; \
+ nCtlID;
+
+#define DDX_TEXT(nID, var) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Text(nID, var, sizeof(var), bSaveAndValidate)) \
+ return FALSE; \
+ }
+
+#define DDX_TEXT_LEN(nID, var, len) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Text(nID, var, sizeof(var), bSaveAndValidate, TRUE, len)) \
+ return FALSE; \
+ }
+
+#define DDX_INT(nID, var) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Int(nID, var, TRUE, bSaveAndValidate)) \
+ return FALSE; \
+ }
+
+#define DDX_INT_RANGE(nID, var, min, max) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Int(nID, var, TRUE, bSaveAndValidate, TRUE, min, max)) \
+ return FALSE; \
+ }
+
+#define DDX_UINT(nID, var) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Int(nID, var, FALSE, bSaveAndValidate)) \
+ return FALSE; \
+ }
+
+#define DDX_UINT_RANGE(nID, var, min, max) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Int(nID, var, FALSE, bSaveAndValidate, TRUE, min, max)) \
+ return FALSE; \
+ }
+
+#ifdef _ATL_USE_DDX_FLOAT
+#define DDX_FLOAT(nID, var) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Float(nID, var, bSaveAndValidate)) \
+ return FALSE; \
+ }
+
+#define DDX_FLOAT_RANGE(nID, var, min, max) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Float(nID, var, bSaveAndValidate, TRUE, min, max)) \
+ return FALSE; \
+ }
+#define DDX_FLOAT_P(nID, var, precision) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Float(nID, var, bSaveAndValidate, FALSE, 0, 0, precision)) \
+ return FALSE; \
+ }
+
+#define DDX_FLOAT_P_RANGE(nID, var, min, max, precision) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ { \
+ if(!DDX_Float(nID, var, bSaveAndValidate, TRUE, min, max, precision)) \
+ return FALSE; \
+ }
+#endif // _ATL_USE_DDX_FLOAT
+
+#define DDX_CONTROL(nID, obj) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ DDX_Control(nID, obj, bSaveAndValidate);
+
+#define DDX_CONTROL_HANDLE(nID, obj) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ DDX_Control_Handle(nID, obj, bSaveAndValidate);
+
+#define DDX_CHECK(nID, var) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ DDX_Check(nID, var, bSaveAndValidate);
+
+#define DDX_RADIO(nID, var) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ DDX_Radio(nID, var, bSaveAndValidate);
+
+#define END_DDX_MAP() \
+ return TRUE; \
+ }
+
+// DDX support for Tab, Combo, ListBox and ListView selection index
+// Note: Specialized versions require atlctrls.h to be included first
+#define DDX_INDEX(CtrlClass, nID, var) \
+ if(nCtlID == (UINT)-1 || nCtlID == nID) \
+ DDX_Index<CtrlClass>(nID, var, bSaveAndValidate);
+
+#ifdef __ATLCTRLS_H__
+ #define DDX_TAB_INDEX(nID, var) DDX_INDEX(WTL::CTabCtrl, nID, var)
+ #define DDX_COMBO_INDEX(nID, var) DDX_INDEX(WTL::CComboBox, nID, var)
+ #define DDX_LISTBOX_INDEX(nID, var) DDX_INDEX(WTL::CListBox, nID, var)
+ #define DDX_LISTVIEW_INDEX(nID, var) DDX_INDEX(WTL::CListViewCtrl, nID, var)
+#endif // __ATLCTRLS_H__
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CWinDataExchange - provides support for DDX
+
+template <class T>
+class CWinDataExchange
+{
+public:
+// Data exchange method - override in your derived class
+ BOOL DoDataExchange(BOOL /*bSaveAndValidate*/ = FALSE, UINT /*nCtlID*/ = (UINT)-1)
+ {
+ // this one should never be called, override it in
+ // your derived class by implementing DDX map
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+// Helpers for validation error reporting
+ enum _XDataType
+ {
+ ddxDataNull = 0,
+ ddxDataText = 1,
+ ddxDataInt = 2,
+ ddxDataFloat = 3,
+ ddxDataDouble = 4
+ };
+
+ struct _XTextData
+ {
+ int nLength;
+ int nMaxLength;
+ };
+
+ struct _XIntData
+ {
+ long nVal;
+ long nMin;
+ long nMax;
+ };
+
+ struct _XFloatData
+ {
+ double nVal;
+ double nMin;
+ double nMax;
+ };
+
+ struct _XData
+ {
+ _XDataType nDataType;
+ union
+ {
+ _XTextData textData;
+ _XIntData intData;
+ _XFloatData floatData;
+ };
+ };
+
+// Text exchange
+ BOOL DDX_Text(UINT nID, LPTSTR lpstrText, int cbSize, BOOL bSave, BOOL bValidate = FALSE, int nLength = 0)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bSuccess = TRUE;
+
+ if(bSave)
+ {
+ HWND hWndCtrl = pT->GetDlgItem(nID);
+ int nRetLen = ::GetWindowText(hWndCtrl, lpstrText, cbSize / sizeof(TCHAR));
+ if(nRetLen < ::GetWindowTextLength(hWndCtrl))
+ bSuccess = FALSE;
+ }
+ else
+ {
+ ATLASSERT(!bValidate || lstrlen(lpstrText) <= nLength);
+ bSuccess = pT->SetDlgItemText(nID, lpstrText);
+ }
+
+ if(!bSuccess)
+ {
+ pT->OnDataExchangeError(nID, bSave);
+ }
+ else if(bSave && bValidate) // validation
+ {
+ ATLASSERT(nLength > 0);
+ if(lstrlen(lpstrText) > nLength)
+ {
+ _XData data = { ddxDataText };
+ data.textData.nLength = lstrlen(lpstrText);
+ data.textData.nMaxLength = nLength;
+ pT->OnDataValidateError(nID, bSave, data);
+ bSuccess = FALSE;
+ }
+ }
+ return bSuccess;
+ }
+
+ BOOL DDX_Text(UINT nID, BSTR& bstrText, int /*cbSize*/, BOOL bSave, BOOL bValidate = FALSE, int nLength = 0)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bSuccess = TRUE;
+
+ if(bSave)
+ {
+ bSuccess = pT->GetDlgItemText(nID, bstrText);
+ }
+ else
+ {
+ USES_CONVERSION;
+ LPTSTR lpstrText = OLE2T(bstrText);
+ ATLASSERT(!bValidate || lstrlen(lpstrText) <= nLength);
+ bSuccess = pT->SetDlgItemText(nID, lpstrText);
+ }
+
+ if(!bSuccess)
+ {
+ pT->OnDataExchangeError(nID, bSave);
+ }
+ else if(bSave && bValidate) // validation
+ {
+ ATLASSERT(nLength > 0);
+ if((int)::SysStringLen(bstrText) > nLength)
+ {
+ _XData data = { ddxDataText };
+ data.textData.nLength = (int)::SysStringLen(bstrText);
+ data.textData.nMaxLength = nLength;
+ pT->OnDataValidateError(nID, bSave, data);
+ bSuccess = FALSE;
+ }
+ }
+ return bSuccess;
+ }
+
+ BOOL DDX_Text(UINT nID, ATL::CComBSTR& bstrText, int /*cbSize*/, BOOL bSave, BOOL bValidate = FALSE, int nLength = 0)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bSuccess = TRUE;
+
+ if(bSave)
+ {
+ bSuccess = pT->GetDlgItemText(nID, (BSTR&)bstrText);
+ }
+ else
+ {
+ USES_CONVERSION;
+ LPTSTR lpstrText = OLE2T(bstrText);
+ ATLASSERT(!bValidate || lstrlen(lpstrText) <= nLength);
+ bSuccess = pT->SetDlgItemText(nID, lpstrText);
+ }
+
+ if(!bSuccess)
+ {
+ pT->OnDataExchangeError(nID, bSave);
+ }
+ else if(bSave && bValidate) // validation
+ {
+ ATLASSERT(nLength > 0);
+ if((int)bstrText.Length() > nLength)
+ {
+ _XData data = { ddxDataText };
+ data.textData.nLength = (int)bstrText.Length();
+ data.textData.nMaxLength = nLength;
+ pT->OnDataValidateError(nID, bSave, data);
+ bSuccess = FALSE;
+ }
+ }
+ return bSuccess;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ BOOL DDX_Text(UINT nID, _CSTRING_NS::CString& strText, int /*cbSize*/, BOOL bSave, BOOL bValidate = FALSE, int nLength = 0)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bSuccess = TRUE;
+
+ if(bSave)
+ {
+ HWND hWndCtrl = pT->GetDlgItem(nID);
+ int nLen = ::GetWindowTextLength(hWndCtrl);
+ int nRetLen = -1;
+ LPTSTR lpstr = strText.GetBufferSetLength(nLen);
+ if(lpstr != NULL)
+ {
+ nRetLen = ::GetWindowText(hWndCtrl, lpstr, nLen + 1);
+ strText.ReleaseBuffer();
+ }
+ if(nRetLen < nLen)
+ bSuccess = FALSE;
+ }
+ else
+ {
+ bSuccess = pT->SetDlgItemText(nID, strText);
+ }
+
+ if(!bSuccess)
+ {
+ pT->OnDataExchangeError(nID, bSave);
+ }
+ else if(bSave && bValidate) // validation
+ {
+ ATLASSERT(nLength > 0);
+ if(strText.GetLength() > nLength)
+ {
+ _XData data = { ddxDataText };
+ data.textData.nLength = strText.GetLength();
+ data.textData.nMaxLength = nLength;
+ pT->OnDataValidateError(nID, bSave, data);
+ bSuccess = FALSE;
+ }
+ }
+ return bSuccess;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+// Numeric exchange
+ template <class Type>
+ BOOL DDX_Int(UINT nID, Type& nVal, BOOL bSigned, BOOL bSave, BOOL bValidate = FALSE, Type nMin = 0, Type nMax = 0)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bSuccess = TRUE;
+
+ if(bSave)
+ {
+ nVal = (Type)pT->GetDlgItemInt(nID, &bSuccess, bSigned);
+ }
+ else
+ {
+ ATLASSERT(!bValidate || nVal >= nMin && nVal <= nMax);
+ bSuccess = pT->SetDlgItemInt(nID, nVal, bSigned);
+ }
+
+ if(!bSuccess)
+ {
+ pT->OnDataExchangeError(nID, bSave);
+ }
+ else if(bSave && bValidate) // validation
+ {
+ ATLASSERT(nMin != nMax);
+ if(nVal < nMin || nVal > nMax)
+ {
+ _XData data = { ddxDataInt };
+ data.intData.nVal = (long)nVal;
+ data.intData.nMin = (long)nMin;
+ data.intData.nMax = (long)nMax;
+ pT->OnDataValidateError(nID, bSave, data);
+ bSuccess = FALSE;
+ }
+ }
+ return bSuccess;
+ }
+
+// Float exchange
+#ifdef _ATL_USE_DDX_FLOAT
+ static BOOL _AtlSimpleFloatParse(LPCTSTR lpszText, double& d)
+ {
+ ATLASSERT(lpszText != NULL);
+ while (*lpszText == _T(' ') || *lpszText == _T('\t'))
+ lpszText++;
+
+ TCHAR chFirst = lpszText[0];
+ d = _tcstod(lpszText, (LPTSTR*)&lpszText);
+ if (d == 0.0 && chFirst != _T('0'))
+ return FALSE; // could not convert
+ while (*lpszText == _T(' ') || *lpszText == _T('\t'))
+ lpszText++;
+
+ if (*lpszText != _T('\0'))
+ return FALSE; // not terminated properly
+
+ return TRUE;
+ }
+
+ BOOL DDX_Float(UINT nID, float& nVal, BOOL bSave, BOOL bValidate = FALSE, float nMin = 0.F, float nMax = 0.F, int nPrecision = FLT_DIG)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bSuccess = TRUE;
+ const int cchBuff = 32;
+ TCHAR szBuff[cchBuff] = { 0 };
+
+ if(bSave)
+ {
+ pT->GetDlgItemText(nID, szBuff, cchBuff);
+ double d = 0;
+ if(_AtlSimpleFloatParse(szBuff, d))
+ nVal = (float)d;
+ else
+ bSuccess = FALSE;
+ }
+ else
+ {
+ ATLASSERT(!bValidate || nVal >= nMin && nVal <= nMax);
+ SecureHelper::sprintf_x(szBuff, cchBuff, _T("%.*g"), nPrecision, nVal);
+ bSuccess = pT->SetDlgItemText(nID, szBuff);
+ }
+
+ if(!bSuccess)
+ {
+ pT->OnDataExchangeError(nID, bSave);
+ }
+ else if(bSave && bValidate) // validation
+ {
+ ATLASSERT(nMin != nMax);
+ if(nVal < nMin || nVal > nMax)
+ {
+ _XData data = { ddxDataFloat };
+ data.floatData.nVal = (double)nVal;
+ data.floatData.nMin = (double)nMin;
+ data.floatData.nMax = (double)nMax;
+ pT->OnDataValidateError(nID, bSave, data);
+ bSuccess = FALSE;
+ }
+ }
+ return bSuccess;
+ }
+
+ BOOL DDX_Float(UINT nID, double& nVal, BOOL bSave, BOOL bValidate = FALSE, double nMin = 0., double nMax = 0., int nPrecision = DBL_DIG)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bSuccess = TRUE;
+ const int cchBuff = 32;
+ TCHAR szBuff[cchBuff] = { 0 };
+
+ if(bSave)
+ {
+ pT->GetDlgItemText(nID, szBuff, cchBuff);
+ double d = 0;
+ if(_AtlSimpleFloatParse(szBuff, d))
+ nVal = d;
+ else
+ bSuccess = FALSE;
+ }
+ else
+ {
+ ATLASSERT(!bValidate || nVal >= nMin && nVal <= nMax);
+ SecureHelper::sprintf_x(szBuff, cchBuff, _T("%.*g"), nPrecision, nVal);
+ bSuccess = pT->SetDlgItemText(nID, szBuff);
+ }
+
+ if(!bSuccess)
+ {
+ pT->OnDataExchangeError(nID, bSave);
+ }
+ else if(bSave && bValidate) // validation
+ {
+ ATLASSERT(nMin != nMax);
+ if(nVal < nMin || nVal > nMax)
+ {
+ _XData data = { ddxDataFloat };
+ data.floatData.nVal = nVal;
+ data.floatData.nMin = nMin;
+ data.floatData.nMax = nMax;
+ pT->OnDataValidateError(nID, bSave, data);
+ bSuccess = FALSE;
+ }
+ }
+ return bSuccess;
+ }
+#endif // _ATL_USE_DDX_FLOAT
+
+// Full control subclassing (for CWindowImpl derived controls)
+ template <class TControl>
+ void DDX_Control(UINT nID, TControl& ctrl, BOOL bSave)
+ {
+ if(!bSave && ctrl.m_hWnd == NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ ctrl.SubclassWindow(pT->GetDlgItem(nID));
+ }
+ }
+
+// Simple control attaching (for HWND wrapper controls)
+ template <class TControl>
+ void DDX_Control_Handle(UINT nID, TControl& ctrl, BOOL bSave)
+ {
+ if(!bSave && ctrl.m_hWnd == NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ ctrl = pT->GetDlgItem(nID);
+ }
+ }
+
+// Control state
+ void DDX_Check(UINT nID, int& nValue, BOOL bSave)
+ {
+ T* pT = static_cast<T*>(this);
+ HWND hWndCtrl = pT->GetDlgItem(nID);
+ if(bSave)
+ {
+ nValue = (int)::SendMessage(hWndCtrl, BM_GETCHECK, 0, 0L);
+ ATLASSERT(nValue >= 0 && nValue <= 2);
+ }
+ else
+ {
+ if(nValue < 0 || nValue > 2)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ATL: Warning - dialog data checkbox value (%d) out of range.\n"), nValue);
+ nValue = 0; // default to off
+ }
+ ::SendMessage(hWndCtrl, BM_SETCHECK, nValue, 0L);
+ }
+ }
+
+ // variant that supports bool (checked/not-checked, no intermediate state)
+ void DDX_Check(UINT nID, bool& bCheck, BOOL bSave)
+ {
+ int nValue = bCheck ? 1 : 0;
+ DDX_Check(nID, nValue, bSave);
+
+ if(bSave)
+ {
+ if(nValue == 2)
+ ATLTRACE2(atlTraceUI, 0, _T("ATL: Warning - checkbox state (%d) out of supported range.\n"), nValue);
+ bCheck = (nValue == 1);
+ }
+ }
+
+ void DDX_Radio(UINT nID, int& nValue, BOOL bSave)
+ {
+ T* pT = static_cast<T*>(this);
+ HWND hWndCtrl = pT->GetDlgItem(nID);
+ ATLASSERT(hWndCtrl != NULL);
+
+ // must be first in a group of auto radio buttons
+ ATLASSERT(::GetWindowLong(hWndCtrl, GWL_STYLE) & WS_GROUP);
+ ATLASSERT(::SendMessage(hWndCtrl, WM_GETDLGCODE, 0, 0L) & DLGC_RADIOBUTTON);
+
+ if(bSave)
+ nValue = -1; // value if none found
+
+ // walk all children in group
+ int nButton = 0;
+ do
+ {
+ if(::SendMessage(hWndCtrl, WM_GETDLGCODE, 0, 0L) & DLGC_RADIOBUTTON)
+ {
+ // control in group is a radio button
+ if(bSave)
+ {
+ if(::SendMessage(hWndCtrl, BM_GETCHECK, 0, 0L) != 0)
+ {
+ ATLASSERT(nValue == -1); // only set once
+ nValue = nButton;
+ }
+ }
+ else
+ {
+ // select button
+ ::SendMessage(hWndCtrl, BM_SETCHECK, (nButton == nValue), 0L);
+ }
+ nButton++;
+ }
+ else
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ATL: Warning - skipping non-radio button in group.\n"));
+ }
+ hWndCtrl = ::GetWindow(hWndCtrl, GW_HWNDNEXT);
+ }
+ while (hWndCtrl != NULL && !(GetWindowLong(hWndCtrl, GWL_STYLE) & WS_GROUP));
+ }
+
+// DDX support for Tab, Combo, ListBox and ListView selection index
+ template <class TCtrl>
+ INT _getSel(TCtrl& tCtrl)
+ {
+ return tCtrl.GetCurSel();
+ }
+
+ template <class TCtrl>
+ void _setSel(TCtrl& tCtrl, INT iSel)
+ {
+ if(iSel < 0)
+ tCtrl.SetCurSel(-1);
+ else
+ tCtrl.SetCurSel(iSel);
+ }
+
+#ifdef __ATLCTRLS_H__
+ // ListViewCtrl specialization
+ template <>
+ INT _getSel(WTL::CListViewCtrl& tCtrl)
+ {
+ return tCtrl.GetSelectedIndex();
+ }
+
+ template <>
+ void _setSel(WTL::CListViewCtrl& tCtrl, INT iSel)
+ {
+ if(iSel < 0)
+ tCtrl.SelectItem(-1);
+ else
+ tCtrl.SelectItem(iSel);
+ }
+#endif // __ATLCTRLS_H__
+
+ template <class TCtrl>
+ void DDX_Index(UINT nID, INT& nVal, BOOL bSave)
+ {
+ T* pT = static_cast<T*>(this);
+ TCtrl ctrl(pT->GetDlgItem(nID));
+
+ if(bSave)
+ nVal = _getSel(ctrl);
+ else
+ _setSel(ctrl, nVal);
+ }
+
+// Overrideables
+ void OnDataExchangeError(UINT nCtrlID, BOOL /*bSave*/)
+ {
+ // Override to display an error message
+ ::MessageBeep((UINT)-1);
+ T* pT = static_cast<T*>(this);
+ ::SetFocus(pT->GetDlgItem(nCtrlID));
+ }
+
+ void OnDataValidateError(UINT nCtrlID, BOOL /*bSave*/, _XData& /*data*/)
+ {
+ // Override to display an error message
+ ::MessageBeep((UINT)-1);
+ T* pT = static_cast<T*>(this);
+ ::SetFocus(pT->GetDlgItem(nCtrlID));
+ }
+};
+
+}; // namespace WTL
+
+#endif // __ATLDDX_H__
diff --git a/plugins/SmartAutoReplier/wtl/atldlgs.h b/plugins/SmartAutoReplier/wtl/atldlgs.h
new file mode 100644
index 0000000000..a55fed4cb5
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atldlgs.h
@@ -0,0 +1,6403 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLDLGS_H__
+#define __ATLDLGS_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atldlgs.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atldlgs.h requires atlwin.h to be included first
+#endif
+
+#include <commdlg.h>
+#include <shlobj.h>
+
+#if (_WIN32_WINNT >= 0x0600) && !defined(_WIN32_WCE)
+ #include <shobjidl.h>
+#endif // (_WIN32_WINNT >= 0x0600) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CFileDialogImpl<T>
+// CFileDialog
+// CFileDialogEx
+// CMultiFileDialogImpl<T>
+// CMultiFileDialog
+// CShellFileDialogImpl<T>
+// CShellFileOpenDialogImpl<T>
+// CShellFileOpenDialog
+// CShellFileSaveDialogImpl<T>
+// CShellFileSaveDialog
+// CFolderDialogImpl<T>
+// CFolderDialog
+// CFontDialogImpl<T>
+// CFontDialog
+// CRichEditFontDialogImpl<T>
+// CRichEditFontDialog
+// CColorDialogImpl<T>
+// CColorDialog
+// CPrintDialogImpl<T>
+// CPrintDialog
+// CPrintDialogExImpl<T>
+// CPrintDialogEx
+// CPageSetupDialogImpl<T>
+// CPageSetupDialog
+// CFindReplaceDialogImpl<T>
+// CFindReplaceDialog
+//
+// CDialogBaseUnits
+// CMemDlgTemplate
+// CIndirectDialogImpl<T, TDlgTemplate, TBase>
+//
+// CPropertySheetWindow
+// CPropertySheetImpl<T, TBase>
+// CPropertySheet
+// CPropertyPageWindow
+// CPropertyPageImpl<T, TBase>
+// CPropertyPage<t_wDlgTemplateID>
+// CAxPropertyPageImpl<T, TBase>
+// CAxPropertyPage<t_wDlgTemplateID>
+//
+// CWizard97SheetWindow
+// CWizard97SheetImpl<T, TBase>
+// CWizard97Sheet
+// CWizard97PageWindow
+// CWizard97PageImpl<T, TBase>
+// CWizard97ExteriorPageImpl<T, TBase>
+// CWizard97InteriorPageImpl<T, TBase>
+//
+// CAeroWizardFrameWindow
+// CAeroWizardFrameImpl<T, TBase>
+// CAeroWizardFrame
+// CAeroWizardPageWindow
+// CAeroWizardPageImpl<T, TBase>
+// CAeroWizardPage<t_wDlgTemplateID>
+// CAeroWizardAxPageImpl<T, TBase>
+// CAeroWizardAxPage<t_wDlgTemplateID>
+//
+// CTaskDialogConfig
+// CTaskDialogImpl<T>
+// CTaskDialog
+//
+// Global functions:
+// AtlTaskDialog()
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CFileDialogImpl - used for File Open or File Save As
+
+// compatibility with the old (vc6.0) headers
+#if (_WIN32_WINNT >= 0x0500) && !defined(OPENFILENAME_SIZE_VERSION_400)
+ #ifndef CDSIZEOF_STRUCT
+ #define CDSIZEOF_STRUCT(structname, member) (((int)((LPBYTE)(&((structname*)0)->member) - ((LPBYTE)((structname*)0)))) + sizeof(((structname*)0)->member))
+ #endif
+ #define OPENFILENAME_SIZE_VERSION_400A CDSIZEOF_STRUCT(OPENFILENAMEA,lpTemplateName)
+ #define OPENFILENAME_SIZE_VERSION_400W CDSIZEOF_STRUCT(OPENFILENAMEW,lpTemplateName)
+ #ifdef UNICODE
+ #define OPENFILENAME_SIZE_VERSION_400 OPENFILENAME_SIZE_VERSION_400W
+ #else
+ #define OPENFILENAME_SIZE_VERSION_400 OPENFILENAME_SIZE_VERSION_400A
+ #endif // !UNICODE
+#endif // (_WIN32_WINNT >= 0x0500) && !defined(OPENFILENAME_SIZE_VERSION_400)
+
+#if !defined(_WIN32_WCE) && !defined(CDN_INCLUDEITEM)
+ #define CDN_INCLUDEITEM (CDN_FIRST - 0x0007)
+#endif
+
+template <class T>
+class ATL_NO_VTABLE CFileDialogImpl : public ATL::CDialogImplBase
+{
+public:
+#if defined(__AYGSHELL_H__) && (_WIN32_WCE >= 0x0501)
+ OPENFILENAMEEX m_ofn;
+#else
+ OPENFILENAME m_ofn;
+#endif
+ BOOL m_bOpenFileDialog; // TRUE for file open, FALSE for file save
+ TCHAR m_szFileTitle[_MAX_FNAME]; // contains file title after return
+ TCHAR m_szFileName[_MAX_PATH]; // contains full path name after return
+
+ CFileDialogImpl(BOOL bOpenFileDialog, // TRUE for FileOpen, FALSE for FileSaveAs
+ LPCTSTR lpszDefExt = NULL,
+ LPCTSTR lpszFileName = NULL,
+ DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
+ LPCTSTR lpszFilter = NULL,
+ HWND hWndParent = NULL)
+ {
+ memset(&m_ofn, 0, sizeof(m_ofn)); // initialize structure to 0/NULL
+ m_szFileName[0] = _T('\0');
+ m_szFileTitle[0] = _T('\0');
+
+ m_bOpenFileDialog = bOpenFileDialog;
+
+#if defined(__AYGSHELL_H__) && (_WIN32_WCE >= 0x0501)
+ m_ofn.lStructSize = bOpenFileDialog ? sizeof(m_ofn) : sizeof(OPENFILENAME);
+#else
+ m_ofn.lStructSize = sizeof(m_ofn);
+#endif
+
+#if (_WIN32_WINNT >= 0x0500)
+ // adjust struct size if running on older version of Windows
+ if(AtlIsOldWindows())
+ {
+ ATLASSERT(sizeof(m_ofn) > OPENFILENAME_SIZE_VERSION_400); // must be
+ m_ofn.lStructSize = OPENFILENAME_SIZE_VERSION_400;
+ }
+#endif // (_WIN32_WINNT >= 0x0500)
+ m_ofn.lpstrFile = m_szFileName;
+ m_ofn.nMaxFile = _MAX_PATH;
+ m_ofn.lpstrDefExt = lpszDefExt;
+ m_ofn.lpstrFileTitle = (LPTSTR)m_szFileTitle;
+ m_ofn.nMaxFileTitle = _MAX_FNAME;
+#ifndef _WIN32_WCE
+ m_ofn.Flags = dwFlags | OFN_EXPLORER | OFN_ENABLEHOOK | OFN_ENABLESIZING;
+#else // CE specific
+ m_ofn.Flags = dwFlags | OFN_EXPLORER | OFN_ENABLEHOOK;
+#endif // !_WIN32_WCE
+ m_ofn.lpstrFilter = lpszFilter;
+ m_ofn.hInstance = ModuleHelper::GetResourceInstance();
+ m_ofn.lpfnHook = (LPOFNHOOKPROC)T::StartDialogProc;
+ m_ofn.hwndOwner = hWndParent;
+
+ // setup initial file name
+ if(lpszFileName != NULL)
+ SecureHelper::strncpy_x(m_szFileName, _countof(m_szFileName), lpszFileName, _TRUNCATE);
+ }
+
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ ATLASSERT((m_ofn.Flags & OFN_ENABLEHOOK) != 0);
+ ATLASSERT(m_ofn.lpfnHook != NULL); // can still be a user hook
+
+ ATLASSERT((m_ofn.Flags & OFN_EXPLORER) != 0);
+
+ if(m_ofn.hwndOwner == NULL) // set only if not specified before
+ m_ofn.hwndOwner = hWndParent;
+
+ ATLASSERT(m_hWnd == NULL);
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, (ATL::CDialogImplBase*)this);
+
+ BOOL bRet;
+ if(m_bOpenFileDialog)
+#if defined(__AYGSHELL_H__) && (_WIN32_WCE >= 0x0501)
+ bRet = ::GetOpenFileNameEx(&m_ofn);
+ else
+ bRet = ::GetSaveFileName((LPOPENFILENAME)&m_ofn);
+#else
+ bRet = ::GetOpenFileName(&m_ofn);
+ else
+ bRet = ::GetSaveFileName(&m_ofn);
+#endif
+
+ m_hWnd = NULL;
+
+ return bRet ? IDOK : IDCANCEL;
+ }
+
+// Attributes
+ ATL::CWindow GetFileDialogWindow() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ATL::CWindow(GetParent());
+ }
+
+ int GetFilePath(LPTSTR lpstrFilePath, int nLength) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((m_ofn.Flags & OFN_EXPLORER) != 0);
+
+ return (int)GetFileDialogWindow().SendMessage(CDM_GETFILEPATH, nLength, (LPARAM)lpstrFilePath);
+ }
+
+ int GetFolderIDList(LPVOID lpBuff, int nLength) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((m_ofn.Flags & OFN_EXPLORER) != 0);
+
+ return (int)GetFileDialogWindow().SendMessage(CDM_GETFOLDERIDLIST, nLength, (LPARAM)lpBuff);
+ }
+
+ int GetFolderPath(LPTSTR lpstrFolderPath, int nLength) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((m_ofn.Flags & OFN_EXPLORER) != 0);
+
+ return (int)GetFileDialogWindow().SendMessage(CDM_GETFOLDERPATH, nLength, (LPARAM)lpstrFolderPath);
+ }
+
+ int GetSpec(LPTSTR lpstrSpec, int nLength) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((m_ofn.Flags & OFN_EXPLORER) != 0);
+
+ return (int)GetFileDialogWindow().SendMessage(CDM_GETSPEC, nLength, (LPARAM)lpstrSpec);
+ }
+
+ void SetControlText(int nCtrlID, LPCTSTR lpstrText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((m_ofn.Flags & OFN_EXPLORER) != 0);
+
+ GetFileDialogWindow().SendMessage(CDM_SETCONTROLTEXT, nCtrlID, (LPARAM)lpstrText);
+ }
+
+ void SetDefExt(LPCTSTR lpstrExt)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((m_ofn.Flags & OFN_EXPLORER) != 0);
+
+ GetFileDialogWindow().SendMessage(CDM_SETDEFEXT, 0, (LPARAM)lpstrExt);
+ }
+
+ BOOL GetReadOnlyPref() const // return TRUE if readonly checked
+ {
+ return ((m_ofn.Flags & OFN_READONLY) != 0) ? TRUE : FALSE;
+ }
+
+// Operations
+ void HideControl(int nCtrlID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((m_ofn.Flags & OFN_EXPLORER) != 0);
+
+ GetFileDialogWindow().SendMessage(CDM_HIDECONTROL, nCtrlID);
+ }
+
+// Special override for common dialogs
+ BOOL EndDialog(INT_PTR /*nRetCode*/ = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ GetFileDialogWindow().SendMessage(WM_COMMAND, MAKEWPARAM(IDCANCEL, 0));
+ return TRUE;
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CFileDialogImpl)
+ NOTIFY_CODE_HANDLER(CDN_FILEOK, _OnFileOK)
+ NOTIFY_CODE_HANDLER(CDN_FOLDERCHANGE, _OnFolderChange)
+ NOTIFY_CODE_HANDLER(CDN_HELP, _OnHelp)
+ NOTIFY_CODE_HANDLER(CDN_INITDONE, _OnInitDone)
+ NOTIFY_CODE_HANDLER(CDN_SELCHANGE, _OnSelChange)
+ NOTIFY_CODE_HANDLER(CDN_SHAREVIOLATION, _OnShareViolation)
+ NOTIFY_CODE_HANDLER(CDN_TYPECHANGE, _OnTypeChange)
+#ifndef _WIN32_WCE
+ NOTIFY_CODE_HANDLER(CDN_INCLUDEITEM, _OnIncludeItem)
+#endif // !_WIN32_WCE
+ END_MSG_MAP()
+
+ LRESULT _OnFileOK(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ return !pT->OnFileOK((LPOFNOTIFY)pnmh);
+ }
+
+ LRESULT _OnFolderChange(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ pT->OnFolderChange((LPOFNOTIFY)pnmh);
+ return 0;
+ }
+
+ LRESULT _OnHelp(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ pT->OnHelp((LPOFNOTIFY)pnmh);
+ return 0;
+ }
+
+ LRESULT _OnInitDone(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ pT->OnInitDone((LPOFNOTIFY)pnmh);
+ return 0;
+ }
+
+ LRESULT _OnSelChange(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ pT->OnSelChange((LPOFNOTIFY)pnmh);
+ return 0;
+ }
+
+ LRESULT _OnShareViolation(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ return pT->OnShareViolation((LPOFNOTIFY)pnmh);
+ }
+
+ LRESULT _OnTypeChange(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ pT->OnTypeChange((LPOFNOTIFY)pnmh);
+ return 0;
+ }
+
+#ifndef _WIN32_WCE
+ LRESULT _OnIncludeItem(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ T* pT = static_cast<T*>(this);
+ return pT->OnIncludeItem((LPOFNOTIFYEX)pnmh);
+ }
+#endif // !_WIN32_WCE
+
+// Overrideables
+ BOOL OnFileOK(LPOFNOTIFY /*lpon*/)
+ {
+ return TRUE;
+ }
+
+ void OnFolderChange(LPOFNOTIFY /*lpon*/)
+ {
+ }
+
+ void OnHelp(LPOFNOTIFY /*lpon*/)
+ {
+ }
+
+ void OnInitDone(LPOFNOTIFY /*lpon*/)
+ {
+ }
+
+ void OnSelChange(LPOFNOTIFY /*lpon*/)
+ {
+ }
+
+ int OnShareViolation(LPOFNOTIFY /*lpon*/)
+ {
+ return 0;
+ }
+
+ void OnTypeChange(LPOFNOTIFY /*lpon*/)
+ {
+ }
+
+#ifndef _WIN32_WCE
+ BOOL OnIncludeItem(LPOFNOTIFYEX /*lponex*/)
+ {
+ return TRUE; // include item
+ }
+#endif // !_WIN32_WCE
+};
+
+class CFileDialog : public CFileDialogImpl<CFileDialog>
+{
+public:
+ CFileDialog(BOOL bOpenFileDialog, // TRUE for FileOpen, FALSE for FileSaveAs
+ LPCTSTR lpszDefExt = NULL,
+ LPCTSTR lpszFileName = NULL,
+ DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
+ LPCTSTR lpszFilter = NULL,
+ HWND hWndParent = NULL)
+ : CFileDialogImpl<CFileDialog>(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, hWndParent)
+ { }
+
+ // override base class map and references to handlers
+ DECLARE_EMPTY_MSG_MAP()
+};
+
+#if defined(__AYGSHELL_H__) && (_WIN32_WCE >= 0x0501)
+class CFileDialogEx : public CFileDialogImpl<CFileDialogEx>
+{
+public:
+ CFileDialogEx( // Supports only FileOpen
+ LPCTSTR lpszDefExt = NULL,
+ LPCTSTR lpszFileName = NULL,
+ DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
+ OFN_EXFLAG ExFlags = OFN_EXFLAG_THUMBNAILVIEW,
+ OFN_SORTORDER dwSortOrder = OFN_SORTORDER_AUTO,
+ LPCTSTR lpszFilter = NULL,
+ HWND hWndParent = NULL)
+ : CFileDialogImpl<CFileDialogEx>(TRUE, lpszDefExt, lpszFileName, dwFlags, lpszFilter, hWndParent)
+ {
+ m_ofn.ExFlags = ExFlags;
+ m_ofn.dwSortOrder = dwSortOrder;
+ }
+
+ // override base class map and references to handlers
+ DECLARE_EMPTY_MSG_MAP()
+};
+#endif // defined(__AYGSHELL_H__) && (_WIN32_WCE >= 0x0501)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Multi File Dialog - Multi-select File Open dialog
+
+#ifndef _WIN32_WCE
+
+// The class dynamically resizes the buffer as the file selection changes
+// (as described in Knowledge Base article 131462). It also expands selected
+// shortcut files to take into account the full path of the target file.
+// Note that this doesn't work on Win9x for the old style dialogs, as well as
+// on NT for non-Unicode builds.
+
+#ifndef _WTL_FIXED_OFN_BUFFER_LENGTH
+ #define _WTL_FIXED_OFN_BUFFER_LENGTH 0x10000
+#endif
+
+template <class T>
+class ATL_NO_VTABLE CMultiFileDialogImpl : public CFileDialogImpl< T >
+{
+public:
+ mutable LPCTSTR m_pNextFile;
+#ifndef _UNICODE
+ bool m_bIsNT;
+#endif
+
+ CMultiFileDialogImpl(
+ LPCTSTR lpszDefExt = NULL,
+ LPCTSTR lpszFileName = NULL,
+ DWORD dwFlags = OFN_HIDEREADONLY,
+ LPCTSTR lpszFilter = NULL,
+ HWND hWndParent = NULL)
+ : CFileDialogImpl<T>(TRUE, lpszDefExt, lpszFileName, dwFlags, lpszFilter, hWndParent),
+ m_pNextFile(NULL)
+ {
+ m_ofn.Flags |= OFN_ALLOWMULTISELECT; // Force multiple selection mode
+
+#ifndef _UNICODE
+ OSVERSIONINFO ovi = { sizeof(ovi) };
+ ::GetVersionEx(&ovi);
+ m_bIsNT = (ovi.dwPlatformId == VER_PLATFORM_WIN32_NT);
+ if (m_bIsNT)
+ {
+ // On NT platforms, GetOpenFileNameA thunks to GetOpenFileNameW and there
+ // is absolutely nothing we can do except to start off with a large buffer.
+ ATLVERIFY(ResizeFilenameBuffer(_WTL_FIXED_OFN_BUFFER_LENGTH));
+ }
+#endif
+ }
+
+ ~CMultiFileDialogImpl()
+ {
+ if (m_ofn.lpstrFile != m_szFileName) // Free the buffer if we allocated it
+ delete[] m_ofn.lpstrFile;
+ }
+
+// Operations
+ // Get the directory that the files were chosen from.
+ // The function returns the number of characters copied, not including the terminating zero.
+ // If the buffer is NULL, the function returns the required size, in characters, including the terminating zero.
+ // If the function fails, the return value is zero.
+ int GetDirectory(LPTSTR pBuffer, int nBufLen) const
+ {
+ if (m_ofn.lpstrFile == NULL)
+ return 0;
+
+ LPCTSTR pStr = m_ofn.lpstrFile;
+ int nLength = lstrlen(pStr);
+ if (pStr[nLength + 1] == 0)
+ {
+ // The OFN buffer contains a single item so extract its path.
+ LPCTSTR pSep = _strrchr(pStr, _T('\\'));
+ if (pSep != NULL)
+ nLength = (int)(DWORD_PTR)(pSep - pStr);
+ }
+
+ int nRet = 0;
+ if (pBuffer == NULL) // If the buffer is NULL, return the required length
+ {
+ nRet = nLength + 1;
+ }
+ else if (nBufLen > nLength)
+ {
+ SecureHelper::strncpy_x(pBuffer, nBufLen, pStr, nLength);
+ nRet = nLength;
+ }
+
+ return nRet;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ bool GetDirectory(_CSTRING_NS::CString& strDir) const
+ {
+ bool bRet = false;
+
+ int nLength = GetDirectory(NULL, 0);
+ if (nLength > 0)
+ {
+ bRet = (GetDirectory(strDir.GetBuffer(nLength), nLength) > 0);
+ strDir.ReleaseBuffer(nLength - 1);
+ }
+
+ return bRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ // Get the first filename as a pointer into the buffer.
+ LPCTSTR GetFirstFileName() const
+ {
+ if (m_ofn.lpstrFile == NULL)
+ return NULL;
+
+ m_pNextFile = NULL; // Reset internal buffer pointer
+
+ LPCTSTR pStr = m_ofn.lpstrFile;
+ int nLength = lstrlen(pStr);
+ if (pStr[nLength + 1] != 0)
+ {
+ // Multiple items were selected. The first string is the directory,
+ // so skip forwards to the second string.
+ pStr += nLength + 1;
+
+ // Set up m_pNext so it points to the second item (or null).
+ m_pNextFile = pStr;
+ GetNextFileName();
+ }
+ else
+ {
+ // A single item was selected. Skip forward past the path.
+ LPCTSTR pSep = _strrchr(pStr, _T('\\'));
+ if (pSep != NULL)
+ pStr = pSep + 1;
+ }
+
+ return pStr;
+ }
+
+ // Get the next filename as a pointer into the buffer.
+ LPCTSTR GetNextFileName() const
+ {
+ if (m_pNextFile == NULL)
+ return NULL;
+
+ LPCTSTR pStr = m_pNextFile;
+ // Set "m_pNextFile" to point to the next file name, or null if we
+ // have reached the last file in the list.
+ int nLength = lstrlen(pStr);
+ m_pNextFile = (pStr[nLength + 1] != 0) ? &pStr[nLength + 1] : NULL;
+
+ return pStr;
+ }
+
+ // Get the first filename as a full path.
+ // The function returns the number of characters copied, not including the terminating zero.
+ // If the buffer is NULL, the function returns the required size, in characters, including the terminating zero.
+ // If the function fails, the return value is zero.
+ int GetFirstPathName(LPTSTR pBuffer, int nBufLen) const
+ {
+ LPCTSTR pStr = GetFirstFileName();
+ int nLengthDir = GetDirectory(NULL, 0);
+ if((pStr == NULL) || (nLengthDir == 0))
+ return 0;
+
+ // Figure out the required length.
+ int nLengthTotal = nLengthDir + lstrlen(pStr);
+
+ int nRet = 0;
+ if(pBuffer == NULL) // If the buffer is NULL, return the required length
+ {
+ nRet = nLengthTotal + 1;
+ }
+ else if (nBufLen > nLengthTotal) // If the buffer is big enough, go ahead and construct the path
+ {
+ GetDirectory(pBuffer, nBufLen);
+ SecureHelper::strcat_x(pBuffer, nBufLen, _T("\\"));
+ SecureHelper::strcat_x(pBuffer, nBufLen, pStr);
+ nRet = nLengthTotal;
+ }
+
+ return nRet;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ bool GetFirstPathName(_CSTRING_NS::CString& strPath) const
+ {
+ bool bRet = false;
+
+ int nLength = GetFirstPathName(NULL, 0);
+ if (nLength > 0)
+ {
+ bRet = (GetFirstPathName(strPath.GetBuffer(nLength), nLength) > 0);
+ strPath.ReleaseBuffer(nLength - 1);
+ }
+
+ return bRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ // Get the next filename as a full path.
+ // The function returns the number of characters copied, not including the terminating zero.
+ // If the buffer is NULL, the function returns the required size, in characters, including the terminating zero.
+ // If the function fails, the return value is zero.
+ // The internal position marker is moved forward only if the function succeeds and the buffer was large enough.
+ int GetNextPathName(LPTSTR pBuffer, int nBufLen) const
+ {
+ if (m_pNextFile == NULL)
+ return 0;
+
+ int nRet = 0;
+ LPCTSTR pStr = m_pNextFile;
+ // Does the filename contain a backslash?
+ if (_strrchr(pStr, _T('\\')) != NULL)
+ {
+ // Yes, so we'll assume it's a full path.
+ int nLength = lstrlen(pStr);
+
+ if (pBuffer == NULL) // If the buffer is NULL, return the required length
+ {
+ nRet = nLength + 1;
+ }
+ else if (nBufLen > nLength) // The buffer is big enough, so go ahead and copy the filename
+ {
+ SecureHelper::strcpy_x(pBuffer, nBufLen, GetNextFileName());
+ nRet = nBufLen;
+ }
+ }
+ else
+ {
+ // The filename is relative, so construct the full path.
+ int nLengthDir = GetDirectory(NULL, 0);
+ if (nLengthDir > 0)
+ {
+ // Calculate the required space.
+ int nLengthTotal = nLengthDir + lstrlen(pStr);
+
+ if(pBuffer == NULL) // If the buffer is NULL, return the required length
+ {
+ nRet = nLengthTotal + 1;
+ }
+ else if (nBufLen > nLengthTotal) // If the buffer is big enough, go ahead and construct the path
+ {
+ GetDirectory(pBuffer, nBufLen);
+ SecureHelper::strcat_x(pBuffer, nBufLen, _T("\\"));
+ SecureHelper::strcat_x(pBuffer, nBufLen, GetNextFileName());
+ nRet = nLengthTotal;
+ }
+ }
+ }
+
+ return nRet;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ bool GetNextPathName(_CSTRING_NS::CString& strPath) const
+ {
+ bool bRet = false;
+
+ int nLength = GetNextPathName(NULL, 0);
+ if (nLength > 0)
+ {
+ bRet = (GetNextPathName(strPath.GetBuffer(nLength), nLength) > 0);
+ strPath.ReleaseBuffer(nLength - 1);
+ }
+
+ return bRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+// Implementation
+ bool ResizeFilenameBuffer(DWORD dwLength)
+ {
+ if (dwLength > m_ofn.nMaxFile)
+ {
+ // Free the old buffer.
+ if (m_ofn.lpstrFile != m_szFileName)
+ {
+ delete[] m_ofn.lpstrFile;
+ m_ofn.lpstrFile = NULL;
+ m_ofn.nMaxFile = 0;
+ }
+
+ // Allocate the new buffer.
+ LPTSTR lpstrBuff = NULL;
+ ATLTRY(lpstrBuff = new TCHAR[dwLength]);
+ if (lpstrBuff != NULL)
+ {
+ m_ofn.lpstrFile = lpstrBuff;
+ m_ofn.lpstrFile[0] = 0;
+ m_ofn.nMaxFile = dwLength;
+ }
+ }
+
+ return (m_ofn.lpstrFile != NULL);
+ }
+
+ void OnSelChange(LPOFNOTIFY /*lpon*/)
+ {
+#ifndef _UNICODE
+ // There is no point resizing the buffer in ANSI builds running on NT.
+ if (m_bIsNT)
+ return;
+#endif
+
+ // Get the buffer length required to hold the spec.
+ int nLength = GetSpec(NULL, 0);
+ if (nLength <= 1)
+ return; // no files are selected, presumably
+
+ // Add room for the directory, and an extra terminating zero.
+ nLength += GetFolderPath(NULL, 0) + 1;
+
+ if (!ResizeFilenameBuffer(nLength))
+ {
+ ATLASSERT(FALSE);
+ return;
+ }
+
+ // If we are not following links then our work is done.
+ if ((m_ofn.Flags & OFN_NODEREFERENCELINKS) != 0)
+ return;
+
+ // Get the file spec, which is the text in the edit control.
+ if (GetSpec(m_ofn.lpstrFile, m_ofn.nMaxFile) <= 0)
+ return;
+
+ // Get the ID-list of the current folder.
+ int nBytes = GetFolderIDList(NULL, 0);
+ CTempBuffer<ITEMIDLIST> idlist;
+ idlist.AllocateBytes(nBytes);
+ if ((nBytes <= 0) || (GetFolderIDList(idlist, nBytes) <= 0))
+ return;
+
+ // First bind to the desktop folder, then to the current folder.
+ ATL::CComPtr<IShellFolder> pDesktop, pFolder;
+ if (FAILED(::SHGetDesktopFolder(&pDesktop)))
+ return;
+ if (FAILED(pDesktop->BindToObject(idlist, NULL, IID_IShellFolder, (void**)&pFolder)))
+ return;
+
+ // Work through the file spec, looking for quoted filenames. If we find a shortcut file, then
+ // we need to add enough extra buffer space to hold its target path.
+ DWORD nExtraChars = 0;
+ bool bInsideQuotes = false;
+ LPCTSTR pAnchor = m_ofn.lpstrFile;
+ LPCTSTR pChar = m_ofn.lpstrFile;
+ for ( ; *pChar; ++pChar)
+ {
+ // Look for quotation marks.
+ if (*pChar == _T('\"'))
+ {
+ // We are either entering or leaving a passage of quoted text.
+ bInsideQuotes = !bInsideQuotes;
+
+ // Is it an opening or closing quote?
+ if (bInsideQuotes)
+ {
+ // We found an opening quote, so set "pAnchor" to the following character.
+ pAnchor = pChar + 1;
+ }
+ else // closing quote
+ {
+ // Each quoted entity should be shorter than MAX_PATH.
+ if (pChar - pAnchor >= MAX_PATH)
+ return;
+
+ // Get the ID-list and attributes of the file.
+ USES_CONVERSION;
+ int nFileNameLength = (int)(DWORD_PTR)(pChar - pAnchor);
+ TCHAR szFileName[MAX_PATH];
+ SecureHelper::strncpy_x(szFileName, MAX_PATH, pAnchor, nFileNameLength);
+ LPITEMIDLIST pidl = NULL;
+ DWORD dwAttrib = SFGAO_LINK;
+ if (SUCCEEDED(pFolder->ParseDisplayName(NULL, NULL, T2W(szFileName), NULL, &pidl, &dwAttrib)))
+ {
+ // Is it a shortcut file?
+ if (dwAttrib & SFGAO_LINK)
+ {
+ // Bind to its IShellLink interface.
+ ATL::CComPtr<IShellLink> pLink;
+ if (SUCCEEDED(pFolder->BindToObject(pidl, NULL, IID_IShellLink, (void**)&pLink)))
+ {
+ // Get the shortcut's target path.
+ TCHAR szPath[MAX_PATH];
+ if (SUCCEEDED(pLink->GetPath(szPath, MAX_PATH, NULL, 0)))
+ {
+ // If the target path is longer than the shortcut name, then add on the number
+ // of extra characters that are required.
+ int nNewLength = lstrlen(szPath);
+ if (nNewLength > nFileNameLength)
+ nExtraChars += nNewLength - nFileNameLength;
+ }
+ }
+ }
+
+ // Free the ID-list returned by ParseDisplayName.
+ ::CoTaskMemFree(pidl);
+ }
+ }
+ }
+ }
+
+ // If we need more space for shortcut targets, then reallocate.
+ if (nExtraChars > 0)
+ ATLVERIFY(ResizeFilenameBuffer(m_ofn.nMaxFile + nExtraChars));
+ }
+
+ // Helper for _ATL_MIN_CRT
+ static const TCHAR* _strrchr(const TCHAR* p, TCHAR ch)
+ {
+#ifndef _ATL_MIN_CRT
+ return _tcsrchr(p, ch);
+#else // _ATL_MIN_CRT
+ const TCHAR* lpsz = NULL;
+ while (*p != 0)
+ {
+ if (*p == ch)
+ lpsz = p;
+ p = ::CharNext(p);
+ }
+ return lpsz;
+#endif // _ATL_MIN_CRT
+ }
+};
+
+class CMultiFileDialog : public CMultiFileDialogImpl<CMultiFileDialog>
+{
+public:
+ CMultiFileDialog(
+ LPCTSTR lpszDefExt = NULL,
+ LPCTSTR lpszFileName = NULL,
+ DWORD dwFlags = OFN_HIDEREADONLY,
+ LPCTSTR lpszFilter = NULL,
+ HWND hWndParent = NULL)
+ : CMultiFileDialogImpl<CMultiFileDialog>(lpszDefExt, lpszFileName, dwFlags, lpszFilter, hWndParent)
+ { }
+
+ BEGIN_MSG_MAP(CMultiFileDialog)
+ CHAIN_MSG_MAP(CMultiFileDialogImpl<CMultiFileDialog>)
+ END_MSG_MAP()
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Shell File Dialog - new Shell File Open and Save dialogs in Vista
+
+// Note: Use GetPtr() to access dialog interface methods.
+// Example:
+// CShellFileOpenDialog dlg;
+// dlg.GetPtr()->SetTitle(L"MyFileOpenDialog");
+
+#if (_WIN32_WINNT >= 0x0600) && !defined(_WIN32_WCE)
+
+///////////////////////////////////////////////////////////////////////////////
+// CShellFileDialogImpl - base class for CShellFileOpenDialogImpl and CShellFileSaveDialogImpl
+
+template <class T>
+class ATL_NO_VTABLE CShellFileDialogImpl : public IFileDialogEvents
+{
+public:
+// Operations
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ INT_PTR nRet = -1;
+
+ T* pT = static_cast<T*>(this);
+ if(pT->m_spFileDlg == NULL)
+ {
+ ATLASSERT(FALSE);
+ return nRet;
+ }
+
+ DWORD dwCookie = 0;
+ pT->_Advise(dwCookie);
+
+ HRESULT hRet = pT->m_spFileDlg->Show(hWndParent);
+ if(SUCCEEDED(hRet))
+ nRet = IDOK;
+ else if(hRet == HRESULT_FROM_WIN32(ERROR_CANCELLED))
+ nRet = IDCANCEL;
+ else
+ ATLASSERT(FALSE); // error
+
+ pT->_Unadvise(dwCookie);
+
+ return nRet;
+ }
+
+ bool IsNull() const
+ {
+ const T* pT = static_cast<const T*>(this);
+ return (pT->m_spFileDlg == NULL);
+ }
+
+// Operations - get file path after dialog returns
+ HRESULT GetFilePath(LPWSTR lpstrFilePath, int cchLength)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg != NULL);
+
+ ATL::CComPtr<IShellItem> spItem;
+ HRESULT hRet = pT->m_spFileDlg->GetResult(&spItem);
+
+ if(SUCCEEDED(hRet))
+ hRet = GetFileNameFromShellItem(spItem, SIGDN_FILESYSPATH, lpstrFilePath, cchLength);
+
+ return hRet;
+ }
+
+ HRESULT GetFileTitle(LPWSTR lpstrFileTitle, int cchLength)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg != NULL);
+
+ ATL::CComPtr<IShellItem> spItem;
+ HRESULT hRet = pT->m_spFileDlg->GetResult(&spItem);
+
+ if(SUCCEEDED(hRet))
+ hRet = GetFileNameFromShellItem(spItem, SIGDN_NORMALDISPLAY, lpstrFileTitle, cchLength);
+
+ return hRet;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ HRESULT GetFilePath(_CSTRING_NS::CString& strFilePath)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg != NULL);
+
+ ATL::CComPtr<IShellItem> spItem;
+ HRESULT hRet = pT->m_spFileDlg->GetResult(&spItem);
+
+ if(SUCCEEDED(hRet))
+ hRet = GetFileNameFromShellItem(spItem, SIGDN_FILESYSPATH, strFilePath);
+
+ return hRet;
+ }
+
+ HRESULT GetFileTitle(_CSTRING_NS::CString& strFileTitle)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg != NULL);
+
+ ATL::CComPtr<IShellItem> spItem;
+ HRESULT hRet = pT->m_spFileDlg->GetResult(&spItem);
+
+ if(SUCCEEDED(hRet))
+ hRet = GetFileNameFromShellItem(spItem, SIGDN_NORMALDISPLAY, strFileTitle);
+
+ return hRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+// Helpers for IShellItem
+ static HRESULT GetFileNameFromShellItem(IShellItem* pShellItem, SIGDN type, LPWSTR lpstr, int cchLength)
+ {
+ ATLASSERT(pShellItem != NULL);
+
+ LPWSTR lpstrName = NULL;
+ HRESULT hRet = pShellItem->GetDisplayName(type, &lpstrName);
+
+ if(SUCCEEDED(hRet))
+ {
+ if(lstrlenW(lpstrName) < cchLength)
+ {
+ SecureHelper::strcpyW_x(lpstr, cchLength, lpstrName);
+ }
+ else
+ {
+ ATLASSERT(FALSE);
+ hRet = DISP_E_BUFFERTOOSMALL;
+ }
+
+ ::CoTaskMemFree(lpstrName);
+ }
+
+ return hRet;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ static HRESULT GetFileNameFromShellItem(IShellItem* pShellItem, SIGDN type, _CSTRING_NS::CString& str)
+ {
+ ATLASSERT(pShellItem != NULL);
+
+ LPWSTR lpstrName = NULL;
+ HRESULT hRet = pShellItem->GetDisplayName(type, &lpstrName);
+
+ if(SUCCEEDED(hRet))
+ {
+ str = lpstrName;
+ ::CoTaskMemFree(lpstrName);
+ }
+
+ return hRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+// Implementation
+ void _Advise(DWORD& dwCookie)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg != NULL);
+ HRESULT hRet = pT->m_spFileDlg->Advise((IFileDialogEvents*)this, &dwCookie);
+ ATLVERIFY(SUCCEEDED(hRet));
+ }
+
+ void _Unadvise(DWORD dwCookie)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg != NULL);
+ HRESULT hRet = pT->m_spFileDlg->Unadvise(dwCookie);
+ ATLVERIFY(SUCCEEDED(hRet));
+ }
+
+ void _Init(LPCWSTR lpszFileName, DWORD dwOptions, LPCWSTR lpszDefExt, const COMDLG_FILTERSPEC* arrFilterSpec, UINT uFilterSpecCount)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg != NULL);
+
+ HRESULT hRet = E_FAIL;
+
+ if(lpszFileName != NULL)
+ {
+ hRet = pT->m_spFileDlg->SetFileName(lpszFileName);
+ ATLASSERT(SUCCEEDED(hRet));
+ }
+
+ hRet = pT->m_spFileDlg->SetOptions(dwOptions);
+ ATLASSERT(SUCCEEDED(hRet));
+
+ if(lpszDefExt != NULL)
+ {
+ hRet = pT->m_spFileDlg->SetDefaultExtension(lpszDefExt);
+ ATLASSERT(SUCCEEDED(hRet));
+ }
+
+ if(arrFilterSpec != NULL && uFilterSpecCount != 0U)
+ {
+ hRet = pT->m_spFileDlg->SetFileTypes(uFilterSpecCount, arrFilterSpec);
+ ATLASSERT(SUCCEEDED(hRet));
+ }
+ }
+
+// Implementation - IUnknown interface
+ STDMETHOD(QueryInterface)(REFIID riid, void** ppvObject)
+ {
+ if(ppvObject == NULL)
+ return E_POINTER;
+
+ T* pT = static_cast<T*>(this);
+ if(IsEqualGUID(riid, IID_IUnknown) || IsEqualGUID(riid, IID_IFileDialogEvents))
+ {
+ *ppvObject = (IFileDialogEvents*)pT;
+ // AddRef() not needed
+ return S_OK;
+ }
+
+ return E_NOINTERFACE;
+ }
+
+ virtual ULONG STDMETHODCALLTYPE AddRef()
+ {
+ return 1;
+ }
+
+ virtual ULONG STDMETHODCALLTYPE Release()
+ {
+ return 1;
+ }
+
+// Implementation - IFileDialogEvents interface
+ virtual HRESULT STDMETHODCALLTYPE IFileDialogEvents::OnFileOk(IFileDialog* pfd)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg.IsEqualObject(pfd));
+ pfd; // avoid level 4 warning
+ return pT->OnFileOk();
+ }
+
+ virtual HRESULT STDMETHODCALLTYPE IFileDialogEvents::OnFolderChanging(IFileDialog* pfd, IShellItem* psiFolder)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg.IsEqualObject(pfd));
+ pfd; // avoid level 4 warning
+ return pT->OnFolderChanging(psiFolder);
+ }
+
+ virtual HRESULT STDMETHODCALLTYPE IFileDialogEvents::OnFolderChange(IFileDialog* pfd)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg.IsEqualObject(pfd));
+ pfd; // avoid level 4 warning
+ return pT->OnFolderChange();
+ }
+
+ virtual HRESULT STDMETHODCALLTYPE IFileDialogEvents::OnSelectionChange(IFileDialog* pfd)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg.IsEqualObject(pfd));
+ pfd; // avoid level 4 warning
+ return pT->OnSelectionChange();
+ }
+
+ virtual HRESULT STDMETHODCALLTYPE IFileDialogEvents::OnShareViolation(IFileDialog* pfd, IShellItem* psi, FDE_SHAREVIOLATION_RESPONSE* pResponse)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg.IsEqualObject(pfd));
+ pfd; // avoid level 4 warning
+ return pT->OnShareViolation(psi, pResponse);
+ }
+
+ virtual HRESULT STDMETHODCALLTYPE IFileDialogEvents::OnTypeChange(IFileDialog* pfd)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg.IsEqualObject(pfd));
+ pfd; // avoid level 4 warning
+ return pT->OnTypeChange();
+ }
+
+ virtual HRESULT STDMETHODCALLTYPE IFileDialogEvents::OnOverwrite(IFileDialog* pfd, IShellItem* psi, FDE_OVERWRITE_RESPONSE* pResponse)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_spFileDlg.IsEqualObject(pfd));
+ pfd; // avoid level 4 warning
+ return pT->OnOverwrite(psi, pResponse);
+ }
+
+// Overrideables - Event handlers
+ HRESULT OnFileOk()
+ {
+ return E_NOTIMPL;
+ }
+
+ HRESULT OnFolderChanging(IShellItem* /*psiFolder*/)
+ {
+ return E_NOTIMPL;
+ }
+
+ HRESULT OnFolderChange()
+ {
+ return E_NOTIMPL;
+ }
+
+ HRESULT OnSelectionChange()
+ {
+ return E_NOTIMPL;
+ }
+
+ HRESULT OnShareViolation(IShellItem* /*psi*/, FDE_SHAREVIOLATION_RESPONSE* /*pResponse*/)
+ {
+ return E_NOTIMPL;
+ }
+
+ HRESULT OnTypeChange()
+ {
+ return E_NOTIMPL;
+ }
+
+ HRESULT OnOverwrite(IShellItem* /*psi*/, FDE_OVERWRITE_RESPONSE* /*pResponse*/)
+ {
+ return E_NOTIMPL;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CShellFileOpenDialogImpl - implements new Shell File Open dialog
+
+template <class T>
+class ATL_NO_VTABLE CShellFileOpenDialogImpl : public CShellFileDialogImpl< T >
+{
+public:
+ ATL::CComPtr<IFileOpenDialog> m_spFileDlg;
+
+ CShellFileOpenDialogImpl(LPCWSTR lpszFileName = NULL,
+ DWORD dwOptions = FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST,
+ LPCWSTR lpszDefExt = NULL,
+ const COMDLG_FILTERSPEC* arrFilterSpec = NULL,
+ UINT uFilterSpecCount = 0U)
+ {
+ HRESULT hRet = m_spFileDlg.CoCreateInstance(CLSID_FileOpenDialog);
+
+ if(SUCCEEDED(hRet))
+ _Init(lpszFileName, dwOptions, lpszDefExt, arrFilterSpec, uFilterSpecCount);
+ }
+
+ IFileOpenDialog* GetPtr()
+ {
+ return m_spFileDlg;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CShellFileOpenDialog - new Shell File Open dialog without events
+
+class CShellFileOpenDialog : public CShellFileOpenDialogImpl<CShellFileOpenDialog>
+{
+public:
+ CShellFileOpenDialog(LPCWSTR lpszFileName = NULL,
+ DWORD dwOptions = FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_FILEMUSTEXIST,
+ LPCWSTR lpszDefExt = NULL,
+ const COMDLG_FILTERSPEC* arrFilterSpec = NULL,
+ UINT uFilterSpecCount = 0U) : CShellFileOpenDialogImpl<CShellFileOpenDialog>(lpszFileName, dwOptions, lpszDefExt, arrFilterSpec, uFilterSpecCount)
+ { }
+
+// Implementation (remove _Advise/_Unadvise code using template magic)
+ void _Advise(DWORD& /*dwCookie*/)
+ { }
+
+ void _Unadvise(DWORD /*dwCookie*/)
+ { }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CShellFileSaveDialogImpl - implements new Shell File Save dialog
+
+template <class T>
+class ATL_NO_VTABLE CShellFileSaveDialogImpl : public CShellFileDialogImpl< T >
+{
+public:
+ ATL::CComPtr<IFileSaveDialog> m_spFileDlg;
+
+ CShellFileSaveDialogImpl(LPCWSTR lpszFileName = NULL,
+ DWORD dwOptions = FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_OVERWRITEPROMPT,
+ LPCWSTR lpszDefExt = NULL,
+ const COMDLG_FILTERSPEC* arrFilterSpec = NULL,
+ UINT uFilterSpecCount = 0U)
+ {
+ HRESULT hRet = m_spFileDlg.CoCreateInstance(CLSID_FileSaveDialog);
+
+ if(SUCCEEDED(hRet))
+ _Init(lpszFileName, dwOptions, lpszDefExt, arrFilterSpec, uFilterSpecCount);
+ }
+
+ IFileSaveDialog* GetPtr()
+ {
+ return m_spFileDlg;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CShellFileSaveDialog - new Shell File Save dialog without events
+
+class CShellFileSaveDialog : public CShellFileSaveDialogImpl<CShellFileSaveDialog>
+{
+public:
+ CShellFileSaveDialog(LPCWSTR lpszFileName = NULL,
+ DWORD dwOptions = FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST | FOS_OVERWRITEPROMPT,
+ LPCWSTR lpszDefExt = NULL,
+ const COMDLG_FILTERSPEC* arrFilterSpec = NULL,
+ UINT uFilterSpecCount = 0U) : CShellFileSaveDialogImpl<CShellFileSaveDialog>(lpszFileName, dwOptions, lpszDefExt, arrFilterSpec, uFilterSpecCount)
+ { }
+
+// Implementation (remove _Advise/_Unadvise code using template magic)
+ void _Advise(DWORD& /*dwCookie*/)
+ { }
+
+ void _Unadvise(DWORD /*dwCookie*/)
+ { }
+};
+
+#endif // (_WIN32_WINNT >= 0x0600) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CFolderDialogImpl - used for browsing for a folder
+
+#ifndef _WIN32_WCE
+
+template <class T>
+class ATL_NO_VTABLE CFolderDialogImpl
+{
+public:
+ BROWSEINFO m_bi;
+ LPCTSTR m_lpstrInitialFolder;
+ LPCITEMIDLIST m_pidlInitialSelection;
+ bool m_bExpandInitialSelection;
+ TCHAR m_szFolderDisplayName[MAX_PATH];
+ TCHAR m_szFolderPath[MAX_PATH];
+ LPITEMIDLIST m_pidlSelected;
+ HWND m_hWnd; // used only in the callback function
+
+// Constructor
+ CFolderDialogImpl(HWND hWndParent = NULL, LPCTSTR lpstrTitle = NULL, UINT uFlags = BIF_RETURNONLYFSDIRS) :
+ m_lpstrInitialFolder(NULL), m_pidlInitialSelection(NULL), m_bExpandInitialSelection(false), m_pidlSelected(NULL), m_hWnd(NULL)
+ {
+ memset(&m_bi, 0, sizeof(m_bi)); // initialize structure to 0/NULL
+
+ m_bi.hwndOwner = hWndParent;
+ m_bi.pidlRoot = NULL;
+ m_bi.pszDisplayName = m_szFolderDisplayName;
+ m_bi.lpszTitle = lpstrTitle;
+ m_bi.ulFlags = uFlags;
+ m_bi.lpfn = BrowseCallbackProc;
+ m_bi.lParam = (LPARAM)static_cast<T*>(this);
+
+ m_szFolderPath[0] = 0;
+ m_szFolderDisplayName[0] = 0;
+ }
+
+ ~CFolderDialogImpl()
+ {
+ ::CoTaskMemFree(m_pidlSelected);
+ }
+
+// Operations
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ if(m_bi.hwndOwner == NULL) // set only if not specified before
+ m_bi.hwndOwner = hWndParent;
+
+ // Clear out any previous results
+ m_szFolderPath[0] = 0;
+ m_szFolderDisplayName[0] = 0;
+ ::CoTaskMemFree(m_pidlSelected);
+
+ INT_PTR nRet = IDCANCEL;
+ m_pidlSelected = ::SHBrowseForFolder(&m_bi);
+
+ if(m_pidlSelected != NULL)
+ {
+ nRet = IDOK;
+
+ // If BIF_RETURNONLYFSDIRS is set, we try to get the filesystem path.
+ // Otherwise, the caller must handle the ID-list directly.
+ if((m_bi.ulFlags & BIF_RETURNONLYFSDIRS) != 0)
+ {
+ if(::SHGetPathFromIDList(m_pidlSelected, m_szFolderPath) == FALSE)
+ nRet = IDCANCEL;
+ }
+ }
+
+ return nRet;
+ }
+
+ // Methods to call before DoModal
+ void SetInitialFolder(LPCTSTR lpstrInitialFolder, bool bExpand = true)
+ {
+ // lpstrInitialFolder may be a file if BIF_BROWSEINCLUDEFILES is specified
+ m_lpstrInitialFolder = lpstrInitialFolder;
+ m_bExpandInitialSelection = bExpand;
+ }
+
+ void SetInitialSelection(LPCITEMIDLIST pidl, bool bExpand = true)
+ {
+ m_pidlInitialSelection = pidl;
+ m_bExpandInitialSelection = bExpand;
+ }
+
+ // Methods to call after DoModal
+ LPITEMIDLIST GetSelectedItem(bool bDetach = false)
+ {
+ LPITEMIDLIST pidl = m_pidlSelected;
+ if(bDetach)
+ m_pidlSelected = NULL;
+
+ return pidl;
+ }
+
+ LPCTSTR GetFolderPath() const
+ {
+ return m_szFolderPath;
+ }
+
+ LPCTSTR GetFolderDisplayName() const
+ {
+ return m_szFolderDisplayName;
+ }
+
+ int GetFolderImageIndex() const
+ {
+ return m_bi.iImage;
+ }
+
+// Callback function and overrideables
+ static int CALLBACK BrowseCallbackProc(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
+ {
+#ifndef BFFM_VALIDATEFAILED
+ #ifdef UNICODE
+ const int BFFM_VALIDATEFAILED = 4;
+ #else
+ const int BFFM_VALIDATEFAILED = 3;
+ #endif
+#endif // !BFFM_VALIDATEFAILED
+#ifndef BFFM_IUNKNOWN
+ const int BFFM_IUNKNOWN = 5;
+#endif // !BFFM_IUNKNOWN
+#ifndef BIF_NEWDIALOGSTYLE
+ const UINT BIF_NEWDIALOGSTYLE = 0x0040;
+#endif // !BIF_NEWDIALOGSTYLE
+
+ int nRet = 0;
+ T* pT = (T*)lpData;
+ bool bClear = false;
+ if(pT->m_hWnd == NULL)
+ {
+ pT->m_hWnd = hWnd;
+ bClear = true;
+ }
+ else
+ {
+ ATLASSERT(pT->m_hWnd == hWnd);
+ }
+
+ switch(uMsg)
+ {
+ case BFFM_INITIALIZED:
+ // Set initial selection
+ // Note that m_pidlInitialSelection, if set, takes precedence over m_lpstrInitialFolder
+ if(pT->m_pidlInitialSelection != NULL)
+ pT->SetSelection(pT->m_pidlInitialSelection);
+ else if(pT->m_lpstrInitialFolder != NULL)
+ pT->SetSelection(pT->m_lpstrInitialFolder);
+
+ // Expand initial selection if appropriate
+ if(pT->m_bExpandInitialSelection && ((pT->m_bi.ulFlags & BIF_NEWDIALOGSTYLE) != 0))
+ {
+ if(pT->m_pidlInitialSelection != NULL)
+ pT->SetExpanded(pT->m_pidlInitialSelection);
+ else if(pT->m_lpstrInitialFolder != NULL)
+ pT->SetExpanded(pT->m_lpstrInitialFolder);
+ }
+ pT->OnInitialized();
+ break;
+ case BFFM_SELCHANGED:
+ pT->OnSelChanged((LPITEMIDLIST)lParam);
+ break;
+ case BFFM_VALIDATEFAILED:
+ nRet = pT->OnValidateFailed((LPCTSTR)lParam);
+ break;
+ case BFFM_IUNKNOWN:
+ pT->OnIUnknown((IUnknown*)lParam);
+ break;
+ default:
+ ATLTRACE2(atlTraceUI, 0, _T("Unknown message received in CFolderDialogImpl::BrowseCallbackProc\n"));
+ break;
+ }
+
+ if(bClear)
+ pT->m_hWnd = NULL;
+ return nRet;
+ }
+
+ void OnInitialized()
+ {
+ }
+
+ void OnSelChanged(LPITEMIDLIST /*pItemIDList*/)
+ {
+ }
+
+ int OnValidateFailed(LPCTSTR /*lpstrFolderPath*/)
+ {
+ return 1; // 1=continue, 0=EndDialog
+ }
+
+ void OnIUnknown(IUnknown* /*pUnknown*/)
+ {
+ }
+
+ // Commands - valid to call only from handlers
+ void EnableOK(BOOL bEnable)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, BFFM_ENABLEOK, 0, bEnable);
+ }
+
+ void SetSelection(LPCITEMIDLIST pItemIDList)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, BFFM_SETSELECTION, FALSE, (LPARAM)pItemIDList);
+ }
+
+ void SetSelection(LPCTSTR lpstrFolderPath)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, BFFM_SETSELECTION, TRUE, (LPARAM)lpstrFolderPath);
+ }
+
+ void SetStatusText(LPCTSTR lpstrText)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, BFFM_SETSTATUSTEXT, 0, (LPARAM)lpstrText);
+ }
+
+ void SetOKText(LPCTSTR lpstrOKText)
+ {
+#ifndef BFFM_SETOKTEXT
+ const UINT BFFM_SETOKTEXT = WM_USER + 105;
+#endif
+ ATLASSERT(m_hWnd != NULL);
+ USES_CONVERSION;
+ LPCWSTR lpstr = T2CW(lpstrOKText);
+ ::SendMessage(m_hWnd, BFFM_SETOKTEXT, 0, (LPARAM)lpstr);
+ }
+
+ void SetExpanded(LPCITEMIDLIST pItemIDList)
+ {
+#ifndef BFFM_SETEXPANDED
+ const UINT BFFM_SETEXPANDED = WM_USER + 106;
+#endif
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, BFFM_SETEXPANDED, FALSE, (LPARAM)pItemIDList);
+ }
+
+ void SetExpanded(LPCTSTR lpstrFolderPath)
+ {
+#ifndef BFFM_SETEXPANDED
+ const UINT BFFM_SETEXPANDED = WM_USER + 106;
+#endif
+ ATLASSERT(m_hWnd != NULL);
+ USES_CONVERSION;
+ LPCWSTR lpstr = T2CW(lpstrFolderPath);
+ ::SendMessage(m_hWnd, BFFM_SETEXPANDED, TRUE, (LPARAM)lpstr);
+ }
+};
+
+class CFolderDialog : public CFolderDialogImpl<CFolderDialog>
+{
+public:
+ CFolderDialog(HWND hWndParent = NULL, LPCTSTR lpstrTitle = NULL, UINT uFlags = BIF_RETURNONLYFSDIRS)
+ : CFolderDialogImpl<CFolderDialog>(hWndParent, lpstrTitle, uFlags)
+ { }
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CCommonDialogImplBase - base class for common dialog classes
+
+class ATL_NO_VTABLE CCommonDialogImplBase : public ATL::CWindowImplBase
+{
+public:
+ static UINT_PTR APIENTRY HookProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+ {
+ if(uMsg != WM_INITDIALOG)
+ return 0;
+ CCommonDialogImplBase* pT = (CCommonDialogImplBase*)ModuleHelper::ExtractCreateWndData();
+ ATLASSERT(pT != NULL);
+ ATLASSERT(pT->m_hWnd == NULL);
+ ATLASSERT(::IsWindow(hWnd));
+ // subclass dialog's window
+ if(!pT->SubclassWindow(hWnd))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("Subclassing a common dialog failed\n"));
+ return 0;
+ }
+ // check message map for WM_INITDIALOG handler
+ LRESULT lRes = 0;
+ if(pT->ProcessWindowMessage(pT->m_hWnd, uMsg, wParam, lParam, lRes, 0) == FALSE)
+ return 0;
+ return lRes;
+ }
+
+// Special override for common dialogs
+ BOOL EndDialog(INT_PTR /*nRetCode*/ = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ SendMessage(WM_COMMAND, MAKEWPARAM(IDABORT, 0));
+ return TRUE;
+ }
+
+// Implementation - try to override these, to prevent errors
+ HWND Create(HWND, ATL::_U_RECT, LPCTSTR, DWORD, DWORD, ATL::_U_MENUorID, ATOM, LPVOID)
+ {
+ ATLASSERT(FALSE); // should not be called
+ return NULL;
+ }
+
+ static LRESULT CALLBACK StartWindowProc(HWND /*hWnd*/, UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/)
+ {
+ ATLASSERT(FALSE); // should not be called
+ return 0;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CFontDialogImpl - font selection dialog
+
+#ifndef _WIN32_WCE
+
+template <class T>
+class ATL_NO_VTABLE CFontDialogImpl : public CCommonDialogImplBase
+{
+public:
+ enum { _cchStyleName = 64 };
+
+ CHOOSEFONT m_cf;
+ TCHAR m_szStyleName[_cchStyleName]; // contains style name after return
+ LOGFONT m_lf; // default LOGFONT to store the info
+
+// Constructors
+ CFontDialogImpl(LPLOGFONT lplfInitial = NULL,
+ DWORD dwFlags = CF_EFFECTS | CF_SCREENFONTS,
+ HDC hDCPrinter = NULL,
+ HWND hWndParent = NULL)
+ {
+ memset(&m_cf, 0, sizeof(m_cf));
+ memset(&m_lf, 0, sizeof(m_lf));
+ memset(&m_szStyleName, 0, sizeof(m_szStyleName));
+
+ m_cf.lStructSize = sizeof(m_cf);
+ m_cf.hwndOwner = hWndParent;
+ m_cf.rgbColors = RGB(0, 0, 0);
+ m_cf.lpszStyle = (LPTSTR)&m_szStyleName;
+ m_cf.Flags = dwFlags | CF_ENABLEHOOK;
+ m_cf.lpfnHook = (LPCFHOOKPROC)T::HookProc;
+
+ if(lplfInitial != NULL)
+ {
+ m_cf.lpLogFont = lplfInitial;
+ m_cf.Flags |= CF_INITTOLOGFONTSTRUCT;
+ m_lf = *lplfInitial;
+ }
+ else
+ {
+ m_cf.lpLogFont = &m_lf;
+ }
+
+ if(hDCPrinter != NULL)
+ {
+ m_cf.hDC = hDCPrinter;
+ m_cf.Flags |= CF_PRINTERFONTS;
+ }
+ }
+
+// Operations
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ ATLASSERT((m_cf.Flags & CF_ENABLEHOOK) != 0);
+ ATLASSERT(m_cf.lpfnHook != NULL); // can still be a user hook
+
+ if(m_cf.hwndOwner == NULL) // set only if not specified before
+ m_cf.hwndOwner = hWndParent;
+
+ ATLASSERT(m_hWnd == NULL);
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, (CCommonDialogImplBase*)this);
+
+ BOOL bRet = ::ChooseFont(&m_cf);
+
+ m_hWnd = NULL;
+
+ if(bRet) // copy logical font from user's initialization buffer (if needed)
+ SecureHelper::memcpy_x(&m_lf, sizeof(m_lf), m_cf.lpLogFont, sizeof(m_lf));
+
+ return bRet ? IDOK : IDCANCEL;
+ }
+
+ // works only when the dialog is dislayed or after
+ void GetCurrentFont(LPLOGFONT lplf) const
+ {
+ ATLASSERT(lplf != NULL);
+
+ if(m_hWnd != NULL)
+ ::SendMessage(m_hWnd, WM_CHOOSEFONT_GETLOGFONT, 0, (LPARAM)lplf);
+ else
+ *lplf = m_lf;
+ }
+
+ // works only when the dialog is dislayed or before
+#ifndef _WIN32_WCE
+ void SetLogFont(LPLOGFONT lplf)
+ {
+ ATLASSERT(lplf != NULL);
+#ifndef WM_CHOOSEFONT_SETLOGFONT
+ const UINT WM_CHOOSEFONT_SETLOGFONT = (WM_USER + 101);
+#endif
+ if(m_hWnd != NULL)
+ {
+ ::SendMessage(m_hWnd, WM_CHOOSEFONT_SETLOGFONT, 0, (LPARAM)lplf);
+ }
+ else
+ {
+ m_lf = *lplf;
+ m_cf.Flags |= CF_INITTOLOGFONTSTRUCT;
+ }
+ }
+
+ void SetFlags(DWORD dwFlags)
+ {
+#ifndef WM_CHOOSEFONT_SETFLAGS
+ const UINT WM_CHOOSEFONT_SETFLAGS = (WM_USER + 102);
+#endif
+ if(m_hWnd != NULL)
+ {
+ CHOOSEFONT cf = { sizeof(CHOOSEFONT) };
+ cf.Flags = dwFlags;
+ ::SendMessage(m_hWnd, WM_CHOOSEFONT_SETFLAGS, 0, (LPARAM)&cf);
+ }
+ else
+ {
+ m_cf.Flags = dwFlags;
+ }
+ }
+#endif // !_WIN32_WCE
+
+ // Helpers for parsing information after successful return
+ LPCTSTR GetFaceName() const // return the face name of the font
+ {
+ return (LPCTSTR)m_cf.lpLogFont->lfFaceName;
+ }
+
+ LPCTSTR GetStyleName() const // return the style name of the font
+ {
+ return m_cf.lpszStyle;
+ }
+
+ int GetSize() const // return the pt size of the font
+ {
+ return m_cf.iPointSize;
+ }
+
+ COLORREF GetColor() const // return the color of the font
+ {
+ return m_cf.rgbColors;
+ }
+
+ int GetWeight() const // return the chosen font weight
+ {
+ return (int)m_cf.lpLogFont->lfWeight;
+ }
+
+ BOOL IsStrikeOut() const // return TRUE if strikeout
+ {
+ return (m_cf.lpLogFont->lfStrikeOut) ? TRUE : FALSE;
+ }
+
+ BOOL IsUnderline() const // return TRUE if underline
+ {
+ return (m_cf.lpLogFont->lfUnderline) ? TRUE : FALSE;
+ }
+
+ BOOL IsBold() const // return TRUE if bold font
+ {
+ return (m_cf.lpLogFont->lfWeight == FW_BOLD) ? TRUE : FALSE;
+ }
+
+ BOOL IsItalic() const // return TRUE if italic font
+ {
+ return m_cf.lpLogFont->lfItalic ? TRUE : FALSE;
+ }
+};
+
+class CFontDialog : public CFontDialogImpl<CFontDialog>
+{
+public:
+ CFontDialog(LPLOGFONT lplfInitial = NULL,
+ DWORD dwFlags = CF_EFFECTS | CF_SCREENFONTS,
+ HDC hDCPrinter = NULL,
+ HWND hWndParent = NULL)
+ : CFontDialogImpl<CFontDialog>(lplfInitial, dwFlags, hDCPrinter, hWndParent)
+ { }
+
+ DECLARE_EMPTY_MSG_MAP()
+};
+
+#endif // _WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRichEditFontDialogImpl - font selection for the Rich Edit ctrl
+
+#if defined(_RICHEDIT_) && !defined(_WIN32_WCE)
+
+template <class T>
+class ATL_NO_VTABLE CRichEditFontDialogImpl : public CFontDialogImpl< T >
+{
+public:
+ CRichEditFontDialogImpl(const CHARFORMAT& charformat,
+ DWORD dwFlags = CF_SCREENFONTS,
+ HDC hDCPrinter = NULL,
+ HWND hWndParent = NULL)
+ : CFontDialogImpl< T >(NULL, dwFlags, hDCPrinter, hWndParent)
+ {
+ m_cf.Flags |= CF_INITTOLOGFONTSTRUCT;
+ m_cf.Flags |= FillInLogFont(charformat);
+ m_cf.lpLogFont = &m_lf;
+
+ if((charformat.dwMask & CFM_COLOR) != 0)
+ m_cf.rgbColors = charformat.crTextColor;
+ }
+
+ void GetCharFormat(CHARFORMAT& cf) const
+ {
+ USES_CONVERSION;
+ cf.dwEffects = 0;
+ cf.dwMask = 0;
+ if((m_cf.Flags & CF_NOSTYLESEL) == 0)
+ {
+ cf.dwMask |= CFM_BOLD | CFM_ITALIC;
+ cf.dwEffects |= IsBold() ? CFE_BOLD : 0;
+ cf.dwEffects |= IsItalic() ? CFE_ITALIC : 0;
+ }
+ if((m_cf.Flags & CF_NOSIZESEL) == 0)
+ {
+ cf.dwMask |= CFM_SIZE;
+ // GetSize() returns in tenths of points so mulitply by 2 to get twips
+ cf.yHeight = GetSize() * 2;
+ }
+
+ if((m_cf.Flags & CF_NOFACESEL) == 0)
+ {
+ cf.dwMask |= CFM_FACE;
+ cf.bPitchAndFamily = m_cf.lpLogFont->lfPitchAndFamily;
+#if (_RICHEDIT_VER >= 0x0200)
+ SecureHelper::strcpy_x(cf.szFaceName, _countof(cf.szFaceName), GetFaceName());
+#else // !(_RICHEDIT_VER >= 0x0200)
+ SecureHelper::strcpyA_x(cf.szFaceName, _countof(cf.szFaceName), T2A((LPTSTR)(LPCTSTR)GetFaceName()));
+#endif // !(_RICHEDIT_VER >= 0x0200)
+ }
+
+ if((m_cf.Flags & CF_EFFECTS) != 0)
+ {
+ cf.dwMask |= CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR;
+ cf.dwEffects |= IsUnderline() ? CFE_UNDERLINE : 0;
+ cf.dwEffects |= IsStrikeOut() ? CFE_STRIKEOUT : 0;
+ cf.crTextColor = GetColor();
+ }
+ if((m_cf.Flags & CF_NOSCRIPTSEL) == 0)
+ {
+ cf.bCharSet = m_cf.lpLogFont->lfCharSet;
+ cf.dwMask |= CFM_CHARSET;
+ }
+ cf.yOffset = 0;
+ }
+
+ DWORD FillInLogFont(const CHARFORMAT& cf)
+ {
+ USES_CONVERSION;
+ DWORD dwFlags = 0;
+ if((cf.dwMask & CFM_SIZE) != 0)
+ {
+ HDC hDC = ::CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
+ LONG yPerInch = ::GetDeviceCaps(hDC, LOGPIXELSY);
+ m_lf.lfHeight = -(int)((cf.yHeight * yPerInch) / 1440);
+ }
+ else
+ m_lf.lfHeight = 0;
+
+ m_lf.lfWidth = 0;
+ m_lf.lfEscapement = 0;
+ m_lf.lfOrientation = 0;
+
+ if((cf.dwMask & (CFM_ITALIC | CFM_BOLD)) == (CFM_ITALIC | CFM_BOLD))
+ {
+ m_lf.lfWeight = ((cf.dwEffects & CFE_BOLD) != 0) ? FW_BOLD : FW_NORMAL;
+ m_lf.lfItalic = (BYTE)(((cf.dwEffects & CFE_ITALIC) != 0) ? TRUE : FALSE);
+ }
+ else
+ {
+ dwFlags |= CF_NOSTYLESEL;
+ m_lf.lfWeight = FW_DONTCARE;
+ m_lf.lfItalic = FALSE;
+ }
+
+ if((cf.dwMask & (CFM_UNDERLINE | CFM_STRIKEOUT | CFM_COLOR)) == (CFM_UNDERLINE|CFM_STRIKEOUT|CFM_COLOR))
+ {
+ dwFlags |= CF_EFFECTS;
+ m_lf.lfUnderline = (BYTE)(((cf.dwEffects & CFE_UNDERLINE) != 0) ? TRUE : FALSE);
+ m_lf.lfStrikeOut = (BYTE)(((cf.dwEffects & CFE_STRIKEOUT) != 0) ? TRUE : FALSE);
+ }
+ else
+ {
+ m_lf.lfUnderline = (BYTE)FALSE;
+ m_lf.lfStrikeOut = (BYTE)FALSE;
+ }
+
+ if((cf.dwMask & CFM_CHARSET) != 0)
+ m_lf.lfCharSet = cf.bCharSet;
+ else
+ dwFlags |= CF_NOSCRIPTSEL;
+ m_lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
+ m_lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
+ m_lf.lfQuality = DEFAULT_QUALITY;
+ if((cf.dwMask & CFM_FACE) != 0)
+ {
+ m_lf.lfPitchAndFamily = cf.bPitchAndFamily;
+#if (_RICHEDIT_VER >= 0x0200)
+ SecureHelper::strcpy_x(m_lf.lfFaceName, _countof(m_lf.lfFaceName), cf.szFaceName);
+#else // !(_RICHEDIT_VER >= 0x0200)
+ SecureHelper::strcpy_x(m_lf.lfFaceName, _countof(m_lf.lfFaceName), A2T((LPSTR)cf.szFaceName));
+#endif // !(_RICHEDIT_VER >= 0x0200)
+ }
+ else
+ {
+ m_lf.lfPitchAndFamily = DEFAULT_PITCH|FF_DONTCARE;
+ m_lf.lfFaceName[0] = (TCHAR)0;
+ }
+ return dwFlags;
+ }
+};
+
+class CRichEditFontDialog : public CRichEditFontDialogImpl<CRichEditFontDialog>
+{
+public:
+ CRichEditFontDialog(const CHARFORMAT& charformat,
+ DWORD dwFlags = CF_SCREENFONTS,
+ HDC hDCPrinter = NULL,
+ HWND hWndParent = NULL)
+ : CRichEditFontDialogImpl<CRichEditFontDialog>(charformat, dwFlags, hDCPrinter, hWndParent)
+ { }
+
+ DECLARE_EMPTY_MSG_MAP()
+};
+
+#endif // defined(_RICHEDIT_) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CColorDialogImpl - color selection
+
+#if !defined(_WIN32_WCE) || ((_WIN32_WCE > 420) && !(defined(WIN32_PLATFORM_WFSP) && (_WIN32_WCE > 0x0500)))
+
+#ifdef _WIN32_WCE
+ #pragma comment(lib, "commdlg.lib")
+
+ #ifndef SETRGBSTRING
+ #define SETRGBSTRING _T("commdlg_SetRGBColor")
+ #endif
+
+ #ifndef COLOROKSTRING
+ #define COLOROKSTRING _T("commdlg_ColorOK")
+ #endif
+#endif
+
+template <class T>
+class ATL_NO_VTABLE CColorDialogImpl : public CCommonDialogImplBase
+{
+public:
+ CHOOSECOLOR m_cc;
+
+// Constructor
+ CColorDialogImpl(COLORREF clrInit = 0, DWORD dwFlags = 0, HWND hWndParent = NULL)
+ {
+ memset(&m_cc, 0, sizeof(m_cc));
+
+ m_cc.lStructSize = sizeof(m_cc);
+ m_cc.lpCustColors = GetCustomColors();
+ m_cc.hwndOwner = hWndParent;
+ m_cc.Flags = dwFlags | CC_ENABLEHOOK;
+ m_cc.lpfnHook = (LPCCHOOKPROC)T::HookProc;
+
+ if(clrInit != 0)
+ {
+ m_cc.rgbResult = clrInit;
+ m_cc.Flags |= CC_RGBINIT;
+ }
+ }
+
+// Operations
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ ATLASSERT((m_cc.Flags & CC_ENABLEHOOK) != 0);
+ ATLASSERT(m_cc.lpfnHook != NULL); // can still be a user hook
+
+ if(m_cc.hwndOwner == NULL) // set only if not specified before
+ m_cc.hwndOwner = hWndParent;
+
+ ATLASSERT(m_hWnd == NULL);
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, (CCommonDialogImplBase*)this);
+
+ BOOL bRet = ::ChooseColor(&m_cc);
+
+ m_hWnd = NULL;
+
+ return bRet ? IDOK : IDCANCEL;
+ }
+
+ // Set the current color while dialog is displayed
+ void SetCurrentColor(COLORREF clr)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ SendMessage(_GetSetRGBMessage(), 0, (LPARAM)clr);
+ }
+
+ // Get the selected color after DoModal returns, or in OnColorOK
+ COLORREF GetColor() const
+ {
+ return m_cc.rgbResult;
+ }
+
+// Special override for the color dialog
+ static UINT_PTR APIENTRY HookProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+ {
+ if(uMsg != WM_INITDIALOG && uMsg != _GetColorOKMessage())
+ return 0;
+
+ LPCHOOSECOLOR lpCC = (LPCHOOSECOLOR)lParam;
+ CCommonDialogImplBase* pT = NULL;
+
+ if(uMsg == WM_INITDIALOG)
+ {
+ pT = (CCommonDialogImplBase*)ModuleHelper::ExtractCreateWndData();
+ lpCC->lCustData = (LPARAM)pT;
+ ATLASSERT(pT != NULL);
+ ATLASSERT(pT->m_hWnd == NULL);
+ ATLASSERT(::IsWindow(hWnd));
+ // subclass dialog's window
+ if(!pT->SubclassWindow(hWnd))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("Subclassing a Color common dialog failed\n"));
+ return 0;
+ }
+ }
+ else if(uMsg == _GetColorOKMessage())
+ {
+ pT = (CCommonDialogImplBase*)lpCC->lCustData;
+ ATLASSERT(pT != NULL);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ }
+
+ // pass to the message map
+ LRESULT lRes;
+ if(pT->ProcessWindowMessage(pT->m_hWnd, uMsg, wParam, lParam, lRes, 0) == FALSE)
+ return 0;
+ return lRes;
+ }
+
+// Helpers
+ static COLORREF* GetCustomColors()
+ {
+ static COLORREF rgbCustomColors[16] =
+ {
+ RGB(255, 255, 255), RGB(255, 255, 255),
+ RGB(255, 255, 255), RGB(255, 255, 255),
+ RGB(255, 255, 255), RGB(255, 255, 255),
+ RGB(255, 255, 255), RGB(255, 255, 255),
+ RGB(255, 255, 255), RGB(255, 255, 255),
+ RGB(255, 255, 255), RGB(255, 255, 255),
+ RGB(255, 255, 255), RGB(255, 255, 255),
+ RGB(255, 255, 255), RGB(255, 255, 255),
+ };
+
+ return rgbCustomColors;
+ }
+
+ static UINT _GetSetRGBMessage()
+ {
+ static UINT uSetRGBMessage = 0;
+ if(uSetRGBMessage == 0)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CColorDialogImpl::_GetSetRGBMessage.\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(uSetRGBMessage == 0)
+ uSetRGBMessage = ::RegisterWindowMessage(SETRGBSTRING);
+
+ lock.Unlock();
+ }
+ ATLASSERT(uSetRGBMessage != 0);
+ return uSetRGBMessage;
+ }
+
+ static UINT _GetColorOKMessage()
+ {
+ static UINT uColorOKMessage = 0;
+ if(uColorOKMessage == 0)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CColorDialogImpl::_GetColorOKMessage.\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(uColorOKMessage == 0)
+ uColorOKMessage = ::RegisterWindowMessage(COLOROKSTRING);
+
+ lock.Unlock();
+ }
+ ATLASSERT(uColorOKMessage != 0);
+ return uColorOKMessage;
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CColorDialogImpl)
+ MESSAGE_HANDLER(_GetColorOKMessage(), _OnColorOK)
+ END_MSG_MAP()
+
+ LRESULT _OnColorOK(UINT, WPARAM, LPARAM, BOOL&)
+ {
+ T* pT = static_cast<T*>(this);
+ return pT->OnColorOK();
+ }
+
+// Overrideable
+ BOOL OnColorOK() // validate color
+ {
+ return FALSE;
+ }
+};
+
+class CColorDialog : public CColorDialogImpl<CColorDialog>
+{
+public:
+ CColorDialog(COLORREF clrInit = 0, DWORD dwFlags = 0, HWND hWndParent = NULL)
+ : CColorDialogImpl<CColorDialog>(clrInit, dwFlags, hWndParent)
+ { }
+
+ // override base class map and references to handlers
+ DECLARE_EMPTY_MSG_MAP()
+};
+
+#endif // !defined(_WIN32_WCE) || ((_WIN32_WCE > 420) && !(defined(WIN32_PLATFORM_WFSP) && (_WIN32_WCE > 0x0500)))
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPrintDialogImpl - used for Print... and PrintSetup...
+
+#ifndef _WIN32_WCE
+
+// global helper
+static HDC _AtlCreateDC(HGLOBAL hDevNames, HGLOBAL hDevMode)
+{
+ if(hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDevNames = (LPDEVNAMES)::GlobalLock(hDevNames);
+ LPDEVMODE lpDevMode = (hDevMode != NULL) ? (LPDEVMODE)::GlobalLock(hDevMode) : NULL;
+
+ if(lpDevNames == NULL)
+ return NULL;
+
+ HDC hDC = ::CreateDC((LPCTSTR)lpDevNames + lpDevNames->wDriverOffset,
+ (LPCTSTR)lpDevNames + lpDevNames->wDeviceOffset,
+ (LPCTSTR)lpDevNames + lpDevNames->wOutputOffset,
+ lpDevMode);
+
+ ::GlobalUnlock(hDevNames);
+ if(hDevMode != NULL)
+ ::GlobalUnlock(hDevMode);
+ return hDC;
+}
+
+template <class T>
+class ATL_NO_VTABLE CPrintDialogImpl : public CCommonDialogImplBase
+{
+public:
+ // print dialog parameter block (note this is a reference)
+ PRINTDLG& m_pd;
+
+// Constructors
+ CPrintDialogImpl(BOOL bPrintSetupOnly = FALSE, // TRUE for Print Setup, FALSE for Print Dialog
+ DWORD dwFlags = PD_ALLPAGES | PD_USEDEVMODECOPIES | PD_NOPAGENUMS | PD_NOSELECTION,
+ HWND hWndParent = NULL)
+ : m_pd(m_pdActual)
+ {
+ memset(&m_pdActual, 0, sizeof(m_pdActual));
+
+ m_pd.lStructSize = sizeof(m_pdActual);
+ m_pd.hwndOwner = hWndParent;
+ m_pd.Flags = (dwFlags | PD_ENABLEPRINTHOOK | PD_ENABLESETUPHOOK);
+ m_pd.lpfnPrintHook = (LPPRINTHOOKPROC)T::HookProc;
+ m_pd.lpfnSetupHook = (LPSETUPHOOKPROC)T::HookProc;
+
+ if(bPrintSetupOnly)
+ m_pd.Flags |= PD_PRINTSETUP;
+ else
+ m_pd.Flags |= PD_RETURNDC;
+
+ m_pd.Flags &= ~PD_RETURNIC; // do not support information context
+ }
+
+// Operations
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ ATLASSERT((m_pd.Flags & PD_ENABLEPRINTHOOK) != 0);
+ ATLASSERT((m_pd.Flags & PD_ENABLESETUPHOOK) != 0);
+ ATLASSERT(m_pd.lpfnPrintHook != NULL); // can still be a user hook
+ ATLASSERT(m_pd.lpfnSetupHook != NULL); // can still be a user hook
+ ATLASSERT((m_pd.Flags & PD_RETURNDEFAULT) == 0); // use GetDefaults for this
+
+ if(m_pd.hwndOwner == NULL) // set only if not specified before
+ m_pd.hwndOwner = hWndParent;
+
+ ATLASSERT(m_hWnd == NULL);
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, (CCommonDialogImplBase*)this);
+
+ BOOL bRet = ::PrintDlg(&m_pd);
+
+ m_hWnd = NULL;
+
+ return bRet ? IDOK : IDCANCEL;
+ }
+
+ // GetDefaults will not display a dialog but will get device defaults
+ BOOL GetDefaults()
+ {
+ m_pd.Flags |= PD_RETURNDEFAULT;
+ ATLASSERT(m_pd.hDevMode == NULL); // must be NULL
+ ATLASSERT(m_pd.hDevNames == NULL); // must be NULL
+
+ return ::PrintDlg(&m_pd);
+ }
+
+ // Helpers for parsing information after successful return num. copies requested
+ int GetCopies() const
+ {
+ if((m_pd.Flags & PD_USEDEVMODECOPIES) != 0)
+ {
+ LPDEVMODE lpDevMode = GetDevMode();
+ return (lpDevMode != NULL) ? lpDevMode->dmCopies : -1;
+ }
+
+ return m_pd.nCopies;
+ }
+
+ BOOL PrintCollate() const // TRUE if collate checked
+ {
+ return ((m_pd.Flags & PD_COLLATE) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL PrintSelection() const // TRUE if printing selection
+ {
+ return ((m_pd.Flags & PD_SELECTION) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL PrintAll() const // TRUE if printing all pages
+ {
+ return (!PrintRange() && !PrintSelection()) ? TRUE : FALSE;
+ }
+
+ BOOL PrintRange() const // TRUE if printing page range
+ {
+ return ((m_pd.Flags & PD_PAGENUMS) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL PrintToFile() const // TRUE if printing to a file
+ {
+ return ((m_pd.Flags & PD_PRINTTOFILE) != 0) ? TRUE : FALSE;
+ }
+
+ int GetFromPage() const // starting page if valid
+ {
+ return PrintRange() ? m_pd.nFromPage : -1;
+ }
+
+ int GetToPage() const // ending page if valid
+ {
+ return PrintRange() ? m_pd.nToPage : -1;
+ }
+
+ LPDEVMODE GetDevMode() const // return DEVMODE
+ {
+ if(m_pd.hDevMode == NULL)
+ return NULL;
+
+ return (LPDEVMODE)::GlobalLock(m_pd.hDevMode);
+ }
+
+ LPCTSTR GetDriverName() const // return driver name
+ {
+ if(m_pd.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_pd.hDevNames);
+ if(lpDev == NULL)
+ return NULL;
+
+ return (LPCTSTR)lpDev + lpDev->wDriverOffset;
+ }
+
+ LPCTSTR GetDeviceName() const // return device name
+ {
+ if(m_pd.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_pd.hDevNames);
+ if(lpDev == NULL)
+ return NULL;
+
+ return (LPCTSTR)lpDev + lpDev->wDeviceOffset;
+ }
+
+ LPCTSTR GetPortName() const // return output port name
+ {
+ if(m_pd.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_pd.hDevNames);
+ if(lpDev == NULL)
+ return NULL;
+
+ return (LPCTSTR)lpDev + lpDev->wOutputOffset;
+ }
+
+ HDC GetPrinterDC() const // return HDC (caller must delete)
+ {
+ ATLASSERT((m_pd.Flags & PD_RETURNDC) != 0);
+ return m_pd.hDC;
+ }
+
+ // This helper creates a DC based on the DEVNAMES and DEVMODE structures.
+ // This DC is returned, but also stored in m_pd.hDC as though it had been
+ // returned by CommDlg. It is assumed that any previously obtained DC
+ // has been/will be deleted by the user. This may be
+ // used without ever invoking the print/print setup dialogs.
+ HDC CreatePrinterDC()
+ {
+ m_pd.hDC = _AtlCreateDC(m_pd.hDevNames, m_pd.hDevMode);
+ return m_pd.hDC;
+ }
+
+// Implementation
+ PRINTDLG m_pdActual; // the Print/Print Setup need to share this
+
+ // The following handle the case of print setup... from the print dialog
+ CPrintDialogImpl(PRINTDLG& pdInit) : m_pd(pdInit)
+ { }
+
+ BEGIN_MSG_MAP(CPrintDialogImpl)
+#ifdef psh1
+ COMMAND_ID_HANDLER(psh1, OnPrintSetup) // print setup button when print is displayed
+#else // !psh1
+ COMMAND_ID_HANDLER(0x0400, OnPrintSetup) // value from dlgs.h
+#endif // !psh1
+ END_MSG_MAP()
+
+ LRESULT OnPrintSetup(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& /*bHandled*/)
+ {
+ T dlgSetup(m_pd);
+ ModuleHelper::AddCreateWndData(&dlgSetup.m_thunk.cd, (CCommonDialogImplBase*)&dlgSetup);
+ return DefWindowProc(WM_COMMAND, MAKEWPARAM(wID, wNotifyCode), (LPARAM)hWndCtl);
+ }
+};
+
+class CPrintDialog : public CPrintDialogImpl<CPrintDialog>
+{
+public:
+ CPrintDialog(BOOL bPrintSetupOnly = FALSE,
+ DWORD dwFlags = PD_ALLPAGES | PD_USEDEVMODECOPIES | PD_NOPAGENUMS | PD_NOSELECTION,
+ HWND hWndParent = NULL)
+ : CPrintDialogImpl<CPrintDialog>(bPrintSetupOnly, dwFlags, hWndParent)
+ { }
+
+ CPrintDialog(PRINTDLG& pdInit) : CPrintDialogImpl<CPrintDialog>(pdInit)
+ { }
+};
+
+#endif // _WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPrintDialogExImpl - new print dialog for Windows 2000
+
+#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+
+}; // namespace WTL
+
+#include <atlcom.h>
+
+extern "C" const __declspec(selectany) IID IID_IPrintDialogCallback = {0x5852a2c3, 0x6530, 0x11d1, {0xb6, 0xa3, 0x0, 0x0, 0xf8, 0x75, 0x7b, 0xf9}};
+extern "C" const __declspec(selectany) IID IID_IPrintDialogServices = {0x509aaeda, 0x5639, 0x11d1, {0xb6, 0xa1, 0x0, 0x0, 0xf8, 0x75, 0x7b, 0xf9}};
+
+namespace WTL
+{
+
+template <class T>
+class ATL_NO_VTABLE CPrintDialogExImpl :
+ public ATL::CWindow,
+ public ATL::CMessageMap,
+ public IPrintDialogCallback,
+ public ATL::IObjectWithSiteImpl< T >
+{
+public:
+ PRINTDLGEX m_pdex;
+
+// Constructor
+ CPrintDialogExImpl(DWORD dwFlags = PD_ALLPAGES | PD_USEDEVMODECOPIES | PD_NOPAGENUMS | PD_NOSELECTION | PD_NOCURRENTPAGE,
+ HWND hWndParent = NULL)
+ {
+ memset(&m_pdex, 0, sizeof(m_pdex));
+
+ m_pdex.lStructSize = sizeof(PRINTDLGEX);
+ m_pdex.hwndOwner = hWndParent;
+ m_pdex.Flags = dwFlags;
+ m_pdex.nStartPage = START_PAGE_GENERAL;
+ // callback object will be set in DoModal
+
+ m_pdex.Flags &= ~PD_RETURNIC; // do not support information context
+ }
+
+// Operations
+ HRESULT DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ ATLASSERT(m_hWnd == NULL);
+ ATLASSERT((m_pdex.Flags & PD_RETURNDEFAULT) == 0); // use GetDefaults for this
+
+ if(m_pdex.hwndOwner == NULL) // set only if not specified before
+ m_pdex.hwndOwner = hWndParent;
+
+ T* pT = static_cast<T*>(this);
+ m_pdex.lpCallback = (IUnknown*)(IPrintDialogCallback*)pT;
+
+ HRESULT hResult = ::PrintDlgEx(&m_pdex);
+
+ m_hWnd = NULL;
+
+ return hResult;
+ }
+
+ BOOL EndDialog(INT_PTR /*nRetCode*/ = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ SendMessage(WM_COMMAND, MAKEWPARAM(IDABORT, 0));
+ return TRUE;
+ }
+
+ // GetDefaults will not display a dialog but will get device defaults
+ HRESULT GetDefaults()
+ {
+ m_pdex.Flags |= PD_RETURNDEFAULT;
+ ATLASSERT(m_pdex.hDevMode == NULL); // must be NULL
+ ATLASSERT(m_pdex.hDevNames == NULL); // must be NULL
+
+ return ::PrintDlgEx(&m_pdex);
+ }
+
+ // Helpers for parsing information after successful return num. copies requested
+ int GetCopies() const
+ {
+ if((m_pdex.Flags & PD_USEDEVMODECOPIES) != 0)
+ {
+ LPDEVMODE lpDevMode = GetDevMode();
+ return (lpDevMode != NULL) ? lpDevMode->dmCopies : -1;
+ }
+
+ return m_pdex.nCopies;
+ }
+
+ BOOL PrintCollate() const // TRUE if collate checked
+ {
+ return ((m_pdex.Flags & PD_COLLATE) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL PrintSelection() const // TRUE if printing selection
+ {
+ return ((m_pdex.Flags & PD_SELECTION) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL PrintAll() const // TRUE if printing all pages
+ {
+ return (!PrintRange() && !PrintSelection()) ? TRUE : FALSE;
+ }
+
+ BOOL PrintRange() const // TRUE if printing page range
+ {
+ return ((m_pdex.Flags & PD_PAGENUMS) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL PrintToFile() const // TRUE if printing to a file
+ {
+ return ((m_pdex.Flags & PD_PRINTTOFILE) != 0) ? TRUE : FALSE;
+ }
+
+ LPDEVMODE GetDevMode() const // return DEVMODE
+ {
+ if(m_pdex.hDevMode == NULL)
+ return NULL;
+
+ return (LPDEVMODE)::GlobalLock(m_pdex.hDevMode);
+ }
+
+ LPCTSTR GetDriverName() const // return driver name
+ {
+ if(m_pdex.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_pdex.hDevNames);
+ if(lpDev == NULL)
+ return NULL;
+
+ return (LPCTSTR)lpDev + lpDev->wDriverOffset;
+ }
+
+ LPCTSTR GetDeviceName() const // return device name
+ {
+ if(m_pdex.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_pdex.hDevNames);
+ if(lpDev == NULL)
+ return NULL;
+
+ return (LPCTSTR)lpDev + lpDev->wDeviceOffset;
+ }
+
+ LPCTSTR GetPortName() const // return output port name
+ {
+ if(m_pdex.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_pdex.hDevNames);
+ if(lpDev == NULL)
+ return NULL;
+
+ return (LPCTSTR)lpDev + lpDev->wOutputOffset;
+ }
+
+ HDC GetPrinterDC() const // return HDC (caller must delete)
+ {
+ ATLASSERT((m_pdex.Flags & PD_RETURNDC) != 0);
+ return m_pdex.hDC;
+ }
+
+ // This helper creates a DC based on the DEVNAMES and DEVMODE structures.
+ // This DC is returned, but also stored in m_pdex.hDC as though it had been
+ // returned by CommDlg. It is assumed that any previously obtained DC
+ // has been/will be deleted by the user. This may be
+ // used without ever invoking the print/print setup dialogs.
+ HDC CreatePrinterDC()
+ {
+ m_pdex.hDC = _AtlCreateDC(m_pdex.hDevNames, m_pdex.hDevMode);
+ return m_pdex.hDC;
+ }
+
+// Implementation - interfaces
+
+// IUnknown
+ STDMETHOD(QueryInterface)(REFIID riid, void** ppvObject)
+ {
+ if(ppvObject == NULL)
+ return E_POINTER;
+
+ T* pT = static_cast<T*>(this);
+ if(IsEqualGUID(riid, IID_IUnknown) || IsEqualGUID(riid, IID_IPrintDialogCallback))
+ {
+ *ppvObject = (IPrintDialogCallback*)pT;
+ // AddRef() not needed
+ return S_OK;
+ }
+ else if(IsEqualGUID(riid, IID_IObjectWithSite))
+ {
+ *ppvObject = (IObjectWithSite*)pT;
+ // AddRef() not needed
+ return S_OK;
+ }
+
+ return E_NOINTERFACE;
+ }
+
+ virtual ULONG STDMETHODCALLTYPE AddRef()
+ {
+ return 1;
+ }
+
+ virtual ULONG STDMETHODCALLTYPE Release()
+ {
+ return 1;
+ }
+
+// IPrintDialogCallback
+ STDMETHOD(InitDone)()
+ {
+ return S_FALSE;
+ }
+
+ STDMETHOD(SelectionChange)()
+ {
+ return S_FALSE;
+ }
+
+ STDMETHOD(HandleMessage)(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* plResult)
+ {
+ // set up m_hWnd the first time
+ if(m_hWnd == NULL)
+ Attach(hWnd);
+
+ // call message map
+ HRESULT hRet = ProcessWindowMessage(hWnd, uMsg, wParam, lParam, *plResult, 0) ? S_OK : S_FALSE;
+ if(hRet == S_OK && uMsg == WM_NOTIFY) // return in DWLP_MSGRESULT
+ ::SetWindowLongPtr(GetParent(), DWLP_MSGRESULT, (LONG_PTR)*plResult);
+
+ if(uMsg == WM_INITDIALOG && hRet == S_OK && (BOOL)*plResult != FALSE)
+ hRet = S_FALSE;
+
+ return hRet;
+ }
+};
+
+class CPrintDialogEx : public CPrintDialogExImpl<CPrintDialogEx>
+{
+public:
+ CPrintDialogEx(
+ DWORD dwFlags = PD_ALLPAGES | PD_USEDEVMODECOPIES | PD_NOPAGENUMS | PD_NOSELECTION | PD_NOCURRENTPAGE,
+ HWND hWndParent = NULL)
+ : CPrintDialogExImpl<CPrintDialogEx>(dwFlags, hWndParent)
+ { }
+
+ DECLARE_EMPTY_MSG_MAP()
+};
+
+#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPageSetupDialogImpl - Page Setup dialog
+
+#ifndef _WIN32_WCE
+
+template <class T>
+class ATL_NO_VTABLE CPageSetupDialogImpl : public CCommonDialogImplBase
+{
+public:
+ PAGESETUPDLG m_psd;
+ ATL::CWndProcThunk m_thunkPaint;
+
+// Constructors
+ CPageSetupDialogImpl(DWORD dwFlags = PSD_MARGINS | PSD_INWININIINTLMEASURE, HWND hWndParent = NULL)
+ {
+ memset(&m_psd, 0, sizeof(m_psd));
+
+ m_psd.lStructSize = sizeof(m_psd);
+ m_psd.hwndOwner = hWndParent;
+ m_psd.Flags = (dwFlags | PSD_ENABLEPAGESETUPHOOK | PSD_ENABLEPAGEPAINTHOOK);
+ m_psd.lpfnPageSetupHook = (LPPAGESETUPHOOK)T::HookProc;
+ m_thunkPaint.Init((WNDPROC)T::PaintHookProc, this);
+#if (_ATL_VER >= 0x0700)
+ m_psd.lpfnPagePaintHook = (LPPAGEPAINTHOOK)m_thunkPaint.GetWNDPROC();
+#else
+ m_psd.lpfnPagePaintHook = (LPPAGEPAINTHOOK)&(m_thunkPaint.thunk);
+#endif
+ }
+
+ DECLARE_EMPTY_MSG_MAP()
+
+// Attributes
+ LPDEVMODE GetDevMode() const // return DEVMODE
+ {
+ if(m_psd.hDevMode == NULL)
+ return NULL;
+
+ return (LPDEVMODE)::GlobalLock(m_psd.hDevMode);
+ }
+
+ LPCTSTR GetDriverName() const // return driver name
+ {
+ if(m_psd.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_psd.hDevNames);
+ return (LPCTSTR)lpDev + lpDev->wDriverOffset;
+ }
+
+ LPCTSTR GetDeviceName() const // return device name
+ {
+ if(m_psd.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_psd.hDevNames);
+ return (LPCTSTR)lpDev + lpDev->wDeviceOffset;
+ }
+
+ LPCTSTR GetPortName() const // return output port name
+ {
+ if(m_psd.hDevNames == NULL)
+ return NULL;
+
+ LPDEVNAMES lpDev = (LPDEVNAMES)::GlobalLock(m_psd.hDevNames);
+ return (LPCTSTR)lpDev + lpDev->wOutputOffset;
+ }
+
+ HDC CreatePrinterDC()
+ {
+ return _AtlCreateDC(m_psd.hDevNames, m_psd.hDevMode);
+ }
+
+ SIZE GetPaperSize() const
+ {
+ SIZE size;
+ size.cx = m_psd.ptPaperSize.x;
+ size.cy = m_psd.ptPaperSize.y;
+ return size;
+ }
+
+ void GetMargins(LPRECT lpRectMargins, LPRECT lpRectMinMargins) const
+ {
+ if(lpRectMargins != NULL)
+ *lpRectMargins = m_psd.rtMargin;
+ if(lpRectMinMargins != NULL)
+ *lpRectMinMargins = m_psd.rtMinMargin;
+ }
+
+// Operations
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ ATLASSERT((m_psd.Flags & PSD_ENABLEPAGESETUPHOOK) != 0);
+ ATLASSERT((m_psd.Flags & PSD_ENABLEPAGEPAINTHOOK) != 0);
+ ATLASSERT(m_psd.lpfnPageSetupHook != NULL); // can still be a user hook
+ ATLASSERT(m_psd.lpfnPagePaintHook != NULL); // can still be a user hook
+
+ if(m_psd.hwndOwner == NULL) // set only if not specified before
+ m_psd.hwndOwner = hWndParent;
+
+ ATLASSERT(m_hWnd == NULL);
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, (CCommonDialogImplBase*)this);
+
+ BOOL bRet = ::PageSetupDlg(&m_psd);
+
+ m_hWnd = NULL;
+
+ return bRet ? IDOK : IDCANCEL;
+ }
+
+// Implementation
+ static UINT_PTR CALLBACK PaintHookProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+ {
+ T* pT = (T*)hWnd;
+ UINT_PTR uRet = 0;
+ switch(uMsg)
+ {
+ case WM_PSD_PAGESETUPDLG:
+ uRet = pT->PreDrawPage(LOWORD(wParam), HIWORD(wParam), (LPPAGESETUPDLG)lParam);
+ break;
+ case WM_PSD_FULLPAGERECT:
+ case WM_PSD_MINMARGINRECT:
+ case WM_PSD_MARGINRECT:
+ case WM_PSD_GREEKTEXTRECT:
+ case WM_PSD_ENVSTAMPRECT:
+ case WM_PSD_YAFULLPAGERECT:
+ uRet = pT->OnDrawPage(uMsg, (HDC)wParam, (LPRECT)lParam);
+ break;
+ default:
+ ATLTRACE2(atlTraceUI, 0, _T("CPageSetupDialogImpl::PaintHookProc - unknown message received\n"));
+ break;
+ }
+ return uRet;
+ }
+
+// Overridables
+ UINT_PTR PreDrawPage(WORD /*wPaper*/, WORD /*wFlags*/, LPPAGESETUPDLG /*pPSD*/)
+ {
+ // return 1 to prevent any more drawing
+ return 0;
+ }
+
+ UINT_PTR OnDrawPage(UINT /*uMsg*/, HDC /*hDC*/, LPRECT /*lpRect*/)
+ {
+ return 0; // do the default
+ }
+};
+
+class CPageSetupDialog : public CPageSetupDialogImpl<CPageSetupDialog>
+{
+public:
+ CPageSetupDialog(DWORD dwFlags = PSD_MARGINS | PSD_INWININIINTLMEASURE, HWND hWndParent = NULL)
+ : CPageSetupDialogImpl<CPageSetupDialog>(dwFlags, hWndParent)
+ { }
+
+ // override PaintHookProc and references to handlers
+ static UINT_PTR CALLBACK PaintHookProc(HWND, UINT, WPARAM, LPARAM)
+ {
+ return 0;
+ }
+};
+
+#endif // _WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CFindReplaceDialogImpl - Find/FindReplace modeless dialogs
+
+#ifndef _WIN32_WCE
+
+template <class T>
+class ATL_NO_VTABLE CFindReplaceDialogImpl : public CCommonDialogImplBase
+{
+public:
+ enum { _cchFindReplaceBuffer = 128 };
+
+ FINDREPLACE m_fr;
+ TCHAR m_szFindWhat[_cchFindReplaceBuffer];
+ TCHAR m_szReplaceWith[_cchFindReplaceBuffer];
+
+// Constructors
+ CFindReplaceDialogImpl()
+ {
+ memset(&m_fr, 0, sizeof(m_fr));
+ m_szFindWhat[0] = _T('\0');
+ m_szReplaceWith[0] = _T('\0');
+
+ m_fr.lStructSize = sizeof(m_fr);
+ m_fr.Flags = FR_ENABLEHOOK;
+ m_fr.lpfnHook = (LPFRHOOKPROC)T::HookProc;
+ m_fr.lpstrFindWhat = (LPTSTR)m_szFindWhat;
+ m_fr.wFindWhatLen = _cchFindReplaceBuffer;
+ m_fr.lpstrReplaceWith = (LPTSTR)m_szReplaceWith;
+ m_fr.wReplaceWithLen = _cchFindReplaceBuffer;
+ }
+
+ // Note: You must allocate the object on the heap.
+ // If you do not, you must override OnFinalMessage()
+ virtual void OnFinalMessage(HWND /*hWnd*/)
+ {
+ delete this;
+ }
+
+ HWND Create(BOOL bFindDialogOnly, // TRUE for Find, FALSE for FindReplace
+ LPCTSTR lpszFindWhat,
+ LPCTSTR lpszReplaceWith = NULL,
+ DWORD dwFlags = FR_DOWN,
+ HWND hWndParent = NULL)
+ {
+ ATLASSERT((m_fr.Flags & FR_ENABLEHOOK) != 0);
+ ATLASSERT(m_fr.lpfnHook != NULL);
+
+ m_fr.Flags |= dwFlags;
+
+ if(hWndParent == NULL)
+ m_fr.hwndOwner = ::GetActiveWindow();
+ else
+ m_fr.hwndOwner = hWndParent;
+ ATLASSERT(m_fr.hwndOwner != NULL); // must have an owner for modeless dialog
+
+ if(lpszFindWhat != NULL)
+ SecureHelper::strncpy_x(m_szFindWhat, _countof(m_szFindWhat), lpszFindWhat, _TRUNCATE);
+
+ if(lpszReplaceWith != NULL)
+ SecureHelper::strncpy_x(m_szReplaceWith, _countof(m_szReplaceWith), lpszReplaceWith, _TRUNCATE);
+
+ ATLASSERT(m_hWnd == NULL);
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, (CCommonDialogImplBase*)this);
+
+ HWND hWnd = NULL;
+ if(bFindDialogOnly)
+ hWnd = ::FindText(&m_fr);
+ else
+ hWnd = ::ReplaceText(&m_fr);
+
+ ATLASSERT(m_hWnd == hWnd);
+ return hWnd;
+ }
+
+ static const UINT GetFindReplaceMsg()
+ {
+ static const UINT nMsgFindReplace = ::RegisterWindowMessage(FINDMSGSTRING);
+ return nMsgFindReplace;
+ }
+ // call while handling FINDMSGSTRING registered message
+ // to retreive the object
+ static T* PASCAL GetNotifier(LPARAM lParam)
+ {
+ ATLASSERT(lParam != NULL);
+ T* pDlg = (T*)(lParam - offsetof(T, m_fr));
+ return pDlg;
+ }
+
+// Operations
+ // Helpers for parsing information after successful return
+ LPCTSTR GetFindString() const // get find string
+ {
+ return (LPCTSTR)m_fr.lpstrFindWhat;
+ }
+
+ LPCTSTR GetReplaceString() const // get replacement string
+ {
+ return (LPCTSTR)m_fr.lpstrReplaceWith;
+ }
+
+ BOOL SearchDown() const // TRUE if search down, FALSE is up
+ {
+ return ((m_fr.Flags & FR_DOWN) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL FindNext() const // TRUE if command is find next
+ {
+ return ((m_fr.Flags & FR_FINDNEXT) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL MatchCase() const // TRUE if matching case
+ {
+ return ((m_fr.Flags & FR_MATCHCASE) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL MatchWholeWord() const // TRUE if matching whole words only
+ {
+ return ((m_fr.Flags & FR_WHOLEWORD) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL ReplaceCurrent() const // TRUE if replacing current string
+ {
+ return ((m_fr. Flags & FR_REPLACE) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL ReplaceAll() const // TRUE if replacing all occurrences
+ {
+ return ((m_fr.Flags & FR_REPLACEALL) != 0) ? TRUE : FALSE;
+ }
+
+ BOOL IsTerminating() const // TRUE if terminating dialog
+ {
+ return ((m_fr.Flags & FR_DIALOGTERM) != 0) ? TRUE : FALSE ;
+ }
+};
+
+class CFindReplaceDialog : public CFindReplaceDialogImpl<CFindReplaceDialog>
+{
+public:
+ DECLARE_EMPTY_MSG_MAP()
+};
+
+#endif // !_WIN32_WCE
+
+
+/////////////////////////////////////////////////////////////////////////
+// CDialogBaseUnits - Dialog Units helper
+//
+
+class CDialogBaseUnits
+{
+public:
+ SIZE m_sizeUnits;
+
+// Constructors
+ CDialogBaseUnits()
+ {
+ // The base units of the out-dated System Font
+ LONG nDlgBaseUnits = ::GetDialogBaseUnits();
+ m_sizeUnits.cx = LOWORD(nDlgBaseUnits);
+ m_sizeUnits.cy = HIWORD(nDlgBaseUnits);
+ }
+
+ CDialogBaseUnits(HWND hWnd)
+ {
+ if(!InitDialogBaseUnits(hWnd)) {
+ LONG nDlgBaseUnits = ::GetDialogBaseUnits();
+ m_sizeUnits.cx = LOWORD(nDlgBaseUnits);
+ m_sizeUnits.cy = HIWORD(nDlgBaseUnits);
+ }
+ }
+
+ CDialogBaseUnits(HFONT hFont, HWND hWnd = NULL)
+ {
+ if(!InitDialogBaseUnits(hFont, hWnd)) {
+ LONG nDlgBaseUnits = ::GetDialogBaseUnits();
+ m_sizeUnits.cx = LOWORD(nDlgBaseUnits);
+ m_sizeUnits.cy = HIWORD(nDlgBaseUnits);
+ }
+ }
+
+ CDialogBaseUnits(LOGFONT lf, HWND hWnd = NULL)
+ {
+ if(!InitDialogBaseUnits(lf, hWnd)) {
+ LONG nDlgBaseUnits = ::GetDialogBaseUnits();
+ m_sizeUnits.cx = LOWORD(nDlgBaseUnits);
+ m_sizeUnits.cy = HIWORD(nDlgBaseUnits);
+ }
+ }
+
+// Operations
+ BOOL InitDialogBaseUnits(HWND hWnd)
+ {
+ ATLASSERT(::IsWindow(hWnd));
+ RECT rc = { 0, 0, 4, 8 };
+ if(!::MapDialogRect(hWnd, &rc)) return FALSE;
+ m_sizeUnits.cx = rc.right;
+ m_sizeUnits.cy = rc.bottom;
+ return TRUE;
+ }
+
+ BOOL InitDialogBaseUnits(LOGFONT lf, HWND hWnd = NULL)
+ {
+ CFont font;
+ font.CreateFontIndirect(&lf);
+ if(font.IsNull()) return FALSE;
+ return InitDialogBaseUnits(font, hWnd);
+ }
+
+ BOOL InitDialogBaseUnits(HFONT hFont, HWND hWnd = NULL)
+ {
+ ATLASSERT(hFont != NULL);
+ CWindowDC dc = hWnd;
+ TEXTMETRIC tmText = { 0 };
+ SIZE sizeText = { 0 };
+ HFONT hFontOld = dc.SelectFont(hFont);
+ dc.GetTextMetrics(&tmText);
+ m_sizeUnits.cy = tmText.tmHeight + tmText.tmExternalLeading;
+ dc.GetTextExtent(_T("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), 52, &sizeText);
+ m_sizeUnits.cx = (sizeText.cx + 26) / 52;
+ dc.SelectFont(hFontOld);
+ return TRUE;
+ }
+
+ SIZE GetDialogBaseUnits() const
+ {
+ return m_sizeUnits;
+ }
+
+ INT MapDialogPixelsX(INT x) const
+ {
+ return ::MulDiv(x, 4, m_sizeUnits.cx); // Pixels X to DLU
+ }
+
+ INT MapDialogPixelsY(INT y) const
+ {
+ return ::MulDiv(y, 8, m_sizeUnits.cy); // Pixels Y to DLU
+ }
+
+ POINT MapDialogPixels(POINT pt) const
+ {
+ POINT out = { MapDialogPixelsX(pt.x), MapDialogPixelsY(pt.y) };
+ return out;
+ }
+
+ SIZE MapDialogPixels(SIZE input) const
+ {
+ SIZE out = { MapDialogPixelsX(input.cx), MapDialogPixelsY(input.cy) };
+ return out;
+ }
+
+ RECT MapDialogPixels(RECT input) const
+ {
+ RECT out = { MapDialogPixelsX(input.left), MapDialogPixelsY(input.top), MapDialogPixelsX(input.right), MapDialogPixelsY(input.bottom) };
+ return out;
+ }
+
+ INT MapDialogUnitsX(INT x) const
+ {
+ return ::MulDiv(x, m_sizeUnits.cx, 4); // DLU to Pixels X
+ }
+
+ INT MapDialogUnitsY(INT y) const
+ {
+ return ::MulDiv(y, m_sizeUnits.cx, 8); // DLU to Pixels Y
+ }
+
+ POINT MapDialogUnits(POINT pt) const
+ {
+ POINT out = { MapDialogUnitsX(pt.x), MapDialogUnitsY(pt.y) };
+ return out;
+ }
+
+ SIZE MapDialogUnits(SIZE input) const
+ {
+ SIZE out = { MapDialogUnitsX(input.cx), MapDialogUnitsY(input.cy) };
+ return out;
+ }
+
+ RECT MapDialogUnits(RECT input) const
+ {
+ RECT out = { MapDialogUnitsX(input.left), MapDialogUnitsY(input.top), MapDialogUnitsX(input.right), MapDialogUnitsY(input.bottom) };
+ return out;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMemDlgTemplate - in-memory dialog template - DLGTEMPLATE or DLGTEMPLATEEX
+
+#if (_ATL_VER >= 0x800)
+ typedef ATL::_DialogSplitHelper::DLGTEMPLATEEX DLGTEMPLATEEX;
+ typedef ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX DLGITEMTEMPLATEEX;
+#else // (_ATL_VER >= 0x800)
+ typedef ATL::_DialogSizeHelper::_ATL_DLGTEMPLATEEX DLGTEMPLATEEX;
+ #pragma pack(push, 4)
+ struct DLGITEMTEMPLATEEX
+ {
+ DWORD helpID;
+ DWORD exStyle;
+ DWORD style;
+ short x;
+ short y;
+ short cx;
+ short cy;
+ DWORD id;
+ };
+ #pragma pack(pop)
+#endif // (_ATL_VER >= 0x800)
+
+
+class CMemDlgTemplate
+{
+public:
+ enum StdCtrlType
+ {
+ CTRL_BUTTON = 0x0080,
+ CTRL_EDIT = 0x0081,
+ CTRL_STATIC = 0x0082,
+ CTRL_LISTBOX = 0x0083,
+ CTRL_SCROLLBAR = 0x0084,
+ CTRL_COMBOBOX = 0x0085
+ };
+
+ CMemDlgTemplate() : m_hData(NULL), m_pData(NULL), m_pPtr(NULL), m_cAllocated(0)
+ { }
+
+ ~CMemDlgTemplate()
+ {
+ Reset();
+ }
+
+ bool IsValid() const
+ {
+ return (m_pData != NULL);
+ }
+
+ bool IsTemplateEx() const
+ {
+ return (IsValid() && ((DLGTEMPLATEEX*)m_pData)->signature == 0xFFFF);
+ }
+
+ LPDLGTEMPLATE GetTemplatePtr()
+ {
+ return reinterpret_cast<LPDLGTEMPLATE>(m_pData);
+ }
+
+ DLGTEMPLATEEX* GetTemplateExPtr()
+ {
+ return reinterpret_cast<DLGTEMPLATEEX*>(m_pData);
+ }
+
+ void Reset()
+ {
+ if (IsValid()) {
+#ifndef UNDER_CE
+ ::GlobalUnlock(m_pData);
+#endif
+ ATLVERIFY(::GlobalFree(m_hData) == NULL);
+ }
+
+ m_hData = NULL;
+ m_pData = NULL;
+ m_pPtr = NULL;
+ m_cAllocated = 0;
+ }
+
+ void Create(bool bDlgEx, LPCTSTR lpszCaption, RECT rc, DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ LPCTSTR lpstrFontName = NULL, WORD wFontSize = 0, WORD wWeight = 0, BYTE bItalic = 0, BYTE bCharset = 0, DWORD dwHelpID = 0,
+ ATL::_U_STRINGorID ClassName = 0U, ATL::_U_STRINGorID Menu = 0U)
+ {
+ Create(bDlgEx, lpszCaption, (short) rc.left, (short) rc.top, (short) (rc.right - rc.left), (short) (rc.bottom - rc.top), dwStyle, dwExStyle,
+ lpstrFontName, wFontSize, wWeight, bItalic, bCharset, dwHelpID, ClassName.m_lpstr, Menu.m_lpstr);
+ }
+
+ void Create(bool bDlgEx, LPCTSTR lpszCaption, short nX, short nY, short nWidth, short nHeight, DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ LPCTSTR lpstrFontName = NULL, WORD wFontSize = 0, WORD wWeight = 0, BYTE bItalic = 0, BYTE bCharset = 0, DWORD dwHelpID = 0,
+ ATL::_U_STRINGorID ClassName = 0U, ATL::_U_STRINGorID Menu = 0U)
+ {
+ // Should have DS_SETFONT style to set the dialog font name and size
+ if (lpstrFontName != NULL)
+ {
+ dwStyle |= DS_SETFONT;
+ }
+ else
+ {
+ dwStyle &= ~DS_SETFONT;
+ }
+
+ if (bDlgEx)
+ {
+ DLGTEMPLATEEX dlg = {1, 0xFFFF, dwHelpID, dwExStyle, dwStyle, 0, nX, nY, nWidth, nHeight};
+ AddData(&dlg, sizeof(dlg));
+ }
+ else
+ {
+ DLGTEMPLATE dlg = {dwStyle, dwExStyle, 0, nX, nY, nWidth, nHeight};
+ AddData(&dlg, sizeof(dlg));
+ }
+
+#ifndef _WIN32_WCE
+ if (Menu.m_lpstr == NULL)
+ {
+ WORD menuData = 0;
+ AddData(&menuData, sizeof(WORD));
+ }
+ else if (IS_INTRESOURCE(Menu.m_lpstr))
+ {
+ WORD menuData[] = {0xFFFF, (WORD)Menu.m_lpstr};
+ AddData(menuData, sizeof(menuData));
+ }
+ else
+ {
+ AddString(Menu.m_lpstr);
+ }
+#else // _WIN32_WCE
+ // Windows CE doesn't support the addition of menus to a dialog box
+ ATLASSERT(Menu.m_lpstr == NULL);
+ Menu.m_lpstr; // avoid level 4 warning
+ WORD menuData = 0;
+ AddData(&menuData, sizeof(WORD));
+#endif // _WIN32_WCE
+
+ if (ClassName.m_lpstr == NULL)
+ {
+ WORD classData = 0;
+ AddData(&classData, sizeof(WORD));
+ }
+ else if (IS_INTRESOURCE(ClassName.m_lpstr))
+ {
+ WORD classData[] = {0xFFFF, (WORD)ClassName.m_lpstr};
+ AddData(classData, sizeof(classData));
+ }
+ else
+ {
+ AddString(ClassName.m_lpstr);
+ }
+
+ // Set dialog caption
+ AddString(lpszCaption);
+
+ if (lpstrFontName != NULL)
+ {
+ AddData(&wFontSize, sizeof(wFontSize));
+
+ if (bDlgEx)
+ {
+ AddData(&wWeight, sizeof(wWeight));
+ AddData(&bItalic, sizeof(bItalic));
+ AddData(&bCharset, sizeof(bCharset));
+ }
+
+ AddString(lpstrFontName);
+ }
+ }
+
+ void AddControl(ATL::_U_STRINGorID ClassName, WORD wId, RECT rc, DWORD dwStyle, DWORD dwExStyle,
+ ATL::_U_STRINGorID Text, const WORD* pCreationData = NULL, WORD nCreationData = 0, DWORD dwHelpID = 0)
+ {
+ AddControl(ClassName.m_lpstr, wId, (short) rc.left, (short) rc.top, (short) (rc.right - rc.left), (short) (rc.bottom - rc.top), dwStyle, dwExStyle,
+ Text.m_lpstr, pCreationData, nCreationData, dwHelpID);
+ }
+
+ void AddControl(ATL::_U_STRINGorID ClassName, WORD wId, short nX, short nY, short nWidth, short nHeight, DWORD dwStyle, DWORD dwExStyle,
+ ATL::_U_STRINGorID Text, const WORD* pCreationData = NULL, WORD nCreationData = 0, DWORD dwHelpID = 0)
+ {
+ ATLASSERT(IsValid());
+
+ // DWORD align data
+ m_pPtr = (LPBYTE)(DWORD_PTR)((DWORD)(DWORD_PTR)(m_pPtr + 3) & (~3));
+
+ if (IsTemplateEx())
+ {
+ DLGTEMPLATEEX* dlg = (DLGTEMPLATEEX*)m_pData;
+ dlg->cDlgItems++;
+
+ DLGITEMTEMPLATEEX item = {dwHelpID, ATL::CControlWinTraits::GetWndExStyle(0) | dwExStyle, ATL::CControlWinTraits::GetWndStyle(0) | dwStyle, nX, nY, nWidth, nHeight, wId};
+ AddData(&item, sizeof(item));
+ }
+ else
+ {
+ LPDLGTEMPLATE dlg = (LPDLGTEMPLATE)m_pData;
+ dlg->cdit++;
+
+ DLGITEMTEMPLATE item = {ATL::CControlWinTraits::GetWndStyle(0) | dwStyle, ATL::CControlWinTraits::GetWndExStyle(0) | dwExStyle, nX, nY, nWidth, nHeight, wId};
+ AddData(&item, sizeof(item));
+ }
+
+ ATLASSERT(ClassName.m_lpstr != NULL);
+ if (IS_INTRESOURCE(ClassName.m_lpstr))
+ {
+ WORD wData[] = {0xFFFF, (WORD)ClassName.m_lpstr};
+ AddData(wData, sizeof(wData));
+ }
+ else
+ {
+ AddString(ClassName.m_lpstr);
+ }
+
+ if (Text.m_lpstr == NULL)
+ {
+ WORD classData = 0;
+ AddData(&classData, sizeof(WORD));
+ }
+ else if (IS_INTRESOURCE(Text.m_lpstr))
+ {
+ WORD wData[] = {0xFFFF, (WORD)Text.m_lpstr};
+ AddData(wData, sizeof(wData));
+ }
+ else
+ {
+ AddString(Text.m_lpstr);
+ }
+
+ AddData(&nCreationData, sizeof(nCreationData));
+
+ if ((nCreationData != 0))
+ {
+ ATLASSERT(pCreationData != NULL);
+ AddData(pCreationData, nCreationData * sizeof(WORD));
+ }
+ }
+
+ void AddStdControl(StdCtrlType CtrlType, WORD wId, short nX, short nY, short nWidth, short nHeight,
+ DWORD dwStyle, DWORD dwExStyle, ATL::_U_STRINGorID Text, const WORD* pCreationData = NULL, WORD nCreationData = 0, DWORD dwHelpID = 0)
+ {
+ AddControl(CtrlType, wId, nX, nY, nWidth, nHeight, dwStyle, dwExStyle, Text, pCreationData, nCreationData, dwHelpID);
+ }
+
+ void AddData(LPCVOID pData, size_t nData)
+ {
+ ATLASSERT(pData != NULL);
+
+ const SIZE_T ALLOCATION_INCREMENT = 1024;
+
+ if (m_pData == NULL)
+ {
+ m_cAllocated = ((nData / ALLOCATION_INCREMENT) + 1) * ALLOCATION_INCREMENT;
+ m_hData = ::GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, m_cAllocated);
+ ATLASSERT(m_hData != NULL);
+#ifndef UNDER_CE
+ m_pPtr = m_pData = static_cast<LPBYTE>(::GlobalLock(m_hData));
+#else
+ m_pPtr = m_pData = static_cast<LPBYTE>(m_hData);
+#endif
+ ATLASSERT(m_pData != NULL);
+ }
+ else if (((m_pPtr - m_pData) + nData) > m_cAllocated)
+ {
+ SIZE_T ptrPos = (m_pPtr - m_pData);
+ m_cAllocated += ((nData / ALLOCATION_INCREMENT) + 1) * ALLOCATION_INCREMENT;
+#ifndef UNDER_CE
+ ::GlobalUnlock(m_pData);
+#endif
+ m_hData = ::GlobalReAlloc(m_hData, m_cAllocated, GMEM_MOVEABLE | GMEM_ZEROINIT);
+ ATLASSERT(m_hData != NULL);
+#ifndef UNDER_CE
+ m_pData = static_cast<LPBYTE>(::GlobalLock(m_hData));
+#else
+ m_pData = static_cast<LPBYTE>(m_hData);
+#endif
+ ATLASSERT(m_pData != NULL);
+ m_pPtr = m_pData + ptrPos;
+ }
+
+ SecureHelper::memcpy_x(m_pPtr, m_cAllocated - (m_pPtr - m_pData), pData, nData);
+
+ m_pPtr += nData;
+ }
+
+ void AddString(LPCTSTR lpszStr)
+ {
+ if (lpszStr == NULL)
+ {
+ WCHAR szEmpty = 0;
+ AddData(&szEmpty, sizeof(szEmpty));
+ }
+ else
+ {
+ USES_CONVERSION;
+ LPCWSTR lpstr = T2CW(lpszStr);
+ int nSize = lstrlenW(lpstr) + 1;
+ AddData(lpstr, nSize * sizeof(WCHAR));
+ }
+ }
+
+ HANDLE m_hData;
+ LPBYTE m_pData;
+ LPBYTE m_pPtr;
+ SIZE_T m_cAllocated;
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Dialog and control macros for indirect dialogs
+
+// for DLGTEMPLATE
+#define BEGIN_DIALOG(x, y, width, height) \
+ void DoInitTemplate() \
+ { \
+ bool bExTemplate = false; \
+ short nX = x, nY = y, nWidth = width, nHeight = height; \
+ LPCTSTR szCaption = NULL; \
+ DWORD dwStyle = WS_POPUP | WS_BORDER | WS_SYSMENU; \
+ DWORD dwExStyle = 0; \
+ LPCTSTR szFontName = NULL; \
+ WORD wFontSize = 0; \
+ WORD wWeight = 0; \
+ BYTE bItalic = 0; \
+ BYTE bCharset = 0; \
+ DWORD dwHelpID = 0; \
+ ATL::_U_STRINGorID Menu = 0U; \
+ ATL::_U_STRINGorID ClassName = 0U;
+
+// for DLGTEMPLATEEX
+#define BEGIN_DIALOG_EX(x, y, width, height, helpID) \
+ void DoInitTemplate() \
+ { \
+ bool bExTemplate = true; \
+ short nX = x, nY = y, nWidth = width, nHeight = height; \
+ LPCTSTR szCaption = NULL; \
+ DWORD dwStyle = WS_POPUP | WS_BORDER | WS_SYSMENU; \
+ DWORD dwExStyle = 0; \
+ LPCTSTR szFontName = NULL; \
+ WORD wFontSize = 0; \
+ WORD wWeight = 0; \
+ BYTE bItalic = 0; \
+ BYTE bCharset = 0; \
+ DWORD dwHelpID = helpID; \
+ ATL::_U_STRINGorID Menu = 0U; \
+ ATL::_U_STRINGorID ClassName = 0U;
+
+#define END_DIALOG() \
+ m_Template.Create(bExTemplate, szCaption, nX, nY, nWidth, nHeight, dwStyle, dwExStyle, szFontName, wFontSize, wWeight, bItalic, bCharset, dwHelpID, ClassName, Menu); \
+ };
+
+#define DIALOG_CAPTION(caption) \
+ szCaption = caption;
+#define DIALOG_STYLE(style) \
+ dwStyle = style;
+#define DIALOG_EXSTYLE(exStyle) \
+ dwExStyle = exStyle;
+#define DIALOG_FONT(pointSize, typeFace) \
+ wFontSize = pointSize; \
+ szFontName = typeFace;
+#define DIALOG_FONT_EX(pointsize, typeface, weight, italic, charset) \
+ ATLASSERT(bExTemplate); \
+ wFontSize = pointsize; \
+ szFontName = typeface; \
+ wWeight = weight; \
+ bItalic = italic; \
+ bCharset = charset;
+#define DIALOG_MENU(menuName) \
+ Menu = menuName;
+#define DIALOG_CLASS(className) \
+ ClassName = className;
+
+#define BEGIN_CONTROLS_MAP() \
+ void DoInitControls() \
+ {
+
+#define END_CONTROLS_MAP() \
+ };
+
+
+#define CONTROL_LTEXT(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_STATIC, (WORD)id, x, y, width, height, style | SS_LEFT | WS_GROUP, exStyle, text, NULL, 0);
+#define CONTROL_CTEXT(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_STATIC, (WORD)id, x, y, width, height, style | SS_CENTER | WS_GROUP, exStyle, text, NULL, 0);
+#define CONTROL_RTEXT(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_STATIC, (WORD)id, x, y, width, height, style | SS_RIGHT | WS_GROUP, exStyle, text, NULL, 0);
+#define CONTROL_PUSHBUTTON(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_PUSHBUTTON | WS_TABSTOP, exStyle, text, NULL, 0);
+#define CONTROL_DEFPUSHBUTTON(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_DEFPUSHBUTTON | WS_TABSTOP, exStyle, text, NULL, 0);
+#ifndef _WIN32_WCE
+#define CONTROL_PUSHBOX(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_PUSHBOX | WS_TABSTOP, exStyle, text, NULL, 0);
+#endif // !_WIN32_WCE
+#define CONTROL_STATE3(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_3STATE | WS_TABSTOP, exStyle, text, NULL, 0);
+#define CONTROL_AUTO3STATE(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_AUTO3STATE | WS_TABSTOP, exStyle, text, NULL, 0);
+#define CONTROL_CHECKBOX(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_CHECKBOX | WS_TABSTOP, exStyle, text, NULL, 0);
+#define CONTROL_AUTOCHECKBOX(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_AUTOCHECKBOX | WS_TABSTOP, exStyle, text, NULL, 0);
+#define CONTROL_RADIOBUTTON(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_RADIOBUTTON | WS_TABSTOP, exStyle, text, NULL, 0);
+#define CONTROL_AUTORADIOBUTTON(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_AUTORADIOBUTTON | WS_TABSTOP, exStyle, text, NULL, 0);
+#define CONTROL_COMBOBOX(id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_COMBOBOX, (WORD)id, x, y, width, height, style | CBS_DROPDOWN | WS_TABSTOP, exStyle, (LPCTSTR)NULL, NULL, 0);
+#define CONTROL_EDITTEXT(id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_EDIT, (WORD)id, x, y, width, height, style | ES_LEFT | WS_BORDER | WS_TABSTOP, exStyle, (LPCTSTR)NULL, NULL, 0);
+#define CONTROL_GROUPBOX(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_BUTTON, (WORD)id, x, y, width, height, style | BS_GROUPBOX, exStyle, text, NULL, 0);
+#define CONTROL_LISTBOX(id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_LISTBOX, (WORD)id, x, y, width, height, style | LBS_NOTIFY | WS_BORDER, exStyle, (LPCTSTR)NULL, NULL, 0);
+#define CONTROL_SCROLLBAR(id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_SCROLLBAR, (WORD)id, x, y, width, height, style | SBS_HORZ, exStyle, (LPCTSTR)NULL, NULL, 0);
+#define CONTROL_ICON(text, id, x, y, width, height, style, exStyle) \
+ m_Template.AddStdControl(WTL::CMemDlgTemplate::CTRL_STATIC, (WORD)id, x, y, width, height, style | SS_ICON, exStyle, text, NULL, 0);
+#define CONTROL_CONTROL(text, id, className, style, x, y, width, height, exStyle) \
+ m_Template.AddControl(className, (WORD)id, x, y, width, height, style, exStyle, text, NULL, 0);
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CIndirectDialogImpl - dialogs with template in memory
+
+template <class T, class TDlgTemplate = CMemDlgTemplate, class TBase = ATL::CDialogImpl<T, ATL::CWindow> >
+class ATL_NO_VTABLE CIndirectDialogImpl : public TBase
+{
+public:
+ enum { IDD = 0 }; // no dialog template resource
+
+ TDlgTemplate m_Template;
+
+ void CreateTemplate()
+ {
+ T* pT = static_cast<T*>(this);
+ pT->DoInitTemplate();
+ pT->DoInitControls();
+ }
+
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow(), LPARAM dwInitParam = NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_hWnd == NULL);
+
+ if (!m_Template.IsValid())
+ CreateTemplate();
+
+#if (_ATL_VER >= 0x0800)
+ // Allocate the thunk structure here, where we can fail gracefully.
+ BOOL result = m_thunk.Init(NULL, NULL);
+ if (result == FALSE)
+ {
+ SetLastError(ERROR_OUTOFMEMORY);
+ return -1;
+ }
+#endif // (_ATL_VER >= 0x0800)
+
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, pT);
+
+#ifdef _DEBUG
+ m_bModal = true;
+#endif // _DEBUG
+
+ return ::DialogBoxIndirectParam(ModuleHelper::GetResourceInstance(), m_Template.GetTemplatePtr(), hWndParent, (DLGPROC)T::StartDialogProc, dwInitParam);
+ }
+
+ HWND Create(HWND hWndParent, LPARAM dwInitParam = NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->m_hWnd == NULL);
+
+ if (!m_Template.IsValid())
+ CreateTemplate();
+
+#if (_ATL_VER >= 0x0800)
+ // Allocate the thunk structure here, where we can fail gracefully.
+ BOOL result = m_thunk.Init(NULL, NULL);
+ if (result == FALSE)
+ {
+ SetLastError(ERROR_OUTOFMEMORY);
+ return NULL;
+ }
+#endif // (_ATL_VER >= 0x0800)
+
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, pT);
+
+#ifdef _DEBUG
+ m_bModal = false;
+#endif // _DEBUG
+
+ HWND hWnd = ::CreateDialogIndirectParam(ModuleHelper::GetResourceInstance(), (LPCDLGTEMPLATE)m_Template.GetTemplatePtr(), hWndParent, (DLGPROC)T::StartDialogProc, dwInitParam);
+ ATLASSERT(m_hWnd == hWnd);
+
+ return hWnd;
+ }
+
+ // for CComControl
+ HWND Create(HWND hWndParent, RECT&, LPARAM dwInitParam = NULL)
+ {
+ return Create(hWndParent, dwInitParam);
+ }
+
+ void DoInitTemplate()
+ {
+ ATLASSERT(FALSE); // MUST be defined in derived class
+ }
+
+ void DoInitControls()
+ {
+ ATLASSERT(FALSE); // MUST be defined in derived class
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CPropertySheetWindow - client side for a property sheet
+
+class CPropertySheetWindow : public ATL::CWindow
+{
+public:
+// Constructors
+ CPropertySheetWindow(HWND hWnd = NULL) : ATL::CWindow(hWnd)
+ { }
+
+ CPropertySheetWindow& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Attributes
+ int GetPageCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HWND hWndTabCtrl = GetTabControl();
+ ATLASSERT(hWndTabCtrl != NULL);
+ return (int)::SendMessage(hWndTabCtrl, TCM_GETITEMCOUNT, 0, 0L);
+ }
+
+ HWND GetActivePage() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HWND)::SendMessage(m_hWnd, PSM_GETCURRENTPAGEHWND, 0, 0L);
+ }
+
+ int GetActiveIndex() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ HWND hWndTabCtrl = GetTabControl();
+ ATLASSERT(hWndTabCtrl != NULL);
+ return (int)::SendMessage(hWndTabCtrl, TCM_GETCURSEL, 0, 0L);
+ }
+
+ BOOL SetActivePage(int nPageIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, PSM_SETCURSEL, nPageIndex, 0L);
+ }
+
+ BOOL SetActivePage(HPROPSHEETPAGE hPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hPage != NULL);
+ return (BOOL)::SendMessage(m_hWnd, PSM_SETCURSEL, 0, (LPARAM)hPage);
+ }
+
+ BOOL SetActivePageByID(int nPageID)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, PSM_SETCURSELID, 0, nPageID);
+ }
+
+ void SetTitle(LPCTSTR lpszText, UINT nStyle = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT((nStyle & ~PSH_PROPTITLE) == 0); // only PSH_PROPTITLE is valid
+ ATLASSERT(lpszText != NULL);
+ ::SendMessage(m_hWnd, PSM_SETTITLE, nStyle, (LPARAM)lpszText);
+ }
+
+ HWND GetTabControl() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HWND)::SendMessage(m_hWnd, PSM_GETTABCONTROL, 0, 0L);
+ }
+
+ void SetFinishText(LPCTSTR lpszText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_SETFINISHTEXT, 0, (LPARAM)lpszText);
+ }
+
+ void SetWizardButtons(DWORD dwFlags)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::PostMessage(m_hWnd, PSM_SETWIZBUTTONS, 0, dwFlags);
+ }
+
+// Operations
+ BOOL AddPage(HPROPSHEETPAGE hPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hPage != NULL);
+ return (BOOL)::SendMessage(m_hWnd, PSM_ADDPAGE, 0, (LPARAM)hPage);
+ }
+
+ BOOL AddPage(LPCPROPSHEETPAGE pPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pPage != NULL);
+ HPROPSHEETPAGE hPage = ::CreatePropertySheetPage(pPage);
+ if(hPage == NULL)
+ return FALSE;
+ return (BOOL)::SendMessage(m_hWnd, PSM_ADDPAGE, 0, (LPARAM)hPage);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL InsertPage(int nNewPageIndex, HPROPSHEETPAGE hPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hPage != NULL);
+ return (BOOL)::SendMessage(m_hWnd, PSM_INSERTPAGE, nNewPageIndex, (LPARAM)hPage);
+ }
+
+ BOOL InsertPage(int nNewPageIndex, LPCPROPSHEETPAGE pPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pPage != NULL);
+ HPROPSHEETPAGE hPage = ::CreatePropertySheetPage(pPage);
+ if(hPage == NULL)
+ return FALSE;
+ return (BOOL)::SendMessage(m_hWnd, PSM_INSERTPAGE, nNewPageIndex, (LPARAM)hPage);
+ }
+
+ BOOL InsertPage(HPROPSHEETPAGE hPageInsertAfter, HPROPSHEETPAGE hPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hPage != NULL);
+ return (BOOL)::SendMessage(m_hWnd, PSM_INSERTPAGE, (WPARAM)hPageInsertAfter, (LPARAM)hPage);
+ }
+
+ BOOL InsertPage(HPROPSHEETPAGE hPageInsertAfter, LPCPROPSHEETPAGE pPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pPage != NULL);
+ HPROPSHEETPAGE hPage = ::CreatePropertySheetPage(pPage);
+ if(hPage == NULL)
+ return FALSE;
+ return (BOOL)::SendMessage(m_hWnd, PSM_INSERTPAGE, (WPARAM)hPageInsertAfter, (LPARAM)hPage);
+ }
+#endif // !_WIN32_WCE
+
+ void RemovePage(int nPageIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_REMOVEPAGE, nPageIndex, 0L);
+ }
+
+ void RemovePage(HPROPSHEETPAGE hPage)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(hPage != NULL);
+ ::SendMessage(m_hWnd, PSM_REMOVEPAGE, 0, (LPARAM)hPage);
+ }
+
+ BOOL PressButton(int nButton)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, PSM_PRESSBUTTON, nButton, 0L);
+ }
+
+ BOOL Apply()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, PSM_APPLY, 0, 0L);
+ }
+
+ void CancelToClose()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_CANCELTOCLOSE, 0, 0L);
+ }
+
+ void SetModified(HWND hWndPage, BOOL bChanged = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(::IsWindow(hWndPage));
+ UINT uMsg = bChanged ? PSM_CHANGED : PSM_UNCHANGED;
+ ::SendMessage(m_hWnd, uMsg, (WPARAM)hWndPage, 0L);
+ }
+
+ LRESULT QuerySiblings(WPARAM wParam, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return ::SendMessage(m_hWnd, PSM_QUERYSIBLINGS, wParam, lParam);
+ }
+
+ void RebootSystem()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_REBOOTSYSTEM, 0, 0L);
+ }
+
+ void RestartWindows()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_RESTARTWINDOWS, 0, 0L);
+ }
+
+ BOOL IsDialogMessage(LPMSG lpMsg)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, PSM_ISDIALOGMESSAGE, 0, (LPARAM)lpMsg);
+ }
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ int HwndToIndex(HWND hWnd) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PSM_HWNDTOINDEX, (WPARAM)hWnd, 0L);
+ }
+
+ HWND IndexToHwnd(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HWND)::SendMessage(m_hWnd, PSM_INDEXTOHWND, nIndex, 0L);
+ }
+
+ int PageToIndex(HPROPSHEETPAGE hPage) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PSM_PAGETOINDEX, 0, (LPARAM)hPage);
+ }
+
+ HPROPSHEETPAGE IndexToPage(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HPROPSHEETPAGE)::SendMessage(m_hWnd, PSM_INDEXTOPAGE, nIndex, 0L);
+ }
+
+ int IdToIndex(int nID) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PSM_IDTOINDEX, 0, nID);
+ }
+
+ int IndexToId(int nIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PSM_INDEXTOID, nIndex, 0L);
+ }
+
+ int GetResult() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, PSM_GETRESULT, 0, 0L);
+ }
+
+ BOOL RecalcPageSizes()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, PSM_RECALCPAGESIZES, 0, 0L);
+ }
+
+ void SetHeaderTitle(int nIndex, LPCTSTR lpstrHeaderTitle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_SETHEADERTITLE, nIndex, (LPARAM)lpstrHeaderTitle);
+ }
+
+ void SetHeaderSubTitle(int nIndex, LPCTSTR lpstrHeaderSubTitle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_SETHEADERSUBTITLE, nIndex, (LPARAM)lpstrHeaderSubTitle);
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+// Implementation - override to prevent usage
+ HWND Create(LPCTSTR, HWND, ATL::_U_RECT = NULL, LPCTSTR = NULL, DWORD = 0, DWORD = 0, ATL::_U_MENUorID = 0U, LPVOID = NULL)
+ {
+ ATLASSERT(FALSE);
+ return NULL;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CPropertySheetImpl - implements a property sheet
+
+template <class T, class TBase = CPropertySheetWindow>
+class ATL_NO_VTABLE CPropertySheetImpl : public ATL::CWindowImplBaseT< TBase >
+{
+public:
+ PROPSHEETHEADER m_psh;
+ ATL::CSimpleArray<HPROPSHEETPAGE> m_arrPages;
+
+#if defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__) // PPC specific
+ #ifndef PROPSHEET_LINK_SIZE
+ #define PROPSHEET_LINK_SIZE 128
+ #endif // PROPSHEET_LINK_SIZE
+ TCHAR m_szLink[PROPSHEET_LINK_SIZE];
+ static LPCTSTR m_pszTitle;
+ static LPCTSTR m_pszLink;
+#endif // defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__)
+
+// Construction/Destruction
+ CPropertySheetImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL, UINT uStartPage = 0, HWND hWndParent = NULL)
+ {
+ memset(&m_psh, 0, sizeof(PROPSHEETHEADER));
+ m_psh.dwSize = sizeof(PROPSHEETHEADER);
+ m_psh.dwFlags = PSH_USECALLBACK;
+ m_psh.hInstance = ModuleHelper::GetResourceInstance();
+ m_psh.phpage = NULL; // will be set later
+ m_psh.nPages = 0; // will be set later
+ m_psh.pszCaption = title.m_lpstr;
+ m_psh.nStartPage = uStartPage;
+ m_psh.hwndParent = hWndParent; // if NULL, will be set in DoModal/Create
+ m_psh.pfnCallback = T::PropSheetCallback;
+
+#if defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__) // PPC specific
+ m_psh.dwFlags |= PSH_MAXIMIZE;
+ m_szLink[0] = 0;
+#endif // defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__)
+ }
+
+ ~CPropertySheetImpl()
+ {
+ if(m_arrPages.GetSize() > 0) // sheet never created, destroy all pages
+ {
+ for(int i = 0; i < m_arrPages.GetSize(); i++)
+ ::DestroyPropertySheetPage((HPROPSHEETPAGE)m_arrPages[i]);
+ }
+ }
+
+// Callback function and overrideables
+ static int CALLBACK PropSheetCallback(HWND hWnd, UINT uMsg, LPARAM lParam)
+ {
+ lParam; // avoid level 4 warning
+ int nRet = 0;
+
+ if(uMsg == PSCB_INITIALIZED)
+ {
+ ATLASSERT(hWnd != NULL);
+ T* pT = (T*)ModuleHelper::ExtractCreateWndData();
+ // subclass the sheet window
+ pT->SubclassWindow(hWnd);
+ // remove page handles array
+ pT->_CleanUpPages();
+
+#if defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__) // PPC specific
+ m_pszTitle = pT->m_psh.pszCaption;
+ if(*pT->m_szLink != 0)
+ m_pszLink = pT->m_szLink;
+#endif // defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__) // PPC specific
+
+ pT->OnSheetInitialized();
+ }
+#if defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__) // PPC specific uMsg
+ else
+ {
+ switch(uMsg)
+ {
+ case PSCB_GETVERSION :
+ nRet = COMCTL32_VERSION;
+ break;
+ case PSCB_GETTITLE :
+ if(m_pszTitle != NULL)
+ {
+ lstrcpy((LPTSTR)lParam, m_pszTitle);
+ m_pszTitle = NULL;
+ }
+ break;
+ case PSCB_GETLINKTEXT:
+ if(m_pszLink != NULL)
+ {
+ lstrcpy((LPTSTR)lParam, m_pszLink);
+ m_pszLink = NULL;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+#endif // defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__)
+
+ return nRet;
+ }
+
+ void OnSheetInitialized()
+ {
+ }
+
+// Create method
+ HWND Create(HWND hWndParent = NULL)
+ {
+ ATLASSERT(m_hWnd == NULL);
+
+ m_psh.dwFlags |= PSH_MODELESS;
+ if(m_psh.hwndParent == NULL)
+ m_psh.hwndParent = hWndParent;
+ m_psh.phpage = (HPROPSHEETPAGE*)m_arrPages.GetData();
+ m_psh.nPages = m_arrPages.GetSize();
+
+ T* pT = static_cast<T*>(this);
+ ModuleHelper::AddCreateWndData(&pT->m_thunk.cd, pT);
+
+ HWND hWnd = (HWND)::PropertySheet(&m_psh);
+ _CleanUpPages(); // ensure clean-up, required if call failed
+
+ ATLASSERT(m_hWnd == hWnd);
+
+ return hWnd;
+ }
+
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow())
+ {
+ ATLASSERT(m_hWnd == NULL);
+
+ m_psh.dwFlags &= ~PSH_MODELESS;
+ if(m_psh.hwndParent == NULL)
+ m_psh.hwndParent = hWndParent;
+ m_psh.phpage = (HPROPSHEETPAGE*)m_arrPages.GetData();
+ m_psh.nPages = m_arrPages.GetSize();
+
+ T* pT = static_cast<T*>(this);
+ ModuleHelper::AddCreateWndData(&pT->m_thunk.cd, pT);
+
+ INT_PTR nRet = ::PropertySheet(&m_psh);
+ _CleanUpPages(); // ensure clean-up, required if call failed
+
+ return nRet;
+ }
+
+ // implementation helper - clean up pages array
+ void _CleanUpPages()
+ {
+ m_psh.nPages = 0;
+ m_psh.phpage = NULL;
+ m_arrPages.RemoveAll();
+ }
+
+// Attributes (extended overrides of client class methods)
+// These now can be called before the sheet is created
+// Note: Calling these after the sheet is created gives unpredictable results
+ int GetPageCount() const
+ {
+ if(m_hWnd == NULL) // not created yet
+ return m_arrPages.GetSize();
+ return TBase::GetPageCount();
+ }
+
+ int GetActiveIndex() const
+ {
+ if(m_hWnd == NULL) // not created yet
+ return m_psh.nStartPage;
+ return TBase::GetActiveIndex();
+ }
+
+ HPROPSHEETPAGE GetPage(int nPageIndex) const
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+ return (HPROPSHEETPAGE)m_arrPages[nPageIndex];
+ }
+
+ int GetPageIndex(HPROPSHEETPAGE hPage) const
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+ return m_arrPages.Find((HPROPSHEETPAGE&)hPage);
+ }
+
+ BOOL SetActivePage(int nPageIndex)
+ {
+ if(m_hWnd == NULL) // not created yet
+ {
+ ATLASSERT(nPageIndex >= 0 && nPageIndex < m_arrPages.GetSize());
+ m_psh.nStartPage = nPageIndex;
+ return TRUE;
+ }
+ return TBase::SetActivePage(nPageIndex);
+ }
+
+ BOOL SetActivePage(HPROPSHEETPAGE hPage)
+ {
+ ATLASSERT(hPage != NULL);
+ if (m_hWnd == NULL) // not created yet
+ {
+ int nPageIndex = GetPageIndex(hPage);
+ if(nPageIndex == -1)
+ return FALSE;
+
+ return SetActivePage(nPageIndex);
+ }
+ return TBase::SetActivePage(hPage);
+
+ }
+
+ void SetTitle(LPCTSTR lpszText, UINT nStyle = 0)
+ {
+ ATLASSERT((nStyle & ~PSH_PROPTITLE) == 0); // only PSH_PROPTITLE is valid
+ ATLASSERT(lpszText != NULL);
+
+ if(m_hWnd == NULL)
+ {
+ // set internal state
+ m_psh.pszCaption = lpszText; // must exist until sheet is created
+ m_psh.dwFlags &= ~PSH_PROPTITLE;
+ m_psh.dwFlags |= nStyle;
+ }
+ else
+ {
+ // set external state
+ TBase::SetTitle(lpszText, nStyle);
+ }
+ }
+
+#if defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__) // PPC specific Link field
+ void SetLinkText(LPCTSTR lpszText)
+ {
+ ATLASSERT(lpszText != NULL);
+ ATLASSERT(lstrlen(lpszText) < PROPSHEET_LINK_SIZE);
+ lstrcpy(m_szLink, lpszText);
+ }
+#endif // defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__)
+
+ void SetWizardMode()
+ {
+ m_psh.dwFlags |= PSH_WIZARD;
+ }
+
+ void EnableHelp()
+ {
+ m_psh.dwFlags |= PSH_HASHELP;
+ }
+
+// Operations
+ BOOL AddPage(HPROPSHEETPAGE hPage)
+ {
+ ATLASSERT(hPage != NULL);
+ BOOL bRet = FALSE;
+ if(m_hWnd != NULL)
+ bRet = TBase::AddPage(hPage);
+ else // sheet not created yet, use internal data
+ bRet = m_arrPages.Add((HPROPSHEETPAGE&)hPage);
+ return bRet;
+ }
+
+ BOOL AddPage(LPCPROPSHEETPAGE pPage)
+ {
+ ATLASSERT(pPage != NULL);
+ HPROPSHEETPAGE hPage = ::CreatePropertySheetPage(pPage);
+ if(hPage == NULL)
+ return FALSE;
+ BOOL bRet = AddPage(hPage);
+ if(!bRet)
+ ::DestroyPropertySheetPage(hPage);
+ return bRet;
+ }
+
+ BOOL RemovePage(HPROPSHEETPAGE hPage)
+ {
+ ATLASSERT(hPage != NULL);
+ if (m_hWnd == NULL) // not created yet
+ {
+ int nPage = GetPageIndex(hPage);
+ if(nPage == -1)
+ return FALSE;
+ return RemovePage(nPage);
+ }
+ TBase::RemovePage(hPage);
+ return TRUE;
+
+ }
+
+ BOOL RemovePage(int nPageIndex)
+ {
+ BOOL bRet = TRUE;
+ if(m_hWnd != NULL)
+ TBase::RemovePage(nPageIndex);
+ else // sheet not created yet, use internal data
+ bRet = m_arrPages.RemoveAt(nPageIndex);
+ return bRet;
+ }
+
+#if (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+ void SetHeader(LPCTSTR szbmHeader)
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+
+ m_psh.dwFlags &= ~PSH_WIZARD;
+ m_psh.dwFlags |= (PSH_HEADER | PSH_WIZARD97);
+ m_psh.pszbmHeader = szbmHeader;
+ }
+
+ void SetHeader(HBITMAP hbmHeader)
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+
+ m_psh.dwFlags &= ~PSH_WIZARD;
+ m_psh.dwFlags |= (PSH_HEADER | PSH_USEHBMHEADER | PSH_WIZARD97);
+ m_psh.hbmHeader = hbmHeader;
+ }
+
+ void SetWatermark(LPCTSTR szbmWatermark, HPALETTE hplWatermark = NULL)
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+
+ m_psh.dwFlags &= ~PSH_WIZARD;
+ m_psh.dwFlags |= PSH_WATERMARK | PSH_WIZARD97;
+ m_psh.pszbmWatermark = szbmWatermark;
+
+ if (hplWatermark != NULL)
+ {
+ m_psh.dwFlags |= PSH_USEHPLWATERMARK;
+ m_psh.hplWatermark = hplWatermark;
+ }
+ }
+
+ void SetWatermark(HBITMAP hbmWatermark, HPALETTE hplWatermark = NULL)
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+
+ m_psh.dwFlags &= ~PSH_WIZARD;
+ m_psh.dwFlags |= (PSH_WATERMARK | PSH_USEHBMWATERMARK | PSH_WIZARD97);
+ m_psh.hbmWatermark = hbmWatermark;
+
+ if (hplWatermark != NULL)
+ {
+ m_psh.dwFlags |= PSH_USEHPLWATERMARK;
+ m_psh.hplWatermark = hplWatermark;
+ }
+ }
+
+ void StretchWatermark(bool bStretchWatermark)
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+ if (bStretchWatermark)
+ m_psh.dwFlags |= PSH_STRETCHWATERMARK;
+ else
+ m_psh.dwFlags &= ~PSH_STRETCHWATERMARK;
+ }
+#endif // (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CPropertySheetImpl)
+ MESSAGE_HANDLER(WM_COMMAND, OnCommand)
+ MESSAGE_HANDLER(WM_SYSCOMMAND, OnSysCommand)
+ END_MSG_MAP()
+
+ LRESULT OnCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRet = DefWindowProc(uMsg, wParam, lParam);
+ if(HIWORD(wParam) == BN_CLICKED && (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) &&
+ ((m_psh.dwFlags & PSH_MODELESS) != 0) && (GetActivePage() == NULL))
+ DestroyWindow();
+ return lRet;
+ }
+
+ LRESULT OnSysCommand(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(((m_psh.dwFlags & PSH_MODELESS) == PSH_MODELESS) && ((wParam & 0xFFF0) == SC_CLOSE))
+ SendMessage(WM_CLOSE);
+ else
+ bHandled = FALSE;
+ return 0;
+ }
+};
+
+#if defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__) // PPC static pointers
+template < class T, class TBase >
+LPCWSTR CPropertySheetImpl<T,TBase>::m_pszTitle = NULL;
+template < class T, class TBase>
+LPCWSTR CPropertySheetImpl<T,TBase>::m_pszLink = NULL;
+#endif // defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__)
+
+// for non-customized sheets
+class CPropertySheet : public CPropertySheetImpl<CPropertySheet>
+{
+public:
+ CPropertySheet(ATL::_U_STRINGorID title = (LPCTSTR)NULL, UINT uStartPage = 0, HWND hWndParent = NULL)
+ : CPropertySheetImpl<CPropertySheet>(title, uStartPage, hWndParent)
+ { }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPropertyPageWindow - client side for a property page
+
+class CPropertyPageWindow : public ATL::CWindow
+{
+public:
+// Constructors
+ CPropertyPageWindow(HWND hWnd = NULL) : ATL::CWindow(hWnd)
+ { }
+
+ CPropertyPageWindow& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Attributes
+ CPropertySheetWindow GetPropertySheet() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CPropertySheetWindow(GetParent());
+ }
+
+// Operations
+ BOOL Apply()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ return GetPropertySheet().Apply();
+ }
+
+ void CancelToClose()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetPropertySheet().CancelToClose();
+ }
+
+ void SetModified(BOOL bChanged = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetPropertySheet().SetModified(m_hWnd, bChanged);
+ }
+
+ LRESULT QuerySiblings(WPARAM wParam, LPARAM lParam)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ return GetPropertySheet().QuerySiblings(wParam, lParam);
+ }
+
+ void RebootSystem()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetPropertySheet().RebootSystem();
+ }
+
+ void RestartWindows()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetPropertySheet().RestartWindows();
+ }
+
+ void SetWizardButtons(DWORD dwFlags)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetPropertySheet().SetWizardButtons(dwFlags);
+ }
+
+// Implementation - overrides to prevent usage
+ HWND Create(LPCTSTR, HWND, ATL::_U_RECT = NULL, LPCTSTR = NULL, DWORD = 0, DWORD = 0, ATL::_U_MENUorID = 0U, LPVOID = NULL)
+ {
+ ATLASSERT(FALSE);
+ return NULL;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CPropertyPageImpl - implements a property page
+
+template <class T, class TBase = CPropertyPageWindow>
+class ATL_NO_VTABLE CPropertyPageImpl : public ATL::CDialogImplBaseT< TBase >
+{
+public:
+ PROPSHEETPAGE m_psp;
+
+ operator PROPSHEETPAGE*() { return &m_psp; }
+
+// Construction
+ CPropertyPageImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL)
+ {
+ // initialize PROPSHEETPAGE struct
+ memset(&m_psp, 0, sizeof(PROPSHEETPAGE));
+ m_psp.dwSize = sizeof(PROPSHEETPAGE);
+ m_psp.dwFlags = PSP_USECALLBACK;
+ m_psp.hInstance = ModuleHelper::GetResourceInstance();
+ T* pT = static_cast<T*>(this);
+ m_psp.pszTemplate = MAKEINTRESOURCE(pT->IDD);
+ m_psp.pfnDlgProc = (DLGPROC)T::StartDialogProc;
+ m_psp.pfnCallback = T::PropPageCallback;
+ m_psp.lParam = (LPARAM)pT;
+
+ if(title.m_lpstr != NULL)
+ SetTitle(title);
+ }
+
+// Callback function and overrideables
+ static UINT CALLBACK PropPageCallback(HWND hWnd, UINT uMsg, LPPROPSHEETPAGE ppsp)
+ {
+ hWnd; // avoid level 4 warning
+ ATLASSERT(hWnd == NULL);
+ T* pT = (T*)ppsp->lParam;
+ UINT uRet = 0;
+
+ switch(uMsg)
+ {
+ case PSPCB_CREATE:
+ {
+ ATL::CDialogImplBaseT< TBase >* pPage = (ATL::CDialogImplBaseT< TBase >*)pT;
+ ModuleHelper::AddCreateWndData(&pPage->m_thunk.cd, pPage);
+ uRet = pT->OnPageCreate() ? 1 : 0;
+ }
+ break;
+#if (_WIN32_IE >= 0x0500)
+ case PSPCB_ADDREF:
+ pT->OnPageAddRef();
+ break;
+#endif // (_WIN32_IE >= 0x0500)
+ case PSPCB_RELEASE:
+ pT->OnPageRelease();
+ break;
+ default:
+ break;
+ }
+
+ return uRet;
+ }
+
+ bool OnPageCreate()
+ {
+ return true; // true - allow page to be created, false - prevent creation
+ }
+
+#if (_WIN32_IE >= 0x0500)
+ void OnPageAddRef()
+ {
+ }
+#endif // (_WIN32_IE >= 0x0500)
+
+ void OnPageRelease()
+ {
+ }
+
+// Create method
+ HPROPSHEETPAGE Create()
+ {
+ return ::CreatePropertySheetPage(&m_psp);
+ }
+
+// Attributes
+ void SetTitle(ATL::_U_STRINGorID title)
+ {
+ m_psp.pszTitle = title.m_lpstr;
+ m_psp.dwFlags |= PSP_USETITLE;
+ }
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ void SetHeaderTitle(LPCTSTR lpstrHeaderTitle)
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+ m_psp.dwFlags |= PSP_USEHEADERTITLE;
+ m_psp.pszHeaderTitle = lpstrHeaderTitle;
+ }
+
+ void SetHeaderSubTitle(LPCTSTR lpstrHeaderSubTitle)
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+ m_psp.dwFlags |= PSP_USEHEADERSUBTITLE;
+ m_psp.pszHeaderSubTitle = lpstrHeaderSubTitle;
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+// Operations
+ void EnableHelp()
+ {
+ m_psp.dwFlags |= PSP_HASHELP;
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CPropertyPageImpl)
+ MESSAGE_HANDLER(WM_NOTIFY, OnNotify)
+ END_MSG_MAP()
+
+ // NOTE: Define _WTL_NEW_PAGE_NOTIFY_HANDLERS to use new notification
+ // handlers that return direct values without any restrictions
+ LRESULT OnNotify(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+#ifndef _WIN32_WCE
+ // This notification is sometimes received on Windows CE after the window is already destroyed
+ ATLASSERT(::IsWindow(m_hWnd));
+#endif
+ NMHDR* pNMHDR = (NMHDR*)lParam;
+
+ // don't handle messages not from the page/sheet itself
+ if(pNMHDR->hwndFrom != m_hWnd && pNMHDR->hwndFrom != ::GetParent(m_hWnd))
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+#ifdef _WIN32_WCE
+ ATLASSERT(::IsWindow(m_hWnd));
+#endif
+
+ T* pT = static_cast<T*>(this);
+ LRESULT lResult = 0;
+ switch(pNMHDR->code)
+ {
+#ifdef _WTL_NEW_PAGE_NOTIFY_HANDLERS
+ case PSN_SETACTIVE:
+ lResult = pT->OnSetActive();
+ break;
+ case PSN_KILLACTIVE:
+ lResult = pT->OnKillActive();
+ break;
+ case PSN_APPLY:
+ lResult = pT->OnApply();
+ break;
+ case PSN_RESET:
+ pT->OnReset();
+ break;
+ case PSN_QUERYCANCEL:
+ lResult = pT->OnQueryCancel();
+ break;
+ case PSN_WIZNEXT:
+ lResult = pT->OnWizardNext();
+ break;
+ case PSN_WIZBACK:
+ lResult = pT->OnWizardBack();
+ break;
+ case PSN_WIZFINISH:
+ lResult = pT->OnWizardFinish();
+ break;
+ case PSN_HELP:
+ pT->OnHelp();
+ break;
+#ifndef _WIN32_WCE
+#if (_WIN32_IE >= 0x0400)
+ case PSN_GETOBJECT:
+ if(!pT->OnGetObject((LPNMOBJECTNOTIFY)lParam))
+ bHandled = FALSE;
+ break;
+#endif // (_WIN32_IE >= 0x0400)
+#if (_WIN32_IE >= 0x0500)
+ case PSN_TRANSLATEACCELERATOR:
+ {
+ LPPSHNOTIFY lpPSHNotify = (LPPSHNOTIFY)lParam;
+ lResult = pT->OnTranslateAccelerator((LPMSG)lpPSHNotify->lParam);
+ }
+ break;
+ case PSN_QUERYINITIALFOCUS:
+ {
+ LPPSHNOTIFY lpPSHNotify = (LPPSHNOTIFY)lParam;
+ lResult = (LRESULT)pT->OnQueryInitialFocus((HWND)lpPSHNotify->lParam);
+ }
+ break;
+#endif // (_WIN32_IE >= 0x0500)
+#endif // !_WIN32_WCE
+
+#else // !_WTL_NEW_PAGE_NOTIFY_HANDLERS
+ case PSN_SETACTIVE:
+ lResult = pT->OnSetActive() ? 0 : -1;
+ break;
+ case PSN_KILLACTIVE:
+ lResult = !pT->OnKillActive();
+ break;
+ case PSN_APPLY:
+ lResult = pT->OnApply() ? PSNRET_NOERROR : PSNRET_INVALID_NOCHANGEPAGE;
+ break;
+ case PSN_RESET:
+ pT->OnReset();
+ break;
+ case PSN_QUERYCANCEL:
+ lResult = !pT->OnQueryCancel();
+ break;
+ case PSN_WIZNEXT:
+ lResult = pT->OnWizardNext();
+ break;
+ case PSN_WIZBACK:
+ lResult = pT->OnWizardBack();
+ break;
+ case PSN_WIZFINISH:
+ lResult = !pT->OnWizardFinish();
+ break;
+ case PSN_HELP:
+ pT->OnHelp();
+ break;
+#ifndef _WIN32_WCE
+#if (_WIN32_IE >= 0x0400)
+ case PSN_GETOBJECT:
+ if(!pT->OnGetObject((LPNMOBJECTNOTIFY)lParam))
+ bHandled = FALSE;
+ break;
+#endif // (_WIN32_IE >= 0x0400)
+#if (_WIN32_IE >= 0x0500)
+ case PSN_TRANSLATEACCELERATOR:
+ {
+ LPPSHNOTIFY lpPSHNotify = (LPPSHNOTIFY)lParam;
+ lResult = pT->OnTranslateAccelerator((LPMSG)lpPSHNotify->lParam) ? PSNRET_MESSAGEHANDLED : PSNRET_NOERROR;
+ }
+ break;
+ case PSN_QUERYINITIALFOCUS:
+ {
+ LPPSHNOTIFY lpPSHNotify = (LPPSHNOTIFY)lParam;
+ lResult = (LRESULT)pT->OnQueryInitialFocus((HWND)lpPSHNotify->lParam);
+ }
+ break;
+#endif // (_WIN32_IE >= 0x0500)
+#endif // !_WIN32_WCE
+
+#endif // !_WTL_NEW_PAGE_NOTIFY_HANDLERS
+ default:
+ bHandled = FALSE; // not handled
+ }
+
+ return lResult;
+ }
+
+// Overridables
+ // NOTE: Define _WTL_NEW_PAGE_NOTIFY_HANDLERS to use new notification
+ // handlers that return direct values without any restrictions
+#ifdef _WTL_NEW_PAGE_NOTIFY_HANDLERS
+ int OnSetActive()
+ {
+ // 0 = allow activate
+ // -1 = go back that was active
+ // page ID = jump to page
+ return 0;
+ }
+
+ BOOL OnKillActive()
+ {
+ // FALSE = allow deactivate
+ // TRUE = prevent deactivation
+ return FALSE;
+ }
+
+ int OnApply()
+ {
+ // PSNRET_NOERROR = apply OK
+ // PSNRET_INVALID = apply not OK, return to this page
+ // PSNRET_INVALID_NOCHANGEPAGE = apply not OK, don't change focus
+ return PSNRET_NOERROR;
+ }
+
+ void OnReset()
+ {
+ }
+
+ BOOL OnQueryCancel()
+ {
+ // FALSE = allow cancel
+ // TRUE = prevent cancel
+ return FALSE;
+ }
+
+ int OnWizardBack()
+ {
+ // 0 = goto previous page
+ // -1 = prevent page change
+ // >0 = jump to page by dlg ID
+ return 0;
+ }
+
+ int OnWizardNext()
+ {
+ // 0 = goto next page
+ // -1 = prevent page change
+ // >0 = jump to page by dlg ID
+ return 0;
+ }
+
+ INT_PTR OnWizardFinish()
+ {
+ // FALSE = allow finish
+ // TRUE = prevent finish
+ // HWND = prevent finish and set focus to HWND (CommCtrl 5.80 only)
+ return FALSE;
+ }
+
+ void OnHelp()
+ {
+ }
+
+#ifndef _WIN32_WCE
+#if (_WIN32_IE >= 0x0400)
+ BOOL OnGetObject(LPNMOBJECTNOTIFY /*lpObjectNotify*/)
+ {
+ return FALSE; // not processed
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500)
+ int OnTranslateAccelerator(LPMSG /*lpMsg*/)
+ {
+ // PSNRET_NOERROR - message not handled
+ // PSNRET_MESSAGEHANDLED - message handled
+ return PSNRET_NOERROR;
+ }
+
+ HWND OnQueryInitialFocus(HWND /*hWndFocus*/)
+ {
+ // NULL = set focus to default control
+ // HWND = set focus to HWND
+ return NULL;
+ }
+#endif // (_WIN32_IE >= 0x0500)
+#endif // !_WIN32_WCE
+
+#else // !_WTL_NEW_PAGE_NOTIFY_HANDLERS
+ BOOL OnSetActive()
+ {
+ return TRUE;
+ }
+
+ BOOL OnKillActive()
+ {
+ return TRUE;
+ }
+
+ BOOL OnApply()
+ {
+ return TRUE;
+ }
+
+ void OnReset()
+ {
+ }
+
+ BOOL OnQueryCancel()
+ {
+ return TRUE; // ok to cancel
+ }
+
+ int OnWizardBack()
+ {
+ // 0 = goto previous page
+ // -1 = prevent page change
+ // >0 = jump to page by dlg ID
+ return 0;
+ }
+
+ int OnWizardNext()
+ {
+ // 0 = goto next page
+ // -1 = prevent page change
+ // >0 = jump to page by dlg ID
+ return 0;
+ }
+
+ BOOL OnWizardFinish()
+ {
+ return TRUE;
+ }
+
+ void OnHelp()
+ {
+ }
+
+#ifndef _WIN32_WCE
+#if (_WIN32_IE >= 0x0400)
+ BOOL OnGetObject(LPNMOBJECTNOTIFY /*lpObjectNotify*/)
+ {
+ return FALSE; // not processed
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500)
+ BOOL OnTranslateAccelerator(LPMSG /*lpMsg*/)
+ {
+ return FALSE; // not translated
+ }
+
+ HWND OnQueryInitialFocus(HWND /*hWndFocus*/)
+ {
+ return NULL; // default
+ }
+#endif // (_WIN32_IE >= 0x0500)
+#endif // !_WIN32_WCE
+
+#endif // !_WTL_NEW_PAGE_NOTIFY_HANDLERS
+};
+
+// for non-customized pages
+template <WORD t_wDlgTemplateID>
+class CPropertyPage : public CPropertyPageImpl<CPropertyPage<t_wDlgTemplateID> >
+{
+public:
+ enum { IDD = t_wDlgTemplateID };
+
+ CPropertyPage(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : CPropertyPageImpl<CPropertyPage>(title)
+ { }
+
+ DECLARE_EMPTY_MSG_MAP()
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CAxPropertyPageImpl - property page that hosts ActiveX controls
+
+#ifndef _ATL_NO_HOSTING
+
+// Note: You must #include <atlhost.h> to use these classes
+
+template <class T, class TBase = CPropertyPageWindow>
+class ATL_NO_VTABLE CAxPropertyPageImpl : public CPropertyPageImpl< T, TBase >
+{
+public:
+// Data members
+ HGLOBAL m_hInitData;
+ HGLOBAL m_hDlgRes;
+ HGLOBAL m_hDlgResSplit;
+
+// Constructor/destructor
+ CAxPropertyPageImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL) :
+ CPropertyPageImpl< T, TBase >(title),
+ m_hInitData(NULL), m_hDlgRes(NULL), m_hDlgResSplit(NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+
+ // initialize ActiveX hosting and modify dialog template
+ ATL::AtlAxWinInit();
+
+ HINSTANCE hInstance = ModuleHelper::GetResourceInstance();
+ LPCTSTR lpTemplateName = MAKEINTRESOURCE(pT->IDD);
+ HRSRC hDlg = ::FindResource(hInstance, lpTemplateName, (LPTSTR)RT_DIALOG);
+ if(hDlg != NULL)
+ {
+ HRSRC hDlgInit = ::FindResource(hInstance, lpTemplateName, (LPTSTR)_ATL_RT_DLGINIT);
+
+ BYTE* pInitData = NULL;
+ if(hDlgInit != NULL)
+ {
+ m_hInitData = ::LoadResource(hInstance, hDlgInit);
+ pInitData = (BYTE*)::LockResource(m_hInitData);
+ }
+
+ m_hDlgRes = ::LoadResource(hInstance, hDlg);
+ DLGTEMPLATE* pDlg = (DLGTEMPLATE*)::LockResource(m_hDlgRes);
+ LPCDLGTEMPLATE lpDialogTemplate = ATL::_DialogSplitHelper::SplitDialogTemplate(pDlg, pInitData);
+ if(lpDialogTemplate != pDlg)
+ m_hDlgResSplit = GlobalHandle(lpDialogTemplate);
+
+ // set up property page to use in-memory dialog template
+ if(lpDialogTemplate != NULL)
+ {
+ m_psp.dwFlags |= PSP_DLGINDIRECT;
+ m_psp.pResource = lpDialogTemplate;
+ }
+ else
+ {
+ ATLASSERT(FALSE && _T("CAxPropertyPageImpl - ActiveX initializtion failed!"));
+ }
+ }
+ else
+ {
+ ATLASSERT(FALSE && _T("CAxPropertyPageImpl - Cannot find dialog template!"));
+ }
+ }
+
+ ~CAxPropertyPageImpl()
+ {
+ if(m_hInitData != NULL)
+ {
+ UnlockResource(m_hInitData);
+ FreeResource(m_hInitData);
+ }
+ if(m_hDlgRes != NULL)
+ {
+ UnlockResource(m_hDlgRes);
+ FreeResource(m_hDlgRes);
+ }
+ if(m_hDlgResSplit != NULL)
+ {
+ ::GlobalFree(m_hDlgResSplit);
+ }
+ }
+
+// Methods
+ // call this one to handle keyboard message for ActiveX controls
+ BOOL PreTranslateMessage(LPMSG pMsg)
+ {
+ if ((pMsg->message < WM_KEYFIRST || pMsg->message > WM_KEYLAST) &&
+ (pMsg->message < WM_MOUSEFIRST || pMsg->message > WM_MOUSELAST))
+ return FALSE;
+ // find a direct child of the dialog from the window that has focus
+ HWND hWndCtl = ::GetFocus();
+ if (IsChild(hWndCtl) && ::GetParent(hWndCtl) != m_hWnd)
+ {
+ do
+ {
+ hWndCtl = ::GetParent(hWndCtl);
+ }
+ while (::GetParent(hWndCtl) != m_hWnd);
+ }
+ // give controls a chance to translate this message
+ return (BOOL)::SendMessage(hWndCtl, WM_FORWARDMSG, 0, (LPARAM)pMsg);
+ }
+
+// Overridables
+#if (_WIN32_IE >= 0x0500)
+ // new default implementation for ActiveX hosting pages
+#ifdef _WTL_NEW_PAGE_NOTIFY_HANDLERS
+ int OnTranslateAccelerator(LPMSG lpMsg)
+ {
+ T* pT = static_cast<T*>(this);
+ return (pT->PreTranslateMessage(lpMsg) != FALSE) ? PSNRET_MESSAGEHANDLED : PSNRET_NOERROR;
+ }
+#else // !_WTL_NEW_PAGE_NOTIFY_HANDLERS
+ BOOL OnTranslateAccelerator(LPMSG lpMsg)
+ {
+ T* pT = static_cast<T*>(this);
+ return pT->PreTranslateMessage(lpMsg);
+ }
+#endif // !_WTL_NEW_PAGE_NOTIFY_HANDLERS
+#endif // (_WIN32_IE >= 0x0500)
+
+// Support for new stuff in ATL7
+#if (_ATL_VER >= 0x0700)
+ int GetIDD()
+ {
+ return( static_cast<T*>(this)->IDD );
+ }
+
+ virtual DLGPROC GetDialogProc()
+ {
+ return DialogProc;
+ }
+
+ static INT_PTR CALLBACK DialogProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+ {
+ CAxPropertyPageImpl< T, TBase >* pThis = (CAxPropertyPageImpl< T, TBase >*)hWnd;
+ if (uMsg == WM_INITDIALOG)
+ {
+ HRESULT hr;
+ if (FAILED(hr = pThis->CreateActiveXControls(pThis->GetIDD())))
+ {
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+ }
+ return CPropertyPageImpl< T, TBase >::DialogProc(hWnd, uMsg, wParam, lParam);
+ }
+
+// ActiveX controls creation
+ virtual HRESULT CreateActiveXControls(UINT nID)
+ {
+ // Load dialog template and InitData
+ HRSRC hDlgInit = ::FindResource(ATL::_AtlBaseModule.GetResourceInstance(), MAKEINTRESOURCE(nID), (LPTSTR)_ATL_RT_DLGINIT);
+ BYTE* pInitData = NULL;
+ HGLOBAL hData = NULL;
+ HRESULT hr = S_OK;
+ if (hDlgInit != NULL)
+ {
+ hData = ::LoadResource(ATL::_AtlBaseModule.GetResourceInstance(), hDlgInit);
+ if (hData != NULL)
+ pInitData = (BYTE*) ::LockResource(hData);
+ }
+
+ HRSRC hDlg = ::FindResource(ATL::_AtlBaseModule.GetResourceInstance(), MAKEINTRESOURCE(nID), (LPTSTR)RT_DIALOG);
+ if (hDlg != NULL)
+ {
+ HGLOBAL hResource = ::LoadResource(ATL::_AtlBaseModule.GetResourceInstance(), hDlg);
+ DLGTEMPLATE* pDlg = NULL;
+ if (hResource != NULL)
+ {
+ pDlg = (DLGTEMPLATE*) ::LockResource(hResource);
+ if (pDlg != NULL)
+ {
+ // Get first control on the template
+ BOOL bDialogEx = ATL::_DialogSplitHelper::IsDialogEx(pDlg);
+ WORD nItems = ATL::_DialogSplitHelper::DlgTemplateItemCount(pDlg);
+
+ // Get first control on the dialog
+ DLGITEMTEMPLATE* pItem = ATL::_DialogSplitHelper::FindFirstDlgItem(pDlg);
+ HWND hWndPrev = GetWindow(GW_CHILD);
+
+ // Create all ActiveX cotnrols in the dialog template and place them in the correct tab order (z-order)
+ for (WORD nItem = 0; nItem < nItems; nItem++)
+ {
+ DWORD wID = bDialogEx ? ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->id : pItem->id;
+ if (ATL::_DialogSplitHelper::IsActiveXControl(pItem, bDialogEx))
+ {
+ BYTE* pData = NULL;
+ DWORD dwLen = ATL::_DialogSplitHelper::FindCreateData(wID, pInitData, &pData);
+ ATL::CComPtr<IStream> spStream;
+ if (dwLen != 0)
+ {
+ HGLOBAL h = GlobalAlloc(GHND, dwLen);
+ if (h != NULL)
+ {
+ BYTE* pBytes = (BYTE*) GlobalLock(h);
+ BYTE* pSource = pData;
+ SecureHelper::memcpy_x(pBytes, dwLen, pSource, dwLen);
+ GlobalUnlock(h);
+ CreateStreamOnHGlobal(h, TRUE, &spStream);
+ }
+ else
+ {
+ hr = E_OUTOFMEMORY;
+ break;
+ }
+ }
+
+ ATL::CComBSTR bstrLicKey;
+ hr = ATL::_DialogSplitHelper::ParseInitData(spStream, &bstrLicKey.m_str);
+ if (SUCCEEDED(hr))
+ {
+ ATL::CAxWindow2 wnd;
+ // Get control caption.
+ LPWSTR pszClassName =
+ bDialogEx ?
+ (LPWSTR)(((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem) + 1) :
+ (LPWSTR)(pItem + 1);
+ // Get control rect.
+ RECT rect;
+ rect.left =
+ bDialogEx ?
+ ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->x :
+ pItem->x;
+ rect.top =
+ bDialogEx ?
+ ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->y :
+ pItem->y;
+ rect.right = rect.left +
+ (bDialogEx ?
+ ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->cx :
+ pItem->cx);
+ rect.bottom = rect.top +
+ (bDialogEx ?
+ ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->cy :
+ pItem->cy);
+
+ // Convert from dialog units to screen units
+ MapDialogRect(&rect);
+
+ // Create AxWindow with a NULL caption.
+ wnd.Create(m_hWnd,
+ &rect,
+ NULL,
+ (bDialogEx ?
+ ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->style :
+ pItem->style) | WS_TABSTOP,
+ bDialogEx ?
+ ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->exStyle :
+ 0,
+ bDialogEx ?
+ ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->id :
+ pItem->id,
+ NULL);
+
+ if (wnd != NULL)
+ {
+#ifndef _WIN32_WCE
+ // Set the Help ID
+ if (bDialogEx && ((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->helpID != 0)
+ wnd.SetWindowContextHelpId(((ATL::_DialogSplitHelper::DLGITEMTEMPLATEEX*)pItem)->helpID);
+#endif // !_WIN32_WCE
+ // Try to create the ActiveX control.
+ hr = wnd.CreateControlLic(pszClassName, spStream, NULL, bstrLicKey);
+ if (FAILED(hr))
+ break;
+ // Set the correct tab position.
+ if (nItem == 0)
+ hWndPrev = HWND_TOP;
+ wnd.SetWindowPos(hWndPrev, 0,0,0,0,SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
+ hWndPrev = wnd;
+ }
+ else
+ {
+ hr = ATL::AtlHresultFromLastError();
+ }
+ }
+ }
+ else
+ {
+ if (nItem != 0)
+ hWndPrev = ::GetWindow(hWndPrev, GW_HWNDNEXT);
+ }
+ pItem = ATL::_DialogSplitHelper::FindNextDlgItem(pItem, bDialogEx);
+ }
+ }
+ else
+ hr = ATL::AtlHresultFromLastError();
+ }
+ else
+ hr = ATL::AtlHresultFromLastError();
+ }
+ return hr;
+ }
+
+// Event handling support
+ HRESULT AdviseSinkMap(bool bAdvise)
+ {
+ if(!bAdvise && m_hWnd == NULL)
+ {
+ // window is gone, controls are already unadvised
+ ATLTRACE2(atlTraceUI, 0, _T("CAxPropertyPageImpl::AdviseSinkMap called after the window was destroyed\n"));
+ return S_OK;
+ }
+ HRESULT hRet = E_NOTIMPL;
+ __if_exists(T::_GetSinkMapFinder)
+ {
+ T* pT = static_cast<T*>(this);
+ hRet = AtlAdviseSinkMap(pT, bAdvise);
+ }
+ return hRet;
+ }
+
+// Message map and handlers
+ typedef CPropertyPageImpl< T, TBase> _baseClass;
+ BEGIN_MSG_MAP(CAxPropertyPageImpl)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ CHAIN_MSG_MAP(_baseClass)
+ END_MSG_MAP()
+
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ // initialize controls in dialog with DLGINIT resource section
+ ExecuteDlgInit(static_cast<T*>(this)->IDD);
+ AdviseSinkMap(true);
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ AdviseSinkMap(false);
+ bHandled = FALSE;
+ return 1;
+ }
+#endif // (_ATL_VER >= 0x0700)
+};
+
+// for non-customized pages
+template <WORD t_wDlgTemplateID>
+class CAxPropertyPage : public CAxPropertyPageImpl<CAxPropertyPage<t_wDlgTemplateID> >
+{
+public:
+ enum { IDD = t_wDlgTemplateID };
+
+ CAxPropertyPage(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : CAxPropertyPageImpl<CAxPropertyPage>(title)
+ { }
+
+#if (_WIN32_IE >= 0x0500) || (_ATL_VER >= 0x0700)
+ // not empty so we handle accelerators/create controls
+ BEGIN_MSG_MAP(CAxPropertyPage)
+ CHAIN_MSG_MAP(CAxPropertyPageImpl<CAxPropertyPage<t_wDlgTemplateID> >)
+ END_MSG_MAP()
+#else // !((_WIN32_IE >= 0x0500) || (_ATL_VER >= 0x0700))
+ DECLARE_EMPTY_MSG_MAP()
+#endif // !((_WIN32_IE >= 0x0500) || (_ATL_VER >= 0x0700))
+};
+
+#endif // _ATL_NO_HOSTING
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Wizard97 Support
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+// Sample wizard dialog resources:
+//
+// IDD_WIZ97_INTERIOR_BLANK DIALOG 0, 0, 317, 143
+// STYLE DS_SETFONT | WS_CHILD | WS_DISABLED | WS_CAPTION
+// CAPTION "Wizard97 Property Page - Interior"
+// FONT 8, "MS Shell Dlg"
+// BEGIN
+// END
+//
+// IDD_WIZ97_EXTERIOR_BLANK DIALOGEX 0, 0, 317, 193
+// STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD | WS_DISABLED | WS_CAPTION
+// CAPTION "Wizard97 Property Page - Welcome/Complete"
+// FONT 8, "MS Shell Dlg", 0, 0, 0x0
+// BEGIN
+// LTEXT "Welcome to the X Wizard",IDC_WIZ97_EXTERIOR_TITLE,115,8,
+// 195,24
+// LTEXT "Wizard Explanation\r\n(The height of the static text should be in multiples of 8 dlus)",
+// IDC_STATIC,115,40,195,16
+// LTEXT "h",IDC_WIZ97_BULLET1,118,64,8,8
+// LTEXT "List Item 1 (the h is turned into a bullet)",IDC_STATIC,
+// 127,63,122,8
+// LTEXT "h",IDC_WIZ97_BULLET2,118,79,8,8
+// LTEXT "List Item 2. Keep 7 dlus between paragraphs",IDC_STATIC,
+// 127,78,33,8
+// CONTROL "&Do not show this Welcome page again",
+// IDC_WIZ97_WELCOME_NOTAGAIN,"Button",BS_AUTOCHECKBOX |
+// WS_TABSTOP,115,169,138,10
+// END
+//
+// GUIDELINES DESIGNINFO
+// BEGIN
+// IDD_WIZ97_INTERIOR_BLANK, DIALOG
+// BEGIN
+// LEFTMARGIN, 7
+// RIGHTMARGIN, 310
+// VERTGUIDE, 21
+// VERTGUIDE, 31
+// VERTGUIDE, 286
+// VERTGUIDE, 296
+// TOPMARGIN, 7
+// BOTTOMMARGIN, 136
+// HORZGUIDE, 8
+// END
+//
+// IDD_WIZ97_EXTERIOR_BLANK, DIALOG
+// BEGIN
+// RIGHTMARGIN, 310
+// VERTGUIDE, 115
+// VERTGUIDE, 118
+// VERTGUIDE, 127
+// TOPMARGIN, 7
+// BOTTOMMARGIN, 186
+// HORZGUIDE, 8
+// HORZGUIDE, 32
+// HORZGUIDE, 40
+// HORZGUIDE, 169
+// END
+// END
+
+///////////////////////////////////////////////////////////////////////////////
+// CWizard97SheetWindow - client side for a Wizard 97 style wizard sheet
+
+class CWizard97SheetWindow : public CPropertySheetWindow
+{
+public:
+// Constructors
+ CWizard97SheetWindow(HWND hWnd = NULL) : CPropertySheetWindow(hWnd)
+ { }
+
+ CWizard97SheetWindow& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Operations
+ HFONT GetExteriorPageTitleFont(void)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HFONT)::SendMessage(m_hWnd, GetMessage_GetExteriorPageTitleFont(), 0, 0L);
+ }
+
+ HFONT GetBulletFont(void)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HFONT)::SendMessage(m_hWnd, GetMessage_GetBulletFont(), 0, 0L);
+ }
+
+// Helpers
+ static UINT GetMessage_GetExteriorPageTitleFont()
+ {
+ static UINT uGetExteriorPageTitleFont = 0;
+ if(uGetExteriorPageTitleFont == 0)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CWizard97SheetWindow::GetMessage_GetExteriorPageTitleFont().\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(uGetExteriorPageTitleFont == 0)
+ uGetExteriorPageTitleFont = ::RegisterWindowMessage(_T("GetExteriorPageTitleFont_531AF056-B8BE-4c4c-B786-AC608DF0DF12"));
+
+ lock.Unlock();
+ }
+ ATLASSERT(uGetExteriorPageTitleFont != 0);
+ return uGetExteriorPageTitleFont;
+ }
+
+ static UINT GetMessage_GetBulletFont()
+ {
+ static UINT uGetBulletFont = 0;
+ if(uGetBulletFont == 0)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CWizard97SheetWindow::GetMessage_GetBulletFont().\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(uGetBulletFont == 0)
+ uGetBulletFont = ::RegisterWindowMessage(_T("GetBulletFont_AD347D08-8F65-45ef-982E-6352E8218AD5"));
+
+ lock.Unlock();
+ }
+ ATLASSERT(uGetBulletFont != 0);
+ return uGetBulletFont;
+ }
+
+// Implementation - override to prevent usage
+ HWND Create(LPCTSTR, HWND, ATL::_U_RECT = NULL, LPCTSTR = NULL, DWORD = 0, DWORD = 0, ATL::_U_MENUorID = 0U, LPVOID = NULL)
+ {
+ ATLASSERT(FALSE);
+ return NULL;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CWizard97SheetImpl - implements a Wizard 97 style wizard sheet
+
+template <class T, class TBase = CWizard97SheetWindow>
+class ATL_NO_VTABLE CWizard97SheetImpl : public CPropertySheetImpl< T, TBase >
+{
+protected:
+// Typedefs
+ typedef CWizard97SheetImpl< T, TBase > thisClass;
+ typedef CPropertySheetImpl< T, TBase > baseClass;
+
+// Member variables
+ CFont m_fontExteriorPageTitle; // Welcome and Completion page title font
+ CFont m_fontBullet; // Bullet font (used on static text 'h' to produce a small bullet)
+ bool m_bReceivedFirstSizeMessage;
+
+public:
+ CWizard97SheetImpl(ATL::_U_STRINGorID title, ATL::_U_STRINGorID headerBitmap, ATL::_U_STRINGorID watermarkBitmap, UINT uStartPage = 0, HWND hWndParent = NULL) :
+ baseClass(title, uStartPage, hWndParent),
+ m_bReceivedFirstSizeMessage(false)
+ {
+ m_psh.dwFlags &= ~(PSH_NOCONTEXTHELP);
+ m_psh.dwFlags &= ~(PSH_WIZARD | PSH_WIZARD_LITE);
+
+ m_psh.dwFlags |= (PSH_HASHELP | PSH_WIZARDCONTEXTHELP);
+ m_psh.dwFlags |= PSH_WIZARD97;
+
+ baseClass::SetHeader(headerBitmap.m_lpstr);
+ baseClass::SetWatermark(watermarkBitmap.m_lpstr);
+ }
+
+// Overrides from base class
+ void OnSheetInitialized()
+ {
+ T* pT = static_cast<T*>(this);
+ pT->_InitializeFonts();
+
+ // We'd like to center the wizard here, but its too early.
+ // Instead, we'll do CenterWindow upon our first WM_SIZE message
+ }
+
+// Initialization
+ void _InitializeFonts()
+ {
+ // Setup the Title and Bullet Font
+ // (Property pages can send the "get external page title font" and "get bullet font" messages)
+ // The derived class needs to do the actual SetFont for the dialog items)
+
+ CFontHandle fontThisDialog = this->GetFont();
+ CClientDC dcScreen(NULL);
+
+ LOGFONT titleLogFont = {0};
+ LOGFONT bulletLogFont = {0};
+ fontThisDialog.GetLogFont(&titleLogFont);
+ fontThisDialog.GetLogFont(&bulletLogFont);
+
+ // The Wizard 97 Spec recommends to do the Title Font
+ // as Verdana Bold, 12pt.
+ titleLogFont.lfCharSet = DEFAULT_CHARSET;
+ titleLogFont.lfWeight = FW_BOLD;
+ SecureHelper::strcpy_x(titleLogFont.lfFaceName, _countof(titleLogFont.lfFaceName), _T("Verdana Bold"));
+ INT titleFontPointSize = 12;
+ titleLogFont.lfHeight = -::MulDiv(titleFontPointSize, dcScreen.GetDeviceCaps(LOGPIXELSY), 72);
+ m_fontExteriorPageTitle.CreateFontIndirect(&titleLogFont);
+
+ // The Wizard 97 Spec recommends to do Bullets by having
+ // static text of "h" in the Marlett font.
+ bulletLogFont.lfCharSet = DEFAULT_CHARSET;
+ bulletLogFont.lfWeight = FW_NORMAL;
+ SecureHelper::strcpy_x(bulletLogFont.lfFaceName, _countof(bulletLogFont.lfFaceName), _T("Marlett"));
+ INT bulletFontSize = 8;
+ bulletLogFont.lfHeight = -::MulDiv(bulletFontSize, dcScreen.GetDeviceCaps(LOGPIXELSY), 72);
+ m_fontBullet.CreateFontIndirect(&bulletLogFont);
+ }
+
+// Message Handling
+ BEGIN_MSG_MAP(thisClass)
+ MESSAGE_HANDLER(CWizard97SheetWindow::GetMessage_GetExteriorPageTitleFont(), OnGetExteriorPageTitleFont)
+ MESSAGE_HANDLER(CWizard97SheetWindow::GetMessage_GetBulletFont(), OnGetBulletFont)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ CHAIN_MSG_MAP(baseClass)
+ END_MSG_MAP()
+
+ LRESULT OnGetExteriorPageTitleFont(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return (LRESULT)(HFONT)m_fontExteriorPageTitle;
+ }
+
+ LRESULT OnGetBulletFont(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return (LRESULT)(HFONT)m_fontBullet;
+ }
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(!m_bReceivedFirstSizeMessage)
+ {
+ m_bReceivedFirstSizeMessage = true;
+ this->CenterWindow();
+ }
+
+ bHandled = FALSE;
+ return 0;
+ }
+};
+
+// for non-customized sheets
+class CWizard97Sheet : public CWizard97SheetImpl<CWizard97Sheet>
+{
+protected:
+// Typedefs
+ typedef CWizard97Sheet thisClass;
+ typedef CWizard97SheetImpl<CWizard97Sheet> baseClass;
+
+public:
+ CWizard97Sheet(ATL::_U_STRINGorID title, ATL::_U_STRINGorID headerBitmap, ATL::_U_STRINGorID watermarkBitmap, UINT uStartPage = 0, HWND hWndParent = NULL) :
+ baseClass(title, headerBitmap, watermarkBitmap, uStartPage, hWndParent)
+ { }
+
+ BEGIN_MSG_MAP(thisClass)
+ CHAIN_MSG_MAP(baseClass)
+ END_MSG_MAP()
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CWizard97PageWindow - client side for a Wizard 97 style wizard page
+
+#define WIZARD97_EXTERIOR_CXDLG 317
+#define WIZARD97_EXTERIOR_CYDLG 193
+
+#define WIZARD97_INTERIOR_CXDLG 317
+#define WIZARD97_INTERIOR_CYDLG 143
+
+class CWizard97PageWindow : public CPropertyPageWindow
+{
+public:
+// Constructors
+ CWizard97PageWindow(HWND hWnd = NULL) : CPropertyPageWindow(hWnd)
+ { }
+
+ CWizard97PageWindow& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Attributes
+ CWizard97SheetWindow GetPropertySheet() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return CWizard97SheetWindow(GetParent());
+ }
+
+// Operations
+ HFONT GetExteriorPageTitleFont(void)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return GetPropertySheet().GetExteriorPageTitleFont();
+ }
+
+ HFONT GetBulletFont(void)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return GetPropertySheet().GetBulletFont();
+ }
+
+// Implementation - overrides to prevent usage
+ HWND Create(LPCTSTR, HWND, ATL::_U_RECT = NULL, LPCTSTR = NULL, DWORD = 0, DWORD = 0, ATL::_U_MENUorID = 0U, LPVOID = NULL)
+ {
+ ATLASSERT(FALSE);
+ return NULL;
+ }
+
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CWizard97PageImpl - implements a Wizard 97 style wizard page
+
+template <class T, class TBase = CWizard97PageWindow>
+class ATL_NO_VTABLE CWizard97PageImpl : public CPropertyPageImpl< T, TBase >
+{
+protected:
+// Typedefs
+ typedef CWizard97PageImpl< T, TBase > thisClass;
+ typedef CPropertyPageImpl< T, TBase > baseClass;
+
+public:
+ CWizard97PageImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : baseClass(title)
+ { }
+
+// Message Handling
+ BEGIN_MSG_MAP(thisClass)
+ CHAIN_MSG_MAP(baseClass)
+ END_MSG_MAP()
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CWizard97ExteriorPageImpl - implements a Wizard 97 style exterior wizard page
+
+template <class T, class TBase = CWizard97PageWindow>
+class ATL_NO_VTABLE CWizard97ExteriorPageImpl : public CPropertyPageImpl< T, TBase >
+{
+protected:
+// Typedefs
+ typedef CWizard97ExteriorPageImpl< T, TBase > thisClass;
+ typedef CPropertyPageImpl< T, TBase > baseClass;
+
+public:
+// Constructors
+ CWizard97ExteriorPageImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : baseClass(title)
+ {
+ m_psp.dwFlags |= PSP_HASHELP;
+ m_psp.dwFlags |= PSP_HIDEHEADER;
+ }
+
+// Message Handling
+ BEGIN_MSG_MAP(thisClass)
+ CHAIN_MSG_MAP(baseClass)
+ END_MSG_MAP()
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CWizard97InteriorPageImpl - implements a Wizard 97 style interior wizard page
+
+template <class T, class TBase = CWizard97PageWindow>
+class ATL_NO_VTABLE CWizard97InteriorPageImpl : public CPropertyPageImpl< T, TBase >
+{
+protected:
+// Typedefs
+ typedef CWizard97InteriorPageImpl< T, TBase > thisClass;
+ typedef CPropertyPageImpl< T, TBase > baseClass;
+
+public:
+// Constructors
+ CWizard97InteriorPageImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : baseClass(title)
+ {
+ m_psp.dwFlags |= PSP_HASHELP;
+ m_psp.dwFlags &= ~PSP_HIDEHEADER;
+ m_psp.dwFlags |= PSP_USEHEADERTITLE | PSP_USEHEADERSUBTITLE;
+
+ // Be sure to have the derived class define this in the constructor.
+ // We'll default it to something obvious in case its forgotten.
+ baseClass::SetHeaderTitle(_T("Call SetHeaderTitle in Derived Class"));
+ baseClass::SetHeaderSubTitle(_T("Call SetHeaderSubTitle in the constructor of the Derived Class."));
+ }
+
+// Message Handling
+ BEGIN_MSG_MAP(thisClass)
+ CHAIN_MSG_MAP(baseClass)
+ END_MSG_MAP()
+};
+
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Aero Wizard support
+
+#if (_WIN32_WINNT >= 0x0600) && !defined(_WIN32_WCE)
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroWizardFrameWindow - client side for an Aero Wizard frame window
+
+class CAeroWizardFrameWindow : public CPropertySheetWindow
+{
+public:
+// Constructors
+ CAeroWizardFrameWindow(HWND hWnd = NULL) : CPropertySheetWindow(hWnd)
+ { }
+
+ CAeroWizardFrameWindow& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Operations - new, Aero Wizard only
+ void SetNextText(LPCWSTR lpszText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_SETNEXTTEXT, 0, (LPARAM)lpszText);
+ }
+
+ void ShowWizardButtons(DWORD dwButtons, DWORD dwStates)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::PostMessage(m_hWnd, PSM_SHOWWIZBUTTONS, (WPARAM)dwStates, (LPARAM)dwButtons);
+ }
+
+ void EnableWizardButtons(DWORD dwButtons, DWORD dwStates)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::PostMessage(m_hWnd, PSM_ENABLEWIZBUTTONS, (WPARAM)dwStates, (LPARAM)dwButtons);
+ }
+
+ void SetButtonText(DWORD dwButton, LPCWSTR lpszText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, PSM_SETBUTTONTEXT, (WPARAM)dwButton, (LPARAM)lpszText);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroWizardFrameImpl - implements an Aero Wizard frame
+
+template <class T, class TBase = CAeroWizardFrameWindow>
+class ATL_NO_VTABLE CAeroWizardFrameImpl : public CPropertySheetImpl<T, TBase >
+{
+public:
+// Constructor
+ CAeroWizardFrameImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL, UINT uStartPage = 0, HWND hWndParent = NULL) :
+ CPropertySheetImpl<T, TBase >(title, uStartPage, hWndParent)
+ {
+ m_psh.dwFlags |= PSH_WIZARD | PSH_AEROWIZARD;
+ }
+
+// Operations
+ void EnableResizing()
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+ m_psh.dwFlags |= PSH_RESIZABLE;
+ }
+
+ void UseHeaderBitmap()
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+ m_psh.dwFlags |= PSH_HEADERBITMAP;
+ }
+
+ void SetNoMargin()
+ {
+ ATLASSERT(m_hWnd == NULL); // can't do this after it's created
+ m_psh.dwFlags |= PSH_NOMARGIN;
+ }
+
+// Override to prevent use
+ HWND Create(HWND /*hWndParent*/ = NULL)
+ {
+ ATLASSERT(FALSE); // not supported for Aero Wizard
+ return NULL;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroWizardFrame - for non-customized frames
+
+class CAeroWizardFrame : public CAeroWizardFrameImpl<CAeroWizardFrame>
+{
+public:
+ CAeroWizardFrame(ATL::_U_STRINGorID title = (LPCTSTR)NULL, UINT uStartPage = 0, HWND hWndParent = NULL)
+ : CAeroWizardFrameImpl<CAeroWizardFrame>(title, uStartPage, hWndParent)
+ { }
+
+ BEGIN_MSG_MAP(CAeroWizardFrame)
+ MESSAGE_HANDLER(WM_COMMAND, CAeroWizardFrameImpl<CAeroWizardFrame>::OnCommand)
+ END_MSG_MAP()
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroWizardPageWindow - client side for an Aero Wizard page
+
+class CAeroWizardPageWindow : public CPropertyPageWindow
+{
+public:
+// Constructors
+ CAeroWizardPageWindow(HWND hWnd = NULL) : CPropertyPageWindow(hWnd)
+ { }
+
+ CAeroWizardPageWindow& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Attributes
+ CAeroWizardFrameWindow GetAeroWizardFrame() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ // This is not really top-level frame window, but it processes all frame messages
+ return CAeroWizardFrameWindow(GetParent());
+ }
+
+// Operations - new, Aero Wizard only
+ void SetNextText(LPCWSTR lpszText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetAeroWizardFrame().SetNextText(lpszText);
+ }
+
+ void ShowWizardButtons(DWORD dwButtons, DWORD dwStates)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetAeroWizardFrame().ShowWizardButtons(dwButtons, dwStates);
+ }
+
+ void EnableWizardButtons(DWORD dwButtons, DWORD dwStates)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetAeroWizardFrame().EnableWizardButtons(dwButtons, dwStates);
+ }
+
+ void SetButtonText(DWORD dwButton, LPCWSTR lpszText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetParent() != NULL);
+ GetAeroWizardFrame().SetButtonText(dwButton, lpszText);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroWizardPageImpl - implements an Aero Wizard page
+
+template <class T, class TBase = CAeroWizardPageWindow>
+class ATL_NO_VTABLE CAeroWizardPageImpl : public CPropertyPageImpl<T, TBase >
+{
+public:
+ CAeroWizardPageImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : CPropertyPageImpl<T, TBase >(title)
+ { }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroWizardPage - for non-customized pages
+
+template <WORD t_wDlgTemplateID>
+class CAeroWizardPage : public CAeroWizardPageImpl<CAeroWizardPage<t_wDlgTemplateID> >
+{
+public:
+ enum { IDD = t_wDlgTemplateID };
+
+ CAeroWizardPage(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : CAeroWizardPageImpl<CAeroWizardPage>(title)
+ { }
+
+ DECLARE_EMPTY_MSG_MAP()
+};
+
+
+#ifndef _ATL_NO_HOSTING
+
+// Note: You must #include <atlhost.h> to use these classes
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroWizardAxPageImpl - Aero Wizard page that hosts ActiveX controls
+
+template <class T, class TBase = CAeroWizardPageWindow>
+class ATL_NO_VTABLE CAeroWizardAxPageImpl : public CAxPropertyPageImpl< T, TBase >
+{
+public:
+ CAeroWizardAxPageImpl(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : CAxPropertyPageImpl< T, TBase >(title)
+ { }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroWizardAxPage - for non-customized pages
+
+template <WORD t_wDlgTemplateID>
+class CAeroWizardAxPage : public CAeroWizardAxPageImpl<CAeroWizardAxPage<t_wDlgTemplateID> >
+{
+public:
+ enum { IDD = t_wDlgTemplateID };
+
+ CAeroWizardAxPage(ATL::_U_STRINGorID title = (LPCTSTR)NULL) : CAeroWizardAxPageImpl<CAeroWizardAxPage>(title)
+ { }
+
+#if (_WIN32_IE >= 0x0500) || (_ATL_VER >= 0x0700)
+ // not empty so we handle accelerators/create controls
+ BEGIN_MSG_MAP(CAeroWizardAxPage)
+ CHAIN_MSG_MAP(CAeroWizardAxPageImpl<CAeroWizardAxPage<t_wDlgTemplateID> >)
+ END_MSG_MAP()
+#else // !((_WIN32_IE >= 0x0500) || (_ATL_VER >= 0x0700))
+ DECLARE_EMPTY_MSG_MAP()
+#endif // !((_WIN32_IE >= 0x0500) || (_ATL_VER >= 0x0700))
+};
+
+#endif // _ATL_NO_HOSTING
+
+#endif // (_WIN32_WINNT >= 0x0600) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// TaskDialog support
+
+#if ((_WIN32_WINNT >= 0x0600) || defined(_WTL_TASKDIALOG)) && !defined(_WIN32_WCE)
+
+///////////////////////////////////////////////////////////////////////////////
+// AtlTaskDialog - support for TaskDialog() function
+
+inline int AtlTaskDialog(HWND hWndParent,
+ ATL::_U_STRINGorID WindowTitle, ATL::_U_STRINGorID MainInstructionText, ATL::_U_STRINGorID ContentText,
+ TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons = 0U, ATL::_U_STRINGorID Icon = (LPCTSTR)NULL)
+{
+ int nRet = -1;
+
+#ifdef _WTL_TASKDIALOG_DIRECT
+ USES_CONVERSION;
+ HRESULT hRet = ::TaskDialog(hWndParent, ModuleHelper::GetResourceInstance(),
+ IS_INTRESOURCE(WindowTitle.m_lpstr) ? (LPCWSTR) WindowTitle.m_lpstr : T2CW(WindowTitle.m_lpstr),
+ IS_INTRESOURCE(MainInstructionText.m_lpstr) ? (LPCWSTR) MainInstructionText.m_lpstr : T2CW(MainInstructionText.m_lpstr),
+ IS_INTRESOURCE(ContentText.m_lpstr) ? (LPCWSTR) ContentText.m_lpstr : T2CW(ContentText.m_lpstr),
+ dwCommonButtons,
+ IS_INTRESOURCE(Icon.m_lpstr) ? (LPCWSTR) Icon.m_lpstr : T2CW(Icon.m_lpstr),
+ &nRet);
+ ATLVERIFY(SUCCEEDED(hRet));
+#else
+ // This allows apps to run on older versions of Windows
+ typedef HRESULT (STDAPICALLTYPE *PFN_TaskDialog)(HWND hwndParent, HINSTANCE hInstance, PCWSTR pszWindowTitle, PCWSTR pszMainInstruction, PCWSTR pszContent, TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons, PCWSTR pszIcon, int* pnButton);
+
+ HMODULE m_hCommCtrlDLL = ::LoadLibrary(_T("comctl32.dll"));
+ if(m_hCommCtrlDLL != NULL)
+ {
+ PFN_TaskDialog pfnTaskDialog = (PFN_TaskDialog)::GetProcAddress(m_hCommCtrlDLL, "TaskDialog");
+ if(pfnTaskDialog != NULL)
+ {
+ USES_CONVERSION;
+ HRESULT hRet = pfnTaskDialog(hWndParent, ModuleHelper::GetResourceInstance(),
+ IS_INTRESOURCE(WindowTitle.m_lpstr) ? (LPCWSTR) WindowTitle.m_lpstr : T2CW(WindowTitle.m_lpstr),
+ IS_INTRESOURCE(MainInstructionText.m_lpstr) ? (LPCWSTR) MainInstructionText.m_lpstr : T2CW(MainInstructionText.m_lpstr),
+ IS_INTRESOURCE(ContentText.m_lpstr) ? (LPCWSTR) ContentText.m_lpstr : T2CW(ContentText.m_lpstr),
+ dwCommonButtons,
+ IS_INTRESOURCE(Icon.m_lpstr) ? (LPCWSTR) Icon.m_lpstr : T2CW(Icon.m_lpstr),
+ &nRet);
+ ATLVERIFY(SUCCEEDED(hRet));
+ }
+
+ ::FreeLibrary(m_hCommCtrlDLL);
+ }
+#endif
+
+ return nRet;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTaskDialogConfig - TASKDIALOGCONFIG wrapper
+
+class CTaskDialogConfig : public TASKDIALOGCONFIG
+{
+public:
+// Constructor
+ CTaskDialogConfig()
+ {
+ Init();
+ }
+
+ void Init()
+ {
+ memset(this, 0, sizeof(TASKDIALOGCONFIG)); // initialize structure to 0/NULL
+ this->cbSize = sizeof(TASKDIALOGCONFIG);
+ this->hInstance = ModuleHelper::GetResourceInstance();
+ }
+
+// Operations - setting values
+ // common buttons
+ void SetCommonButtons(TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons)
+ {
+ this->dwCommonButtons = dwCommonButtons;
+ }
+
+ // window title text
+ void SetWindowTitle(UINT nID)
+ {
+ this->pszWindowTitle = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetWindowTitle(LPCWSTR lpstrWindowTitle)
+ {
+ this->pszWindowTitle = lpstrWindowTitle;
+ }
+
+ // main icon
+ void SetMainIcon(HICON hIcon)
+ {
+ this->dwFlags |= TDF_USE_HICON_MAIN;
+ this->hMainIcon = hIcon;
+ }
+
+ void SetMainIcon(UINT nID)
+ {
+ this->dwFlags &= ~TDF_USE_HICON_MAIN;
+ this->pszMainIcon = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetMainIcon(LPCWSTR lpstrMainIcon)
+ {
+ this->dwFlags &= ~TDF_USE_HICON_MAIN;
+ this->pszMainIcon = lpstrMainIcon;
+ }
+
+ // main instruction text
+ void SetMainInstructionText(UINT nID)
+ {
+ this->pszMainInstruction = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetMainInstructionText(LPCWSTR lpstrMainInstruction)
+ {
+ this->pszMainInstruction = lpstrMainInstruction;
+ }
+
+ // content text
+ void SetContentText(UINT nID)
+ {
+ this->pszContent = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetContentText(LPCWSTR lpstrContent)
+ {
+ this->pszContent = lpstrContent;
+ }
+
+ // buttons
+ void SetButtons(const TASKDIALOG_BUTTON* pButtons, UINT cButtons, int nDefaultButton = 0)
+ {
+ this->pButtons = pButtons;
+ this->cButtons = cButtons;
+ if(nDefaultButton != 0)
+ this->nDefaultButton = nDefaultButton;
+ }
+
+ void SetDefaultButton(int nDefaultButton)
+ {
+ this->nDefaultButton = nDefaultButton;
+ }
+
+ // radio buttons
+ void SetRadioButtons(const TASKDIALOG_BUTTON* pRadioButtons, UINT cRadioButtons, int nDefaultRadioButton = 0)
+ {
+ this->pRadioButtons = pRadioButtons;
+ this->cRadioButtons = cRadioButtons;
+ if(nDefaultRadioButton != 0)
+ this->nDefaultRadioButton = nDefaultRadioButton;
+ }
+
+ void SetDefaultRadioButton(int nDefaultRadioButton)
+ {
+ this->nDefaultRadioButton = nDefaultRadioButton;
+ }
+
+ // verification text
+ void SetVerificationText(UINT nID)
+ {
+ this->pszVerificationText = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetVerificationText(LPCWSTR lpstrVerificationText)
+ {
+ this->pszVerificationText = lpstrVerificationText;
+ }
+
+ // expanded information text
+ void SetExpandedInformationText(UINT nID)
+ {
+ this->pszExpandedInformation = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetExpandedInformationText(LPCWSTR lpstrExpandedInformation)
+ {
+ this->pszExpandedInformation = lpstrExpandedInformation;
+ }
+
+ // expanded control text
+ void SetExpandedControlText(UINT nID)
+ {
+ this->pszExpandedControlText = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetExpandedControlText(LPCWSTR lpstrExpandedControlText)
+ {
+ this->pszExpandedControlText = lpstrExpandedControlText;
+ }
+
+ // collapsed control text
+ void SetCollapsedControlText(UINT nID)
+ {
+ this->pszCollapsedControlText = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetCollapsedControlText(LPCWSTR lpstrCollapsedControlText)
+ {
+ this->pszCollapsedControlText = lpstrCollapsedControlText;
+ }
+
+ // footer icon
+ void SetFooterIcon(HICON hIcon)
+ {
+ this->dwFlags |= TDF_USE_HICON_FOOTER;
+ this->hFooterIcon = hIcon;
+ }
+
+ void SetFooterIcon(UINT nID)
+ {
+ this->dwFlags &= ~TDF_USE_HICON_FOOTER;
+ this->pszFooterIcon = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetFooterIcon(LPCWSTR lpstrFooterIcon)
+ {
+ this->dwFlags &= ~TDF_USE_HICON_FOOTER;
+ this->pszFooterIcon = lpstrFooterIcon;
+ }
+
+ // footer text
+ void SetFooterText(UINT nID)
+ {
+ this->pszFooter = MAKEINTRESOURCEW(nID);
+ }
+
+ void SetFooterText(LPCWSTR lpstrFooterText)
+ {
+ this->pszFooter = lpstrFooterText;
+ }
+
+ // width (in DLUs)
+ void SetWidth(UINT cxWidth)
+ {
+ this->cxWidth = cxWidth;
+ }
+
+ // modify flags
+ void ModifyFlags(DWORD dwRemove, DWORD dwAdd)
+ {
+ this->dwFlags = (this->dwFlags & ~dwRemove) | dwAdd;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTaskDialogImpl - implements a Task Dialog
+
+template <class T>
+class ATL_NO_VTABLE CTaskDialogImpl
+{
+public:
+ CTaskDialogConfig m_tdc;
+ HWND m_hWnd; // used only in callback functions
+
+// Constructor
+ CTaskDialogImpl(HWND hWndParent = NULL) : m_hWnd(NULL)
+ {
+ m_tdc.hwndParent = hWndParent;
+ m_tdc.pfCallback = T::TaskDialogCallback;
+ m_tdc.lpCallbackData = (LONG_PTR)static_cast<T*>(this);
+ }
+
+// Operations
+ HRESULT DoModal(HWND hWndParent = ::GetActiveWindow(), int* pnButton = NULL, int* pnRadioButton = NULL, BOOL* pfVerificationFlagChecked = NULL)
+ {
+ if(m_tdc.hwndParent == NULL)
+ m_tdc.hwndParent = hWndParent;
+
+#ifdef _WTL_TASKDIALOG_DIRECT
+ return ::TaskDialogIndirect(&m_tdc, pnButton, pnRadioButton, pfVerificationFlagChecked);
+#else
+
+ // This allows apps to run on older versions of Windows
+ typedef HRESULT (STDAPICALLTYPE *PFN_TaskDialogIndirect)(const TASKDIALOGCONFIG* pTaskConfig, int* pnButton, int* pnRadioButton, BOOL* pfVerificationFlagChecked);
+
+ HRESULT hRet = E_UNEXPECTED;
+ HMODULE m_hCommCtrlDLL = ::LoadLibrary(_T("comctl32.dll"));
+ if(m_hCommCtrlDLL != NULL)
+ {
+ PFN_TaskDialogIndirect pfnTaskDialogIndirect = (PFN_TaskDialogIndirect)::GetProcAddress(m_hCommCtrlDLL, "TaskDialogIndirect");
+ if(pfnTaskDialogIndirect != NULL)
+ hRet = pfnTaskDialogIndirect(&m_tdc, pnButton, pnRadioButton, pfVerificationFlagChecked);
+
+ ::FreeLibrary(m_hCommCtrlDLL);
+ }
+
+ return hRet;
+#endif
+ }
+
+// Operations - setting values of TASKDIALOGCONFIG
+ // common buttons
+ void SetCommonButtons(TASKDIALOG_COMMON_BUTTON_FLAGS dwCommonButtons)
+ { m_tdc.SetCommonButtons(dwCommonButtons); }
+ // window title text
+ void SetWindowTitle(UINT nID)
+ { m_tdc.SetWindowTitle(nID); }
+ void SetWindowTitle(LPCWSTR lpstrWindowTitle)
+ { m_tdc.SetWindowTitle(lpstrWindowTitle); }
+ // main icon
+ void SetMainIcon(HICON hIcon)
+ { m_tdc.SetMainIcon(hIcon); }
+ void SetMainIcon(UINT nID)
+ { m_tdc.SetMainIcon(nID); }
+ void SetMainIcon(LPCWSTR lpstrMainIcon)
+ { m_tdc.SetMainIcon(lpstrMainIcon); }
+ // main instruction text
+ void SetMainInstructionText(UINT nID)
+ { m_tdc.SetMainInstructionText(nID); }
+ void SetMainInstructionText(LPCWSTR lpstrMainInstruction)
+ { m_tdc.SetMainInstructionText(lpstrMainInstruction); }
+ // content text
+ void SetContentText(UINT nID)
+ { m_tdc.SetContentText(nID); }
+ void SetContentText(LPCWSTR lpstrContent)
+ { m_tdc.SetContentText(lpstrContent); }
+ // buttons
+ void SetButtons(const TASKDIALOG_BUTTON* pButtons, UINT cButtons, int nDefaultButton = 0)
+ { m_tdc.SetButtons(pButtons, cButtons, nDefaultButton); }
+ void SetDefaultButton(int nDefaultButton)
+ { m_tdc.SetDefaultButton(nDefaultButton); }
+ // radio buttons
+ void SetRadioButtons(const TASKDIALOG_BUTTON* pRadioButtons, UINT cRadioButtons, int nDefaultRadioButton = 0)
+ { m_tdc.SetRadioButtons(pRadioButtons, cRadioButtons, nDefaultRadioButton); }
+ void SetDefaultRadioButton(int nDefaultRadioButton)
+ { m_tdc.SetDefaultRadioButton(nDefaultRadioButton); }
+ // verification text
+ void SetVerificationText(UINT nID)
+ { m_tdc.SetVerificationText(nID); }
+ void SetVerificationText(LPCWSTR lpstrVerificationText)
+ { m_tdc.SetVerificationText(lpstrVerificationText); }
+ // expanded information text
+ void SetExpandedInformationText(UINT nID)
+ { m_tdc.SetExpandedInformationText(nID); }
+ void SetExpandedInformationText(LPCWSTR lpstrExpandedInformation)
+ { m_tdc.SetExpandedInformationText(lpstrExpandedInformation); }
+ // expanded control text
+ void SetExpandedControlText(UINT nID)
+ { m_tdc.SetExpandedControlText(nID); }
+ void SetExpandedControlText(LPCWSTR lpstrExpandedControlText)
+ { m_tdc.SetExpandedControlText(lpstrExpandedControlText); }
+ // collapsed control text
+ void SetCollapsedControlText(UINT nID)
+ { m_tdc.SetCollapsedControlText(nID); }
+ void SetCollapsedControlText(LPCWSTR lpstrCollapsedControlText)
+ { m_tdc.SetCollapsedControlText(lpstrCollapsedControlText); }
+ // footer icon
+ void SetFooterIcon(HICON hIcon)
+ { m_tdc.SetFooterIcon(hIcon); }
+ void SetFooterIcon(UINT nID)
+ { m_tdc.SetFooterIcon(nID); }
+ void SetFooterIcon(LPCWSTR lpstrFooterIcon)
+ { m_tdc.SetFooterIcon(lpstrFooterIcon); }
+ // footer text
+ void SetFooterText(UINT nID)
+ { m_tdc.SetFooterText(nID); }
+ void SetFooterText(LPCWSTR lpstrFooterText)
+ { m_tdc.SetFooterText(lpstrFooterText); }
+ // width (in DLUs)
+ void SetWidth(UINT cxWidth)
+ { m_tdc.SetWidth(cxWidth); }
+ // modify flags
+ void ModifyFlags(DWORD dwRemove, DWORD dwAdd)
+ { m_tdc.ModifyFlags(dwRemove, dwAdd); }
+
+// Implementation
+ static HRESULT CALLBACK TaskDialogCallback(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LONG_PTR lpRefData)
+ {
+ T* pT = (T*)lpRefData;
+ ATLASSERT(pT->m_hWnd == NULL || pT->m_hWnd == hWnd);
+
+ BOOL bRet = FALSE;
+ switch(uMsg)
+ {
+ case TDN_DIALOG_CONSTRUCTED:
+ pT->m_hWnd = hWnd;
+ pT->OnDialogConstructed();
+ break;
+ case TDN_CREATED:
+ pT->OnCreated();
+ break;
+ case TDN_BUTTON_CLICKED:
+ bRet = pT->OnButtonClicked((int)wParam);
+ break;
+ case TDN_RADIO_BUTTON_CLICKED:
+ pT->OnRadioButtonClicked((int)wParam);
+ break;
+ case TDN_HYPERLINK_CLICKED:
+ pT->OnHyperlinkClicked((LPCWSTR)lParam);
+ break;
+ case TDN_EXPANDO_BUTTON_CLICKED:
+ pT->OnExpandoButtonClicked((wParam != 0));
+ break;
+ case TDN_VERIFICATION_CLICKED:
+ pT->OnVerificationClicked((wParam != 0));
+ break;
+ case TDN_HELP:
+ pT->OnHelp();
+ break;
+ case TDN_TIMER:
+ bRet = pT->OnTimer((DWORD)wParam);
+ break;
+ case TDN_NAVIGATED:
+ pT->OnNavigated();
+ break;
+ case TDN_DESTROYED:
+ pT->OnDestroyed();
+ pT->m_hWnd = NULL;
+ break;
+ default:
+ ATLTRACE2(atlTraceUI, 0, _T("Unknown notification received in CTaskDialogImpl::TaskDialogCallback\n"));
+ break;
+ }
+
+ return (HRESULT)bRet;
+ }
+
+// Overrideables - notification handlers
+ void OnDialogConstructed()
+ {
+ }
+
+ void OnCreated()
+ {
+ }
+
+ BOOL OnButtonClicked(int /*nButton*/)
+ {
+ return FALSE; // don't prevent dialog to close
+ }
+
+ void OnRadioButtonClicked(int /*nRadioButton*/)
+ {
+ }
+
+ void OnHyperlinkClicked(LPCWSTR /*pszHREF*/)
+ {
+ }
+
+ void OnExpandoButtonClicked(bool /*bExpanded*/)
+ {
+ }
+
+ void OnVerificationClicked(bool /*bChecked*/)
+ {
+ }
+
+ void OnHelp()
+ {
+ }
+
+ BOOL OnTimer(DWORD /*dwTickCount*/)
+ {
+ return FALSE; // don't reset counter
+ }
+
+ void OnNavigated()
+ {
+ }
+
+ void OnDestroyed()
+ {
+ }
+
+// Commands - valid to call only from handlers
+ void NavigatePage(TASKDIALOGCONFIG& tdc)
+ {
+ ATLASSERT(m_hWnd != NULL);
+
+ tdc.cbSize = sizeof(TASKDIALOGCONFIG);
+ if(tdc.hwndParent == NULL)
+ tdc.hwndParent = m_tdc.hwndParent;
+ tdc.pfCallback = m_tdc.pfCallback;
+ tdc.lpCallbackData = m_tdc.lpCallbackData;
+ (TASKDIALOGCONFIG)m_tdc = tdc;
+
+ ::SendMessage(m_hWnd, TDM_NAVIGATE_PAGE, 0, (LPARAM)&tdc);
+ }
+
+ // modify TASKDIALOGCONFIG values, then call this to update task dialog
+ void NavigatePage()
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_NAVIGATE_PAGE, 0, (LPARAM)&m_tdc);
+ }
+
+ void ClickButton(int nButton)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_CLICK_BUTTON, nButton, 0L);
+ }
+
+ void SetMarqueeProgressBar(BOOL bMarquee)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_SET_MARQUEE_PROGRESS_BAR, bMarquee, 0L);
+ }
+
+ BOOL SetProgressBarState(int nNewState)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ return (BOOL)::SendMessage(m_hWnd, TDM_SET_PROGRESS_BAR_STATE, nNewState, 0L);
+ }
+
+ DWORD SetProgressBarRange(int nMinRange, int nMaxRange)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ return (DWORD)::SendMessage(m_hWnd, TDM_SET_PROGRESS_BAR_RANGE, 0, MAKELPARAM(nMinRange, nMaxRange));
+ }
+
+ int SetProgressBarPos(int nNewPos)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ return (int)::SendMessage(m_hWnd, TDM_SET_PROGRESS_BAR_POS, nNewPos, 0L);
+ }
+
+ BOOL SetProgressBarMarquee(BOOL bMarquee, UINT uSpeed)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ return (BOOL)::SendMessage(m_hWnd, TDM_SET_PROGRESS_BAR_MARQUEE, bMarquee, uSpeed);
+ }
+
+ void SetElementText(TASKDIALOG_ELEMENTS element, LPCWSTR lpstrText)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_SET_ELEMENT_TEXT, element, (LPARAM)lpstrText);
+ }
+
+ void ClickRadioButton(int nRadioButton)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_CLICK_RADIO_BUTTON, nRadioButton, 0L);
+ }
+
+ void EnableButton(int nButton, BOOL bEnable)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_ENABLE_BUTTON, nButton, bEnable);
+ }
+
+ void EnableRadioButton(int nButton, BOOL bEnable)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_ENABLE_RADIO_BUTTON, nButton, bEnable);
+ }
+
+ void ClickVerification(BOOL bCheck, BOOL bFocus)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_CLICK_VERIFICATION, bCheck, bFocus);
+ }
+
+ void UpdateElementText(TASKDIALOG_ELEMENTS element, LPCWSTR lpstrText)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_UPDATE_ELEMENT_TEXT, element, (LPARAM)lpstrText);
+ }
+
+ void SetButtonElevationRequiredState(int nButton, BOOL bElevation)
+ {
+ ATLASSERT(m_hWnd != NULL);
+ ::SendMessage(m_hWnd, TDM_SET_BUTTON_ELEVATION_REQUIRED_STATE, nButton, bElevation);
+ }
+
+ void UpdateIcon(TASKDIALOG_ICON_ELEMENTS element, HICON hIcon)
+ {
+ ATLASSERT(m_hWnd != NULL);
+#ifdef _DEBUG
+ if(element == TDIE_ICON_MAIN)
+ ATLASSERT((m_tdc.dwFlags & TDF_USE_HICON_MAIN) != 0);
+ else if(element == TDIE_ICON_FOOTER)
+ ATLASSERT((m_tdc.dwFlags & TDF_USE_HICON_FOOTER) != 0);
+#endif // _DEBUG
+ ::SendMessage(m_hWnd, TDM_UPDATE_ICON, element, (LPARAM)hIcon);
+ }
+
+ void UpdateIcon(TASKDIALOG_ICON_ELEMENTS element, LPCWSTR lpstrIcon)
+ {
+ ATLASSERT(m_hWnd != NULL);
+#ifdef _DEBUG
+ if(element == TDIE_ICON_MAIN)
+ ATLASSERT((m_tdc.dwFlags & TDF_USE_HICON_MAIN) == 0);
+ else if(element == TDIE_ICON_FOOTER)
+ ATLASSERT((m_tdc.dwFlags & TDF_USE_HICON_FOOTER) == 0);
+#endif // _DEBUG
+ ::SendMessage(m_hWnd, TDM_UPDATE_ICON, element, (LPARAM)lpstrIcon);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTaskDialog - for non-customized task dialogs
+
+class CTaskDialog : public CTaskDialogImpl<CTaskDialog>
+{
+public:
+ CTaskDialog(HWND hWndParent = NULL) : CTaskDialogImpl<CTaskDialog>(hWndParent)
+ {
+ m_tdc.pfCallback = NULL;
+ }
+};
+
+#endif // ((_WIN32_WINNT >= 0x0600) || defined(_WTL_TASKDIALOG)) && !defined(_WIN32_WCE)
+
+}; // namespace WTL
+
+#endif // __ATLDLGS_H__
diff --git a/plugins/SmartAutoReplier/wtl/atldwm.h b/plugins/SmartAutoReplier/wtl/atldwm.h
new file mode 100644
index 0000000000..fea8254827
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atldwm.h
@@ -0,0 +1,461 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLDWM_H__
+#define __ATLDWM_H__
+
+#pragma once
+
+#ifdef _WIN32_WCE
+ #error atldwm.h is not supported on Windows CE
+#endif
+
+#ifndef __ATLAPP_H__
+ #error atldwm.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atldwm.h requires atlwin.h to be included first
+#endif
+
+#if (_WIN32_WINNT < 0x0600)
+ #error atldwm.h requires _WIN32_WINNT >= 0x0600
+#endif // (_WIN32_WINNT < 0x0600)
+
+#ifndef _DWMAPI_H_
+#include <dwmapi.h>
+#endif // _DWMAPI_H_
+#pragma comment(lib, "dwmapi.lib")
+
+// Note: To create an application that also runs on older versions of Windows,
+// use delay load of dwmapi.dll and ensure that no calls to the DWM API are
+// Delay load is NOT AUTOMATIC for VC++ 7, you have to link to delayimp.lib,
+// and add dwmapi.dll in the Linker.Input.Delay Loaded DLLs section of the
+// project properties.
+#if (_MSC_VER < 1300) && !defined(_WTL_NO_DWMAPI_DELAYLOAD)
+ #pragma comment(lib, "delayimp.lib")
+ #pragma comment(linker, "/delayload:dwmapi.dll")
+#endif // (_MSC_VER < 1300) && !defined(_WTL_NO_DWMAPI_DELAYLOAD)
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CDwm
+// CDwmImpl<T, TBase>
+// CDwmWindowT<TBase> - CDwmWindow
+// CDwmThumbnailT<t_bManaged, TBase>
+// CDwmThumbnail
+// CDwmThumbnailHandle
+// CAeroControlImpl
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CDwm - wrapper for DWM handle
+
+class CDwm
+{
+public:
+// Data members
+ static int m_nIsDwmSupported;
+
+// Constructor
+ CDwm()
+ {
+ IsDwmSupported();
+ }
+
+// Dwm support helper
+ static bool IsDwmSupported()
+ {
+ if(m_nIsDwmSupported == -1)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CDwm::IsDwmSupported.\n"));
+ ATLASSERT(FALSE);
+ return false;
+ }
+
+ if(m_nIsDwmSupported == -1)
+ {
+ HMODULE hDwmDLL = ::LoadLibrary(_T("dwmapi.dll"));
+ m_nIsDwmSupported = (hDwmDLL != NULL) ? 1 : 0;
+ if(hDwmDLL != NULL)
+ ::FreeLibrary(hDwmDLL);
+ }
+
+ lock.Unlock();
+ }
+
+ ATLASSERT(m_nIsDwmSupported != -1);
+ return (m_nIsDwmSupported == 1);
+ }
+
+// Operations
+ BOOL DwmIsCompositionEnabled() const
+ {
+ if(!IsDwmSupported()) return FALSE;
+ BOOL bRes = FALSE;
+ return SUCCEEDED(::DwmIsCompositionEnabled(&bRes)) && bRes;
+ }
+
+ BOOL DwmEnableComposition(UINT fEnable)
+ {
+ if(!IsDwmSupported()) return FALSE;
+ return SUCCEEDED(::DwmEnableComposition(fEnable));
+ }
+
+ BOOL DwmEnableMMCSS(BOOL fEnableMMCSS)
+ {
+ if(!IsDwmSupported()) return FALSE;
+ return SUCCEEDED(::DwmEnableMMCSS(fEnableMMCSS));
+ }
+
+ HRESULT DwmGetColorizationColor(DWORD* pcrColorization, BOOL* pfOpaqueBlend)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ return ::DwmGetColorizationColor(pcrColorization, pfOpaqueBlend);
+ }
+
+ HRESULT DwmFlush()
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ return ::DwmFlush();
+ }
+};
+
+__declspec(selectany) int CDwm::m_nIsDwmSupported = -1;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDwmImpl - DWM window support
+
+template <class T, class TBase = CDwm>
+class CDwmImpl : public TBase
+{
+public:
+ HRESULT DwmEnableBlurBehindWindow(const DWM_BLURBEHIND* pBB)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmEnableBlurBehindWindow(pT->m_hWnd, pBB);
+ }
+
+ HRESULT DwmExtendFrameIntoClientArea(const MARGINS* pMargins)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmExtendFrameIntoClientArea(pT->m_hWnd, pMargins);
+ }
+
+ HRESULT DwmExtendFrameIntoEntireClientArea()
+ {
+ MARGINS margins = { -1 };
+ return DwmExtendFrameIntoClientArea(&margins);
+ }
+
+ HRESULT DwmGetCompositionTimingInfo(DWM_TIMING_INFO* pTimingInfo)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmGetCompositionTimingInfo(pT->m_hWnd, pTimingInfo);
+ }
+
+ HRESULT DwmGetWindowAttribute(DWORD dwAttribute, PVOID pvAttribute, DWORD cbAttribute)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmGetWindowAttribute(pT->m_hWnd, dwAttribute, pvAttribute, cbAttribute);
+ }
+
+ HRESULT DwmModifyPreviousDxFrameDuration(INT cRefreshes, BOOL fRelative)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmModifyPreviousDxFrameDuration(pT->m_hWnd, cRefreshes, fRelative);
+ }
+
+ HRESULT DwmSetDxFrameDuration(INT cRefreshes)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmSetDxFrameDuration(pT->m_hWnd, cRefreshes);
+ }
+
+ HRESULT DwmSetPresentParameters(DWM_PRESENT_PARAMETERS* pPresentParams)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmSetPresentParameters(pT->m_hWnd, pPresentParams);
+ }
+
+ HRESULT DwmSetWindowAttribute(DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmSetWindowAttribute(pT->m_hWnd, dwAttribute, pvAttribute, cbAttribute);
+ }
+
+ HRESULT DwmAttachMilContent()
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmAttachMilContent(pT->m_hWnd);
+ }
+
+ HRESULT DwmDetachMilContent()
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DwmDetachMilContent(pT->m_hWnd);
+ }
+};
+
+template <class TBase>
+class CDwmWindowT : public TBase, public CDwmImpl<CDwmWindowT< TBase > >
+{
+public:
+ CDwmWindowT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CDwmWindowT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+};
+
+typedef CDwmWindowT<ATL::CWindow> CDwmWindow;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDwmThumbnail - provides DWM thumbnail support
+
+template <bool t_bManaged, class TBase = CDwm>
+class CDwmThumbnailT : public TBase
+{
+public:
+// Data members
+ HTHUMBNAIL m_hThumbnail;
+
+// Constructor
+ CDwmThumbnailT(HTHUMBNAIL hThumbnail = NULL) : m_hThumbnail(hThumbnail)
+ {
+ }
+
+ ~CDwmThumbnailT()
+ {
+ if(t_bManaged && m_hThumbnail != NULL)
+ Unregister();
+ }
+
+// Operations
+ CDwmThumbnailT<t_bManaged, TBase>& operator =(HTHUMBNAIL hThumbnail)
+ {
+ Attach(hThumbnail);
+ return *this;
+ }
+
+ void Attach(HTHUMBNAIL hThumbnailNew)
+ {
+ if(t_bManaged && m_hThumbnail != NULL && m_hThumbnail != hThumbnailNew)
+ Unregister();
+ m_hThumbnail = hThumbnailNew;
+ }
+
+ HTHUMBNAIL Detach()
+ {
+ HTHUMBNAIL hThumbnail = m_hThumbnail;
+ m_hThumbnail = NULL;
+ return hThumbnail;
+ }
+
+ HRESULT Register(HWND hwndDestination, HWND hwndSource)
+ {
+ ATLASSERT(::IsWindow(hwndDestination));
+ ATLASSERT(::IsWindow(hwndSource));
+ ATLASSERT(m_hThumbnail==NULL);
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ return ::DwmRegisterThumbnail(hwndDestination, hwndSource, &m_hThumbnail);
+ }
+
+ HRESULT Unregister()
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ if(m_hThumbnail == NULL) return S_FALSE;
+ HRESULT Hr = ::DwmUnregisterThumbnail(m_hThumbnail);
+ if(SUCCEEDED(Hr)) m_hThumbnail = NULL;
+ return Hr;
+ }
+
+ operator HTHUMBNAIL() const { return m_hThumbnail; }
+
+ bool IsNull() const { return (m_hThumbnail == NULL); }
+
+ HRESULT UpdateProperties(const DWM_THUMBNAIL_PROPERTIES* ptnProperties)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ ATLASSERT(m_hThumbnail != NULL);
+ return ::DwmUpdateThumbnailProperties(m_hThumbnail, ptnProperties);
+ }
+
+// Attributes
+ HRESULT QuerySourceSize(PSIZE pSize)
+ {
+ if(!IsDwmSupported()) return E_NOTIMPL;
+ ATLASSERT(m_hThumbnail != NULL);
+ return ::DwmQueryThumbnailSourceSize(m_hThumbnail, pSize);
+ }
+};
+
+typedef CDwmThumbnailT<true, CDwm> CDwmThumbnail;
+typedef CDwmThumbnailT<false, CDwm> CDwmThumbnailHandle;
+
+
+#ifdef __ATLTHEME_H__
+
+///////////////////////////////////////////////////////////////////////////////
+// CAeroControlImpl - Base class for controls on Glass
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class CAeroControlImpl :
+ public CThemeImpl<T>,
+ public CBufferedPaintImpl<T>,
+ public ATL::CWindowImpl<T, TBase, TWinTraits>
+{
+public:
+ typedef CThemeImpl<T> _themeClass;
+ typedef CBufferedPaintImpl<T> _baseClass;
+ typedef ATL::CWindowImpl<T, TBase, TWinTraits> _windowClass;
+
+ CAeroControlImpl()
+ {
+ m_PaintParams.dwFlags = BPPF_ERASE;
+ }
+
+ static LPCWSTR GetThemeName()
+ {
+#ifdef _UNICODE
+ return TBase::GetWndClassName();
+#else
+ ATLASSERT(!_T("Return UNICODE string of window classname / theme class"));
+ return NULL;
+#endif // _UNICODE
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CAeroControlImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_ACTIVATE, OnActivate)
+ CHAIN_MSG_MAP(_themeClass)
+ CHAIN_MSG_MAP(_baseClass)
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Init();
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnActivate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(IsThemingSupported()) Invalidate(FALSE);
+ bHandled = FALSE;
+ return 0;
+ }
+
+// Operations
+ BOOL SubclassWindow(HWND hWnd)
+ {
+ ATLASSERT(m_hWnd == NULL);
+ ATLASSERT(::IsWindow(hWnd));
+ BOOL bRet = _windowClass::SubclassWindow(hWnd);
+ if(bRet) {
+ T* pT = static_cast<T*>(this);
+ pT->Init();
+ }
+ return bRet;
+ }
+
+// Implementation
+ LRESULT DefWindowProc()
+ {
+ const _ATL_MSG* pMsg = m_pCurrentMsg;
+ LRESULT lRes = 0;
+ if(pMsg != NULL)
+ lRes = DefWindowProc(pMsg->message, pMsg->wParam, pMsg->lParam);
+ return lRes;
+ }
+
+ LRESULT DefWindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
+ {
+ T* pT = static_cast<T*>(this);
+ LRESULT lRes = 0;
+ if( ::DwmDefWindowProc(pT->m_hWnd, uMsg, wParam, lParam, &lRes) ) return lRes;
+ return _windowClass::DefWindowProc(uMsg, wParam, lParam);
+ }
+
+ void DoBufferedPaint(HDC hDC, RECT& rcPaint)
+ {
+ T* pT = static_cast<T*>(this);
+ HDC hDCPaint = NULL;
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+ m_BufferedPaint.Begin(hDC, &rcClient, m_dwFormat, &m_PaintParams, &hDCPaint);
+ ATLASSERT(hDCPaint != NULL);
+ pT->DoAeroPaint(hDCPaint, rcClient, rcPaint);
+ m_BufferedPaint.End();
+ }
+
+ void DoPaint(HDC /*hdc*/, RECT& /*rcClient*/)
+ {
+ DefWindowProc();
+ }
+
+// Overridables
+ void Init()
+ {
+ T* pT = static_cast<T*>(this);
+ SetThemeClassList(pT->GetThemeName());
+ if(m_lpstrThemeClassList != NULL)
+ OpenThemeData();
+ }
+
+ void DoAeroPaint(HDC hDC, RECT& /*rcClient*/, RECT& rcPaint)
+ {
+ DefWindowProc(WM_PAINT, (WPARAM) hDC, 0L);
+ m_BufferedPaint.MakeOpaque(&rcPaint);
+ }
+};
+
+#endif // __ATLTHEME_H__
+
+
+}; // namespace WTL
+
+
+#endif // __ATLDWM_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlfind.h b/plugins/SmartAutoReplier/wtl/atlfind.h
new file mode 100644
index 0000000000..832aba204e
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlfind.h
@@ -0,0 +1,1032 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLFIND_H__
+#define __ATLFIND_H__
+
+#pragma once
+
+#ifdef _WIN32_WCE
+ #error atlfind.h is not supported on Windows CE
+#endif
+
+#ifndef __ATLCTRLS_H__
+ #error atlfind.h requires atlctrls.h to be included first
+#endif
+
+#ifndef __ATLDLGS_H__
+ #error atlfind.h requires atldlgs.h to be included first
+#endif
+
+#if !((defined(__ATLMISC_H__) && defined(_WTL_USE_CSTRING)) || defined(__ATLSTR_H__))
+ #error atlfind.h requires CString (either from ATL's atlstr.h or WTL's atlmisc.h with _WTL_USE_CSTRING)
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CEditFindReplaceImplBase<T, TFindReplaceDialog>
+// CEditFindReplaceImpl<T, TFindReplaceDialog>
+// CRichEditFindReplaceImpl<T, TFindReplaceDialog>
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CEditFindReplaceImplBase - Base class for mixin classes that
+// help implement Find/Replace for CEdit or CRichEditCtrl based window classes.
+
+template <class T, class TFindReplaceDialog = CFindReplaceDialog>
+class CEditFindReplaceImplBase
+{
+protected:
+// Typedefs
+ typedef CEditFindReplaceImplBase<T, TFindReplaceDialog> thisClass;
+
+// Data members
+ TFindReplaceDialog* m_pFindReplaceDialog;
+ _CSTRING_NS::CString m_sFindNext, m_sReplaceWith;
+ BOOL m_bFindOnly, m_bFirstSearch, m_bMatchCase, m_bWholeWord, m_bFindDown;
+ LONG m_nInitialSearchPos;
+ HCURSOR m_hOldCursor;
+
+// Enumerations
+ enum TranslationTextItem
+ {
+ eText_OnReplaceAllMessage = 0,
+ eText_OnReplaceAllTitle = 1,
+ eText_OnTextNotFoundMessage = 2,
+ eText_OnTextNotFoundTitle = 3
+ };
+
+public:
+// Constructors
+ CEditFindReplaceImplBase() :
+ m_pFindReplaceDialog(NULL),
+ m_bFindOnly(TRUE),
+ m_bFirstSearch(TRUE),
+ m_bMatchCase(FALSE),
+ m_bWholeWord(FALSE),
+ m_bFindDown(TRUE),
+ m_nInitialSearchPos(0),
+ m_hOldCursor(NULL)
+ {
+ }
+
+// Message Handlers
+ BEGIN_MSG_MAP(thisClass)
+ ALT_MSG_MAP(1)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_HANDLER(TFindReplaceDialog::GetFindReplaceMsg(), OnFindReplaceCmd)
+ COMMAND_ID_HANDLER(ID_EDIT_FIND, OnEditFind)
+ COMMAND_ID_HANDLER(ID_EDIT_REPEAT, OnEditRepeat)
+ COMMAND_ID_HANDLER(ID_EDIT_REPLACE, OnEditReplace)
+ END_MSG_MAP()
+
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_pFindReplaceDialog != NULL)
+ {
+ m_pFindReplaceDialog->SendMessage(WM_CLOSE);
+ ATLASSERT(m_pFindReplaceDialog == NULL);
+ }
+
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnFindReplaceCmd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+
+ TFindReplaceDialog* pDialog = TFindReplaceDialog::GetNotifier(lParam);
+ if(pDialog == NULL)
+ {
+ ATLASSERT(FALSE);
+ ::MessageBeep(MB_ICONERROR);
+ return 1;
+ }
+ ATLASSERT(pDialog == m_pFindReplaceDialog);
+
+ LPFINDREPLACE findReplace = (LPFINDREPLACE)lParam;
+ if((m_pFindReplaceDialog != NULL) && (findReplace != NULL))
+ {
+ if(pDialog->FindNext())
+ {
+ pT->OnFindNext(pDialog->GetFindString(), pDialog->SearchDown(),
+ pDialog->MatchCase(), pDialog->MatchWholeWord());
+ }
+ else if(pDialog->ReplaceCurrent())
+ {
+ pT->OnReplaceSel(pDialog->GetFindString(),
+ pDialog->SearchDown(), pDialog->MatchCase(), pDialog->MatchWholeWord(),
+ pDialog->GetReplaceString());
+ }
+ else if(pDialog->ReplaceAll())
+ {
+ pT->OnReplaceAll(pDialog->GetFindString(), pDialog->GetReplaceString(),
+ pDialog->MatchCase(), pDialog->MatchWholeWord());
+ }
+ else if(pDialog->IsTerminating())
+ {
+ // Dialog is going away (but hasn't gone away yet)
+ // OnFinalMessage will "delete this"
+ pT->OnTerminatingFindReplaceDialog(m_pFindReplaceDialog);
+ m_pFindReplaceDialog = NULL;
+ }
+ }
+
+ return 0;
+ }
+
+ LRESULT OnEditFind(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->FindReplace(TRUE);
+
+ return 0;
+ }
+
+ LRESULT OnEditRepeat(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+
+ // If the user is holding down SHIFT when hitting F3, we'll
+ // search in reverse. Otherwise, we'll search forward.
+ // (be sure to have an accelerator mapped to ID_EDIT_REPEAT
+ // for both F3 and Shift+F3)
+ m_bFindDown = !((::GetKeyState(VK_SHIFT) & 0x8000) == 0x8000);
+
+ if(m_sFindNext.IsEmpty())
+ {
+ pT->FindReplace(TRUE);
+ }
+ else
+ {
+ if(!pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown))
+ pT->TextNotFound(m_sFindNext);
+ }
+
+ return 0;
+ }
+
+ LRESULT OnEditReplace(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+
+ DWORD style = pT->GetStyle();
+ if((style & ES_READONLY) != ES_READONLY)
+ {
+ pT->FindReplace(FALSE);
+ }
+ else
+ {
+ // Don't allow replace when the edit control is read only
+ bHandled = FALSE;
+ }
+
+ return 0;
+ }
+
+// Operations (overrideable)
+ TFindReplaceDialog* CreateFindReplaceDialog(BOOL bFindOnly, // TRUE for Find, FALSE for FindReplace
+ LPCTSTR lpszFindWhat,
+ LPCTSTR lpszReplaceWith = NULL,
+ DWORD dwFlags = FR_DOWN,
+ HWND hWndParent = NULL)
+ {
+ // You can override all of this in a derived class
+
+ TFindReplaceDialog* findReplaceDialog = new TFindReplaceDialog();
+ if(findReplaceDialog == NULL)
+ {
+ ::MessageBeep(MB_ICONHAND);
+ }
+ else
+ {
+ HWND hWndFindReplace = findReplaceDialog->Create(bFindOnly,
+ lpszFindWhat, lpszReplaceWith, dwFlags, hWndParent);
+ if(hWndFindReplace == NULL)
+ {
+ delete findReplaceDialog;
+ findReplaceDialog = NULL;
+ }
+ else
+ {
+ findReplaceDialog->SetActiveWindow();
+ findReplaceDialog->ShowWindow(SW_SHOW);
+ }
+ }
+
+ return findReplaceDialog;
+ }
+
+ void AdjustDialogPosition(HWND hWndDialog)
+ {
+ ATLASSERT((hWndDialog != NULL) && ::IsWindow(hWndDialog));
+
+ T* pT = static_cast<T*>(this);
+ LONG nStartChar = 0, nEndChar = 0;
+ // Send EM_GETSEL so we can use both Edit and RichEdit
+ // (CEdit::GetSel uses int&, and CRichEditCtrlT::GetSel uses LONG&)
+ ::SendMessage(pT->m_hWnd, EM_GETSEL, (WPARAM)&nStartChar, (LPARAM)&nEndChar);
+ POINT point = pT->PosFromChar(nStartChar);
+ ::ClientToScreen(pT->GetParent(), &point);
+ CRect rect;
+ ::GetWindowRect(hWndDialog, &rect);
+ if(rect.PtInRect(point))
+ {
+ if(point.y > rect.Height())
+ {
+ rect.OffsetRect(0, point.y - rect.bottom - 20);
+ }
+ else
+ {
+ int nVertExt = GetSystemMetrics(SM_CYSCREEN);
+ if(point.y + rect.Height() < nVertExt)
+ rect.OffsetRect(0, 40 + point.y - rect.top);
+ }
+
+ ::MoveWindow(hWndDialog, rect.left, rect.top, rect.Width(), rect.Height(), TRUE);
+ }
+ }
+
+ DWORD GetFindReplaceDialogFlags(void) const
+ {
+ DWORD dwFlags = 0;
+
+ if(m_bFindDown)
+ dwFlags |= FR_DOWN;
+ if(m_bMatchCase)
+ dwFlags |= FR_MATCHCASE;
+ if(m_bWholeWord)
+ dwFlags |= FR_WHOLEWORD;
+
+ return dwFlags;
+ }
+
+ void FindReplace(BOOL bFindOnly)
+ {
+ T* pT = static_cast<T*>(this);
+ m_bFirstSearch = TRUE;
+ if(m_pFindReplaceDialog != NULL)
+ {
+ if(m_bFindOnly == bFindOnly)
+ {
+ m_pFindReplaceDialog->SetActiveWindow();
+ m_pFindReplaceDialog->ShowWindow(SW_SHOW);
+ return;
+ }
+ else
+ {
+ m_pFindReplaceDialog->SendMessage(WM_CLOSE);
+ ATLASSERT(m_pFindReplaceDialog == NULL);
+ }
+ }
+
+ ATLASSERT(m_pFindReplaceDialog == NULL);
+
+ _CSTRING_NS::CString findNext;
+ pT->GetSelText(findNext);
+ // if selection is empty or spans multiple lines use old find text
+ if(findNext.IsEmpty() || (findNext.FindOneOf(_T("\n\r")) != -1))
+ findNext = m_sFindNext;
+ _CSTRING_NS::CString replaceWith = m_sReplaceWith;
+ DWORD dwFlags = pT->GetFindReplaceDialogFlags();
+
+ m_pFindReplaceDialog = pT->CreateFindReplaceDialog(bFindOnly,
+ findNext, replaceWith, dwFlags, pT->operator HWND());
+ ATLASSERT(m_pFindReplaceDialog != NULL);
+ if(m_pFindReplaceDialog != NULL)
+ m_bFindOnly = bFindOnly;
+ }
+
+ BOOL SameAsSelected(LPCTSTR lpszCompare, BOOL bMatchCase, BOOL /*bWholeWord*/)
+ {
+ T* pT = static_cast<T*>(this);
+
+ // check length first
+ size_t nLen = lstrlen(lpszCompare);
+ LONG nStartChar = 0, nEndChar = 0;
+ // Send EM_GETSEL so we can use both Edit and RichEdit
+ // (CEdit::GetSel uses int&, and CRichEditCtrlT::GetSel uses LONG&)
+ ::SendMessage(pT->m_hWnd, EM_GETSEL, (WPARAM)&nStartChar, (LPARAM)&nEndChar);
+ if(nLen != (size_t)(nEndChar - nStartChar))
+ return FALSE;
+
+ // length is the same, check contents
+ _CSTRING_NS::CString selectedText;
+ pT->GetSelText(selectedText);
+
+ return (bMatchCase && selectedText.Compare(lpszCompare) == 0) ||
+ (!bMatchCase && selectedText.CompareNoCase(lpszCompare) == 0);
+ }
+
+ void TextNotFound(LPCTSTR lpszFind)
+ {
+ T* pT = static_cast<T*>(this);
+ m_bFirstSearch = TRUE;
+ pT->OnTextNotFound(lpszFind);
+ }
+
+ _CSTRING_NS::CString GetTranslationText(enum TranslationTextItem eItem) const
+ {
+ _CSTRING_NS::CString text;
+ switch(eItem)
+ {
+ case eText_OnReplaceAllMessage:
+ text = _T("Replaced %d occurances of \"%s\" with \"%s\"");
+ break;
+ case eText_OnReplaceAllTitle:
+ text = _T("Replace All");
+ break;
+ case eText_OnTextNotFoundMessage:
+ text = _T("Unable to find the text \"%s\"");
+ break;
+ case eText_OnTextNotFoundTitle:
+ text = _T("Text not found");
+ break;
+ }
+
+ return text;
+ }
+
+// Overrideable Handlers
+ void OnFindNext(LPCTSTR lpszFind, BOOL bFindDown, BOOL bMatchCase, BOOL bWholeWord)
+ {
+ T* pT = static_cast<T*>(this);
+
+ m_sFindNext = lpszFind;
+ m_bMatchCase = bMatchCase;
+ m_bWholeWord = bWholeWord;
+ m_bFindDown = bFindDown;
+
+ if(!pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown))
+ pT->TextNotFound(m_sFindNext);
+ else
+ pT->AdjustDialogPosition(m_pFindReplaceDialog->operator HWND());
+ }
+
+ void OnReplaceSel(LPCTSTR lpszFind, BOOL bFindDown, BOOL bMatchCase, BOOL bWholeWord, LPCTSTR lpszReplace)
+ {
+ T* pT = static_cast<T*>(this);
+
+ m_sFindNext = lpszFind;
+ m_sReplaceWith = lpszReplace;
+ m_bMatchCase = bMatchCase;
+ m_bWholeWord = bWholeWord;
+ m_bFindDown = bFindDown;
+
+ if(pT->SameAsSelected(m_sFindNext, m_bMatchCase, m_bWholeWord))
+ pT->ReplaceSel(m_sReplaceWith);
+
+ if(!pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown))
+ pT->TextNotFound(m_sFindNext);
+ else
+ pT->AdjustDialogPosition(m_pFindReplaceDialog->operator HWND());
+ }
+
+ void OnReplaceAll(LPCTSTR lpszFind, LPCTSTR lpszReplace, BOOL bMatchCase, BOOL bWholeWord)
+ {
+ T* pT = static_cast<T*>(this);
+
+ m_sFindNext = lpszFind;
+ m_sReplaceWith = lpszReplace;
+ m_bMatchCase = bMatchCase;
+ m_bWholeWord = bWholeWord;
+ m_bFindDown = TRUE;
+
+ // no selection or different than what looking for
+ if(!pT->SameAsSelected(m_sFindNext, m_bMatchCase, m_bWholeWord))
+ {
+ if(!pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown))
+ {
+ pT->TextNotFound(m_sFindNext);
+ return;
+ }
+ }
+
+ pT->OnReplaceAllCoreBegin();
+
+ int replaceCount=0;
+ do
+ {
+ ++replaceCount;
+ pT->ReplaceSel(m_sReplaceWith);
+ } while(pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown));
+
+ pT->OnReplaceAllCoreEnd(replaceCount);
+ }
+
+ void OnReplaceAllCoreBegin()
+ {
+ T* pT = static_cast<T*>(this);
+
+ m_hOldCursor = ::SetCursor(::LoadCursor(NULL, IDC_WAIT));
+
+ pT->HideSelection(TRUE, FALSE);
+
+ }
+
+ void OnReplaceAllCoreEnd(int replaceCount)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->HideSelection(FALSE, FALSE);
+
+ ::SetCursor(m_hOldCursor);
+
+ _CSTRING_NS::CString message = pT->GetTranslationText(eText_OnReplaceAllMessage);
+ if(message.GetLength() > 0)
+ {
+ _CSTRING_NS::CString formattedMessage;
+ formattedMessage.Format(message,
+ replaceCount, m_sFindNext, m_sReplaceWith);
+ if(m_pFindReplaceDialog != NULL)
+ {
+ m_pFindReplaceDialog->MessageBox(formattedMessage,
+ pT->GetTranslationText(eText_OnReplaceAllTitle),
+ MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
+ }
+ else
+ {
+ pT->MessageBox(formattedMessage,
+ pT->GetTranslationText(eText_OnReplaceAllTitle),
+ MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
+ }
+ }
+ }
+
+ void OnTextNotFound(LPCTSTR lpszFind)
+ {
+ T* pT = static_cast<T*>(this);
+ _CSTRING_NS::CString message = pT->GetTranslationText(eText_OnTextNotFoundMessage);
+ if(message.GetLength() > 0)
+ {
+ _CSTRING_NS::CString formattedMessage;
+ formattedMessage.Format(message, lpszFind);
+ if(m_pFindReplaceDialog != NULL)
+ {
+ m_pFindReplaceDialog->MessageBox(formattedMessage,
+ pT->GetTranslationText(eText_OnTextNotFoundTitle),
+ MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
+ }
+ else
+ {
+ pT->MessageBox(formattedMessage,
+ pT->GetTranslationText(eText_OnTextNotFoundTitle),
+ MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
+ }
+ }
+ else
+ {
+ ::MessageBeep(MB_ICONHAND);
+ }
+ }
+
+ void OnTerminatingFindReplaceDialog(TFindReplaceDialog*& /*findReplaceDialog*/)
+ {
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CEditFindReplaceImpl - Mixin class for implementing Find/Replace for CEdit
+// based window classes.
+
+// Chain to CEditFindReplaceImpl message map. Your class must also derive from CEdit.
+// Example:
+// class CMyEdit : public CWindowImpl<CMyEdit, CEdit>,
+// public CEditFindReplaceImpl<CMyEdit>
+// {
+// public:
+// BEGIN_MSG_MAP(CMyEdit)
+// // your handlers...
+// CHAIN_MSG_MAP_ALT(CEditFindReplaceImpl<CMyEdit>, 1)
+// END_MSG_MAP()
+// // other stuff...
+// };
+
+template <class T, class TFindReplaceDialog = CFindReplaceDialog>
+class CEditFindReplaceImpl : public CEditFindReplaceImplBase<T, TFindReplaceDialog>
+{
+protected:
+ typedef CEditFindReplaceImpl<T, TFindReplaceDialog> thisClass;
+ typedef CEditFindReplaceImplBase<T, TFindReplaceDialog> baseClass;
+
+// Data members
+ LPTSTR m_pShadowBuffer; // Special shadow buffer only used in some cases.
+ UINT m_nShadowSize;
+ int m_bShadowBufferNeeded; // TRUE, FALSE, < 0 => Need to check
+
+public:
+// Constructors
+ CEditFindReplaceImpl() :
+ m_pShadowBuffer(NULL),
+ m_nShadowSize(0),
+ m_bShadowBufferNeeded(-1)
+ {
+ }
+
+ virtual ~CEditFindReplaceImpl()
+ {
+ if(m_pShadowBuffer != NULL)
+ {
+ delete [] m_pShadowBuffer;
+ m_pShadowBuffer = NULL;
+ }
+ }
+
+// Message Handlers
+ BEGIN_MSG_MAP(thisClass)
+ ALT_MSG_MAP(1)
+ CHAIN_MSG_MAP_ALT(baseClass, 1)
+ END_MSG_MAP()
+
+// Operations
+ // Supported only for RichEdit, so this does nothing for Edit
+ void HideSelection(BOOL /*bHide*/ = TRUE, BOOL /*bChangeStyle*/ = FALSE)
+ {
+ }
+
+// Operations (overrideable)
+ BOOL FindTextSimple(LPCTSTR lpszFind, BOOL bMatchCase, BOOL bWholeWord, BOOL bFindDown = TRUE)
+ {
+ T* pT = static_cast<T*>(this);
+
+ ATLASSERT(lpszFind != NULL);
+ ATLASSERT(*lpszFind != _T('\0'));
+
+ UINT nLen = pT->GetBufferLength();
+ int nStartChar = 0, nEndChar = 0;
+ pT->GetSel(nStartChar, nEndChar);
+ UINT nStart = nStartChar;
+ int iDir = bFindDown ? +1 : -1;
+
+ // can't find a match before the first character
+ if(nStart == 0 && iDir < 0)
+ return FALSE;
+
+ LPCTSTR lpszText = pT->LockBuffer();
+
+ bool isDBCS = false;
+#ifdef _MBCS
+ CPINFO info = { 0 };
+ ::GetCPInfo(::GetOEMCP(), &info);
+ isDBCS = (info.MaxCharSize > 1);
+#endif
+
+ if(iDir < 0)
+ {
+ // always go back one for search backwards
+ nStart -= int((lpszText + nStart) - ::CharPrev(lpszText, lpszText + nStart));
+ }
+ else if(nStartChar != nEndChar && pT->SameAsSelected(lpszFind, bMatchCase, bWholeWord))
+ {
+ // easy to go backward/forward with SBCS
+#ifndef _UNICODE
+ if(::IsDBCSLeadByte(lpszText[nStart]))
+ nStart++;
+#endif
+ nStart += iDir;
+ }
+
+ // handle search with nStart past end of buffer
+ UINT nLenFind = ::lstrlen(lpszFind);
+ if(nStart + nLenFind - 1 >= nLen)
+ {
+ if(iDir < 0 && nLen >= nLenFind)
+ {
+ if(isDBCS)
+ {
+ // walk back to previous character n times
+ nStart = nLen;
+ int n = nLenFind;
+ while(n--)
+ {
+ nStart -= int((lpszText + nStart) - ::CharPrev(lpszText, lpszText + nStart));
+ }
+ }
+ else
+ {
+ // single-byte character set is easy and fast
+ nStart = nLen - nLenFind;
+ }
+ ATLASSERT(nStart + nLenFind - 1 <= nLen);
+ }
+ else
+ {
+ pT->UnlockBuffer();
+ return FALSE;
+ }
+ }
+
+ // start the search at nStart
+ LPCTSTR lpsz = lpszText + nStart;
+ typedef int (WINAPI* CompareProc)(LPCTSTR str1, LPCTSTR str2);
+ CompareProc pfnCompare = bMatchCase ? lstrcmp : lstrcmpi;
+
+ if(isDBCS)
+ {
+ // double-byte string search
+ LPCTSTR lpszStop = NULL;
+ if(iDir > 0)
+ {
+ // start at current and find _first_ occurrance
+ lpszStop = lpszText + nLen - nLenFind + 1;
+ }
+ else
+ {
+ // start at top and find _last_ occurrance
+ lpszStop = lpsz;
+ lpsz = lpszText;
+ }
+
+ LPCTSTR lpszFound = NULL;
+ while(lpsz <= lpszStop)
+ {
+#ifndef _UNICODE
+ if(!bMatchCase || (*lpsz == *lpszFind && (!::IsDBCSLeadByte(*lpsz) || lpsz[1] == lpszFind[1])))
+#else
+ if(!bMatchCase || (*lpsz == *lpszFind && lpsz[1] == lpszFind[1]))
+#endif
+ {
+ LPTSTR lpch = (LPTSTR)(lpsz + nLenFind);
+ TCHAR chSave = *lpch;
+ *lpch = _T('\0');
+ int nResult = (*pfnCompare)(lpsz, lpszFind);
+ *lpch = chSave;
+ if(nResult == 0)
+ {
+ lpszFound = lpsz;
+ if(iDir > 0)
+ break;
+ }
+ }
+ lpsz = ::CharNext(lpsz);
+ }
+ pT->UnlockBuffer();
+
+ if(lpszFound != NULL)
+ {
+ int n = (int)(lpszFound - lpszText);
+ pT->SetSel(n, n + nLenFind);
+ return TRUE;
+ }
+ }
+ else
+ {
+ // single-byte string search
+ UINT nCompare;
+ if(iDir < 0)
+ nCompare = (UINT)(lpsz - lpszText) + 1;
+ else
+ nCompare = nLen - (UINT)(lpsz - lpszText) - nLenFind + 1;
+
+ while(nCompare > 0)
+ {
+ ATLASSERT(lpsz >= lpszText);
+ ATLASSERT(lpsz + nLenFind - 1 <= lpszText + nLen - 1);
+
+ LPSTR lpch = (LPSTR)(lpsz + nLenFind);
+ char chSave = *lpch;
+ *lpch = '\0';
+ int nResult = (*pfnCompare)(lpsz, lpszFind);
+ *lpch = chSave;
+ if(nResult == 0)
+ {
+ pT->UnlockBuffer();
+ int n = (int)(lpsz - lpszText);
+ pT->SetSel(n, n + nLenFind);
+ return TRUE;
+ }
+
+ // restore character at end of search
+ *lpch = chSave;
+
+ // move on to next substring
+ nCompare--;
+ lpsz += iDir;
+ }
+ pT->UnlockBuffer();
+ }
+
+ return FALSE;
+ }
+
+ LPCTSTR LockBuffer() const
+ {
+ const T* pT = static_cast<const T*>(this);
+
+ ATLASSERT(pT->m_hWnd != NULL);
+
+ BOOL useShadowBuffer = pT->UseShadowBuffer();
+ if(useShadowBuffer)
+ {
+ if(m_pShadowBuffer == NULL || pT->GetModify())
+ {
+ ATLASSERT(m_pShadowBuffer != NULL || m_nShadowSize == 0);
+ UINT nSize = pT->GetWindowTextLength() + 1;
+ if(nSize > m_nShadowSize)
+ {
+ // need more room for shadow buffer
+ T* pThisNoConst = const_cast<T*>(pT);
+ delete[] m_pShadowBuffer;
+ pThisNoConst->m_pShadowBuffer = NULL;
+ pThisNoConst->m_nShadowSize = 0;
+ pThisNoConst->m_pShadowBuffer = new TCHAR[nSize];
+ pThisNoConst->m_nShadowSize = nSize;
+ }
+
+ // update the shadow buffer with GetWindowText
+ ATLASSERT(m_nShadowSize >= nSize);
+ ATLASSERT(m_pShadowBuffer != NULL);
+ pT->GetWindowText(m_pShadowBuffer, nSize);
+ }
+
+ return m_pShadowBuffer;
+ }
+
+ HLOCAL hLocal = pT->GetHandle();
+ ATLASSERT(hLocal != NULL);
+ LPCTSTR lpszText = (LPCTSTR)::LocalLock(hLocal);
+ ATLASSERT(lpszText != NULL);
+
+ return lpszText;
+ }
+
+ void UnlockBuffer() const
+ {
+ const T* pT = static_cast<const T*>(this);
+
+ ATLASSERT(pT->m_hWnd != NULL);
+
+ BOOL useShadowBuffer = pT->UseShadowBuffer();
+ if(!useShadowBuffer)
+ {
+ HLOCAL hLocal = pT->GetHandle();
+ ATLASSERT(hLocal != NULL);
+ ::LocalUnlock(hLocal);
+ }
+ }
+
+ UINT GetBufferLength() const
+ {
+ const T* pT = static_cast<const T*>(this);
+
+ ATLASSERT(pT->m_hWnd != NULL);
+ UINT nLen = 0;
+ LPCTSTR lpszText = pT->LockBuffer();
+ if(lpszText != NULL)
+ nLen = ::lstrlen(lpszText);
+ pT->UnlockBuffer();
+
+ return nLen;
+ }
+
+ LONG EndOfLine(LPCTSTR lpszText, UINT nLen, UINT nIndex) const
+ {
+ LPCTSTR lpsz = lpszText + nIndex;
+ LPCTSTR lpszStop = lpszText + nLen;
+ while(lpsz < lpszStop && *lpsz != _T('\r'))
+ ++lpsz;
+ return LONG(lpsz - lpszText);
+ }
+
+ LONG GetSelText(_CSTRING_NS::CString& strText) const
+ {
+ const T* pT = static_cast<const T*>(this);
+
+ int nStartChar = 0, nEndChar = 0;
+ pT->GetSel(nStartChar, nEndChar);
+ ATLASSERT((UINT)nEndChar <= pT->GetBufferLength());
+ LPCTSTR lpszText = pT->LockBuffer();
+ LONG nLen = pT->EndOfLine(lpszText, nEndChar, nStartChar) - nStartChar;
+ SecureHelper::memcpy_x(strText.GetBuffer(nLen), nLen * sizeof(TCHAR), lpszText + nStartChar, nLen * sizeof(TCHAR));
+ strText.ReleaseBuffer(nLen);
+ pT->UnlockBuffer();
+
+ return nLen;
+ }
+
+ BOOL UseShadowBuffer(void) const
+ {
+ const T* pT = static_cast<const T*>(this);
+
+ if(pT->m_bShadowBufferNeeded < 0)
+ {
+ T* pThisNoConst = const_cast<T*>(pT);
+
+ OSVERSIONINFO ovi = { 0 };
+ ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
+ ::GetVersionEx(&ovi);
+
+ bool bWin9x = (ovi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
+ if(bWin9x)
+ {
+ // Windows 95, 98, ME
+ // Under Win9x, it is necessary to maintain a shadow buffer.
+ // It is only updated when the control contents have been changed.
+ pThisNoConst->m_bShadowBufferNeeded = TRUE;
+ }
+ else
+ {
+ // Windows NT, 2000, XP, etc.
+ pThisNoConst->m_bShadowBufferNeeded = FALSE;
+
+#ifndef _UNICODE
+ // On Windows XP (or later), if common controls version 6 is in use
+ // (such as via theming), then EM_GETHANDLE will always return a UNICODE string.
+ // If theming is enabled and Common Controls version 6 is in use,
+ // you're really not suppose to superclass or subclass common controls
+ // with an ANSI windows procedure (so its best to only theme if you use UNICODE).
+ // Using a shadow buffer uses GetWindowText instead, so it solves
+ // this problem for us (although it makes it a little less efficient).
+
+ if((ovi.dwMajorVersion == 5 && ovi.dwMinorVersion >= 1) || (ovi.dwMajorVersion > 5))
+ {
+ // We use DLLVERSIONINFO_private so we don't have to depend on shlwapi.h
+ typedef struct _DLLVERSIONINFO_private
+ {
+ DWORD cbSize;
+ DWORD dwMajorVersion;
+ DWORD dwMinorVersion;
+ DWORD dwBuildNumber;
+ DWORD dwPlatformID;
+ } DLLVERSIONINFO_private;
+
+ HMODULE hModule = ::LoadLibrary("comctl32.dll");
+ if(hModule != NULL)
+ {
+ typedef HRESULT (CALLBACK *LPFN_DllGetVersion)(DLLVERSIONINFO_private *);
+ LPFN_DllGetVersion fnDllGetVersion = (LPFN_DllGetVersion)::GetProcAddress(hModule, "DllGetVersion");
+ if(fnDllGetVersion != NULL)
+ {
+ DLLVERSIONINFO_private version = { 0 };
+ version.cbSize = sizeof(DLLVERSIONINFO_private);
+ if(SUCCEEDED(fnDllGetVersion(&version)))
+ {
+ if(version.dwMajorVersion >= 6)
+ {
+ pThisNoConst->m_bShadowBufferNeeded = TRUE;
+
+ ATLTRACE2(atlTraceUI, 0, _T("Warning: You have compiled for MBCS/ANSI but are using common controls version 6 or later (likely through a manifest file).\r\n"));
+ ATLTRACE2(atlTraceUI, 0, _T("If you use common controls version 6 or later, you should only do so for UNICODE builds.\r\n"));
+ }
+ }
+ }
+
+ ::FreeLibrary(hModule);
+ hModule = NULL;
+ }
+ }
+#endif // !_UNICODE
+ }
+ }
+
+ return (pT->m_bShadowBufferNeeded != FALSE);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRichEditFindReplaceImpl - Mixin class for implementing Find/Replace for CRichEditCtrl
+// based window classes.
+
+// Chain to CRichEditFindReplaceImpl message map. Your class must also derive from CRichEditCtrl.
+// Example:
+// class CMyRichEdit : public CWindowImpl<CMyRichEdit, CRichEditCtrl>,
+// public CRichEditFindReplaceImpl<CMyRichEdit>
+// {
+// public:
+// BEGIN_MSG_MAP(CMyRichEdit)
+// // your handlers...
+// CHAIN_MSG_MAP_ALT(CRichEditFindReplaceImpl<CMyRichEdit>, 1)
+// END_MSG_MAP()
+// // other stuff...
+// };
+
+template <class T, class TFindReplaceDialog = CFindReplaceDialog>
+class CRichEditFindReplaceImpl : public CEditFindReplaceImplBase<T, TFindReplaceDialog>
+{
+protected:
+ typedef CRichEditFindReplaceImpl<T, TFindReplaceDialog> thisClass;
+ typedef CEditFindReplaceImplBase<T, TFindReplaceDialog> baseClass;
+
+public:
+ BEGIN_MSG_MAP(thisClass)
+ ALT_MSG_MAP(1)
+ CHAIN_MSG_MAP_ALT(baseClass, 1)
+ END_MSG_MAP()
+
+// Operations (overrideable)
+ BOOL FindTextSimple(LPCTSTR lpszFind, BOOL bMatchCase, BOOL bWholeWord, BOOL bFindDown = TRUE)
+ {
+ T* pT = static_cast<T*>(this);
+
+ ATLASSERT(lpszFind != NULL);
+ FINDTEXTEX ft = { 0 };
+
+ pT->GetSel(ft.chrg);
+ if(m_bFirstSearch)
+ {
+ if(bFindDown)
+ m_nInitialSearchPos = ft.chrg.cpMin;
+ else
+ m_nInitialSearchPos = ft.chrg.cpMax;
+ m_bFirstSearch = FALSE;
+ }
+
+#if (_RICHEDIT_VER >= 0x0200)
+ ft.lpstrText = (LPTSTR)lpszFind;
+#else // !(_RICHEDIT_VER >= 0x0200)
+ USES_CONVERSION;
+ ft.lpstrText = T2A((LPTSTR)lpszFind);
+#endif // !(_RICHEDIT_VER >= 0x0200)
+
+ if(ft.chrg.cpMin != ft.chrg.cpMax) // i.e. there is a selection
+ {
+ if(bFindDown)
+ {
+ ft.chrg.cpMin++;
+ }
+ else
+ {
+ // won't wraparound backwards
+ ft.chrg.cpMin = max(ft.chrg.cpMin, 0);
+ }
+ }
+
+ DWORD dwFlags = bMatchCase ? FR_MATCHCASE : 0;
+ dwFlags |= bWholeWord ? FR_WHOLEWORD : 0;
+
+ ft.chrg.cpMax = pT->GetTextLength() + m_nInitialSearchPos;
+
+ if(bFindDown)
+ {
+ if(m_nInitialSearchPos >= 0)
+ ft.chrg.cpMax = pT->GetTextLength();
+
+ dwFlags |= FR_DOWN;
+ ATLASSERT(ft.chrg.cpMax >= ft.chrg.cpMin);
+ }
+ else
+ {
+ if(m_nInitialSearchPos >= 0)
+ ft.chrg.cpMax = 0;
+
+ dwFlags &= ~FR_DOWN;
+ ATLASSERT(ft.chrg.cpMax <= ft.chrg.cpMin);
+ }
+
+ BOOL bRet = FALSE;
+
+ if(pT->FindAndSelect(dwFlags, ft) != -1)
+ {
+ bRet = TRUE; // we found the text
+ }
+ else if(m_nInitialSearchPos > 0)
+ {
+ // if the original starting point was not the beginning
+ // of the buffer and we haven't already been here
+ if(bFindDown)
+ {
+ ft.chrg.cpMin = 0;
+ ft.chrg.cpMax = m_nInitialSearchPos;
+ }
+ else
+ {
+ ft.chrg.cpMin = pT->GetTextLength();
+ ft.chrg.cpMax = m_nInitialSearchPos;
+ }
+ m_nInitialSearchPos = m_nInitialSearchPos - pT->GetTextLength();
+
+ bRet = (pT->FindAndSelect(dwFlags, ft) != -1) ? TRUE : FALSE;
+ }
+
+ return bRet;
+ }
+
+ long FindAndSelect(DWORD dwFlags, FINDTEXTEX& ft)
+ {
+ T* pT = static_cast<T*>(this);
+ LONG index = pT->FindText(dwFlags, ft);
+ if(index != -1) // i.e. we found something
+ pT->SetSel(ft.chrgText);
+
+ return index;
+ }
+};
+
+}; // namespace WTL
+
+#endif // __ATLFIND_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlframe.h b/plugins/SmartAutoReplier/wtl/atlframe.h
new file mode 100644
index 0000000000..252e50e902
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlframe.h
@@ -0,0 +1,3688 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLFRAME_H__
+#define __ATLFRAME_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlframe.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atlframe.h requires atlwin.h to be included first
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CFrameWindowImpl<T, TBase, TWinTraits>
+// CMDIWindow
+// CMDIFrameWindowImpl<T, TBase, TWinTraits>
+// CMDIChildWindowImpl<T, TBase, TWinTraits>
+// COwnerDraw<T>
+// CUpdateUIBase
+// CUpdateUI<T>
+// CDynamicUpdateUI<T>
+// CAutoUpdateUI<T>
+// CDialogResize<T>
+// CDoubleBufferImpl<T>
+// CDoubleBufferWindowImpl<T, TBase, TWinTraits>
+//
+// Global functions:
+// AtlCreateSimpleToolBar()
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CFrameWndClassInfo - Manages frame window Windows class information
+
+class CFrameWndClassInfo
+{
+public:
+#ifndef _WIN32_WCE
+ enum { cchAutoName = 5 + sizeof(void*) * 2 }; // sizeof(void*) * 2 is the number of digits %p outputs
+ WNDCLASSEX m_wc;
+#else // CE specific
+ enum { cchAutoName = MAX_PATH }; // MAX_PATH because this can be set in the wizard generated CMainFrame::ActivatePreviousInstance to a user defined string.
+ WNDCLASS m_wc;
+#endif // !_WIN32_WCE
+ LPCTSTR m_lpszOrigName;
+ WNDPROC pWndProc;
+ LPCTSTR m_lpszCursorID;
+ BOOL m_bSystemCursor;
+ ATOM m_atom;
+ TCHAR m_szAutoName[cchAutoName];
+ UINT m_uCommonResourceID;
+
+#ifndef _WIN32_WCE
+ ATOM Register(WNDPROC* pProc)
+ {
+ if (m_atom == 0)
+ {
+ CWindowCreateCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CFrameWndClassInfo::Register.\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(m_atom == 0)
+ {
+ HINSTANCE hInst = ModuleHelper::GetModuleInstance();
+
+ if (m_lpszOrigName != NULL)
+ {
+ ATLASSERT(pProc != NULL);
+ LPCTSTR lpsz = m_wc.lpszClassName;
+ WNDPROC proc = m_wc.lpfnWndProc;
+
+ WNDCLASSEX wc = { 0 };
+ wc.cbSize = sizeof(WNDCLASSEX);
+ // try process local class first
+ if(!::GetClassInfoEx(ModuleHelper::GetModuleInstance(), m_lpszOrigName, &wc))
+ {
+ // try global class
+ if(!::GetClassInfoEx(NULL, m_lpszOrigName, &wc))
+ {
+ lock.Unlock();
+ return 0;
+ }
+ }
+ m_wc = wc;
+ pWndProc = m_wc.lpfnWndProc;
+ m_wc.lpszClassName = lpsz;
+ m_wc.lpfnWndProc = proc;
+ }
+ else
+ {
+ m_wc.hCursor = ::LoadCursor(m_bSystemCursor ? NULL : hInst, m_lpszCursorID);
+ }
+
+ m_wc.hInstance = hInst;
+ m_wc.style &= ~CS_GLOBALCLASS; // we don't register global classes
+ if (m_wc.lpszClassName == NULL)
+ {
+#if (_WIN32_WINNT >= 0x0500) || defined(_WIN64)
+ SecureHelper::wsprintf_x(m_szAutoName, cchAutoName, _T("ATL:%p"), &m_wc);
+#else // !((_WIN32_WINNT >= 0x0500) || defined(_WIN64))
+ SecureHelper::wsprintf_x(m_szAutoName, cchAutoName, _T("ATL:%8.8X"), (DWORD_PTR)&m_wc);
+#endif // !((_WIN32_WINNT >= 0x0500) || defined(_WIN64))
+ m_wc.lpszClassName = m_szAutoName;
+ }
+
+ WNDCLASSEX wcTemp = m_wc;
+ m_atom = (ATOM)::GetClassInfoEx(m_wc.hInstance, m_wc.lpszClassName, &wcTemp);
+ if (m_atom == 0)
+ {
+ if(m_uCommonResourceID != 0) // use it if not zero
+ {
+ m_wc.hIcon = (HICON)::LoadImage(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(m_uCommonResourceID), IMAGE_ICON, 32, 32, LR_DEFAULTCOLOR);
+ m_wc.hIconSm = (HICON)::LoadImage(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(m_uCommonResourceID), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
+ }
+ m_atom = ::RegisterClassEx(&m_wc);
+ }
+ }
+
+ lock.Unlock();
+ }
+
+ if (m_lpszOrigName != NULL)
+ {
+ ATLASSERT(pProc != NULL);
+ ATLASSERT(pWndProc != NULL);
+ *pProc = pWndProc;
+ }
+
+ return m_atom;
+ }
+#else // CE specific
+ ATOM Register(WNDPROC* pProc)
+ {
+ if (m_atom == 0)
+ {
+ CWindowCreateCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CFrameWndClassInfo::Register.\n"));
+ ATLASSERT(FALSE);
+ return 0;
+ }
+
+ if(m_atom == 0)
+ {
+ HINSTANCE hInst = ModuleHelper::GetModuleInstance();
+
+ if (m_lpszOrigName != NULL)
+ {
+ ATLASSERT(pProc != NULL);
+ LPCTSTR lpsz = m_wc.lpszClassName;
+ WNDPROC proc = m_wc.lpfnWndProc;
+
+ WNDCLASS wc = { 0 };
+ // try process local class first
+ if(!::GetClassInfo(ModuleHelper::GetModuleInstance(), m_lpszOrigName, &wc))
+ {
+ // try global class
+ if(!::GetClassInfo(NULL, m_lpszOrigName, &wc))
+ {
+ lock.Unlock();
+ return 0;
+ }
+ }
+ m_wc = wc;
+ pWndProc = m_wc.lpfnWndProc;
+ m_wc.lpszClassName = lpsz;
+ m_wc.lpfnWndProc = proc;
+ }
+ else
+ {
+#if defined(GWES_CURSOR) || defined(GWES_MCURSOR)
+ m_wc.hCursor = ::LoadCursor(m_bSystemCursor ? NULL : hInst, m_lpszCursorID);
+#else // !(defined(GWES_CURSOR) || defined(GWES_MCURSOR))
+ m_wc.hCursor = NULL;
+#endif // !(defined(GWES_CURSOR) || defined(GWES_MCURSOR))
+ }
+
+ m_wc.hInstance = hInst;
+ m_wc.style &= ~CS_GLOBALCLASS; // we don't register global classes
+ if (m_wc.lpszClassName == NULL)
+ {
+ wsprintf(m_szAutoName, _T("ATL:%8.8X"), (DWORD_PTR)&m_wc);
+ m_wc.lpszClassName = m_szAutoName;
+ }
+
+ WNDCLASS wcTemp = m_wc;
+ m_atom = (ATOM)::GetClassInfo(m_wc.hInstance, m_wc.lpszClassName, &wcTemp);
+ if (m_atom == 0)
+ {
+ if(m_uCommonResourceID != 0) // use it if not zero
+ m_wc.hIcon = (HICON)::LoadImage(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(m_uCommonResourceID), IMAGE_ICON, 32, 32, LR_DEFAULTCOLOR);
+ m_atom = ::RegisterClass(&m_wc);
+ }
+ }
+
+ lock.Unlock();
+ }
+
+ if (m_lpszOrigName != NULL)
+ {
+ ATLASSERT(pProc != NULL);
+ ATLASSERT(pWndProc != NULL);
+ *pProc = pWndProc;
+ }
+
+ return m_atom;
+ }
+#endif // _WIN32_WCE
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Macros for declaring frame window WNDCLASS
+
+#ifndef _WIN32_WCE
+
+#define DECLARE_FRAME_WND_CLASS(WndClassName, uCommonResourceID) \
+static WTL::CFrameWndClassInfo& GetWndClassInfo() \
+{ \
+ static WTL::CFrameWndClassInfo wc = \
+ { \
+ { sizeof(WNDCLASSEX), 0, StartWindowProc, \
+ 0, 0, NULL, NULL, NULL, (HBRUSH)(COLOR_WINDOW + 1), NULL, WndClassName, NULL }, \
+ NULL, NULL, IDC_ARROW, TRUE, 0, _T(""), uCommonResourceID \
+ }; \
+ return wc; \
+}
+
+#define DECLARE_FRAME_WND_CLASS_EX(WndClassName, uCommonResourceID, style, bkgnd) \
+static WTL::CFrameWndClassInfo& GetWndClassInfo() \
+{ \
+ static WTL::CFrameWndClassInfo wc = \
+ { \
+ { sizeof(WNDCLASSEX), style, StartWindowProc, \
+ 0, 0, NULL, NULL, NULL, (HBRUSH)(bkgnd + 1), NULL, WndClassName, NULL }, \
+ NULL, NULL, IDC_ARROW, TRUE, 0, _T(""), uCommonResourceID \
+ }; \
+ return wc; \
+}
+
+#define DECLARE_FRAME_WND_SUPERCLASS(WndClassName, OrigWndClassName, uCommonResourceID) \
+static WTL::CFrameWndClassInfo& GetWndClassInfo() \
+{ \
+ static WTL::CFrameWndClassInfo wc = \
+ { \
+ { sizeof(WNDCLASSEX), 0, StartWindowProc, \
+ 0, 0, NULL, NULL, NULL, NULL, NULL, WndClassName, NULL }, \
+ OrigWndClassName, NULL, NULL, TRUE, 0, _T(""), uCommonResourceID \
+ }; \
+ return wc; \
+}
+
+#else // CE specific
+
+#define DECLARE_FRAME_WND_CLASS(WndClassName, uCommonResourceID) \
+static WTL::CFrameWndClassInfo& GetWndClassInfo() \
+{ \
+ static WTL::CFrameWndClassInfo wc = \
+ { \
+ { 0, StartWindowProc, \
+ 0, 0, NULL, NULL, NULL, (HBRUSH)(COLOR_WINDOW + 1), NULL, WndClassName }, \
+ NULL, NULL, IDC_ARROW, TRUE, 0, _T(""), uCommonResourceID \
+ }; \
+ return wc; \
+}
+
+#define DECLARE_FRAME_WND_CLASS_EX(WndClassName, uCommonResourceID, style, bkgnd) \
+static WTL::CFrameWndClassInfo& GetWndClassInfo() \
+{ \
+ static WTL::CFrameWndClassInfo wc = \
+ { \
+ { style, StartWindowProc, \
+ 0, 0, NULL, NULL, NULL, (HBRUSH)(bkgnd + 1), NULL, WndClassName }, \
+ NULL, NULL, IDC_ARROW, TRUE, 0, _T(""), uCommonResourceID \
+ }; \
+ return wc; \
+}
+
+#define DECLARE_FRAME_WND_SUPERCLASS(WndClassName, OrigWndClassName, uCommonResourceID) \
+static WTL::CFrameWndClassInfo& GetWndClassInfo() \
+{ \
+ static WTL::CFrameWndClassInfo wc = \
+ { \
+ { NULL, StartWindowProc, \
+ 0, 0, NULL, NULL, NULL, NULL, NULL, WndClassName }, \
+ OrigWndClassName, NULL, IDC_ARROW, TRUE, 0, _T(""), uCommonResourceID \
+ }; \
+ return wc; \
+}
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CFrameWindowImpl
+
+// Client window command chaining macro (only for frame windows)
+#define CHAIN_CLIENT_COMMANDS() \
+ if(uMsg == WM_COMMAND && m_hWndClient != NULL) \
+ ::SendMessage(m_hWndClient, uMsg, wParam, lParam);
+
+// standard toolbar styles
+#define ATL_SIMPLE_TOOLBAR_STYLE \
+ (WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | TBSTYLE_TOOLTIPS)
+// toolbar in a rebar pane
+#define ATL_SIMPLE_TOOLBAR_PANE_STYLE \
+ (WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | CCS_NODIVIDER | CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_TOOLTIPS | TBSTYLE_FLAT)
+// standard rebar styles
+#if (_WIN32_IE >= 0x0400)
+ #define ATL_SIMPLE_REBAR_STYLE \
+ (WS_CHILD | WS_VISIBLE | WS_BORDER | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | RBS_VARHEIGHT | RBS_BANDBORDERS | RBS_AUTOSIZE)
+#else
+ #define ATL_SIMPLE_REBAR_STYLE \
+ (WS_CHILD | WS_VISIBLE | WS_BORDER | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | RBS_VARHEIGHT | RBS_BANDBORDERS)
+#endif // !(_WIN32_IE >= 0x0400)
+// rebar without borders
+#if (_WIN32_IE >= 0x0400)
+ #define ATL_SIMPLE_REBAR_NOBORDER_STYLE \
+ (WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | RBS_VARHEIGHT | RBS_BANDBORDERS | RBS_AUTOSIZE | CCS_NODIVIDER)
+#else
+ #define ATL_SIMPLE_REBAR_NOBORDER_STYLE \
+ (WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | RBS_VARHEIGHT | RBS_BANDBORDERS | CCS_NODIVIDER)
+#endif // !(_WIN32_IE >= 0x0400)
+
+// command bar support
+#if !defined(__ATLCTRLW_H__) && !defined(_WIN32_WCE)
+
+#define CBRM_GETCMDBAR (WM_USER + 301) // returns command bar HWND
+#define CBRM_GETMENU (WM_USER + 302) // returns loaded or attached menu
+#define CBRM_TRACKPOPUPMENU (WM_USER + 303) // displays a popup menu
+
+struct _AtlFrameWnd_CmdBarPopupMenu
+{
+ int cbSize;
+ HMENU hMenu;
+ UINT uFlags;
+ int x;
+ int y;
+ LPTPMPARAMS lptpm;
+};
+
+#define CBRPOPUPMENU _AtlFrameWnd_CmdBarPopupMenu
+
+#endif // !defined(__ATLCTRLW_H__) && !defined(_WIN32_WCE)
+
+
+template <class TBase = ATL::CWindow, class TWinTraits = ATL::CFrameWinTraits>
+class ATL_NO_VTABLE CFrameWindowImplBase : public ATL::CWindowImplBaseT< TBase, TWinTraits >
+{
+public:
+ DECLARE_FRAME_WND_CLASS(NULL, 0)
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ struct _ChevronMenuInfo
+ {
+ HMENU hMenu;
+ LPNMREBARCHEVRON lpnm;
+ bool bCmdBar;
+ };
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+
+// Data members
+ HWND m_hWndToolBar;
+ HWND m_hWndStatusBar;
+ HWND m_hWndClient;
+
+#ifdef _WIN32_WCE
+ HWND m_hWndCECommandBar;
+#endif // _WIN32_WCE
+
+ HACCEL m_hAccel;
+
+// Constructor
+ CFrameWindowImplBase() :
+ m_hWndToolBar(NULL),
+ m_hWndStatusBar(NULL),
+ m_hWndClient(NULL),
+#ifdef _WIN32_WCE
+ m_hWndCECommandBar(NULL),
+#endif // _WIN32_WCE
+ m_hAccel(NULL)
+ { }
+
+// Methods
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect, LPCTSTR szWindowName, DWORD dwStyle, DWORD dwExStyle, ATL::_U_MENUorID MenuOrID, ATOM atom, LPVOID lpCreateParam)
+ {
+ ATLASSERT(m_hWnd == NULL);
+
+ if(atom == 0)
+ return NULL;
+
+ ModuleHelper::AddCreateWndData(&m_thunk.cd, this);
+
+ if(MenuOrID.m_hMenu == NULL && (dwStyle & WS_CHILD))
+ MenuOrID.m_hMenu = (HMENU)(UINT_PTR)this;
+ if(rect.m_lpRect == NULL)
+ rect.m_lpRect = &TBase::rcDefault;
+
+ HWND hWnd = ::CreateWindowEx(dwExStyle, MAKEINTATOM(atom), szWindowName,
+ dwStyle, rect.m_lpRect->left, rect.m_lpRect->top, rect.m_lpRect->right - rect.m_lpRect->left,
+ rect.m_lpRect->bottom - rect.m_lpRect->top, hWndParent, MenuOrID.m_hMenu,
+ ModuleHelper::GetModuleInstance(), lpCreateParam);
+
+ ATLASSERT(hWnd == NULL || m_hWnd == hWnd);
+
+ return hWnd;
+ }
+
+ static HWND CreateSimpleToolBarCtrl(HWND hWndParent, UINT nResourceID, BOOL bInitialSeparator = FALSE,
+ DWORD dwStyle = ATL_SIMPLE_TOOLBAR_STYLE, UINT nID = ATL_IDW_TOOLBAR)
+ {
+ HINSTANCE hInst = ModuleHelper::GetResourceInstance();
+ HRSRC hRsrc = ::FindResource(hInst, MAKEINTRESOURCE(nResourceID), RT_TOOLBAR);
+ if (hRsrc == NULL)
+ return NULL;
+
+ HGLOBAL hGlobal = ::LoadResource(hInst, hRsrc);
+ if (hGlobal == NULL)
+ return NULL;
+
+ _AtlToolBarData* pData = (_AtlToolBarData*)::LockResource(hGlobal);
+ if (pData == NULL)
+ return NULL;
+ ATLASSERT(pData->wVersion == 1);
+
+ WORD* pItems = pData->items();
+ int nItems = pData->wItemCount + (bInitialSeparator ? 1 : 0);
+ CTempBuffer<TBBUTTON, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ TBBUTTON* pTBBtn = buff.Allocate(nItems);
+ ATLASSERT(pTBBtn != NULL);
+ if(pTBBtn == NULL)
+ return NULL;
+
+ const int cxSeparator = 8;
+
+ // set initial separator (half width)
+ if(bInitialSeparator)
+ {
+ pTBBtn[0].iBitmap = cxSeparator / 2;
+ pTBBtn[0].idCommand = 0;
+ pTBBtn[0].fsState = 0;
+ pTBBtn[0].fsStyle = TBSTYLE_SEP;
+ pTBBtn[0].dwData = 0;
+ pTBBtn[0].iString = 0;
+ }
+
+ int nBmp = 0;
+ for(int i = 0, j = bInitialSeparator ? 1 : 0; i < pData->wItemCount; i++, j++)
+ {
+ if(pItems[i] != 0)
+ {
+ pTBBtn[j].iBitmap = nBmp++;
+ pTBBtn[j].idCommand = pItems[i];
+ pTBBtn[j].fsState = TBSTATE_ENABLED;
+ pTBBtn[j].fsStyle = TBSTYLE_BUTTON;
+ pTBBtn[j].dwData = 0;
+ pTBBtn[j].iString = 0;
+ }
+ else
+ {
+ pTBBtn[j].iBitmap = cxSeparator;
+ pTBBtn[j].idCommand = 0;
+ pTBBtn[j].fsState = 0;
+ pTBBtn[j].fsStyle = TBSTYLE_SEP;
+ pTBBtn[j].dwData = 0;
+ pTBBtn[j].iString = 0;
+ }
+ }
+
+#ifndef _WIN32_WCE
+ HWND hWnd = ::CreateWindowEx(0, TOOLBARCLASSNAME, NULL, dwStyle, 0, 0, 100, 100, hWndParent, (HMENU)LongToHandle(nID), ModuleHelper::GetModuleInstance(), NULL);
+ if(hWnd == NULL)
+ {
+ ATLASSERT(FALSE);
+ return NULL;
+ }
+#else // CE specific
+ dwStyle;
+ nID;
+ // The toolbar must go onto the existing CommandBar or MenuBar
+ HWND hWnd = hWndParent;
+#endif // _WIN32_WCE
+
+ ::SendMessage(hWnd, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0L);
+
+ // check if font is taller than our bitmaps
+ CFontHandle font = (HFONT)::SendMessage(hWnd, WM_GETFONT, 0, 0L);
+ if(font.IsNull())
+ font = (HFONT)::GetStockObject(SYSTEM_FONT);
+ LOGFONT lf = { 0 };
+ font.GetLogFont(lf);
+ WORD cyFontHeight = (WORD)abs(lf.lfHeight);
+
+#ifndef _WIN32_WCE
+ WORD bitsPerPixel = AtlGetBitmapResourceBitsPerPixel(nResourceID);
+ if(bitsPerPixel > 4)
+ {
+ COLORREF crMask = CLR_DEFAULT;
+ if(bitsPerPixel == 32)
+ {
+ // 32-bit color bitmap with alpha channel (valid for Windows XP and later)
+ crMask = CLR_NONE;
+ }
+ HIMAGELIST hImageList = ImageList_LoadImage(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(nResourceID), pData->wWidth, 1, crMask, IMAGE_BITMAP, LR_CREATEDIBSECTION | LR_DEFAULTSIZE);
+ ATLASSERT(hImageList != NULL);
+ ::SendMessage(hWnd, TB_SETIMAGELIST, 0, (LPARAM)hImageList);
+ }
+ else
+#endif // !_WIN32_WCE
+ {
+ TBADDBITMAP tbab = { 0 };
+ tbab.hInst = hInst;
+ tbab.nID = nResourceID;
+ ::SendMessage(hWnd, TB_ADDBITMAP, nBmp, (LPARAM)&tbab);
+ }
+
+ ::SendMessage(hWnd, TB_ADDBUTTONS, nItems, (LPARAM)pTBBtn);
+ ::SendMessage(hWnd, TB_SETBITMAPSIZE, 0, MAKELONG(pData->wWidth, max(pData->wHeight, cyFontHeight)));
+ const int cxyButtonMargin = 7;
+ ::SendMessage(hWnd, TB_SETBUTTONSIZE, 0, MAKELONG(pData->wWidth + cxyButtonMargin, max(pData->wHeight, cyFontHeight) + cxyButtonMargin));
+
+ return hWnd;
+ }
+
+#ifndef _WIN32_WCE
+ static HWND CreateSimpleReBarCtrl(HWND hWndParent, DWORD dwStyle = ATL_SIMPLE_REBAR_STYLE, UINT nID = ATL_IDW_TOOLBAR)
+ {
+ // Ensure style combinations for proper rebar painting
+ if(dwStyle & CCS_NODIVIDER && dwStyle & WS_BORDER)
+ dwStyle &= ~WS_BORDER;
+ else if(!(dwStyle & WS_BORDER) && !(dwStyle & CCS_NODIVIDER))
+ dwStyle |= CCS_NODIVIDER;
+
+ // Create rebar window
+ HWND hWndReBar = ::CreateWindowEx(0, REBARCLASSNAME, NULL, dwStyle, 0, 0, 100, 100, hWndParent, (HMENU)LongToHandle(nID), ModuleHelper::GetModuleInstance(), NULL);
+ if(hWndReBar == NULL)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("Failed to create rebar.\n"));
+ return NULL;
+ }
+
+ // Initialize and send the REBARINFO structure
+ REBARINFO rbi = { 0 };
+ rbi.cbSize = sizeof(REBARINFO);
+ rbi.fMask = 0;
+ if(!::SendMessage(hWndReBar, RB_SETBARINFO, 0, (LPARAM)&rbi))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("Failed to initialize rebar.\n"));
+ ::DestroyWindow(hWndReBar);
+ return NULL;
+ }
+
+ return hWndReBar;
+ }
+
+ BOOL CreateSimpleReBar(DWORD dwStyle = ATL_SIMPLE_REBAR_STYLE, UINT nID = ATL_IDW_TOOLBAR)
+ {
+ ATLASSERT(!::IsWindow(m_hWndToolBar));
+ m_hWndToolBar = CreateSimpleReBarCtrl(m_hWnd, dwStyle, nID);
+ return (m_hWndToolBar != NULL);
+ }
+
+ static BOOL AddSimpleReBarBandCtrl(HWND hWndReBar, HWND hWndBand, int nID = 0, LPCTSTR lpstrTitle = NULL, BOOL bNewRow = FALSE, int cxWidth = 0, BOOL bFullWidthAlways = FALSE)
+ {
+ ATLASSERT(::IsWindow(hWndReBar)); // must be already created
+#ifdef _DEBUG
+ // block - check if this is really a rebar
+ {
+ TCHAR lpszClassName[sizeof(REBARCLASSNAME)] = { 0 };
+ ::GetClassName(hWndReBar, lpszClassName, sizeof(REBARCLASSNAME));
+ ATLASSERT(lstrcmp(lpszClassName, REBARCLASSNAME) == 0);
+ }
+#endif // _DEBUG
+ ATLASSERT(::IsWindow(hWndBand)); // must be already created
+
+ // Get number of buttons on the toolbar
+ int nBtnCount = (int)::SendMessage(hWndBand, TB_BUTTONCOUNT, 0, 0L);
+
+ // Set band info structure
+ REBARBANDINFO rbBand = { RunTimeHelper::SizeOf_REBARBANDINFO() };
+#if (_WIN32_IE >= 0x0400)
+ rbBand.fMask = RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_STYLE | RBBIM_ID | RBBIM_SIZE | RBBIM_IDEALSIZE;
+#else
+ rbBand.fMask = RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_STYLE | RBBIM_ID | RBBIM_SIZE;
+#endif // !(_WIN32_IE >= 0x0400)
+ if(lpstrTitle != NULL)
+ rbBand.fMask |= RBBIM_TEXT;
+ rbBand.fStyle = RBBS_CHILDEDGE;
+#if (_WIN32_IE >= 0x0500)
+ if(nBtnCount > 0) // add chevron style for toolbar with buttons
+ rbBand.fStyle |= RBBS_USECHEVRON;
+#endif // (_WIN32_IE >= 0x0500)
+ if(bNewRow)
+ rbBand.fStyle |= RBBS_BREAK;
+
+ rbBand.lpText = (LPTSTR)lpstrTitle;
+ rbBand.hwndChild = hWndBand;
+ if(nID == 0) // calc band ID
+ nID = ATL_IDW_BAND_FIRST + (int)::SendMessage(hWndReBar, RB_GETBANDCOUNT, 0, 0L);
+ rbBand.wID = nID;
+
+ // Calculate the size of the band
+ BOOL bRet = FALSE;
+ RECT rcTmp = { 0 };
+ if(nBtnCount > 0)
+ {
+ bRet = (BOOL)::SendMessage(hWndBand, TB_GETITEMRECT, nBtnCount - 1, (LPARAM)&rcTmp);
+ ATLASSERT(bRet);
+ rbBand.cx = (cxWidth != 0) ? cxWidth : rcTmp.right;
+ rbBand.cyMinChild = rcTmp.bottom - rcTmp.top;
+ if(bFullWidthAlways)
+ {
+ rbBand.cxMinChild = rbBand.cx;
+ }
+ else if(lpstrTitle == NULL)
+ {
+ bRet = (BOOL)::SendMessage(hWndBand, TB_GETITEMRECT, 0, (LPARAM)&rcTmp);
+ ATLASSERT(bRet);
+ rbBand.cxMinChild = rcTmp.right;
+ }
+ else
+ {
+ rbBand.cxMinChild = 0;
+ }
+ }
+ else // no buttons, either not a toolbar or really has no buttons
+ {
+ bRet = ::GetWindowRect(hWndBand, &rcTmp);
+ ATLASSERT(bRet);
+ rbBand.cx = (cxWidth != 0) ? cxWidth : (rcTmp.right - rcTmp.left);
+ rbBand.cxMinChild = bFullWidthAlways ? rbBand.cx : 0;
+ rbBand.cyMinChild = rcTmp.bottom - rcTmp.top;
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ rbBand.cxIdeal = rbBand.cx;
+#endif // (_WIN32_IE >= 0x0400)
+
+ // Add the band
+ LRESULT lRes = ::SendMessage(hWndReBar, RB_INSERTBAND, (WPARAM)-1, (LPARAM)&rbBand);
+ if(lRes == 0)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("Failed to add a band to the rebar.\n"));
+ return FALSE;
+ }
+
+#if (_WIN32_IE >= 0x0501)
+ DWORD dwExStyle = (DWORD)::SendMessage(hWndBand, TB_GETEXTENDEDSTYLE, 0, 0L);
+ ::SendMessage(hWndBand, TB_SETEXTENDEDSTYLE, 0, dwExStyle | TBSTYLE_EX_HIDECLIPPEDBUTTONS);
+#endif // (_WIN32_IE >= 0x0501)
+
+ return TRUE;
+ }
+
+ BOOL AddSimpleReBarBand(HWND hWndBand, LPCTSTR lpstrTitle = NULL, BOOL bNewRow = FALSE, int cxWidth = 0, BOOL bFullWidthAlways = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWndToolBar)); // must be an existing rebar
+ ATLASSERT(::IsWindow(hWndBand)); // must be created
+ return AddSimpleReBarBandCtrl(m_hWndToolBar, hWndBand, 0, lpstrTitle, bNewRow, cxWidth, bFullWidthAlways);
+ }
+
+#if (_WIN32_IE >= 0x0400)
+ void SizeSimpleReBarBands()
+ {
+ ATLASSERT(::IsWindow(m_hWndToolBar)); // must be an existing rebar
+
+ int nCount = (int)::SendMessage(m_hWndToolBar, RB_GETBANDCOUNT, 0, 0L);
+
+ for(int i = 0; i < nCount; i++)
+ {
+ REBARBANDINFO rbBand = { RunTimeHelper::SizeOf_REBARBANDINFO() };
+ rbBand.fMask = RBBIM_SIZE;
+ BOOL bRet = (BOOL)::SendMessage(m_hWndToolBar, RB_GETBANDINFO, i, (LPARAM)&rbBand);
+ ATLASSERT(bRet);
+ RECT rect = { 0, 0, 0, 0 };
+ ::SendMessage(m_hWndToolBar, RB_GETBANDBORDERS, i, (LPARAM)&rect);
+ rbBand.cx += rect.left + rect.right;
+ bRet = (BOOL)::SendMessage(m_hWndToolBar, RB_SETBANDINFO, i, (LPARAM)&rbBand);
+ ATLASSERT(bRet);
+ }
+ }
+#endif // (_WIN32_IE >= 0x0400)
+#endif // _WIN32_WCE
+
+#ifndef _WIN32_WCE
+ BOOL CreateSimpleStatusBar(LPCTSTR lpstrText, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | SBARS_SIZEGRIP, UINT nID = ATL_IDW_STATUS_BAR)
+#else // CE specific
+ BOOL CreateSimpleStatusBar(LPCTSTR lpstrText, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, UINT nID = ATL_IDW_STATUS_BAR)
+#endif // _WIN32_WCE
+ {
+ ATLASSERT(!::IsWindow(m_hWndStatusBar));
+ m_hWndStatusBar = ::CreateStatusWindow(dwStyle, lpstrText, m_hWnd, nID);
+ return (m_hWndStatusBar != NULL);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL CreateSimpleStatusBar(UINT nTextID = ATL_IDS_IDLEMESSAGE, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | SBARS_SIZEGRIP, UINT nID = ATL_IDW_STATUS_BAR)
+#else // CE specific
+ BOOL CreateSimpleStatusBar(UINT nTextID = ATL_IDS_IDLEMESSAGE, DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, UINT nID = ATL_IDW_STATUS_BAR)
+#endif // _WIN32_WCE
+ {
+ const int cchMax = 128; // max text length is 127 for status bars (+1 for null)
+ TCHAR szText[cchMax];
+ szText[0] = 0;
+ ::LoadString(ModuleHelper::GetResourceInstance(), nTextID, szText, cchMax);
+ return CreateSimpleStatusBar(szText, dwStyle, nID);
+ }
+
+#ifdef _WIN32_WCE
+ BOOL CreateSimpleCECommandBar(LPTSTR pszMenu = NULL, WORD iButton = 0, DWORD dwFlags = 0, int nCmdBarID = 1)
+ {
+ ATLASSERT(m_hWndCECommandBar == NULL);
+ ATLASSERT(m_hWndToolBar == NULL);
+
+ m_hWndCECommandBar = ::CommandBar_Create(ModuleHelper::GetModuleInstance(), m_hWnd, nCmdBarID);
+ if(m_hWndCECommandBar == NULL)
+ return FALSE;
+
+ m_hWndToolBar = m_hWndCECommandBar;
+
+ BOOL bRet = TRUE;
+
+ if(pszMenu != NULL)
+ bRet &= ::CommandBar_InsertMenubarEx(m_hWndCECommandBar, IS_INTRESOURCE(pszMenu) ? ModuleHelper::GetResourceInstance() : NULL, pszMenu, iButton);
+
+ bRet &= ::CommandBar_AddAdornments(m_hWndCECommandBar, dwFlags, 0);
+
+ return bRet;
+ }
+
+#if defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__)
+ BOOL CreateSimpleCEMenuBar(UINT nToolBarId = ATL_IDW_MENU_BAR, DWORD dwFlags = 0, int nBmpId = 0, int cBmpImages = 0)
+ {
+ ATLASSERT(m_hWndCECommandBar == NULL);
+
+ SHMENUBARINFO mbi = { 0 };
+ mbi.cbSize = sizeof(mbi);
+ mbi.hwndParent = m_hWnd;
+ mbi.dwFlags = dwFlags;
+ mbi.nToolBarId = nToolBarId;
+ mbi.hInstRes = ModuleHelper::GetResourceInstance();
+ mbi.nBmpId = nBmpId;
+ mbi.cBmpImages = cBmpImages;
+ mbi.hwndMB = NULL; // This gets set by SHCreateMenuBar
+
+ BOOL bRet = ::SHCreateMenuBar(&mbi);
+ if(bRet != FALSE)
+ {
+ m_hWndCECommandBar = mbi.hwndMB;
+ SizeToMenuBar();
+ }
+
+ return bRet;
+ }
+
+ void SizeToMenuBar() // for menu bar only
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(::IsWindow(m_hWndCECommandBar));
+
+ RECT rect = { 0 };
+ GetWindowRect(&rect);
+ RECT rectMB = { 0 };
+ ::GetWindowRect(m_hWndCECommandBar, &rectMB);
+ int cy = ::IsWindowVisible(m_hWndCECommandBar) ? rectMB.top - rect.top : rectMB.bottom - rect.top;
+ SetWindowPos(NULL, 0, 0, rect.right - rect.left, cy, SWP_NOZORDER | SWP_NOMOVE);
+ }
+#endif // defined(_AYGSHELL_H_) || defined(__AYGSHELL_H__)
+#endif // _WIN32_WCE
+
+ void UpdateLayout(BOOL bResizeBars = TRUE)
+ {
+ RECT rect = { 0 };
+ GetClientRect(&rect);
+
+ // position bars and offset their dimensions
+ UpdateBarsPosition(rect, bResizeBars);
+
+ // resize client window
+ if(m_hWndClient != NULL)
+ ::SetWindowPos(m_hWndClient, NULL, rect.left, rect.top,
+ rect.right - rect.left, rect.bottom - rect.top,
+ SWP_NOZORDER | SWP_NOACTIVATE);
+ }
+
+ void UpdateBarsPosition(RECT& rect, BOOL bResizeBars = TRUE)
+ {
+ // resize toolbar
+ if(m_hWndToolBar != NULL && ((DWORD)::GetWindowLong(m_hWndToolBar, GWL_STYLE) & WS_VISIBLE))
+ {
+ if(bResizeBars != FALSE)
+ {
+ ::SendMessage(m_hWndToolBar, WM_SIZE, 0, 0);
+ ::InvalidateRect(m_hWndToolBar, NULL, TRUE);
+ }
+ RECT rectTB = { 0 };
+ ::GetWindowRect(m_hWndToolBar, &rectTB);
+ rect.top += rectTB.bottom - rectTB.top;
+ }
+
+ // resize status bar
+ if(m_hWndStatusBar != NULL && ((DWORD)::GetWindowLong(m_hWndStatusBar, GWL_STYLE) & WS_VISIBLE))
+ {
+ if(bResizeBars != FALSE)
+ ::SendMessage(m_hWndStatusBar, WM_SIZE, 0, 0);
+ RECT rectSB = { 0 };
+ ::GetWindowRect(m_hWndStatusBar, &rectSB);
+ rect.bottom -= rectSB.bottom - rectSB.top;
+ }
+ }
+
+ BOOL PreTranslateMessage(MSG* pMsg)
+ {
+ if(m_hAccel != NULL && ::TranslateAccelerator(m_hWnd, m_hAccel, pMsg))
+ return TRUE;
+ return FALSE;
+ }
+
+ BEGIN_MSG_MAP(CFrameWindowImplBase)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_MENUSELECT, OnMenuSelect)
+#endif // !_WIN32_WCE
+ MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+#ifndef _WIN32_WCE
+ NOTIFY_CODE_HANDLER(TTN_GETDISPINFOA, OnToolTipTextA)
+ NOTIFY_CODE_HANDLER(TTN_GETDISPINFOW, OnToolTipTextW)
+#endif // !_WIN32_WCE
+ END_MSG_MAP()
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_hWndClient != NULL) // view will paint itself instead
+ return 1;
+
+ bHandled = FALSE;
+ return 0;
+ }
+
+#ifndef _WIN32_WCE
+ LRESULT OnMenuSelect(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ bHandled = FALSE;
+
+ if(m_hWndStatusBar == NULL)
+ return 1;
+
+ WORD wFlags = HIWORD(wParam);
+ if(wFlags == 0xFFFF && lParam == NULL) // menu closing
+ {
+ ::SendMessage(m_hWndStatusBar, SB_SIMPLE, FALSE, 0L);
+ }
+ else
+ {
+ const int cchBuff = 256;
+ TCHAR szBuff[cchBuff];
+ szBuff[0] = 0;
+ if(!(wFlags & MF_POPUP))
+ {
+ WORD wID = LOWORD(wParam);
+ // check for special cases
+ if(wID >= 0xF000 && wID < 0xF1F0) // system menu IDs
+ wID = (WORD)(((wID - 0xF000) >> 4) + ATL_IDS_SCFIRST);
+ else if(wID >= ID_FILE_MRU_FIRST && wID <= ID_FILE_MRU_LAST) // MRU items
+ wID = ATL_IDS_MRU_FILE;
+ else if(wID >= ATL_IDM_FIRST_MDICHILD && wID <= ATL_IDM_LAST_MDICHILD) // MDI child windows
+ wID = ATL_IDS_MDICHILD;
+
+ int nRet = ::LoadString(ModuleHelper::GetResourceInstance(), wID, szBuff, cchBuff);
+ for(int i = 0; i < nRet; i++)
+ {
+ if(szBuff[i] == _T('\n'))
+ {
+ szBuff[i] = 0;
+ break;
+ }
+ }
+ }
+ ::SendMessage(m_hWndStatusBar, SB_SIMPLE, TRUE, 0L);
+ ::SendMessage(m_hWndStatusBar, SB_SETTEXT, (255 | SBT_NOBORDERS), (LPARAM)szBuff);
+ }
+
+ return 1;
+ }
+#endif // !_WIN32_WCE
+
+ LRESULT OnSetFocus(UINT, WPARAM, LPARAM, BOOL& bHandled)
+ {
+ if(m_hWndClient != NULL)
+ ::SetFocus(m_hWndClient);
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnDestroy(UINT, WPARAM, LPARAM, BOOL& bHandled)
+ {
+ if((GetStyle() & (WS_CHILD | WS_POPUP)) == 0)
+ ::PostQuitMessage(1);
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+#ifndef _WIN32_WCE
+ LRESULT OnToolTipTextA(int idCtrl, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ LPNMTTDISPINFOA pDispInfo = (LPNMTTDISPINFOA)pnmh;
+ pDispInfo->szText[0] = 0;
+
+ if((idCtrl != 0) && !(pDispInfo->uFlags & TTF_IDISHWND))
+ {
+ const int cchBuff = 256;
+ char szBuff[cchBuff];
+ szBuff[0] = 0;
+ int nRet = ::LoadStringA(ModuleHelper::GetResourceInstance(), idCtrl, szBuff, cchBuff);
+ for(int i = 0; i < nRet; i++)
+ {
+ if(szBuff[i] == '\n')
+ {
+ SecureHelper::strncpyA_x(pDispInfo->szText, _countof(pDispInfo->szText), &szBuff[i + 1], _TRUNCATE);
+ break;
+ }
+ }
+#if (_WIN32_IE >= 0x0300)
+ if(nRet > 0) // string was loaded, save it
+ pDispInfo->uFlags |= TTF_DI_SETITEM;
+#endif // (_WIN32_IE >= 0x0300)
+ }
+
+ return 0;
+ }
+
+ LRESULT OnToolTipTextW(int idCtrl, LPNMHDR pnmh, BOOL& /*bHandled*/)
+ {
+ LPNMTTDISPINFOW pDispInfo = (LPNMTTDISPINFOW)pnmh;
+ pDispInfo->szText[0] = 0;
+
+ if((idCtrl != 0) && !(pDispInfo->uFlags & TTF_IDISHWND))
+ {
+ const int cchBuff = 256;
+ wchar_t szBuff[cchBuff];
+ szBuff[0] = 0;
+ int nRet = ::LoadStringW(ModuleHelper::GetResourceInstance(), idCtrl, szBuff, cchBuff);
+ for(int i = 0; i < nRet; i++)
+ {
+ if(szBuff[i] == L'\n')
+ {
+ SecureHelper::strncpyW_x(pDispInfo->szText, _countof(pDispInfo->szText), &szBuff[i + 1], _TRUNCATE);
+ break;
+ }
+ }
+#if (_WIN32_IE >= 0x0300)
+ if(nRet > 0) // string was loaded, save it
+ pDispInfo->uFlags |= TTF_DI_SETITEM;
+#endif // (_WIN32_IE >= 0x0300)
+ }
+
+ return 0;
+ }
+#endif // !_WIN32_WCE
+
+// Implementation - chevron menu support
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ bool PrepareChevronMenu(_ChevronMenuInfo& cmi)
+ {
+ // get rebar and toolbar
+ REBARBANDINFO rbbi = { RunTimeHelper::SizeOf_REBARBANDINFO() };
+ rbbi.fMask = RBBIM_CHILD;
+ BOOL bRet = (BOOL)::SendMessage(cmi.lpnm->hdr.hwndFrom, RB_GETBANDINFO, cmi.lpnm->uBand, (LPARAM)&rbbi);
+ ATLASSERT(bRet);
+
+ // assume the band is a toolbar
+ ATL::CWindow wnd = rbbi.hwndChild;
+ int nCount = (int)wnd.SendMessage(TB_BUTTONCOUNT);
+ if(nCount <= 0) // probably not a toolbar
+ return false;
+
+ // check if it's a command bar
+ CMenuHandle menuCmdBar = (HMENU)wnd.SendMessage(CBRM_GETMENU);
+ cmi.bCmdBar = (menuCmdBar.m_hMenu != NULL);
+
+ // build a menu from hidden items
+ CMenuHandle menu;
+ bRet = menu.CreatePopupMenu();
+ ATLASSERT(bRet);
+ RECT rcClient = { 0 };
+ bRet = wnd.GetClientRect(&rcClient);
+ ATLASSERT(bRet);
+ for(int i = 0; i < nCount; i++)
+ {
+ TBBUTTON tbb = { 0 };
+ bRet = (BOOL)wnd.SendMessage(TB_GETBUTTON, i, (LPARAM)&tbb);
+ ATLASSERT(bRet);
+ // skip hidden buttons
+ if((tbb.fsState & TBSTATE_HIDDEN) != 0)
+ continue;
+ RECT rcButton = { 0 };
+ bRet = (BOOL)wnd.SendMessage(TB_GETITEMRECT, i, (LPARAM)&rcButton);
+ ATLASSERT(bRet);
+ bool bEnabled = ((tbb.fsState & TBSTATE_ENABLED) != 0);
+ if(rcButton.right > rcClient.right)
+ {
+ if(tbb.fsStyle & BTNS_SEP)
+ {
+ if(menu.GetMenuItemCount() > 0)
+ menu.AppendMenu(MF_SEPARATOR);
+ }
+ else if(cmi.bCmdBar)
+ {
+ const int cchBuff = 200;
+ TCHAR szBuff[cchBuff] = { 0 };
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_TYPE | MIIM_SUBMENU;
+ mii.dwTypeData = szBuff;
+ mii.cch = cchBuff;
+ bRet = menuCmdBar.GetMenuItemInfo(i, TRUE, &mii);
+ ATLASSERT(bRet);
+ // Note: CmdBar currently supports only drop-down items
+ ATLASSERT(::IsMenu(mii.hSubMenu));
+ bRet = menu.AppendMenu(MF_STRING | MF_POPUP | (bEnabled ? MF_ENABLED : MF_GRAYED), (UINT_PTR)mii.hSubMenu, mii.dwTypeData);
+ ATLASSERT(bRet);
+ }
+ else
+ {
+ // get button's text
+ const int cchBuff = 200;
+ TCHAR szBuff[cchBuff] = { 0 };
+ LPTSTR lpstrText = szBuff;
+ TBBUTTONINFO tbbi = { 0 };
+ tbbi.cbSize = sizeof(TBBUTTONINFO);
+ tbbi.dwMask = TBIF_TEXT;
+ tbbi.pszText = szBuff;
+ tbbi.cchText = cchBuff;
+ if(wnd.SendMessage(TB_GETBUTTONINFO, tbb.idCommand, (LPARAM)&tbbi) == -1 || lstrlen(szBuff) == 0)
+ {
+ // no text for this button, try a resource string
+ lpstrText = _T("");
+ int nRet = ::LoadString(ModuleHelper::GetResourceInstance(), tbb.idCommand, szBuff, cchBuff);
+ for(int n = 0; n < nRet; n++)
+ {
+ if(szBuff[n] == _T('\n'))
+ {
+ lpstrText = &szBuff[n + 1];
+ break;
+ }
+ }
+ }
+ bRet = menu.AppendMenu(MF_STRING | (bEnabled ? MF_ENABLED : MF_GRAYED), tbb.idCommand, lpstrText);
+ ATLASSERT(bRet);
+ }
+ }
+ }
+
+ if(menu.GetMenuItemCount() == 0) // no hidden buttons after all
+ {
+ menu.DestroyMenu();
+ ::MessageBeep((UINT)-1);
+ return false;
+ }
+
+ cmi.hMenu = menu;
+ return true;
+ }
+
+ void DisplayChevronMenu(_ChevronMenuInfo& cmi)
+ {
+#ifndef TPM_VERPOSANIMATION
+ const UINT TPM_VERPOSANIMATION = 0x1000L; // Menu animation flag
+#endif
+ // convert chevron rect to screen coordinates
+ ATL::CWindow wndFrom = cmi.lpnm->hdr.hwndFrom;
+ POINT pt = { cmi.lpnm->rc.left, cmi.lpnm->rc.bottom };
+ wndFrom.MapWindowPoints(NULL, &pt, 1);
+ RECT rc = cmi.lpnm->rc;
+ wndFrom.MapWindowPoints(NULL, &rc);
+ // set up flags and rect
+ UINT uMenuFlags = TPM_LEFTBUTTON | TPM_VERTICAL | TPM_LEFTALIGN | TPM_TOPALIGN | (!AtlIsOldWindows() ? TPM_VERPOSANIMATION : 0);
+ TPMPARAMS TPMParams = { 0 };
+ TPMParams.cbSize = sizeof(TPMPARAMS);
+ TPMParams.rcExclude = rc;
+ // check if this window has a command bar
+ HWND hWndCmdBar = (HWND)::SendMessage(m_hWnd, CBRM_GETCMDBAR, 0, 0L);
+ if(::IsWindow(hWndCmdBar))
+ {
+ CBRPOPUPMENU CBRPopupMenu = { sizeof(CBRPOPUPMENU), cmi.hMenu, uMenuFlags, pt.x, pt.y, &TPMParams };
+ ::SendMessage(hWndCmdBar, CBRM_TRACKPOPUPMENU, 0, (LPARAM)&CBRPopupMenu);
+ }
+ else
+ {
+ CMenuHandle menu = cmi.hMenu;
+ menu.TrackPopupMenuEx(uMenuFlags, pt.x, pt.y, m_hWnd, &TPMParams);
+ }
+ }
+
+ void CleanupChevronMenu(_ChevronMenuInfo& cmi)
+ {
+ CMenuHandle menu = cmi.hMenu;
+ // if menu is from a command bar, detach submenus so they are not destroyed
+ if(cmi.bCmdBar)
+ {
+ for(int i = menu.GetMenuItemCount() - 1; i >=0; i--)
+ menu.RemoveMenu(i, MF_BYPOSITION);
+ }
+ // destroy menu
+ menu.DestroyMenu();
+ // convert chevron rect to screen coordinates
+ ATL::CWindow wndFrom = cmi.lpnm->hdr.hwndFrom;
+ RECT rc = cmi.lpnm->rc;
+ wndFrom.MapWindowPoints(NULL, &rc);
+ // eat next message if click is on the same button
+ MSG msg = { 0 };
+ if(::PeekMessage(&msg, m_hWnd, WM_LBUTTONDOWN, WM_LBUTTONDOWN, PM_NOREMOVE) && ::PtInRect(&rc, msg.pt))
+ ::PeekMessage(&msg, m_hWnd, WM_LBUTTONDOWN, WM_LBUTTONDOWN, PM_REMOVE);
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+};
+
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CFrameWinTraits>
+class ATL_NO_VTABLE CFrameWindowImpl : public CFrameWindowImplBase< TBase, TWinTraits >
+{
+public:
+ HWND Create(HWND hWndParent = NULL, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ HMENU hMenu = NULL, LPVOID lpCreateParam = NULL)
+ {
+ ATOM atom = T::GetWndClassInfo().Register(&m_pfnSuperWindowProc);
+
+ dwStyle = T::GetWndStyle(dwStyle);
+ dwExStyle = T::GetWndExStyle(dwExStyle);
+
+ if(rect.m_lpRect == NULL)
+ rect.m_lpRect = &TBase::rcDefault;
+
+ return CFrameWindowImplBase< TBase, TWinTraits >::Create(hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, hMenu, atom, lpCreateParam);
+ }
+
+ HWND CreateEx(HWND hWndParent = NULL, ATL::_U_RECT rect = NULL, DWORD dwStyle = 0, DWORD dwExStyle = 0, LPVOID lpCreateParam = NULL)
+ {
+ const int cchName = 256;
+ TCHAR szWindowName[cchName];
+ szWindowName[0] = 0;
+#ifndef _WIN32_WCE
+ ::LoadString(ModuleHelper::GetResourceInstance(), T::GetWndClassInfo().m_uCommonResourceID, szWindowName, cchName);
+ HMENU hMenu = ::LoadMenu(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(T::GetWndClassInfo().m_uCommonResourceID));
+#else // CE specific
+ ::LoadString(ModuleHelper::GetResourceInstance(), T::GetWndClassInfo().m_uCommonResourceID, szWindowName, cchName);
+
+ // This always needs to be NULL for Windows CE.
+ // Frame Window menus have to go onto the CommandBar.
+ // Use CreateSimpleCECommandBar
+ HMENU hMenu = NULL;
+#endif // _WIN32_WCE
+
+ T* pT = static_cast<T*>(this);
+ HWND hWnd = pT->Create(hWndParent, rect, szWindowName, dwStyle, dwExStyle, hMenu, lpCreateParam);
+
+ if(hWnd != NULL)
+ m_hAccel = ::LoadAccelerators(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(T::GetWndClassInfo().m_uCommonResourceID));
+
+ return hWnd;
+ }
+
+ BOOL CreateSimpleToolBar(UINT nResourceID = 0, DWORD dwStyle = ATL_SIMPLE_TOOLBAR_STYLE, UINT nID = ATL_IDW_TOOLBAR)
+ {
+ if(nResourceID == 0)
+ nResourceID = T::GetWndClassInfo().m_uCommonResourceID;
+#ifndef _WIN32_WCE
+ ATLASSERT(!::IsWindow(m_hWndToolBar));
+ m_hWndToolBar = T::CreateSimpleToolBarCtrl(m_hWnd, nResourceID, TRUE, dwStyle, nID);
+ return (m_hWndToolBar != NULL);
+#else // CE specific
+ HWND hWnd= T::CreateSimpleToolBarCtrl(m_hWndCECommandBar, nResourceID, TRUE, dwStyle, nID);
+ return (hWnd != NULL);
+#endif // _WIN32_WCE
+ }
+
+#ifdef _WIN32_WCE
+ // CE specific variant that returns the handle of the toolbar
+ HWND CreateSimpleCEToolBar(UINT nResourceID = 0, DWORD dwStyle = ATL_SIMPLE_TOOLBAR_STYLE, UINT nID = ATL_IDW_TOOLBAR)
+ {
+ if(nResourceID == 0)
+ nResourceID = T::GetWndClassInfo().m_uCommonResourceID;
+
+ return T::CreateSimpleToolBarCtrl(m_hWndCECommandBar, nResourceID, TRUE, dwStyle, nID);
+ }
+#endif // _WIN32_WCE
+
+// message map and handlers
+ typedef CFrameWindowImplBase< TBase, TWinTraits > _baseClass;
+
+ BEGIN_MSG_MAP(CFrameWindowImpl)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+#ifndef _ATL_NO_REBAR_SUPPORT
+#if (_WIN32_IE >= 0x0400)
+ NOTIFY_CODE_HANDLER(RBN_AUTOSIZE, OnReBarAutoSize)
+#endif // (_WIN32_IE >= 0x0400)
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ NOTIFY_CODE_HANDLER(RBN_CHEVRONPUSHED, OnChevronPushed)
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+#endif // !_ATL_NO_REBAR_SUPPORT
+ CHAIN_MSG_MAP(_baseClass)
+ END_MSG_MAP()
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(wParam != SIZE_MINIMIZED)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+#ifndef _ATL_NO_REBAR_SUPPORT
+#if (_WIN32_IE >= 0x0400)
+ LRESULT OnReBarAutoSize(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout(FALSE);
+ return 0;
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+ LRESULT OnChevronPushed(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ _ChevronMenuInfo cmi = { NULL, (LPNMREBARCHEVRON)pnmh, false };
+ if(!pT->PrepareChevronMenu(cmi))
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+ // display a popup menu with hidden items
+ pT->DisplayChevronMenu(cmi);
+ // cleanup
+ pT->CleanupChevronMenu(cmi);
+ return 0;
+ }
+#endif // (_WIN32_IE >= 0x0500) && !defined(_WIN32_WCE)
+#endif // !_ATL_NO_REBAR_SUPPORT
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// AtlCreateSimpleToolBar - helper for creating simple toolbars
+
+#ifndef _WIN32_WCE
+
+inline HWND AtlCreateSimpleToolBar(HWND hWndParent, UINT nResourceID, BOOL bInitialSeparator = FALSE,
+ DWORD dwStyle = ATL_SIMPLE_TOOLBAR_STYLE, UINT nID = ATL_IDW_TOOLBAR)
+{
+ return CFrameWindowImplBase<>::CreateSimpleToolBarCtrl(hWndParent, nResourceID, bInitialSeparator, dwStyle, nID);
+}
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMDIWindow
+
+#ifndef _WIN32_WCE
+
+#ifndef _WTL_MDIWINDOWMENU_TEXT
+#define _WTL_MDIWINDOWMENU_TEXT _T("&Window")
+#endif
+
+class CMDIWindow : public ATL::CWindow
+{
+public:
+// Data members
+ HWND m_hWndMDIClient;
+ HMENU m_hMenu;
+
+// Constructors
+ CMDIWindow(HWND hWnd = NULL) : ATL::CWindow(hWnd), m_hWndMDIClient(NULL), m_hMenu(NULL)
+ { }
+
+ CMDIWindow& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// Operations
+ HWND MDIGetActive(BOOL* lpbMaximized = NULL)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ return (HWND)::SendMessage(m_hWndMDIClient, WM_MDIGETACTIVE, 0, (LPARAM)lpbMaximized);
+ }
+
+ void MDIActivate(HWND hWndChildToActivate)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ ATLASSERT(::IsWindow(hWndChildToActivate));
+ ::SendMessage(m_hWndMDIClient, WM_MDIACTIVATE, (WPARAM)hWndChildToActivate, 0);
+ }
+
+ void MDINext(HWND hWndChild, BOOL bPrevious = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ ATLASSERT(hWndChild == NULL || ::IsWindow(hWndChild));
+ ::SendMessage(m_hWndMDIClient, WM_MDINEXT, (WPARAM)hWndChild, (LPARAM)bPrevious);
+ }
+
+ void MDIMaximize(HWND hWndChildToMaximize)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ ATLASSERT(::IsWindow(hWndChildToMaximize));
+ ::SendMessage(m_hWndMDIClient, WM_MDIMAXIMIZE, (WPARAM)hWndChildToMaximize, 0);
+ }
+
+ void MDIRestore(HWND hWndChildToRestore)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ ATLASSERT(::IsWindow(hWndChildToRestore));
+ ::SendMessage(m_hWndMDIClient, WM_MDIRESTORE, (WPARAM)hWndChildToRestore, 0);
+ }
+
+ void MDIDestroy(HWND hWndChildToDestroy)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ ATLASSERT(::IsWindow(hWndChildToDestroy));
+ ::SendMessage(m_hWndMDIClient, WM_MDIDESTROY, (WPARAM)hWndChildToDestroy, 0);
+ }
+
+ BOOL MDICascade(UINT uFlags = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ return (BOOL)::SendMessage(m_hWndMDIClient, WM_MDICASCADE, (WPARAM)uFlags, 0);
+ }
+
+ BOOL MDITile(UINT uFlags = MDITILE_HORIZONTAL)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ return (BOOL)::SendMessage(m_hWndMDIClient, WM_MDITILE, (WPARAM)uFlags, 0);
+ }
+
+ void MDIIconArrange()
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ ::SendMessage(m_hWndMDIClient, WM_MDIICONARRANGE, 0, 0);
+ }
+
+ HMENU MDISetMenu(HMENU hMenuFrame, HMENU hMenuWindow)
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ return (HMENU)::SendMessage(m_hWndMDIClient, WM_MDISETMENU, (WPARAM)hMenuFrame, (LPARAM)hMenuWindow);
+ }
+
+ HMENU MDIRefreshMenu()
+ {
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+ return (HMENU)::SendMessage(m_hWndMDIClient, WM_MDIREFRESHMENU, 0, 0);
+ }
+
+// Additional operations
+ static HMENU GetStandardWindowMenu(HMENU hMenu)
+ {
+ int nCount = ::GetMenuItemCount(hMenu);
+ if(nCount == -1)
+ return NULL;
+ int nLen = ::GetMenuString(hMenu, nCount - 2, NULL, 0, MF_BYPOSITION);
+ if(nLen == 0)
+ return NULL;
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpszText = buff.Allocate(nLen + 1);
+ if(lpszText == NULL)
+ return NULL;
+ if(::GetMenuString(hMenu, nCount - 2, lpszText, nLen + 1, MF_BYPOSITION) != nLen)
+ return NULL;
+ if(lstrcmp(lpszText, _WTL_MDIWINDOWMENU_TEXT) != 0)
+ return NULL;
+ return ::GetSubMenu(hMenu, nCount - 2);
+ }
+
+ void SetMDIFrameMenu()
+ {
+ HMENU hWindowMenu = GetStandardWindowMenu(m_hMenu);
+ MDISetMenu(m_hMenu, hWindowMenu);
+ MDIRefreshMenu();
+ ::DrawMenuBar(GetMDIFrame());
+ }
+
+ HWND GetMDIFrame() const
+ {
+ return ::GetParent(m_hWndMDIClient);
+ }
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMDIFrameWindowImpl
+
+#ifndef _WIN32_WCE
+
+// MDI child command chaining macro (only for MDI frame windows)
+#define CHAIN_MDI_CHILD_COMMANDS() \
+ if(uMsg == WM_COMMAND) \
+ { \
+ HWND hWndChild = MDIGetActive(); \
+ if(hWndChild != NULL) \
+ ::SendMessage(hWndChild, uMsg, wParam, lParam); \
+ }
+
+template <class T, class TBase = CMDIWindow, class TWinTraits = ATL::CFrameWinTraits>
+class ATL_NO_VTABLE CMDIFrameWindowImpl : public CFrameWindowImplBase<TBase, TWinTraits >
+{
+public:
+ HWND Create(HWND hWndParent = NULL, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ HMENU hMenu = NULL, LPVOID lpCreateParam = NULL)
+ {
+ m_hMenu = hMenu;
+ ATOM atom = T::GetWndClassInfo().Register(&m_pfnSuperWindowProc);
+
+ dwStyle = T::GetWndStyle(dwStyle);
+ dwExStyle = T::GetWndExStyle(dwExStyle);
+
+ if(rect.m_lpRect == NULL)
+ rect.m_lpRect = &TBase::rcDefault;
+
+ return CFrameWindowImplBase<TBase, TWinTraits >::Create(hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, hMenu, atom, lpCreateParam);
+ }
+
+ HWND CreateEx(HWND hWndParent = NULL, ATL::_U_RECT rect = NULL, DWORD dwStyle = 0, DWORD dwExStyle = 0, LPVOID lpCreateParam = NULL)
+ {
+ const int cchName = 256;
+ TCHAR szWindowName[cchName];
+ szWindowName[0] = 0;
+ ::LoadString(ModuleHelper::GetResourceInstance(), T::GetWndClassInfo().m_uCommonResourceID, szWindowName, cchName);
+ HMENU hMenu = ::LoadMenu(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(T::GetWndClassInfo().m_uCommonResourceID));
+
+ T* pT = static_cast<T*>(this);
+ HWND hWnd = pT->Create(hWndParent, rect, szWindowName, dwStyle, dwExStyle, hMenu, lpCreateParam);
+
+ if(hWnd != NULL)
+ m_hAccel = ::LoadAccelerators(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(T::GetWndClassInfo().m_uCommonResourceID));
+
+ return hWnd;
+ }
+
+ BOOL CreateSimpleToolBar(UINT nResourceID = 0, DWORD dwStyle = ATL_SIMPLE_TOOLBAR_STYLE, UINT nID = ATL_IDW_TOOLBAR)
+ {
+ ATLASSERT(!::IsWindow(m_hWndToolBar));
+ if(nResourceID == 0)
+ nResourceID = T::GetWndClassInfo().m_uCommonResourceID;
+ m_hWndToolBar = T::CreateSimpleToolBarCtrl(m_hWnd, nResourceID, TRUE, dwStyle, nID);
+ return (m_hWndToolBar != NULL);
+ }
+
+ virtual WNDPROC GetWindowProc()
+ {
+ return MDIFrameWindowProc;
+ }
+
+ static LRESULT CALLBACK MDIFrameWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
+ {
+ CMDIFrameWindowImpl< T, TBase, TWinTraits >* pThis = (CMDIFrameWindowImpl< T, TBase, TWinTraits >*)hWnd;
+ // set a ptr to this message and save the old value
+#if (_ATL_VER >= 0x0700)
+ ATL::_ATL_MSG msg(pThis->m_hWnd, uMsg, wParam, lParam);
+ const ATL::_ATL_MSG* pOldMsg = pThis->m_pCurrentMsg;
+#else // !(_ATL_VER >= 0x0700)
+ MSG msg = { pThis->m_hWnd, uMsg, wParam, lParam, 0, { 0, 0 } };
+ const MSG* pOldMsg = pThis->m_pCurrentMsg;
+#endif // !(_ATL_VER >= 0x0700)
+ pThis->m_pCurrentMsg = &msg;
+ // pass to the message map to process
+ LRESULT lRes = 0;
+ BOOL bRet = pThis->ProcessWindowMessage(pThis->m_hWnd, uMsg, wParam, lParam, lRes, 0);
+ // restore saved value for the current message
+ ATLASSERT(pThis->m_pCurrentMsg == &msg);
+ pThis->m_pCurrentMsg = pOldMsg;
+ // do the default processing if message was not handled
+ if(!bRet)
+ {
+ if(uMsg != WM_NCDESTROY)
+ lRes = pThis->DefWindowProc(uMsg, wParam, lParam);
+ else
+ {
+ // unsubclass, if needed
+ LONG_PTR pfnWndProc = ::GetWindowLongPtr(pThis->m_hWnd, GWLP_WNDPROC);
+ lRes = pThis->DefWindowProc(uMsg, wParam, lParam);
+ if(pThis->m_pfnSuperWindowProc != ::DefWindowProc && ::GetWindowLongPtr(pThis->m_hWnd, GWLP_WNDPROC) == pfnWndProc)
+ ::SetWindowLongPtr(pThis->m_hWnd, GWLP_WNDPROC, (LONG_PTR)pThis->m_pfnSuperWindowProc);
+#if (_ATL_VER >= 0x0700)
+ // mark window as destryed
+ pThis->m_dwState |= WINSTATE_DESTROYED;
+#else // !(_ATL_VER >= 0x0700)
+ // clear out window handle
+ HWND hWnd = pThis->m_hWnd;
+ pThis->m_hWnd = NULL;
+ // clean up after window is destroyed
+ pThis->OnFinalMessage(hWnd);
+#endif // !(_ATL_VER >= 0x0700)
+ }
+ }
+#if (_ATL_VER >= 0x0700)
+ if(pThis->m_dwState & WINSTATE_DESTROYED && pThis->m_pCurrentMsg == NULL)
+ {
+ // clear out window handle
+ HWND hWnd = pThis->m_hWnd;
+ pThis->m_hWnd = NULL;
+ pThis->m_dwState &= ~WINSTATE_DESTROYED;
+ // clean up after window is destroyed
+ pThis->OnFinalMessage(hWnd);
+ }
+#endif // (_ATL_VER >= 0x0700)
+ return lRes;
+ }
+
+ // Overriden to call DefWindowProc which uses DefFrameProc
+ LRESULT DefWindowProc()
+ {
+ const MSG* pMsg = m_pCurrentMsg;
+ LRESULT lRes = 0;
+ if (pMsg != NULL)
+ lRes = DefWindowProc(pMsg->message, pMsg->wParam, pMsg->lParam);
+ return lRes;
+ }
+
+ LRESULT DefWindowProc(UINT uMsg, WPARAM wParam, LPARAM lParam)
+ {
+ return ::DefFrameProc(m_hWnd, m_hWndMDIClient, uMsg, wParam, lParam);
+ }
+
+ BOOL PreTranslateMessage(MSG* pMsg)
+ {
+ if(CFrameWindowImplBase<TBase, TWinTraits>::PreTranslateMessage(pMsg))
+ return TRUE;
+ return ::TranslateMDISysAccel(m_hWndMDIClient, pMsg);
+ }
+
+ HWND CreateMDIClient(HMENU hWindowMenu = NULL, UINT nID = ATL_IDW_CLIENT, UINT nFirstChildID = ATL_IDM_FIRST_MDICHILD)
+ {
+ DWORD dwStyle = WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | MDIS_ALLCHILDSTYLES;
+ DWORD dwExStyle = WS_EX_CLIENTEDGE;
+
+ CLIENTCREATESTRUCT ccs = { 0 };
+ ccs.hWindowMenu = hWindowMenu;
+ ccs.idFirstChild = nFirstChildID;
+
+ if((GetStyle() & (WS_HSCROLL | WS_VSCROLL)) != 0)
+ {
+ // parent MDI frame's scroll styles move to the MDICLIENT
+ dwStyle |= (GetStyle() & (WS_HSCROLL | WS_VSCROLL));
+
+ // fast way to turn off the scrollbar bits (without a resize)
+ ModifyStyle(WS_HSCROLL | WS_VSCROLL, 0, SWP_NOREDRAW | SWP_FRAMECHANGED);
+ }
+
+ // Create MDICLIENT window
+ m_hWndClient = ::CreateWindowEx(dwExStyle, _T("MDIClient"), NULL,
+ dwStyle, 0, 0, 1, 1, m_hWnd, (HMENU)LongToHandle(nID),
+ ModuleHelper::GetModuleInstance(), (LPVOID)&ccs);
+ if (m_hWndClient == NULL)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("MDI Frame failed to create MDICLIENT.\n"));
+ return NULL;
+ }
+
+ // Move it to the top of z-order
+ ::BringWindowToTop(m_hWndClient);
+
+ // set as MDI client window
+ m_hWndMDIClient = m_hWndClient;
+
+ // update to proper size
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+
+ return m_hWndClient;
+ }
+
+ typedef CFrameWindowImplBase<TBase, TWinTraits > _baseClass;
+
+ BEGIN_MSG_MAP(CMDIFrameWindowImpl)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
+ MESSAGE_HANDLER(WM_MDISETMENU, OnMDISetMenu)
+#ifndef _ATL_NO_REBAR_SUPPORT
+#if (_WIN32_IE >= 0x0400)
+ NOTIFY_CODE_HANDLER(RBN_AUTOSIZE, OnReBarAutoSize)
+#endif // (_WIN32_IE >= 0x0400)
+#if (_WIN32_IE >= 0x0500)
+ NOTIFY_CODE_HANDLER(RBN_CHEVRONPUSHED, OnChevronPushed)
+#endif // (_WIN32_IE >= 0x0500)
+#endif // !_ATL_NO_REBAR_SUPPORT
+ CHAIN_MSG_MAP(_baseClass)
+ END_MSG_MAP()
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(wParam != SIZE_MINIMIZED)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+ }
+ // message must be handled, otherwise DefFrameProc would resize the client again
+ return 0;
+ }
+
+ LRESULT OnSetFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ // don't allow CFrameWindowImplBase to handle this one
+ return DefWindowProc(uMsg, wParam, lParam);
+ }
+
+ LRESULT OnMDISetMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ SetMDIFrameMenu();
+ return 0;
+ }
+
+#ifndef _ATL_NO_REBAR_SUPPORT
+#if (_WIN32_IE >= 0x0400)
+ LRESULT OnReBarAutoSize(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout(FALSE);
+ return 0;
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500)
+ LRESULT OnChevronPushed(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ _ChevronMenuInfo cmi = { NULL, (LPNMREBARCHEVRON)pnmh, false };
+ if(!pT->PrepareChevronMenu(cmi))
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+ // display a popup menu with hidden items
+ pT->DisplayChevronMenu(cmi);
+ // cleanup
+ pT->CleanupChevronMenu(cmi);
+ return 0;
+ }
+#endif // (_WIN32_IE >= 0x0500)
+#endif // !_ATL_NO_REBAR_SUPPORT
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMDIChildWindowImpl
+
+#ifndef _WIN32_WCE
+
+template <class T, class TBase = CMDIWindow, class TWinTraits = ATL::CMDIChildWinTraits>
+class ATL_NO_VTABLE CMDIChildWindowImpl : public CFrameWindowImplBase<TBase, TWinTraits >
+{
+public:
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ UINT nMenuID = 0, LPVOID lpCreateParam = NULL)
+ {
+ ATOM atom = T::GetWndClassInfo().Register(&m_pfnSuperWindowProc);
+
+ if(nMenuID != 0)
+ m_hMenu = ::LoadMenu(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(nMenuID));
+
+ dwStyle = T::GetWndStyle(dwStyle);
+ dwExStyle = T::GetWndExStyle(dwExStyle);
+
+ dwExStyle |= WS_EX_MDICHILD; // force this one
+ m_pfnSuperWindowProc = ::DefMDIChildProc;
+ m_hWndMDIClient = hWndParent;
+ ATLASSERT(::IsWindow(m_hWndMDIClient));
+
+ if(rect.m_lpRect == NULL)
+ rect.m_lpRect = &TBase::rcDefault;
+
+ // If the currently active MDI child is maximized, we want to create this one maximized too
+ ATL::CWindow wndParent = hWndParent;
+ BOOL bMaximized = FALSE;
+ wndParent.SendMessage(WM_MDIGETACTIVE, 0, (LPARAM)&bMaximized);
+ if(bMaximized)
+ wndParent.SetRedraw(FALSE);
+
+ HWND hWnd = CFrameWindowImplBase<TBase, TWinTraits >::Create(hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, (UINT)0U, atom, lpCreateParam);
+
+ if(bMaximized)
+ {
+ // Maximize and redraw everything
+ if(hWnd != NULL)
+ MDIMaximize(hWnd);
+ wndParent.SetRedraw(TRUE);
+ wndParent.RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN);
+ ::SetFocus(GetMDIFrame()); // focus will be set back to this window
+ }
+ else if(hWnd != NULL && ::IsWindowVisible(m_hWnd) && !::IsChild(hWnd, ::GetFocus()))
+ {
+ ::SetFocus(hWnd);
+ }
+
+ return hWnd;
+ }
+
+ HWND CreateEx(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR lpcstrWindowName = NULL, DWORD dwStyle = 0, DWORD dwExStyle = 0, LPVOID lpCreateParam = NULL)
+ {
+ const int cchName = 256;
+ TCHAR szWindowName[cchName];
+ szWindowName[0] = 0;
+ if(lpcstrWindowName == NULL)
+ {
+ ::LoadString(ModuleHelper::GetResourceInstance(), T::GetWndClassInfo().m_uCommonResourceID, szWindowName, cchName);
+ lpcstrWindowName = szWindowName;
+ }
+
+ T* pT = static_cast<T*>(this);
+ HWND hWnd = pT->Create(hWndParent, rect, lpcstrWindowName, dwStyle, dwExStyle, T::GetWndClassInfo().m_uCommonResourceID, lpCreateParam);
+
+ if(hWnd != NULL)
+ m_hAccel = ::LoadAccelerators(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(T::GetWndClassInfo().m_uCommonResourceID));
+
+ return hWnd;
+ }
+
+ BOOL CreateSimpleToolBar(UINT nResourceID = 0, DWORD dwStyle = ATL_SIMPLE_TOOLBAR_STYLE, UINT nID = ATL_IDW_TOOLBAR)
+ {
+ ATLASSERT(!::IsWindow(m_hWndToolBar));
+ if(nResourceID == 0)
+ nResourceID = T::GetWndClassInfo().m_uCommonResourceID;
+ m_hWndToolBar = T::CreateSimpleToolBarCtrl(m_hWnd, nResourceID, TRUE, dwStyle, nID);
+ return (m_hWndToolBar != NULL);
+ }
+
+ BOOL UpdateClientEdge(LPRECT lpRect = NULL)
+ {
+ // only adjust for active MDI child window
+ HWND hWndChild = MDIGetActive();
+ if(hWndChild != NULL && hWndChild != m_hWnd)
+ return FALSE;
+
+ // need to adjust the client edge style as max/restore happens
+ DWORD dwStyle = ::GetWindowLong(m_hWndMDIClient, GWL_EXSTYLE);
+ DWORD dwNewStyle = dwStyle;
+ if(hWndChild != NULL && ((GetExStyle() & WS_EX_CLIENTEDGE) == 0) && ((GetStyle() & WS_MAXIMIZE) != 0))
+ dwNewStyle &= ~(WS_EX_CLIENTEDGE);
+ else
+ dwNewStyle |= WS_EX_CLIENTEDGE;
+
+ if(dwStyle != dwNewStyle)
+ {
+ // SetWindowPos will not move invalid bits
+ ::RedrawWindow(m_hWndMDIClient, NULL, NULL,
+ RDW_INVALIDATE | RDW_ALLCHILDREN);
+ // remove/add WS_EX_CLIENTEDGE to MDI client area
+ ::SetWindowLong(m_hWndMDIClient, GWL_EXSTYLE, dwNewStyle);
+ ::SetWindowPos(m_hWndMDIClient, NULL, 0, 0, 0, 0,
+ SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE |
+ SWP_NOZORDER | SWP_NOCOPYBITS);
+
+ // return new client area
+ if (lpRect != NULL)
+ ::GetClientRect(m_hWndMDIClient, lpRect);
+
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ typedef CFrameWindowImplBase<TBase, TWinTraits > _baseClass;
+ BEGIN_MSG_MAP(CMDIChildWindowImpl)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ MESSAGE_HANDLER(WM_WINDOWPOSCHANGED, OnWindowPosChanged)
+ MESSAGE_HANDLER(WM_MOUSEACTIVATE, OnMouseActivate)
+ MESSAGE_HANDLER(WM_MENUSELECT, OnMenuSelect)
+ MESSAGE_HANDLER(WM_MDIACTIVATE, OnMDIActivate)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+#ifndef _ATL_NO_REBAR_SUPPORT
+#if (_WIN32_IE >= 0x0400)
+ NOTIFY_CODE_HANDLER(RBN_AUTOSIZE, OnReBarAutoSize)
+#endif // (_WIN32_IE >= 0x0400)
+#if (_WIN32_IE >= 0x0500)
+ NOTIFY_CODE_HANDLER(RBN_CHEVRONPUSHED, OnChevronPushed)
+#endif // (_WIN32_IE >= 0x0500)
+#endif // !_ATL_NO_REBAR_SUPPORT
+ CHAIN_MSG_MAP(_baseClass)
+ END_MSG_MAP()
+
+ LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ DefWindowProc(uMsg, wParam, lParam); // needed for MDI children
+ if(wParam != SIZE_MINIMIZED)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+ }
+ return 0;
+ }
+
+ LRESULT OnWindowPosChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ // update MDI client edge and adjust MDI child rect
+ LPWINDOWPOS lpWndPos = (LPWINDOWPOS)lParam;
+
+ if(!(lpWndPos->flags & SWP_NOSIZE))
+ {
+ RECT rectClient;
+ if(UpdateClientEdge(&rectClient) && ((GetStyle() & WS_MAXIMIZE) != 0))
+ {
+ ::AdjustWindowRectEx(&rectClient, GetStyle(), FALSE, GetExStyle());
+ lpWndPos->x = rectClient.left;
+ lpWndPos->y = rectClient.top;
+ lpWndPos->cx = rectClient.right - rectClient.left;
+ lpWndPos->cy = rectClient.bottom - rectClient.top;
+ }
+ }
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnMouseActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ LRESULT lRes = DefWindowProc(uMsg, wParam, lParam);
+
+ // Activate this MDI window if needed
+ if(lRes == MA_ACTIVATE || lRes == MA_ACTIVATEANDEAT)
+ {
+ if(MDIGetActive() != m_hWnd)
+ MDIActivate(m_hWnd);
+ }
+
+ return lRes;
+ }
+
+ LRESULT OnMenuSelect(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ return ::SendMessage(GetMDIFrame(), uMsg, wParam, lParam);
+ }
+
+ LRESULT OnMDIActivate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if((HWND)lParam == m_hWnd && m_hMenu != NULL)
+ SetMDIFrameMenu();
+ else if((HWND)lParam == NULL)
+ ::SendMessage(GetMDIFrame(), WM_MDISETMENU, 0, 0);
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_hMenu != NULL)
+ {
+ ::DestroyMenu(m_hMenu);
+ m_hMenu = NULL;
+ }
+ UpdateClientEdge();
+ bHandled = FALSE;
+ return 1;
+ }
+
+#ifndef _ATL_NO_REBAR_SUPPORT
+#if (_WIN32_IE >= 0x0400)
+ LRESULT OnReBarAutoSize(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout(FALSE);
+ return 0;
+ }
+#endif // (_WIN32_IE >= 0x0400)
+
+#if (_WIN32_IE >= 0x0500)
+ LRESULT OnChevronPushed(int /*idCtrl*/, LPNMHDR pnmh, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ _ChevronMenuInfo cmi = { NULL, (LPNMREBARCHEVRON)pnmh, false };
+ if(!pT->PrepareChevronMenu(cmi))
+ {
+ bHandled = FALSE;
+ return 1;
+ }
+ // display a popup menu with hidden items
+ pT->DisplayChevronMenu(cmi);
+ // cleanup
+ pT->CleanupChevronMenu(cmi);
+ return 0;
+ }
+#endif // (_WIN32_IE >= 0x0500)
+#endif // !_ATL_NO_REBAR_SUPPORT
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// COwnerDraw - MI class for owner-draw support
+
+template <class T>
+class COwnerDraw
+{
+public:
+#if (_ATL_VER < 0x0700)
+ BOOL m_bHandledOD;
+
+ BOOL IsMsgHandled() const
+ {
+ return m_bHandledOD;
+ }
+ void SetMsgHandled(BOOL bHandled)
+ {
+ m_bHandledOD = bHandled;
+ }
+#endif // (_ATL_VER < 0x0700)
+
+// Message map and handlers
+ BEGIN_MSG_MAP(COwnerDraw< T >)
+ MESSAGE_HANDLER(WM_DRAWITEM, OnDrawItem)
+ MESSAGE_HANDLER(WM_MEASUREITEM, OnMeasureItem)
+ MESSAGE_HANDLER(WM_COMPAREITEM, OnCompareItem)
+ MESSAGE_HANDLER(WM_DELETEITEM, OnDeleteItem)
+ ALT_MSG_MAP(1)
+ MESSAGE_HANDLER(OCM_DRAWITEM, OnDrawItem)
+ MESSAGE_HANDLER(OCM_MEASUREITEM, OnMeasureItem)
+ MESSAGE_HANDLER(OCM_COMPAREITEM, OnCompareItem)
+ MESSAGE_HANDLER(OCM_DELETEITEM, OnDeleteItem)
+ END_MSG_MAP()
+
+ LRESULT OnDrawItem(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetMsgHandled(TRUE);
+ pT->DrawItem((LPDRAWITEMSTRUCT)lParam);
+ bHandled = pT->IsMsgHandled();
+ return (LRESULT)TRUE;
+ }
+
+ LRESULT OnMeasureItem(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetMsgHandled(TRUE);
+ pT->MeasureItem((LPMEASUREITEMSTRUCT)lParam);
+ bHandled = pT->IsMsgHandled();
+ return (LRESULT)TRUE;
+ }
+
+ LRESULT OnCompareItem(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetMsgHandled(TRUE);
+ bHandled = pT->IsMsgHandled();
+ return (LRESULT)pT->CompareItem((LPCOMPAREITEMSTRUCT)lParam);
+ }
+
+ LRESULT OnDeleteItem(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetMsgHandled(TRUE);
+ pT->DeleteItem((LPDELETEITEMSTRUCT)lParam);
+ bHandled = pT->IsMsgHandled();
+ return (LRESULT)TRUE;
+ }
+
+// Overrideables
+ void DrawItem(LPDRAWITEMSTRUCT /*lpDrawItemStruct*/)
+ {
+ // must be implemented
+ ATLASSERT(FALSE);
+ }
+
+ void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct)
+ {
+ if(lpMeasureItemStruct->CtlType != ODT_MENU)
+ {
+ // return default height for a system font
+ T* pT = static_cast<T*>(this);
+ HWND hWnd = pT->GetDlgItem(lpMeasureItemStruct->CtlID);
+ CClientDC dc(hWnd);
+ TEXTMETRIC tm = { 0 };
+ dc.GetTextMetrics(&tm);
+
+ lpMeasureItemStruct->itemHeight = tm.tmHeight;
+ }
+ else
+ lpMeasureItemStruct->itemHeight = ::GetSystemMetrics(SM_CYMENU);
+ }
+
+ int CompareItem(LPCOMPAREITEMSTRUCT /*lpCompareItemStruct*/)
+ {
+ // all items are equal
+ return 0;
+ }
+
+ void DeleteItem(LPDELETEITEMSTRUCT /*lpDeleteItemStruct*/)
+ {
+ // default - nothing
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Update UI macros
+
+// these build the Update UI map inside a class definition
+#define BEGIN_UPDATE_UI_MAP(thisClass) \
+ static const CUpdateUIBase::_AtlUpdateUIMap* GetUpdateUIMap() \
+ { \
+ static const _AtlUpdateUIMap theMap[] = \
+ {
+
+#define UPDATE_ELEMENT(nID, wType) \
+ { nID, wType },
+
+#define END_UPDATE_UI_MAP() \
+ { (WORD)-1, 0 } \
+ }; \
+ return theMap; \
+ }
+
+///////////////////////////////////////////////////////////////////////////////
+// CUpdateUI - manages UI elements updating
+
+class CUpdateUIBase
+{
+public:
+ // constants
+ enum
+ {
+ // UI element type
+ UPDUI_MENUPOPUP = 0x0001,
+ UPDUI_MENUBAR = 0x0002,
+ UPDUI_CHILDWINDOW = 0x0004,
+ UPDUI_TOOLBAR = 0x0008,
+ UPDUI_STATUSBAR = 0x0010,
+ // state
+ UPDUI_ENABLED = 0x0000,
+ UPDUI_DISABLED = 0x0100,
+ UPDUI_CHECKED = 0x0200,
+ UPDUI_CHECKED2 = 0x0400,
+ UPDUI_RADIO = 0x0800,
+ UPDUI_DEFAULT = 0x1000,
+ UPDUI_TEXT = 0x2000,
+ // internal state
+ UPDUI_CLEARDEFAULT = 0x4000,
+ };
+
+ // element data
+ struct _AtlUpdateUIElement
+ {
+ HWND m_hWnd;
+ WORD m_wType;
+
+ bool operator ==(const _AtlUpdateUIElement& e) const
+ { return (m_hWnd == e.m_hWnd && m_wType == e.m_wType); }
+ };
+
+ // map data
+ struct _AtlUpdateUIMap
+ {
+ WORD m_nID;
+ WORD m_wType;
+
+ bool operator ==(const _AtlUpdateUIMap& e) const
+ { return (m_nID == e.m_nID && m_wType == e.m_wType); }
+ };
+
+ // instance data
+ struct _AtlUpdateUIData
+ {
+ WORD m_wState;
+ union
+ {
+ void* m_lpData;
+ LPTSTR m_lpstrText;
+ struct
+ {
+ WORD m_nIDFirst;
+ WORD m_nIDLast;
+ };
+ };
+
+ bool operator ==(const _AtlUpdateUIData& e) const
+ { return (m_wState == e.m_wState && m_lpData == e.m_lpData); }
+ };
+
+ ATL::CSimpleArray<_AtlUpdateUIElement> m_UIElements; // elements data
+ const _AtlUpdateUIMap* m_pUIMap; // static UI data
+ _AtlUpdateUIData* m_pUIData; // instance UI data
+ WORD m_wDirtyType; // global dirty flag
+
+ bool m_bBlockAccelerators;
+
+
+// Constructor, destructor
+ CUpdateUIBase() : m_pUIMap(NULL), m_pUIData(NULL), m_wDirtyType(0), m_bBlockAccelerators(false)
+ { }
+
+ ~CUpdateUIBase()
+ {
+ if(m_pUIMap != NULL && m_pUIData != NULL)
+ {
+ const _AtlUpdateUIMap* pUIMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ while(pUIMap->m_nID != (WORD)-1)
+ {
+ if(pUIData->m_wState & UPDUI_TEXT)
+ delete [] pUIData->m_lpstrText;
+ pUIMap++;
+ pUIData++;
+ }
+ delete [] m_pUIData;
+ }
+ }
+
+// Check for disabled commands
+ bool UIGetBlockAccelerators() const
+ {
+ return m_bBlockAccelerators;
+ }
+
+ bool UISetBlockAccelerators(bool bBlock)
+ {
+ bool bOld = m_bBlockAccelerators;
+ m_bBlockAccelerators = bBlock;
+ return bOld;
+ }
+
+// Add elements
+ BOOL UIAddMenuBar(HWND hWnd) // menu bar (main menu)
+ {
+ if(hWnd == NULL)
+ return FALSE;
+ _AtlUpdateUIElement e;
+ e.m_hWnd = hWnd;
+ e.m_wType = UPDUI_MENUBAR;
+ return m_UIElements.Add(e);
+ }
+
+ BOOL UIAddToolBar(HWND hWnd) // toolbar
+ {
+ if(hWnd == NULL)
+ return FALSE;
+ _AtlUpdateUIElement e;
+ e.m_hWnd = hWnd;
+ e.m_wType = UPDUI_TOOLBAR;
+ return m_UIElements.Add(e);
+ }
+
+ BOOL UIAddStatusBar(HWND hWnd) // status bar
+ {
+ if(hWnd == NULL)
+ return FALSE;
+ _AtlUpdateUIElement e;
+ e.m_hWnd = hWnd;
+ e.m_wType = UPDUI_STATUSBAR;
+ return m_UIElements.Add(e);
+ }
+
+ BOOL UIAddChildWindowContainer(HWND hWnd) // child window
+ {
+ if(hWnd == NULL)
+ return FALSE;
+ _AtlUpdateUIElement e;
+ e.m_hWnd = hWnd;
+ e.m_wType = UPDUI_CHILDWINDOW;
+ return m_UIElements.Add(e);
+ }
+
+// Message map for popup menu updates and accelerator blocking
+ BEGIN_MSG_MAP(CUpdateUIBase)
+ MESSAGE_HANDLER(WM_INITMENUPOPUP, OnInitMenuPopup)
+ MESSAGE_HANDLER(WM_COMMAND, OnCommand)
+ END_MSG_MAP()
+
+ LRESULT OnInitMenuPopup(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ bHandled = FALSE;
+ HMENU hMenu = (HMENU)wParam;
+ if(hMenu == NULL)
+ return 1;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return 1;
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ while(pMap->m_nID != (WORD)-1)
+ {
+ if(pMap->m_wType & UPDUI_MENUPOPUP)
+ {
+ UIUpdateMenuBarElement(pMap->m_nID, pUIData, hMenu);
+
+ if((pUIData->m_wState & UPDUI_RADIO) != 0)
+ ::CheckMenuRadioItem(hMenu, pUIData->m_nIDFirst, pUIData->m_nIDLast, pMap->m_nID, MF_BYCOMMAND);
+ }
+ pMap++;
+ pUIData++;
+ }
+ return 0;
+ }
+
+ LRESULT OnCommand(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ bHandled = FALSE;
+ if(m_bBlockAccelerators && HIWORD(wParam) == 1) // accelerators only
+ {
+ int nID = LOWORD(wParam);
+ if((UIGetState(nID) & UPDUI_DISABLED) == UPDUI_DISABLED)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("CUpdateUIBase::OnCommand - blocked disabled command 0x%4.4X\n"), nID);
+ bHandled = TRUE; // eat the command, UI item is disabled
+ }
+ }
+ return 0;
+ }
+
+// methods for setting UI element state
+ BOOL UIEnable(int nID, BOOL bEnable, BOOL bForceUpdate = FALSE)
+ {
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ for( ; pMap->m_nID != (WORD)-1; pMap++, pUIData++)
+ {
+ if(nID == (int)pMap->m_nID)
+ {
+ if(bEnable)
+ {
+ if(pUIData->m_wState & UPDUI_DISABLED)
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState &= ~UPDUI_DISABLED;
+ }
+ }
+ else
+ {
+ if(!(pUIData->m_wState & UPDUI_DISABLED))
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState |= UPDUI_DISABLED;
+ }
+ }
+
+ if(bForceUpdate)
+ pUIData->m_wState |= pMap->m_wType;
+ if(pUIData->m_wState & pMap->m_wType)
+ m_wDirtyType |= pMap->m_wType;
+
+ break; // found
+ }
+ }
+
+ return TRUE;
+ }
+
+ BOOL UISetCheck(int nID, int nCheck, BOOL bForceUpdate = FALSE)
+ {
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ for( ; pMap->m_nID != (WORD)-1; pMap++, pUIData++)
+ {
+ if(nID == (int)pMap->m_nID)
+ {
+ switch(nCheck)
+ {
+ case 0:
+ if((pUIData->m_wState & UPDUI_CHECKED) || (pUIData->m_wState & UPDUI_CHECKED2))
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState &= ~(UPDUI_CHECKED | UPDUI_CHECKED2);
+ }
+ break;
+ case 1:
+ if(!(pUIData->m_wState & UPDUI_CHECKED))
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState &= ~UPDUI_CHECKED2;
+ pUIData->m_wState |= UPDUI_CHECKED;
+ }
+ break;
+ case 2:
+ if(!(pUIData->m_wState & UPDUI_CHECKED2))
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState &= ~UPDUI_CHECKED;
+ pUIData->m_wState |= UPDUI_CHECKED2;
+ }
+ break;
+ }
+
+ if(bForceUpdate)
+ pUIData->m_wState |= pMap->m_wType;
+ if(pUIData->m_wState & pMap->m_wType)
+ m_wDirtyType |= pMap->m_wType;
+
+ break; // found
+ }
+ }
+
+ return TRUE;
+ }
+
+ // variant that supports bool (checked/not-checked, no intermediate state)
+ BOOL UISetCheck(int nID, bool bCheck, BOOL bForceUpdate = FALSE)
+ {
+ return UISetCheck(nID, bCheck ? 1 : 0, bForceUpdate);
+ }
+
+ BOOL UISetRadio(int nID, BOOL bRadio, BOOL bForceUpdate = FALSE)
+ {
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ for( ; pMap->m_nID != (WORD)-1; pMap++, pUIData++)
+ {
+ if(nID == (int)pMap->m_nID)
+ {
+ if(bRadio)
+ {
+ if(!(pUIData->m_wState & UPDUI_RADIO))
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState |= UPDUI_RADIO;
+ }
+ }
+ else
+ {
+ if(pUIData->m_wState & UPDUI_RADIO)
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState &= ~UPDUI_RADIO;
+ }
+ }
+
+ if(bForceUpdate)
+ pUIData->m_wState |= pMap->m_wType;
+ if(pUIData->m_wState & pMap->m_wType)
+ m_wDirtyType |= pMap->m_wType;
+
+ break; // found
+ }
+ }
+
+ return TRUE;
+ }
+
+ // for menu items
+ BOOL UISetRadioMenuItem(int nID, int nIDFirst, int nIDLast, BOOL bForceUpdate = FALSE)
+ {
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ for( ; pMap->m_nID != (WORD)-1; pMap++, pUIData++)
+ {
+ if(nID == (int)pMap->m_nID)
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState |= UPDUI_RADIO;
+ pUIData->m_nIDFirst = (WORD)nIDFirst;
+ pUIData->m_nIDLast = (WORD)nIDLast;
+
+ if(bForceUpdate)
+ pUIData->m_wState |= pMap->m_wType;
+ if(pUIData->m_wState & pMap->m_wType)
+ m_wDirtyType |= pMap->m_wType;
+ }
+ else if(pMap->m_nID >= nIDFirst && pMap->m_nID <= nIDLast)
+ {
+ if(pUIData->m_wState & UPDUI_RADIO)
+ {
+ pUIData->m_wState &= ~pMap->m_wType;
+ pUIData->m_wState &= ~UPDUI_RADIO;
+ pUIData->m_nIDFirst = 0;
+ pUIData->m_nIDLast = 0;
+ }
+ }
+
+ if(pMap->m_nID == nIDLast)
+ break;
+ }
+
+ return TRUE;
+ }
+
+ BOOL UISetText(int nID, LPCTSTR lpstrText, BOOL bForceUpdate = FALSE)
+ {
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+ if(lpstrText == NULL)
+ lpstrText = _T("");
+
+ for( ; pMap->m_nID != (WORD)-1; pMap++, pUIData++)
+ {
+ if(nID == (int)pMap->m_nID)
+ {
+ if(pUIData->m_lpstrText == NULL || lstrcmp(pUIData->m_lpstrText, lpstrText))
+ {
+ delete [] pUIData->m_lpstrText;
+ pUIData->m_lpstrText = NULL;
+ int nStrLen = lstrlen(lpstrText);
+ ATLTRY(pUIData->m_lpstrText = new TCHAR[nStrLen + 1]);
+ if(pUIData->m_lpstrText == NULL)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("UISetText - memory allocation failed\n"));
+ break;
+ }
+ SecureHelper::strcpy_x(pUIData->m_lpstrText, nStrLen + 1, lpstrText);
+ pUIData->m_wState |= (UPDUI_TEXT | pMap->m_wType);
+ }
+
+ if(bForceUpdate)
+ pUIData->m_wState |= (UPDUI_TEXT | pMap->m_wType);
+ if(pUIData->m_wState & pMap->m_wType)
+ m_wDirtyType |= pMap->m_wType;
+
+ break; // found
+ }
+ }
+
+ return TRUE;
+ }
+
+ BOOL UISetDefault(int nID, BOOL bDefault, BOOL bForceUpdate = FALSE)
+ {
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ for( ; pMap->m_nID != (WORD)-1; pMap++, pUIData++)
+ {
+ if(nID == (int)pMap->m_nID)
+ {
+ if(bDefault)
+ {
+ if((pUIData->m_wState & UPDUI_DEFAULT) == 0)
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState |= UPDUI_DEFAULT;
+ }
+ }
+ else
+ {
+ if((pUIData->m_wState & UPDUI_DEFAULT) != 0)
+ {
+ pUIData->m_wState |= pMap->m_wType;
+ pUIData->m_wState &= ~UPDUI_DEFAULT;
+ pUIData->m_wState |= UPDUI_CLEARDEFAULT;
+ }
+ }
+
+ if(bForceUpdate)
+ pUIData->m_wState |= pMap->m_wType;
+ if(pUIData->m_wState & pMap->m_wType)
+ m_wDirtyType |= pMap->m_wType;
+
+ break; // found
+ }
+ }
+
+ return TRUE;
+ }
+
+// methods for complete state set/get
+ BOOL UISetState(int nID, DWORD dwState)
+ {
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+ for( ; pMap->m_nID != (WORD)-1; pMap++, pUIData++)
+ {
+ if(nID == (int)pMap->m_nID)
+ {
+ pUIData->m_wState = (WORD)(dwState | pMap->m_wType);
+ m_wDirtyType |= pMap->m_wType;
+ break; // found
+ }
+ }
+ return TRUE;
+ }
+
+ DWORD UIGetState(int nID)
+ {
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return 0;
+ for( ; pMap->m_nID != (WORD)-1; pMap++, pUIData++)
+ {
+ if(nID == (int)pMap->m_nID)
+ return pUIData->m_wState;
+ }
+ return 0;
+ }
+
+// methods for updating UI
+#ifndef _WIN32_WCE
+ BOOL UIUpdateMenuBar(BOOL bForceUpdate = FALSE, BOOL bMainMenu = FALSE)
+ {
+ if(!(m_wDirtyType & UPDUI_MENUBAR) && !bForceUpdate)
+ return TRUE;
+
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ while(pMap->m_nID != (WORD)-1)
+ {
+ for(int i = 0; i < m_UIElements.GetSize(); i++)
+ {
+ if(m_UIElements[i].m_wType == UPDUI_MENUBAR)
+ {
+ HMENU hMenu = ::GetMenu(m_UIElements[i].m_hWnd);
+ if(hMenu != NULL && (pUIData->m_wState & UPDUI_MENUBAR) && (pMap->m_wType & UPDUI_MENUBAR))
+ UIUpdateMenuBarElement(pMap->m_nID, pUIData, hMenu);
+ }
+ if(bMainMenu)
+ ::DrawMenuBar(m_UIElements[i].m_hWnd);
+ }
+ pMap++;
+ pUIData->m_wState &= ~UPDUI_MENUBAR;
+ if(pUIData->m_wState & UPDUI_TEXT)
+ {
+ delete [] pUIData->m_lpstrText;
+ pUIData->m_lpstrText = NULL;
+ pUIData->m_wState &= ~UPDUI_TEXT;
+ }
+ pUIData++;
+ }
+
+ m_wDirtyType &= ~UPDUI_MENUBAR;
+ return TRUE;
+ }
+#endif // !_WIN32_WCE
+
+ BOOL UIUpdateToolBar(BOOL bForceUpdate = FALSE)
+ {
+ if(!(m_wDirtyType & UPDUI_TOOLBAR) && !bForceUpdate)
+ return TRUE;
+
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ while(pMap->m_nID != (WORD)-1)
+ {
+ for(int i = 0; i < m_UIElements.GetSize(); i++)
+ {
+ if(m_UIElements[i].m_wType == UPDUI_TOOLBAR)
+ {
+ if((pUIData->m_wState & UPDUI_TOOLBAR) && (pMap->m_wType & UPDUI_TOOLBAR))
+ UIUpdateToolBarElement(pMap->m_nID, pUIData, m_UIElements[i].m_hWnd);
+ }
+ }
+ pMap++;
+ pUIData->m_wState &= ~UPDUI_TOOLBAR;
+ pUIData++;
+ }
+
+ m_wDirtyType &= ~UPDUI_TOOLBAR;
+ return TRUE;
+ }
+
+ BOOL UIUpdateStatusBar(BOOL bForceUpdate = FALSE)
+ {
+ if(!(m_wDirtyType & UPDUI_STATUSBAR) && !bForceUpdate)
+ return TRUE;
+
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ while(pMap->m_nID != (WORD)-1)
+ {
+ for(int i = 0; i < m_UIElements.GetSize(); i++)
+ {
+ if(m_UIElements[i].m_wType == UPDUI_STATUSBAR)
+ {
+ if((pUIData->m_wState & UPDUI_STATUSBAR) && (pMap->m_wType & UPDUI_STATUSBAR))
+ UIUpdateStatusBarElement(pMap->m_nID, pUIData, m_UIElements[i].m_hWnd);
+ }
+ }
+ pMap++;
+ pUIData->m_wState &= ~UPDUI_STATUSBAR;
+ if(pUIData->m_wState & UPDUI_TEXT)
+ {
+ delete [] pUIData->m_lpstrText;
+ pUIData->m_lpstrText = NULL;
+ pUIData->m_wState &= ~UPDUI_TEXT;
+ }
+ pUIData++;
+ }
+
+ m_wDirtyType &= ~UPDUI_STATUSBAR;
+ return TRUE;
+ }
+
+ BOOL UIUpdateChildWindows(BOOL bForceUpdate = FALSE)
+ {
+ if(!(m_wDirtyType & UPDUI_CHILDWINDOW) && !bForceUpdate)
+ return TRUE;
+
+ const _AtlUpdateUIMap* pMap = m_pUIMap;
+ _AtlUpdateUIData* pUIData = m_pUIData;
+ if(pUIData == NULL)
+ return FALSE;
+
+ while(pMap->m_nID != (WORD)-1)
+ {
+ for(int i = 0; i < m_UIElements.GetSize(); i++)
+ {
+ if(m_UIElements[i].m_wType == UPDUI_CHILDWINDOW)
+ {
+ if((pUIData->m_wState & UPDUI_CHILDWINDOW) && (pMap->m_wType & UPDUI_CHILDWINDOW))
+ UIUpdateChildWindow(pMap->m_nID, pUIData, m_UIElements[i].m_hWnd);
+ }
+ }
+ pMap++;
+ pUIData->m_wState &= ~UPDUI_CHILDWINDOW;
+ if(pUIData->m_wState & UPDUI_TEXT)
+ {
+ delete [] pUIData->m_lpstrText;
+ pUIData->m_lpstrText = NULL;
+ pUIData->m_wState &= ~UPDUI_TEXT;
+ }
+ pUIData++;
+ }
+
+ m_wDirtyType &= ~UPDUI_CHILDWINDOW;
+ return TRUE;
+ }
+
+// internal element specific methods
+ static void UIUpdateMenuBarElement(int nID, _AtlUpdateUIData* pUIData, HMENU hMenu)
+ {
+#ifndef _WIN32_WCE
+ if((pUIData->m_wState & UPDUI_CLEARDEFAULT) != 0)
+ {
+ ::SetMenuDefaultItem(hMenu, (UINT)-1, 0);
+ pUIData->m_wState &= ~UPDUI_CLEARDEFAULT;
+ }
+#endif // !_WIN32_WCE
+
+ CMenuItemInfo mii;
+ mii.fMask = MIIM_STATE;
+ mii.wID = nID;
+
+#ifndef _WIN32_WCE
+ if((pUIData->m_wState & UPDUI_DISABLED) != 0)
+ mii.fState |= MFS_DISABLED | MFS_GRAYED;
+ else
+ mii.fState |= MFS_ENABLED;
+
+ if((pUIData->m_wState & UPDUI_CHECKED) != 0)
+ mii.fState |= MFS_CHECKED;
+ else
+ mii.fState |= MFS_UNCHECKED;
+
+ if((pUIData->m_wState & UPDUI_DEFAULT) != 0)
+ mii.fState |= MFS_DEFAULT;
+#else // CE specific
+ // ::SetMenuItemInfo() can't disable or check menu items
+ // on Windows CE, so we have to do that directly
+ UINT uEnable = MF_BYCOMMAND;
+ if((pUIData->m_wState & UPDUI_DISABLED) != 0)
+ uEnable |= MF_GRAYED;
+ else
+ uEnable |= MF_ENABLED;
+ ::EnableMenuItem(hMenu, nID, uEnable);
+
+ UINT uCheck = MF_BYCOMMAND;
+ if((pUIData->m_wState & UPDUI_CHECKED) != 0)
+ uCheck |= MF_CHECKED;
+ else
+ uCheck |= MF_UNCHECKED;
+ ::CheckMenuItem(hMenu, nID, uCheck);
+#endif // _WIN32_WCE
+
+ if((pUIData->m_wState & UPDUI_TEXT) != 0)
+ {
+ CMenuItemInfo miiNow;
+ miiNow.fMask = MIIM_TYPE;
+ miiNow.wID = nID;
+ if(::GetMenuItemInfo(hMenu, nID, FALSE, &miiNow))
+ {
+ mii.fMask |= MIIM_TYPE;
+ // MFT_BITMAP and MFT_SEPARATOR don't go together with MFT_STRING
+#ifndef _WIN32_WCE
+ mii.fType |= (miiNow.fType & ~(MFT_BITMAP | MFT_SEPARATOR)) | MFT_STRING;
+#else // CE specific
+ mii.fType |= (miiNow.fType & ~(MFT_SEPARATOR)) | MFT_STRING;
+#endif // _WIN32_WCE
+ mii.dwTypeData = pUIData->m_lpstrText;
+ }
+ }
+
+ ::SetMenuItemInfo(hMenu, nID, FALSE, &mii);
+ }
+
+ static void UIUpdateToolBarElement(int nID, _AtlUpdateUIData* pUIData, HWND hWndToolBar)
+ {
+ // Note: only handles enabled/disabled, checked state, and radio (press)
+ ::SendMessage(hWndToolBar, TB_ENABLEBUTTON, nID, (LPARAM)(pUIData->m_wState & UPDUI_DISABLED) ? FALSE : TRUE);
+ ::SendMessage(hWndToolBar, TB_CHECKBUTTON, nID, (LPARAM)(pUIData->m_wState & UPDUI_CHECKED) ? TRUE : FALSE);
+ ::SendMessage(hWndToolBar, TB_INDETERMINATE, nID, (LPARAM)(pUIData->m_wState & UPDUI_CHECKED2) ? TRUE : FALSE);
+ ::SendMessage(hWndToolBar, TB_PRESSBUTTON, nID, (LPARAM)(pUIData->m_wState & UPDUI_RADIO) ? TRUE : FALSE);
+ }
+
+ static void UIUpdateStatusBarElement(int nID, _AtlUpdateUIData* pUIData, HWND hWndStatusBar)
+ {
+ // Note: only handles text
+ if(pUIData->m_wState & UPDUI_TEXT)
+ ::SendMessage(hWndStatusBar, SB_SETTEXT, nID, (LPARAM)pUIData->m_lpstrText);
+ }
+
+ static void UIUpdateChildWindow(int nID, _AtlUpdateUIData* pUIData, HWND hWnd)
+ {
+ HWND hChild = ::GetDlgItem(hWnd, nID);
+
+ ::EnableWindow(hChild, (pUIData->m_wState & UPDUI_DISABLED) ? FALSE : TRUE);
+ // for check and radio, assume that window is a button
+ int nCheck = BST_UNCHECKED;
+ if(pUIData->m_wState & UPDUI_CHECKED || pUIData->m_wState & UPDUI_RADIO)
+ nCheck = BST_CHECKED;
+ else if(pUIData->m_wState & UPDUI_CHECKED2)
+ nCheck = BST_INDETERMINATE;
+ ::SendMessage(hChild, BM_SETCHECK, nCheck, 0L);
+ if(pUIData->m_wState & UPDUI_DEFAULT)
+ {
+ DWORD dwRet = (DWORD)::SendMessage(hWnd, DM_GETDEFID, 0, 0L);
+ if(HIWORD(dwRet) == DC_HASDEFID)
+ {
+ HWND hOldDef = ::GetDlgItem(hWnd, (int)(short)LOWORD(dwRet));
+ // remove BS_DEFPUSHBUTTON
+ ::SendMessage(hOldDef, BM_SETSTYLE, BS_PUSHBUTTON, MAKELPARAM(TRUE, 0));
+ }
+ ::SendMessage(hWnd, DM_SETDEFID, nID, 0L);
+ }
+ if(pUIData->m_wState & UPDUI_TEXT)
+ ::SetWindowText(hChild, pUIData->m_lpstrText);
+ }
+};
+
+template <class T>
+class CUpdateUI : public CUpdateUIBase
+{
+public:
+ CUpdateUI()
+ {
+ T* pT = static_cast<T*>(this);
+ pT;
+ const _AtlUpdateUIMap* pMap = pT->GetUpdateUIMap();
+ m_pUIMap = pMap;
+ ATLASSERT(m_pUIMap != NULL);
+ int nCount;
+ for(nCount = 1; pMap->m_nID != (WORD)-1; nCount++)
+ pMap++;
+
+ // check for duplicates (debug only)
+#ifdef _DEBUG
+ for(int i = 0; i < nCount; i++)
+ {
+ for(int j = 0; j < nCount; j++)
+ {
+ // shouldn't have duplicates in the update UI map
+ if(i != j)
+ ATLASSERT(m_pUIMap[j].m_nID != m_pUIMap[i].m_nID);
+ }
+ }
+#endif // _DEBUG
+
+ ATLTRY(m_pUIData = new _AtlUpdateUIData[nCount]);
+ ATLASSERT(m_pUIData != NULL);
+
+ if(m_pUIData != NULL)
+ memset(m_pUIData, 0, sizeof(_AtlUpdateUIData) * nCount);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDynamicUpdateUI - allows update elements to dynamically added and removed
+// in addition to a static update UI map
+
+template <class T>
+class CDynamicUpdateUI : public CUpdateUIBase
+{
+public:
+// Data members
+ ATL::CSimpleArray<_AtlUpdateUIMap> m_arrUIMap; // copy of the static UI data
+ ATL::CSimpleArray<_AtlUpdateUIData> m_arrUIData; // instance UI data
+
+// Constructor/destructor
+ CDynamicUpdateUI()
+ {
+ T* pT = static_cast<T*>(this);
+ pT;
+ const _AtlUpdateUIMap* pMap = pT->GetUpdateUIMap();
+ ATLASSERT(pMap != NULL);
+
+ for(;;)
+ {
+ BOOL bRet = m_arrUIMap.Add(*(_AtlUpdateUIMap*)pMap);
+ ATLASSERT(bRet);
+
+ if(bRet != FALSE)
+ {
+ _AtlUpdateUIData data = { 0, NULL };
+ bRet = m_arrUIData.Add(data);
+ ATLASSERT(bRet);
+ }
+
+ if(pMap->m_nID == (WORD)-1)
+ break;
+
+ pMap++;
+ }
+
+ ATLASSERT(m_arrUIMap.GetSize() == m_arrUIData.GetSize());
+
+#ifdef _DEBUG
+ // check for duplicates (debug only)
+ for(int i = 0; i < m_arrUIMap.GetSize(); i++)
+ {
+ for(int j = 0; j < m_arrUIMap.GetSize(); j++)
+ {
+ // shouldn't have duplicates in the update UI map
+ if(i != j)
+ ATLASSERT(m_arrUIMap[j].m_nID != m_arrUIMap[i].m_nID);
+ }
+ }
+#endif // _DEBUG
+
+ // Set internal data pointers to point to the new data arrays
+ m_pUIMap = m_arrUIMap.m_aT;
+ m_pUIData = m_arrUIData.m_aT;
+ }
+
+ ~CDynamicUpdateUI()
+ {
+ for(int i = 0; i < m_arrUIData.GetSize(); i++)
+ {
+ if((m_arrUIData[i].m_wState & UPDUI_TEXT) != 0)
+ delete [] m_arrUIData[i].m_lpstrText;
+ }
+
+ // Reset internal data pointers (memory will be released by CSimpleArray d-tor)
+ m_pUIMap = NULL;
+ m_pUIData = NULL;
+ }
+
+// Methods for dynamically adding and removing update elements
+ bool UIAddUpdateElement(WORD nID, WORD wType)
+ {
+ // check for duplicates
+ for(int i = 0; i < m_arrUIMap.GetSize(); i++)
+ {
+ // shouldn't have duplicates in the update UI map
+ ATLASSERT(m_arrUIMap[i].m_nID != nID);
+ if(m_arrUIMap[i].m_nID == nID)
+ return false;
+ }
+
+ bool bRetVal = false;
+
+ // Add new end element
+ _AtlUpdateUIMap uumEnd = { (WORD)-1, 0 };
+ BOOL bRet = m_arrUIMap.Add(uumEnd);
+ ATLASSERT(bRet);
+
+ if(bRet != FALSE)
+ {
+ _AtlUpdateUIData uud = { 0, NULL };
+ bRet = m_arrUIData.Add(uud);
+ ATLASSERT(bRet);
+
+ // Set new data to the previous end element
+ if(bRet != FALSE)
+ {
+ int nSize = m_arrUIMap.GetSize();
+ _AtlUpdateUIMap uum = { nID, wType };
+ m_arrUIMap.SetAtIndex(nSize - 2, uum);
+ m_arrUIData.SetAtIndex(nSize - 2, uud);
+
+ // Set internal data pointers again, just in case that memory moved
+ m_pUIMap = m_arrUIMap.m_aT;
+ m_pUIData = m_arrUIData.m_aT;
+
+ bRetVal = true;
+ }
+ }
+
+ return bRetVal;
+ }
+
+ bool UIRemoveUpdateElement(WORD nID)
+ {
+ bool bRetVal = false;
+
+ for(int i = 0; i < m_arrUIMap.GetSize(); i++)
+ {
+ if(m_arrUIMap[i].m_nID == nID)
+ {
+ BOOL bRet = m_arrUIMap.RemoveAt(i);
+ ATLASSERT(bRet);
+ bRet = m_arrUIData.RemoveAt(i);
+ ATLASSERT(bRet);
+
+ bRetVal = true;
+ break;
+ }
+ }
+
+ return bRetVal;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAutoUpdateUI : Automatic mapping of UI elements
+
+template <class T>
+class CAutoUpdateUI : public CDynamicUpdateUI<T>
+{
+public:
+ LPCTSTR UIGetText(int nID)
+ {
+ for(int i = 0; i < m_arrUIMap.GetSize(); i++)
+ {
+ if(m_arrUIMap[i].m_nID == nID)
+ return m_arrUIData[i].m_lpstrText;
+ }
+
+ return NULL;
+ }
+
+// Element
+ template <WORD t_wType>
+ bool UIAddElement(UINT nID)
+ {
+ // check for existing UI map element
+ for(int i = 0; i < m_arrUIMap.GetSize(); i++)
+ {
+ if(m_arrUIMap[i].m_nID == nID)
+ {
+ // set requested type
+ m_arrUIMap[i].m_wType |= t_wType;
+ return true;
+ }
+ }
+
+ // Add element to UI map with requested type
+ return UIAddUpdateElement((WORD)nID, t_wType);
+ }
+
+ template <WORD t_wType>
+ bool UIRemoveElement(UINT nID)
+ {
+ for(int i = 0; i < m_arrUIMap.GetSize(); i++)
+ {
+ if(m_arrUIMap[i].m_nID == nID) // matching UI map element
+ {
+ WORD wType = m_arrUIMap[i].m_wType & ~t_wType;
+ if (wType) // has other types
+ {
+ m_arrUIMap[i].m_wType = wType; // keep other types
+ return true;
+ }
+ else
+ {
+ return UIRemoveUpdateElement((WORD)nID);
+ }
+ }
+ }
+
+ return false;
+ }
+
+// Menu
+ bool UIAddMenu(HMENU hMenu, bool bSetText = false)
+ {
+#if defined(_WIN32_WCE) && (_ATL_VER >= 0x0800)
+ using ATL::GetMenuString;
+#endif
+ ATLASSERT(::IsMenu(hMenu));
+ MENUITEMINFO mii = {sizeof(MENUITEMINFO), MIIM_TYPE | MIIM_ID | MIIM_SUBMENU};
+
+ // Complete the UI map
+ for (INT uItem = 0; CMenuHandle(hMenu).GetMenuItemInfo(uItem, TRUE, &mii); uItem++)
+ {
+ if(mii.hSubMenu)
+ {
+ // Add submenu to UI map
+ UIAddMenu(mii.hSubMenu, bSetText);
+ }
+ else if (mii.wID)
+ {
+ // Add element to UI map
+ UIAddElement<UPDUI_MENUPOPUP>(mii.wID);
+#if !defined(_WIN32_WCE) || (_ATL_VER >= 0x0800)
+ if (bSetText)
+ {
+ TCHAR sText[64] = { 0 };
+ if (GetMenuString(hMenu, uItem, sText, 64, MF_BYPOSITION))
+ UISetText(mii.wID, sText);
+ }
+#else
+ bSetText;
+#endif // !defined(_WIN32_WCE) || (_ATL_VER >= 0x0800)
+ }
+ }
+
+ return true;
+ }
+
+ bool UIAddMenu(UINT uID, bool bSetText = false)
+ {
+ CMenu menu;
+ ATLVERIFY(menu.LoadMenu(uID));
+ return UIAddMenu(menu, bSetText);
+ }
+
+// ToolBar
+#ifndef BTNS_SEP
+ #define BTNS_SEP TBSTYLE_SEP
+#endif // BTNS_SEP compatibility
+
+#if !defined(_WIN32_WCE) || (defined(_AUTOUI_CE_TOOLBAR) && defined(TBIF_BYINDEX))
+ bool UIAddToolBar(HWND hWndToolBar)
+ {
+ ATLASSERT(::IsWindow(hWndToolBar));
+ TBBUTTONINFO tbbi = {sizeof TBBUTTONINFO, TBIF_COMMAND | TBIF_STYLE | TBIF_BYINDEX};
+
+ // Add toolbar buttons
+ for (int uItem = 0; ::SendMessage(hWndToolBar, TB_GETBUTTONINFO, uItem, (LPARAM)&tbbi) != -1; uItem++)
+ {
+ if (tbbi.fsStyle ^ BTNS_SEP)
+ UIAddElement<UPDUI_TOOLBAR>(tbbi.idCommand);
+ }
+
+ // Add embedded controls if any
+ if (::GetWindow(hWndToolBar, GW_CHILD))
+ UIAddChildWindowContainer(hWndToolBar);
+
+ return (CUpdateUIBase::UIAddToolBar(hWndToolBar) != FALSE);
+ }
+#endif // !defined(_WIN32_WCE) || (defined(_AUTOUI_CE_TOOLBAR) && defined(TBIF_BYINDEX))
+
+// Container
+ bool UIAddChildWindowContainer(HWND hWnd)
+ {
+ ATLASSERT(::IsWindow(hWnd));
+
+ // Add children controls if any
+ for (ATL::CWindow wCtl = ::GetWindow(hWnd, GW_CHILD); wCtl.IsWindow(); wCtl = wCtl.GetWindow(GW_HWNDNEXT))
+ {
+ if (int id = wCtl.GetDlgCtrlID())
+ UIAddElement<UPDUI_CHILDWINDOW>(id);
+ }
+
+ return (CUpdateUIBase::UIAddChildWindowContainer(hWnd) != FALSE);
+ }
+
+// StatusBar
+ BOOL UIUpdateStatusBar(BOOL bForceUpdate = FALSE)
+ {
+ if(!(m_wDirtyType & UPDUI_STATUSBAR) && !bForceUpdate)
+ return TRUE;
+
+ for(int i = 0; i < m_arrUIMap.GetSize(); i++)
+ {
+ for(int e = 0; e < m_UIElements.GetSize(); e++)
+ {
+ if((m_UIElements[e].m_wType == UPDUI_STATUSBAR) &&
+ (m_arrUIMap[i].m_wType & UPDUI_STATUSBAR) &&
+ (m_arrUIData[i].m_wState & UPDUI_STATUSBAR))
+ {
+ UIUpdateStatusBarElement(m_arrUIMap[i].m_nID, &m_arrUIData[i], m_UIElements[e].m_hWnd);
+ m_arrUIData[i].m_wState &= ~UPDUI_STATUSBAR;
+ if(m_arrUIData[i].m_wState & UPDUI_TEXT)
+ m_arrUIData[i].m_wState &= ~UPDUI_TEXT;
+ }
+ }
+ }
+
+ m_wDirtyType &= ~UPDUI_STATUSBAR;
+ return TRUE;
+ }
+
+ bool UIAddStatusBar(HWND hWndStatusBar, INT nPanes = 1)
+ {
+ ATLASSERT(::IsWindow(hWndStatusBar));
+
+ // Add StatusBar panes
+ for (int iPane = 0; iPane < nPanes; iPane++)
+ UIAddElement<UPDUI_STATUSBAR>(ID_DEFAULT_PANE + iPane);
+
+ return (CUpdateUIBase::UIAddStatusBar(hWndStatusBar) != FALSE);
+ }
+
+// UI Map used if derived class has none
+ BEGIN_UPDATE_UI_MAP(CAutoUpdateUI)
+ END_UPDATE_UI_MAP()
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDialogResize - provides support for resizing dialog controls
+// (works for any window that has child controls)
+
+// Put CDialogResize in the list of base classes for a dialog (or even plain window),
+// then implement DLGRESIZE map by specifying controls and groups of control
+// and using DLSZ_* values to specify how are they supposed to be resized.
+//
+// Notes:
+// - Resizeable border (WS_THICKFRAME style) should be set in the dialog template
+// for top level dialogs (popup or overlapped), so that users can resize the dialog.
+// - Some flags cannot be combined; for instance DLSZ_CENTER_X overrides DLSZ_SIZE_X,
+// DLSZ_SIZE_X overrides DLSZ_MOVE_X. X and Y flags can be combined.
+// - Order of controls is important - group controls are resized and moved based
+// on the position of the previous control in a group.
+
+// dialog resize map macros
+#define BEGIN_DLGRESIZE_MAP(thisClass) \
+ static const _AtlDlgResizeMap* GetDlgResizeMap() \
+ { \
+ static const _AtlDlgResizeMap theMap[] = \
+ {
+
+#define END_DLGRESIZE_MAP() \
+ { -1, 0 }, \
+ }; \
+ return theMap; \
+ }
+
+#define DLGRESIZE_CONTROL(id, flags) \
+ { id, flags },
+
+#define BEGIN_DLGRESIZE_GROUP() \
+ { -1, _DLSZ_BEGIN_GROUP },
+
+#define END_DLGRESIZE_GROUP() \
+ { -1, _DLSZ_END_GROUP },
+
+
+template <class T>
+class CDialogResize
+{
+public:
+// Data declarations and members
+ enum
+ {
+ DLSZ_SIZE_X = 0x00000001,
+ DLSZ_SIZE_Y = 0x00000002,
+ DLSZ_MOVE_X = 0x00000004,
+ DLSZ_MOVE_Y = 0x00000008,
+ DLSZ_REPAINT = 0x00000010,
+ DLSZ_CENTER_X = 0x00000020,
+ DLSZ_CENTER_Y = 0x00000040,
+
+ // internal use only
+ _DLSZ_BEGIN_GROUP = 0x00001000,
+ _DLSZ_END_GROUP = 0x00002000,
+ _DLSZ_GRIPPER = 0x00004000
+ };
+
+ struct _AtlDlgResizeMap
+ {
+ int m_nCtlID;
+ DWORD m_dwResizeFlags;
+ };
+
+ struct _AtlDlgResizeData
+ {
+ int m_nCtlID;
+ DWORD m_dwResizeFlags;
+ RECT m_rect;
+
+ int GetGroupCount() const
+ {
+ return (int)LOBYTE(HIWORD(m_dwResizeFlags));
+ }
+
+ void SetGroupCount(int nCount)
+ {
+ ATLASSERT(nCount > 0 && nCount < 256);
+ DWORD dwCount = (DWORD)MAKELONG(0, MAKEWORD(nCount, 0));
+ m_dwResizeFlags &= 0xFF00FFFF;
+ m_dwResizeFlags |= dwCount;
+ }
+
+ bool operator ==(const _AtlDlgResizeData& r) const
+ { return (m_nCtlID == r.m_nCtlID && m_dwResizeFlags == r.m_dwResizeFlags); }
+ };
+
+ ATL::CSimpleArray<_AtlDlgResizeData> m_arrData;
+ SIZE m_sizeDialog;
+ POINT m_ptMinTrackSize;
+ bool m_bGripper;
+
+
+// Constructor
+ CDialogResize() : m_bGripper(false)
+ {
+ m_sizeDialog.cx = 0;
+ m_sizeDialog.cy = 0;
+ m_ptMinTrackSize.x = -1;
+ m_ptMinTrackSize.y = -1;
+ }
+
+// Operations
+ void DlgResize_Init(bool bAddGripper = true, bool bUseMinTrackSize = true, DWORD dwForceStyle = WS_CLIPCHILDREN)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ DWORD dwStyle = pT->GetStyle();
+
+#ifdef _DEBUG
+ // Debug only: Check if top level dialogs have a resizeable border.
+ if(((dwStyle & WS_CHILD) == 0) && ((dwStyle & WS_THICKFRAME) == 0))
+ ATLTRACE2(atlTraceUI, 0, _T("DlgResize_Init - warning: top level dialog without the WS_THICKFRAME style - user cannot resize it\n"));
+#endif // _DEBUG
+
+ // Force specified styles (default WS_CLIPCHILDREN reduces flicker)
+ if((dwStyle & dwForceStyle) != dwForceStyle)
+ pT->ModifyStyle(0, dwForceStyle);
+
+ // Adding this style removes an empty icon that dialogs with WS_THICKFRAME have.
+ // Setting icon to NULL is required when XP themes are active.
+ // Note: This will not prevent adding an icon for the dialog using SetIcon()
+ if((dwStyle & WS_CHILD) == 0)
+ {
+ pT->ModifyStyleEx(0, WS_EX_DLGMODALFRAME);
+ if(pT->GetIcon(FALSE) == NULL)
+ pT->SetIcon(NULL, FALSE);
+ }
+
+ // Cleanup in case of multiple initialization
+ // block: first check for the gripper control, destroy it if needed
+ {
+ ATL::CWindow wndGripper = pT->GetDlgItem(ATL_IDW_STATUS_BAR);
+ if(wndGripper.IsWindow() && m_arrData.GetSize() > 0 && (m_arrData[0].m_dwResizeFlags & _DLSZ_GRIPPER) != 0)
+ wndGripper.DestroyWindow();
+ }
+ // clear out everything else
+ m_arrData.RemoveAll();
+ m_sizeDialog.cx = 0;
+ m_sizeDialog.cy = 0;
+ m_ptMinTrackSize.x = -1;
+ m_ptMinTrackSize.y = -1;
+
+ // Get initial dialog client size
+ RECT rectDlg = { 0 };
+ pT->GetClientRect(&rectDlg);
+ m_sizeDialog.cx = rectDlg.right;
+ m_sizeDialog.cy = rectDlg.bottom;
+
+#ifndef _WIN32_WCE
+ // Create gripper if requested
+ m_bGripper = false;
+ if(bAddGripper)
+ {
+ // shouldn't exist already
+ ATLASSERT(!::IsWindow(pT->GetDlgItem(ATL_IDW_STATUS_BAR)));
+ if(!::IsWindow(pT->GetDlgItem(ATL_IDW_STATUS_BAR)))
+ {
+ ATL::CWindow wndGripper;
+ wndGripper.Create(_T("SCROLLBAR"), pT->m_hWnd, rectDlg, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SBS_SIZEBOX | SBS_SIZEGRIP | SBS_SIZEBOXBOTTOMRIGHTALIGN, 0, ATL_IDW_STATUS_BAR);
+ ATLASSERT(wndGripper.IsWindow());
+ if(wndGripper.IsWindow())
+ {
+ m_bGripper = true;
+ RECT rectCtl = { 0 };
+ wndGripper.GetWindowRect(&rectCtl);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rectCtl, 2);
+ _AtlDlgResizeData data = { ATL_IDW_STATUS_BAR, DLSZ_MOVE_X | DLSZ_MOVE_Y | DLSZ_REPAINT | _DLSZ_GRIPPER, { rectCtl.left, rectCtl.top, rectCtl.right, rectCtl.bottom } };
+ m_arrData.Add(data);
+ }
+ }
+ }
+#else // CE specific
+ bAddGripper; // avoid level 4 warning
+#endif // _WIN32_WCE
+
+ // Get min track position if requested
+ if(bUseMinTrackSize)
+ {
+ if((dwStyle & WS_CHILD) != 0)
+ {
+ RECT rect = { 0 };
+ pT->GetClientRect(&rect);
+ m_ptMinTrackSize.x = rect.right - rect.left;
+ m_ptMinTrackSize.y = rect.bottom - rect.top;
+ }
+ else
+ {
+ RECT rect = { 0 };
+ pT->GetWindowRect(&rect);
+ m_ptMinTrackSize.x = rect.right - rect.left;
+ m_ptMinTrackSize.y = rect.bottom - rect.top;
+ }
+ }
+
+ // Walk the map and initialize data
+ const _AtlDlgResizeMap* pMap = pT->GetDlgResizeMap();
+ ATLASSERT(pMap != NULL);
+ int nGroupStart = -1;
+ for(int nCount = 1; !(pMap->m_nCtlID == -1 && pMap->m_dwResizeFlags == 0); nCount++, pMap++)
+ {
+ if(pMap->m_nCtlID == -1)
+ {
+ switch(pMap->m_dwResizeFlags)
+ {
+ case _DLSZ_BEGIN_GROUP:
+ ATLASSERT(nGroupStart == -1);
+ nGroupStart = m_arrData.GetSize();
+ break;
+ case _DLSZ_END_GROUP:
+ {
+ ATLASSERT(nGroupStart != -1);
+ int nGroupCount = m_arrData.GetSize() - nGroupStart;
+ m_arrData[nGroupStart].SetGroupCount(nGroupCount);
+ nGroupStart = -1;
+ }
+ break;
+ default:
+ ATLASSERT(FALSE && _T("Invalid DLGRESIZE Map Entry"));
+ break;
+ }
+ }
+ else
+ {
+ // this ID conflicts with the default gripper one
+ ATLASSERT(m_bGripper ? (pMap->m_nCtlID != ATL_IDW_STATUS_BAR) : TRUE);
+
+ ATL::CWindow ctl = pT->GetDlgItem(pMap->m_nCtlID);
+ ATLASSERT(ctl.IsWindow());
+ RECT rectCtl = { 0 };
+ ctl.GetWindowRect(&rectCtl);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rectCtl, 2);
+
+ DWORD dwGroupFlag = (nGroupStart != -1 && m_arrData.GetSize() == nGroupStart) ? _DLSZ_BEGIN_GROUP : 0;
+ _AtlDlgResizeData data = { pMap->m_nCtlID, pMap->m_dwResizeFlags | dwGroupFlag, { rectCtl.left, rectCtl.top, rectCtl.right, rectCtl.bottom } };
+ m_arrData.Add(data);
+ }
+ }
+ ATLASSERT((nGroupStart == -1) && _T("No End Group Entry in the DLGRESIZE Map"));
+ }
+
+ void DlgResize_UpdateLayout(int cxWidth, int cyHeight)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ // Restrict minimum size if requested
+ if(((pT->GetStyle() & WS_CHILD) != 0) && m_ptMinTrackSize.x != -1 && m_ptMinTrackSize.y != -1)
+ {
+ if(cxWidth < m_ptMinTrackSize.x)
+ cxWidth = m_ptMinTrackSize.x;
+ if(cyHeight < m_ptMinTrackSize.y)
+ cyHeight = m_ptMinTrackSize.y;
+ }
+
+ BOOL bVisible = pT->IsWindowVisible();
+ if(bVisible)
+ pT->SetRedraw(FALSE);
+
+ for(int i = 0; i < m_arrData.GetSize(); i++)
+ {
+ if((m_arrData[i].m_dwResizeFlags & _DLSZ_BEGIN_GROUP) != 0) // start of a group
+ {
+ int nGroupCount = m_arrData[i].GetGroupCount();
+ ATLASSERT(nGroupCount > 0 && i + nGroupCount - 1 < m_arrData.GetSize());
+ RECT rectGroup = m_arrData[i].m_rect;
+
+ int j = 1;
+ for(j = 1; j < nGroupCount; j++)
+ {
+ rectGroup.left = min(rectGroup.left, m_arrData[i + j].m_rect.left);
+ rectGroup.top = min(rectGroup.top, m_arrData[i + j].m_rect.top);
+ rectGroup.right = max(rectGroup.right, m_arrData[i + j].m_rect.right);
+ rectGroup.bottom = max(rectGroup.bottom, m_arrData[i + j].m_rect.bottom);
+ }
+
+ for(j = 0; j < nGroupCount; j++)
+ {
+ _AtlDlgResizeData* pDataPrev = NULL;
+ if(j > 0)
+ pDataPrev = &(m_arrData[i + j - 1]);
+ pT->DlgResize_PositionControl(cxWidth, cyHeight, rectGroup, m_arrData[i + j], true, pDataPrev);
+ }
+
+ i += nGroupCount - 1; // increment to skip all group controls
+ }
+ else // one control entry
+ {
+ RECT rectGroup = { 0, 0, 0, 0 };
+ pT->DlgResize_PositionControl(cxWidth, cyHeight, rectGroup, m_arrData[i], false);
+ }
+ }
+
+ if(bVisible)
+ pT->SetRedraw(TRUE);
+
+ pT->RedrawWindow(NULL, NULL, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CDialogResize)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_GETMINMAXINFO, OnGetMinMaxInfo)
+#endif // _WIN32_WCE
+ END_MSG_MAP()
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+#ifndef _WIN32_WCE
+ if(m_bGripper)
+ {
+ ATL::CWindow wndGripper = pT->GetDlgItem(ATL_IDW_STATUS_BAR);
+ if(wParam == SIZE_MAXIMIZED)
+ wndGripper.ShowWindow(SW_HIDE);
+ else if(wParam == SIZE_RESTORED)
+ wndGripper.ShowWindow(SW_SHOW);
+ }
+#endif // _WIN32_WCE
+ if(wParam != SIZE_MINIMIZED)
+ {
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DlgResize_UpdateLayout(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
+ }
+ return 0;
+ }
+
+#ifndef _WIN32_WCE
+ LRESULT OnGetMinMaxInfo(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ if(m_ptMinTrackSize.x != -1 && m_ptMinTrackSize.y != -1)
+ {
+ LPMINMAXINFO lpMMI = (LPMINMAXINFO)lParam;
+ lpMMI->ptMinTrackSize = m_ptMinTrackSize;
+ }
+ return 0;
+ }
+#endif // _WIN32_WCE
+
+// Implementation
+ bool DlgResize_PositionControl(int cxWidth, int cyHeight, RECT& rectGroup, _AtlDlgResizeData& data, bool bGroup,
+ _AtlDlgResizeData* pDataPrev = NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ ATL::CWindow ctl;
+ RECT rectCtl = { 0 };
+
+ ctl = pT->GetDlgItem(data.m_nCtlID);
+ if(!ctl.GetWindowRect(&rectCtl))
+ return false;
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rectCtl, 2);
+
+ if(bGroup)
+ {
+ if((data.m_dwResizeFlags & DLSZ_CENTER_X) != 0)
+ {
+ int cxRight = rectGroup.right + cxWidth - m_sizeDialog.cx;
+ int cxCtl = data.m_rect.right - data.m_rect.left;
+ rectCtl.left = rectGroup.left + (cxRight - rectGroup.left - cxCtl) / 2;
+ rectCtl.right = rectCtl.left + cxCtl;
+ }
+ else if((data.m_dwResizeFlags & (DLSZ_SIZE_X | DLSZ_MOVE_X)) != 0)
+ {
+ rectCtl.left = rectGroup.left + ::MulDiv(data.m_rect.left - rectGroup.left, rectGroup.right - rectGroup.left + (cxWidth - m_sizeDialog.cx), rectGroup.right - rectGroup.left);
+
+ if((data.m_dwResizeFlags & DLSZ_SIZE_X) != 0)
+ {
+ rectCtl.right = rectGroup.left + ::MulDiv(data.m_rect.right - rectGroup.left, rectGroup.right - rectGroup.left + (cxWidth - m_sizeDialog.cx), rectGroup.right - rectGroup.left);
+
+ if(pDataPrev != NULL)
+ {
+ ATL::CWindow ctlPrev = pT->GetDlgItem(pDataPrev->m_nCtlID);
+ RECT rcPrev = { 0 };
+ ctlPrev.GetWindowRect(&rcPrev);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rcPrev, 2);
+ int dxAdjust = (rectCtl.left - rcPrev.right) - (data.m_rect.left - pDataPrev->m_rect.right);
+ rcPrev.right += dxAdjust;
+ ctlPrev.SetWindowPos(NULL, &rcPrev, SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE);
+ }
+ }
+ else
+ {
+ rectCtl.right = rectCtl.left + (data.m_rect.right - data.m_rect.left);
+ }
+ }
+
+ if((data.m_dwResizeFlags & DLSZ_CENTER_Y) != 0)
+ {
+ int cyBottom = rectGroup.bottom + cyHeight - m_sizeDialog.cy;
+ int cyCtl = data.m_rect.bottom - data.m_rect.top;
+ rectCtl.top = rectGroup.top + (cyBottom - rectGroup.top - cyCtl) / 2;
+ rectCtl.bottom = rectCtl.top + cyCtl;
+ }
+ else if((data.m_dwResizeFlags & (DLSZ_SIZE_Y | DLSZ_MOVE_Y)) != 0)
+ {
+ rectCtl.top = rectGroup.top + ::MulDiv(data.m_rect.top - rectGroup.top, rectGroup.bottom - rectGroup.top + (cyHeight - m_sizeDialog.cy), rectGroup.bottom - rectGroup.top);
+
+ if((data.m_dwResizeFlags & DLSZ_SIZE_Y) != 0)
+ {
+ rectCtl.bottom = rectGroup.top + ::MulDiv(data.m_rect.bottom - rectGroup.top, rectGroup.bottom - rectGroup.top + (cyHeight - m_sizeDialog.cy), rectGroup.bottom - rectGroup.top);
+
+ if(pDataPrev != NULL)
+ {
+ ATL::CWindow ctlPrev = pT->GetDlgItem(pDataPrev->m_nCtlID);
+ RECT rcPrev = { 0 };
+ ctlPrev.GetWindowRect(&rcPrev);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rcPrev, 2);
+ int dxAdjust = (rectCtl.top - rcPrev.bottom) - (data.m_rect.top - pDataPrev->m_rect.bottom);
+ rcPrev.bottom += dxAdjust;
+ ctlPrev.SetWindowPos(NULL, &rcPrev, SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE);
+ }
+ }
+ else
+ {
+ rectCtl.bottom = rectCtl.top + (data.m_rect.bottom - data.m_rect.top);
+ }
+ }
+ }
+ else // no group
+ {
+ if((data.m_dwResizeFlags & DLSZ_CENTER_X) != 0)
+ {
+ int cxCtl = data.m_rect.right - data.m_rect.left;
+ rectCtl.left = (cxWidth - cxCtl) / 2;
+ rectCtl.right = rectCtl.left + cxCtl;
+ }
+ else if((data.m_dwResizeFlags & (DLSZ_SIZE_X | DLSZ_MOVE_X)) != 0)
+ {
+ rectCtl.right = data.m_rect.right + (cxWidth - m_sizeDialog.cx);
+
+ if((data.m_dwResizeFlags & DLSZ_MOVE_X) != 0)
+ rectCtl.left = rectCtl.right - (data.m_rect.right - data.m_rect.left);
+ }
+
+ if((data.m_dwResizeFlags & DLSZ_CENTER_Y) != 0)
+ {
+ int cyCtl = data.m_rect.bottom - data.m_rect.top;
+ rectCtl.top = (cyHeight - cyCtl) / 2;
+ rectCtl.bottom = rectCtl.top + cyCtl;
+ }
+ else if((data.m_dwResizeFlags & (DLSZ_SIZE_Y | DLSZ_MOVE_Y)) != 0)
+ {
+ rectCtl.bottom = data.m_rect.bottom + (cyHeight - m_sizeDialog.cy);
+
+ if((data.m_dwResizeFlags & DLSZ_MOVE_Y) != 0)
+ rectCtl.top = rectCtl.bottom - (data.m_rect.bottom - data.m_rect.top);
+ }
+ }
+
+ if((data.m_dwResizeFlags & DLSZ_REPAINT) != 0)
+ ctl.Invalidate();
+
+ if((data.m_dwResizeFlags & (DLSZ_SIZE_X | DLSZ_SIZE_Y | DLSZ_MOVE_X | DLSZ_MOVE_Y | DLSZ_REPAINT | DLSZ_CENTER_X | DLSZ_CENTER_Y)) != 0)
+ ctl.SetWindowPos(NULL, &rectCtl, SWP_NOZORDER | SWP_NOACTIVATE);
+
+ return true;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDoubleBufferImpl - Provides double-buffer painting support to any window
+
+template <class T>
+class CDoubleBufferImpl
+{
+public:
+// Overrideables
+ void DoPaint(CDCHandle /*dc*/)
+ {
+ // must be implemented in a derived class
+ ATLASSERT(FALSE);
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CDoubleBufferImpl)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+#endif // !_WIN32_WCE
+ END_MSG_MAP()
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1; // no background painting needed
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ if(wParam != NULL)
+ {
+ RECT rect = { 0 };
+ pT->GetClientRect(&rect);
+ CMemoryDC dcMem((HDC)wParam, rect);
+ pT->DoPaint(dcMem.m_hDC);
+ }
+ else
+ {
+ CPaintDC dc(pT->m_hWnd);
+ CMemoryDC dcMem(dc.m_hDC, dc.m_ps.rcPaint);
+ pT->DoPaint(dcMem.m_hDC);
+ }
+
+ return 0;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDoubleBufferWindowImpl - Implements a double-buffer painting window
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CDoubleBufferWindowImpl : public ATL::CWindowImpl< T, TBase, TWinTraits >, public CDoubleBufferImpl< T >
+{
+public:
+ BEGIN_MSG_MAP(CDoubleBufferWindowImpl)
+ CHAIN_MSG_MAP(CDoubleBufferImpl< T >)
+ END_MSG_MAP()
+};
+
+
+// command bar support
+#if !defined(__ATLCTRLW_H__) && !defined(_WIN32_WCE)
+ #undef CBRM_GETMENU
+ #undef CBRM_TRACKPOPUPMENU
+ #undef CBRM_GETCMDBAR
+ #undef CBRPOPUPMENU
+#endif // !defined(__ATLCTRLW_H__) && !defined(_WIN32_WCE)
+
+}; // namespace WTL
+
+#endif // __ATLFRAME_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlgdi.h b/plugins/SmartAutoReplier/wtl/atlgdi.h
new file mode 100644
index 0000000000..1e452c4d9b
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlgdi.h
@@ -0,0 +1,3891 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLGDI_H__
+#define __ATLGDI_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlgdi.h requires atlapp.h to be included first
+#endif
+
+
+// protect template members from windowsx.h macros
+#ifdef _INC_WINDOWSX
+ #undef CopyRgn
+ #undef CreateBrush
+ #undef CreatePen
+ #undef SelectBrush
+ #undef SelectPen
+ #undef SelectFont
+ #undef SelectBitmap
+#endif // _INC_WINDOWSX
+
+// required libraries
+#if !defined(_ATL_NO_MSIMG) && !defined(_WIN32_WCE)
+ #pragma comment(lib, "msimg32.lib")
+#endif // !defined(_ATL_NO_MSIMG) && !defined(_WIN32_WCE)
+#if !defined(_ATL_NO_OPENGL) && !defined(_WIN32_WCE)
+ #pragma comment(lib, "opengl32.lib")
+#endif // !defined(_ATL_NO_OPENGL) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CPenT<t_bManaged>
+// CBrushT<t_bManaged>
+// CLogFont
+// CFontT<t_bManaged>
+// CBitmapT<t_bManaged>
+// CPaletteT<t_bManaged>
+// CRgnT<t_bManaged>
+// CDCT<t_bManaged>
+// CPaintDC
+// CClientDC
+// CWindowDC
+// CMemoryDC
+// CEnhMetaFileInfo
+// CEnhMetaFileT<t_bManaged>
+// CEnhMetaFileDC
+//
+// Global functions:
+// AtlGetBitmapResourceInfo()
+// AtlGetBitmapResourceBitsPerPixel()
+// AtlIsAlphaBitmapResource()
+// AtlIsDib16()
+// AtlGetDibColorTableSize()
+// AtlGetDibNumColors(),
+// AtlGetDibBitmap()
+// AtlCopyBitmap()
+// AtlCreatePackedDib16()
+// AtlSetClipboardDib16()
+// AtlGetClipboardDib()
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// Bitmap resource helpers to extract bitmap information for a bitmap resource
+
+inline LPBITMAPINFOHEADER AtlGetBitmapResourceInfo(HMODULE hModule, ATL::_U_STRINGorID image)
+{
+ HRSRC hResource = ::FindResource(hModule, image.m_lpstr, RT_BITMAP);
+ ATLASSERT(hResource != NULL);
+ HGLOBAL hGlobal = ::LoadResource(hModule, hResource);
+ ATLASSERT(hGlobal != NULL);
+ LPBITMAPINFOHEADER pBitmapInfoHeader = (LPBITMAPINFOHEADER)::LockResource(hGlobal);
+ ATLASSERT(pBitmapInfoHeader != NULL);
+ return pBitmapInfoHeader;
+}
+
+inline WORD AtlGetBitmapResourceBitsPerPixel(HMODULE hModule, ATL::_U_STRINGorID image)
+{
+ LPBITMAPINFOHEADER pBitmapInfoHeader = AtlGetBitmapResourceInfo(hModule, image);
+ ATLASSERT(pBitmapInfoHeader != NULL);
+ return pBitmapInfoHeader->biBitCount;
+}
+
+inline WORD AtlGetBitmapResourceBitsPerPixel(ATL::_U_STRINGorID image)
+{
+ return AtlGetBitmapResourceBitsPerPixel(ModuleHelper::GetResourceInstance(), image);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// 32-bit (alpha channel) bitmap resource helper
+
+// Note: 32-bit (alpha channel) images work only on Windows XP with Common Controls version 6.
+// If you want your app to work on older version of Windows, load non-alpha images if Common
+// Controls version is less than 6.
+
+inline bool AtlIsAlphaBitmapResource(ATL::_U_STRINGorID image)
+{
+ return (AtlGetBitmapResourceBitsPerPixel(image) == 32);
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPen
+
+template <bool t_bManaged>
+class CPenT
+{
+public:
+// Data members
+ HPEN m_hPen;
+
+// Constructor/destructor/operators
+ CPenT(HPEN hPen = NULL) : m_hPen(hPen)
+ { }
+
+ ~CPenT()
+ {
+ if(t_bManaged && m_hPen != NULL)
+ DeleteObject();
+ }
+
+ CPenT<t_bManaged>& operator =(HPEN hPen)
+ {
+ Attach(hPen);
+ return *this;
+ }
+
+ void Attach(HPEN hPen)
+ {
+ if(t_bManaged && m_hPen != NULL && m_hPen != hPen)
+ ::DeleteObject(m_hPen);
+ m_hPen = hPen;
+ }
+
+ HPEN Detach()
+ {
+ HPEN hPen = m_hPen;
+ m_hPen = NULL;
+ return hPen;
+ }
+
+ operator HPEN() const { return m_hPen; }
+
+ bool IsNull() const { return (m_hPen == NULL); }
+
+// Create methods
+ HPEN CreatePen(int nPenStyle, int nWidth, COLORREF crColor)
+ {
+ ATLASSERT(m_hPen == NULL);
+ m_hPen = ::CreatePen(nPenStyle, nWidth, crColor);
+ return m_hPen;
+ }
+
+#ifndef _WIN32_WCE
+ HPEN CreatePen(int nPenStyle, int nWidth, const LOGBRUSH* pLogBrush, int nStyleCount = 0, const DWORD* lpStyle = NULL)
+ {
+ ATLASSERT(m_hPen == NULL);
+ m_hPen = ::ExtCreatePen(nPenStyle, nWidth, pLogBrush, nStyleCount, lpStyle);
+ return m_hPen;
+ }
+#endif // !_WIN32_WCE
+
+ HPEN CreatePenIndirect(LPLOGPEN lpLogPen)
+ {
+ ATLASSERT(m_hPen == NULL);
+ m_hPen = ::CreatePenIndirect(lpLogPen);
+ return m_hPen;
+ }
+
+ BOOL DeleteObject()
+ {
+ ATLASSERT(m_hPen != NULL);
+ BOOL bRet = ::DeleteObject(m_hPen);
+ if(bRet)
+ m_hPen = NULL;
+ return bRet;
+ }
+
+// Attributes
+ int GetLogPen(LOGPEN* pLogPen) const
+ {
+ ATLASSERT(m_hPen != NULL);
+ return ::GetObject(m_hPen, sizeof(LOGPEN), pLogPen);
+ }
+
+ bool GetLogPen(LOGPEN& LogPen) const
+ {
+ ATLASSERT(m_hPen != NULL);
+ return (::GetObject(m_hPen, sizeof(LOGPEN), &LogPen) == sizeof(LOGPEN));
+ }
+
+#ifndef _WIN32_WCE
+ int GetExtLogPen(EXTLOGPEN* pLogPen) const
+ {
+ ATLASSERT(m_hPen != NULL);
+ return ::GetObject(m_hPen, sizeof(EXTLOGPEN), pLogPen);
+ }
+
+ bool GetExtLogPen(EXTLOGPEN& ExtLogPen) const
+ {
+ ATLASSERT(m_hPen != NULL);
+ return (::GetObject(m_hPen, sizeof(EXTLOGPEN), &ExtLogPen) == sizeof(EXTLOGPEN));
+ }
+#endif // !_WIN32_WCE
+};
+
+typedef CPenT<false> CPenHandle;
+typedef CPenT<true> CPen;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CBrush
+
+template <bool t_bManaged>
+class CBrushT
+{
+public:
+// Data members
+ HBRUSH m_hBrush;
+
+// Constructor/destructor/operators
+ CBrushT(HBRUSH hBrush = NULL) : m_hBrush(hBrush)
+ { }
+
+ ~CBrushT()
+ {
+ if(t_bManaged && m_hBrush != NULL)
+ DeleteObject();
+ }
+
+ CBrushT<t_bManaged>& operator =(HBRUSH hBrush)
+ {
+ Attach(hBrush);
+ return *this;
+ }
+
+ void Attach(HBRUSH hBrush)
+ {
+ if(t_bManaged && m_hBrush != NULL && m_hBrush != hBrush)
+ ::DeleteObject(m_hBrush);
+ m_hBrush = hBrush;
+ }
+
+ HBRUSH Detach()
+ {
+ HBRUSH hBrush = m_hBrush;
+ m_hBrush = NULL;
+ return hBrush;
+ }
+
+ operator HBRUSH() const { return m_hBrush; }
+
+ bool IsNull() const { return (m_hBrush == NULL); }
+
+// Create methods
+ HBRUSH CreateSolidBrush(COLORREF crColor)
+ {
+ ATLASSERT(m_hBrush == NULL);
+ m_hBrush = ::CreateSolidBrush(crColor);
+ return m_hBrush;
+ }
+
+#ifndef _WIN32_WCE
+ HBRUSH CreateHatchBrush(int nIndex, COLORREF crColor)
+ {
+ ATLASSERT(m_hBrush == NULL);
+ m_hBrush = ::CreateHatchBrush(nIndex, crColor);
+ return m_hBrush;
+ }
+#endif // !_WIN32_WCE
+
+#if !defined(_WIN32_WCE) || (_ATL_VER >= 0x0800)
+ HBRUSH CreateBrushIndirect(const LOGBRUSH* lpLogBrush)
+ {
+ ATLASSERT(m_hBrush == NULL);
+#ifndef _WIN32_WCE
+ m_hBrush = ::CreateBrushIndirect(lpLogBrush);
+#else // CE specific
+ m_hBrush = ATL::CreateBrushIndirect(lpLogBrush);
+#endif // _WIN32_WCE
+ return m_hBrush;
+ }
+#endif // !defined(_WIN32_WCE) || (_ATL_VER >= 0x0800)
+
+ HBRUSH CreatePatternBrush(HBITMAP hBitmap)
+ {
+ ATLASSERT(m_hBrush == NULL);
+ m_hBrush = ::CreatePatternBrush(hBitmap);
+ return m_hBrush;
+ }
+
+ HBRUSH CreateDIBPatternBrush(HGLOBAL hPackedDIB, UINT nUsage)
+ {
+ ATLASSERT(hPackedDIB != NULL);
+ const void* lpPackedDIB = GlobalLock(hPackedDIB);
+ ATLASSERT(lpPackedDIB != NULL);
+ m_hBrush = ::CreateDIBPatternBrushPt(lpPackedDIB, nUsage);
+ GlobalUnlock(hPackedDIB);
+ return m_hBrush;
+ }
+
+ HBRUSH CreateDIBPatternBrush(const void* lpPackedDIB, UINT nUsage)
+ {
+ ATLASSERT(m_hBrush == NULL);
+ m_hBrush = ::CreateDIBPatternBrushPt(lpPackedDIB, nUsage);
+ return m_hBrush;
+ }
+
+ HBRUSH CreateSysColorBrush(int nIndex)
+ {
+ ATLASSERT(m_hBrush == NULL);
+ m_hBrush = ::GetSysColorBrush(nIndex);
+ return m_hBrush;
+ }
+
+ BOOL DeleteObject()
+ {
+ ATLASSERT(m_hBrush != NULL);
+ BOOL bRet = ::DeleteObject(m_hBrush);
+ if(bRet)
+ m_hBrush = NULL;
+ return bRet;
+ }
+
+// Attributes
+ int GetLogBrush(LOGBRUSH* pLogBrush) const
+ {
+ ATLASSERT(m_hBrush != NULL);
+ return ::GetObject(m_hBrush, sizeof(LOGBRUSH), pLogBrush);
+ }
+
+ bool GetLogBrush(LOGBRUSH& LogBrush) const
+ {
+ ATLASSERT(m_hBrush != NULL);
+ return (::GetObject(m_hBrush, sizeof(LOGBRUSH), &LogBrush) == sizeof(LOGBRUSH));
+ }
+};
+
+typedef CBrushT<false> CBrushHandle;
+typedef CBrushT<true> CBrush;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CFont
+
+class CLogFont : public LOGFONT
+{
+public:
+ CLogFont()
+ {
+ memset(this, 0, sizeof(LOGFONT));
+ }
+
+ CLogFont(const LOGFONT& lf)
+ {
+ Copy(&lf);
+ }
+
+ CLogFont(HFONT hFont)
+ {
+ ATLASSERT(::GetObjectType(hFont) == OBJ_FONT);
+ ::GetObject(hFont, sizeof(LOGFONT), (LOGFONT*)this);
+ }
+
+ HFONT CreateFontIndirect()
+ {
+ return ::CreateFontIndirect(this);
+ }
+
+ void SetBold()
+ {
+ lfWeight = FW_BOLD;
+ }
+
+ bool IsBold() const
+ {
+ return (lfWeight >= FW_BOLD);
+ }
+
+ void MakeBolder(int iScale = 1)
+ {
+ lfWeight += FW_BOLD * iScale;
+ }
+
+ void MakeLarger(int iScale)
+ {
+ if(lfHeight > 0)
+ lfHeight += iScale;
+ else
+ lfHeight -= iScale;
+ }
+
+ void SetHeight(LONG nPointSize, HDC hDC = NULL)
+ {
+ HDC hDC1 = (hDC != NULL) ? hDC : ::GetDC(NULL);
+ // For MM_TEXT mapping mode
+ lfHeight = -::MulDiv(nPointSize, ::GetDeviceCaps(hDC1, LOGPIXELSY), 72);
+ if(hDC == NULL)
+ ::ReleaseDC(NULL, hDC1);
+ }
+
+ LONG GetHeight(HDC hDC = NULL) const
+ {
+ HDC hDC1 = (hDC != NULL) ? hDC : ::GetDC(NULL);
+ // For MM_TEXT mapping mode
+ LONG nPointSize = ::MulDiv(-lfHeight, 72, ::GetDeviceCaps(hDC1, LOGPIXELSY));
+ if(hDC == NULL)
+ ::ReleaseDC(NULL, hDC1);
+
+ return nPointSize;
+ }
+
+ LONG GetDeciPointHeight(HDC hDC = NULL) const
+ {
+ HDC hDC1 = (hDC != NULL) ? hDC : ::GetDC(NULL);
+#ifndef _WIN32_WCE
+ POINT ptOrg = { 0, 0 };
+ ::DPtoLP(hDC1, &ptOrg, 1);
+ POINT pt = { 0, 0 };
+ pt.y = abs(lfHeight) + ptOrg.y;
+ ::LPtoDP(hDC1, &pt,1);
+ LONG nDeciPoint = ::MulDiv(pt.y, 720, ::GetDeviceCaps(hDC1, LOGPIXELSY)); // 72 points/inch, 10 decipoints/point
+#else // CE specific
+ // DP and LP are always the same on CE
+ LONG nDeciPoint = ::MulDiv(abs(lfHeight), 720, ::GetDeviceCaps(hDC1, LOGPIXELSY)); // 72 points/inch, 10 decipoints/point
+#endif // _WIN32_WCE
+ if(hDC == NULL)
+ ::ReleaseDC(NULL, hDC1);
+
+ return nDeciPoint;
+ }
+
+ void SetHeightFromDeciPoint(LONG nDeciPtHeight, HDC hDC = NULL)
+ {
+ HDC hDC1 = (hDC != NULL) ? hDC : ::GetDC(NULL);
+#ifndef _WIN32_WCE
+ POINT pt = { 0, 0 };
+ pt.y = ::MulDiv(::GetDeviceCaps(hDC1, LOGPIXELSY), nDeciPtHeight, 720); // 72 points/inch, 10 decipoints/point
+ ::DPtoLP(hDC1, &pt, 1);
+ POINT ptOrg = { 0, 0 };
+ ::DPtoLP(hDC1, &ptOrg, 1);
+ lfHeight = -abs(pt.y - ptOrg.y);
+#else // CE specific
+ // DP and LP are always the same on CE
+ lfHeight = -abs(::MulDiv(::GetDeviceCaps(hDC1, LOGPIXELSY), nDeciPtHeight, 720)); // 72 points/inch, 10 decipoints/point
+#endif // _WIN32_WCE
+ if(hDC == NULL)
+ ::ReleaseDC(NULL, hDC1);
+ }
+
+#ifndef _WIN32_WCE
+ void SetCaptionFont()
+ {
+ NONCLIENTMETRICS ncm = { RunTimeHelper::SizeOf_NONCLIENTMETRICS() };
+ ATLVERIFY(::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0));
+ Copy(&ncm.lfCaptionFont);
+ }
+
+ void SetMenuFont()
+ {
+ NONCLIENTMETRICS ncm = { RunTimeHelper::SizeOf_NONCLIENTMETRICS() };
+ ATLVERIFY(::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0));
+ Copy(&ncm.lfMenuFont);
+ }
+
+ void SetStatusFont()
+ {
+ NONCLIENTMETRICS ncm = { RunTimeHelper::SizeOf_NONCLIENTMETRICS() };
+ ATLVERIFY(::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0));
+ Copy(&ncm.lfStatusFont);
+ }
+
+ void SetMessageBoxFont()
+ {
+ NONCLIENTMETRICS ncm = { RunTimeHelper::SizeOf_NONCLIENTMETRICS() };
+ ATLVERIFY(::SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0));
+ Copy(&ncm.lfMessageFont);
+ }
+#endif // !_WIN32_WCE
+
+ void Copy(const LOGFONT* pLogFont)
+ {
+ ATLASSERT(pLogFont != NULL);
+ *(LOGFONT*)this = *pLogFont;
+ }
+
+ CLogFont& operator =(const CLogFont& src)
+ {
+ Copy(&src);
+ return *this;
+ }
+
+ CLogFont& operator =(const LOGFONT& src)
+ {
+ Copy(&src);
+ return *this;
+ }
+
+ CLogFont& operator =(HFONT hFont)
+ {
+ ATLASSERT(::GetObjectType(hFont) == OBJ_FONT);
+ ::GetObject(hFont, sizeof(LOGFONT), (LOGFONT*)this);
+ return *this;
+ }
+
+ bool operator ==(const LOGFONT& logfont) const
+ {
+ return(logfont.lfHeight == lfHeight &&
+ logfont.lfWidth == lfWidth &&
+ logfont.lfEscapement == lfEscapement &&
+ logfont.lfOrientation == lfOrientation &&
+ logfont.lfWeight == lfWeight &&
+ logfont.lfItalic == lfItalic &&
+ logfont.lfUnderline == lfUnderline &&
+ logfont.lfStrikeOut == lfStrikeOut &&
+ logfont.lfCharSet == lfCharSet &&
+ logfont.lfOutPrecision == lfOutPrecision &&
+ logfont.lfClipPrecision == lfClipPrecision &&
+ logfont.lfQuality == lfQuality &&
+ logfont.lfPitchAndFamily == lfPitchAndFamily &&
+ lstrcmp(logfont.lfFaceName, lfFaceName) == 0);
+ }
+};
+
+
+template <bool t_bManaged>
+class CFontT
+{
+public:
+// Data members
+ HFONT m_hFont;
+
+// Constructor/destructor/operators
+ CFontT(HFONT hFont = NULL) : m_hFont(hFont)
+ { }
+
+ ~CFontT()
+ {
+ if(t_bManaged && m_hFont != NULL)
+ DeleteObject();
+ }
+
+ CFontT<t_bManaged>& operator =(HFONT hFont)
+ {
+ Attach(hFont);
+ return *this;
+ }
+
+ void Attach(HFONT hFont)
+ {
+ if(t_bManaged && m_hFont != NULL && m_hFont != hFont)
+ ::DeleteObject(m_hFont);
+ m_hFont = hFont;
+ }
+
+ HFONT Detach()
+ {
+ HFONT hFont = m_hFont;
+ m_hFont = NULL;
+ return hFont;
+ }
+
+ operator HFONT() const { return m_hFont; }
+
+ bool IsNull() const { return (m_hFont == NULL); }
+
+// Create methods
+ HFONT CreateFontIndirect(const LOGFONT* lpLogFont)
+ {
+ ATLASSERT(m_hFont == NULL);
+ m_hFont = ::CreateFontIndirect(lpLogFont);
+ return m_hFont;
+ }
+
+#if !defined(_WIN32_WCE) && (_WIN32_WINNT >= 0x0500)
+ HFONT CreateFontIndirectEx(CONST ENUMLOGFONTEXDV* penumlfex)
+ {
+ ATLASSERT(m_hFont == NULL);
+ m_hFont = ::CreateFontIndirectEx(penumlfex);
+ return m_hFont;
+ }
+#endif // !defined(_WIN32_WCE) && (_WIN32_WINNT >= 0x0500)
+
+#if !defined(_WIN32_WCE) || (_ATL_VER >= 0x0800)
+ HFONT CreateFont(int nHeight, int nWidth, int nEscapement,
+ int nOrientation, int nWeight, BYTE bItalic, BYTE bUnderline,
+ BYTE cStrikeOut, BYTE nCharSet, BYTE nOutPrecision,
+ BYTE nClipPrecision, BYTE nQuality, BYTE nPitchAndFamily,
+ LPCTSTR lpszFacename)
+ {
+ ATLASSERT(m_hFont == NULL);
+#ifndef _WIN32_WCE
+ m_hFont = ::CreateFont(nHeight, nWidth, nEscapement,
+ nOrientation, nWeight, bItalic, bUnderline, cStrikeOut,
+ nCharSet, nOutPrecision, nClipPrecision, nQuality,
+ nPitchAndFamily, lpszFacename);
+#else // CE specific
+ m_hFont = ATL::CreateFont(nHeight, nWidth, nEscapement,
+ nOrientation, nWeight, bItalic, bUnderline, cStrikeOut,
+ nCharSet, nOutPrecision, nClipPrecision, nQuality,
+ nPitchAndFamily, lpszFacename);
+#endif // _WIN32_WCE
+ return m_hFont;
+ }
+#endif // !defined(_WIN32_WCE) || (_ATL_VER >= 0x0800)
+
+ HFONT CreatePointFont(int nPointSize, LPCTSTR lpszFaceName, HDC hDC = NULL, bool bBold = false, bool bItalic = false)
+ {
+ LOGFONT logFont = { 0 };
+ logFont.lfCharSet = DEFAULT_CHARSET;
+ logFont.lfHeight = nPointSize;
+ SecureHelper::strncpy_x(logFont.lfFaceName, _countof(logFont.lfFaceName), lpszFaceName, _TRUNCATE);
+
+ if(bBold)
+ logFont.lfWeight = FW_BOLD;
+ if(bItalic)
+ logFont.lfItalic = (BYTE)TRUE;
+
+ return CreatePointFontIndirect(&logFont, hDC);
+ }
+
+ HFONT CreatePointFontIndirect(const LOGFONT* lpLogFont, HDC hDC = NULL)
+ {
+ HDC hDC1 = (hDC != NULL) ? hDC : ::GetDC(NULL);
+
+ // convert nPointSize to logical units based on hDC
+ LOGFONT logFont = *lpLogFont;
+#ifndef _WIN32_WCE
+ POINT pt = { 0, 0 };
+ pt.y = ::MulDiv(::GetDeviceCaps(hDC1, LOGPIXELSY), logFont.lfHeight, 720); // 72 points/inch, 10 decipoints/point
+ ::DPtoLP(hDC1, &pt, 1);
+ POINT ptOrg = { 0, 0 };
+ ::DPtoLP(hDC1, &ptOrg, 1);
+ logFont.lfHeight = -abs(pt.y - ptOrg.y);
+#else // CE specific
+ // DP and LP are always the same on CE
+ logFont.lfHeight = -abs(::MulDiv(::GetDeviceCaps(hDC1, LOGPIXELSY), logFont.lfHeight, 720)); // 72 points/inch, 10 decipoints/point
+#endif // _WIN32_WCE
+
+ if(hDC == NULL)
+ ::ReleaseDC(NULL, hDC1);
+
+ return CreateFontIndirect(&logFont);
+ }
+
+ BOOL DeleteObject()
+ {
+ ATLASSERT(m_hFont != NULL);
+ BOOL bRet = ::DeleteObject(m_hFont);
+ if(bRet)
+ m_hFont = NULL;
+ return bRet;
+ }
+
+// Attributes
+ int GetLogFont(LOGFONT* pLogFont) const
+ {
+ ATLASSERT(m_hFont != NULL);
+ return ::GetObject(m_hFont, sizeof(LOGFONT), pLogFont);
+ }
+
+ bool GetLogFont(LOGFONT& LogFont) const
+ {
+ ATLASSERT(m_hFont != NULL);
+ return (::GetObject(m_hFont, sizeof(LOGFONT), &LogFont) == sizeof(LOGFONT));
+ }
+};
+
+typedef CFontT<false> CFontHandle;
+typedef CFontT<true> CFont;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CBitmap
+
+template <bool t_bManaged>
+class CBitmapT
+{
+public:
+// Data members
+ HBITMAP m_hBitmap;
+
+// Constructor/destructor/operators
+ CBitmapT(HBITMAP hBitmap = NULL) : m_hBitmap(hBitmap)
+ { }
+
+ ~CBitmapT()
+ {
+ if(t_bManaged && m_hBitmap != NULL)
+ DeleteObject();
+ }
+
+ CBitmapT<t_bManaged>& operator =(HBITMAP hBitmap)
+ {
+ Attach(hBitmap);
+ return *this;
+ }
+
+ void Attach(HBITMAP hBitmap)
+ {
+ if(t_bManaged && m_hBitmap != NULL&& m_hBitmap != hBitmap)
+ ::DeleteObject(m_hBitmap);
+ m_hBitmap = hBitmap;
+ }
+
+ HBITMAP Detach()
+ {
+ HBITMAP hBitmap = m_hBitmap;
+ m_hBitmap = NULL;
+ return hBitmap;
+ }
+
+ operator HBITMAP() const { return m_hBitmap; }
+
+ bool IsNull() const { return (m_hBitmap == NULL); }
+
+// Create and load methods
+ HBITMAP LoadBitmap(ATL::_U_STRINGorID bitmap)
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::LoadBitmap(ModuleHelper::GetResourceInstance(), bitmap.m_lpstr);
+ return m_hBitmap;
+ }
+
+ HBITMAP LoadOEMBitmap(UINT nIDBitmap) // for OBM_/OCR_/OIC_
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::LoadBitmap(NULL, MAKEINTRESOURCE(nIDBitmap));
+ return m_hBitmap;
+ }
+
+#ifndef _WIN32_WCE
+ HBITMAP LoadMappedBitmap(UINT nIDBitmap, UINT nFlags = 0, LPCOLORMAP lpColorMap = NULL, int nMapSize = 0)
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::CreateMappedBitmap(ModuleHelper::GetResourceInstance(), nIDBitmap, (WORD)nFlags, lpColorMap, nMapSize);
+ return m_hBitmap;
+ }
+#endif // !_WIN32_WCE
+
+ HBITMAP CreateBitmap(int nWidth, int nHeight, UINT nPlanes, UINT nBitsPerPixel, const void* lpBits)
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::CreateBitmap(nWidth, nHeight, nPlanes, nBitsPerPixel, lpBits);
+ return m_hBitmap;
+ }
+
+#ifndef _WIN32_WCE
+ HBITMAP CreateBitmapIndirect(LPBITMAP lpBitmap)
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::CreateBitmapIndirect(lpBitmap);
+ return m_hBitmap;
+ }
+#endif // !_WIN32_WCE
+
+ HBITMAP CreateCompatibleBitmap(HDC hDC, int nWidth, int nHeight)
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::CreateCompatibleBitmap(hDC, nWidth, nHeight);
+ return m_hBitmap;
+ }
+
+#ifndef _WIN32_WCE
+ HBITMAP CreateDiscardableBitmap(HDC hDC, int nWidth, int nHeight)
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::CreateDiscardableBitmap(hDC, nWidth, nHeight);
+ return m_hBitmap;
+ }
+#endif // !_WIN32_WCE
+
+ BOOL DeleteObject()
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ BOOL bRet = ::DeleteObject(m_hBitmap);
+ if(bRet)
+ m_hBitmap = NULL;
+ return bRet;
+ }
+
+// Attributes
+ int GetBitmap(BITMAP* pBitMap) const
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ return ::GetObject(m_hBitmap, sizeof(BITMAP), pBitMap);
+ }
+
+ bool GetBitmap(BITMAP& bm) const
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ return (::GetObject(m_hBitmap, sizeof(BITMAP), &bm) == sizeof(BITMAP));
+ }
+
+ bool GetSize(SIZE& size) const
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ BITMAP bm = { 0 };
+ if(!GetBitmap(&bm))
+ return false;
+ size.cx = bm.bmWidth;
+ size.cy = bm.bmHeight;
+ return true;
+ }
+
+#ifndef _WIN32_WCE
+ DWORD GetBitmapBits(DWORD dwCount, LPVOID lpBits) const
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ return ::GetBitmapBits(m_hBitmap, dwCount, lpBits);
+ }
+#endif // !_WIN32_WCE
+
+#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 410)
+ DWORD SetBitmapBits(DWORD dwCount, const void* lpBits)
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ return ::SetBitmapBits(m_hBitmap, dwCount, lpBits);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 410)
+
+#ifndef _WIN32_WCE
+ BOOL GetBitmapDimension(LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ return ::GetBitmapDimensionEx(m_hBitmap, lpSize);
+ }
+
+ BOOL SetBitmapDimension(int nWidth, int nHeight, LPSIZE lpSize = NULL)
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ return ::SetBitmapDimensionEx(m_hBitmap, nWidth, nHeight, lpSize);
+ }
+
+// DIB support
+ HBITMAP CreateDIBitmap(HDC hDC, CONST BITMAPINFOHEADER* lpbmih, DWORD dwInit, CONST VOID* lpbInit, CONST BITMAPINFO* lpbmi, UINT uColorUse)
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::CreateDIBitmap(hDC, lpbmih, dwInit, lpbInit, lpbmi, uColorUse);
+ return m_hBitmap;
+ }
+#endif // !_WIN32_WCE
+
+ HBITMAP CreateDIBSection(HDC hDC, CONST BITMAPINFO* lpbmi, UINT uColorUse, VOID** ppvBits, HANDLE hSection, DWORD dwOffset)
+ {
+ ATLASSERT(m_hBitmap == NULL);
+ m_hBitmap = ::CreateDIBSection(hDC, lpbmi, uColorUse, ppvBits, hSection, dwOffset);
+ return m_hBitmap;
+ }
+
+#ifndef _WIN32_WCE
+ int GetDIBits(HDC hDC, UINT uStartScan, UINT cScanLines, LPVOID lpvBits, LPBITMAPINFO lpbmi, UINT uColorUse) const
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ return ::GetDIBits(hDC, m_hBitmap, uStartScan, cScanLines, lpvBits, lpbmi, uColorUse);
+ }
+
+ int SetDIBits(HDC hDC, UINT uStartScan, UINT cScanLines, CONST VOID* lpvBits, CONST BITMAPINFO* lpbmi, UINT uColorUse)
+ {
+ ATLASSERT(m_hBitmap != NULL);
+ return ::SetDIBits(hDC, m_hBitmap, uStartScan, cScanLines, lpvBits, lpbmi, uColorUse);
+ }
+#endif // !_WIN32_WCE
+};
+
+typedef CBitmapT<false> CBitmapHandle;
+typedef CBitmapT<true> CBitmap;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPalette
+
+template <bool t_bManaged>
+class CPaletteT
+{
+public:
+// Data members
+ HPALETTE m_hPalette;
+
+// Constructor/destructor/operators
+ CPaletteT(HPALETTE hPalette = NULL) : m_hPalette(hPalette)
+ { }
+
+ ~CPaletteT()
+ {
+ if(t_bManaged && m_hPalette != NULL)
+ DeleteObject();
+ }
+
+ CPaletteT<t_bManaged>& operator =(HPALETTE hPalette)
+ {
+ Attach(hPalette);
+ return *this;
+ }
+
+ void Attach(HPALETTE hPalette)
+ {
+ if(t_bManaged && m_hPalette != NULL && m_hPalette != hPalette)
+ ::DeleteObject(m_hPalette);
+ m_hPalette = hPalette;
+ }
+
+ HPALETTE Detach()
+ {
+ HPALETTE hPalette = m_hPalette;
+ m_hPalette = NULL;
+ return hPalette;
+ }
+
+ operator HPALETTE() const { return m_hPalette; }
+
+ bool IsNull() const { return (m_hPalette == NULL); }
+
+// Create methods
+ HPALETTE CreatePalette(LPLOGPALETTE lpLogPalette)
+ {
+ ATLASSERT(m_hPalette == NULL);
+ m_hPalette = ::CreatePalette(lpLogPalette);
+ return m_hPalette;
+ }
+
+#ifndef _WIN32_WCE
+ HPALETTE CreateHalftonePalette(HDC hDC)
+ {
+ ATLASSERT(m_hPalette == NULL);
+ ATLASSERT(hDC != NULL);
+ m_hPalette = ::CreateHalftonePalette(hDC);
+ return m_hPalette;
+ }
+#endif // !_WIN32_WCE
+
+ BOOL DeleteObject()
+ {
+ ATLASSERT(m_hPalette != NULL);
+ BOOL bRet = ::DeleteObject(m_hPalette);
+ if(bRet)
+ m_hPalette = NULL;
+ return bRet;
+ }
+
+// Attributes
+ int GetEntryCount() const
+ {
+ ATLASSERT(m_hPalette != NULL);
+ WORD nEntries = 0;
+ ::GetObject(m_hPalette, sizeof(WORD), &nEntries);
+ return (int)nEntries;
+ }
+
+ UINT GetPaletteEntries(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors) const
+ {
+ ATLASSERT(m_hPalette != NULL);
+ return ::GetPaletteEntries(m_hPalette, nStartIndex, nNumEntries, lpPaletteColors);
+ }
+
+ UINT SetPaletteEntries(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors)
+ {
+ ATLASSERT(m_hPalette != NULL);
+ return ::SetPaletteEntries(m_hPalette, nStartIndex, nNumEntries, lpPaletteColors);
+ }
+
+// Operations
+#ifndef _WIN32_WCE
+ void AnimatePalette(UINT nStartIndex, UINT nNumEntries, LPPALETTEENTRY lpPaletteColors)
+ {
+ ATLASSERT(m_hPalette != NULL);
+ ::AnimatePalette(m_hPalette, nStartIndex, nNumEntries, lpPaletteColors);
+ }
+
+ BOOL ResizePalette(UINT nNumEntries)
+ {
+ ATLASSERT(m_hPalette != NULL);
+ return ::ResizePalette(m_hPalette, nNumEntries);
+ }
+#endif // !_WIN32_WCE
+
+ UINT GetNearestPaletteIndex(COLORREF crColor) const
+ {
+ ATLASSERT(m_hPalette != NULL);
+ return ::GetNearestPaletteIndex(m_hPalette, crColor);
+ }
+};
+
+typedef CPaletteT<false> CPaletteHandle;
+typedef CPaletteT<true> CPalette;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRgn
+
+template <bool t_bManaged>
+class CRgnT
+{
+public:
+// Data members
+ HRGN m_hRgn;
+
+// Constructor/destructor/operators
+ CRgnT(HRGN hRgn = NULL) : m_hRgn(hRgn)
+ { }
+
+ ~CRgnT()
+ {
+ if(t_bManaged && m_hRgn != NULL)
+ DeleteObject();
+ }
+
+ CRgnT<t_bManaged>& operator =(HRGN hRgn)
+ {
+ Attach(hRgn);
+ return *this;
+ }
+
+ void Attach(HRGN hRgn)
+ {
+ if(t_bManaged && m_hRgn != NULL && m_hRgn != hRgn)
+ ::DeleteObject(m_hRgn);
+ m_hRgn = hRgn;
+ }
+
+ HRGN Detach()
+ {
+ HRGN hRgn = m_hRgn;
+ m_hRgn = NULL;
+ return hRgn;
+ }
+
+ operator HRGN() const { return m_hRgn; }
+
+ bool IsNull() const { return (m_hRgn == NULL); }
+
+// Create methods
+ HRGN CreateRectRgn(int x1, int y1, int x2, int y2)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ m_hRgn = ::CreateRectRgn(x1, y1, x2, y2);
+ return m_hRgn;
+ }
+
+ HRGN CreateRectRgnIndirect(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ m_hRgn = ::CreateRectRgnIndirect(lpRect);
+ return m_hRgn;
+ }
+
+#ifndef _WIN32_WCE
+ HRGN CreateEllipticRgn(int x1, int y1, int x2, int y2)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ m_hRgn = ::CreateEllipticRgn(x1, y1, x2, y2);
+ return m_hRgn;
+ }
+
+ HRGN CreateEllipticRgnIndirect(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ m_hRgn = ::CreateEllipticRgnIndirect(lpRect);
+ return m_hRgn;
+ }
+
+ HRGN CreatePolygonRgn(LPPOINT lpPoints, int nCount, int nMode)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ m_hRgn = ::CreatePolygonRgn(lpPoints, nCount, nMode);
+ return m_hRgn;
+ }
+
+ HRGN CreatePolyPolygonRgn(LPPOINT lpPoints, LPINT lpPolyCounts, int nCount, int nPolyFillMode)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ m_hRgn = ::CreatePolyPolygonRgn(lpPoints, lpPolyCounts, nCount, nPolyFillMode);
+ return m_hRgn;
+ }
+
+ HRGN CreateRoundRectRgn(int x1, int y1, int x2, int y2, int x3, int y3)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ m_hRgn = ::CreateRoundRectRgn(x1, y1, x2, y2, x3, y3);
+ return m_hRgn;
+ }
+
+ HRGN CreateFromPath(HDC hDC)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ ATLASSERT(hDC != NULL);
+ m_hRgn = ::PathToRegion(hDC);
+ return m_hRgn;
+ }
+
+ HRGN CreateFromData(const XFORM* lpXForm, int nCount, const RGNDATA* pRgnData)
+ {
+ ATLASSERT(m_hRgn == NULL);
+ m_hRgn = ::ExtCreateRegion(lpXForm, nCount, pRgnData);
+ return m_hRgn;
+ }
+#endif // !_WIN32_WCE
+
+ BOOL DeleteObject()
+ {
+ ATLASSERT(m_hRgn != NULL);
+ BOOL bRet = ::DeleteObject(m_hRgn);
+ if(bRet)
+ m_hRgn = NULL;
+ return bRet;
+ }
+
+// Operations
+ void SetRectRgn(int x1, int y1, int x2, int y2)
+ {
+ ATLASSERT(m_hRgn != NULL);
+ ::SetRectRgn(m_hRgn, x1, y1, x2, y2);
+ }
+
+ void SetRectRgn(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hRgn != NULL);
+ ::SetRectRgn(m_hRgn, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom);
+ }
+
+ int CombineRgn(HRGN hRgnSrc1, HRGN hRgnSrc2, int nCombineMode)
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::CombineRgn(m_hRgn, hRgnSrc1, hRgnSrc2, nCombineMode);
+ }
+
+ int CombineRgn(HRGN hRgnSrc, int nCombineMode)
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::CombineRgn(m_hRgn, m_hRgn, hRgnSrc, nCombineMode);
+ }
+
+ int CopyRgn(HRGN hRgnSrc)
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::CombineRgn(m_hRgn, hRgnSrc, NULL, RGN_COPY);
+ }
+
+ BOOL EqualRgn(HRGN hRgn) const
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::EqualRgn(m_hRgn, hRgn);
+ }
+
+ int OffsetRgn(int x, int y)
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::OffsetRgn(m_hRgn, x, y);
+ }
+
+ int OffsetRgn(POINT point)
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::OffsetRgn(m_hRgn, point.x, point.y);
+ }
+
+ int GetRgnBox(LPRECT lpRect) const
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::GetRgnBox(m_hRgn, lpRect);
+ }
+
+ BOOL PtInRegion(int x, int y) const
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::PtInRegion(m_hRgn, x, y);
+ }
+
+ BOOL PtInRegion(POINT point) const
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::PtInRegion(m_hRgn, point.x, point.y);
+ }
+
+ BOOL RectInRegion(LPCRECT lpRect) const
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return ::RectInRegion(m_hRgn, lpRect);
+ }
+
+ int GetRegionData(LPRGNDATA lpRgnData, int nDataSize) const
+ {
+ ATLASSERT(m_hRgn != NULL);
+ return (int)::GetRegionData(m_hRgn, nDataSize, lpRgnData);
+ }
+};
+
+typedef CRgnT<false> CRgnHandle;
+typedef CRgnT<true> CRgn;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDC - The device context class
+
+template <bool t_bManaged>
+class CDCT
+{
+public:
+// Data members
+ HDC m_hDC;
+
+// Constructor/destructor/operators
+ CDCT(HDC hDC = NULL) : m_hDC(hDC)
+ {
+ }
+
+ ~CDCT()
+ {
+ if(t_bManaged && m_hDC != NULL)
+ ::DeleteDC(Detach());
+ }
+
+ CDCT<t_bManaged>& operator =(HDC hDC)
+ {
+ Attach(hDC);
+ return *this;
+ }
+
+ void Attach(HDC hDC)
+ {
+ if(t_bManaged && m_hDC != NULL && m_hDC != hDC)
+ ::DeleteDC(m_hDC);
+ m_hDC = hDC;
+ }
+
+ HDC Detach()
+ {
+ HDC hDC = m_hDC;
+ m_hDC = NULL;
+ return hDC;
+ }
+
+ operator HDC() const { return m_hDC; }
+
+ bool IsNull() const { return (m_hDC == NULL); }
+
+// Operations
+#ifndef _WIN32_WCE
+ HWND WindowFromDC() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::WindowFromDC(m_hDC);
+ }
+#endif // !_WIN32_WCE
+
+ CPenHandle GetCurrentPen() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return CPenHandle((HPEN)::GetCurrentObject(m_hDC, OBJ_PEN));
+ }
+
+ CBrushHandle GetCurrentBrush() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return CBrushHandle((HBRUSH)::GetCurrentObject(m_hDC, OBJ_BRUSH));
+ }
+
+ CPaletteHandle GetCurrentPalette() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return CPaletteHandle((HPALETTE)::GetCurrentObject(m_hDC, OBJ_PAL));
+ }
+
+ CFontHandle GetCurrentFont() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return CFontHandle((HFONT)::GetCurrentObject(m_hDC, OBJ_FONT));
+ }
+
+ CBitmapHandle GetCurrentBitmap() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return CBitmapHandle((HBITMAP)::GetCurrentObject(m_hDC, OBJ_BITMAP));
+ }
+
+ HDC CreateDC(LPCTSTR lpszDriverName, LPCTSTR lpszDeviceName, LPCTSTR lpszOutput, const DEVMODE* lpInitData)
+ {
+ ATLASSERT(m_hDC == NULL);
+ m_hDC = ::CreateDC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData);
+ return m_hDC;
+ }
+
+ HDC CreateCompatibleDC(HDC hDC = NULL)
+ {
+ ATLASSERT(m_hDC == NULL);
+ m_hDC = ::CreateCompatibleDC(hDC);
+ return m_hDC;
+ }
+
+ BOOL DeleteDC()
+ {
+ if(m_hDC == NULL)
+ return FALSE;
+ BOOL bRet = ::DeleteDC(m_hDC);
+ if(bRet)
+ m_hDC = NULL;
+ return bRet;
+ }
+
+// Device-Context Functions
+ int SaveDC()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SaveDC(m_hDC);
+ }
+
+ BOOL RestoreDC(int nSavedDC)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::RestoreDC(m_hDC, nSavedDC);
+ }
+
+ int GetDeviceCaps(int nIndex) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetDeviceCaps(m_hDC, nIndex);
+ }
+
+#ifndef _WIN32_WCE
+ UINT SetBoundsRect(LPCRECT lpRectBounds, UINT flags)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetBoundsRect(m_hDC, lpRectBounds, flags);
+ }
+
+ UINT GetBoundsRect(LPRECT lpRectBounds, UINT flags) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetBoundsRect(m_hDC, lpRectBounds, flags);
+ }
+
+ BOOL ResetDC(const DEVMODE* lpDevMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ResetDC(m_hDC, lpDevMode) != NULL;
+ }
+
+// Drawing-Tool Functions
+ BOOL GetBrushOrg(LPPOINT lpPoint) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetBrushOrgEx(m_hDC, lpPoint);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL SetBrushOrg(int x, int y, LPPOINT lpPoint = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetBrushOrgEx(m_hDC, x, y, lpPoint);
+ }
+
+ BOOL SetBrushOrg(POINT point, LPPOINT lpPointRet = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetBrushOrgEx(m_hDC, point.x, point.y, lpPointRet);
+ }
+
+#ifndef _WIN32_WCE
+ int EnumObjects(int nObjectType, int (CALLBACK* lpfn)(LPVOID, LPARAM), LPARAM lpData)
+ {
+ ATLASSERT(m_hDC != NULL);
+#ifdef STRICT
+ return ::EnumObjects(m_hDC, nObjectType, (GOBJENUMPROC)lpfn, lpData);
+#else
+ return ::EnumObjects(m_hDC, nObjectType, (GOBJENUMPROC)lpfn, (LPVOID)lpData);
+#endif
+ }
+#endif // !_WIN32_WCE
+
+// Type-safe selection helpers
+ HPEN SelectPen(HPEN hPen)
+ {
+ ATLASSERT(m_hDC != NULL);
+#ifndef _WIN32_WCE
+ ATLASSERT(hPen == NULL || ::GetObjectType(hPen) == OBJ_PEN || ::GetObjectType(hPen) == OBJ_EXTPEN);
+#else // CE specific
+ ATLASSERT(hPen == NULL || ::GetObjectType(hPen) == OBJ_PEN);
+#endif // _WIN32_WCE
+ return (HPEN)::SelectObject(m_hDC, hPen);
+ }
+
+ HBRUSH SelectBrush(HBRUSH hBrush)
+ {
+ ATLASSERT(m_hDC != NULL);
+ ATLASSERT(hBrush == NULL || ::GetObjectType(hBrush) == OBJ_BRUSH);
+ return (HBRUSH)::SelectObject(m_hDC, hBrush);
+ }
+
+ HFONT SelectFont(HFONT hFont)
+ {
+ ATLASSERT(m_hDC != NULL);
+ ATLASSERT(hFont == NULL || ::GetObjectType(hFont) == OBJ_FONT);
+ return (HFONT)::SelectObject(m_hDC, hFont);
+ }
+
+ HBITMAP SelectBitmap(HBITMAP hBitmap)
+ {
+ ATLASSERT(m_hDC != NULL);
+ ATLASSERT(hBitmap == NULL || ::GetObjectType(hBitmap) == OBJ_BITMAP);
+ return (HBITMAP)::SelectObject(m_hDC, hBitmap);
+ }
+
+ int SelectRgn(HRGN hRgn) // special return for regions
+ {
+ ATLASSERT(m_hDC != NULL);
+ ATLASSERT(hRgn == NULL || ::GetObjectType(hRgn) == OBJ_REGION);
+ return PtrToInt(::SelectObject(m_hDC, hRgn));
+ }
+
+// Type-safe selection helpers for stock objects
+ HPEN SelectStockPen(int nPen)
+ {
+ ATLASSERT(m_hDC != NULL);
+#if (_WIN32_WINNT >= 0x0500)
+ ATLASSERT(nPen == WHITE_PEN || nPen == BLACK_PEN || nPen == NULL_PEN || nPen == DC_PEN);
+#else
+ ATLASSERT(nPen == WHITE_PEN || nPen == BLACK_PEN || nPen == NULL_PEN);
+#endif // !(_WIN32_WINNT >= 0x0500)
+ return SelectPen((HPEN)::GetStockObject(nPen));
+ }
+
+ HBRUSH SelectStockBrush(int nBrush)
+ {
+#if (_WIN32_WINNT >= 0x0500)
+ ATLASSERT((nBrush >= WHITE_BRUSH && nBrush <= HOLLOW_BRUSH) || nBrush == DC_BRUSH);
+#else
+ ATLASSERT(nBrush >= WHITE_BRUSH && nBrush <= HOLLOW_BRUSH);
+#endif // !(_WIN32_WINNT >= 0x0500)
+ return SelectBrush((HBRUSH)::GetStockObject(nBrush));
+ }
+
+ HFONT SelectStockFont(int nFont)
+ {
+#ifndef _WIN32_WCE
+ ATLASSERT((nFont >= OEM_FIXED_FONT && nFont <= SYSTEM_FIXED_FONT) || nFont == DEFAULT_GUI_FONT);
+#else // CE specific
+ ATLASSERT(nFont == SYSTEM_FONT);
+#endif // _WIN32_WCE
+ return SelectFont((HFONT)::GetStockObject(nFont));
+ }
+
+ HPALETTE SelectStockPalette(int nPalette, BOOL bForceBackground)
+ {
+ ATLASSERT(nPalette == DEFAULT_PALETTE); // the only one supported
+ return SelectPalette((HPALETTE)::GetStockObject(nPalette), bForceBackground);
+ }
+
+// Color and Color Palette Functions
+ COLORREF GetNearestColor(COLORREF crColor) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetNearestColor(m_hDC, crColor);
+ }
+
+ HPALETTE SelectPalette(HPALETTE hPalette, BOOL bForceBackground)
+ {
+ ATLASSERT(m_hDC != NULL);
+
+ return ::SelectPalette(m_hDC, hPalette, bForceBackground);
+ }
+
+ UINT RealizePalette()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::RealizePalette(m_hDC);
+ }
+
+#ifndef _WIN32_WCE
+ void UpdateColors()
+ {
+ ATLASSERT(m_hDC != NULL);
+ ::UpdateColors(m_hDC);
+ }
+#endif // !_WIN32_WCE
+
+// Drawing-Attribute Functions
+ COLORREF GetBkColor() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetBkColor(m_hDC);
+ }
+
+ int GetBkMode() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetBkMode(m_hDC);
+ }
+
+#ifndef _WIN32_WCE
+ int GetPolyFillMode() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetPolyFillMode(m_hDC);
+ }
+
+ int GetROP2() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetROP2(m_hDC);
+ }
+
+ int GetStretchBltMode() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetStretchBltMode(m_hDC);
+ }
+#endif // !_WIN32_WCE
+
+ COLORREF GetTextColor() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextColor(m_hDC);
+ }
+
+ COLORREF SetBkColor(COLORREF crColor)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetBkColor(m_hDC, crColor);
+ }
+
+ int SetBkMode(int nBkMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetBkMode(m_hDC, nBkMode);
+ }
+
+#ifndef _WIN32_WCE
+ int SetPolyFillMode(int nPolyFillMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetPolyFillMode(m_hDC, nPolyFillMode);
+ }
+#endif // !_WIN32_WCE
+
+ int SetROP2(int nDrawMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetROP2(m_hDC, nDrawMode);
+ }
+
+#ifndef _WIN32_WCE
+ int SetStretchBltMode(int nStretchMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetStretchBltMode(m_hDC, nStretchMode);
+ }
+#endif // !_WIN32_WCE
+
+ COLORREF SetTextColor(COLORREF crColor)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetTextColor(m_hDC, crColor);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetColorAdjustment(LPCOLORADJUSTMENT lpColorAdjust) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetColorAdjustment(m_hDC, lpColorAdjust);
+ }
+
+ BOOL SetColorAdjustment(const COLORADJUSTMENT* lpColorAdjust)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetColorAdjustment(m_hDC, lpColorAdjust);
+ }
+
+// Mapping Functions
+ int GetMapMode() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetMapMode(m_hDC);
+ }
+
+ BOOL GetViewportOrg(LPPOINT lpPoint) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetViewportOrgEx(m_hDC, lpPoint);
+ }
+
+ int SetMapMode(int nMapMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetMapMode(m_hDC, nMapMode);
+ }
+#endif // !_WIN32_WCE
+
+ // Viewport Origin
+ BOOL SetViewportOrg(int x, int y, LPPOINT lpPoint = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetViewportOrgEx(m_hDC, x, y, lpPoint);
+ }
+
+ BOOL SetViewportOrg(POINT point, LPPOINT lpPointRet = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return SetViewportOrg(point.x, point.y, lpPointRet);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL OffsetViewportOrg(int nWidth, int nHeight, LPPOINT lpPoint = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::OffsetViewportOrgEx(m_hDC, nWidth, nHeight, lpPoint);
+ }
+
+ // Viewport Extent
+ BOOL GetViewportExt(LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetViewportExtEx(m_hDC, lpSize);
+ }
+
+ BOOL SetViewportExt(int x, int y, LPSIZE lpSize = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetViewportExtEx(m_hDC, x, y, lpSize);
+ }
+
+ BOOL SetViewportExt(SIZE size, LPSIZE lpSizeRet = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return SetViewportExt(size.cx, size.cy, lpSizeRet);
+ }
+
+ BOOL ScaleViewportExt(int xNum, int xDenom, int yNum, int yDenom, LPSIZE lpSize = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ScaleViewportExtEx(m_hDC, xNum, xDenom, yNum, yDenom, lpSize);
+ }
+#endif // !_WIN32_WCE
+
+ // Window Origin
+#ifndef _WIN32_WCE
+ BOOL GetWindowOrg(LPPOINT lpPoint) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetWindowOrgEx(m_hDC, lpPoint);
+ }
+
+ BOOL SetWindowOrg(int x, int y, LPPOINT lpPoint = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetWindowOrgEx(m_hDC, x, y, lpPoint);
+ }
+
+ BOOL SetWindowOrg(POINT point, LPPOINT lpPointRet = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return SetWindowOrg(point.x, point.y, lpPointRet);
+ }
+
+ BOOL OffsetWindowOrg(int nWidth, int nHeight, LPPOINT lpPoint = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::OffsetWindowOrgEx(m_hDC, nWidth, nHeight, lpPoint);
+ }
+
+ // Window extent
+ BOOL GetWindowExt(LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetWindowExtEx(m_hDC, lpSize);
+ }
+
+ BOOL SetWindowExt(int x, int y, LPSIZE lpSize = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetWindowExtEx(m_hDC, x, y, lpSize);
+ }
+
+ BOOL SetWindowExt(SIZE size, LPSIZE lpSizeRet = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return SetWindowExt(size.cx, size.cy, lpSizeRet);
+ }
+
+ BOOL ScaleWindowExt(int xNum, int xDenom, int yNum, int yDenom, LPSIZE lpSize = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ScaleWindowExtEx(m_hDC, xNum, xDenom, yNum, yDenom, lpSize);
+ }
+
+// Coordinate Functions
+ BOOL DPtoLP(LPPOINT lpPoints, int nCount = 1) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DPtoLP(m_hDC, lpPoints, nCount);
+ }
+
+ BOOL DPtoLP(LPRECT lpRect) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DPtoLP(m_hDC, (LPPOINT)lpRect, 2);
+ }
+
+ BOOL DPtoLP(LPSIZE lpSize) const
+ {
+ SIZE sizeWinExt = { 0, 0 };
+ if(!GetWindowExt(&sizeWinExt))
+ return FALSE;
+ SIZE sizeVpExt = { 0, 0 };
+ if(!GetViewportExt(&sizeVpExt))
+ return FALSE;
+ lpSize->cx = ::MulDiv(lpSize->cx, abs(sizeWinExt.cx), abs(sizeVpExt.cx));
+ lpSize->cy = ::MulDiv(lpSize->cy, abs(sizeWinExt.cy), abs(sizeVpExt.cy));
+ return TRUE;
+ }
+
+ BOOL LPtoDP(LPPOINT lpPoints, int nCount = 1) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::LPtoDP(m_hDC, lpPoints, nCount);
+ }
+
+ BOOL LPtoDP(LPRECT lpRect) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::LPtoDP(m_hDC, (LPPOINT)lpRect, 2);
+ }
+
+ BOOL LPtoDP(LPSIZE lpSize) const
+ {
+ SIZE sizeWinExt = { 0, 0 };
+ if(!GetWindowExt(&sizeWinExt))
+ return FALSE;
+ SIZE sizeVpExt = { 0, 0 };
+ if(!GetViewportExt(&sizeVpExt))
+ return FALSE;
+ lpSize->cx = ::MulDiv(lpSize->cx, abs(sizeVpExt.cx), abs(sizeWinExt.cx));
+ lpSize->cy = ::MulDiv(lpSize->cy, abs(sizeVpExt.cy), abs(sizeWinExt.cy));
+ return TRUE;
+ }
+
+// Special Coordinate Functions (useful for dealing with metafiles and OLE)
+ #define HIMETRIC_INCH 2540 // HIMETRIC units per inch
+
+ void DPtoHIMETRIC(LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ int nMapMode;
+ if((nMapMode = GetMapMode()) < MM_ISOTROPIC && nMapMode != MM_TEXT)
+ {
+ // when using a constrained map mode, map against physical inch
+ ((CDCHandle*)this)->SetMapMode(MM_HIMETRIC);
+ DPtoLP(lpSize);
+ ((CDCHandle*)this)->SetMapMode(nMapMode);
+ }
+ else
+ {
+ // map against logical inch for non-constrained mapping modes
+ int cxPerInch = GetDeviceCaps(LOGPIXELSX);
+ int cyPerInch = GetDeviceCaps(LOGPIXELSY);
+ ATLASSERT(cxPerInch != 0 && cyPerInch != 0);
+ lpSize->cx = ::MulDiv(lpSize->cx, HIMETRIC_INCH, cxPerInch);
+ lpSize->cy = ::MulDiv(lpSize->cy, HIMETRIC_INCH, cyPerInch);
+ }
+ }
+
+ void HIMETRICtoDP(LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ int nMapMode;
+ if((nMapMode = GetMapMode()) < MM_ISOTROPIC && nMapMode != MM_TEXT)
+ {
+ // when using a constrained map mode, map against physical inch
+ ((CDCHandle*)this)->SetMapMode(MM_HIMETRIC);
+ LPtoDP(lpSize);
+ ((CDCHandle*)this)->SetMapMode(nMapMode);
+ }
+ else
+ {
+ // map against logical inch for non-constrained mapping modes
+ int cxPerInch = GetDeviceCaps(LOGPIXELSX);
+ int cyPerInch = GetDeviceCaps(LOGPIXELSY);
+ ATLASSERT(cxPerInch != 0 && cyPerInch != 0);
+ lpSize->cx = ::MulDiv(lpSize->cx, cxPerInch, HIMETRIC_INCH);
+ lpSize->cy = ::MulDiv(lpSize->cy, cyPerInch, HIMETRIC_INCH);
+ }
+ }
+
+ void LPtoHIMETRIC(LPSIZE lpSize) const
+ {
+ LPtoDP(lpSize);
+ DPtoHIMETRIC(lpSize);
+ }
+
+ void HIMETRICtoLP(LPSIZE lpSize) const
+ {
+ HIMETRICtoDP(lpSize);
+ DPtoLP(lpSize);
+ }
+#endif // !_WIN32_WCE
+
+// Region Functions
+ BOOL FillRgn(HRGN hRgn, HBRUSH hBrush)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::FillRgn(m_hDC, hRgn, hBrush);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL FrameRgn(HRGN hRgn, HBRUSH hBrush, int nWidth, int nHeight)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::FrameRgn(m_hDC, hRgn, hBrush, nWidth, nHeight);
+ }
+
+ BOOL InvertRgn(HRGN hRgn)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::InvertRgn(m_hDC, hRgn);
+ }
+
+ BOOL PaintRgn(HRGN hRgn)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PaintRgn(m_hDC, hRgn);
+ }
+#endif // !_WIN32_WCE
+
+// Clipping Functions
+ int GetClipBox(LPRECT lpRect) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetClipBox(m_hDC, lpRect);
+ }
+
+ int GetClipRgn(CRgn& region) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ if(region.IsNull())
+ region.CreateRectRgn(0, 0, 0, 0);
+
+ int nRet = ::GetClipRgn(m_hDC, region);
+ if(nRet != 1)
+ region.DeleteObject();
+
+ return nRet;
+ }
+
+#ifndef _WIN32_WCE
+ BOOL PtVisible(int x, int y) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PtVisible(m_hDC, x, y);
+ }
+
+ BOOL PtVisible(POINT point) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PtVisible(m_hDC, point.x, point.y);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL RectVisible(LPCRECT lpRect) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::RectVisible(m_hDC, lpRect);
+ }
+
+ int SelectClipRgn(HRGN hRgn)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SelectClipRgn(m_hDC, (HRGN)hRgn);
+ }
+
+ int ExcludeClipRect(int x1, int y1, int x2, int y2)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ExcludeClipRect(m_hDC, x1, y1, x2, y2);
+ }
+
+ int ExcludeClipRect(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ExcludeClipRect(m_hDC, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom);
+ }
+
+#ifndef _WIN32_WCE
+ int ExcludeUpdateRgn(HWND hWnd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ExcludeUpdateRgn(m_hDC, hWnd);
+ }
+#endif // !_WIN32_WCE
+
+ int IntersectClipRect(int x1, int y1, int x2, int y2)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::IntersectClipRect(m_hDC, x1, y1, x2, y2);
+ }
+
+ int IntersectClipRect(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::IntersectClipRect(m_hDC, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom);
+ }
+
+#ifndef _WIN32_WCE
+ int OffsetClipRgn(int x, int y)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::OffsetClipRgn(m_hDC, x, y);
+ }
+
+ int OffsetClipRgn(SIZE size)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::OffsetClipRgn(m_hDC, size.cx, size.cy);
+ }
+
+ int SelectClipRgn(HRGN hRgn, int nMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ExtSelectClipRgn(m_hDC, hRgn, nMode);
+ }
+#endif // !_WIN32_WCE
+
+// Line-Output Functions
+#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
+ BOOL GetCurrentPosition(LPPOINT lpPoint) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetCurrentPositionEx(m_hDC, lpPoint);
+ }
+
+ BOOL MoveTo(int x, int y, LPPOINT lpPoint = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::MoveToEx(m_hDC, x, y, lpPoint);
+ }
+
+ BOOL MoveTo(POINT point, LPPOINT lpPointRet = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return MoveTo(point.x, point.y, lpPointRet);
+ }
+
+ BOOL LineTo(int x, int y)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::LineTo(m_hDC, x, y);
+ }
+
+ BOOL LineTo(POINT point)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return LineTo(point.x, point.y);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
+
+#ifndef _WIN32_WCE
+ BOOL Arc(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Arc(m_hDC, x1, y1, x2, y2, x3, y3, x4, y4);
+ }
+
+ BOOL Arc(LPCRECT lpRect, POINT ptStart, POINT ptEnd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Arc(m_hDC, lpRect->left, lpRect->top,
+ lpRect->right, lpRect->bottom, ptStart.x, ptStart.y,
+ ptEnd.x, ptEnd.y);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL Polyline(LPPOINT lpPoints, int nCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Polyline(m_hDC, lpPoints, nCount);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL AngleArc(int x, int y, int nRadius, float fStartAngle, float fSweepAngle)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::AngleArc(m_hDC, x, y, nRadius, fStartAngle, fSweepAngle);
+ }
+
+ BOOL ArcTo(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ArcTo(m_hDC, x1, y1, x2, y2, x3, y3, x4, y4);
+ }
+
+ BOOL ArcTo(LPCRECT lpRect, POINT ptStart, POINT ptEnd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ArcTo(lpRect->left, lpRect->top, lpRect->right,
+ lpRect->bottom, ptStart.x, ptStart.y, ptEnd.x, ptEnd.y);
+ }
+
+ int GetArcDirection() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetArcDirection(m_hDC);
+ }
+
+ int SetArcDirection(int nArcDirection)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetArcDirection(m_hDC, nArcDirection);
+ }
+
+ BOOL PolyDraw(const POINT* lpPoints, const BYTE* lpTypes, int nCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PolyDraw(m_hDC, lpPoints, lpTypes, nCount);
+ }
+
+ BOOL PolylineTo(const POINT* lpPoints, int nCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PolylineTo(m_hDC, lpPoints, nCount);
+ }
+
+ BOOL PolyPolyline(const POINT* lpPoints,
+ const DWORD* lpPolyPoints, int nCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PolyPolyline(m_hDC, lpPoints, lpPolyPoints, nCount);
+ }
+
+ BOOL PolyBezier(const POINT* lpPoints, int nCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PolyBezier(m_hDC, lpPoints, nCount);
+ }
+
+ BOOL PolyBezierTo(const POINT* lpPoints, int nCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PolyBezierTo(m_hDC, lpPoints, nCount);
+ }
+#endif // !_WIN32_WCE
+
+// Simple Drawing Functions
+ BOOL FillRect(LPCRECT lpRect, HBRUSH hBrush)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::FillRect(m_hDC, lpRect, hBrush);
+ }
+
+ BOOL FillRect(LPCRECT lpRect, int nColorIndex)
+ {
+ ATLASSERT(m_hDC != NULL);
+#ifndef _WIN32_WCE
+ return ::FillRect(m_hDC, lpRect, (HBRUSH)LongToPtr(nColorIndex + 1));
+#else // CE specific
+ return ::FillRect(m_hDC, lpRect, ::GetSysColorBrush(nColorIndex));
+#endif // _WIN32_WCE
+ }
+
+#ifndef _WIN32_WCE
+ BOOL FrameRect(LPCRECT lpRect, HBRUSH hBrush)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::FrameRect(m_hDC, lpRect, hBrush);
+ }
+#endif // !_WIN32_WCE
+
+#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 420)
+ BOOL InvertRect(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::InvertRect(m_hDC, lpRect);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 420)
+
+ BOOL DrawIcon(int x, int y, HICON hIcon)
+ {
+ ATLASSERT(m_hDC != NULL);
+#ifndef _WIN32_WCE
+ return ::DrawIcon(m_hDC, x, y, hIcon);
+#else // CE specific
+ return ::DrawIconEx(m_hDC, x, y, hIcon, 0, 0, 0, NULL, DI_NORMAL);
+#endif // _WIN32_WCE
+ }
+
+ BOOL DrawIcon(POINT point, HICON hIcon)
+ {
+ ATLASSERT(m_hDC != NULL);
+#ifndef _WIN32_WCE
+ return ::DrawIcon(m_hDC, point.x, point.y, hIcon);
+#else // CE specific
+ return ::DrawIconEx(m_hDC, point.x, point.y, hIcon, 0, 0, 0, NULL, DI_NORMAL);
+#endif // _WIN32_WCE
+ }
+
+ BOOL DrawIconEx(int x, int y, HICON hIcon, int cxWidth, int cyWidth, UINT uStepIfAniCur = 0, HBRUSH hbrFlickerFreeDraw = NULL, UINT uFlags = DI_NORMAL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawIconEx(m_hDC, x, y, hIcon, cxWidth, cyWidth, uStepIfAniCur, hbrFlickerFreeDraw, uFlags);
+ }
+
+ BOOL DrawIconEx(POINT point, HICON hIcon, SIZE size, UINT uStepIfAniCur = 0, HBRUSH hbrFlickerFreeDraw = NULL, UINT uFlags = DI_NORMAL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawIconEx(m_hDC, point.x, point.y, hIcon, size.cx, size.cy, uStepIfAniCur, hbrFlickerFreeDraw, uFlags);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL DrawState(POINT pt, SIZE size, HBITMAP hBitmap, UINT nFlags, HBRUSH hBrush = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawState(m_hDC, hBrush, NULL, (LPARAM)hBitmap, 0, pt.x, pt.y, size.cx, size.cy, nFlags | DST_BITMAP);
+ }
+
+ BOOL DrawState(POINT pt, SIZE size, HICON hIcon, UINT nFlags, HBRUSH hBrush = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawState(m_hDC, hBrush, NULL, (LPARAM)hIcon, 0, pt.x, pt.y, size.cx, size.cy, nFlags | DST_ICON);
+ }
+
+ BOOL DrawState(POINT pt, SIZE size, LPCTSTR lpszText, UINT nFlags, BOOL bPrefixText = TRUE, int nTextLen = 0, HBRUSH hBrush = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawState(m_hDC, hBrush, NULL, (LPARAM)lpszText, (WPARAM)nTextLen, pt.x, pt.y, size.cx, size.cy, nFlags | (bPrefixText ? DST_PREFIXTEXT : DST_TEXT));
+ }
+
+ BOOL DrawState(POINT pt, SIZE size, DRAWSTATEPROC lpDrawProc, LPARAM lData, UINT nFlags, HBRUSH hBrush = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawState(m_hDC, hBrush, lpDrawProc, lData, 0, pt.x, pt.y, size.cx, size.cy, nFlags | DST_COMPLEX);
+ }
+#endif // !_WIN32_WCE
+
+// Ellipse and Polygon Functions
+#ifndef _WIN32_WCE
+ BOOL Chord(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Chord(m_hDC, x1, y1, x2, y2, x3, y3, x4, y4);
+ }
+
+ BOOL Chord(LPCRECT lpRect, POINT ptStart, POINT ptEnd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Chord(m_hDC, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom, ptStart.x, ptStart.y, ptEnd.x, ptEnd.y);
+ }
+#endif // !_WIN32_WCE
+
+ void DrawFocusRect(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hDC != NULL);
+ ::DrawFocusRect(m_hDC, lpRect);
+ }
+
+ BOOL Ellipse(int x1, int y1, int x2, int y2)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Ellipse(m_hDC, x1, y1, x2, y2);
+ }
+
+ BOOL Ellipse(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Ellipse(m_hDC, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL Pie(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Pie(m_hDC, x1, y1, x2, y2, x3, y3, x4, y4);
+ }
+
+ BOOL Pie(LPCRECT lpRect, POINT ptStart, POINT ptEnd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Pie(m_hDC, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom, ptStart.x, ptStart.y, ptEnd.x, ptEnd.y);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL Polygon(LPPOINT lpPoints, int nCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Polygon(m_hDC, lpPoints, nCount);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL PolyPolygon(LPPOINT lpPoints, LPINT lpPolyCounts, int nCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PolyPolygon(m_hDC, lpPoints, lpPolyCounts, nCount);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL Rectangle(int x1, int y1, int x2, int y2)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Rectangle(m_hDC, x1, y1, x2, y2);
+ }
+
+ BOOL Rectangle(LPCRECT lpRect)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Rectangle(m_hDC, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom);
+ }
+
+ BOOL RoundRect(int x1, int y1, int x2, int y2, int x3, int y3)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::RoundRect(m_hDC, x1, y1, x2, y2, x3, y3);
+ }
+
+ BOOL RoundRect(LPCRECT lpRect, POINT point)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::RoundRect(m_hDC, lpRect->left, lpRect->top, lpRect->right, lpRect->bottom, point.x, point.y);
+ }
+
+// Bitmap Functions
+ BOOL PatBlt(int x, int y, int nWidth, int nHeight, DWORD dwRop)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PatBlt(m_hDC, x, y, nWidth, nHeight, dwRop);
+ }
+
+ BOOL BitBlt(int x, int y, int nWidth, int nHeight, HDC hSrcDC,
+ int xSrc, int ySrc, DWORD dwRop)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::BitBlt(m_hDC, x, y, nWidth, nHeight, hSrcDC, xSrc, ySrc, dwRop);
+ }
+
+ BOOL StretchBlt(int x, int y, int nWidth, int nHeight, HDC hSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, DWORD dwRop)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::StretchBlt(m_hDC, x, y, nWidth, nHeight, hSrcDC, xSrc, ySrc, nSrcWidth, nSrcHeight, dwRop);
+ }
+
+ COLORREF GetPixel(int x, int y) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetPixel(m_hDC, x, y);
+ }
+
+ COLORREF GetPixel(POINT point) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetPixel(m_hDC, point.x, point.y);
+ }
+
+ COLORREF SetPixel(int x, int y, COLORREF crColor)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetPixel(m_hDC, x, y, crColor);
+ }
+
+ COLORREF SetPixel(POINT point, COLORREF crColor)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetPixel(m_hDC, point.x, point.y, crColor);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL FloodFill(int x, int y, COLORREF crColor)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::FloodFill(m_hDC, x, y, crColor);
+ }
+
+ BOOL ExtFloodFill(int x, int y, COLORREF crColor, UINT nFillType)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ExtFloodFill(m_hDC, x, y, crColor, nFillType);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL MaskBlt(int x, int y, int nWidth, int nHeight, HDC hSrcDC, int xSrc, int ySrc, HBITMAP hMaskBitmap, int xMask, int yMask, DWORD dwRop)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::MaskBlt(m_hDC, x, y, nWidth, nHeight, hSrcDC, xSrc, ySrc, hMaskBitmap, xMask, yMask, dwRop);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL PlgBlt(LPPOINT lpPoint, HDC hSrcDC, int xSrc, int ySrc, int nWidth, int nHeight, HBITMAP hMaskBitmap, int xMask, int yMask)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PlgBlt(m_hDC, lpPoint, hSrcDC, xSrc, ySrc, nWidth, nHeight, hMaskBitmap, xMask, yMask);
+ }
+
+ BOOL SetPixelV(int x, int y, COLORREF crColor)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetPixelV(m_hDC, x, y, crColor);
+ }
+
+ BOOL SetPixelV(POINT point, COLORREF crColor)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetPixelV(m_hDC, point.x, point.y, crColor);
+ }
+#endif // !_WIN32_WCE
+
+#if !defined(_ATL_NO_MSIMG) || defined(_WIN32_WCE)
+#ifndef _WIN32_WCE
+ BOOL TransparentBlt(int x, int y, int nWidth, int nHeight, HDC hSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, UINT crTransparent)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::TransparentBlt(m_hDC, x, y, nWidth, nHeight, hSrcDC, xSrc, ySrc, nSrcWidth, nSrcHeight, crTransparent);
+ }
+#else // CE specific
+ BOOL TransparentImage(int x, int y, int nWidth, int nHeight, HDC hSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, UINT crTransparent)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::TransparentImage(m_hDC, x, y, nWidth, nHeight, hSrcDC, xSrc, ySrc, nSrcWidth, nSrcHeight, crTransparent);
+ }
+#endif // _WIN32_WCE
+
+#if (!defined(_WIN32_WCE) || (_WIN32_WCE >= 420))
+ BOOL GradientFill(const PTRIVERTEX pVertices, DWORD nVertices, void* pMeshElements, DWORD nMeshElements, DWORD dwMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GradientFill(m_hDC, pVertices, nVertices, pMeshElements, nMeshElements, dwMode);
+ }
+
+ BOOL GradientFillRect(RECT& rect, COLORREF clr1, COLORREF clr2, bool bHorizontal)
+ {
+ ATLASSERT(m_hDC != NULL);
+
+ TRIVERTEX arrTvx[2] = { { 0 }, { 0 } };
+
+ arrTvx[0].x = rect.left;
+ arrTvx[0].y = rect.top;
+ arrTvx[0].Red = MAKEWORD(0, GetRValue(clr1));
+ arrTvx[0].Green = MAKEWORD(0, GetGValue(clr1));
+ arrTvx[0].Blue = MAKEWORD(0, GetBValue(clr1));
+ arrTvx[0].Alpha = 0;
+
+ arrTvx[1].x = rect.right;
+ arrTvx[1].y = rect.bottom;
+ arrTvx[1].Red = MAKEWORD(0, GetRValue(clr2));
+ arrTvx[1].Green = MAKEWORD(0, GetGValue(clr2));
+ arrTvx[1].Blue = MAKEWORD(0, GetBValue(clr2));
+ arrTvx[1].Alpha = 0;
+
+ GRADIENT_RECT gr = { 0, 1 };
+
+ return ::GradientFill(m_hDC, arrTvx, 2, &gr, 1, bHorizontal ? GRADIENT_FILL_RECT_H : GRADIENT_FILL_RECT_V);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 420)
+
+#if !defined(_WIN32_WCE) || (_WIN32_WCE > 0x500)
+ BOOL AlphaBlend(int x, int y, int nWidth, int nHeight, HDC hSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, BLENDFUNCTION bf)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::AlphaBlend(m_hDC, x, y, nWidth, nHeight, hSrcDC, xSrc, ySrc, nSrcWidth, nSrcHeight, bf);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE > 0x500)
+#endif // !defined(_ATL_NO_MSIMG) || defined(_WIN32_WCE)
+
+// Extra bitmap functions
+ // Helper function for painting a disabled toolbar or menu bitmap
+ // This function can take either an HBITMAP (for SS) or a DC with
+ // the bitmap already painted (for cmdbar)
+ BOOL DitherBlt(int x, int y, int nWidth, int nHeight, HDC hSrcDC, HBITMAP hBitmap, int xSrc, int ySrc,
+ HBRUSH hBrushBackground = ::GetSysColorBrush(COLOR_3DFACE),
+ HBRUSH hBrush3DEffect = ::GetSysColorBrush(COLOR_3DHILIGHT),
+ HBRUSH hBrushDisabledImage = ::GetSysColorBrush(COLOR_3DSHADOW))
+ {
+ ATLASSERT(m_hDC != NULL || hBitmap != NULL);
+ ATLASSERT(nWidth > 0 && nHeight > 0);
+
+ // Create a generic DC for all BitBlts
+ CDCHandle dc = (hSrcDC != NULL) ? hSrcDC : ::CreateCompatibleDC(m_hDC);
+ ATLASSERT(dc.m_hDC != NULL);
+ if(dc.m_hDC == NULL)
+ return FALSE;
+
+ // Create a DC for the monochrome DIB section
+ CDC dcBW = ::CreateCompatibleDC(m_hDC);
+ ATLASSERT(dcBW.m_hDC != NULL);
+ if(dcBW.m_hDC == NULL)
+ {
+ if(hSrcDC == NULL)
+ dc.DeleteDC();
+ return FALSE;
+ }
+
+ // Create the monochrome DIB section with a black and white palette
+ struct RGBBWBITMAPINFO
+ {
+ BITMAPINFOHEADER bmiHeader;
+ RGBQUAD bmiColors[2];
+ };
+
+ RGBBWBITMAPINFO rgbBWBitmapInfo =
+ {
+ { sizeof(BITMAPINFOHEADER), nWidth, nHeight, 1, 1, BI_RGB, 0, 0, 0, 0, 0 },
+ { { 0x00, 0x00, 0x00, 0x00 }, { 0xFF, 0xFF, 0xFF, 0x00 } }
+ };
+
+ VOID* pbitsBW;
+ CBitmap bmpBW = ::CreateDIBSection(dcBW, (LPBITMAPINFO)&rgbBWBitmapInfo, DIB_RGB_COLORS, &pbitsBW, NULL, 0);
+ ATLASSERT(bmpBW.m_hBitmap != NULL);
+ if(bmpBW.m_hBitmap == NULL)
+ {
+ if(hSrcDC == NULL)
+ dc.DeleteDC();
+ return FALSE;
+ }
+
+ // Attach the monochrome DIB section and the bitmap to the DCs
+ HBITMAP hbmOldBW = dcBW.SelectBitmap(bmpBW);
+ HBITMAP hbmOldDC = NULL;
+ if(hBitmap != NULL)
+ hbmOldDC = dc.SelectBitmap(hBitmap);
+
+ // Block: Dark gray removal: we want (128, 128, 128) pixels to become black and not white
+ {
+ CDC dcTemp1 = ::CreateCompatibleDC(m_hDC);
+ CDC dcTemp2 = ::CreateCompatibleDC(m_hDC);
+ CBitmap bmpTemp1;
+ bmpTemp1.CreateCompatibleBitmap(dc, nWidth, nHeight);
+ CBitmap bmpTemp2;
+ bmpTemp2.CreateBitmap(nWidth, nHeight, 1, 1, NULL);
+ HBITMAP hOldBmp1 = dcTemp1.SelectBitmap(bmpTemp1);
+ HBITMAP hOldBmp2 = dcTemp2.SelectBitmap(bmpTemp2);
+ // Let's copy our image, it will be altered
+ dcTemp1.BitBlt(0, 0, nWidth, nHeight, dc, xSrc, ySrc, SRCCOPY);
+
+ // All dark gray pixels will become white, the others black
+ dcTemp1.SetBkColor(RGB(128, 128, 128));
+ dcTemp2.BitBlt(0, 0, nWidth, nHeight, dcTemp1, 0, 0, SRCCOPY);
+ // Do an XOR to set to black these white pixels
+ dcTemp1.BitBlt(0, 0, nWidth, nHeight, dcTemp2, 0, 0, SRCINVERT);
+
+ // BitBlt the bitmap into the monochrome DIB section
+ // The DIB section will do a true monochrome conversion
+ // The magenta background being closer to white will become white
+ dcBW.BitBlt(0, 0, nWidth, nHeight, dcTemp1, 0, 0, SRCCOPY);
+
+ // Cleanup
+ dcTemp1.SelectBitmap(hOldBmp1);
+ dcTemp2.SelectBitmap(hOldBmp2);
+ }
+
+ // Paint the destination rectangle using hBrushBackground
+ if(hBrushBackground != NULL)
+ {
+ RECT rc = { x, y, x + nWidth, y + nHeight };
+ FillRect(&rc, hBrushBackground);
+ }
+
+ // BitBlt the black bits in the monochrome bitmap into hBrush3DEffect color in the destination DC
+ // The magic ROP comes from the Charles Petzold's book
+ HBRUSH hOldBrush = SelectBrush(hBrush3DEffect);
+ BitBlt(x + 1, y + 1, nWidth, nHeight, dcBW, 0, 0, 0xB8074A);
+
+ // BitBlt the black bits in the monochrome bitmap into hBrushDisabledImage color in the destination DC
+ SelectBrush(hBrushDisabledImage);
+ BitBlt(x, y, nWidth, nHeight, dcBW, 0, 0, 0xB8074A);
+
+ SelectBrush(hOldBrush);
+ dcBW.SelectBitmap(hbmOldBW);
+ dc.SelectBitmap(hbmOldDC);
+
+ if(hSrcDC == NULL)
+ dc.DeleteDC();
+
+ return TRUE;
+ }
+
+// Text Functions
+#ifndef _WIN32_WCE
+ BOOL TextOut(int x, int y, LPCTSTR lpszString, int nCount = -1)
+ {
+ ATLASSERT(m_hDC != NULL);
+ if(nCount == -1)
+ nCount = lstrlen(lpszString);
+ return ::TextOut(m_hDC, x, y, lpszString, nCount);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL ExtTextOut(int x, int y, UINT nOptions, LPCRECT lpRect, LPCTSTR lpszString, UINT nCount = -1, LPINT lpDxWidths = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ if(nCount == -1)
+ nCount = lstrlen(lpszString);
+ return ::ExtTextOut(m_hDC, x, y, nOptions, lpRect, lpszString, nCount, lpDxWidths);
+ }
+
+#ifndef _WIN32_WCE
+ SIZE TabbedTextOut(int x, int y, LPCTSTR lpszString, int nCount = -1, int nTabPositions = 0, LPINT lpnTabStopPositions = NULL, int nTabOrigin = 0)
+ {
+ ATLASSERT(m_hDC != NULL);
+ if(nCount == -1)
+ nCount = lstrlen(lpszString);
+ LONG lRes = ::TabbedTextOut(m_hDC, x, y, lpszString, nCount, nTabPositions, lpnTabStopPositions, nTabOrigin);
+ SIZE size = { GET_X_LPARAM(lRes), GET_Y_LPARAM(lRes) };
+ return size;
+ }
+#endif // !_WIN32_WCE
+
+ int DrawText(LPCTSTR lpstrText, int cchText, LPRECT lpRect, UINT uFormat)
+ {
+ ATLASSERT(m_hDC != NULL);
+#ifndef _WIN32_WCE
+ ATLASSERT((uFormat & DT_MODIFYSTRING) == 0);
+#endif // !_WIN32_WCE
+ return ::DrawText(m_hDC, lpstrText, cchText, lpRect, uFormat);
+ }
+
+ int DrawText(LPTSTR lpstrText, int cchText, LPRECT lpRect, UINT uFormat)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawText(m_hDC, lpstrText, cchText, lpRect, uFormat);
+ }
+
+#ifndef _WIN32_WCE
+ int DrawTextEx(LPTSTR lpstrText, int cchText, LPRECT lpRect, UINT uFormat, LPDRAWTEXTPARAMS lpDTParams = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawTextEx(m_hDC, lpstrText, cchText, lpRect, uFormat, lpDTParams);
+ }
+#endif // !_WIN32_WCE
+
+#if (_WIN32_WINNT >= 0x0501)
+ int DrawShadowText(LPCWSTR lpstrText, int cchText, LPRECT lpRect, DWORD dwFlags, COLORREF clrText, COLORREF clrShadow, int xOffset, int yOffset)
+ {
+ ATLASSERT(m_hDC != NULL);
+ // This function is present only if comctl32.dll version 6 is loaded;
+ // we use LoadLibrary/GetProcAddress to allow apps compiled with
+ // _WIN32_WINNT >= 0x0501 to run on older Windows/CommCtrl
+ int nRet = 0;
+ HMODULE hCommCtrlDLL = ::LoadLibrary(_T("comctl32.dll"));
+ ATLASSERT(hCommCtrlDLL != NULL);
+ if(hCommCtrlDLL != NULL)
+ {
+ typedef int (WINAPI *PFN_DrawShadowText)(HDC hDC, LPCWSTR lpstrText, UINT cchText, LPRECT lpRect, DWORD dwFlags, COLORREF clrText, COLORREF clrShadow, int xOffset, int yOffset);
+ PFN_DrawShadowText pfnDrawShadowText = (PFN_DrawShadowText)::GetProcAddress(hCommCtrlDLL, "DrawShadowText");
+ ATLASSERT(pfnDrawShadowText != NULL); // this function requires CommCtrl6
+ if(pfnDrawShadowText != NULL)
+ nRet = pfnDrawShadowText(m_hDC, lpstrText, cchText, lpRect, dwFlags, clrText, clrShadow, xOffset, yOffset);
+ ::FreeLibrary(hCommCtrlDLL);
+ }
+ return nRet;
+ }
+#endif // (_WIN32_WINNT >= 0x0501)
+
+ BOOL GetTextExtent(LPCTSTR lpszString, int nCount, LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ if(nCount == -1)
+ nCount = lstrlen(lpszString);
+ return ::GetTextExtentPoint32(m_hDC, lpszString, nCount, lpSize);
+ }
+
+ BOOL GetTextExtentExPoint(LPCTSTR lpszString, int cchString, LPSIZE lpSize, int nMaxExtent, LPINT lpnFit = NULL, LPINT alpDx = NULL)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextExtentExPoint(m_hDC, lpszString, cchString, nMaxExtent, lpnFit, alpDx, lpSize);
+ }
+
+#ifndef _WIN32_WCE
+ DWORD GetTabbedTextExtent(LPCTSTR lpszString, int nCount = -1, int nTabPositions = 0, LPINT lpnTabStopPositions = NULL) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ if(nCount == -1)
+ nCount = lstrlen(lpszString);
+ return ::GetTabbedTextExtent(m_hDC, lpszString, nCount, nTabPositions, lpnTabStopPositions);
+ }
+
+ BOOL GrayString(HBRUSH hBrush, BOOL (CALLBACK* lpfnOutput)(HDC, LPARAM, int), LPARAM lpData, int nCount, int x, int y, int nWidth, int nHeight)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GrayString(m_hDC, hBrush, (GRAYSTRINGPROC)lpfnOutput, lpData, nCount, x, y, nWidth, nHeight);
+ }
+#endif // !_WIN32_WCE
+
+#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
+ UINT GetTextAlign() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextAlign(m_hDC);
+ }
+
+ UINT SetTextAlign(UINT nFlags)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetTextAlign(m_hDC, nFlags);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
+
+ int GetTextFace(LPTSTR lpszFacename, int nCount) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextFace(m_hDC, nCount, lpszFacename);
+ }
+
+ int GetTextFaceLen() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextFace(m_hDC, 0, NULL);
+ }
+
+#ifndef _ATL_NO_COM
+#ifdef _OLEAUTO_H_
+ BOOL GetTextFace(BSTR& bstrFace) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(m_hDC != NULL);
+ ATLASSERT(bstrFace == NULL);
+
+ int nLen = GetTextFaceLen();
+ if(nLen == 0)
+ return FALSE;
+
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpszText = buff.Allocate(nLen);
+ if(lpszText == NULL)
+ return FALSE;
+
+ if(!GetTextFace(lpszText, nLen))
+ return FALSE;
+
+ bstrFace = ::SysAllocString(T2OLE(lpszText));
+ return (bstrFace != NULL) ? TRUE : FALSE;
+ }
+#endif
+#endif // !_ATL_NO_COM
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ int GetTextFace(_CSTRING_NS::CString& strFace) const
+ {
+ ATLASSERT(m_hDC != NULL);
+
+ int nLen = GetTextFaceLen();
+ if(nLen == 0)
+ return 0;
+
+ LPTSTR lpstr = strFace.GetBufferSetLength(nLen);
+ if(lpstr == NULL)
+ return 0;
+ int nRet = GetTextFace(lpstr, nLen);
+ strFace.ReleaseBuffer();
+ return nRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ BOOL GetTextMetrics(LPTEXTMETRIC lpMetrics) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextMetrics(m_hDC, lpMetrics);
+ }
+
+#ifndef _WIN32_WCE
+ int SetTextJustification(int nBreakExtra, int nBreakCount)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetTextJustification(m_hDC, nBreakExtra, nBreakCount);
+ }
+
+ int GetTextCharacterExtra() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextCharacterExtra(m_hDC);
+ }
+
+ int SetTextCharacterExtra(int nCharExtra)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetTextCharacterExtra(m_hDC, nCharExtra);
+ }
+#endif // !_WIN32_WCE
+
+// Advanced Drawing
+ BOOL DrawEdge(LPRECT lpRect, UINT nEdge, UINT nFlags)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawEdge(m_hDC, lpRect, nEdge, nFlags);
+ }
+
+ BOOL DrawFrameControl(LPRECT lpRect, UINT nType, UINT nState)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawFrameControl(m_hDC, lpRect, nType, nState);
+ }
+
+// Scrolling Functions
+ BOOL ScrollDC(int dx, int dy, LPCRECT lpRectScroll, LPCRECT lpRectClip, HRGN hRgnUpdate, LPRECT lpRectUpdate)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ScrollDC(m_hDC, dx, dy, lpRectScroll, lpRectClip, hRgnUpdate, lpRectUpdate);
+ }
+
+// Font Functions
+#ifndef _WIN32_WCE
+ BOOL GetCharWidth(UINT nFirstChar, UINT nLastChar, LPINT lpBuffer) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetCharWidth(m_hDC, nFirstChar, nLastChar, lpBuffer);
+ }
+
+ // GetCharWidth32 is not supported under Win9x
+ BOOL GetCharWidth32(UINT nFirstChar, UINT nLastChar, LPINT lpBuffer) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetCharWidth32(m_hDC, nFirstChar, nLastChar, lpBuffer);
+ }
+
+ DWORD SetMapperFlags(DWORD dwFlag)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetMapperFlags(m_hDC, dwFlag);
+ }
+
+ BOOL GetAspectRatioFilter(LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetAspectRatioFilterEx(m_hDC, lpSize);
+ }
+
+ BOOL GetCharABCWidths(UINT nFirstChar, UINT nLastChar, LPABC lpabc) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetCharABCWidths(m_hDC, nFirstChar, nLastChar, lpabc);
+ }
+
+ DWORD GetFontData(DWORD dwTable, DWORD dwOffset, LPVOID lpData, DWORD cbData) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetFontData(m_hDC, dwTable, dwOffset, lpData, cbData);
+ }
+
+ int GetKerningPairs(int nPairs, LPKERNINGPAIR lpkrnpair) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetKerningPairs(m_hDC, nPairs, lpkrnpair);
+ }
+
+ UINT GetOutlineTextMetrics(UINT cbData, LPOUTLINETEXTMETRIC lpotm) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetOutlineTextMetrics(m_hDC, cbData, lpotm);
+ }
+
+ DWORD GetGlyphOutline(UINT nChar, UINT nFormat, LPGLYPHMETRICS lpgm, DWORD cbBuffer, LPVOID lpBuffer, const MAT2* lpmat2) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetGlyphOutline(m_hDC, nChar, nFormat, lpgm, cbBuffer, lpBuffer, lpmat2);
+ }
+
+ BOOL GetCharABCWidths(UINT nFirstChar, UINT nLastChar, LPABCFLOAT lpABCF) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetCharABCWidthsFloat(m_hDC, nFirstChar, nLastChar, lpABCF);
+ }
+
+ BOOL GetCharWidth(UINT nFirstChar, UINT nLastChar, float* lpFloatBuffer) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetCharWidthFloat(m_hDC, nFirstChar, nLastChar, lpFloatBuffer);
+ }
+#endif // !_WIN32_WCE
+
+// Printer/Device Escape Functions
+#ifndef _WIN32_WCE
+ int Escape(int nEscape, int nCount, LPCSTR lpszInData, LPVOID lpOutData)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::Escape(m_hDC, nEscape, nCount, lpszInData, lpOutData);
+ }
+#endif // !_WIN32_WCE
+
+ int Escape(int nEscape, int nInputSize, LPCSTR lpszInputData,
+ int nOutputSize, LPSTR lpszOutputData)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ExtEscape(m_hDC, nEscape, nInputSize, lpszInputData, nOutputSize, lpszOutputData);
+ }
+
+#ifndef _WIN32_WCE
+ int DrawEscape(int nEscape, int nInputSize, LPCSTR lpszInputData)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DrawEscape(m_hDC, nEscape, nInputSize, lpszInputData);
+ }
+#endif // !_WIN32_WCE
+
+ // Escape helpers
+#if !defined(_WIN32_WCE) || ((_WIN32_WCE >= 200) && defined(StartDoc))
+ int StartDoc(LPCTSTR lpszDocName) // old Win3.0 version
+ {
+ DOCINFO di = { 0 };
+ di.cbSize = sizeof(DOCINFO);
+ di.lpszDocName = lpszDocName;
+ return StartDoc(&di);
+ }
+
+ int StartDoc(LPDOCINFO lpDocInfo)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::StartDoc(m_hDC, lpDocInfo);
+ }
+
+ int StartPage()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::StartPage(m_hDC);
+ }
+
+ int EndPage()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::EndPage(m_hDC);
+ }
+
+ int SetAbortProc(BOOL (CALLBACK* lpfn)(HDC, int))
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetAbortProc(m_hDC, (ABORTPROC)lpfn);
+ }
+
+ int AbortDoc()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::AbortDoc(m_hDC);
+ }
+
+ int EndDoc()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::EndDoc(m_hDC);
+ }
+#endif // !defined(_WIN32_WCE) || ((_WIN32_WCE >= 200) && defined(StartDoc))
+
+// MetaFile Functions
+#ifndef _WIN32_WCE
+ BOOL PlayMetaFile(HMETAFILE hMF)
+ {
+ ATLASSERT(m_hDC != NULL);
+ if(::GetDeviceCaps(m_hDC, TECHNOLOGY) == DT_METAFILE)
+ {
+ // playing metafile in metafile, just use core windows API
+ return ::PlayMetaFile(m_hDC, hMF);
+ }
+
+ // for special playback, lParam == pDC
+ return ::EnumMetaFile(m_hDC, hMF, EnumMetaFileProc, (LPARAM)this);
+ }
+
+ BOOL PlayMetaFile(HENHMETAFILE hEnhMetaFile, LPCRECT lpBounds)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::PlayEnhMetaFile(m_hDC, hEnhMetaFile, lpBounds);
+ }
+
+ BOOL AddMetaFileComment(UINT nDataSize, const BYTE* pCommentData) // can be used for enhanced metafiles only
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GdiComment(m_hDC, nDataSize, pCommentData);
+ }
+
+ // Special handling for metafile playback
+ static int CALLBACK EnumMetaFileProc(HDC hDC, HANDLETABLE* pHandleTable, METARECORD* pMetaRec, int nHandles, LPARAM lParam)
+ {
+ CDCHandle* pDC = (CDCHandle*)lParam;
+
+ switch (pMetaRec->rdFunction)
+ {
+ case META_SETMAPMODE:
+ pDC->SetMapMode((int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_SETWINDOWEXT:
+ pDC->SetWindowExt((int)(short)pMetaRec->rdParm[1], (int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_SETWINDOWORG:
+ pDC->SetWindowOrg((int)(short)pMetaRec->rdParm[1], (int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_SETVIEWPORTEXT:
+ pDC->SetViewportExt((int)(short)pMetaRec->rdParm[1], (int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_SETVIEWPORTORG:
+ pDC->SetViewportOrg((int)(short)pMetaRec->rdParm[1], (int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_SCALEWINDOWEXT:
+ pDC->ScaleWindowExt((int)(short)pMetaRec->rdParm[3], (int)(short)pMetaRec->rdParm[2],
+ (int)(short)pMetaRec->rdParm[1], (int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_SCALEVIEWPORTEXT:
+ pDC->ScaleViewportExt((int)(short)pMetaRec->rdParm[3], (int)(short)pMetaRec->rdParm[2],
+ (int)(short)pMetaRec->rdParm[1], (int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_OFFSETVIEWPORTORG:
+ pDC->OffsetViewportOrg((int)(short)pMetaRec->rdParm[1], (int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_SAVEDC:
+ pDC->SaveDC();
+ break;
+ case META_RESTOREDC:
+ pDC->RestoreDC((int)(short)pMetaRec->rdParm[0]);
+ break;
+ case META_SETBKCOLOR:
+ pDC->SetBkColor(*(UNALIGNED COLORREF*)&pMetaRec->rdParm[0]);
+ break;
+ case META_SETTEXTCOLOR:
+ pDC->SetTextColor(*(UNALIGNED COLORREF*)&pMetaRec->rdParm[0]);
+ break;
+
+ // need to watch out for SelectObject(HFONT), for custom font mapping
+ case META_SELECTOBJECT:
+ {
+ HGDIOBJ hObject = pHandleTable->objectHandle[pMetaRec->rdParm[0]];
+ UINT nObjType = ::GetObjectType(hObject);
+ if(nObjType == 0)
+ {
+ // object type is unknown, determine if it is a font
+ HFONT hStockFont = (HFONT)::GetStockObject(SYSTEM_FONT);
+ HFONT hFontOld = (HFONT)::SelectObject(pDC->m_hDC, hStockFont);
+ HGDIOBJ hObjOld = ::SelectObject(pDC->m_hDC, hObject);
+ if(hObjOld == hStockFont)
+ {
+ // got the stock object back, so must be selecting a font
+ pDC->SelectFont((HFONT)hObject);
+ break; // don't play the default record
+ }
+ else
+ {
+ // didn't get the stock object back, so restore everything
+ ::SelectObject(pDC->m_hDC, hFontOld);
+ ::SelectObject(pDC->m_hDC, hObjOld);
+ }
+ // and fall through to PlayMetaFileRecord...
+ }
+ else if(nObjType == OBJ_FONT)
+ {
+ // play back as CDCHandle::SelectFont(HFONT)
+ pDC->SelectFont((HFONT)hObject);
+ break; // don't play the default record
+ }
+ }
+ // fall through...
+
+ default:
+ ::PlayMetaFileRecord(hDC, pHandleTable, pMetaRec, nHandles);
+ break;
+ }
+
+ return 1;
+ }
+#endif // !_WIN32_WCE
+
+// Path Functions
+#ifndef _WIN32_WCE
+ BOOL AbortPath()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::AbortPath(m_hDC);
+ }
+
+ BOOL BeginPath()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::BeginPath(m_hDC);
+ }
+
+ BOOL CloseFigure()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::CloseFigure(m_hDC);
+ }
+
+ BOOL EndPath()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::EndPath(m_hDC);
+ }
+
+ BOOL FillPath()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::FillPath(m_hDC);
+ }
+
+ BOOL FlattenPath()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::FlattenPath(m_hDC);
+ }
+
+ BOOL StrokeAndFillPath()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::StrokeAndFillPath(m_hDC);
+ }
+
+ BOOL StrokePath()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::StrokePath(m_hDC);
+ }
+
+ BOOL WidenPath()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::WidenPath(m_hDC);
+ }
+
+ BOOL GetMiterLimit(PFLOAT pfMiterLimit) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetMiterLimit(m_hDC, pfMiterLimit);
+ }
+
+ BOOL SetMiterLimit(float fMiterLimit)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetMiterLimit(m_hDC, fMiterLimit, NULL);
+ }
+
+ int GetPath(LPPOINT lpPoints, LPBYTE lpTypes, int nCount) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetPath(m_hDC, lpPoints, lpTypes, nCount);
+ }
+
+ BOOL SelectClipPath(int nMode)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SelectClipPath(m_hDC, nMode);
+ }
+#endif // !_WIN32_WCE
+
+// Misc Helper Functions
+ static CBrushHandle PASCAL GetHalftoneBrush()
+ {
+ HBRUSH halftoneBrush = NULL;
+ WORD grayPattern[8];
+ for(int i = 0; i < 8; i++)
+ grayPattern[i] = (WORD)(0x5555 << (i & 1));
+ HBITMAP grayBitmap = CreateBitmap(8, 8, 1, 1, &grayPattern);
+ if(grayBitmap != NULL)
+ {
+ halftoneBrush = ::CreatePatternBrush(grayBitmap);
+ DeleteObject(grayBitmap);
+ }
+ return CBrushHandle(halftoneBrush);
+ }
+
+ void DrawDragRect(LPCRECT lpRect, SIZE size, LPCRECT lpRectLast, SIZE sizeLast, HBRUSH hBrush = NULL, HBRUSH hBrushLast = NULL)
+ {
+ // first, determine the update region and select it
+ CRgn rgnOutside;
+ rgnOutside.CreateRectRgnIndirect(lpRect);
+ RECT rect = *lpRect;
+ ::InflateRect(&rect, -size.cx, -size.cy);
+ ::IntersectRect(&rect, &rect, lpRect);
+ CRgn rgnInside;
+ rgnInside.CreateRectRgnIndirect(&rect);
+ CRgn rgnNew;
+ rgnNew.CreateRectRgn(0, 0, 0, 0);
+ rgnNew.CombineRgn(rgnOutside, rgnInside, RGN_XOR);
+
+ HBRUSH hBrushOld = NULL;
+ CBrush brushHalftone;
+ if(hBrush == NULL)
+ brushHalftone = hBrush = CDCHandle::GetHalftoneBrush();
+ if(hBrushLast == NULL)
+ hBrushLast = hBrush;
+
+ CRgn rgnLast;
+ CRgn rgnUpdate;
+ if(lpRectLast != NULL)
+ {
+ // find difference between new region and old region
+ rgnLast.CreateRectRgn(0, 0, 0, 0);
+ rgnOutside.SetRectRgn(lpRectLast->left, lpRectLast->top, lpRectLast->right, lpRectLast->bottom);
+ rect = *lpRectLast;
+ ::InflateRect(&rect, -sizeLast.cx, -sizeLast.cy);
+ ::IntersectRect(&rect, &rect, lpRectLast);
+ rgnInside.SetRectRgn(rect.left, rect.top, rect.right, rect.bottom);
+ rgnLast.CombineRgn(rgnOutside, rgnInside, RGN_XOR);
+
+ // only diff them if brushes are the same
+ if(hBrush == hBrushLast)
+ {
+ rgnUpdate.CreateRectRgn(0, 0, 0, 0);
+ rgnUpdate.CombineRgn(rgnLast, rgnNew, RGN_XOR);
+ }
+ }
+ if(hBrush != hBrushLast && lpRectLast != NULL)
+ {
+ // brushes are different -- erase old region first
+ SelectClipRgn(rgnLast);
+ GetClipBox(&rect);
+ hBrushOld = SelectBrush(hBrushLast);
+ PatBlt(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, PATINVERT);
+ SelectBrush(hBrushOld);
+ hBrushOld = NULL;
+ }
+
+ // draw into the update/new region
+ SelectClipRgn(rgnUpdate.IsNull() ? rgnNew : rgnUpdate);
+ GetClipBox(&rect);
+ hBrushOld = SelectBrush(hBrush);
+ PatBlt(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, PATINVERT);
+
+ // cleanup DC
+ if(hBrushOld != NULL)
+ SelectBrush(hBrushOld);
+ SelectClipRgn(NULL);
+ }
+
+ void FillSolidRect(LPCRECT lpRect, COLORREF clr)
+ {
+ ATLASSERT(m_hDC != NULL);
+
+ COLORREF clrOld = ::SetBkColor(m_hDC, clr);
+ ATLASSERT(clrOld != CLR_INVALID);
+ if(clrOld != CLR_INVALID)
+ {
+ ::ExtTextOut(m_hDC, 0, 0, ETO_OPAQUE, lpRect, NULL, 0, NULL);
+ ::SetBkColor(m_hDC, clrOld);
+ }
+ }
+
+ void FillSolidRect(int x, int y, int cx, int cy, COLORREF clr)
+ {
+ ATLASSERT(m_hDC != NULL);
+
+ RECT rect = { x, y, x + cx, y + cy };
+ FillSolidRect(&rect, clr);
+ }
+
+ void Draw3dRect(LPCRECT lpRect, COLORREF clrTopLeft, COLORREF clrBottomRight)
+ {
+ Draw3dRect(lpRect->left, lpRect->top, lpRect->right - lpRect->left,
+ lpRect->bottom - lpRect->top, clrTopLeft, clrBottomRight);
+ }
+
+ void Draw3dRect(int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight)
+ {
+ FillSolidRect(x, y, cx - 1, 1, clrTopLeft);
+ FillSolidRect(x, y, 1, cy - 1, clrTopLeft);
+ FillSolidRect(x + cx, y, -1, cy, clrBottomRight);
+ FillSolidRect(x, y + cy, cx, -1, clrBottomRight);
+ }
+
+// DIB support
+#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 410)
+ int SetDIBitsToDevice(int x, int y, DWORD dwWidth, DWORD dwHeight, int xSrc, int ySrc, UINT uStartScan, UINT cScanLines, CONST VOID* lpvBits, CONST BITMAPINFO* lpbmi, UINT uColorUse)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetDIBitsToDevice(m_hDC, x, y, dwWidth, dwHeight, xSrc, ySrc, uStartScan, cScanLines, lpvBits, lpbmi, uColorUse);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 410)
+
+#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
+ int StretchDIBits(int x, int y, int nWidth, int nHeight, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, CONST VOID* lpvBits, CONST BITMAPINFO* lpbmi, UINT uColorUse, DWORD dwRop)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::StretchDIBits(m_hDC, x, y, nWidth, nHeight, xSrc, ySrc, nSrcWidth, nSrcHeight, lpvBits, lpbmi, uColorUse, dwRop);
+ }
+
+ UINT GetDIBColorTable(UINT uStartIndex, UINT cEntries, RGBQUAD* pColors) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetDIBColorTable(m_hDC, uStartIndex, cEntries, pColors);
+ }
+
+ UINT SetDIBColorTable(UINT uStartIndex, UINT cEntries, CONST RGBQUAD* pColors)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetDIBColorTable(m_hDC, uStartIndex, cEntries, pColors);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 400)
+
+// OpenGL support
+#if !defined(_ATL_NO_OPENGL) && !defined(_WIN32_WCE)
+ int ChoosePixelFormat(CONST PIXELFORMATDESCRIPTOR* ppfd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ChoosePixelFormat(m_hDC, ppfd);
+ }
+
+ int DescribePixelFormat(int iPixelFormat, UINT nBytes, LPPIXELFORMATDESCRIPTOR ppfd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::DescribePixelFormat(m_hDC, iPixelFormat, nBytes, ppfd);
+ }
+
+ int GetPixelFormat() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetPixelFormat(m_hDC);
+ }
+
+ BOOL SetPixelFormat(int iPixelFormat, CONST PIXELFORMATDESCRIPTOR* ppfd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetPixelFormat(m_hDC, iPixelFormat, ppfd);
+ }
+
+ BOOL SwapBuffers()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SwapBuffers(m_hDC);
+ }
+
+ HGLRC wglCreateContext()
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglCreateContext(m_hDC);
+ }
+
+ HGLRC wglCreateLayerContext(int iLayerPlane)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglCreateLayerContext(m_hDC, iLayerPlane);
+ }
+
+ BOOL wglMakeCurrent(HGLRC hglrc)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglMakeCurrent(m_hDC, hglrc);
+ }
+
+ BOOL wglUseFontBitmaps(DWORD dwFirst, DWORD dwCount, DWORD listBase)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglUseFontBitmaps(m_hDC, dwFirst, dwCount, listBase);
+ }
+
+ BOOL wglUseFontOutlines(DWORD dwFirst, DWORD dwCount, DWORD listBase, FLOAT deviation, FLOAT extrusion, int format, LPGLYPHMETRICSFLOAT lpgmf)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglUseFontOutlines(m_hDC, dwFirst, dwCount, listBase, deviation, extrusion, format, lpgmf);
+ }
+
+ BOOL wglDescribeLayerPlane(int iPixelFormat, int iLayerPlane, UINT nBytes, LPLAYERPLANEDESCRIPTOR plpd)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglDescribeLayerPlane(m_hDC, iPixelFormat, iLayerPlane, nBytes, plpd);
+ }
+
+ int wglSetLayerPaletteEntries(int iLayerPlane, int iStart, int cEntries, CONST COLORREF* pclr)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglSetLayerPaletteEntries(m_hDC, iLayerPlane, iStart, cEntries, pclr);
+ }
+
+ int wglGetLayerPaletteEntries(int iLayerPlane, int iStart, int cEntries, COLORREF* pclr)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglGetLayerPaletteEntries(m_hDC, iLayerPlane, iStart, cEntries, pclr);
+ }
+
+ BOOL wglRealizeLayerPalette(int iLayerPlane, BOOL bRealize)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglRealizeLayerPalette(m_hDC, iLayerPlane, bRealize);
+ }
+
+ BOOL wglSwapLayerBuffers(UINT uPlanes)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::wglSwapLayerBuffers(m_hDC, uPlanes);
+ }
+#endif // !defined(_ATL_NO_OPENGL) && !defined(_WIN32_WCE)
+
+// New for Windows 2000 only
+#if (_WIN32_WINNT >= 0x0500)
+ COLORREF GetDCPenColor() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetDCPenColor(m_hDC);
+ }
+
+ COLORREF SetDCPenColor(COLORREF clr)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetDCPenColor(m_hDC, clr);
+ }
+
+ COLORREF GetDCBrushColor() const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetDCBrushColor(m_hDC);
+ }
+
+ COLORREF SetDCBrushColor(COLORREF clr)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::SetDCBrushColor(m_hDC, clr);
+ }
+
+#ifndef _WIN32_WCE
+ DWORD GetFontUnicodeRanges(LPGLYPHSET lpgs) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetFontUnicodeRanges(m_hDC, lpgs);
+ }
+#endif // !_WIN32_WCE
+
+ DWORD GetGlyphIndices(LPCTSTR lpstr, int cch, LPWORD pgi, DWORD dwFlags) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetGlyphIndices(m_hDC, lpstr, cch, pgi, dwFlags);
+ }
+
+ BOOL GetTextExtentPointI(LPWORD pgiIn, int cgi, LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextExtentPointI(m_hDC, pgiIn, cgi, lpSize);
+ }
+
+ BOOL GetTextExtentExPointI(LPWORD pgiIn, int cgi, int nMaxExtent, LPINT lpnFit, LPINT alpDx, LPSIZE lpSize) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetTextExtentExPointI(m_hDC, pgiIn, cgi, nMaxExtent, lpnFit, alpDx, lpSize);
+ }
+
+ BOOL GetCharWidthI(UINT giFirst, UINT cgi, LPWORD pgi, LPINT lpBuffer) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetCharWidthI(m_hDC, giFirst, cgi, pgi, lpBuffer);
+ }
+
+ BOOL GetCharABCWidthsI(UINT giFirst, UINT cgi, LPWORD pgi, LPABC lpabc) const
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::GetCharABCWidthsI(m_hDC, giFirst, cgi, pgi, lpabc);
+ }
+#endif // (_WIN32_WINNT >= 0x0500)
+
+// New for Windows 2000 and Windows 98
+#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ BOOL ColorCorrectPalette(HPALETTE hPalette, DWORD dwFirstEntry, DWORD dwNumOfEntries)
+ {
+ ATLASSERT(m_hDC != NULL);
+ return ::ColorCorrectPalette(m_hDC, hPalette, dwFirstEntry, dwNumOfEntries);
+ }
+#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+};
+
+typedef CDCT<false> CDCHandle;
+typedef CDCT<true> CDC;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDC Helpers
+
+class CPaintDC : public CDC
+{
+public:
+// Data members
+ HWND m_hWnd;
+ PAINTSTRUCT m_ps;
+
+// Constructor/destructor
+ CPaintDC(HWND hWnd)
+ {
+ ATLASSERT(::IsWindow(hWnd));
+ m_hWnd = hWnd;
+ m_hDC = ::BeginPaint(hWnd, &m_ps);
+ }
+
+ ~CPaintDC()
+ {
+ ATLASSERT(m_hDC != NULL);
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::EndPaint(m_hWnd, &m_ps);
+ Detach();
+ }
+};
+
+class CClientDC : public CDC
+{
+public:
+// Data members
+ HWND m_hWnd;
+
+// Constructor/destructor
+ CClientDC(HWND hWnd)
+ {
+ ATLASSERT(hWnd == NULL || ::IsWindow(hWnd));
+ m_hWnd = hWnd;
+ m_hDC = ::GetDC(hWnd);
+ }
+
+ ~CClientDC()
+ {
+ ATLASSERT(m_hDC != NULL);
+ ::ReleaseDC(m_hWnd, Detach());
+ }
+};
+
+class CWindowDC : public CDC
+{
+public:
+// Data members
+ HWND m_hWnd;
+
+// Constructor/destructor
+ CWindowDC(HWND hWnd)
+ {
+ ATLASSERT(hWnd == NULL || ::IsWindow(hWnd));
+ m_hWnd = hWnd;
+ m_hDC = ::GetWindowDC(hWnd);
+ }
+
+ ~CWindowDC()
+ {
+ ATLASSERT(m_hDC != NULL);
+ ::ReleaseDC(m_hWnd, Detach());
+ }
+};
+
+class CMemoryDC : public CDC
+{
+public:
+// Data members
+ HDC m_hDCOriginal;
+ RECT m_rcPaint;
+ CBitmap m_bmp;
+ HBITMAP m_hBmpOld;
+
+// Constructor/destructor
+ CMemoryDC(HDC hDC, RECT& rcPaint) : m_hDCOriginal(hDC), m_hBmpOld(NULL)
+ {
+ m_rcPaint = rcPaint;
+ CreateCompatibleDC(m_hDCOriginal);
+ ATLASSERT(m_hDC != NULL);
+ m_bmp.CreateCompatibleBitmap(m_hDCOriginal, m_rcPaint.right - m_rcPaint.left, m_rcPaint.bottom - m_rcPaint.top);
+ ATLASSERT(m_bmp.m_hBitmap != NULL);
+ m_hBmpOld = SelectBitmap(m_bmp);
+ SetViewportOrg(-m_rcPaint.left, -m_rcPaint.top);
+ }
+
+ ~CMemoryDC()
+ {
+ ::BitBlt(m_hDCOriginal, m_rcPaint.left, m_rcPaint.top, m_rcPaint.right - m_rcPaint.left, m_rcPaint.bottom - m_rcPaint.top, m_hDC, m_rcPaint.left, m_rcPaint.top, SRCCOPY);
+ SelectBitmap(m_hBmpOld);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Enhanced metafile support
+
+#ifndef _WIN32_WCE
+
+class CEnhMetaFileInfo
+{
+public:
+// Data members
+ HENHMETAFILE m_hEMF;
+ BYTE* m_pBits;
+ TCHAR* m_pDesc;
+ ENHMETAHEADER m_header;
+ PIXELFORMATDESCRIPTOR m_pfd;
+
+// Constructor/destructor
+ CEnhMetaFileInfo(HENHMETAFILE hEMF) : m_pBits(NULL), m_pDesc(NULL), m_hEMF(hEMF)
+ { }
+
+ ~CEnhMetaFileInfo()
+ {
+ delete [] m_pBits;
+ delete [] m_pDesc;
+ }
+
+// Operations
+ BYTE* GetEnhMetaFileBits()
+ {
+ ATLASSERT(m_hEMF != NULL);
+ UINT nBytes = ::GetEnhMetaFileBits(m_hEMF, 0, NULL);
+ delete [] m_pBits;
+ m_pBits = NULL;
+ ATLTRY(m_pBits = new BYTE[nBytes]);
+ if (m_pBits != NULL)
+ ::GetEnhMetaFileBits(m_hEMF, nBytes, m_pBits);
+ return m_pBits;
+ }
+
+ LPTSTR GetEnhMetaFileDescription()
+ {
+ ATLASSERT(m_hEMF != NULL);
+ UINT nLen = ::GetEnhMetaFileDescription(m_hEMF, 0, NULL);
+ delete [] m_pDesc;
+ m_pDesc = NULL;
+ ATLTRY(m_pDesc = new TCHAR[nLen]);
+ if (m_pDesc != NULL)
+ nLen = ::GetEnhMetaFileDescription(m_hEMF, nLen, m_pDesc);
+ return m_pDesc;
+ }
+
+ ENHMETAHEADER* GetEnhMetaFileHeader()
+ {
+ ATLASSERT(m_hEMF != NULL);
+ memset(&m_header, 0, sizeof(m_header));
+ m_header.iType = EMR_HEADER;
+ m_header.nSize = sizeof(ENHMETAHEADER);
+ UINT n = ::GetEnhMetaFileHeader(m_hEMF, sizeof(ENHMETAHEADER), &m_header);
+ return (n != 0) ? &m_header : NULL;
+ }
+
+ PIXELFORMATDESCRIPTOR* GetEnhMetaFilePixelFormat()
+ {
+ ATLASSERT(m_hEMF != NULL);
+ memset(&m_pfd, 0, sizeof(m_pfd));
+ UINT n = ::GetEnhMetaFilePixelFormat(m_hEMF, sizeof(m_pfd), &m_pfd);
+ return (n != 0) ? &m_pfd : NULL;
+ }
+};
+
+
+template <bool t_bManaged>
+class CEnhMetaFileT
+{
+public:
+// Data members
+ HENHMETAFILE m_hEMF;
+
+// Constructor/destructor
+ CEnhMetaFileT(HENHMETAFILE hEMF = NULL) : m_hEMF(hEMF)
+ {
+ }
+
+ ~CEnhMetaFileT()
+ {
+ if(t_bManaged && m_hEMF != NULL)
+ DeleteObject();
+ }
+
+// Operations
+ CEnhMetaFileT<t_bManaged>& operator =(HENHMETAFILE hEMF)
+ {
+ Attach(hEMF);
+ return *this;
+ }
+
+ void Attach(HENHMETAFILE hEMF)
+ {
+ if(t_bManaged && m_hEMF != NULL && m_hEMF != hEMF)
+ DeleteObject();
+ m_hEMF = hEMF;
+ }
+
+ HENHMETAFILE Detach()
+ {
+ HENHMETAFILE hEMF = m_hEMF;
+ m_hEMF = NULL;
+ return hEMF;
+ }
+
+ operator HENHMETAFILE() const { return m_hEMF; }
+
+ bool IsNull() const { return (m_hEMF == NULL); }
+
+ BOOL DeleteObject()
+ {
+ ATLASSERT(m_hEMF != NULL);
+ BOOL bRet = ::DeleteEnhMetaFile(m_hEMF);
+ m_hEMF = NULL;
+ return bRet;
+ }
+
+ UINT GetEnhMetaFileBits(UINT cbBuffer, LPBYTE lpbBuffer) const
+ {
+ ATLASSERT(m_hEMF != NULL);
+ return ::GetEnhMetaFileBits(m_hEMF, cbBuffer, lpbBuffer);
+ }
+
+ UINT GetEnhMetaFileDescription(UINT cchBuffer, LPTSTR lpszDescription) const
+ {
+ ATLASSERT(m_hEMF != NULL);
+ return ::GetEnhMetaFileDescription(m_hEMF, cchBuffer, lpszDescription);
+ }
+
+ UINT GetEnhMetaFileHeader(LPENHMETAHEADER lpemh) const
+ {
+ ATLASSERT(m_hEMF != NULL);
+ lpemh->iType = EMR_HEADER;
+ lpemh->nSize = sizeof(ENHMETAHEADER);
+ return ::GetEnhMetaFileHeader(m_hEMF, sizeof(ENHMETAHEADER), lpemh);
+ }
+
+ UINT GetEnhMetaFilePaletteEntries(UINT cEntries, LPPALETTEENTRY lppe) const
+ {
+ ATLASSERT(m_hEMF != NULL);
+ return ::GetEnhMetaFilePaletteEntries(m_hEMF, cEntries, lppe);
+ }
+
+ UINT GetEnhMetaFilePixelFormat(DWORD cbBuffer, PIXELFORMATDESCRIPTOR* ppfd) const
+ {
+ ATLASSERT(m_hEMF != NULL);
+ return ::GetEnhMetaFilePixelFormat(m_hEMF, cbBuffer, ppfd);
+ }
+};
+
+typedef CEnhMetaFileT<false> CEnhMetaFileHandle;
+typedef CEnhMetaFileT<true> CEnhMetaFile;
+
+
+class CEnhMetaFileDC : public CDC
+{
+public:
+// Constructor/destructor
+ CEnhMetaFileDC()
+ {
+ }
+
+ CEnhMetaFileDC(HDC hdc, LPCRECT lpRect)
+ {
+ Create(hdc, NULL, lpRect, NULL);
+ ATLASSERT(m_hDC != NULL);
+ }
+
+ CEnhMetaFileDC(HDC hdcRef, LPCTSTR lpFilename, LPCRECT lpRect, LPCTSTR lpDescription)
+ {
+ Create(hdcRef, lpFilename, lpRect, lpDescription);
+ ATLASSERT(m_hDC != NULL);
+ }
+
+ ~CEnhMetaFileDC()
+ {
+ HENHMETAFILE hEMF = Close();
+ if (hEMF != NULL)
+ ::DeleteEnhMetaFile(hEMF);
+ }
+
+// Operations
+ void Create(HDC hdcRef, LPCTSTR lpFilename, LPCRECT lpRect, LPCTSTR lpDescription)
+ {
+ ATLASSERT(m_hDC == NULL);
+ m_hDC = ::CreateEnhMetaFile(hdcRef, lpFilename, lpRect, lpDescription);
+ }
+
+ HENHMETAFILE Close()
+ {
+ HENHMETAFILE hEMF = NULL;
+ if (m_hDC != NULL)
+ {
+ hEMF = ::CloseEnhMetaFile(m_hDC);
+ m_hDC = NULL;
+ }
+ return hEMF;
+ }
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// WinCE compatible clipboard CF_DIB format support functions
+
+#ifndef _WTL_NO_DIB16
+
+#define DIBINFO16_BITFIELDS { 31744, 992, 31 }
+
+// DIBINFO16 - To avoid color table problems in WinCE we only create this type of Dib
+struct DIBINFO16 // a BITMAPINFO with 2 additional color bitfields
+{
+ BITMAPINFOHEADER bmiHeader;
+ RGBQUAD bmiColors[3];
+
+ DIBINFO16(SIZE size)
+ {
+ BITMAPINFOHEADER bmih = { sizeof(BITMAPINFOHEADER), size.cx, size.cy,
+ 1, 16, BI_BITFIELDS, 2 * size.cx * size.cy , 0, 0, 3 };
+ DWORD dw[3] = DIBINFO16_BITFIELDS ;
+
+ bmiHeader = bmih;
+ SecureHelper::memcpy_x(bmiColors, sizeof(bmiColors), dw, 3 * sizeof(DWORD));
+ }
+};
+
+
+// AtlxxxDibxxx minimal packed DIB implementation and helpers to copy and paste CF_DIB
+
+inline bool AtlIsDib16(LPBITMAPINFOHEADER pbmih)
+{
+ return (pbmih->biBitCount == 16) && (pbmih->biCompression == BI_BITFIELDS);
+}
+
+inline int AtlGetDibColorTableSize(LPBITMAPINFOHEADER pbmih)
+{
+ switch (pbmih->biBitCount)
+ {
+ case 2:
+ case 4:
+ case 8:
+ return pbmih->biClrUsed ? pbmih->biClrUsed : 1 << pbmih->biBitCount;
+ case 24:
+ break;
+ case 16:
+ case 32:
+ return pbmih->biCompression == BI_BITFIELDS ? 3 : 0;
+ default:
+ ATLASSERT(FALSE); // should never come here
+ }
+
+ return 0;
+}
+
+inline int AtlGetDibNumColors(LPBITMAPINFOHEADER pbmih)
+{
+ switch (pbmih->biBitCount)
+ {
+ case 2:
+ case 4:
+ case 8:
+ if (pbmih->biClrUsed)
+ return pbmih->biClrUsed;
+ else
+ break;
+ case 16:
+ if (pbmih->biCompression == BI_BITFIELDS )
+ return 1 << 15;
+ else
+ break;
+ case 24:
+ break;
+ case 32:
+ if (pbmih->biCompression == BI_BITFIELDS )
+ return 1 << 24;
+ else
+ break;
+ default:
+ ATLASSERT(FALSE);
+ }
+
+ return 1 << pbmih->biBitCount;
+}
+
+inline HBITMAP AtlGetDibBitmap(LPBITMAPINFO pbmi)
+{
+ CDC dc(NULL);
+ void* pBits = NULL;
+
+ LPBYTE pDibBits = (LPBYTE)pbmi + sizeof(BITMAPINFOHEADER) + AtlGetDibColorTableSize(&pbmi->bmiHeader) * sizeof(RGBQUAD);
+ HBITMAP hbm = CreateDIBSection(dc, pbmi, DIB_RGB_COLORS, &pBits, NULL, NULL);
+ if (hbm != NULL)
+ {
+ int cbBits = pbmi->bmiHeader.biWidth * pbmi->bmiHeader.biHeight * pbmi->bmiHeader.biBitCount / 8;
+ SecureHelper::memcpy_x(pBits, cbBits, pDibBits, pbmi->bmiHeader.biSizeImage);
+ }
+
+ return hbm;
+}
+
+inline HBITMAP AtlCopyBitmap(HBITMAP hbm, SIZE sizeDst, bool bAsBitmap = false)
+{
+ CDC hdcSrc = CreateCompatibleDC(NULL);
+ CDC hdcDst = CreateCompatibleDC(NULL);
+
+ CBitmapHandle hbmOld = NULL, hbmOld2 = NULL, bmSrc = hbm;
+
+ CBitmap bmNew = NULL;
+
+ SIZE sizeSrc = { 0 };
+ bmSrc.GetSize(sizeSrc);
+
+ hbmOld = hdcSrc.SelectBitmap(bmSrc);
+
+ if (bAsBitmap)
+ {
+ bmNew.CreateCompatibleBitmap(hdcSrc, sizeDst.cx, sizeDst.cy);
+ }
+ else
+ {
+ DIBINFO16 dib16(sizeDst);
+ LPVOID pBits = NULL;
+ bmNew = CreateDIBSection(hdcDst, (const BITMAPINFO*)&dib16, DIB_RGB_COLORS, &pBits, NULL, NULL);
+ }
+
+ ATLASSERT(!bmNew.IsNull());
+
+ hbmOld2 = hdcDst.SelectBitmap(bmNew);
+ BOOL bOK = FALSE;
+
+ if ((sizeDst.cx == sizeSrc.cx) && (sizeDst.cy == sizeSrc.cy))
+ bOK = hdcDst.BitBlt(0, 0, sizeDst.cx, sizeDst.cy, hdcSrc, 0, 0, SRCCOPY);
+ else
+ bOK = hdcDst.StretchBlt(0, 0, sizeDst.cx, sizeDst.cy, hdcSrc, 0, 0, sizeSrc.cx, sizeSrc.cy, SRCCOPY);
+
+ hdcSrc.SelectBitmap(hbmOld);
+ hdcDst.SelectBitmap(hbmOld2);
+
+ if (bOK == FALSE)
+ bmNew.DeleteObject();
+
+ return bmNew.Detach();
+}
+
+inline HLOCAL AtlCreatePackedDib16(HBITMAP hbm, SIZE size)
+{
+ DIBSECTION ds = { 0 };
+ LPBYTE pDib = NULL;
+ bool bCopied = false;
+
+ bool bOK = GetObject(hbm, sizeof(ds), &ds) == sizeof(ds);
+ if ((bOK == FALSE) || (ds.dsBm.bmBits == NULL) || (AtlIsDib16(&ds.dsBmih) == FALSE) ||
+ (ds.dsBmih.biWidth != size.cx ) || (ds.dsBmih.biHeight != size.cy ))
+ {
+ if ((hbm = AtlCopyBitmap(hbm, size)) != NULL)
+ {
+ bCopied = true;
+ bOK = GetObject(hbm, sizeof(ds), &ds) == sizeof(ds);
+ }
+ else
+ {
+ bOK = FALSE;
+ }
+ }
+
+ if((bOK != FALSE) && (AtlIsDib16(&ds.dsBmih) != FALSE) && (ds.dsBm.bmBits != NULL))
+ {
+ pDib = (LPBYTE)LocalAlloc(LMEM_ZEROINIT, sizeof(DIBINFO16) + ds.dsBmih.biSizeImage);
+ if (pDib != NULL)
+ {
+ SecureHelper::memcpy_x(pDib, sizeof(DIBINFO16) + ds.dsBmih.biSizeImage, &ds.dsBmih, sizeof(DIBINFO16));
+ SecureHelper::memcpy_x(pDib + sizeof(DIBINFO16), ds.dsBmih.biSizeImage, ds.dsBm.bmBits, ds.dsBmih.biSizeImage);
+ }
+ }
+
+ if (bCopied == true)
+ DeleteObject(hbm);
+
+ return (HLOCAL)pDib;
+}
+
+inline bool AtlSetClipboardDib16(HBITMAP hbm, SIZE size, HWND hWnd)
+{
+ ATLASSERT(::IsWindow(hWnd));
+ BOOL bOK = OpenClipboard(hWnd);
+ if (bOK != FALSE)
+ {
+ bOK = EmptyClipboard();
+ if (bOK != FALSE)
+ {
+ HLOCAL hDib = AtlCreatePackedDib16(hbm, size);
+ if (hDib != NULL)
+ {
+ bOK = SetClipboardData(CF_DIB, hDib) != NULL;
+ if (bOK == FALSE)
+ LocalFree(hDib);
+ }
+ else
+ {
+ bOK = FALSE;
+ }
+ }
+ CloseClipboard();
+ }
+
+ return (bOK != FALSE);
+}
+
+inline HBITMAP AtlGetClipboardDib(HWND hWnd)
+{
+ ATLASSERT(::IsWindow(hWnd) != FALSE);
+ HBITMAP hbm = NULL;
+ if (OpenClipboard(hWnd) != FALSE)
+ {
+ LPBITMAPINFO pbmi = (LPBITMAPINFO)GetClipboardData(CF_DIB);
+ if (pbmi != NULL)
+ hbm = AtlGetDibBitmap(pbmi);
+ CloseClipboard();
+ }
+
+ return hbm;
+}
+
+#endif // _WTL_NO_DIB16
+
+}; // namespace WTL
+
+#endif // __ATLGDI_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlmisc.h b/plugins/SmartAutoReplier/wtl/atlmisc.h
new file mode 100644
index 0000000000..3519b348fd
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlmisc.h
@@ -0,0 +1,3817 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLMISC_H__
+#define __ATLMISC_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlmisc.h requires atlapp.h to be included first
+#endif
+
+
+#ifdef _ATL_TMP_NO_CSTRING
+ #define _WTL_NO_CSTRING
+#endif
+
+#if defined(_WTL_USE_CSTRING) && defined(_WTL_NO_CSTRING)
+ #error Conflicting options - both _WTL_USE_CSTRING and _WTL_NO_CSTRING are defined
+#endif // defined(_WTL_USE_CSTRING) && defined(_WTL_NO_CSTRING)
+
+#if !defined(_WTL_USE_CSTRING) && !defined(_WTL_NO_CSTRING)
+ #define _WTL_USE_CSTRING
+#endif // !defined(_WTL_USE_CSTRING) && !defined(_WTL_NO_CSTRING)
+
+#ifndef _WTL_NO_CSTRING
+ #if defined(_ATL_USE_CSTRING_FLOAT) && defined(_ATL_MIN_CRT)
+ #error Cannot use CString floating point formatting with _ATL_MIN_CRT defined
+ #endif // defined(_ATL_USE_CSTRING_FLOAT) && defined(_ATL_MIN_CRT)
+#endif // !_WTL_NO_CSTRING
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CSize
+// CPoint
+// CRect
+// CString
+//
+// CRecentDocumentListBase<T, t_cchItemLen, t_nFirstID, t_nLastID>
+// CRecentDocumentList
+// CFindFile
+//
+// Global functions:
+// AtlGetStockPen()
+// AtlGetStockBrush()
+// AtlGetStockFont()
+// AtlGetStockPalette()
+//
+// AtlCompactPath()
+
+
+namespace WTL
+{
+
+#ifndef _WTL_NO_WTYPES
+
+// forward declarations
+class CSize;
+class CPoint;
+class CRect;
+
+///////////////////////////////////////////////////////////////////////////////
+// CSize - Wrapper for Windows SIZE structure.
+
+class CSize : public SIZE
+{
+public:
+// Constructors
+ CSize()
+ {
+ cx = 0;
+ cy = 0;
+ }
+
+ CSize(int initCX, int initCY)
+ {
+ cx = initCX;
+ cy = initCY;
+ }
+
+ CSize(SIZE initSize)
+ {
+ *(SIZE*)this = initSize;
+ }
+
+ CSize(POINT initPt)
+ {
+ *(POINT*)this = initPt;
+ }
+
+ CSize(DWORD dwSize)
+ {
+ cx = (short)LOWORD(dwSize);
+ cy = (short)HIWORD(dwSize);
+ }
+
+// Operations
+ BOOL operator ==(SIZE size) const
+ {
+ return (cx == size.cx && cy == size.cy);
+ }
+
+ BOOL operator !=(SIZE size) const
+ {
+ return (cx != size.cx || cy != size.cy);
+ }
+
+ void operator +=(SIZE size)
+ {
+ cx += size.cx;
+ cy += size.cy;
+ }
+
+ void operator -=(SIZE size)
+ {
+ cx -= size.cx;
+ cy -= size.cy;
+ }
+
+ void SetSize(int CX, int CY)
+ {
+ cx = CX;
+ cy = CY;
+ }
+
+// Operators returning CSize values
+ CSize operator +(SIZE size) const
+ {
+ return CSize(cx + size.cx, cy + size.cy);
+ }
+
+ CSize operator -(SIZE size) const
+ {
+ return CSize(cx - size.cx, cy - size.cy);
+ }
+
+ CSize operator -() const
+ {
+ return CSize(-cx, -cy);
+ }
+
+// Operators returning CPoint values
+ CPoint operator +(POINT point) const;
+ CPoint operator -(POINT point) const;
+
+// Operators returning CRect values
+ CRect operator +(const RECT* lpRect) const;
+ CRect operator -(const RECT* lpRect) const;
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPoint - Wrapper for Windows POINT structure.
+
+class CPoint : public POINT
+{
+public:
+// Constructors
+ CPoint()
+ {
+ x = 0;
+ y = 0;
+ }
+
+ CPoint(int initX, int initY)
+ {
+ x = initX;
+ y = initY;
+ }
+
+ CPoint(POINT initPt)
+ {
+ *(POINT*)this = initPt;
+ }
+
+ CPoint(SIZE initSize)
+ {
+ *(SIZE*)this = initSize;
+ }
+
+ CPoint(DWORD dwPoint)
+ {
+ x = (short)LOWORD(dwPoint);
+ y = (short)HIWORD(dwPoint);
+ }
+
+// Operations
+ void Offset(int xOffset, int yOffset)
+ {
+ x += xOffset;
+ y += yOffset;
+ }
+
+ void Offset(POINT point)
+ {
+ x += point.x;
+ y += point.y;
+ }
+
+ void Offset(SIZE size)
+ {
+ x += size.cx;
+ y += size.cy;
+ }
+
+ BOOL operator ==(POINT point) const
+ {
+ return (x == point.x && y == point.y);
+ }
+
+ BOOL operator !=(POINT point) const
+ {
+ return (x != point.x || y != point.y);
+ }
+
+ void operator +=(SIZE size)
+ {
+ x += size.cx;
+ y += size.cy;
+ }
+
+ void operator -=(SIZE size)
+ {
+ x -= size.cx;
+ y -= size.cy;
+ }
+
+ void operator +=(POINT point)
+ {
+ x += point.x;
+ y += point.y;
+ }
+
+ void operator -=(POINT point)
+ {
+ x -= point.x;
+ y -= point.y;
+ }
+
+ void SetPoint(int X, int Y)
+ {
+ x = X;
+ y = Y;
+ }
+
+// Operators returning CPoint values
+ CPoint operator +(SIZE size) const
+ {
+ return CPoint(x + size.cx, y + size.cy);
+ }
+
+ CPoint operator -(SIZE size) const
+ {
+ return CPoint(x - size.cx, y - size.cy);
+ }
+
+ CPoint operator -() const
+ {
+ return CPoint(-x, -y);
+ }
+
+ CPoint operator +(POINT point) const
+ {
+ return CPoint(x + point.x, y + point.y);
+ }
+
+// Operators returning CSize values
+ CSize operator -(POINT point) const
+ {
+ return CSize(x - point.x, y - point.y);
+ }
+
+// Operators returning CRect values
+ CRect operator +(const RECT* lpRect) const;
+ CRect operator -(const RECT* lpRect) const;
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRect - Wrapper for Windows RECT structure.
+
+class CRect : public RECT
+{
+public:
+// Constructors
+ CRect()
+ {
+ left = 0;
+ top = 0;
+ right = 0;
+ bottom = 0;
+ }
+
+ CRect(int l, int t, int r, int b)
+ {
+ left = l;
+ top = t;
+ right = r;
+ bottom = b;
+ }
+
+ CRect(const RECT& srcRect)
+ {
+ ::CopyRect(this, &srcRect);
+ }
+
+ CRect(LPCRECT lpSrcRect)
+ {
+ ::CopyRect(this, lpSrcRect);
+ }
+
+ CRect(POINT point, SIZE size)
+ {
+ right = (left = point.x) + size.cx;
+ bottom = (top = point.y) + size.cy;
+ }
+
+ CRect(POINT topLeft, POINT bottomRight)
+ {
+ left = topLeft.x;
+ top = topLeft.y;
+ right = bottomRight.x;
+ bottom = bottomRight.y;
+ }
+
+// Attributes (in addition to RECT members)
+ int Width() const
+ {
+ return right - left;
+ }
+
+ int Height() const
+ {
+ return bottom - top;
+ }
+
+ CSize Size() const
+ {
+ return CSize(right - left, bottom - top);
+ }
+
+ CPoint& TopLeft()
+ {
+ return *((CPoint*)this);
+ }
+
+ CPoint& BottomRight()
+ {
+ return *((CPoint*)this + 1);
+ }
+
+ const CPoint& TopLeft() const
+ {
+ return *((CPoint*)this);
+ }
+
+ const CPoint& BottomRight() const
+ {
+ return *((CPoint*)this + 1);
+ }
+
+ CPoint CenterPoint() const
+ {
+ return CPoint((left + right) / 2, (top + bottom) / 2);
+ }
+
+ // convert between CRect and LPRECT/LPCRECT (no need for &)
+ operator LPRECT()
+ {
+ return this;
+ }
+
+ operator LPCRECT() const
+ {
+ return this;
+ }
+
+ BOOL IsRectEmpty() const
+ {
+ return ::IsRectEmpty(this);
+ }
+
+ BOOL IsRectNull() const
+ {
+ return (left == 0 && right == 0 && top == 0 && bottom == 0);
+ }
+
+ BOOL PtInRect(POINT point) const
+ {
+ return ::PtInRect(this, point);
+ }
+
+// Operations
+ void SetRect(int x1, int y1, int x2, int y2)
+ {
+ ::SetRect(this, x1, y1, x2, y2);
+ }
+
+ void SetRect(POINT topLeft, POINT bottomRight)
+ {
+ ::SetRect(this, topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
+ }
+
+ void SetRectEmpty()
+ {
+ ::SetRectEmpty(this);
+ }
+
+ void CopyRect(LPCRECT lpSrcRect)
+ {
+ ::CopyRect(this, lpSrcRect);
+ }
+
+ BOOL EqualRect(LPCRECT lpRect) const
+ {
+ return ::EqualRect(this, lpRect);
+ }
+
+ void InflateRect(int x, int y)
+ {
+ ::InflateRect(this, x, y);
+ }
+
+ void InflateRect(SIZE size)
+ {
+ ::InflateRect(this, size.cx, size.cy);
+ }
+
+ void InflateRect(LPCRECT lpRect)
+ {
+ left -= lpRect->left;
+ top -= lpRect->top;
+ right += lpRect->right;
+ bottom += lpRect->bottom;
+ }
+
+ void InflateRect(int l, int t, int r, int b)
+ {
+ left -= l;
+ top -= t;
+ right += r;
+ bottom += b;
+ }
+
+ void DeflateRect(int x, int y)
+ {
+ ::InflateRect(this, -x, -y);
+ }
+
+ void DeflateRect(SIZE size)
+ {
+ ::InflateRect(this, -size.cx, -size.cy);
+ }
+
+ void DeflateRect(LPCRECT lpRect)
+ {
+ left += lpRect->left;
+ top += lpRect->top;
+ right -= lpRect->right;
+ bottom -= lpRect->bottom;
+ }
+
+ void DeflateRect(int l, int t, int r, int b)
+ {
+ left += l;
+ top += t;
+ right -= r;
+ bottom -= b;
+ }
+
+ void OffsetRect(int x, int y)
+ {
+ ::OffsetRect(this, x, y);
+ }
+ void OffsetRect(SIZE size)
+ {
+ ::OffsetRect(this, size.cx, size.cy);
+ }
+
+ void OffsetRect(POINT point)
+ {
+ ::OffsetRect(this, point.x, point.y);
+ }
+
+ void NormalizeRect()
+ {
+ int nTemp;
+ if (left > right)
+ {
+ nTemp = left;
+ left = right;
+ right = nTemp;
+ }
+ if (top > bottom)
+ {
+ nTemp = top;
+ top = bottom;
+ bottom = nTemp;
+ }
+ }
+
+ // absolute position of rectangle
+ void MoveToY(int y)
+ {
+ bottom = Height() + y;
+ top = y;
+ }
+
+ void MoveToX(int x)
+ {
+ right = Width() + x;
+ left = x;
+ }
+
+ void MoveToXY(int x, int y)
+ {
+ MoveToX(x);
+ MoveToY(y);
+ }
+
+ void MoveToXY(POINT pt)
+ {
+ MoveToX(pt.x);
+ MoveToY(pt.y);
+ }
+
+ // operations that fill '*this' with result
+ BOOL IntersectRect(LPCRECT lpRect1, LPCRECT lpRect2)
+ {
+ return ::IntersectRect(this, lpRect1, lpRect2);
+ }
+
+ BOOL UnionRect(LPCRECT lpRect1, LPCRECT lpRect2)
+ {
+ return ::UnionRect(this, lpRect1, lpRect2);
+ }
+
+ BOOL SubtractRect(LPCRECT lpRectSrc1, LPCRECT lpRectSrc2)
+ {
+ return ::SubtractRect(this, lpRectSrc1, lpRectSrc2);
+ }
+
+// Additional Operations
+ void operator =(const RECT& srcRect)
+ {
+ ::CopyRect(this, &srcRect);
+ }
+
+ BOOL operator ==(const RECT& rect) const
+ {
+ return ::EqualRect(this, &rect);
+ }
+
+ BOOL operator !=(const RECT& rect) const
+ {
+ return !::EqualRect(this, &rect);
+ }
+
+ void operator +=(POINT point)
+ {
+ ::OffsetRect(this, point.x, point.y);
+ }
+
+ void operator +=(SIZE size)
+ {
+ ::OffsetRect(this, size.cx, size.cy);
+ }
+
+ void operator +=(LPCRECT lpRect)
+ {
+ InflateRect(lpRect);
+ }
+
+ void operator -=(POINT point)
+ {
+ ::OffsetRect(this, -point.x, -point.y);
+ }
+
+ void operator -=(SIZE size)
+ {
+ ::OffsetRect(this, -size.cx, -size.cy);
+ }
+
+ void operator -=(LPCRECT lpRect)
+ {
+ DeflateRect(lpRect);
+ }
+
+ void operator &=(const RECT& rect)
+ {
+ ::IntersectRect(this, this, &rect);
+ }
+
+ void operator |=(const RECT& rect)
+ {
+ ::UnionRect(this, this, &rect);
+ }
+
+// Operators returning CRect values
+ CRect operator +(POINT pt) const
+ {
+ CRect rect(*this);
+ ::OffsetRect(&rect, pt.x, pt.y);
+ return rect;
+ }
+
+ CRect operator -(POINT pt) const
+ {
+ CRect rect(*this);
+ ::OffsetRect(&rect, -pt.x, -pt.y);
+ return rect;
+ }
+
+ CRect operator +(LPCRECT lpRect) const
+ {
+ CRect rect(this);
+ rect.InflateRect(lpRect);
+ return rect;
+ }
+
+ CRect operator +(SIZE size) const
+ {
+ CRect rect(*this);
+ ::OffsetRect(&rect, size.cx, size.cy);
+ return rect;
+ }
+
+ CRect operator -(SIZE size) const
+ {
+ CRect rect(*this);
+ ::OffsetRect(&rect, -size.cx, -size.cy);
+ return rect;
+ }
+
+ CRect operator -(LPCRECT lpRect) const
+ {
+ CRect rect(this);
+ rect.DeflateRect(lpRect);
+ return rect;
+ }
+
+ CRect operator &(const RECT& rect2) const
+ {
+ CRect rect;
+ ::IntersectRect(&rect, this, &rect2);
+ return rect;
+ }
+
+ CRect operator |(const RECT& rect2) const
+ {
+ CRect rect;
+ ::UnionRect(&rect, this, &rect2);
+ return rect;
+ }
+
+ CRect MulDiv(int nMultiplier, int nDivisor) const
+ {
+ return CRect(
+ ::MulDiv(left, nMultiplier, nDivisor),
+ ::MulDiv(top, nMultiplier, nDivisor),
+ ::MulDiv(right, nMultiplier, nDivisor),
+ ::MulDiv(bottom, nMultiplier, nDivisor));
+ }
+};
+
+
+// CSize implementation
+
+inline CPoint CSize::operator +(POINT point) const
+{ return CPoint(cx + point.x, cy + point.y); }
+
+inline CPoint CSize::operator -(POINT point) const
+{ return CPoint(cx - point.x, cy - point.y); }
+
+inline CRect CSize::operator +(const RECT* lpRect) const
+{ return CRect(lpRect) + *this; }
+
+inline CRect CSize::operator -(const RECT* lpRect) const
+{ return CRect(lpRect) - *this; }
+
+
+// CPoint implementation
+
+inline CRect CPoint::operator +(const RECT* lpRect) const
+{ return CRect(lpRect) + *this; }
+
+inline CRect CPoint::operator -(const RECT* lpRect) const
+{ return CRect(lpRect) - *this; }
+
+#endif // !_WTL_NO_WTYPES
+
+
+// WTL::CSize or ATL::CSize scalar operators
+
+#if !defined(_WTL_NO_SIZE_SCALAR) && (!defined(_WTL_NO_WTYPES) || defined(__ATLTYPES_H__))
+
+template <class Num>
+inline CSize operator *(SIZE s, Num n)
+{
+ return CSize((int)(s.cx * n), (int)(s.cy * n));
+};
+
+template <class Num>
+inline void operator *=(SIZE & s, Num n)
+{
+ s = s * n;
+};
+
+template <class Num>
+inline CSize operator /(SIZE s, Num n)
+{
+ return CSize((int)(s.cx / n), (int)(s.cy / n));
+};
+
+template <class Num>
+inline void operator /=(SIZE & s, Num n)
+{
+ s = s / n;
+};
+
+#endif // !defined(_WTL_NO_SIZE_SCALAR) && (!defined(_WTL_NO_WTYPES) || defined(__ATLTYPES_H__))
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CString - String class
+
+#ifndef _WTL_NO_CSTRING
+
+struct CStringData
+{
+ long nRefs; // reference count
+ int nDataLength;
+ int nAllocLength;
+ // TCHAR data[nAllocLength]
+
+ TCHAR* data()
+ { return (TCHAR*)(this + 1); }
+};
+
+// Globals
+
+// For an empty string, m_pchData will point here
+// (note: avoids special case of checking for NULL m_pchData)
+// empty string data (and locked)
+_declspec(selectany) int rgInitData[] = { -1, 0, 0, 0 };
+_declspec(selectany) CStringData* _atltmpDataNil = (CStringData*)&rgInitData;
+_declspec(selectany) LPCTSTR _atltmpPchNil = (LPCTSTR)(((BYTE*)&rgInitData) + sizeof(CStringData));
+
+
+class CString
+{
+public:
+// Constructors
+ CString()
+ {
+ Init();
+ }
+
+ CString(const CString& stringSrc)
+ {
+ ATLASSERT(stringSrc.GetData()->nRefs != 0);
+ if (stringSrc.GetData()->nRefs >= 0)
+ {
+ ATLASSERT(stringSrc.GetData() != _atltmpDataNil);
+ m_pchData = stringSrc.m_pchData;
+ InterlockedIncrement(&GetData()->nRefs);
+ }
+ else
+ {
+ Init();
+ *this = stringSrc.m_pchData;
+ }
+ }
+
+ CString(TCHAR ch, int nRepeat = 1)
+ {
+ ATLASSERT(!_istlead(ch)); // can't create a lead byte string
+ Init();
+ if (nRepeat >= 1)
+ {
+ if(AllocBuffer(nRepeat))
+ {
+#ifdef _UNICODE
+ for (int i = 0; i < nRepeat; i++)
+ m_pchData[i] = ch;
+#else
+ memset(m_pchData, ch, nRepeat);
+#endif
+ }
+ }
+ }
+
+ CString(LPCTSTR lpsz)
+ {
+ Init();
+ if (lpsz != NULL && HIWORD(lpsz) == NULL)
+ {
+ UINT nID = LOWORD((DWORD_PTR)lpsz);
+ if (!LoadString(nID))
+ ATLTRACE2(atlTraceUI, 0, _T("Warning: implicit LoadString(%u) in CString failed\n"), nID);
+ }
+ else
+ {
+ int nLen = SafeStrlen(lpsz);
+ if (nLen != 0)
+ {
+ if(AllocBuffer(nLen))
+ SecureHelper::memcpy_x(m_pchData, (nLen + 1) * sizeof(TCHAR), lpsz, nLen * sizeof(TCHAR));
+ }
+ }
+ }
+
+#ifdef _UNICODE
+ CString(LPCSTR lpsz)
+ {
+ Init();
+#if defined(_WIN32_WCE) && (_ATL_VER >= 0x0800)
+ int nSrcLen = (lpsz != NULL) ? ATL::lstrlenA(lpsz) : 0;
+#else
+ int nSrcLen = (lpsz != NULL) ? lstrlenA(lpsz) : 0;
+#endif
+ if (nSrcLen != 0)
+ {
+ if(AllocBuffer(nSrcLen))
+ {
+ _mbstowcsz(m_pchData, lpsz, nSrcLen + 1);
+ ReleaseBuffer();
+ }
+ }
+ }
+#else // !_UNICODE
+ CString(LPCWSTR lpsz)
+ {
+ Init();
+ int nSrcLen = (lpsz != NULL) ? (int)wcslen(lpsz) : 0;
+ if (nSrcLen != 0)
+ {
+ if(AllocBuffer(nSrcLen * 2))
+ {
+ _wcstombsz(m_pchData, lpsz, (nSrcLen * 2) + 1);
+ ReleaseBuffer();
+ }
+ }
+ }
+#endif // !_UNICODE
+
+ CString(LPCTSTR lpch, int nLength)
+ {
+ Init();
+ if (nLength != 0)
+ {
+ if(AllocBuffer(nLength))
+ SecureHelper::memcpy_x(m_pchData, (nLength + 1) * sizeof(TCHAR), lpch, nLength * sizeof(TCHAR));
+ }
+ }
+
+#ifdef _UNICODE
+ CString(LPCSTR lpsz, int nLength)
+ {
+ Init();
+ if (nLength != 0)
+ {
+ if(AllocBuffer(nLength))
+ {
+ int n = ::MultiByteToWideChar(CP_ACP, 0, lpsz, nLength, m_pchData, nLength + 1);
+ ReleaseBuffer((n >= 0) ? n : -1);
+ }
+ }
+ }
+#else // !_UNICODE
+ CString(LPCWSTR lpsz, int nLength)
+ {
+ Init();
+ if (nLength != 0)
+ {
+ if(((nLength * 2) > nLength) && AllocBuffer(nLength * 2))
+ {
+ int n = ::WideCharToMultiByte(CP_ACP, 0, lpsz, nLength, m_pchData, (nLength * 2) + 1, NULL, NULL);
+ ReleaseBuffer((n >= 0) ? n : -1);
+ }
+ }
+ }
+#endif // !_UNICODE
+
+ CString(const unsigned char* lpsz)
+ {
+ Init();
+ *this = (LPCSTR)lpsz;
+ }
+
+// Attributes & Operations
+ int GetLength() const // as an array of characters
+ {
+ return GetData()->nDataLength;
+ }
+
+ BOOL IsEmpty() const
+ {
+ return GetData()->nDataLength == 0;
+ }
+
+ void Empty() // free up the data
+ {
+ if (GetData()->nDataLength == 0)
+ return;
+
+ if (GetData()->nRefs >= 0)
+ Release();
+ else
+ *this = _T("");
+
+ ATLASSERT(GetData()->nDataLength == 0);
+ ATLASSERT(GetData()->nRefs < 0 || GetData()->nAllocLength == 0);
+ }
+
+ TCHAR GetAt(int nIndex) const // 0 based
+ {
+ ATLASSERT(nIndex >= 0);
+ ATLASSERT(nIndex < GetData()->nDataLength);
+ return m_pchData[nIndex];
+ }
+
+ TCHAR operator [](int nIndex) const // same as GetAt
+ {
+ // same as GetAt
+ ATLASSERT(nIndex >= 0);
+ ATLASSERT(nIndex < GetData()->nDataLength);
+ return m_pchData[nIndex];
+ }
+
+ void SetAt(int nIndex, TCHAR ch)
+ {
+ ATLASSERT(nIndex >= 0);
+ ATLASSERT(nIndex < GetData()->nDataLength);
+
+ CopyBeforeWrite();
+ m_pchData[nIndex] = ch;
+ }
+
+ operator LPCTSTR() const // as a C string
+ {
+ return m_pchData;
+ }
+
+ // overloaded assignment
+ CString& operator =(const CString& stringSrc)
+ {
+ if (m_pchData != stringSrc.m_pchData)
+ {
+ if ((GetData()->nRefs < 0 && GetData() != _atltmpDataNil) || stringSrc.GetData()->nRefs < 0)
+ {
+ // actual copy necessary since one of the strings is locked
+ AssignCopy(stringSrc.GetData()->nDataLength, stringSrc.m_pchData);
+ }
+ else
+ {
+ // can just copy references around
+ Release();
+ ATLASSERT(stringSrc.GetData() != _atltmpDataNil);
+ m_pchData = stringSrc.m_pchData;
+ InterlockedIncrement(&GetData()->nRefs);
+ }
+ }
+ return *this;
+ }
+
+ CString& operator =(TCHAR ch)
+ {
+ ATLASSERT(!_istlead(ch)); // can't set single lead byte
+ AssignCopy(1, &ch);
+ return *this;
+ }
+
+#ifdef _UNICODE
+ CString& operator =(char ch)
+ {
+ *this = (TCHAR)ch;
+ return *this;
+ }
+#endif
+
+ CString& operator =(LPCTSTR lpsz)
+ {
+ ATLASSERT(lpsz == NULL || _IsValidString(lpsz));
+ AssignCopy(SafeStrlen(lpsz), lpsz);
+ return *this;
+ }
+
+#ifdef _UNICODE
+ CString& operator =(LPCSTR lpsz)
+ {
+#if defined(_WIN32_WCE) && (_ATL_VER >= 0x0800)
+ int nSrcLen = (lpsz != NULL) ? ATL::lstrlenA(lpsz) : 0;
+#else
+ int nSrcLen = (lpsz != NULL) ? lstrlenA(lpsz) : 0;
+#endif
+ if(AllocBeforeWrite(nSrcLen))
+ {
+ _mbstowcsz(m_pchData, lpsz, nSrcLen + 1);
+ ReleaseBuffer();
+ }
+ return *this;
+ }
+#else // !_UNICODE
+ CString& operator =(LPCWSTR lpsz)
+ {
+ int nSrcLen = (lpsz != NULL) ? (int)wcslen(lpsz) : 0;
+ if(AllocBeforeWrite(nSrcLen * 2))
+ {
+ _wcstombsz(m_pchData, lpsz, (nSrcLen * 2) + 1);
+ ReleaseBuffer();
+ }
+ return *this;
+ }
+#endif // !_UNICODE
+
+ CString& operator =(const unsigned char* lpsz)
+ {
+ *this = (LPCSTR)lpsz;
+ return *this;
+ }
+
+ // string concatenation
+ CString& operator +=(const CString& string)
+ {
+ ConcatInPlace(string.GetData()->nDataLength, string.m_pchData);
+ return *this;
+ }
+
+ CString& operator +=(TCHAR ch)
+ {
+ ConcatInPlace(1, &ch);
+ return *this;
+ }
+
+#ifdef _UNICODE
+ CString& operator +=(char ch)
+ {
+ *this += (TCHAR)ch;
+ return *this;
+ }
+#endif
+
+ CString& operator +=(LPCTSTR lpsz)
+ {
+ ATLASSERT(lpsz == NULL || _IsValidString(lpsz));
+ ConcatInPlace(SafeStrlen(lpsz), lpsz);
+ return *this;
+ }
+
+ friend CString __stdcall operator +(const CString& string1, const CString& string2);
+ friend CString __stdcall operator +(const CString& string, TCHAR ch);
+ friend CString __stdcall operator +(TCHAR ch, const CString& string);
+#ifdef _UNICODE
+ friend CString __stdcall operator +(const CString& string, char ch);
+ friend CString __stdcall operator +(char ch, const CString& string);
+#endif
+ friend CString __stdcall operator +(const CString& string, LPCTSTR lpsz);
+ friend CString __stdcall operator +(LPCTSTR lpsz, const CString& string);
+
+ // string comparison
+ int Compare(LPCTSTR lpsz) const // straight character (MBCS/Unicode aware)
+ {
+ return _cstrcmp(m_pchData, lpsz);
+ }
+
+ int CompareNoCase(LPCTSTR lpsz) const // ignore case (MBCS/Unicode aware)
+ {
+ return _cstrcmpi(m_pchData, lpsz);
+ }
+
+#ifndef _WIN32_WCE
+ // CString::Collate is often slower than Compare but is MBSC/Unicode
+ // aware as well as locale-sensitive with respect to sort order.
+ int Collate(LPCTSTR lpsz) const // NLS aware
+ {
+ return _cstrcoll(m_pchData, lpsz);
+ }
+
+ int CollateNoCase(LPCTSTR lpsz) const // ignore case
+ {
+ return _cstrcolli(m_pchData, lpsz);
+ }
+#endif // !_WIN32_WCE
+
+ // simple sub-string extraction
+ CString Mid(int nFirst, int nCount) const
+ {
+ // out-of-bounds requests return sensible things
+ if (nFirst < 0)
+ nFirst = 0;
+ if (nCount < 0)
+ nCount = 0;
+
+ if (nFirst + nCount > GetData()->nDataLength)
+ nCount = GetData()->nDataLength - nFirst;
+ if (nFirst > GetData()->nDataLength)
+ nCount = 0;
+
+ CString dest;
+ AllocCopy(dest, nCount, nFirst, 0);
+ return dest;
+ }
+
+ CString Mid(int nFirst) const
+ {
+ return Mid(nFirst, GetData()->nDataLength - nFirst);
+ }
+
+ CString Left(int nCount) const
+ {
+ if (nCount < 0)
+ nCount = 0;
+ else if (nCount > GetData()->nDataLength)
+ nCount = GetData()->nDataLength;
+
+ CString dest;
+ AllocCopy(dest, nCount, 0, 0);
+ return dest;
+ }
+
+ CString Right(int nCount) const
+ {
+ if (nCount < 0)
+ nCount = 0;
+ else if (nCount > GetData()->nDataLength)
+ nCount = GetData()->nDataLength;
+
+ CString dest;
+ AllocCopy(dest, nCount, GetData()->nDataLength-nCount, 0);
+ return dest;
+ }
+
+ CString SpanIncluding(LPCTSTR lpszCharSet) const // strspn equivalent
+ {
+ ATLASSERT(_IsValidString(lpszCharSet));
+ return Left(_cstrspn(m_pchData, lpszCharSet));
+ }
+
+ CString SpanExcluding(LPCTSTR lpszCharSet) const // strcspn equivalent
+ {
+ ATLASSERT(_IsValidString(lpszCharSet));
+ return Left(_cstrcspn(m_pchData, lpszCharSet));
+ }
+
+ // upper/lower/reverse conversion
+ void MakeUpper()
+ {
+ CopyBeforeWrite();
+ CharUpper(m_pchData);
+ }
+
+ void MakeLower()
+ {
+ CopyBeforeWrite();
+ CharLower(m_pchData);
+ }
+
+ void MakeReverse()
+ {
+ CopyBeforeWrite();
+ _cstrrev(m_pchData);
+ }
+
+ // trimming whitespace (either side)
+ void TrimRight()
+ {
+ CopyBeforeWrite();
+
+ // find beginning of trailing spaces by starting at beginning (DBCS aware)
+ LPTSTR lpsz = m_pchData;
+ LPTSTR lpszLast = NULL;
+ while (*lpsz != _T('\0'))
+ {
+ if (_cstrisspace(*lpsz))
+ {
+ if (lpszLast == NULL)
+ lpszLast = lpsz;
+ }
+ else
+ {
+ lpszLast = NULL;
+ }
+ lpsz = ::CharNext(lpsz);
+ }
+
+ if (lpszLast != NULL)
+ {
+ // truncate at trailing space start
+ *lpszLast = _T('\0');
+ GetData()->nDataLength = (int)(DWORD_PTR)(lpszLast - m_pchData);
+ }
+ }
+
+ void TrimLeft()
+ {
+ CopyBeforeWrite();
+
+ // find first non-space character
+ LPCTSTR lpsz = m_pchData;
+ while (_cstrisspace(*lpsz))
+ lpsz = ::CharNext(lpsz);
+
+ // fix up data and length
+ int nDataLength = GetData()->nDataLength - (int)(DWORD_PTR)(lpsz - m_pchData);
+ SecureHelper::memmove_x(m_pchData, (GetData()->nAllocLength + 1) * sizeof(TCHAR), lpsz, (nDataLength + 1) * sizeof(TCHAR));
+ GetData()->nDataLength = nDataLength;
+ }
+
+ // remove continuous occurrences of chTarget starting from right
+ void TrimRight(TCHAR chTarget)
+ {
+ // find beginning of trailing matches
+ // by starting at beginning (DBCS aware)
+
+ CopyBeforeWrite();
+ LPTSTR lpsz = m_pchData;
+ LPTSTR lpszLast = NULL;
+
+ while (*lpsz != _T('\0'))
+ {
+ if (*lpsz == chTarget)
+ {
+ if (lpszLast == NULL)
+ lpszLast = lpsz;
+ }
+ else
+ lpszLast = NULL;
+ lpsz = ::CharNext(lpsz);
+ }
+
+ if (lpszLast != NULL)
+ {
+ // truncate at left-most matching character
+ *lpszLast = _T('\0');
+ GetData()->nDataLength = (int)(DWORD_PTR)(lpszLast - m_pchData);
+ }
+ }
+
+ // remove continuous occcurrences of characters in passed string, starting from right
+ void TrimRight(LPCTSTR lpszTargetList)
+ {
+ // find beginning of trailing matches by starting at beginning (DBCS aware)
+
+ CopyBeforeWrite();
+ LPTSTR lpsz = m_pchData;
+ LPTSTR lpszLast = NULL;
+
+ while (*lpsz != _T('\0'))
+ {
+ TCHAR* pNext = ::CharNext(lpsz);
+ if(pNext > lpsz + 1)
+ {
+ if (_cstrchr_db(lpszTargetList, *lpsz, *(lpsz + 1)) != NULL)
+ {
+ if (lpszLast == NULL)
+ lpszLast = lpsz;
+ }
+ else
+ {
+ lpszLast = NULL;
+ }
+ }
+ else
+ {
+ if (_cstrchr(lpszTargetList, *lpsz) != NULL)
+ {
+ if (lpszLast == NULL)
+ lpszLast = lpsz;
+ }
+ else
+ {
+ lpszLast = NULL;
+ }
+ }
+
+ lpsz = pNext;
+ }
+
+ if (lpszLast != NULL)
+ {
+ // truncate at left-most matching character
+ *lpszLast = _T('\0');
+ GetData()->nDataLength = (int)(DWORD_PTR)(lpszLast - m_pchData);
+ }
+ }
+
+ // remove continuous occurrences of chTarget starting from left
+ void TrimLeft(TCHAR chTarget)
+ {
+ // find first non-matching character
+
+ CopyBeforeWrite();
+ LPCTSTR lpsz = m_pchData;
+
+ while (chTarget == *lpsz)
+ lpsz = ::CharNext(lpsz);
+
+ if (lpsz != m_pchData)
+ {
+ // fix up data and length
+ int nDataLength = GetData()->nDataLength - (int)(DWORD_PTR)(lpsz - m_pchData);
+ SecureHelper::memmove_x(m_pchData, (GetData()->nAllocLength + 1) * sizeof(TCHAR), lpsz, (nDataLength + 1) * sizeof(TCHAR));
+ GetData()->nDataLength = nDataLength;
+ }
+ }
+
+ // remove continuous occcurrences of characters in passed string, starting from left
+ void TrimLeft(LPCTSTR lpszTargets)
+ {
+ // if we're not trimming anything, we're not doing any work
+ if (SafeStrlen(lpszTargets) == 0)
+ return;
+
+ CopyBeforeWrite();
+ LPCTSTR lpsz = m_pchData;
+
+ while (*lpsz != _T('\0'))
+ {
+ TCHAR* pNext = ::CharNext(lpsz);
+ if(pNext > lpsz + 1)
+ {
+ if (_cstrchr_db(lpszTargets, *lpsz, *(lpsz + 1)) == NULL)
+ break;
+ }
+ else
+ {
+ if (_cstrchr(lpszTargets, *lpsz) == NULL)
+ break;
+ }
+ lpsz = pNext;
+ }
+
+ if (lpsz != m_pchData)
+ {
+ // fix up data and length
+ int nDataLength = GetData()->nDataLength - (int)(DWORD_PTR)(lpsz - m_pchData);
+ SecureHelper::memmove_x(m_pchData, (GetData()->nAllocLength + 1) * sizeof(TCHAR), lpsz, (nDataLength + 1) * sizeof(TCHAR));
+ GetData()->nDataLength = nDataLength;
+ }
+ }
+
+ // advanced manipulation
+ // replace occurrences of chOld with chNew
+ int Replace(TCHAR chOld, TCHAR chNew)
+ {
+ int nCount = 0;
+
+ // short-circuit the nop case
+ if (chOld != chNew)
+ {
+ // otherwise modify each character that matches in the string
+ CopyBeforeWrite();
+ LPTSTR psz = m_pchData;
+ LPTSTR pszEnd = psz + GetData()->nDataLength;
+ while (psz < pszEnd)
+ {
+ // replace instances of the specified character only
+ if (*psz == chOld)
+ {
+ *psz = chNew;
+ nCount++;
+ }
+ psz = ::CharNext(psz);
+ }
+ }
+ return nCount;
+ }
+
+ // replace occurrences of substring lpszOld with lpszNew;
+ // empty lpszNew removes instances of lpszOld
+ int Replace(LPCTSTR lpszOld, LPCTSTR lpszNew)
+ {
+ // can't have empty or NULL lpszOld
+
+ int nSourceLen = SafeStrlen(lpszOld);
+ if (nSourceLen == 0)
+ return 0;
+ int nReplacementLen = SafeStrlen(lpszNew);
+
+ // loop once to figure out the size of the result string
+ int nCount = 0;
+ LPTSTR lpszStart = m_pchData;
+ LPTSTR lpszEnd = m_pchData + GetData()->nDataLength;
+ LPTSTR lpszTarget = NULL;
+ while (lpszStart < lpszEnd)
+ {
+ while ((lpszTarget = (TCHAR*)_cstrstr(lpszStart, lpszOld)) != NULL)
+ {
+ nCount++;
+ lpszStart = lpszTarget + nSourceLen;
+ }
+ lpszStart += lstrlen(lpszStart) + 1;
+ }
+
+ // if any changes were made, make them
+ if (nCount > 0)
+ {
+ CopyBeforeWrite();
+
+ // if the buffer is too small, just allocate a new buffer (slow but sure)
+ int nOldLength = GetData()->nDataLength;
+ int nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount;
+ if (GetData()->nAllocLength < nNewLength || GetData()->nRefs > 1)
+ {
+ CStringData* pOldData = GetData();
+ LPTSTR pstr = m_pchData;
+ if(!AllocBuffer(nNewLength))
+ return -1;
+ SecureHelper::memcpy_x(m_pchData, (nNewLength + 1) * sizeof(TCHAR), pstr, pOldData->nDataLength * sizeof(TCHAR));
+ CString::Release(pOldData);
+ }
+ // else, we just do it in-place
+ lpszStart = m_pchData;
+ lpszEnd = m_pchData + GetData()->nDataLength;
+
+ // loop again to actually do the work
+ while (lpszStart < lpszEnd)
+ {
+ while ((lpszTarget = (TCHAR*)_cstrstr(lpszStart, lpszOld)) != NULL)
+ {
+ int nBalance = nOldLength - ((int)(DWORD_PTR)(lpszTarget - m_pchData) + nSourceLen);
+ int cchBuffLen = GetData()->nAllocLength - (int)(DWORD_PTR)(lpszTarget - m_pchData);
+ SecureHelper::memmove_x(lpszTarget + nReplacementLen, (cchBuffLen - nReplacementLen + 1) * sizeof(TCHAR), lpszTarget + nSourceLen, nBalance * sizeof(TCHAR));
+ SecureHelper::memcpy_x(lpszTarget, (cchBuffLen + 1) * sizeof(TCHAR), lpszNew, nReplacementLen * sizeof(TCHAR));
+ lpszStart = lpszTarget + nReplacementLen;
+ lpszStart[nBalance] = _T('\0');
+ nOldLength += (nReplacementLen - nSourceLen);
+ }
+ lpszStart += lstrlen(lpszStart) + 1;
+ }
+ ATLASSERT(m_pchData[nNewLength] == _T('\0'));
+ GetData()->nDataLength = nNewLength;
+ }
+
+ return nCount;
+ }
+
+ // remove occurrences of chRemove
+ int Remove(TCHAR chRemove)
+ {
+ CopyBeforeWrite();
+
+ LPTSTR pstrSource = m_pchData;
+ LPTSTR pstrDest = m_pchData;
+ LPTSTR pstrEnd = m_pchData + GetData()->nDataLength;
+
+ while (pstrSource < pstrEnd)
+ {
+ if (*pstrSource != chRemove)
+ {
+ *pstrDest = *pstrSource;
+ pstrDest = ::CharNext(pstrDest);
+ }
+ pstrSource = ::CharNext(pstrSource);
+ }
+ *pstrDest = _T('\0');
+ int nCount = (int)(DWORD_PTR)(pstrSource - pstrDest);
+ GetData()->nDataLength -= nCount;
+
+ return nCount;
+ }
+
+ // insert character at zero-based index; concatenates if index is past end of string
+ int Insert(int nIndex, TCHAR ch)
+ {
+ CopyBeforeWrite();
+
+ if (nIndex < 0)
+ nIndex = 0;
+
+ int nNewLength = GetData()->nDataLength;
+ if (nIndex > nNewLength)
+ nIndex = nNewLength;
+ nNewLength++;
+
+ if (GetData()->nAllocLength < nNewLength)
+ {
+ CStringData* pOldData = GetData();
+ LPTSTR pstr = m_pchData;
+ if(!AllocBuffer(nNewLength))
+ return -1;
+ SecureHelper::memcpy_x(m_pchData, (nNewLength + 1) * sizeof(TCHAR), pstr, (pOldData->nDataLength + 1) * sizeof(TCHAR));
+ CString::Release(pOldData);
+ }
+
+ // move existing bytes down
+ SecureHelper::memmove_x(m_pchData + nIndex + 1, (GetData()->nAllocLength - nIndex) * sizeof(TCHAR), m_pchData + nIndex, (nNewLength - nIndex) * sizeof(TCHAR));
+ m_pchData[nIndex] = ch;
+ GetData()->nDataLength = nNewLength;
+
+ return nNewLength;
+ }
+
+ // insert substring at zero-based index; concatenates if index is past end of string
+ int Insert(int nIndex, LPCTSTR pstr)
+ {
+ if (nIndex < 0)
+ nIndex = 0;
+
+ int nInsertLength = SafeStrlen(pstr);
+ int nNewLength = GetData()->nDataLength;
+ if (nInsertLength > 0)
+ {
+ CopyBeforeWrite();
+ if (nIndex > nNewLength)
+ nIndex = nNewLength;
+ nNewLength += nInsertLength;
+
+ if (GetData()->nAllocLength < nNewLength)
+ {
+ CStringData* pOldData = GetData();
+ LPTSTR pstr = m_pchData;
+ if(!AllocBuffer(nNewLength))
+ return -1;
+ SecureHelper::memcpy_x(m_pchData, (nNewLength + 1) * sizeof(TCHAR), pstr, (pOldData->nDataLength + 1) * sizeof(TCHAR));
+ CString::Release(pOldData);
+ }
+
+ // move existing bytes down
+ SecureHelper::memmove_x(m_pchData + nIndex + nInsertLength, (GetData()->nAllocLength + 1 - nIndex - nInsertLength) * sizeof(TCHAR), m_pchData + nIndex, (nNewLength - nIndex - nInsertLength + 1) * sizeof(TCHAR));
+ SecureHelper::memcpy_x(m_pchData + nIndex, (GetData()->nAllocLength + 1 - nIndex) * sizeof(TCHAR), pstr, nInsertLength * sizeof(TCHAR));
+ GetData()->nDataLength = nNewLength;
+ }
+
+ return nNewLength;
+ }
+
+ // delete nCount characters starting at zero-based index
+ int Delete(int nIndex, int nCount = 1)
+ {
+ if (nIndex < 0)
+ nIndex = 0;
+ int nLength = GetData()->nDataLength;
+ if (nCount > 0 && nIndex < nLength)
+ {
+ if((nIndex + nCount) > nLength)
+ nCount = nLength - nIndex;
+ CopyBeforeWrite();
+ int nBytesToCopy = nLength - (nIndex + nCount) + 1;
+
+ SecureHelper::memmove_x(m_pchData + nIndex, (GetData()->nAllocLength + 1 - nIndex) * sizeof(TCHAR), m_pchData + nIndex + nCount, nBytesToCopy * sizeof(TCHAR));
+ nLength -= nCount;
+ GetData()->nDataLength = nLength;
+ }
+
+ return nLength;
+ }
+
+ // searching (return starting index, or -1 if not found)
+ // look for a single character match
+ int Find(TCHAR ch) const // like "C" strchr
+ {
+ return Find(ch, 0);
+ }
+
+ int ReverseFind(TCHAR ch) const
+ {
+ // find last single character
+ LPCTSTR lpsz = _cstrrchr(m_pchData, (_TUCHAR)ch);
+
+ // return -1 if not found, distance from beginning otherwise
+ return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData);
+ }
+
+ int Find(TCHAR ch, int nStart) const // starting at index
+ {
+ int nLength = GetData()->nDataLength;
+ if (nStart < 0 || nStart >= nLength)
+ return -1;
+
+ // find first single character
+ LPCTSTR lpsz = _cstrchr(m_pchData + nStart, (_TUCHAR)ch);
+
+ // return -1 if not found and index otherwise
+ return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData);
+ }
+
+ int FindOneOf(LPCTSTR lpszCharSet) const
+ {
+ ATLASSERT(_IsValidString(lpszCharSet));
+ LPCTSTR lpsz = _cstrpbrk(m_pchData, lpszCharSet);
+ return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData);
+ }
+
+ // look for a specific sub-string
+ // find a sub-string (like strstr)
+ int Find(LPCTSTR lpszSub) const // like "C" strstr
+ {
+ return Find(lpszSub, 0);
+ }
+
+ int Find(LPCTSTR lpszSub, int nStart) const // starting at index
+ {
+ ATLASSERT(_IsValidString(lpszSub));
+
+ int nLength = GetData()->nDataLength;
+ if (nStart < 0 || nStart > nLength)
+ return -1;
+
+ // find first matching substring
+ LPCTSTR lpsz = _cstrstr(m_pchData + nStart, lpszSub);
+
+ // return -1 for not found, distance from beginning otherwise
+ return (lpsz == NULL) ? -1 : (int)(lpsz - m_pchData);
+ }
+
+ // Concatentation for non strings
+ CString& Append(int n)
+ {
+ const int cchBuff = 12;
+ TCHAR szBuffer[cchBuff] = { 0 };
+ SecureHelper::wsprintf_x(szBuffer, cchBuff, _T("%d"), n);
+ ConcatInPlace(SafeStrlen(szBuffer), szBuffer);
+ return *this;
+ }
+
+ // simple formatting
+ // formatting (using wsprintf style formatting)
+ BOOL __cdecl Format(LPCTSTR lpszFormat, ...)
+ {
+ ATLASSERT(_IsValidString(lpszFormat));
+
+ va_list argList;
+ va_start(argList, lpszFormat);
+ BOOL bRet = FormatV(lpszFormat, argList);
+ va_end(argList);
+ return bRet;
+ }
+
+ BOOL __cdecl Format(UINT nFormatID, ...)
+ {
+ CString strFormat;
+ BOOL bRet = strFormat.LoadString(nFormatID);
+ ATLASSERT(bRet != 0);
+
+ va_list argList;
+ va_start(argList, nFormatID);
+ bRet = FormatV(strFormat, argList);
+ va_end(argList);
+ return bRet;
+ }
+
+ BOOL FormatV(LPCTSTR lpszFormat, va_list argList)
+ {
+ ATLASSERT(_IsValidString(lpszFormat));
+
+ enum _FormatModifiers
+ {
+ FORCE_ANSI = 0x10000,
+ FORCE_UNICODE = 0x20000,
+ FORCE_INT64 = 0x40000
+ };
+
+ va_list argListSave = argList;
+
+ // make a guess at the maximum length of the resulting string
+ int nMaxLen = 0;
+ for (LPCTSTR lpsz = lpszFormat; *lpsz != _T('\0'); lpsz = ::CharNext(lpsz))
+ {
+ // handle '%' character, but watch out for '%%'
+ if (*lpsz != _T('%') || *(lpsz = ::CharNext(lpsz)) == _T('%'))
+ {
+ nMaxLen += (int)(::CharNext(lpsz) - lpsz);
+ continue;
+ }
+
+ int nItemLen = 0;
+
+ // handle '%' character with format
+ int nWidth = 0;
+ for (; *lpsz != _T('\0'); lpsz = ::CharNext(lpsz))
+ {
+ // check for valid flags
+ if (*lpsz == _T('#'))
+ nMaxLen += 2; // for '0x'
+ else if (*lpsz == _T('*'))
+ nWidth = va_arg(argList, int);
+ else if (*lpsz == _T('-') || *lpsz == _T('+') || *lpsz == _T('0') || *lpsz == _T(' '))
+ ;
+ else // hit non-flag character
+ break;
+ }
+ // get width and skip it
+ if (nWidth == 0)
+ {
+ // width indicated by
+ nWidth = _cstrtoi(lpsz);
+ for (; *lpsz != _T('\0') && _cstrisdigit(*lpsz); lpsz = ::CharNext(lpsz))
+ ;
+ }
+ ATLASSERT(nWidth >= 0);
+
+ int nPrecision = 0;
+ if (*lpsz == _T('.'))
+ {
+ // skip past '.' separator (width.precision)
+ lpsz = ::CharNext(lpsz);
+
+ // get precision and skip it
+ if (*lpsz == _T('*'))
+ {
+ nPrecision = va_arg(argList, int);
+ lpsz = ::CharNext(lpsz);
+ }
+ else
+ {
+ nPrecision = _cstrtoi(lpsz);
+ for (; *lpsz != _T('\0') && _cstrisdigit(*lpsz); lpsz = ::CharNext(lpsz))
+ ;
+ }
+ ATLASSERT(nPrecision >= 0);
+ }
+
+ // should be on type modifier or specifier
+ int nModifier = 0;
+ if(lpsz[0] == _T('I') && lpsz[1] == _T('6') && lpsz[2] == _T('4'))
+ {
+ lpsz += 3;
+ nModifier = FORCE_INT64;
+ }
+ else
+ {
+ switch (*lpsz)
+ {
+ // modifiers that affect size
+ case _T('h'):
+ nModifier = FORCE_ANSI;
+ lpsz = ::CharNext(lpsz);
+ break;
+ case _T('l'):
+ nModifier = FORCE_UNICODE;
+ lpsz = ::CharNext(lpsz);
+ break;
+
+ // modifiers that do not affect size
+ case _T('F'):
+ case _T('N'):
+ case _T('L'):
+ lpsz = ::CharNext(lpsz);
+ break;
+ }
+ }
+
+ // now should be on specifier
+ switch (*lpsz | nModifier)
+ {
+ // single characters
+ case _T('c'):
+ case _T('C'):
+ nItemLen = 2;
+ va_arg(argList, TCHAR);
+ break;
+ case _T('c') | FORCE_ANSI:
+ case _T('C') | FORCE_ANSI:
+ nItemLen = 2;
+ va_arg(argList, char);
+ break;
+ case _T('c') | FORCE_UNICODE:
+ case _T('C') | FORCE_UNICODE:
+ nItemLen = 2;
+ va_arg(argList, WCHAR);
+ break;
+
+ // strings
+ case _T('s'):
+ {
+ LPCTSTR pstrNextArg = va_arg(argList, LPCTSTR);
+ if (pstrNextArg == NULL)
+ {
+ nItemLen = 6; // "(null)"
+ }
+ else
+ {
+ nItemLen = lstrlen(pstrNextArg);
+ nItemLen = max(1, nItemLen);
+ }
+ break;
+ }
+
+ case _T('S'):
+ {
+#ifndef _UNICODE
+ LPWSTR pstrNextArg = va_arg(argList, LPWSTR);
+ if (pstrNextArg == NULL)
+ {
+ nItemLen = 6; // "(null)"
+ }
+ else
+ {
+ nItemLen = (int)wcslen(pstrNextArg);
+ nItemLen = max(1, nItemLen);
+ }
+#else // _UNICODE
+ LPCSTR pstrNextArg = va_arg(argList, LPCSTR);
+ if (pstrNextArg == NULL)
+ {
+ nItemLen = 6; // "(null)"
+ }
+ else
+ {
+#if defined(_WIN32_WCE) && (_ATL_VER >= 0x0800)
+ nItemLen = ATL::lstrlenA(pstrNextArg);
+#else
+ nItemLen = lstrlenA(pstrNextArg);
+#endif
+ nItemLen = max(1, nItemLen);
+ }
+#endif // _UNICODE
+ break;
+ }
+
+ case _T('s') | FORCE_ANSI:
+ case _T('S') | FORCE_ANSI:
+ {
+ LPCSTR pstrNextArg = va_arg(argList, LPCSTR);
+ if (pstrNextArg == NULL)
+ {
+ nItemLen = 6; // "(null)"
+ }
+ else
+ {
+#if defined(_WIN32_WCE) && (_ATL_VER >= 0x0800)
+ nItemLen = ATL::lstrlenA(pstrNextArg);
+#else
+ nItemLen = lstrlenA(pstrNextArg);
+#endif
+ nItemLen = max(1, nItemLen);
+ }
+ break;
+ }
+
+ case _T('s') | FORCE_UNICODE:
+ case _T('S') | FORCE_UNICODE:
+ {
+ LPWSTR pstrNextArg = va_arg(argList, LPWSTR);
+ if (pstrNextArg == NULL)
+ {
+ nItemLen = 6; // "(null)"
+ }
+ else
+ {
+ nItemLen = (int)wcslen(pstrNextArg);
+ nItemLen = max(1, nItemLen);
+ }
+ break;
+ }
+ }
+
+ // adjust nItemLen for strings
+ if (nItemLen != 0)
+ {
+ nItemLen = max(nItemLen, nWidth);
+ if (nPrecision != 0)
+ nItemLen = min(nItemLen, nPrecision);
+ }
+ else
+ {
+ switch (*lpsz)
+ {
+ // integers
+ case _T('d'):
+ case _T('i'):
+ case _T('u'):
+ case _T('x'):
+ case _T('X'):
+ case _T('o'):
+ if (nModifier & FORCE_INT64)
+ va_arg(argList, __int64);
+ else
+ va_arg(argList, int);
+ nItemLen = 32;
+ nItemLen = max(nItemLen, nWidth + nPrecision);
+ break;
+
+#ifndef _ATL_USE_CSTRING_FLOAT
+ case _T('e'):
+ case _T('E'):
+ case _T('f'):
+ case _T('g'):
+ case _T('G'):
+ ATLASSERT(!"Floating point (%%e, %%E, %%f, %%g, and %%G) is not supported by the WTL::CString class.");
+#ifndef _DEBUG
+ ::OutputDebugString(_T("Floating point (%%e, %%f, %%g, and %%G) is not supported by the WTL::CString class."));
+#ifndef _WIN32_WCE
+ ::DebugBreak();
+#else // CE specific
+ DebugBreak();
+#endif // _WIN32_WCE
+#endif // !_DEBUG
+ break;
+#else // _ATL_USE_CSTRING_FLOAT
+ case _T('e'):
+ case _T('E'):
+ case _T('g'):
+ case _T('G'):
+ va_arg(argList, double);
+ nItemLen = 128;
+ nItemLen = max(nItemLen, nWidth + nPrecision);
+ break;
+ case _T('f'):
+ {
+ double f = va_arg(argList, double);
+ // 312 == strlen("-1+(309 zeroes).")
+ // 309 zeroes == max precision of a double
+ // 6 == adjustment in case precision is not specified,
+ // which means that the precision defaults to 6
+ int cchLen = max(nWidth, 312 + nPrecision + 6);
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR pszTemp = buff.Allocate(cchLen);
+ if(pszTemp != NULL)
+ {
+ SecureHelper::sprintf_x(pszTemp, cchLen, _T("%*.*f"), nWidth, nPrecision + 6, f);
+ nItemLen = (int)_tcslen(pszTemp);
+ }
+ else
+ {
+ nItemLen = cchLen;
+ }
+ }
+ break;
+#endif // _ATL_USE_CSTRING_FLOAT
+
+ case _T('p'):
+ va_arg(argList, void*);
+ nItemLen = 32;
+ nItemLen = max(nItemLen, nWidth + nPrecision);
+ break;
+
+ // no output
+ case _T('n'):
+ va_arg(argList, int*);
+ break;
+
+ default:
+ ATLASSERT(FALSE); // unknown formatting option
+ }
+ }
+
+ // adjust nMaxLen for output nItemLen
+ nMaxLen += nItemLen;
+ }
+
+ if(GetBuffer(nMaxLen) == NULL)
+ return FALSE;
+#ifndef _ATL_USE_CSTRING_FLOAT
+ int nRet = SecureHelper::wvsprintf_x(m_pchData, GetAllocLength() + 1, lpszFormat, argListSave);
+#else // _ATL_USE_CSTRING_FLOAT
+ int nRet = SecureHelper::vsprintf_x(m_pchData, GetAllocLength() + 1, lpszFormat, argListSave);
+#endif // _ATL_USE_CSTRING_FLOAT
+ nRet; // ref
+ ATLASSERT(nRet <= GetAllocLength());
+ ReleaseBuffer();
+
+ va_end(argListSave);
+ return TRUE;
+ }
+
+ // formatting for localization (uses FormatMessage API)
+ // formatting (using FormatMessage style formatting)
+ BOOL __cdecl FormatMessage(LPCTSTR lpszFormat, ...)
+ {
+ // format message into temporary buffer lpszTemp
+ va_list argList;
+ va_start(argList, lpszFormat);
+ LPTSTR lpszTemp;
+ BOOL bRet = TRUE;
+
+ if (::FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+ lpszFormat, 0, 0, (LPTSTR)&lpszTemp, 0, &argList) == 0 || lpszTemp == NULL)
+ bRet = FALSE;
+
+ // assign lpszTemp into the resulting string and free the temporary
+ *this = lpszTemp;
+ LocalFree(lpszTemp);
+ va_end(argList);
+ return bRet;
+ }
+
+ BOOL __cdecl FormatMessage(UINT nFormatID, ...)
+ {
+ // get format string from string table
+ CString strFormat;
+ BOOL bRetTmp = strFormat.LoadString(nFormatID);
+ bRetTmp; // ref
+ ATLASSERT(bRetTmp != 0);
+
+ // format message into temporary buffer lpszTemp
+ va_list argList;
+ va_start(argList, nFormatID);
+ LPTSTR lpszTemp;
+ BOOL bRet = TRUE;
+
+ if (::FormatMessage(FORMAT_MESSAGE_FROM_STRING | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+ strFormat, 0, 0, (LPTSTR)&lpszTemp, 0, &argList) == 0 || lpszTemp == NULL)
+ bRet = FALSE;
+
+ // assign lpszTemp into the resulting string and free lpszTemp
+ *this = lpszTemp;
+ LocalFree(lpszTemp);
+ va_end(argList);
+ return bRet;
+ }
+
+ // Windows support
+ BOOL LoadString(UINT nID) // load from string resource (255 chars max.)
+ {
+#ifdef _UNICODE
+ const int CHAR_FUDGE = 1; // one TCHAR unused is good enough
+#else
+ const int CHAR_FUDGE = 2; // two BYTES unused for case of DBC last char
+#endif
+
+ // try fixed buffer first (to avoid wasting space in the heap)
+ TCHAR szTemp[256];
+ int nCount = sizeof(szTemp) / sizeof(szTemp[0]);
+ int nLen = _LoadString(nID, szTemp, nCount);
+ if (nCount - nLen > CHAR_FUDGE)
+ {
+ *this = szTemp;
+ return (nLen > 0);
+ }
+
+ // try buffer size of 512, then larger size until entire string is retrieved
+ int nSize = 256;
+ do
+ {
+ nSize += 256;
+ LPTSTR lpstr = GetBuffer(nSize - 1);
+ if(lpstr == NULL)
+ {
+ nLen = 0;
+ break;
+ }
+ nLen = _LoadString(nID, lpstr, nSize);
+ } while (nSize - nLen <= CHAR_FUDGE);
+ ReleaseBuffer();
+
+ return (nLen > 0);
+ }
+
+#ifndef _UNICODE
+ // ANSI <-> OEM support (convert string in place)
+ void AnsiToOem()
+ {
+ CopyBeforeWrite();
+ ::AnsiToOem(m_pchData, m_pchData);
+ }
+
+ void OemToAnsi()
+ {
+ CopyBeforeWrite();
+ ::OemToAnsi(m_pchData, m_pchData);
+ }
+#endif
+
+#ifndef _ATL_NO_COM
+ // OLE BSTR support (use for OLE automation)
+ BSTR AllocSysString() const
+ {
+#if defined(_UNICODE) || defined(OLE2ANSI)
+ BSTR bstr = ::SysAllocStringLen(m_pchData, GetData()->nDataLength);
+#else
+ int nLen = MultiByteToWideChar(CP_ACP, 0, m_pchData,
+ GetData()->nDataLength, NULL, NULL);
+ BSTR bstr = ::SysAllocStringLen(NULL, nLen);
+ if(bstr != NULL)
+ MultiByteToWideChar(CP_ACP, 0, m_pchData, GetData()->nDataLength, bstr, nLen);
+#endif
+ return bstr;
+ }
+
+ BSTR SetSysString(BSTR* pbstr) const
+ {
+#if defined(_UNICODE) || defined(OLE2ANSI)
+ ::SysReAllocStringLen(pbstr, m_pchData, GetData()->nDataLength);
+#else
+ int nLen = MultiByteToWideChar(CP_ACP, 0, m_pchData,
+ GetData()->nDataLength, NULL, NULL);
+ if(::SysReAllocStringLen(pbstr, NULL, nLen))
+ MultiByteToWideChar(CP_ACP, 0, m_pchData, GetData()->nDataLength, *pbstr, nLen);
+#endif
+ ATLASSERT(*pbstr != NULL);
+ return *pbstr;
+ }
+#endif // !_ATL_NO_COM
+
+ // Access to string implementation buffer as "C" character array
+ LPTSTR GetBuffer(int nMinBufLength)
+ {
+ ATLASSERT(nMinBufLength >= 0);
+
+ if (GetData()->nRefs > 1 || nMinBufLength > GetData()->nAllocLength)
+ {
+ // we have to grow the buffer
+ CStringData* pOldData = GetData();
+ int nOldLen = GetData()->nDataLength; // AllocBuffer will tromp it
+ if (nMinBufLength < nOldLen)
+ nMinBufLength = nOldLen;
+
+ if(!AllocBuffer(nMinBufLength))
+ return NULL;
+
+ SecureHelper::memcpy_x(m_pchData, (nMinBufLength + 1) * sizeof(TCHAR), pOldData->data(), (nOldLen + 1) * sizeof(TCHAR));
+ GetData()->nDataLength = nOldLen;
+ CString::Release(pOldData);
+ }
+ ATLASSERT(GetData()->nRefs <= 1);
+
+ // return a pointer to the character storage for this string
+ ATLASSERT(m_pchData != NULL);
+ return m_pchData;
+ }
+
+ void ReleaseBuffer(int nNewLength = -1)
+ {
+ CopyBeforeWrite(); // just in case GetBuffer was not called
+
+ if (nNewLength == -1)
+ nNewLength = lstrlen(m_pchData); // zero terminated
+
+ ATLASSERT(nNewLength <= GetData()->nAllocLength);
+ GetData()->nDataLength = nNewLength;
+ m_pchData[nNewLength] = _T('\0');
+ }
+
+ LPTSTR GetBufferSetLength(int nNewLength)
+ {
+ ATLASSERT(nNewLength >= 0);
+
+ if(GetBuffer(nNewLength) == NULL)
+ return NULL;
+
+ GetData()->nDataLength = nNewLength;
+ m_pchData[nNewLength] = _T('\0');
+ return m_pchData;
+ }
+
+ void FreeExtra()
+ {
+ ATLASSERT(GetData()->nDataLength <= GetData()->nAllocLength);
+ if (GetData()->nDataLength != GetData()->nAllocLength)
+ {
+ CStringData* pOldData = GetData();
+ if(AllocBuffer(GetData()->nDataLength))
+ {
+ SecureHelper::memcpy_x(m_pchData, (GetData()->nAllocLength + 1) * sizeof(TCHAR), pOldData->data(), pOldData->nDataLength * sizeof(TCHAR));
+ ATLASSERT(m_pchData[GetData()->nDataLength] == _T('\0'));
+ CString::Release(pOldData);
+ }
+ }
+ ATLASSERT(GetData() != NULL);
+ }
+
+ // Use LockBuffer/UnlockBuffer to turn refcounting off
+ LPTSTR LockBuffer()
+ {
+ LPTSTR lpsz = GetBuffer(0);
+ if(lpsz != NULL)
+ GetData()->nRefs = -1;
+ return lpsz;
+ }
+
+ void UnlockBuffer()
+ {
+ ATLASSERT(GetData()->nRefs == -1);
+ if (GetData() != _atltmpDataNil)
+ GetData()->nRefs = 1;
+ }
+
+// Implementation
+public:
+ ~CString() // free any attached data
+ {
+ if (GetData() != _atltmpDataNil)
+ {
+ if (InterlockedDecrement(&GetData()->nRefs) <= 0)
+ delete[] (BYTE*)GetData();
+ }
+ }
+
+ int GetAllocLength() const
+ {
+ return GetData()->nAllocLength;
+ }
+
+ static BOOL __stdcall _IsValidString(LPCTSTR lpsz, int /*nLength*/ = -1)
+ {
+ return (lpsz != NULL) ? TRUE : FALSE;
+ }
+
+protected:
+ LPTSTR m_pchData; // pointer to ref counted string data
+
+ // implementation helpers
+ CStringData* GetData() const
+ {
+ ATLASSERT(m_pchData != NULL);
+ return ((CStringData*)m_pchData) - 1;
+ }
+
+ void Init()
+ {
+ m_pchData = _GetEmptyString().m_pchData;
+ }
+
+ BOOL AllocCopy(CString& dest, int nCopyLen, int nCopyIndex, int nExtraLen) const
+ {
+ // will clone the data attached to this string
+ // allocating 'nExtraLen' characters
+ // Places results in uninitialized string 'dest'
+ // Will copy the part or all of original data to start of new string
+
+ BOOL bRet = FALSE;
+ int nNewLen = nCopyLen + nExtraLen;
+ if (nNewLen == 0)
+ {
+ dest.Init();
+ bRet = TRUE;
+ }
+ else if(nNewLen >= nCopyLen)
+ {
+ if(dest.AllocBuffer(nNewLen))
+ {
+ SecureHelper::memcpy_x(dest.m_pchData, (nNewLen + 1) * sizeof(TCHAR), m_pchData + nCopyIndex, nCopyLen * sizeof(TCHAR));
+ bRet = TRUE;
+ }
+ }
+
+ return bRet;
+ }
+
+ // always allocate one extra character for '\0' termination
+ // assumes [optimistically] that data length will equal allocation length
+ BOOL AllocBuffer(int nLen)
+ {
+ ATLASSERT(nLen >= 0);
+ ATLASSERT(nLen <= INT_MAX - 1); // max size (enough room for 1 extra)
+
+ if (nLen == 0)
+ {
+ Init();
+ }
+ else
+ {
+ CStringData* pData = NULL;
+ ATLTRY(pData = (CStringData*)new BYTE[sizeof(CStringData) + (nLen + 1) * sizeof(TCHAR)]);
+ if(pData == NULL)
+ return FALSE;
+
+ pData->nRefs = 1;
+ pData->data()[nLen] = _T('\0');
+ pData->nDataLength = nLen;
+ pData->nAllocLength = nLen;
+ m_pchData = pData->data();
+ }
+
+ return TRUE;
+ }
+
+ // Assignment operators
+ // All assign a new value to the string
+ // (a) first see if the buffer is big enough
+ // (b) if enough room, copy on top of old buffer, set size and type
+ // (c) otherwise free old string data, and create a new one
+ //
+ // All routines return the new string (but as a 'const CString&' so that
+ // assigning it again will cause a copy, eg: s1 = s2 = "hi there".
+ //
+ void AssignCopy(int nSrcLen, LPCTSTR lpszSrcData)
+ {
+ if(AllocBeforeWrite(nSrcLen))
+ {
+ SecureHelper::memcpy_x(m_pchData, (nSrcLen + 1) * sizeof(TCHAR), lpszSrcData, nSrcLen * sizeof(TCHAR));
+ GetData()->nDataLength = nSrcLen;
+ m_pchData[nSrcLen] = _T('\0');
+ }
+ }
+
+ // Concatenation
+ // NOTE: "operator +" is done as friend functions for simplicity
+ // There are three variants:
+ // CString + CString
+ // and for ? = TCHAR, LPCTSTR
+ // CString + ?
+ // ? + CString
+ BOOL ConcatCopy(int nSrc1Len, LPCTSTR lpszSrc1Data, int nSrc2Len, LPCTSTR lpszSrc2Data)
+ {
+ // -- master concatenation routine
+ // Concatenate two sources
+ // -- assume that 'this' is a new CString object
+
+ BOOL bRet = TRUE;
+ int nNewLen = nSrc1Len + nSrc2Len;
+ if(nNewLen < nSrc1Len || nNewLen < nSrc2Len)
+ {
+ bRet = FALSE;
+ }
+ else if(nNewLen != 0)
+ {
+ bRet = AllocBuffer(nNewLen);
+ if (bRet)
+ {
+ SecureHelper::memcpy_x(m_pchData, (nNewLen + 1) * sizeof(TCHAR), lpszSrc1Data, nSrc1Len * sizeof(TCHAR));
+ SecureHelper::memcpy_x(m_pchData + nSrc1Len, (nNewLen + 1 - nSrc1Len) * sizeof(TCHAR), lpszSrc2Data, nSrc2Len * sizeof(TCHAR));
+ }
+ }
+ return bRet;
+ }
+
+ void ConcatInPlace(int nSrcLen, LPCTSTR lpszSrcData)
+ {
+ // -- the main routine for += operators
+
+ // concatenating an empty string is a no-op!
+ if (nSrcLen == 0)
+ return;
+
+ // if the buffer is too small, or we have a width mis-match, just
+ // allocate a new buffer (slow but sure)
+ if (GetData()->nRefs > 1 || GetData()->nDataLength + nSrcLen > GetData()->nAllocLength)
+ {
+ // we have to grow the buffer, use the ConcatCopy routine
+ CStringData* pOldData = GetData();
+ if (ConcatCopy(GetData()->nDataLength, m_pchData, nSrcLen, lpszSrcData))
+ {
+ ATLASSERT(pOldData != NULL);
+ CString::Release(pOldData);
+ }
+ }
+ else
+ {
+ // fast concatenation when buffer big enough
+ SecureHelper::memcpy_x(m_pchData + GetData()->nDataLength, (GetData()->nAllocLength + 1) * sizeof(TCHAR), lpszSrcData, nSrcLen * sizeof(TCHAR));
+ GetData()->nDataLength += nSrcLen;
+ ATLASSERT(GetData()->nDataLength <= GetData()->nAllocLength);
+ m_pchData[GetData()->nDataLength] = _T('\0');
+ }
+ }
+
+ void CopyBeforeWrite()
+ {
+ if (GetData()->nRefs > 1)
+ {
+ CStringData* pData = GetData();
+ Release();
+ if(AllocBuffer(pData->nDataLength))
+ SecureHelper::memcpy_x(m_pchData, (GetData()->nAllocLength + 1) * sizeof(TCHAR), pData->data(), (pData->nDataLength + 1) * sizeof(TCHAR));
+ }
+ ATLASSERT(GetData()->nRefs <= 1);
+ }
+
+ BOOL AllocBeforeWrite(int nLen)
+ {
+ BOOL bRet = TRUE;
+ if (GetData()->nRefs > 1 || nLen > GetData()->nAllocLength)
+ {
+ Release();
+ bRet = AllocBuffer(nLen);
+ }
+ ATLASSERT(GetData()->nRefs <= 1);
+ return bRet;
+ }
+
+ void Release()
+ {
+ if (GetData() != _atltmpDataNil)
+ {
+ ATLASSERT(GetData()->nRefs != 0);
+ if (InterlockedDecrement(&GetData()->nRefs) <= 0)
+ delete[] (BYTE*)GetData();
+ Init();
+ }
+ }
+
+ static void PASCAL Release(CStringData* pData)
+ {
+ if (pData != _atltmpDataNil)
+ {
+ ATLASSERT(pData->nRefs != 0);
+ if (InterlockedDecrement(&pData->nRefs) <= 0)
+ delete[] (BYTE*)pData;
+ }
+ }
+
+ static int PASCAL SafeStrlen(LPCTSTR lpsz)
+ {
+ return (lpsz == NULL) ? 0 : lstrlen(lpsz);
+ }
+
+ static int __stdcall _LoadString(UINT nID, LPTSTR lpszBuf, UINT nMaxBuf)
+ {
+#ifdef _DEBUG
+ // LoadString without annoying warning from the Debug kernel if the
+ // segment containing the string is not present
+ if (::FindResource(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE((nID >> 4) + 1), RT_STRING) == NULL)
+ {
+ lpszBuf[0] = _T('\0');
+ return 0; // not found
+ }
+#endif // _DEBUG
+
+ int nLen = ::LoadString(ModuleHelper::GetResourceInstance(), nID, lpszBuf, nMaxBuf);
+ if (nLen == 0)
+ lpszBuf[0] = _T('\0');
+
+ return nLen;
+ }
+
+ static const CString& __stdcall _GetEmptyString()
+ {
+ return *(CString*)&_atltmpPchNil;
+ }
+
+// CString conversion helpers
+ static int __cdecl _wcstombsz(char* mbstr, const wchar_t* wcstr, size_t count)
+ {
+ if (count == 0 && mbstr != NULL)
+ return 0;
+
+ int result = ::WideCharToMultiByte(CP_ACP, 0, wcstr, -1, mbstr, (int)count, NULL, NULL);
+ ATLASSERT(mbstr == NULL || result <= (int)count);
+ if (result > 0)
+ mbstr[result - 1] = 0;
+ return result;
+ }
+
+ static int __cdecl _mbstowcsz(wchar_t* wcstr, const char* mbstr, size_t count)
+ {
+ if (count == 0 && wcstr != NULL)
+ return 0;
+
+ int result = ::MultiByteToWideChar(CP_ACP, 0, mbstr, -1, wcstr, (int)count);
+ ATLASSERT(wcstr == NULL || result <= (int)count);
+ if (result > 0)
+ wcstr[result - 1] = 0;
+ return result;
+ }
+
+// Helpers to avoid CRT startup code
+#ifdef _ATL_MIN_CRT
+ static const TCHAR* _cstrchr(const TCHAR* p, TCHAR ch)
+ {
+ // strchr for '\0' should succeed
+ while (*p != 0)
+ {
+ if (*p == ch)
+ break;
+ p = ::CharNext(p);
+ }
+ return (*p == ch) ? p : NULL;
+ }
+
+ static const TCHAR* _cstrrchr(const TCHAR* p, TCHAR ch)
+ {
+ const TCHAR* lpsz = NULL;
+ while (*p != 0)
+ {
+ if (*p == ch)
+ lpsz = p;
+ p = ::CharNext(p);
+ }
+ return lpsz;
+ }
+
+ static TCHAR* _cstrrev(TCHAR* pStr)
+ {
+ // optimize NULL, zero-length, and single-char case
+ if ((pStr == NULL) || (pStr[0] == _T('\0')) || (pStr[1] == _T('\0')))
+ return pStr;
+
+ TCHAR* p = pStr;
+
+ while (*p != 0)
+ {
+ TCHAR* pNext = ::CharNext(p);
+ if(pNext > p + 1)
+ {
+ char p1 = *(char*)p;
+ *(char*)p = *(char*)(p + 1);
+ *(char*)(p + 1) = p1;
+ }
+ p = pNext;
+ }
+
+ p--;
+ TCHAR* q = pStr;
+
+ while (q < p)
+ {
+ TCHAR t = *q;
+ *q = *p;
+ *p = t;
+ q++;
+ p--;
+ }
+ return pStr;
+ }
+
+ static const TCHAR* _cstrstr(const TCHAR* pStr, const TCHAR* pCharSet)
+ {
+ int nLen = lstrlen(pCharSet);
+ if (nLen == 0)
+ return (TCHAR*)pStr;
+
+ const TCHAR* pRet = NULL;
+ const TCHAR* pCur = pStr;
+ while((pCur = _cstrchr(pCur, *pCharSet)) != NULL)
+ {
+ if(memcmp(pCur, pCharSet, nLen * sizeof(TCHAR)) == 0)
+ {
+ pRet = pCur;
+ break;
+ }
+ pCur = ::CharNext(pCur);
+ }
+ return pRet;
+ }
+
+ static int _cstrspn(const TCHAR* pStr, const TCHAR* pCharSet)
+ {
+ int nRet = 0;
+ const TCHAR* p = pStr;
+ while (*p != 0)
+ {
+ const TCHAR* pNext = ::CharNext(p);
+ if(pNext > p + 1)
+ {
+ if(_cstrchr_db(pCharSet, *p, *(p + 1)) == NULL)
+ break;
+ nRet += 2;
+ }
+ else
+ {
+ if(_cstrchr(pCharSet, *p) == NULL)
+ break;
+ nRet++;
+ }
+ p = pNext;
+ }
+ return nRet;
+ }
+
+ static int _cstrcspn(const TCHAR* pStr, const TCHAR* pCharSet)
+ {
+ int nRet = 0;
+ TCHAR* p = (TCHAR*)pStr;
+ while (*p != 0)
+ {
+ TCHAR* pNext = ::CharNext(p);
+ if(pNext > p + 1)
+ {
+ if(_cstrchr_db(pCharSet, *p, *(p + 1)) != NULL)
+ break;
+ nRet += 2;
+ }
+ else
+ {
+ if(_cstrchr(pCharSet, *p) != NULL)
+ break;
+ nRet++;
+ }
+ p = pNext;
+ }
+ return nRet;
+ }
+
+ static const TCHAR* _cstrpbrk(const TCHAR* p, const TCHAR* lpszCharSet)
+ {
+ int n = _cstrcspn(p, lpszCharSet);
+ return (p[n] != 0) ? &p[n] : NULL;
+ }
+
+ static int _cstrisdigit(TCHAR ch)
+ {
+ WORD type;
+ GetStringTypeEx(GetThreadLocale(), CT_CTYPE1, &ch, 1, &type);
+ return (type & C1_DIGIT) == C1_DIGIT;
+ }
+
+ static int _cstrisspace(TCHAR ch)
+ {
+ WORD type;
+ GetStringTypeEx(GetThreadLocale(), CT_CTYPE1, &ch, 1, &type);
+ return (type & C1_SPACE) == C1_SPACE;
+ }
+
+ static int _cstrcmp(const TCHAR* pstrOne, const TCHAR* pstrOther)
+ {
+ return lstrcmp(pstrOne, pstrOther);
+ }
+
+ static int _cstrcmpi(const TCHAR* pstrOne, const TCHAR* pstrOther)
+ {
+ return lstrcmpi(pstrOne, pstrOther);
+ }
+
+ static int _cstrcoll(const TCHAR* pstrOne, const TCHAR* pstrOther)
+ {
+ int nRet = CompareString(GetThreadLocale(), 0, pstrOne, -1, pstrOther, -1);
+ ATLASSERT(nRet != 0);
+ return nRet - 2; // convert to strcmp convention
+ }
+
+ static int _cstrcolli(const TCHAR* pstrOne, const TCHAR* pstrOther)
+ {
+ int nRet = CompareString(GetThreadLocale(), NORM_IGNORECASE, pstrOne, -1, pstrOther, -1);
+ ATLASSERT(nRet != 0);
+ return nRet - 2; // convert to strcmp convention
+ }
+
+ static int _cstrtoi(const TCHAR* nptr)
+ {
+ int c; // current char
+ int total; // current total
+ int sign; // if '-', then negative, otherwise positive
+
+ while (_cstrisspace(*nptr))
+ ++nptr;
+
+ c = (int)(_TUCHAR)*nptr++;
+ sign = c; // save sign indication
+ if (c == _T('-') || c == _T('+'))
+ c = (int)(_TUCHAR)*nptr++; // skip sign
+
+ total = 0;
+
+ while (_cstrisdigit((TCHAR)c))
+ {
+ total = 10 * total + (c - '0'); // accumulate digit
+ c = (int)(_TUCHAR)*nptr++; // get next char
+ }
+
+ if (sign == '-')
+ return -total;
+ else
+ return total; // return result, negated if necessary
+ }
+#else // !_ATL_MIN_CRT
+ static const TCHAR* _cstrchr(const TCHAR* p, TCHAR ch)
+ {
+ return _tcschr(p, ch);
+ }
+
+ static const TCHAR* _cstrrchr(const TCHAR* p, TCHAR ch)
+ {
+ return _tcsrchr(p, ch);
+ }
+
+ static TCHAR* _cstrrev(TCHAR* pStr)
+ {
+ return _tcsrev(pStr);
+ }
+
+ static const TCHAR* _cstrstr(const TCHAR* pStr, const TCHAR* pCharSet)
+ {
+ return _tcsstr(pStr, pCharSet);
+ }
+
+ static int _cstrspn(const TCHAR* pStr, const TCHAR* pCharSet)
+ {
+ return (int)_tcsspn(pStr, pCharSet);
+ }
+
+ static int _cstrcspn(const TCHAR* pStr, const TCHAR* pCharSet)
+ {
+ return (int)_tcscspn(pStr, pCharSet);
+ }
+
+ static const TCHAR* _cstrpbrk(const TCHAR* p, const TCHAR* lpszCharSet)
+ {
+ return _tcspbrk(p, lpszCharSet);
+ }
+
+ static int _cstrisdigit(TCHAR ch)
+ {
+ return _istdigit(ch);
+ }
+
+ static int _cstrisspace(TCHAR ch)
+ {
+ return _istspace((_TUCHAR)ch);
+ }
+
+ static int _cstrcmp(const TCHAR* pstrOne, const TCHAR* pstrOther)
+ {
+ return _tcscmp(pstrOne, pstrOther);
+ }
+
+ static int _cstrcmpi(const TCHAR* pstrOne, const TCHAR* pstrOther)
+ {
+ return _tcsicmp(pstrOne, pstrOther);
+ }
+
+#ifndef _WIN32_WCE
+ static int _cstrcoll(const TCHAR* pstrOne, const TCHAR* pstrOther)
+ {
+ return _tcscoll(pstrOne, pstrOther);
+ }
+
+ static int _cstrcolli(const TCHAR* pstrOne, const TCHAR* pstrOther)
+ {
+ return _tcsicoll(pstrOne, pstrOther);
+ }
+#endif // !_WIN32_WCE
+
+ static int _cstrtoi(const TCHAR* nptr)
+ {
+ return _ttoi(nptr);
+ }
+#endif // !_ATL_MIN_CRT
+
+ static const TCHAR* _cstrchr_db(const TCHAR* p, TCHAR ch1, TCHAR ch2)
+ {
+ const TCHAR* lpsz = NULL;
+ while (*p != 0)
+ {
+ if (*p == ch1 && *(p + 1) == ch2)
+ {
+ lpsz = p;
+ break;
+ }
+ p = ::CharNext(p);
+ }
+ return lpsz;
+ }
+};
+
+
+// Compare helpers
+
+inline bool __stdcall operator ==(const CString& s1, const CString& s2)
+{ return s1.Compare(s2) == 0; }
+
+inline bool __stdcall operator ==(const CString& s1, LPCTSTR s2)
+{ return s1.Compare(s2) == 0; }
+
+inline bool __stdcall operator ==(LPCTSTR s1, const CString& s2)
+{ return s2.Compare(s1) == 0; }
+
+inline bool __stdcall operator !=(const CString& s1, const CString& s2)
+{ return s1.Compare(s2) != 0; }
+
+inline bool __stdcall operator !=(const CString& s1, LPCTSTR s2)
+{ return s1.Compare(s2) != 0; }
+
+inline bool __stdcall operator !=(LPCTSTR s1, const CString& s2)
+{ return s2.Compare(s1) != 0; }
+
+inline bool __stdcall operator <(const CString& s1, const CString& s2)
+{ return s1.Compare(s2) < 0; }
+
+inline bool __stdcall operator <(const CString& s1, LPCTSTR s2)
+{ return s1.Compare(s2) < 0; }
+
+inline bool __stdcall operator <(LPCTSTR s1, const CString& s2)
+{ return s2.Compare(s1) > 0; }
+
+inline bool __stdcall operator >(const CString& s1, const CString& s2)
+{ return s1.Compare(s2) > 0; }
+
+inline bool __stdcall operator >(const CString& s1, LPCTSTR s2)
+{ return s1.Compare(s2) > 0; }
+
+inline bool __stdcall operator >(LPCTSTR s1, const CString& s2)
+{ return s2.Compare(s1) < 0; }
+
+inline bool __stdcall operator <=(const CString& s1, const CString& s2)
+{ return s1.Compare(s2) <= 0; }
+
+inline bool __stdcall operator <=(const CString& s1, LPCTSTR s2)
+{ return s1.Compare(s2) <= 0; }
+
+inline bool __stdcall operator <=(LPCTSTR s1, const CString& s2)
+{ return s2.Compare(s1) >= 0; }
+
+inline bool __stdcall operator >=(const CString& s1, const CString& s2)
+{ return s1.Compare(s2) >= 0; }
+
+inline bool __stdcall operator >=(const CString& s1, LPCTSTR s2)
+{ return s1.Compare(s2) >= 0; }
+
+inline bool __stdcall operator >=(LPCTSTR s1, const CString& s2)
+{ return s2.Compare(s1) <= 0; }
+
+
+// CString "operator +" functions
+
+inline CString __stdcall operator +(const CString& string1, const CString& string2)
+{
+ CString s;
+ s.ConcatCopy(string1.GetData()->nDataLength, string1.m_pchData, string2.GetData()->nDataLength, string2.m_pchData);
+ return s;
+}
+
+inline CString __stdcall operator +(const CString& string, TCHAR ch)
+{
+ CString s;
+ s.ConcatCopy(string.GetData()->nDataLength, string.m_pchData, 1, &ch);
+ return s;
+}
+
+inline CString __stdcall operator +(TCHAR ch, const CString& string)
+{
+ CString s;
+ s.ConcatCopy(1, &ch, string.GetData()->nDataLength, string.m_pchData);
+ return s;
+}
+
+#ifdef _UNICODE
+inline CString __stdcall operator +(const CString& string, char ch)
+{
+ return string + (TCHAR)ch;
+}
+
+inline CString __stdcall operator +(char ch, const CString& string)
+{
+ return (TCHAR)ch + string;
+}
+#endif // _UNICODE
+
+inline CString __stdcall operator +(const CString& string, LPCTSTR lpsz)
+{
+ ATLASSERT(lpsz == NULL || CString::_IsValidString(lpsz));
+ CString s;
+ s.ConcatCopy(string.GetData()->nDataLength, string.m_pchData, CString::SafeStrlen(lpsz), lpsz);
+ return s;
+}
+
+inline CString __stdcall operator +(LPCTSTR lpsz, const CString& string)
+{
+ ATLASSERT(lpsz == NULL || CString::_IsValidString(lpsz));
+ CString s;
+ s.ConcatCopy(CString::SafeStrlen(lpsz), lpsz, string.GetData()->nDataLength, string.m_pchData);
+ return s;
+}
+
+#endif // !_WTL_NO_CSTRING
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRecentDocumentList - MRU List Support
+
+#ifndef _WIN32_WCE
+
+#ifndef _WTL_MRUEMPTY_TEXT
+ #define _WTL_MRUEMPTY_TEXT _T("(empty)")
+#endif
+
+// forward declaration
+inline bool AtlCompactPath(LPTSTR lpstrOut, LPCTSTR lpstrIn, int cchLen);
+
+template <class T, int t_cchItemLen = MAX_PATH, int t_nFirstID = ID_FILE_MRU_FIRST, int t_nLastID = ID_FILE_MRU_LAST>
+class CRecentDocumentListBase
+{
+public:
+// Declarations
+ struct _DocEntry
+ {
+ TCHAR szDocName[t_cchItemLen];
+ bool operator ==(const _DocEntry& de) const
+ { return (lstrcmpi(szDocName, de.szDocName) == 0); }
+ };
+
+ enum
+ {
+ m_nMaxEntries_Min = 2,
+ m_nMaxEntries_Max = t_nLastID - t_nFirstID + 1,
+ m_cchMaxItemLen_Min = 6,
+ m_cchMaxItemLen_Max = t_cchItemLen,
+ m_cchItemNameLen = 11
+ };
+
+// Data members
+ ATL::CSimpleArray<_DocEntry> m_arrDocs;
+ int m_nMaxEntries; // default is 4
+ HMENU m_hMenu;
+
+ TCHAR m_szNoEntries[t_cchItemLen];
+
+ int m_cchMaxItemLen;
+
+// Constructor
+ CRecentDocumentListBase() : m_hMenu(NULL), m_nMaxEntries(4), m_cchMaxItemLen(-1)
+ {
+ // These ASSERTs verify values of the template arguments
+ ATLASSERT(t_cchItemLen > m_cchMaxItemLen_Min);
+ ATLASSERT(m_nMaxEntries_Max > m_nMaxEntries_Min);
+ }
+
+// Attributes
+ HMENU GetMenuHandle() const
+ {
+ return m_hMenu;
+ }
+
+ void SetMenuHandle(HMENU hMenu)
+ {
+ ATLASSERT(hMenu == NULL || ::IsMenu(hMenu));
+ m_hMenu = hMenu;
+ if(m_hMenu == NULL || (::GetMenuString(m_hMenu, t_nFirstID, m_szNoEntries, t_cchItemLen, MF_BYCOMMAND) == 0))
+ {
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ SecureHelper::strncpy_x(m_szNoEntries, _countof(m_szNoEntries), pT->GetMRUEmptyText(), _TRUNCATE);
+ }
+ }
+
+ int GetMaxEntries() const
+ {
+ return m_nMaxEntries;
+ }
+
+ void SetMaxEntries(int nMaxEntries)
+ {
+ ATLASSERT(nMaxEntries >= m_nMaxEntries_Min && nMaxEntries <= m_nMaxEntries_Max);
+ if(nMaxEntries < m_nMaxEntries_Min)
+ nMaxEntries = m_nMaxEntries_Min;
+ else if(nMaxEntries > m_nMaxEntries_Max)
+ nMaxEntries = m_nMaxEntries_Max;
+ m_nMaxEntries = nMaxEntries;
+ }
+
+ int GetMaxItemLength() const
+ {
+ return m_cchMaxItemLen;
+ }
+
+ void SetMaxItemLength(int cchMaxLen)
+ {
+ ATLASSERT((cchMaxLen >= m_cchMaxItemLen_Min && cchMaxLen <= m_cchMaxItemLen_Max) || cchMaxLen == -1);
+ if(cchMaxLen != -1)
+ {
+ if(cchMaxLen < m_cchMaxItemLen_Min)
+ cchMaxLen = m_cchMaxItemLen_Min;
+ else if(cchMaxLen > m_cchMaxItemLen_Max)
+ cchMaxLen = m_cchMaxItemLen_Max;
+ }
+ m_cchMaxItemLen = cchMaxLen;
+ T* pT = static_cast<T*>(this);
+ pT->UpdateMenu();
+ }
+
+// Operations
+ BOOL AddToList(LPCTSTR lpstrDocName)
+ {
+ _DocEntry de;
+ errno_t nRet = SecureHelper::strncpy_x(de.szDocName, _countof(de.szDocName), lpstrDocName, _TRUNCATE);
+ if(nRet != 0 && nRet != STRUNCATE)
+ return FALSE;
+
+ for(int i = 0; i < m_arrDocs.GetSize(); i++)
+ {
+ if(lstrcmpi(m_arrDocs[i].szDocName, lpstrDocName) == 0)
+ {
+ m_arrDocs.RemoveAt(i);
+ break;
+ }
+ }
+
+ if(m_arrDocs.GetSize() == m_nMaxEntries)
+ m_arrDocs.RemoveAt(0);
+
+ BOOL bRet = m_arrDocs.Add(de);
+ if(bRet)
+ {
+ T* pT = static_cast<T*>(this);
+ bRet = pT->UpdateMenu();
+ }
+ return bRet;
+ }
+
+ // This function is deprecated because it is not safe.
+ // Use the version below that accepts the buffer length.
+#if (_MSC_VER >= 1300)
+ __declspec(deprecated)
+#endif
+ BOOL GetFromList(int /*nItemID*/, LPTSTR /*lpstrDocName*/)
+ {
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+ BOOL GetFromList(int nItemID, LPTSTR lpstrDocName, int cchLength)
+ {
+ int nIndex = m_arrDocs.GetSize() - (nItemID - t_nFirstID) - 1;
+ if(nIndex < 0 || nIndex >= m_arrDocs.GetSize())
+ return FALSE;
+ if(lstrlen(m_arrDocs[nIndex].szDocName) >= cchLength)
+ return FALSE;
+ SecureHelper::strcpy_x(lpstrDocName, cchLength, m_arrDocs[nIndex].szDocName);
+
+ return TRUE;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ BOOL GetFromList(int nItemID, _CSTRING_NS::CString& strDocName)
+ {
+ int nIndex = m_arrDocs.GetSize() - (nItemID - t_nFirstID) - 1;
+ if(nIndex < 0 || nIndex >= m_arrDocs.GetSize())
+ return FALSE;
+ strDocName = m_arrDocs[nIndex].szDocName;
+ return TRUE;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ BOOL RemoveFromList(int nItemID)
+ {
+ int nIndex = m_arrDocs.GetSize() - (nItemID - t_nFirstID) - 1;
+ BOOL bRet = m_arrDocs.RemoveAt(nIndex);
+ if(bRet)
+ {
+ T* pT = static_cast<T*>(this);
+ bRet = pT->UpdateMenu();
+ }
+ return bRet;
+ }
+
+ BOOL MoveToTop(int nItemID)
+ {
+ int nIndex = m_arrDocs.GetSize() - (nItemID - t_nFirstID) - 1;
+ if(nIndex < 0 || nIndex >= m_arrDocs.GetSize())
+ return FALSE;
+ _DocEntry de;
+ de = m_arrDocs[nIndex];
+ m_arrDocs.RemoveAt(nIndex);
+ BOOL bRet = m_arrDocs.Add(de);
+ if(bRet)
+ {
+ T* pT = static_cast<T*>(this);
+ bRet = pT->UpdateMenu();
+ }
+ return bRet;
+ }
+
+ BOOL ReadFromRegistry(LPCTSTR lpstrRegKey)
+ {
+ T* pT = static_cast<T*>(this);
+ CRegKeyEx rkParent;
+ CRegKeyEx rk;
+
+ LONG lRet = rkParent.Open(HKEY_CURRENT_USER, lpstrRegKey);
+ if(lRet != ERROR_SUCCESS)
+ return FALSE;
+ lRet = rk.Open(rkParent, pT->GetRegKeyName());
+ if(lRet != ERROR_SUCCESS)
+ return FALSE;
+
+ DWORD dwRet = 0;
+ lRet = rk.QueryDWORDValue(pT->GetRegCountName(), dwRet);
+ if(lRet != ERROR_SUCCESS)
+ return FALSE;
+ SetMaxEntries(dwRet);
+
+ m_arrDocs.RemoveAll();
+
+ TCHAR szRetString[t_cchItemLen] = { 0 };
+ _DocEntry de;
+
+ for(int nItem = m_nMaxEntries; nItem > 0; nItem--)
+ {
+ TCHAR szBuff[m_cchItemNameLen] = { 0 };
+ SecureHelper::wsprintf_x(szBuff, m_cchItemNameLen, pT->GetRegItemName(), nItem);
+ ULONG ulCount = t_cchItemLen;
+ lRet = rk.QueryStringValue(szBuff, szRetString, &ulCount);
+ if(lRet == ERROR_SUCCESS)
+ {
+ SecureHelper::strcpy_x(de.szDocName, _countof(de.szDocName), szRetString);
+ m_arrDocs.Add(de);
+ }
+ }
+
+ rk.Close();
+ rkParent.Close();
+
+ return pT->UpdateMenu();
+ }
+
+ BOOL WriteToRegistry(LPCTSTR lpstrRegKey)
+ {
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ CRegKeyEx rkParent;
+ CRegKeyEx rk;
+
+ LONG lRet = rkParent.Create(HKEY_CURRENT_USER, lpstrRegKey);
+ if(lRet != ERROR_SUCCESS)
+ return FALSE;
+ lRet = rk.Create(rkParent, pT->GetRegKeyName());
+ if(lRet != ERROR_SUCCESS)
+ return FALSE;
+
+ lRet = rk.SetDWORDValue(pT->GetRegCountName(), m_nMaxEntries);
+ ATLASSERT(lRet == ERROR_SUCCESS);
+
+ // set new values
+ int nItem;
+ for(nItem = m_arrDocs.GetSize(); nItem > 0; nItem--)
+ {
+ TCHAR szBuff[m_cchItemNameLen] = { 0 };
+ SecureHelper::wsprintf_x(szBuff, m_cchItemNameLen, pT->GetRegItemName(), nItem);
+ TCHAR szDocName[t_cchItemLen] = { 0 };
+ GetFromList(t_nFirstID + nItem - 1, szDocName, t_cchItemLen);
+ lRet = rk.SetStringValue(szBuff, szDocName);
+ ATLASSERT(lRet == ERROR_SUCCESS);
+ }
+
+ // delete unused keys
+ for(nItem = m_arrDocs.GetSize() + 1; nItem < m_nMaxEntries_Max; nItem++)
+ {
+ TCHAR szBuff[m_cchItemNameLen] = { 0 };
+ SecureHelper::wsprintf_x(szBuff, m_cchItemNameLen, pT->GetRegItemName(), nItem);
+ rk.DeleteValue(szBuff);
+ }
+
+ rk.Close();
+ rkParent.Close();
+
+ return TRUE;
+ }
+
+// Implementation
+ BOOL UpdateMenu()
+ {
+ if(m_hMenu == NULL)
+ return FALSE;
+ ATLASSERT(::IsMenu(m_hMenu));
+
+ int nItems = ::GetMenuItemCount(m_hMenu);
+ int nInsertPoint;
+ for(nInsertPoint = 0; nInsertPoint < nItems; nInsertPoint++)
+ {
+ CMenuItemInfo mi;
+ mi.fMask = MIIM_ID;
+ ::GetMenuItemInfo(m_hMenu, nInsertPoint, TRUE, &mi);
+ if (mi.wID == t_nFirstID)
+ break;
+ }
+ ATLASSERT(nInsertPoint < nItems && "You need a menu item with an ID = t_nFirstID");
+
+ int nItem;
+ for(nItem = t_nFirstID; nItem < t_nFirstID + m_nMaxEntries; nItem++)
+ {
+ // keep the first one as an insertion point
+ if (nItem != t_nFirstID)
+ ::DeleteMenu(m_hMenu, nItem, MF_BYCOMMAND);
+ }
+
+ TCHAR szItemText[t_cchItemLen + 6] = { 0 }; // add space for &, 2 digits, and a space
+ int nSize = m_arrDocs.GetSize();
+ nItem = 0;
+ if(nSize > 0)
+ {
+ for(nItem = 0; nItem < nSize; nItem++)
+ {
+ if(m_cchMaxItemLen == -1)
+ {
+ SecureHelper::wsprintf_x(szItemText, t_cchItemLen + 6, _T("&%i %s"), nItem + 1, m_arrDocs[nSize - 1 - nItem].szDocName);
+ }
+ else
+ {
+ TCHAR szBuff[t_cchItemLen] = { 0 };
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ bool bRet = pT->CompactDocumentName(szBuff, m_arrDocs[nSize - 1 - nItem].szDocName, m_cchMaxItemLen);
+ bRet; // avoid level 4 warning
+ ATLASSERT(bRet);
+ SecureHelper::wsprintf_x(szItemText, t_cchItemLen + 6, _T("&%i %s"), nItem + 1, szBuff);
+ }
+ ::InsertMenu(m_hMenu, nInsertPoint + nItem, MF_BYPOSITION | MF_STRING, t_nFirstID + nItem, szItemText);
+ }
+ }
+ else // empty
+ {
+ ::InsertMenu(m_hMenu, nInsertPoint, MF_BYPOSITION | MF_STRING, t_nFirstID, m_szNoEntries);
+ ::EnableMenuItem(m_hMenu, t_nFirstID, MF_GRAYED);
+ nItem++;
+ }
+ ::DeleteMenu(m_hMenu, nInsertPoint + nItem, MF_BYPOSITION);
+
+ return TRUE;
+ }
+
+// Overrideables
+ // override to provide a different method of compacting document names
+ static bool CompactDocumentName(LPTSTR lpstrOut, LPCTSTR lpstrIn, int cchLen)
+ {
+ return AtlCompactPath(lpstrOut, lpstrIn, cchLen);
+ }
+
+ static LPCTSTR GetRegKeyName()
+ {
+ return _T("Recent Document List");
+ }
+
+ static LPCTSTR GetRegCountName()
+ {
+ return _T("DocumentCount");
+ }
+
+ static LPCTSTR GetRegItemName()
+ {
+ // Note: This string is a format string used with wsprintf().
+ // Resulting formatted string must be m_cchItemNameLen or less
+ // characters long, including the terminating null character.
+ return _T("Document%i");
+ }
+
+ static LPCTSTR GetMRUEmptyText()
+ {
+ return _WTL_MRUEMPTY_TEXT;
+ }
+};
+
+class CRecentDocumentList : public CRecentDocumentListBase<CRecentDocumentList>
+{
+public:
+// nothing here
+};
+
+#endif // _WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CFindFile - file search helper class
+
+class CFindFile
+{
+public:
+// Data members
+ WIN32_FIND_DATA m_fd;
+ TCHAR m_lpszRoot[MAX_PATH];
+ TCHAR m_chDirSeparator;
+ HANDLE m_hFind;
+ BOOL m_bFound;
+
+// Constructor/destructor
+ CFindFile() : m_hFind(NULL), m_chDirSeparator(_T('\\')), m_bFound(FALSE)
+ { }
+
+ ~CFindFile()
+ {
+ Close();
+ }
+
+// Attributes
+ ULONGLONG GetFileSize() const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ ULARGE_INTEGER nFileSize = { 0 };
+
+ if(m_bFound)
+ {
+ nFileSize.LowPart = m_fd.nFileSizeLow;
+ nFileSize.HighPart = m_fd.nFileSizeHigh;
+ }
+ else
+ {
+ nFileSize.QuadPart = 0;
+ }
+
+ return nFileSize.QuadPart;
+ }
+
+ BOOL GetFileName(LPTSTR lpstrFileName, int cchLength) const
+ {
+ ATLASSERT(m_hFind != NULL);
+ if(lstrlen(m_fd.cFileName) >= cchLength)
+ return FALSE;
+
+ if(m_bFound)
+ SecureHelper::strcpy_x(lpstrFileName, cchLength, m_fd.cFileName);
+
+ return m_bFound;
+ }
+
+ BOOL GetFilePath(LPTSTR lpstrFilePath, int cchLength) const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ int nLen = lstrlen(m_lpszRoot);
+#ifndef _WIN32_WCE
+ ATLASSERT(nLen > 0);
+ if(nLen == 0)
+ return FALSE;
+
+ bool bAddSep = (m_lpszRoot[nLen - 1] != _T('\\') && m_lpszRoot[nLen - 1] !=_T('/'));
+#else // CE specific
+ // allow diskless devices (nLen == 0)
+ bool bAddSep = ((nLen == 0) || (m_lpszRoot[nLen - 1] != _T('\\') && m_lpszRoot[nLen - 1] !=_T('/')));
+#endif // _WIN32_WCE
+
+ if((lstrlen(m_lpszRoot) + (bAddSep ? 1 : 0)) >= cchLength)
+ return FALSE;
+
+ SecureHelper::strcpy_x(lpstrFilePath, cchLength, m_lpszRoot);
+
+ if(bAddSep)
+ {
+ TCHAR szSeparator[2] = { m_chDirSeparator, 0 };
+ SecureHelper::strcat_x(lpstrFilePath, cchLength, szSeparator);
+ }
+
+ SecureHelper::strcat_x(lpstrFilePath, cchLength, m_fd.cFileName);
+
+ return TRUE;
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetFileTitle(LPTSTR lpstrFileTitle, int cchLength) const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ TCHAR szBuff[MAX_PATH] = { 0 };
+ if(!GetFileName(szBuff, MAX_PATH))
+ return FALSE;
+
+ if(lstrlen(szBuff) >= cchLength || cchLength < 1)
+ return FALSE;
+
+ // find the last dot
+ LPTSTR pstrDot = (LPTSTR)_cstrrchr(szBuff, _T('.'));
+ if(pstrDot != NULL)
+ *pstrDot = 0;
+
+ SecureHelper::strcpy_x(lpstrFileTitle, cchLength, szBuff);
+
+ return TRUE;
+ }
+#endif // !_WIN32_WCE
+
+ BOOL GetFileURL(LPTSTR lpstrFileURL, int cchLength) const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ TCHAR szBuff[MAX_PATH] = { 0 };
+ if(!GetFilePath(szBuff, MAX_PATH))
+ return FALSE;
+ LPCTSTR lpstrFileURLPrefix = _T("file://");
+ if(lstrlen(szBuff) + lstrlen(lpstrFileURLPrefix) >= cchLength)
+ return FALSE;
+ SecureHelper::strcpy_x(lpstrFileURL, cchLength, lpstrFileURLPrefix);
+ SecureHelper::strcat_x(lpstrFileURL, cchLength, szBuff);
+
+ return TRUE;
+ }
+
+ BOOL GetRoot(LPTSTR lpstrRoot, int cchLength) const
+ {
+ ATLASSERT(m_hFind != NULL);
+ if(lstrlen(m_lpszRoot) >= cchLength)
+ return FALSE;
+
+ SecureHelper::strcpy_x(lpstrRoot, cchLength, m_lpszRoot);
+
+ return TRUE;
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ _CSTRING_NS::CString GetFileName() const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ _CSTRING_NS::CString ret;
+
+ if(m_bFound)
+ ret = m_fd.cFileName;
+ return ret;
+ }
+
+ _CSTRING_NS::CString GetFilePath() const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ _CSTRING_NS::CString strResult = m_lpszRoot;
+ int nLen = strResult.GetLength();
+#ifndef _WIN32_WCE
+ ATLASSERT(nLen > 0);
+ if(nLen == 0)
+ return strResult;
+
+ if((strResult[nLen - 1] != _T('\\')) && (strResult[nLen - 1] != _T('/')))
+#else // CE specific
+ // allow diskless devices (nLen == 0)
+ if((nLen == 0) || ((strResult[nLen - 1] != _T('\\')) && (strResult[nLen - 1] != _T('/'))))
+#endif // _WIN32_WCE
+ strResult += m_chDirSeparator;
+ strResult += GetFileName();
+ return strResult;
+ }
+
+#ifndef _WIN32_WCE
+ _CSTRING_NS::CString GetFileTitle() const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ _CSTRING_NS::CString strResult;
+ GetFileTitle(strResult.GetBuffer(MAX_PATH), MAX_PATH);
+ strResult.ReleaseBuffer();
+
+ return strResult;
+ }
+#endif // !_WIN32_WCE
+
+ _CSTRING_NS::CString GetFileURL() const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ _CSTRING_NS::CString strResult("file://");
+ strResult += GetFilePath();
+ return strResult;
+ }
+
+ _CSTRING_NS::CString GetRoot() const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ _CSTRING_NS::CString str = m_lpszRoot;
+ return str;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ BOOL GetLastWriteTime(FILETIME* pTimeStamp) const
+ {
+ ATLASSERT(m_hFind != NULL);
+ ATLASSERT(pTimeStamp != NULL);
+
+ if(m_bFound && pTimeStamp != NULL)
+ {
+ *pTimeStamp = m_fd.ftLastWriteTime;
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ BOOL GetLastAccessTime(FILETIME* pTimeStamp) const
+ {
+ ATLASSERT(m_hFind != NULL);
+ ATLASSERT(pTimeStamp != NULL);
+
+ if(m_bFound && pTimeStamp != NULL)
+ {
+ *pTimeStamp = m_fd.ftLastAccessTime;
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ BOOL GetCreationTime(FILETIME* pTimeStamp) const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ if(m_bFound && pTimeStamp != NULL)
+ {
+ *pTimeStamp = m_fd.ftCreationTime;
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
+ BOOL MatchesMask(DWORD dwMask) const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ if(m_bFound)
+ return ((m_fd.dwFileAttributes & dwMask) != 0);
+
+ return FALSE;
+ }
+
+ BOOL IsDots() const
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ // return TRUE if the file name is "." or ".." and
+ // the file is a directory
+
+ BOOL bResult = FALSE;
+ if(m_bFound && IsDirectory())
+ {
+ if(m_fd.cFileName[0] == _T('.') && (m_fd.cFileName[1] == _T('\0') || (m_fd.cFileName[1] == _T('.') && m_fd.cFileName[2] == _T('\0'))))
+ bResult = TRUE;
+ }
+
+ return bResult;
+ }
+
+ BOOL IsReadOnly() const
+ {
+ return MatchesMask(FILE_ATTRIBUTE_READONLY);
+ }
+
+ BOOL IsDirectory() const
+ {
+ return MatchesMask(FILE_ATTRIBUTE_DIRECTORY);
+ }
+
+ BOOL IsCompressed() const
+ {
+ return MatchesMask(FILE_ATTRIBUTE_COMPRESSED);
+ }
+
+ BOOL IsSystem() const
+ {
+ return MatchesMask(FILE_ATTRIBUTE_SYSTEM);
+ }
+
+ BOOL IsHidden() const
+ {
+ return MatchesMask(FILE_ATTRIBUTE_HIDDEN);
+ }
+
+ BOOL IsTemporary() const
+ {
+ return MatchesMask(FILE_ATTRIBUTE_TEMPORARY);
+ }
+
+ BOOL IsNormal() const
+ {
+ return MatchesMask(FILE_ATTRIBUTE_NORMAL);
+ }
+
+ BOOL IsArchived() const
+ {
+ return MatchesMask(FILE_ATTRIBUTE_ARCHIVE);
+ }
+
+// Operations
+ BOOL FindFile(LPCTSTR pstrName = NULL)
+ {
+ Close();
+
+ if(pstrName == NULL)
+ {
+ pstrName = _T("*.*");
+ }
+ else if(lstrlen(pstrName) >= MAX_PATH)
+ {
+ ATLASSERT(FALSE);
+ return FALSE;
+ }
+
+ SecureHelper::strcpy_x(m_fd.cFileName, _countof(m_fd.cFileName), pstrName);
+
+ m_hFind = ::FindFirstFile(pstrName, &m_fd);
+
+ if(m_hFind == INVALID_HANDLE_VALUE)
+ return FALSE;
+
+#ifndef _WIN32_WCE
+ bool bFullPath = (::GetFullPathName(pstrName, MAX_PATH, m_lpszRoot, NULL) != 0);
+#else // CE specific
+ errno_t nRet = SecureHelper::strncpy_x(m_lpszRoot, _countof(m_lpszRoot), pstrName, _TRUNCATE);
+ bool bFullPath = (nRet == 0 || nRet == STRUNCATE);
+#endif // _WIN32_WCE
+
+ // passed name isn't a valid path but was found by the API
+ ATLASSERT(bFullPath);
+ if(!bFullPath)
+ {
+ Close();
+ ::SetLastError(ERROR_INVALID_NAME);
+ return FALSE;
+ }
+ else
+ {
+ // find the last forward or backward whack
+ LPTSTR pstrBack = (LPTSTR)_cstrrchr(m_lpszRoot, _T('\\'));
+ LPTSTR pstrFront = (LPTSTR)_cstrrchr(m_lpszRoot, _T('/'));
+
+ if(pstrFront != NULL || pstrBack != NULL)
+ {
+ if(pstrFront == NULL)
+ pstrFront = m_lpszRoot;
+ if(pstrBack == NULL)
+ pstrBack = m_lpszRoot;
+
+ // from the start to the last whack is the root
+
+ if(pstrFront >= pstrBack)
+ *pstrFront = _T('\0');
+ else
+ *pstrBack = _T('\0');
+ }
+ }
+
+ m_bFound = TRUE;
+
+ return TRUE;
+ }
+
+ BOOL FindNextFile()
+ {
+ ATLASSERT(m_hFind != NULL);
+
+ if(m_hFind == NULL)
+ return FALSE;
+
+ if(!m_bFound)
+ return FALSE;
+
+ m_bFound = ::FindNextFile(m_hFind, &m_fd);
+
+ return m_bFound;
+ }
+
+ void Close()
+ {
+ m_bFound = FALSE;
+
+ if(m_hFind != NULL && m_hFind != INVALID_HANDLE_VALUE)
+ {
+ ::FindClose(m_hFind);
+ m_hFind = NULL;
+ }
+ }
+
+// Helper
+ static const TCHAR* _cstrrchr(const TCHAR* p, TCHAR ch)
+ {
+#ifdef _ATL_MIN_CRT
+ const TCHAR* lpsz = NULL;
+ while (*p != 0)
+ {
+ if (*p == ch)
+ lpsz = p;
+ p = ::CharNext(p);
+ }
+ return lpsz;
+#else // !_ATL_MIN_CRT
+ return _tcsrchr(p, ch);
+#endif // !_ATL_MIN_CRT
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Global functions for stock GDI objects
+
+inline HPEN AtlGetStockPen(int nPen)
+{
+#if (_WIN32_WINNT >= 0x0500) && !defined(_WIN32_WCE)
+ ATLASSERT(nPen == WHITE_PEN || nPen == BLACK_PEN || nPen == NULL_PEN || nPen == DC_PEN);
+#else
+ ATLASSERT(nPen == WHITE_PEN || nPen == BLACK_PEN || nPen == NULL_PEN);
+#endif
+ return (HPEN)::GetStockObject(nPen);
+}
+
+inline HBRUSH AtlGetStockBrush(int nBrush)
+{
+#if (_WIN32_WINNT >= 0x0500) && !defined(_WIN32_WCE)
+ ATLASSERT((nBrush >= WHITE_BRUSH && nBrush <= HOLLOW_BRUSH) || nBrush == DC_BRUSH);
+#else
+ ATLASSERT(nBrush >= WHITE_BRUSH && nBrush <= HOLLOW_BRUSH);
+#endif
+ return (HBRUSH)::GetStockObject(nBrush);
+}
+
+inline HFONT AtlGetStockFont(int nFont)
+{
+#ifndef _WIN32_WCE
+ ATLASSERT((nFont >= OEM_FIXED_FONT && nFont <= SYSTEM_FIXED_FONT) || nFont == DEFAULT_GUI_FONT);
+#else // CE specific
+ ATLASSERT(nFont == SYSTEM_FONT);
+#endif // _WIN32_WCE
+ return (HFONT)::GetStockObject(nFont);
+}
+
+inline HPALETTE AtlGetStockPalette(int nPalette)
+{
+ ATLASSERT(nPalette == DEFAULT_PALETTE); // the only one supported
+ return (HPALETTE)::GetStockObject(nPalette);
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Global function for compacting a path by replacing parts with ellipsis
+
+// helper for multi-byte character sets
+inline bool _IsDBCSTrailByte(LPCTSTR lpstr, int nChar)
+{
+#ifndef _UNICODE
+ int i = nChar;
+ for( ; i > 0; i--)
+ {
+ if(!::IsDBCSLeadByte(lpstr[i - 1]))
+ break;
+ }
+ return ((nChar > 0) && (((nChar - i) & 1) != 0));
+#else // _UNICODE
+ lpstr; nChar;
+ return false;
+#endif // _UNICODE
+}
+
+inline bool AtlCompactPath(LPTSTR lpstrOut, LPCTSTR lpstrIn, int cchLen)
+{
+ ATLASSERT(lpstrOut != NULL);
+ ATLASSERT(lpstrIn != NULL);
+ ATLASSERT(cchLen > 0);
+
+ LPCTSTR szEllipsis = _T("...");
+ const int cchEndEllipsis = 3;
+ const int cchMidEllipsis = 4;
+
+ if(lstrlen(lpstrIn) < cchLen)
+ {
+ SecureHelper::strcpy_x(lpstrOut, cchLen, lpstrIn);
+ return true;
+ }
+
+ lpstrOut[0] = 0;
+
+ // check if the separator is a slash or a backslash
+ TCHAR chSlash = _T('\\');
+ for(LPTSTR lpstr = (LPTSTR)lpstrIn; *lpstr != 0; lpstr = ::CharNext(lpstr))
+ {
+ if((*lpstr == _T('/')) || (*lpstr == _T('\\')))
+ chSlash = *lpstr;
+ }
+
+ // find the filename portion of the path
+ LPCTSTR lpstrFileName = lpstrIn;
+ for(LPCTSTR pPath = lpstrIn; *pPath; pPath = ::CharNext(pPath))
+ {
+ if((pPath[0] == _T('\\') || pPath[0] == _T(':') || pPath[0] == _T('/'))
+ && pPath[1] && pPath[1] != _T('\\') && pPath[1] != _T('/'))
+ lpstrFileName = pPath + 1;
+ }
+ int cchFileName = lstrlen(lpstrFileName);
+
+ // handle just the filename without a path
+ if(lpstrFileName == lpstrIn && cchLen > cchEndEllipsis)
+ {
+ bool bRet = (SecureHelper::strncpy_x(lpstrOut, cchLen, lpstrIn, cchLen - cchEndEllipsis - 1) == 0);
+ if(bRet)
+ {
+#ifndef _UNICODE
+ if(_IsDBCSTrailByte(lpstrIn, cchLen - cchEndEllipsis))
+ lpstrOut[cchLen - cchEndEllipsis - 1] = 0;
+#endif // _UNICODE
+ SecureHelper::strcat_x(lpstrOut, cchLen, szEllipsis);
+ }
+ return bRet;
+ }
+
+ // handle just ellipsis
+ if((cchLen < (cchMidEllipsis + cchEndEllipsis)))
+ {
+ for(int i = 0; i < cchLen - 1; i++)
+ lpstrOut[i] = ((i + 1) == cchMidEllipsis) ? chSlash : _T('.');
+ lpstrOut[cchLen - 1] = 0;
+ return true;
+ }
+
+ // calc how much we have to copy
+ int cchToCopy = cchLen - (cchMidEllipsis + cchFileName) - 1;
+
+ if(cchToCopy < 0)
+ cchToCopy = 0;
+
+#ifndef _UNICODE
+ if(cchToCopy > 0 && _IsDBCSTrailByte(lpstrIn, cchToCopy))
+ cchToCopy--;
+#endif // _UNICODE
+
+ bool bRet = (SecureHelper::strncpy_x(lpstrOut, cchLen, lpstrIn, cchToCopy) == 0);
+ if(!bRet)
+ return false;
+
+ // add ellipsis
+ SecureHelper::strcat_x(lpstrOut, cchLen, szEllipsis);
+ if(!bRet)
+ return false;
+ TCHAR szSlash[2] = { chSlash, 0 };
+ SecureHelper::strcat_x(lpstrOut, cchLen, szSlash);
+ if(!bRet)
+ return false;
+
+ // add filename (and ellipsis, if needed)
+ if(cchLen > (cchMidEllipsis + cchFileName))
+ {
+ SecureHelper::strcat_x(lpstrOut, cchLen, lpstrFileName);
+ }
+ else
+ {
+ cchToCopy = cchLen - cchMidEllipsis - cchEndEllipsis - 1;
+#ifndef _UNICODE
+ if(cchToCopy > 0 && _IsDBCSTrailByte(lpstrFileName, cchToCopy))
+ cchToCopy--;
+#endif // _UNICODE
+ bRet = (SecureHelper::strncpy_x(&lpstrOut[cchMidEllipsis], cchLen - cchMidEllipsis, lpstrFileName, cchToCopy) == 0);
+ if(bRet)
+ SecureHelper::strcat_x(lpstrOut, cchLen, szEllipsis);
+ }
+
+ return bRet;
+}
+
+}; // namespace WTL
+
+#endif // __ATLMISC_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlprint.h b/plugins/SmartAutoReplier/wtl/atlprint.h
new file mode 100644
index 0000000000..50a7fb17dc
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlprint.h
@@ -0,0 +1,1109 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLPRINT_H__
+#define __ATLPRINT_H__
+
+#pragma once
+
+#ifdef _WIN32_WCE
+ #error atlprint.h is not supported on Windows CE
+#endif
+
+#ifndef __ATLAPP_H__
+ #error atlprint.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atlprint.h requires atlwin.h to be included first
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CPrinterInfo<t_nInfo>
+// CPrinterT<t_bManaged>
+// CDevModeT<t_bManaged>
+// CPrinterDC
+// CPrintJobInfo
+// CPrintJob
+// CPrintPreview
+// CPrintPreviewWindowImpl<T, TBase, TWinTraits>
+// CPrintPreviewWindow
+// CZoomPrintPreviewWindowImpl<T, TBase, TWinTraits>
+// CZoomPrintPreviewWindow
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CPrinterInfo - This class wraps all of the PRINTER_INFO_* structures
+// and provided by ::GetPrinter.
+
+template <unsigned int t_nInfo>
+class _printer_info
+{
+public:
+ typedef void infotype;
+};
+
+template <> class _printer_info<1> { public: typedef PRINTER_INFO_1 infotype; };
+template <> class _printer_info<2> { public: typedef PRINTER_INFO_2 infotype; };
+template <> class _printer_info<3> { public: typedef PRINTER_INFO_3 infotype; };
+template <> class _printer_info<4> { public: typedef PRINTER_INFO_4 infotype; };
+template <> class _printer_info<5> { public: typedef PRINTER_INFO_5 infotype; };
+template <> class _printer_info<6> { public: typedef PRINTER_INFO_6 infotype; };
+template <> class _printer_info<7> { public: typedef PRINTER_INFO_7 infotype; };
+// these are not in the old (vc6.0) headers
+#ifdef _ATL_USE_NEW_PRINTER_INFO
+template <> class _printer_info<8> { public: typedef PRINTER_INFO_8 infotype; };
+template <> class _printer_info<9> { public: typedef PRINTER_INFO_9 infotype; };
+#endif // _ATL_USE_NEW_PRINTER_INFO
+
+
+template <unsigned int t_nInfo>
+class CPrinterInfo
+{
+public:
+// Data members
+ typename _printer_info<t_nInfo>::infotype* m_pi;
+
+// Constructor/destructor
+ CPrinterInfo() : m_pi(NULL)
+ { }
+
+ CPrinterInfo(HANDLE hPrinter) : m_pi(NULL)
+ {
+ GetPrinterInfo(hPrinter);
+ }
+
+ ~CPrinterInfo()
+ {
+ Cleanup();
+ }
+
+// Operations
+ bool GetPrinterInfo(HANDLE hPrinter)
+ {
+ Cleanup();
+ return GetPrinterInfoHelper(hPrinter, (BYTE**)&m_pi, t_nInfo);
+ }
+
+// Implementation
+ void Cleanup()
+ {
+ delete [] (BYTE*)m_pi;
+ m_pi = NULL;
+ }
+
+ static bool GetPrinterInfoHelper(HANDLE hPrinter, BYTE** pi, int nIndex)
+ {
+ ATLASSERT(pi != NULL);
+ DWORD dw = 0;
+ BYTE* pb = NULL;
+ ::GetPrinter(hPrinter, nIndex, NULL, 0, &dw);
+ if (dw > 0)
+ {
+ ATLTRY(pb = new BYTE[dw]);
+ if (pb != NULL)
+ {
+ memset(pb, 0, dw);
+ DWORD dwNew;
+ if (!::GetPrinter(hPrinter, nIndex, pb, dw, &dwNew))
+ {
+ delete [] pb;
+ pb = NULL;
+ }
+ }
+ }
+ *pi = pb;
+ return (pb != NULL);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPrinter - Wrapper class for a HANDLE to a printer
+
+template <bool t_bManaged>
+class CPrinterT
+{
+public:
+// Data members
+ HANDLE m_hPrinter;
+
+// Constructor/destructor
+ CPrinterT(HANDLE hPrinter = NULL) : m_hPrinter(hPrinter)
+ { }
+
+ ~CPrinterT()
+ {
+ ClosePrinter();
+ }
+
+// Operations
+ CPrinterT& operator =(HANDLE hPrinter)
+ {
+ if (hPrinter != m_hPrinter)
+ {
+ ClosePrinter();
+ m_hPrinter = hPrinter;
+ }
+ return *this;
+ }
+
+ bool IsNull() const { return (m_hPrinter == NULL); }
+
+ bool OpenPrinter(HANDLE hDevNames, const DEVMODE* pDevMode = NULL)
+ {
+ bool b = false;
+ DEVNAMES* pdn = (DEVNAMES*)::GlobalLock(hDevNames);
+ if (pdn != NULL)
+ {
+ LPTSTR lpszPrinterName = (LPTSTR)pdn + pdn->wDeviceOffset;
+ b = OpenPrinter(lpszPrinterName, pDevMode);
+ ::GlobalUnlock(hDevNames);
+ }
+ return b;
+ }
+
+ bool OpenPrinter(LPCTSTR lpszPrinterName, const DEVMODE* pDevMode = NULL)
+ {
+ ClosePrinter();
+ PRINTER_DEFAULTS pdefs = { NULL, (DEVMODE*)pDevMode, PRINTER_ACCESS_USE };
+ ::OpenPrinter((LPTSTR) lpszPrinterName, &m_hPrinter, (pDevMode == NULL) ? NULL : &pdefs);
+
+ return (m_hPrinter != NULL);
+ }
+
+ bool OpenPrinter(LPCTSTR lpszPrinterName, PRINTER_DEFAULTS* pprintdefs)
+ {
+ ClosePrinter();
+ ::OpenPrinter((LPTSTR) lpszPrinterName, &m_hPrinter, pprintdefs);
+ return (m_hPrinter != NULL);
+ }
+
+ bool OpenDefaultPrinter(const DEVMODE* pDevMode = NULL)
+ {
+ ClosePrinter();
+ const int cchBuff = 512;
+ TCHAR buffer[cchBuff];
+ buffer[0] = 0;
+ ::GetProfileString(_T("windows"), _T("device"), _T(",,,"), buffer, cchBuff);
+ int nLen = lstrlen(buffer);
+ if (nLen != 0)
+ {
+ LPTSTR lpsz = buffer;
+ while (*lpsz)
+ {
+ if (*lpsz == _T(','))
+ {
+ *lpsz = 0;
+ break;
+ }
+ lpsz = CharNext(lpsz);
+ }
+ PRINTER_DEFAULTS pdefs = { NULL, (DEVMODE*)pDevMode, PRINTER_ACCESS_USE };
+ ::OpenPrinter(buffer, &m_hPrinter, (pDevMode == NULL) ? NULL : &pdefs);
+ }
+ return m_hPrinter != NULL;
+ }
+
+ void ClosePrinter()
+ {
+ if (m_hPrinter != NULL)
+ {
+ if (t_bManaged)
+ ::ClosePrinter(m_hPrinter);
+ m_hPrinter = NULL;
+ }
+ }
+
+ bool PrinterProperties(HWND hWnd = NULL)
+ {
+ if (hWnd == NULL)
+ hWnd = ::GetActiveWindow();
+ return !!::PrinterProperties(hWnd, m_hPrinter);
+ }
+
+ HANDLE CopyToHDEVNAMES() const
+ {
+ HANDLE h = NULL;
+ CPrinterInfo<5> pinfon5;
+ CPrinterInfo<2> pinfon2;
+ LPTSTR lpszPrinterName = NULL;
+ // Some printers fail for PRINTER_INFO_5 in some situations
+ if (pinfon5.GetPrinterInfo(m_hPrinter))
+ lpszPrinterName = pinfon5.m_pi->pPrinterName;
+ else if (pinfon2.GetPrinterInfo(m_hPrinter))
+ lpszPrinterName = pinfon2.m_pi->pPrinterName;
+ if (lpszPrinterName != NULL)
+ {
+ int nLen = sizeof(DEVNAMES) + (lstrlen(lpszPrinterName) + 1) * sizeof(TCHAR);
+ h = ::GlobalAlloc(GMEM_MOVEABLE, nLen);
+ BYTE* pv = (BYTE*)::GlobalLock(h);
+ DEVNAMES* pdev = (DEVNAMES*)pv;
+ if (pv != NULL)
+ {
+ memset(pv, 0, nLen);
+ pdev->wDeviceOffset = sizeof(DEVNAMES) / sizeof(TCHAR);
+ pv = pv + sizeof(DEVNAMES); // now points to end
+ SecureHelper::strcpy_x((LPTSTR)pv, lstrlen(lpszPrinterName) + 1, lpszPrinterName);
+ ::GlobalUnlock(h);
+ }
+ }
+ return h;
+ }
+
+ HDC CreatePrinterDC(const DEVMODE* pdm = NULL) const
+ {
+ CPrinterInfo<5> pinfo5;
+ CPrinterInfo<2> pinfo2;
+ HDC hDC = NULL;
+ LPTSTR lpszPrinterName = NULL;
+ // Some printers fail for PRINTER_INFO_5 in some situations
+ if (pinfo5.GetPrinterInfo(m_hPrinter))
+ lpszPrinterName = pinfo5.m_pi->pPrinterName;
+ else if (pinfo2.GetPrinterInfo(m_hPrinter))
+ lpszPrinterName = pinfo2.m_pi->pPrinterName;
+ if (lpszPrinterName != NULL)
+ hDC = ::CreateDC(NULL, lpszPrinterName, NULL, pdm);
+ return hDC;
+ }
+
+ HDC CreatePrinterIC(const DEVMODE* pdm = NULL) const
+ {
+ CPrinterInfo<5> pinfo5;
+ CPrinterInfo<2> pinfo2;
+ HDC hDC = NULL;
+ LPTSTR lpszPrinterName = NULL;
+ // Some printers fail for PRINTER_INFO_5 in some situations
+ if (pinfo5.GetPrinterInfo(m_hPrinter))
+ lpszPrinterName = pinfo5.m_pi->pPrinterName;
+ else if (pinfo2.GetPrinterInfo(m_hPrinter))
+ lpszPrinterName = pinfo2.m_pi->pPrinterName;
+ if (lpszPrinterName != NULL)
+ hDC = ::CreateIC(NULL, lpszPrinterName, NULL, pdm);
+ return hDC;
+ }
+
+ void Attach(HANDLE hPrinter)
+ {
+ ClosePrinter();
+ m_hPrinter = hPrinter;
+ }
+
+ HANDLE Detach()
+ {
+ HANDLE hPrinter = m_hPrinter;
+ m_hPrinter = NULL;
+ return hPrinter;
+ }
+
+ operator HANDLE() const { return m_hPrinter; }
+};
+
+typedef CPrinterT<false> CPrinterHandle;
+typedef CPrinterT<true> CPrinter;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CDevMode - Wrapper class for DEVMODE
+
+template <bool t_bManaged>
+class CDevModeT
+{
+public:
+// Data members
+ HANDLE m_hDevMode;
+ DEVMODE* m_pDevMode;
+
+// Constructor/destructor
+ CDevModeT(HANDLE hDevMode = NULL) : m_hDevMode(hDevMode)
+ {
+ m_pDevMode = (m_hDevMode != NULL) ? (DEVMODE*)::GlobalLock(m_hDevMode) : NULL;
+ }
+
+ ~CDevModeT()
+ {
+ Cleanup();
+ }
+
+// Operations
+ CDevModeT<t_bManaged>& operator =(HANDLE hDevMode)
+ {
+ Attach(hDevMode);
+ return *this;
+ }
+
+ void Attach(HANDLE hDevModeNew)
+ {
+ Cleanup();
+ m_hDevMode = hDevModeNew;
+ m_pDevMode = (m_hDevMode != NULL) ? (DEVMODE*)::GlobalLock(m_hDevMode) : NULL;
+ }
+
+ HANDLE Detach()
+ {
+ if (m_hDevMode != NULL)
+ ::GlobalUnlock(m_hDevMode);
+ HANDLE hDevMode = m_hDevMode;
+ m_hDevMode = NULL;
+ return hDevMode;
+ }
+
+ bool IsNull() const { return (m_hDevMode == NULL); }
+
+ bool CopyFromPrinter(HANDLE hPrinter)
+ {
+ CPrinterInfo<2> pinfo;
+ bool b = pinfo.GetPrinterInfo(hPrinter);
+ if (b)
+ b = CopyFromDEVMODE(pinfo.m_pi->pDevMode);
+ return b;
+ }
+
+ bool CopyFromDEVMODE(const DEVMODE* pdm)
+ {
+ if (pdm == NULL)
+ return false;
+ int nSize = pdm->dmSize + pdm->dmDriverExtra;
+ HANDLE h = ::GlobalAlloc(GMEM_MOVEABLE, nSize);
+ if (h != NULL)
+ {
+ void* p = ::GlobalLock(h);
+ SecureHelper::memcpy_x(p, nSize, pdm, nSize);
+ ::GlobalUnlock(h);
+ }
+ Attach(h);
+ return (h != NULL);
+ }
+
+ bool CopyFromHDEVMODE(HANDLE hdm)
+ {
+ bool b = false;
+ if (hdm != NULL)
+ {
+ DEVMODE* pdm = (DEVMODE*)::GlobalLock(hdm);
+ b = CopyFromDEVMODE(pdm);
+ ::GlobalUnlock(hdm);
+ }
+ return b;
+ }
+
+ HANDLE CopyToHDEVMODE()
+ {
+ if ((m_hDevMode == NULL) || (m_pDevMode == NULL))
+ return NULL;
+ int nSize = m_pDevMode->dmSize + m_pDevMode->dmDriverExtra;
+ HANDLE h = ::GlobalAlloc(GMEM_MOVEABLE, nSize);
+ if (h != NULL)
+ {
+ void* p = ::GlobalLock(h);
+ SecureHelper::memcpy_x(p, nSize, m_pDevMode, nSize);
+ ::GlobalUnlock(h);
+ }
+ return h;
+ }
+
+ // If this devmode was for another printer, this will create a new devmode
+ // based on the existing devmode, but retargeted at the new printer
+ bool UpdateForNewPrinter(HANDLE hPrinter)
+ {
+ bool bRet = false;
+ LONG nLen = ::DocumentProperties(NULL, hPrinter, NULL, NULL, NULL, 0);
+ CTempBuffer<DEVMODE, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ DEVMODE* pdm = buff.AllocateBytes(nLen);
+ if(pdm != NULL)
+ {
+ memset(pdm, 0, nLen);
+ LONG l = ::DocumentProperties(NULL, hPrinter, NULL, pdm, m_pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER);
+ if (l == IDOK)
+ bRet = CopyFromDEVMODE(pdm);
+ }
+
+ return bRet;
+ }
+
+ bool DocumentProperties(HANDLE hPrinter, HWND hWnd = NULL)
+ {
+ CPrinterInfo<1> pi;
+ pi.GetPrinterInfo(hPrinter);
+ if (hWnd == NULL)
+ hWnd = ::GetActiveWindow();
+
+ bool bRet = false;
+ LONG nLen = ::DocumentProperties(hWnd, hPrinter, pi.m_pi->pName, NULL, NULL, 0);
+ CTempBuffer<DEVMODE, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ DEVMODE* pdm = buff.AllocateBytes(nLen);
+ if(pdm != NULL)
+ {
+ memset(pdm, 0, nLen);
+ LONG l = ::DocumentProperties(hWnd, hPrinter, pi.m_pi->pName, pdm, m_pDevMode, DM_IN_BUFFER | DM_OUT_BUFFER | DM_PROMPT);
+ if (l == IDOK)
+ bRet = CopyFromDEVMODE(pdm);
+ }
+
+ return bRet;
+ }
+
+ operator HANDLE() const { return m_hDevMode; }
+
+ operator DEVMODE*() const { return m_pDevMode; }
+
+// Implementation
+ void Cleanup()
+ {
+ if (m_hDevMode != NULL)
+ {
+ ::GlobalUnlock(m_hDevMode);
+ if(t_bManaged)
+ ::GlobalFree(m_hDevMode);
+ m_hDevMode = NULL;
+ }
+ }
+};
+
+typedef CDevModeT<false> CDevModeHandle;
+typedef CDevModeT<true> CDevMode;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPrinterDC
+
+class CPrinterDC : public CDC
+{
+public:
+// Constructors/destructor
+ CPrinterDC()
+ {
+ CPrinter printer;
+ printer.OpenDefaultPrinter();
+ Attach(printer.CreatePrinterDC());
+ ATLASSERT(m_hDC != NULL);
+ }
+
+ CPrinterDC(HANDLE hPrinter, const DEVMODE* pdm = NULL)
+ {
+ CPrinterHandle p;
+ p.Attach(hPrinter);
+ Attach(p.CreatePrinterDC(pdm));
+ ATLASSERT(m_hDC != NULL);
+ }
+
+ ~CPrinterDC()
+ {
+ DeleteDC();
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPrintJob - Wraps a set of tasks for a specific printer (StartDoc/EndDoc)
+// Handles aborting, background printing
+
+// Defines callbacks used by CPrintJob (not a COM interface)
+class ATL_NO_VTABLE IPrintJobInfo
+{
+public:
+ virtual void BeginPrintJob(HDC hDC) = 0; // allocate handles needed, etc.
+ virtual void EndPrintJob(HDC hDC, bool bAborted) = 0; // free handles, etc.
+ virtual void PrePrintPage(UINT nPage, HDC hDC) = 0;
+ virtual bool PrintPage(UINT nPage, HDC hDC) = 0;
+ virtual void PostPrintPage(UINT nPage, HDC hDC) = 0;
+ // If you want per page devmodes, return the DEVMODE* to use for nPage.
+ // You can optimize by only returning a new DEVMODE* when it is different
+ // from the one for nLastPage, otherwise return NULL.
+ // When nLastPage==0, the current DEVMODE* will be the default passed to
+ // StartPrintJob.
+ // Note: During print preview, nLastPage will always be "0".
+ virtual DEVMODE* GetNewDevModeForPage(UINT nLastPage, UINT nPage) = 0;
+ virtual bool IsValidPage(UINT nPage) = 0;
+};
+
+// Provides a default implementatin for IPrintJobInfo
+// Typically, MI'd into a document or view class
+class ATL_NO_VTABLE CPrintJobInfo : public IPrintJobInfo
+{
+public:
+ virtual void BeginPrintJob(HDC /*hDC*/) // allocate handles needed, etc
+ {
+ }
+
+ virtual void EndPrintJob(HDC /*hDC*/, bool /*bAborted*/) // free handles, etc
+ {
+ }
+
+ virtual void PrePrintPage(UINT /*nPage*/, HDC hDC)
+ {
+ m_nPJState = ::SaveDC(hDC);
+ }
+
+ virtual bool PrintPage(UINT /*nPage*/, HDC /*hDC*/) = 0;
+
+ virtual void PostPrintPage(UINT /*nPage*/, HDC hDC)
+ {
+ RestoreDC(hDC, m_nPJState);
+ }
+
+ virtual DEVMODE* GetNewDevModeForPage(UINT /*nLastPage*/, UINT /*nPage*/)
+ {
+ return NULL;
+ }
+
+ virtual bool IsValidPage(UINT /*nPage*/)
+ {
+ return true;
+ }
+
+// Implementation - data
+ int m_nPJState;
+};
+
+
+class CPrintJob
+{
+public:
+// Data members
+ CPrinterHandle m_printer;
+ IPrintJobInfo* m_pInfo;
+ DEVMODE* m_pDefDevMode;
+ DOCINFO m_docinfo;
+ int m_nJobID;
+ bool m_bCancel;
+ bool m_bComplete;
+ unsigned long m_nStartPage;
+ unsigned long m_nEndPage;
+
+// Constructor/destructor
+ CPrintJob() : m_nJobID(0), m_bCancel(false), m_bComplete(true)
+ { }
+
+ ~CPrintJob()
+ {
+ ATLASSERT(IsJobComplete()); // premature destruction?
+ }
+
+// Operations
+ bool IsJobComplete() const
+ {
+ return m_bComplete;
+ }
+
+ bool StartPrintJob(bool bBackground, HANDLE hPrinter, DEVMODE* pDefaultDevMode,
+ IPrintJobInfo* pInfo, LPCTSTR lpszDocName,
+ unsigned long nStartPage, unsigned long nEndPage,
+ bool bPrintToFile = false, LPCTSTR lpstrOutputFile = NULL)
+ {
+ ATLASSERT(m_bComplete); // previous job not done yet?
+ if (pInfo == NULL)
+ return false;
+
+ memset(&m_docinfo, 0, sizeof(m_docinfo));
+ m_docinfo.cbSize = sizeof(m_docinfo);
+ m_docinfo.lpszDocName = lpszDocName;
+ m_pInfo = pInfo;
+ m_nStartPage = nStartPage;
+ m_nEndPage = nEndPage;
+ m_printer.Attach(hPrinter);
+ m_pDefDevMode = pDefaultDevMode;
+ m_bComplete = false;
+
+ if(bPrintToFile)
+ m_docinfo.lpszOutput = (lpstrOutputFile != NULL) ? lpstrOutputFile : _T("FILE:");
+
+ if (!bBackground)
+ {
+ m_bComplete = true;
+ return StartHelper();
+ }
+
+ // Create a thread and return
+ DWORD dwThreadID = 0;
+#if !defined(_ATL_MIN_CRT) && defined(_MT)
+ HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, (UINT (WINAPI*)(void*))StartProc, this, 0, (UINT*)&dwThreadID);
+#else
+ HANDLE hThread = ::CreateThread(NULL, 0, StartProc, (void*)this, 0, &dwThreadID);
+#endif
+ if (hThread == NULL)
+ return false;
+
+ ::CloseHandle(hThread);
+
+ return true;
+ }
+
+// Implementation
+ static DWORD WINAPI StartProc(void* p)
+ {
+ CPrintJob* pThis = (CPrintJob*)p;
+ pThis->StartHelper();
+ pThis->m_bComplete = true;
+ return 0;
+ }
+
+ bool StartHelper()
+ {
+ CDC dcPrinter;
+ dcPrinter.Attach(m_printer.CreatePrinterDC(m_pDefDevMode));
+ if (dcPrinter.IsNull())
+ return false;
+
+ m_nJobID = ::StartDoc(dcPrinter, &m_docinfo);
+ if (m_nJobID <= 0)
+ return false;
+
+ m_pInfo->BeginPrintJob(dcPrinter);
+
+ // print all the pages now
+ unsigned long nLastPage = 0;
+ for (unsigned long nPage = m_nStartPage; nPage <= m_nEndPage; nPage++)
+ {
+ if (!m_pInfo->IsValidPage(nPage))
+ break;
+ DEVMODE* pdm = m_pInfo->GetNewDevModeForPage(nLastPage, nPage);
+ if (pdm != NULL)
+ dcPrinter.ResetDC(pdm);
+ dcPrinter.StartPage();
+ m_pInfo->PrePrintPage(nPage, dcPrinter);
+ if (!m_pInfo->PrintPage(nPage, dcPrinter))
+ m_bCancel = true;
+ m_pInfo->PostPrintPage(nPage, dcPrinter);
+ dcPrinter.EndPage();
+ if (m_bCancel)
+ break;
+ nLastPage = nPage;
+ }
+
+ m_pInfo->EndPrintJob(dcPrinter, m_bCancel);
+ if (m_bCancel)
+ ::AbortDoc(dcPrinter);
+ else
+ ::EndDoc(dcPrinter);
+ m_nJobID = 0;
+ return true;
+ }
+
+ // Cancels a print job. Can be called asynchronously.
+ void CancelPrintJob()
+ {
+ m_bCancel = true;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPrintPreview - Adds print preview support to an existing window
+
+class CPrintPreview
+{
+public:
+// Data members
+ IPrintJobInfo* m_pInfo;
+ CPrinterHandle m_printer;
+ CEnhMetaFile m_meta;
+ DEVMODE* m_pDefDevMode;
+ DEVMODE* m_pCurDevMode;
+ SIZE m_sizeCurPhysOffset;
+
+// Constructor
+ CPrintPreview() : m_pInfo(NULL), m_pDefDevMode(NULL), m_pCurDevMode(NULL)
+ {
+ m_sizeCurPhysOffset.cx = 0;
+ m_sizeCurPhysOffset.cy = 0;
+ }
+
+// Operations
+ void SetPrintPreviewInfo(HANDLE hPrinter, DEVMODE* pDefaultDevMode, IPrintJobInfo* pji)
+ {
+ m_printer.Attach(hPrinter);
+ m_pDefDevMode = pDefaultDevMode;
+ m_pInfo = pji;
+ m_nCurPage = 0;
+ m_pCurDevMode = NULL;
+ }
+
+ void SetEnhMetaFile(HENHMETAFILE hEMF)
+ {
+ m_meta = hEMF;
+ }
+
+ void SetPage(int nPage)
+ {
+ if (!m_pInfo->IsValidPage(nPage))
+ return;
+ m_nCurPage = nPage;
+ m_pCurDevMode = m_pInfo->GetNewDevModeForPage(0, nPage);
+ if (m_pCurDevMode == NULL)
+ m_pCurDevMode = m_pDefDevMode;
+ CDC dcPrinter = m_printer.CreatePrinterDC(m_pCurDevMode);
+
+ int iWidth = dcPrinter.GetDeviceCaps(PHYSICALWIDTH);
+ int iHeight = dcPrinter.GetDeviceCaps(PHYSICALHEIGHT);
+ int nLogx = dcPrinter.GetDeviceCaps(LOGPIXELSX);
+ int nLogy = dcPrinter.GetDeviceCaps(LOGPIXELSY);
+
+ RECT rcMM = { 0, 0, ::MulDiv(iWidth, 2540, nLogx), ::MulDiv(iHeight, 2540, nLogy) };
+
+ m_sizeCurPhysOffset.cx = dcPrinter.GetDeviceCaps(PHYSICALOFFSETX);
+ m_sizeCurPhysOffset.cy = dcPrinter.GetDeviceCaps(PHYSICALOFFSETY);
+
+ CEnhMetaFileDC dcMeta(dcPrinter, &rcMM);
+ m_pInfo->PrePrintPage(nPage, dcMeta);
+ m_pInfo->PrintPage(nPage, dcMeta);
+ m_pInfo->PostPrintPage(nPage, dcMeta);
+ m_meta.Attach(dcMeta.Close());
+ }
+
+ void GetPageRect(RECT& rc, LPRECT prc)
+ {
+ int x1 = rc.right-rc.left;
+ int y1 = rc.bottom - rc.top;
+ if ((x1 < 0) || (y1 < 0))
+ return;
+
+ CEnhMetaFileInfo emfinfo(m_meta);
+ ENHMETAHEADER* pmh = emfinfo.GetEnhMetaFileHeader();
+
+ // Compute whether we are OK vertically or horizontally
+ int x2 = pmh->szlDevice.cx;
+ int y2 = pmh->szlDevice.cy;
+ int y1p = MulDiv(x1, y2, x2);
+ int x1p = MulDiv(y1, x2, y2);
+ ATLASSERT((x1p <= x1) || (y1p <= y1));
+ if (x1p <= x1)
+ {
+ prc->left = rc.left + (x1 - x1p) / 2;
+ prc->right = prc->left + x1p;
+ prc->top = rc.top;
+ prc->bottom = rc.bottom;
+ }
+ else
+ {
+ prc->left = rc.left;
+ prc->right = rc.right;
+ prc->top = rc.top + (y1 - y1p) / 2;
+ prc->bottom = prc->top + y1p;
+ }
+ }
+
+// Painting helpers
+ void DoPaint(CDCHandle dc)
+ {
+ // this one is not used
+ }
+
+ void DoPaint(CDCHandle dc, RECT& rc)
+ {
+ CEnhMetaFileInfo emfinfo(m_meta);
+ ENHMETAHEADER* pmh = emfinfo.GetEnhMetaFileHeader();
+ int nOffsetX = MulDiv(m_sizeCurPhysOffset.cx, rc.right-rc.left, pmh->szlDevice.cx);
+ int nOffsetY = MulDiv(m_sizeCurPhysOffset.cy, rc.bottom-rc.top, pmh->szlDevice.cy);
+
+ dc.OffsetWindowOrg(-nOffsetX, -nOffsetY);
+ dc.PlayMetaFile(m_meta, &rc);
+ }
+
+// Implementation - data
+ int m_nCurPage;
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CPrintPreviewWindow - Implements a print preview window
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CPrintPreviewWindowImpl : public ATL::CWindowImpl<T, TBase, TWinTraits>, public CPrintPreview
+{
+public:
+ DECLARE_WND_CLASS_EX(NULL, CS_VREDRAW | CS_HREDRAW, -1)
+
+ enum { m_cxOffset = 10, m_cyOffset = 10 };
+
+// Constructor
+ CPrintPreviewWindowImpl() : m_nMaxPage(0), m_nMinPage(0)
+ { }
+
+// Operations
+ void SetPrintPreviewInfo(HANDLE hPrinter, DEVMODE* pDefaultDevMode,
+ IPrintJobInfo* pji, int nMinPage, int nMaxPage)
+ {
+ CPrintPreview::SetPrintPreviewInfo(hPrinter, pDefaultDevMode, pji);
+ m_nMinPage = nMinPage;
+ m_nMaxPage = nMaxPage;
+ }
+
+ bool NextPage()
+ {
+ if (m_nCurPage == m_nMaxPage)
+ return false;
+ SetPage(m_nCurPage + 1);
+ Invalidate();
+ return true;
+ }
+
+ bool PrevPage()
+ {
+ if (m_nCurPage == m_nMinPage)
+ return false;
+ if (m_nCurPage == 0)
+ return false;
+ SetPage(m_nCurPage - 1);
+ Invalidate();
+ return true;
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CPrintPreviewWindowImpl)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+ END_MSG_MAP()
+
+ LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1; // no need for the background
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ RECT rc = { 0 };
+
+ if(wParam != NULL)
+ {
+ pT->DoPrePaint((HDC)wParam, rc);
+ pT->DoPaint((HDC)wParam, rc);
+ }
+ else
+ {
+ CPaintDC dc(m_hWnd);
+ pT->DoPrePaint(dc.m_hDC, rc);
+ pT->DoPaint(dc.m_hDC, rc);
+ }
+
+ return 0;
+ }
+
+// Painting helper
+ void DoPrePaint(CDCHandle dc, RECT& rc)
+ {
+ RECT rcClient = { 0 };
+ GetClientRect(&rcClient);
+ RECT rcArea = rcClient;
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ ::InflateRect(&rcArea, -pT->m_cxOffset, -pT->m_cyOffset);
+ if (rcArea.left > rcArea.right)
+ rcArea.right = rcArea.left;
+ if (rcArea.top > rcArea.bottom)
+ rcArea.bottom = rcArea.top;
+ GetPageRect(rcArea, &rc);
+ CRgn rgn1, rgn2;
+ rgn1.CreateRectRgnIndirect(&rc);
+ rgn2.CreateRectRgnIndirect(&rcClient);
+ rgn2.CombineRgn(rgn1, RGN_DIFF);
+ dc.SelectClipRgn(rgn2);
+ dc.FillRect(&rcClient, COLOR_BTNSHADOW);
+ dc.SelectClipRgn(NULL);
+ dc.FillRect(&rc, (HBRUSH)::GetStockObject(WHITE_BRUSH));
+ }
+
+// Implementation - data
+ int m_nMinPage;
+ int m_nMaxPage;
+};
+
+
+class CPrintPreviewWindow : public CPrintPreviewWindowImpl<CPrintPreviewWindow>
+{
+public:
+ DECLARE_WND_CLASS_EX(_T("WTL_PrintPreview"), CS_VREDRAW | CS_HREDRAW, -1)
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CZoomPrintPreviewWindowImpl - Implements print preview window with zooming
+
+#ifdef __ATLSCRL_H__
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CZoomPrintPreviewWindowImpl : public CPrintPreviewWindowImpl< T, TBase, TWinTraits >, public CZoomScrollImpl< T >
+{
+public:
+ bool m_bSized;
+
+ CZoomPrintPreviewWindowImpl()
+ {
+ SetScrollExtendedStyle(SCRL_DISABLENOSCROLL);
+ InitZoom();
+ }
+
+ // should be called to reset data members before recreating window
+ void InitZoom()
+ {
+ m_bSized = false;
+ m_nZoomMode = ZOOMMODE_OFF;
+ m_fZoomScaleMin = 1.0;
+ m_fZoomScale = 1.0;
+ }
+
+ BEGIN_MSG_MAP(CZoomPrintPreviewWindowImpl)
+ MESSAGE_HANDLER(WM_SETCURSOR, CZoomScrollImpl< T >::OnSetCursor)
+ MESSAGE_HANDLER(WM_VSCROLL, CScrollImpl< T >::OnVScroll)
+ MESSAGE_HANDLER(WM_HSCROLL, CScrollImpl< T >::OnHScroll)
+ MESSAGE_HANDLER(WM_MOUSEWHEEL, CScrollImpl< T >::OnMouseWheel)
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(m_uMsgMouseWheel, CScrollImpl< T >::OnMouseWheel)
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, CScrollImpl< T >::OnSettingChange)
+ MESSAGE_HANDLER(WM_LBUTTONDOWN, CZoomScrollImpl< T >::OnLButtonDown)
+ MESSAGE_HANDLER(WM_MOUSEMOVE, CZoomScrollImpl< T >::OnMouseMove)
+ MESSAGE_HANDLER(WM_LBUTTONUP, CZoomScrollImpl< T >::OnLButtonUp)
+ MESSAGE_HANDLER(WM_CAPTURECHANGED, CZoomScrollImpl< T >::OnCaptureChanged)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_SCROLL_UP, CScrollImpl< T >::OnScrollUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_DOWN, CScrollImpl< T >::OnScrollDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_UP, CScrollImpl< T >::OnScrollPageUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_DOWN, CScrollImpl< T >::OnScrollPageDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_TOP, CScrollImpl< T >::OnScrollTop)
+ COMMAND_ID_HANDLER(ID_SCROLL_BOTTOM, CScrollImpl< T >::OnScrollBottom)
+ COMMAND_ID_HANDLER(ID_SCROLL_LEFT, CScrollImpl< T >::OnScrollLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_RIGHT, CScrollImpl< T >::OnScrollRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_LEFT, CScrollImpl< T >::OnScrollPageLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_RIGHT, CScrollImpl< T >::OnScrollPageRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_LEFT, CScrollImpl< T >::OnScrollAllLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_RIGHT, CScrollImpl< T >::OnScrollAllRight)
+ END_MSG_MAP()
+
+ LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ SIZE sizeClient = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
+ POINT ptOffset = m_ptOffset;
+ SIZE sizeAll = m_sizeAll;
+ SetScrollSize(sizeClient);
+ if(sizeAll.cx > 0)
+ ptOffset.x = ::MulDiv(ptOffset.x, m_sizeAll.cx, sizeAll.cx);
+ if(sizeAll.cy > 0)
+ ptOffset.y = ::MulDiv(ptOffset.y, m_sizeAll.cy, sizeAll.cy);
+ SetScrollOffset(ptOffset);
+ CScrollImpl< T >::OnSize(uMsg, wParam, lParam, bHandled);
+ if(!m_bSized)
+ {
+ m_bSized = true;
+ T* pT = static_cast<T*>(this);
+ pT->ShowScrollBar(SB_HORZ, TRUE);
+ pT->ShowScrollBar(SB_VERT, TRUE);
+ }
+ return 0;
+ }
+
+ LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1;
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ RECT rc = { 0 };
+
+ if(wParam != NULL)
+ {
+ CDCHandle dc = (HDC)wParam;
+ int nMapModeSav = dc.GetMapMode();
+ dc.SetMapMode(MM_ANISOTROPIC);
+ SIZE szWindowExt = { 0, 0 };
+ dc.SetWindowExt(m_sizeLogAll, &szWindowExt);
+ SIZE szViewportExt = { 0, 0 };
+ dc.SetViewportExt(m_sizeAll, &szViewportExt);
+ POINT ptViewportOrg = { 0, 0 };
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y, &ptViewportOrg);
+
+ pT->DoPrePaint(dc, rc);
+ pT->DoPaint(dc, rc);
+
+ dc.SetMapMode(nMapModeSav);
+ dc.SetWindowExt(szWindowExt);
+ dc.SetViewportExt(szViewportExt);
+ dc.SetViewportOrg(ptViewportOrg);
+ }
+ else
+ {
+ CPaintDC dc(pT->m_hWnd);
+ pT->PrepareDC(dc.m_hDC);
+ pT->DoPrePaint(dc.m_hDC, rc);
+ pT->DoPaint(dc.m_hDC, rc);
+ }
+
+ return 0;
+ }
+
+ // Painting helpers
+ void DoPaint(CDCHandle dc)
+ {
+ // this one is not used
+ }
+
+ void DoPrePaint(CDCHandle dc, RECT& rc)
+ {
+ RECT rcClient;
+ GetClientRect(&rcClient);
+ RECT rcArea = rcClient;
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ ::InflateRect(&rcArea, -pT->m_cxOffset, -pT->m_cyOffset);
+ if (rcArea.left > rcArea.right)
+ rcArea.right = rcArea.left;
+ if (rcArea.top > rcArea.bottom)
+ rcArea.bottom = rcArea.top;
+ GetPageRect(rcArea, &rc);
+ HBRUSH hbrOld = dc.SelectBrush(::GetSysColorBrush(COLOR_BTNSHADOW));
+ dc.PatBlt(rcClient.left, rcClient.top, rc.left - rcClient.left, rcClient.bottom - rcClient.top, PATCOPY);
+ dc.PatBlt(rc.left, rcClient.top, rc.right - rc.left, rc.top - rcClient.top, PATCOPY);
+ dc.PatBlt(rc.right, rcClient.top, rcClient.right - rc.right, rcClient.bottom - rcClient.top, PATCOPY);
+ dc.PatBlt(rc.left, rc.bottom, rc.right - rc.left, rcClient.bottom - rc.bottom, PATCOPY);
+ dc.SelectBrush((HBRUSH)::GetStockObject(WHITE_BRUSH));
+ dc.PatBlt(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, PATCOPY);
+ dc.SelectBrush(::GetSysColorBrush(COLOR_3DDKSHADOW));
+ dc.PatBlt(rc.right, rc.top + 4, 4, rc.bottom - rc.top, PATCOPY);
+ dc.PatBlt(rc.left + 4, rc.bottom, rc.right - rc.left, 4, PATCOPY);
+ dc.SelectBrush(hbrOld);
+ }
+
+ void DoPaint(CDCHandle dc, RECT& rc)
+ {
+ CEnhMetaFileInfo emfinfo(m_meta);
+ ENHMETAHEADER* pmh = emfinfo.GetEnhMetaFileHeader();
+ int nOffsetX = MulDiv(m_sizeCurPhysOffset.cx, rc.right-rc.left, pmh->szlDevice.cx);
+ int nOffsetY = MulDiv(m_sizeCurPhysOffset.cy, rc.bottom-rc.top, pmh->szlDevice.cy);
+
+ dc.OffsetWindowOrg(-nOffsetX, -nOffsetY);
+ dc.PlayMetaFile(m_meta, &rc);
+ }
+};
+
+class CZoomPrintPreviewWindow : public CZoomPrintPreviewWindowImpl<CZoomPrintPreviewWindow>
+{
+public:
+ DECLARE_WND_CLASS_EX(_T("WTL_ZoomPrintPreview"), CS_VREDRAW | CS_HREDRAW, -1)
+};
+
+#endif // __ATLSCRL_H__
+
+}; // namespace WTL
+
+#endif // __ATLPRINT_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlres.h b/plugins/SmartAutoReplier/wtl/atlres.h
new file mode 100644
index 0000000000..22fb3e6fdd
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlres.h
@@ -0,0 +1,263 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLRES_H__
+#define __ATLRES_H__
+
+#pragma once
+
+#if defined(_WIN32_WCE) && !defined(__ATLRESCE_H__)
+ #error Use atlresCE.h instead of atlres.h for Windows CE
+#endif
+
+
+#ifdef RC_INVOKED
+#ifndef _INC_WINDOWS
+
+ #define _INC_WINDOWS
+
+ #ifndef _WIN32_WCE
+ #define VS_VERSION_INFO 1
+
+ #ifdef APSTUDIO_INVOKED
+ #define APSTUDIO_HIDDEN_SYMBOLS // Ignore following symbols
+ #endif // APSTUDIO_INVOKED
+
+ #ifndef WINVER
+ #define WINVER 0x0400 // default to Windows Version 4.0
+ #endif // !WINVER
+
+ #include <winresrc.h>
+
+ // operation messages sent to DLGINIT
+ #define LB_ADDSTRING (WM_USER+1)
+ #define CB_ADDSTRING (WM_USER+3)
+ #endif // !_WIN32_WCE
+
+ #ifdef APSTUDIO_INVOKED
+ #undef APSTUDIO_HIDDEN_SYMBOLS
+ #endif // APSTUDIO_INVOKED
+
+ #ifdef IDC_STATIC
+ #undef IDC_STATIC
+ #endif // IDC_STATIC
+ #define IDC_STATIC (-1)
+
+#endif // !_INC_WINDOWS
+#endif // RC_INVOKED
+
+#ifdef APSTUDIO_INVOKED
+ #define APSTUDIO_HIDDEN_SYMBOLS
+#endif // APSTUDIO_INVOKED
+
+///////////////////////////////////////////////////////////////////////////////
+// ATL resource types
+
+#ifndef RC_INVOKED
+ #define RT_DLGINIT MAKEINTRESOURCE(240)
+ #define RT_TOOLBAR MAKEINTRESOURCE(241)
+#endif // RC_INVOKED
+
+///////////////////////////////////////////////////////////////////////////////
+
+#ifdef APSTUDIO_INVOKED
+ #undef APSTUDIO_HIDDEN_SYMBOLS
+#endif // APSTUDIO_INVOKED
+
+///////////////////////////////////////////////////////////////////////////////
+// Standard window components
+
+#define ID_SEPARATOR 0 // special separator value
+#define ID_DEFAULT_PANE 0 // default status bar pane
+
+#ifndef RC_INVOKED // code only
+// standard control bars (IDW = window ID)
+ #define ATL_IDW_TOOLBAR 0xE800 // main Toolbar for window
+ #define ATL_IDW_STATUS_BAR 0xE801 // Status bar window
+ #define ATL_IDW_COMMAND_BAR 0xE802 // Command bar window
+
+// parts of a frame window
+ #define ATL_IDW_CLIENT 0xE900
+ #define ATL_IDW_PANE_FIRST 0xE900 // first pane (256 max)
+ #define ATL_IDW_PANE_LAST 0xE9FF
+ #define ATL_IDW_HSCROLL_FIRST 0xEA00 // first Horz scrollbar (16 max)
+ #define ATL_IDW_VSCROLL_FIRST 0xEA10 // first Vert scrollbar (16 max)
+
+ #define ATL_IDW_SIZE_BOX 0xEA20 // size box for splitters
+ #define ATL_IDW_PANE_SAVE 0xEA21 // to shift ATL_IDW_PANE_FIRST
+
+// bands for a rebar
+ #define ATL_IDW_BAND_FIRST 0xEB00
+ #define ATL_IDW_BAND_LAST 0xEBFF
+#endif // !RC_INVOKED
+
+///////////////////////////////////////////////////////////////////////////////
+// Standard Commands
+
+// File commands
+#define ID_FILE_NEW 0xE100
+#define ID_FILE_OPEN 0xE101
+#define ID_FILE_CLOSE 0xE102
+#define ID_FILE_SAVE 0xE103
+#define ID_FILE_SAVE_AS 0xE104
+#define ID_FILE_PAGE_SETUP 0xE105
+#define ID_FILE_PRINT_SETUP 0xE106
+#define ID_FILE_PRINT 0xE107
+#define ID_FILE_PRINT_DIRECT 0xE108
+#define ID_FILE_PRINT_PREVIEW 0xE109
+#define ID_FILE_UPDATE 0xE10A
+#define ID_FILE_SAVE_COPY_AS 0xE10B
+#define ID_FILE_SEND_MAIL 0xE10C
+
+#define ID_FILE_MRU_FIRST 0xE110
+#define ID_FILE_MRU_FILE1 0xE110 // range - 16 max
+#define ID_FILE_MRU_FILE2 0xE111
+#define ID_FILE_MRU_FILE3 0xE112
+#define ID_FILE_MRU_FILE4 0xE113
+#define ID_FILE_MRU_FILE5 0xE114
+#define ID_FILE_MRU_FILE6 0xE115
+#define ID_FILE_MRU_FILE7 0xE116
+#define ID_FILE_MRU_FILE8 0xE117
+#define ID_FILE_MRU_FILE9 0xE118
+#define ID_FILE_MRU_FILE10 0xE119
+#define ID_FILE_MRU_FILE11 0xE11A
+#define ID_FILE_MRU_FILE12 0xE11B
+#define ID_FILE_MRU_FILE13 0xE11C
+#define ID_FILE_MRU_FILE14 0xE11D
+#define ID_FILE_MRU_FILE15 0xE11E
+#define ID_FILE_MRU_FILE16 0xE11F
+#define ID_FILE_MRU_LAST 0xE11F
+
+// Edit commands
+#define ID_EDIT_CLEAR 0xE120
+#define ID_EDIT_CLEAR_ALL 0xE121
+#define ID_EDIT_COPY 0xE122
+#define ID_EDIT_CUT 0xE123
+#define ID_EDIT_FIND 0xE124
+#define ID_EDIT_PASTE 0xE125
+#define ID_EDIT_PASTE_LINK 0xE126
+#define ID_EDIT_PASTE_SPECIAL 0xE127
+#define ID_EDIT_REPEAT 0xE128
+#define ID_EDIT_REPLACE 0xE129
+#define ID_EDIT_SELECT_ALL 0xE12A
+#define ID_EDIT_UNDO 0xE12B
+#define ID_EDIT_REDO 0xE12C
+
+// Window commands
+#define ID_WINDOW_NEW 0xE130
+#define ID_WINDOW_ARRANGE 0xE131
+#define ID_WINDOW_CASCADE 0xE132
+#define ID_WINDOW_TILE_HORZ 0xE133
+#define ID_WINDOW_TILE_VERT 0xE134
+#define ID_WINDOW_SPLIT 0xE135
+#ifndef RC_INVOKED // code only
+ #define ATL_IDM_WINDOW_FIRST 0xE130
+ #define ATL_IDM_WINDOW_LAST 0xE13F
+ #define ATL_IDM_FIRST_MDICHILD 0xFF00 // window list starts here
+ #define ATL_IDM_LAST_MDICHILD 0xFFFD
+#endif // !RC_INVOKED
+// TabView
+#define ID_WINDOW_TABFIRST 0xFF00 // = ATL_IDM_FIRST_MDICHILD
+#define ID_WINDOW_TABLAST 0xFFFD
+#define ID_WINDOW_SHOWTABLIST 0xFFFE
+
+// Help and App commands
+#define ID_APP_ABOUT 0xE140
+#define ID_APP_EXIT 0xE141
+#define ID_HELP_INDEX 0xE142
+#define ID_HELP_FINDER 0xE143
+#define ID_HELP_USING 0xE144
+#define ID_CONTEXT_HELP 0xE145 // shift-F1
+// special commands for processing help
+#define ID_HELP 0xE146 // first attempt for F1
+#define ID_DEFAULT_HELP 0xE147 // last attempt
+
+// Misc
+#define ID_NEXT_PANE 0xE150
+#define ID_PREV_PANE 0xE151
+#define ID_PANE_CLOSE 0xE152
+
+// Format
+#define ID_FORMAT_FONT 0xE160
+
+// Scroll
+#define ID_SCROLL_UP 0xE170
+#define ID_SCROLL_DOWN 0xE171
+#define ID_SCROLL_PAGE_UP 0xE172
+#define ID_SCROLL_PAGE_DOWN 0xE173
+#define ID_SCROLL_TOP 0xE174
+#define ID_SCROLL_BOTTOM 0xE175
+#define ID_SCROLL_LEFT 0xE176
+#define ID_SCROLL_RIGHT 0xE177
+#define ID_SCROLL_PAGE_LEFT 0xE178
+#define ID_SCROLL_PAGE_RIGHT 0xE179
+#define ID_SCROLL_ALL_LEFT 0xE17A
+#define ID_SCROLL_ALL_RIGHT 0xE17B
+
+// OLE commands
+#define ID_OLE_INSERT_NEW 0xE200
+#define ID_OLE_EDIT_LINKS 0xE201
+#define ID_OLE_EDIT_CONVERT 0xE202
+#define ID_OLE_EDIT_CHANGE_ICON 0xE203
+#define ID_OLE_EDIT_PROPERTIES 0xE204
+#define ID_OLE_VERB_FIRST 0xE210 // range - 16 max
+#ifndef RC_INVOKED // code only
+ #define ID_OLE_VERB_LAST 0xE21F
+#endif // !RC_INVOKED
+
+// View commands (same number used as IDW used for toolbar and status bar)
+#define ID_VIEW_TOOLBAR 0xE800
+#define ID_VIEW_STATUS_BAR 0xE801
+#define ID_VIEW_REFRESH 0xE803
+#define ID_VIEW_RIBBON 0xE804 // Ribbon
+
+///////////////////////////////////////////////////////////////////////////////
+// Standard control IDs
+
+#ifdef IDC_STATIC
+ #undef IDC_STATIC
+#endif // IDC_STATIC
+#define IDC_STATIC (-1) // all static controls
+
+///////////////////////////////////////////////////////////////////////////////
+// Standard string error/warnings
+
+// idle status bar message
+#define ATL_IDS_IDLEMESSAGE 0xE001
+
+#ifndef RC_INVOKED // code only
+ #define ATL_IDS_SCFIRST 0xEF00
+#endif // !RC_INVOKED
+
+#define ATL_IDS_SCSIZE 0xEF00
+#define ATL_IDS_SCMOVE 0xEF01
+#define ATL_IDS_SCMINIMIZE 0xEF02
+#define ATL_IDS_SCMAXIMIZE 0xEF03
+#define ATL_IDS_SCNEXTWINDOW 0xEF04
+#define ATL_IDS_SCPREVWINDOW 0xEF05
+#define ATL_IDS_SCCLOSE 0xEF06
+#define ATL_IDS_SCRESTORE 0xEF12
+#define ATL_IDS_SCTASKLIST 0xEF13
+
+#define ATL_IDS_MDICHILD 0xEF1F
+#define ATL_IDS_MRU_FILE 0xEFDA
+
+///////////////////////////////////////////////////////////////////////////////
+// Misc. control IDs
+
+// Property Sheet control id's (determined with Spy++)
+#define ID_APPLY_NOW 0x3021
+#define ID_WIZBACK 0x3023
+#define ID_WIZNEXT 0x3024
+#define ID_WIZFINISH 0x3025
+#define ATL_IDC_TAB_CONTROL 0x3020
+
+#endif // __ATLRES_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlresce.h b/plugins/SmartAutoReplier/wtl/atlresce.h
new file mode 100644
index 0000000000..3b2b93388f
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlresce.h
@@ -0,0 +1,93 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLRESCE_H__
+#define __ATLRESCE_H__
+
+#pragma once
+
+#ifndef _WIN32_WCE
+ #error atlresCE.h is only for Windows CE
+#endif
+
+
+#ifdef RC_INVOKED
+#ifndef _INC_WINDOWS
+
+ #define VS_VERSION_INFO 1
+
+ #ifdef APSTUDIO_INVOKED
+ #define APSTUDIO_HIDDEN_SYMBOLS // Ignore following symbols
+ #endif // APSTUDIO_INVOKED
+
+ #ifndef WINVER
+ #define WINVER 0x0400 // default to Windows Version 4.0
+ #endif // !WINVER
+
+ #if !defined(WCEOLE_ENABLE_DIALOGEX)
+ #define DIALOGEX DIALOG DISCARDABLE
+ #endif
+
+ #include <commctrl.h>
+ #define SHMENUBAR RCDATA
+
+ #if defined(SHELLSDK_MODULES_AYGSHELL)
+ #include <aygshell.h>
+ #else
+ #define NOMENU 0xFFFF
+ #define IDS_SHNEW 1
+ #define IDM_SHAREDNEW 10
+ #define IDM_SHAREDNEWDEFAULT 11
+ #endif
+ #ifndef I_IMAGENONE
+ #define I_IMAGENONE (-2)
+ #endif
+
+ #include <windows.h>
+
+#endif // !_INC_WINDOWS
+#endif // RC_INVOKED
+
+#include "atlres.h"
+
+#ifdef APSTUDIO_INVOKED
+ #undef APSTUDIO_HIDDEN_SYMBOLS
+#endif // APSTUDIO_INVOKED
+
+// Visual Studio dialog editor bug fix
+#ifndef DS_FIXEDSYS
+ #define DS_FIXEDSYS 0
+#endif
+
+#define IDC_INFOSTATIC 0xFFFE // == IDC_STATIC -1
+
+///////////////////////////////////////////////////////////////////////////////
+// Smartphone and PPC 2005 Resource IDs
+
+// Command and associated string resource IDs
+#define ID_MENU_OK 0xE790
+#define ID_MENU_CANCEL 0xE791
+#define ID_MENU 0xE792
+#define ID_ACTION 0xE793
+#define ID_VIEW_FULLSCREEN 0xE802
+
+// MenuBar resource IDs
+#define ATL_IDM_MENU_DONE 0xE701
+#define ATL_IDM_MENU_CANCEL 0xE702
+#define ATL_IDM_MENU_DONECANCEL 0xE703
+
+// Default device MenuBar control ID and MenuBar resource ID
+#define ATL_IDW_MENU_BAR 0xE802
+
+// SmartPhone spinned controls ID offset for CSpinCtrl
+#define ATL_IDW_SPIN_ID 9999
+
+#endif // __ATLRESCE_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlribbon.h b/plugins/SmartAutoReplier/wtl/atlribbon.h
new file mode 100644
index 0000000000..2b21026441
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlribbon.h
@@ -0,0 +1,3446 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLRIBBON_H__
+#define __ATLRIBBON_H__
+
+#pragma once
+
+#if (_MSC_VER < 1500)
+ #error atlribbon.h requires Visual C++ 2008 compiler or higher
+#endif
+
+#ifndef _UNICODE
+ #error atlribbon.h requires the Unicode character set
+#endif
+
+#if !defined(NTDDI_WIN7) || (NTDDI_VERSION < NTDDI_WIN7)
+ #error atlribbon.h requires the Windows 7 SDK or higher
+#endif
+
+#ifdef _WIN32_WCE
+ #error atlribbon.h is not supported on Windows CE
+#endif
+
+#ifndef __ATLAPP_H__
+ #error atlribbon.h requires atlapp.h to be included first
+#endif
+
+#if (_ATL_VER < 0x0700)
+ #include <shlwapi.h>
+ #pragma comment(lib, "shlwapi.lib")
+#endif
+
+#include <atlmisc.h> // for RecentDocumentList classes
+#include <atlframe.h> // for Frame and UpdateUI classes
+#include <atlctrls.h> // required for atlctrlw.h
+#include <atlctrlw.h> // for CCommandBarCtrl
+
+#if !defined(_WTL_USE_CSTRING) && !defined(__ATLSTR_H__)
+ #pragma warning(disable : 4530) // unwind semantics not enabled
+ #include <string>
+ #pragma warning(default : 4530)
+#endif
+
+#include <dwmapi.h>
+#pragma comment(lib, "dwmapi.lib")
+
+#include <UIRibbon.h>
+#include <UIRibbonPropertyHelpers.h>
+#pragma comment(lib, "propsys.lib")
+
+#include <Richedit.h> // for CHARFORMAT2
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CRibbonUpdateUI : Automatic mapping of ribbon UI elements
+//
+// RibbonUI::Text
+// RibbonUI::CharFormat
+// RibbonUI::ICtrl
+// RibbonUI::CtrlImpl
+// RibbonUI::CommandCtrlImpl
+// RibbonUI::ItemProperty
+// RibbonUI::CollectionImplBase
+// RibbonUI::CollectionImpl
+// RibbonUI::TextCollectionImpl
+// RibbonUI::ItemCollectionImpl
+// RibbonUI::ComboCollectionImpl
+// RibbonUI::CommandCollectionImpl
+// RibbonUI::ToolbarCollectionImpl
+// RibbonUI::SimpleCollectionImpl
+// RibbonUI::CollectionCtrlImpl
+// RibbonUI::ToolbarGalleryCtrlImpl
+// RibbonUI::SimpleCollectionCtrlImpl
+// RibbonUI::RecentItemsCtrlImpl
+// RibbonUI::FontCtrlImpl
+// RibbonUI::ColorCtrlImpl
+// RibbonUI::SpinnerCtrlImpl
+//
+// RibbonUI::CRibbonImpl
+// CRibbonImpl::CRibbonComboCtrl
+// CRibbonImpl::CRibbonItemGalleryCtrl
+// CRibbonImpl::CRibbonCommandGalleryCtrl
+// CRibbonImpl::CRibbonToolbarGalleryCtrl
+// CRibbonImpl::CRibbonSimpleComboCtrl
+// CRibbonImpl::CRibbonSimpleGalleryCtrl
+// CRibbonImpl::CRibbonRecentItemsCtrl
+// CRibbonImpl::CRibbonColorCtrl
+// CRibbonImpl::CRibbonFontCtrl
+// CRibbonImpl::CRibbonSpinnerCtrl
+// CRibbonImpl::CRibbonFloatSpinnerCtrl
+// CRibbonImpl::CRibbonCommandCtrl
+//
+// CRibbonFrameWindowImplBase
+// CRibbonFrameWindowImpl
+// CRibbonMDIFrameWindowImpl
+// CRibbonPersist
+//
+// Global functions:
+// RibbonUI::SetPropertyVal()
+// RibbonUI::GetImage()
+
+
+// Constants
+
+#ifndef RIBBONUI_MAX_TEXT
+ #define RIBBONUI_MAX_TEXT 128
+#endif
+
+#define TWIPS_PER_POINT 20 // For font size
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CRibbonUpdateUI : Automatic mapping of ribbon UI elements
+
+template <class T>
+class CRibbonUpdateUI : public CAutoUpdateUI<T>
+{
+public:
+ enum
+ {
+ UPDUI_RIBBON = 0x0080,
+ UPDUI_PERSIST = 0x0020
+ };
+
+ bool IsRibbonElement(const _AtlUpdateUIMap& UIMap)
+ {
+ return (UIMap.m_wType & UPDUI_RIBBON) != 0;
+ }
+
+ bool IsRibbonID(UINT nID)
+ {
+ for(int i = 0; i < m_arrUIMap.GetSize(); i++)
+ {
+ if(m_arrUIMap[i].m_nID == nID)
+ return IsRibbonElement(m_arrUIMap[i]);
+ }
+
+ return false;
+ }
+
+// Element
+ bool UIAddRibbonElement(UINT nID)
+ {
+ return UIAddElement<UPDUI_RIBBON>(nID);
+ }
+
+ bool UIRemoveRibbonElement(UINT nID)
+ {
+ return UIRemoveElement<UPDUI_RIBBON>(nID);
+ }
+
+ bool UIPersistElement(UINT nID, bool bPersist = true)
+ {
+ return bPersist ?
+ UIAddElement<UPDUI_PERSIST>(nID) :
+ UIRemoveElement<UPDUI_PERSIST>(nID);
+ }
+
+// methods for Ribbon elements
+ BOOL UISetText(int nID, LPCWSTR sText, BOOL bForceUpdate = FALSE)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bRes = CUpdateUIBase::UISetText(nID, sText, bForceUpdate);
+ if (pT->IsRibbonUI() && IsRibbonID(nID))
+ bRes = SUCCEEDED(pT->InvalidateProperty(nID, UI_PKEY_Label));
+ return bRes;
+ }
+
+ BOOL UISetText(int nID, UINT uIdResource, BOOL bForceUpdate = FALSE)
+ {
+ CTempBuffer<WCHAR> sText(RIBBONUI_MAX_TEXT);
+ return AtlLoadString(uIdResource, sText, RIBBONUI_MAX_TEXT) ?
+ UISetText(nID, sText, bForceUpdate) :
+ E_FAIL;
+ }
+
+ LPCTSTR UIGetText(int nID)
+ {
+ T* pT = static_cast<T*>(this);
+ LPCTSTR sUI = CAutoUpdateUI::UIGetText(nID);
+
+ // replace 'tab' by 'space' for RibbonUI elements
+ if (sUI && pT->IsRibbonUI() && IsRibbonID(nID) && wcschr(sUI, L'\t'))
+ {
+ static WCHAR sText[RIBBONUI_MAX_TEXT] = { 0 };
+ wcscpy_s(sText, sUI);
+ *wcschr(sText, L'\t') = L' ';
+ return sText;
+ }
+ else
+ {
+ return sUI;
+ }
+ }
+
+ BOOL UIEnable(int nID, BOOL bEnable, BOOL bForceUpdate = FALSE)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bRes = CUpdateUIBase::UIEnable(nID, bEnable, bForceUpdate);
+ if (pT->IsRibbonUI() && IsRibbonID(nID))
+ bRes = SUCCEEDED(pT->SetProperty((WORD)nID, UI_PKEY_Enabled, bEnable));
+ return bRes;
+ }
+
+ BOOL UISetCheck(int nID, INT nCheck, BOOL bForceUpdate = FALSE)
+ {
+ if ((nCheck == 0) || (nCheck == 1))
+ return UISetCheck(nID, nCheck != 0, bForceUpdate);
+ else
+ return CUpdateUIBase::UISetCheck(nID, nCheck, bForceUpdate);
+ }
+
+ BOOL UISetCheck(int nID, bool bCheck, BOOL bForceUpdate = FALSE)
+ {
+ T* pT = static_cast<T*>(this);
+ BOOL bRes = CUpdateUIBase::UISetCheck(nID, bCheck, bForceUpdate);
+ if (bRes && pT->IsRibbonUI() && IsRibbonID(nID))
+ bRes = SUCCEEDED(pT->SetProperty((WORD)nID, UI_PKEY_BooleanValue, bCheck));
+ return bRes;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// RibbonUI namespace
+//
+
+namespace RibbonUI
+{
+
+// Minimal string allocation support for various PROPERTYKEY values
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ typedef _CSTRING_NS::CString Text;
+#else
+ class Text : public std::wstring
+ {
+ public:
+ Text(std::wstring& s) : std::wstring(s)
+ { }
+ Text(LPCWSTR s) : std::wstring(s)
+ { }
+ Text()
+ { }
+ bool IsEmpty()
+ {
+ return empty();
+ }
+ operator LPCWSTR()
+ {
+ return c_str();
+ }
+ Text& operator =(LPCWSTR s)
+ {
+ return static_cast<Text&>(std::wstring::operator =(s));
+ }
+ };
+#endif
+
+// PROPERTYKEY enum and helpers
+enum k_KEY
+{
+ // state
+ k_Enabled = 1, k_BooleanValue = 200,
+ // text properties
+ k_LabelDescription = 2, k_Keytip = 3, k_Label = 4, k_TooltipDescription = 5, k_TooltipTitle = 6,
+ // image properties
+ k_LargeImage = 7, k_LargeHighContrastImage = 8, k_SmallImage = 9, k_SmallHighContrastImage = 10,
+ // collection properties
+ k_ItemsSource = 101, k_Categories = 102, k_SelectedItem = 104,
+ // collection item properties
+ k_CommandId = 100, k_CategoryId = 103, k_CommandType = 105, k_ItemImage = 106,
+ // combo control property
+ k_StringValue = 202,
+ // spinner control properties
+ k_DecimalValue = 201, k_MaxValue = 203, k_MinValue, k_Increment, k_DecimalPlaces, k_FormatString, k_RepresentativeString = 208,
+ // font control properties
+ k_FontProperties = 300, k_FontProperties_Family, k_FontProperties_Size, k_FontProperties_Bold, k_FontProperties_Italic = 304,
+ k_FontProperties_Underline = 305, k_FontProperties_Strikethrough, k_FontProperties_VerticalPositioning, k_FontProperties_ForegroundColor = 308,
+ k_FontProperties_BackgroundColor = 309, k_FontProperties_ForegroundColorType, k_FontProperties_BackgroundColorType, k_FontProperties_ChangedProperties = 312,
+ k_FontProperties_DeltaSize = 313,
+ // recent items properties
+ k_RecentItems = 350, k_Pinned = 351,
+ // color control properties
+ k_Color = 400, k_ColorType = 401, k_ColorMode,
+ k_ThemeColorsCategoryLabel = 403, k_StandardColorsCategoryLabel, k_RecentColorsCategoryLabel = 405, k_AutomaticColorLabel = 406,
+ k_NoColorLabel = 407, k_MoreColorsLabel = 408,
+ k_ThemeColors = 409, k_StandardColors = 410, k_ThemeColorsTooltips = 411, k_StandardColorsTooltips = 412,
+ // Ribbon state
+ k_Viewable = 1000, k_Minimized = 1001, k_QuickAccessToolbarDock = 1002, k_ContextAvailable = 1100,
+ // Ribbon UI colors
+ k_GlobalBackgroundColor = 2000, k_GlobalHighlightColor, k_GlobalTextColor = 2002
+};
+
+inline k_KEY k_(REFPROPERTYKEY key)
+{
+ return (k_KEY)key.fmtid.Data1;
+}
+
+// PROPERTYKEY value assignment and specializations
+//
+template <typename V>
+HRESULT SetPropertyVal(REFPROPERTYKEY key, V val, PROPVARIANT* ppv)
+{
+ switch (k_(key))
+ {
+ case k_Enabled:
+ case k_BooleanValue:
+ return InitPropVariantFromBoolean(val, ppv);
+ default:
+ return UIInitPropertyFromUInt32(key, val, ppv);
+ }
+}
+
+inline HRESULT SetPropertyVal(REFPROPERTYKEY key, DOUBLE val, PROPVARIANT* ppv)
+{
+ return SetPropertyVal(key, (LONG)val, ppv);
+}
+
+inline HRESULT SetPropertyVal(REFPROPERTYKEY key, IUIImage* val, PROPVARIANT* ppv)
+{
+ HRESULT hr = UIInitPropertyFromImage(key, val, ppv);
+ ATLVERIFY(val->Release() == 1);
+ return hr;
+}
+
+inline HRESULT SetPropertyVal(REFPROPERTYKEY key, IUnknown* val, PROPVARIANT* ppv)
+{
+ return UIInitPropertyFromInterface(key, val, ppv);
+}
+
+inline HRESULT SetPropertyVal(REFPROPERTYKEY key, IPropertyStore* val, PROPVARIANT* ppv)
+{
+ return UIInitPropertyFromInterface(key, val, ppv);
+}
+
+inline HRESULT SetPropertyVal(REFPROPERTYKEY key, SAFEARRAY* val, PROPVARIANT* ppv)
+{
+ return UIInitPropertyFromIUnknownArray(key, val, ppv);
+}
+
+inline HRESULT SetPropertyVal(REFPROPERTYKEY key, DECIMAL* val, PROPVARIANT* ppv)
+{
+ return UIInitPropertyFromDecimal(key, *val, ppv);
+}
+
+inline HRESULT SetPropertyVal(REFPROPERTYKEY key, bool val, PROPVARIANT* ppv)
+{
+ return UIInitPropertyFromBoolean(key, val, ppv);
+}
+
+inline HRESULT SetPropertyVal(REFPROPERTYKEY key, LPCWSTR val, PROPVARIANT* ppv)
+{
+ return UIInitPropertyFromString(key, val, ppv);
+}
+
+// CharFormat helper struct for RibbonUI font control
+//
+struct CharFormat : CHARFORMAT2
+{
+ // Default constructor
+ CharFormat()
+ {
+ cbSize = sizeof CHARFORMAT2;
+ Reset();
+ }
+
+ // Copy constructor
+ CharFormat(const CharFormat& cf)
+ {
+ CopyMemory(this, &cf, sizeof CHARFORMAT2);
+ }
+
+ // Assign operator
+ CharFormat& operator =(const CharFormat& cf)
+ {
+ CopyMemory(this, &cf, sizeof CHARFORMAT2);
+ return (*this);
+ }
+
+ void Reset()
+ {
+ uValue = dwMask = dwEffects = 0;
+ PropVariantInit(&propvar);
+ }
+
+ void operator <<(IPropertyStore* pStore)
+ {
+ if (pStore == NULL)
+ {
+ ATLASSERT(FALSE);
+ return;
+ }
+
+ static void (CharFormat::*Getk_[])(IPropertyStore*) =
+ {
+ &CharFormat::Getk_Family,
+ &CharFormat::Getk_FontProperties_Size,
+ &CharFormat::Getk_MaskEffect<CFM_BOLD, CFE_BOLD, UI_PKEY_FontProperties_Bold>,
+ &CharFormat::Getk_MaskEffect<CFM_ITALIC, CFE_ITALIC, UI_PKEY_FontProperties_Italic>,
+ &CharFormat::Getk_MaskEffect<CFM_UNDERLINE, CFE_UNDERLINE, UI_PKEY_FontProperties_Underline>,
+ &CharFormat::Getk_MaskEffect<CFM_STRIKEOUT, CFE_STRIKEOUT, UI_PKEY_FontProperties_Strikethrough>,
+ &CharFormat::Getk_VerticalPositioning,
+ &CharFormat::Getk_Color<CFM_COLOR, UI_PKEY_FontProperties_ForegroundColor>,
+ &CharFormat::Getk_Color<CFM_BACKCOLOR, UI_PKEY_FontProperties_BackgroundColor>,
+ &CharFormat::Getk_ColorType<CFM_COLOR, CFE_AUTOCOLOR, UI_SWATCHCOLORTYPE_AUTOMATIC, UI_PKEY_FontProperties_ForegroundColorType>,
+ &CharFormat::Getk_ColorType<CFM_BACKCOLOR, CFE_AUTOBACKCOLOR, UI_SWATCHCOLORTYPE_NOCOLOR, UI_PKEY_FontProperties_BackgroundColorType>,
+ };
+
+ DWORD nProps = 0;
+ Reset();
+
+ ATLVERIFY(SUCCEEDED(pStore->GetCount(&nProps)));
+ for (DWORD iProp = 0; iProp < nProps; iProp++)
+ {
+ PROPERTYKEY key;
+ ATLVERIFY(SUCCEEDED(pStore->GetAt(iProp, &key)));
+ ATLASSERT(k_(key) >= k_FontProperties_Family);
+
+ if (k_(key) <= k_FontProperties_BackgroundColorType)
+ (this->*Getk_[k_(key) - k_FontProperties_Family])(pStore);
+ }
+ }
+
+ void operator >>(IPropertyStore* pStore)
+ {
+ if (pStore == NULL)
+ {
+ ATLASSERT(FALSE);
+ return;
+ }
+
+ PutFace(pStore);
+ PutSize(pStore);
+ PutMaskEffect(CFM_BOLD, CFE_BOLD, UI_PKEY_FontProperties_Bold, pStore);
+ PutMaskEffect(CFM_ITALIC, CFE_ITALIC, UI_PKEY_FontProperties_Italic, pStore);
+ PutMaskEffect(CFM_UNDERLINE, CFE_UNDERLINE, UI_PKEY_FontProperties_Underline, pStore);
+ PutMaskEffect(CFM_STRIKEOUT, CFE_STRIKEOUT, UI_PKEY_FontProperties_Strikethrough, pStore);
+ PutVerticalPos(pStore);
+ PutColor(pStore);
+ PutBackColor(pStore);
+ }
+
+private:
+ PROPVARIANT propvar;
+ UINT uValue;
+
+ // Getk_ functions
+ void Getk_Family(IPropertyStore* pStore)
+ {
+ if (SUCCEEDED(pStore->GetValue(UI_PKEY_FontProperties_Family, &propvar)))
+ {
+ PropVariantToString(propvar, szFaceName, LF_FACESIZE);
+ if (*szFaceName)
+ dwMask |= CFM_FACE;
+ }
+ }
+
+ void Getk_FontProperties_Size(IPropertyStore* pStore)
+ {
+ if (SUCCEEDED(pStore->GetValue(UI_PKEY_FontProperties_Size, &propvar)))
+ {
+ DECIMAL decSize;
+ UIPropertyToDecimal(UI_PKEY_FontProperties_Size, propvar, &decSize);
+ DOUBLE dSize;
+ VarR8FromDec(&decSize, &dSize);
+ if (dSize > 0)
+ {
+ dwMask |= CFM_SIZE;
+ yHeight = (LONG)(dSize * TWIPS_PER_POINT);
+ }
+ }
+ }
+
+ template <DWORD t_dwMask, DWORD t_dwEffects, REFPROPERTYKEY key>
+ void Getk_MaskEffect(IPropertyStore* pStore)
+ {
+ if (SUCCEEDED(pStore->GetValue(key, &propvar)))
+ {
+ UIPropertyToUInt32(key, propvar, &uValue);
+ if ((UI_FONTPROPERTIES)uValue != UI_FONTPROPERTIES_NOTAVAILABLE)
+ {
+ dwMask |= t_dwMask;
+ dwEffects |= ((UI_FONTPROPERTIES) uValue == UI_FONTPROPERTIES_SET) ? t_dwEffects : 0;
+ }
+ }
+ }
+
+ void Getk_VerticalPositioning(IPropertyStore* pStore)
+ {
+ if (SUCCEEDED(pStore->GetValue(UI_PKEY_FontProperties_VerticalPositioning, &propvar)))
+ {
+ UIPropertyToUInt32(UI_PKEY_FontProperties_VerticalPositioning, propvar, &uValue);
+ UI_FONTVERTICALPOSITION uVerticalPosition = (UI_FONTVERTICALPOSITION) uValue;
+ if ((uVerticalPosition != UI_FONTVERTICALPOSITION_NOTAVAILABLE))
+ {
+ dwMask |= (CFM_SUPERSCRIPT | CFM_SUBSCRIPT);
+ if (uVerticalPosition != UI_FONTVERTICALPOSITION_NOTSET)
+ {
+ dwEffects |= (uVerticalPosition == UI_FONTVERTICALPOSITION_SUPERSCRIPT) ? CFE_SUPERSCRIPT : CFE_SUBSCRIPT;
+ }
+ }
+ }
+ }
+
+ template <DWORD t_dwMask, REFPROPERTYKEY key>
+ void Getk_Color(IPropertyStore* pStore)
+ {
+ UINT32 color;
+ if (SUCCEEDED(pStore->GetValue(key, &propvar)))
+ {
+ UIPropertyToUInt32(key, propvar, &color);
+ dwMask |= t_dwMask;
+
+ if (t_dwMask == CFM_COLOR)
+ crTextColor = color;
+ else
+ crBackColor = color;
+ }
+ }
+
+ template <DWORD t_dwMask, DWORD t_dwEffects, UI_SWATCHCOLORTYPE t_type, REFPROPERTYKEY key>
+ void Getk_ColorType(IPropertyStore* pStore)
+ {
+ if (SUCCEEDED(pStore->GetValue(key, &propvar)))
+ {
+ UIPropertyToUInt32(key, propvar, &uValue);
+ if (t_type == (UI_SWATCHCOLORTYPE)uValue)
+ {
+ dwMask |= t_dwMask;
+ dwEffects |= t_dwEffects;
+ }
+ }
+ }
+
+ // Put functions
+ void PutMaskEffect(WORD dwMaskVal, WORD dwEffectVal, REFPROPERTYKEY key, IPropertyStore* pStore)
+ {
+ PROPVARIANT propvar;
+ UI_FONTPROPERTIES uProp = UI_FONTPROPERTIES_NOTAVAILABLE;
+ if ((dwMask & dwMaskVal) != 0)
+ uProp = dwEffects & dwEffectVal ? UI_FONTPROPERTIES_SET : UI_FONTPROPERTIES_NOTSET;
+ SetPropertyVal(key, uProp, &propvar);
+ pStore->SetValue(key, propvar);
+ }
+
+ void PutVerticalPos(IPropertyStore* pStore)
+ {
+ PROPVARIANT propvar;
+ UI_FONTVERTICALPOSITION uProp = UI_FONTVERTICALPOSITION_NOTAVAILABLE;
+
+ if ((dwMask & CFE_SUBSCRIPT) != 0)
+ {
+ if ((dwMask & CFM_SUBSCRIPT) && (dwEffects & CFE_SUBSCRIPT))
+ uProp = UI_FONTVERTICALPOSITION_SUBSCRIPT;
+ else
+ uProp = UI_FONTVERTICALPOSITION_SUPERSCRIPT;
+ }
+ else if ((dwMask & CFM_OFFSET) != 0)
+ {
+ if (yOffset > 0)
+ uProp = UI_FONTVERTICALPOSITION_SUPERSCRIPT;
+ else if (yOffset < 0)
+ uProp = UI_FONTVERTICALPOSITION_SUBSCRIPT;
+ }
+
+ SetPropertyVal(UI_PKEY_FontProperties_VerticalPositioning, uProp, &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_VerticalPositioning, propvar);
+ }
+
+ void PutFace(IPropertyStore* pStore)
+ {
+ PROPVARIANT propvar;
+ SetPropertyVal(UI_PKEY_FontProperties_Family,
+ dwMask & CFM_FACE ? szFaceName : L"", &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_Family, propvar);
+ }
+
+ void PutSize(IPropertyStore* pStore)
+ {
+ PROPVARIANT propvar;
+ DECIMAL decVal;
+
+ if ((dwMask & CFM_SIZE) != 0)
+ VarDecFromR8((DOUBLE)yHeight / TWIPS_PER_POINT, &decVal);
+ else
+ VarDecFromI4(0, &decVal);
+
+ SetPropertyVal(UI_PKEY_FontProperties_Size, &decVal, &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_Size, propvar);
+ }
+
+ void PutColor(IPropertyStore* pStore)
+ {
+ if ((dwMask & CFM_COLOR) != 0)
+ if ((dwEffects & CFE_AUTOCOLOR) == 0)
+ {
+ SetPropertyVal(UI_PKEY_FontProperties_ForegroundColorType, UI_SWATCHCOLORTYPE_RGB, &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_ForegroundColorType, propvar);
+
+ SetPropertyVal(UI_PKEY_FontProperties_ForegroundColor, crTextColor, &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_ForegroundColor, propvar);
+ }
+ else
+ {
+ SetPropertyVal(UI_PKEY_FontProperties_ForegroundColorType, UI_SWATCHCOLORTYPE_AUTOMATIC, &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_ForegroundColorType, propvar);
+ }
+ }
+
+ void PutBackColor(IPropertyStore* pStore)
+ {
+ if (((dwMask & CFM_BACKCOLOR) != 0) && ((dwEffects & CFE_AUTOBACKCOLOR) == 0))
+ {
+ SetPropertyVal(UI_PKEY_FontProperties_BackgroundColorType, UI_SWATCHCOLORTYPE_RGB, &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_BackgroundColorType, propvar);
+
+ SetPropertyVal(UI_PKEY_FontProperties_BackgroundColor, crBackColor, &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_BackgroundColor, propvar);
+ }
+ else
+ {
+ SetPropertyVal(UI_PKEY_FontProperties_BackgroundColorType, UI_SWATCHCOLORTYPE_NOCOLOR, &propvar);
+ pStore->SetValue(UI_PKEY_FontProperties_BackgroundColorType, propvar);
+ }
+ }
+};
+
+// IUIImage helper
+//
+inline IUIImage* GetImage(HBITMAP hbm, UI_OWNERSHIP owner)
+{
+ ATLASSERT(hbm);
+ IUIImage* pIUII = NULL;
+ ATL::CComPtr<IUIImageFromBitmap> pIFB;
+
+ if SUCCEEDED(pIFB.CoCreateInstance(CLSID_UIRibbonImageFromBitmapFactory))
+ ATLVERIFY(SUCCEEDED(pIFB->CreateImage(hbm, owner, &pIUII)));
+
+ return pIUII;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Ribbon control classes
+
+// RibbonUI::ICtrl abstract interface of RibbonUI::CRibbonImpl and all RibbonUI control classes
+//
+struct ICtrl
+{
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* pCommandExecutionProperties) = 0;
+
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue) = 0;
+};
+
+// RibbonUI::CtrlImpl base class for all ribbon controls
+//
+template <class T, UINT t_ID>
+class ATL_NO_VTABLE CtrlImpl : public ICtrl
+{
+protected:
+ T* m_pWndRibbon;
+
+public:
+ typedef T WndRibbon;
+
+ CtrlImpl() : m_pWndRibbon(T::pWndRibbon)
+ { }
+
+ WndRibbon& GetWndRibbon()
+ {
+ return *m_pWndRibbon;
+ }
+
+ static WORD GetID()
+ {
+ return t_ID;
+ }
+
+ Text m_sTxt[5];
+
+ // Operations
+ HRESULT Invalidate()
+ {
+ return GetWndRibbon().InvalidateCtrl(GetID());
+ }
+
+ HRESULT Invalidate(REFPROPERTYKEY key, UI_INVALIDATIONS flags = UI_INVALIDATIONS_PROPERTY)
+ {
+ return GetWndRibbon().InvalidateProperty(GetID(), key, flags);
+ }
+
+ HRESULT SetText(REFPROPERTYKEY key, LPCWSTR sTxt, bool bUpdate = false)
+ {
+ ATLASSERT((k_(key) <= k_TooltipTitle) && (k_(key) >= k_LabelDescription));
+
+ m_sTxt[k_(key) - k_LabelDescription] = sTxt;
+
+ return bUpdate ?
+ GetWndRibbon().InvalidateProperty(GetID(), key) :
+ S_OK;
+ }
+
+ // Implementation
+ template <typename V>
+ HRESULT SetProperty(REFPROPERTYKEY key, V val)
+ {
+ return GetWndRibbon().SetProperty(GetID(), key, val);
+ }
+
+ HRESULT OnGetText(REFPROPERTYKEY key, PROPVARIANT* ppv)
+ {
+ ATLASSERT((k_(key) <= k_TooltipTitle) && (k_(key) >= k_LabelDescription));
+
+ const INT iText = k_(key) - k_LabelDescription;
+ if (m_sTxt[iText].IsEmpty())
+ if (LPCWSTR sText = GetWndRibbon().OnRibbonQueryText(GetID(), key))
+ m_sTxt[iText] = sText;
+
+ return !m_sTxt[iText].IsEmpty() ?
+ SetPropertyVal(key, (LPCWSTR)m_sTxt[iText], ppv) :
+ S_OK;
+ }
+
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* pCommandExecutionProperties)
+ {
+ ATLASSERT(nCmdID == t_ID);
+ return GetWndRibbon().DoExecute(nCmdID, verb, key, ppropvarValue, pCommandExecutionProperties);
+ }
+
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ ATLASSERT(nCmdID == t_ID);
+
+ const INT iMax = k_TooltipTitle - k_LabelDescription;
+ const INT iVal = k_(key) - k_LabelDescription;
+
+ return (iVal <= iMax) && (iVal >= 0) ?
+ OnGetText(key, ppropvarNewValue) :
+ GetWndRibbon().DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ }
+};
+
+// CommandCtrlImpl base class for most ribbon controls
+//
+template <class T, UINT t_ID>
+class CommandCtrlImpl : public CtrlImpl<T, t_ID>
+{
+public:
+ CBitmap m_hbm[4];
+
+ HRESULT SetImage(REFPROPERTYKEY key, HBITMAP hbm, bool bUpdate = false)
+ {
+ ATLASSERT((k_(key) <= k_SmallHighContrastImage) && (k_(key) >= k_LargeImage));
+
+ m_hbm[k_(key) - k_LargeImage].Attach(hbm);
+
+ return bUpdate ?
+ GetWndRibbon().InvalidateProperty(GetID(), key) :
+ S_OK;
+ }
+
+ HRESULT OnGetImage(REFPROPERTYKEY key, PROPVARIANT* ppv)
+ {
+ ATLASSERT((k_(key) <= k_SmallHighContrastImage) && (k_(key) >= k_LargeImage));
+
+ const INT iImage = k_(key) - k_LargeImage;
+
+ if (m_hbm[iImage].IsNull())
+ m_hbm[iImage] = GetWndRibbon().OnRibbonQueryImage(GetID(), key);
+
+ return m_hbm[iImage].IsNull() ?
+ E_NOTIMPL :
+ SetPropertyVal(key, GetImage(m_hbm[iImage], UI_OWNERSHIP_COPY), ppv);
+ }
+
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ ATLASSERT (nCmdID == GetID());
+
+ return (k_(key) <= k_SmallHighContrastImage) && (k_(key) >= k_LargeImage) ?
+ OnGetImage(key, ppropvarNewValue) :
+ CtrlImpl::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Ribbon collection base classes
+
+// ItemProperty class: ribbon callback for each item in a collection
+//
+template <class TCollection>
+class ItemProperty : public IUISimplePropertySet
+{
+public:
+ ItemProperty(UINT i, TCollection* pCollection) : m_Index(i), m_pCollection(pCollection)
+ { }
+
+ const UINT m_Index;
+ TCollection* m_pCollection;
+
+ // IUISimplePropertySet method.
+ STDMETHODIMP GetValue(REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ return m_pCollection->OnGetItem(m_Index, key, value);
+ }
+
+ // IUnknown methods.
+ STDMETHODIMP_(ULONG) AddRef()
+ {
+ return 1;
+ }
+
+ STDMETHODIMP_(ULONG) Release()
+ {
+ return 1;
+ }
+
+ STDMETHODIMP QueryInterface(REFIID iid, void** ppv)
+ {
+ if ((iid == __uuidof(IUnknown)) || (iid == __uuidof(IUISimplePropertySet)))
+ {
+ *ppv = this;
+ return S_OK;
+ }
+ else
+ {
+ return E_NOINTERFACE;
+ }
+ }
+};
+
+
+// CollectionImplBase: base class for all RibbonUI collections
+//
+template <class TCollection, size_t t_size>
+class CollectionImplBase
+{
+ typedef CollectionImplBase<TCollection, t_size> thisClass;
+
+public:
+ CollectionImplBase()
+ {
+ for (int i = 0; i < t_size; i++)
+ m_apItems[i] = new ItemProperty<TCollection>(i, static_cast<TCollection*>(this));
+ }
+
+ ~CollectionImplBase()
+ {
+ for (int i = 0; i < t_size; i++)
+ delete m_apItems[i];
+ }
+
+// Data members
+ ItemProperty<TCollection>* m_apItems[t_size];
+};
+
+// CollectionImpl: handles categories and collecton resizing
+//
+template <class TCtrl, size_t t_items, size_t t_categories>
+class CollectionImpl : public CollectionImplBase<CollectionImpl<TCtrl, t_items, t_categories>, t_items + t_categories>
+{
+ typedef CollectionImpl<TCtrl, t_items, t_categories> thisClass;
+public:
+ typedef thisClass Collection;
+
+ CollectionImpl() : m_size(t_items)
+ {
+ FillMemory(m_auItemCat, sizeof m_auItemCat, 0xff); // UI_COLLECTION_INVALIDINDEX
+ }
+
+ UINT32 m_auItemCat[t_items];
+ Text m_asCatName[max(t_categories, 1)];
+ size_t m_size;
+
+// Operations
+ HRESULT SetItemCategory(UINT uItem, UINT uCat, bool bUpdate = false)
+ {
+ ATLASSERT((uItem < t_items) && (uCat < t_categories));
+
+ m_auItemCat[uItem] = uCat;
+
+ return bUpdate ? InvalidateItems() : S_OK;
+ }
+
+ HRESULT SetCategoryText(UINT uCat, LPCWSTR sText, bool bUpdate = false)
+ {
+ ATLASSERT(uCat < t_categories);
+
+ m_asCatName[uCat] = sText;
+
+ return bUpdate ? InvalidateCategories() : S_OK;
+ }
+
+ HRESULT Resize(size_t size, bool bUpdate = false)
+ {
+ ATLASSERT(size <= t_items);
+
+ m_size = size;
+
+ return bUpdate ? InvalidateItems() : S_OK;
+ }
+
+// Implementation
+ HRESULT OnGetItem(UINT uIndex, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ ATLASSERT(uIndex < t_items + t_categories);
+ TCtrl* pCtrl = static_cast<TCtrl*>(this);
+
+ return uIndex < t_items ?
+ pCtrl->DoGetItem(uIndex, key, value) :
+ pCtrl->DoGetCategory(uIndex - t_items, key, value);
+ }
+
+ HRESULT DoGetItem(UINT uItem, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ ATLASSERT(k_(key) == k_CategoryId);
+ UINT32 uCat = UI_COLLECTION_INVALIDINDEX;
+
+ if (t_categories != 0)
+ {
+ if (m_auItemCat[uItem] == UI_COLLECTION_INVALIDINDEX)
+ {
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+ m_auItemCat[uItem] = ribbon.OnRibbonQueryItemCategory(TCtrl::GetID(), uItem);
+ }
+ uCat = m_auItemCat[uItem];
+ }
+
+ return SetPropertyVal(key, uCat, value);
+ }
+
+ HRESULT DoGetCategory(UINT uCat, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ HRESULT hr = S_OK;
+
+ switch (k_(key))
+ {
+ case k_Label:
+ if (m_asCatName[uCat].IsEmpty())
+ {
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+ m_asCatName[uCat] = ribbon.OnRibbonQueryCategoryText(TCtrl::GetID(), uCat);
+ }
+ hr = SetPropertyVal(key, (LPCWSTR)m_asCatName[uCat], value);
+ break;
+ case k_CategoryId:
+ hr = SetPropertyVal(key, uCat, value);
+ break;
+ default:
+ ATLASSERT(FALSE);
+ break;
+ }
+
+ return hr;
+ }
+
+ HRESULT InvalidateItems()
+ {
+ return static_cast<TCtrl*>(this)->Invalidate(UI_PKEY_ItemsSource);
+ }
+
+ HRESULT InvalidateCategories()
+ {
+ return static_cast<TCtrl*>(this)->Invalidate(UI_PKEY_Categories);
+ }
+
+ HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* /*ppropvarNewValue*/)
+ {
+ ATLASSERT(nCmdID == TCtrl::GetID());
+ nCmdID; // avoid level 4 warning
+
+ HRESULT hr = E_NOTIMPL;
+ switch (k_(key))
+ {
+ case k_ItemsSource:
+ {
+ ATL::CComQIPtr<IUICollection> pIUICollection(ppropvarCurrentValue->punkVal);
+ ATLASSERT(pIUICollection);
+ hr = pIUICollection->Clear();
+ for (UINT i = 0; i < m_size; i++)
+ {
+ if FAILED(hr = pIUICollection->Add(m_apItems[i]))
+ break;
+ }
+ ATLASSERT(SUCCEEDED(hr));
+ }
+ break;
+ case k_Categories:
+ if (t_categories != 0)
+ {
+ ATL::CComQIPtr<IUICollection> pIUICategory(ppropvarCurrentValue->punkVal);
+ ATLASSERT(pIUICategory.p);
+ hr = pIUICategory->Clear();
+ for (UINT i = t_items; i < t_items + t_categories; i++)
+ {
+ if FAILED(hr = pIUICategory->Add(m_apItems[i]))
+ break;
+ }
+ ATLASSERT(SUCCEEDED(hr));
+ }
+ break;
+ }
+
+ return hr;
+ }
+};
+
+// TextCollectionImpl: handles item labels and selection
+//
+template <class TCtrl, size_t t_items, size_t t_categories = 0>
+class TextCollectionImpl : public CollectionImpl<TCtrl, t_items, t_categories>
+{
+ typedef TextCollectionImpl<TCtrl, t_items, t_categories> thisClass;
+public:
+ typedef thisClass TextCollection;
+
+ TextCollectionImpl() : m_uSelected(UI_COLLECTION_INVALIDINDEX)
+ { }
+
+ Text m_asText[t_items];
+ UINT m_uSelected;
+
+ // Operations
+ HRESULT SetItemText(UINT uItem, LPCWSTR sText, bool bUpdate = false)
+ {
+ ATLASSERT(uItem < t_items);
+
+ m_asText[uItem] = sText;
+
+ return bUpdate ? InvalidateItems() : S_OK;
+ }
+
+ UINT GetSelected()
+ {
+ return m_uSelected;
+ }
+
+ HRESULT Select(UINT uItem, bool bUpdate = false)
+ {
+ ATLASSERT((uItem < t_items) || (uItem == UI_COLLECTION_INVALIDINDEX));
+
+ m_uSelected = uItem;
+
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+ return bUpdate ?
+ ribbon.SetProperty(TCtrl::GetID(), UI_PKEY_SelectedItem, uItem) :
+ S_OK;
+ }
+
+// Implementation
+ HRESULT DoGetItem(UINT uItem, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ ATLASSERT(uItem < t_items);
+
+ if (k_(key) == k_Label)
+ {
+ if (m_asText[uItem].IsEmpty())
+ {
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+ m_asText[uItem] = ribbon.OnRibbonQueryItemText(TCtrl::GetID(), uItem);
+ }
+ return SetPropertyVal(key, (LPCWSTR)m_asText[uItem], value);
+ }
+ else
+ {
+ return Collection::DoGetItem(uItem, key, value);
+ }
+ }
+
+ HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ ATLASSERT(nCmdID == TCtrl::GetID());
+
+ if (k_(key) == k_SelectedItem)
+ {
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+ UINT uSel = UI_COLLECTION_INVALIDINDEX;
+ if ((m_uSelected == UI_COLLECTION_INVALIDINDEX) &&
+ ribbon.OnRibbonQuerySelectedItem(TCtrl::GetID(), uSel))
+ m_uSelected = uSel;
+
+ return SetPropertyVal(key, m_uSelected, ppropvarNewValue);
+ }
+ else
+ {
+ return Collection::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ }
+ }
+};
+
+// ItemCollectionImpl: handles item image
+//
+template <class TCtrl, size_t t_items, size_t t_categories = 0>
+class ItemCollectionImpl : public TextCollectionImpl<TCtrl, t_items, t_categories>
+{
+ typedef ItemCollectionImpl<TCtrl, t_items, t_categories> thisClass;
+public:
+ typedef thisClass ItemCollection;
+
+ ItemCollectionImpl()
+ {
+ ZeroMemory(m_aBitmap, sizeof m_aBitmap);
+ }
+
+ CBitmap m_aBitmap[t_items];
+
+ // Operations
+ HRESULT SetItemImage(UINT uIndex, HBITMAP hbm, bool bUpdate = false)
+ {
+ ATLASSERT(uIndex < t_items);
+
+ m_aBitmap[uIndex] = hbm;
+
+ return bUpdate ? InvalidateItems() : S_OK;
+ }
+
+// Implementation
+ HRESULT DoGetItem(UINT uItem, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ ATLASSERT(uItem < t_items);
+
+ if (k_(key) == k_ItemImage)
+ {
+ if (m_aBitmap[uItem].IsNull())
+ {
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+ m_aBitmap[uItem] = ribbon.OnRibbonQueryItemImage(TCtrl::GetID(), uItem);
+ }
+ return m_aBitmap[uItem].IsNull() ?
+ E_NOTIMPL :
+ SetPropertyVal(key, GetImage(m_aBitmap[uItem], UI_OWNERSHIP_COPY), value);
+ }
+ else
+ {
+ return TextCollection::DoGetItem(uItem, key, value);
+ }
+ }
+};
+
+// ComboCollectionImpl: handles combo text
+//
+template <class TCtrl, size_t t_items, size_t t_categories = 0>
+class ComboCollectionImpl : public ItemCollectionImpl<TCtrl, t_items, t_categories>
+{
+ typedef ComboCollectionImpl<TCtrl, t_items, t_categories> thisClass;
+public:
+ typedef thisClass ComboCollection;
+
+ // Operations
+ HRESULT SetComboText(LPCWSTR sText)
+ {
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+ return ribbon.IsRibbonUI() ?
+ ribbon.SetProperty(TCtrl::GetID(), UI_PKEY_StringValue, sText) :
+ S_OK;
+ }
+
+ LPCWSTR GetComboText()
+ {
+ static WCHAR sCombo[RIBBONUI_MAX_TEXT] = { 0 };
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+ PROPVARIANT var;
+ if (ribbon.IsRibbonUI())
+ {
+ HRESULT hr = ribbon.GetIUIFrameworkPtr()->GetUICommandProperty(TCtrl::GetID(), UI_PKEY_StringValue, &var);
+ hr = PropVariantToString(var, sCombo, RIBBONUI_MAX_TEXT);
+ return sCombo;
+ }
+ return NULL;
+ }
+};
+
+// CommandCollectionImpl: handles RibbonUI command collection controls
+//
+template <class TCtrl, size_t t_items, size_t t_categories = 0>
+class CommandCollectionImpl : public CollectionImpl<TCtrl, t_items, t_categories>
+{
+ typedef CommandCollectionImpl<TCtrl, t_items, t_categories> thisClass;
+public:
+ typedef thisClass CommandCollection;
+
+ CommandCollectionImpl()
+ {
+ ZeroMemory(m_auCmd, sizeof m_auCmd);
+ ZeroMemory(m_aCmdType, sizeof m_aCmdType);
+ }
+
+ UINT32 m_auCmd[t_items];
+ BYTE m_aCmdType[t_items];
+
+ // Operations
+ HRESULT SetItemCommand(UINT uItem, UINT32 uCommandID, bool bUpdate = false)
+ {
+ ATLASSERT(uItem < t_items);
+
+ if (uCommandID == m_auCmd[uItem])
+ return S_OK;
+
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+
+ m_auCmd[uItem] = uCommandID;
+ if (uCommandID != 0)
+ ribbon.UIAddRibbonElement(uCommandID);
+
+ return bUpdate ? InvalidateItems() : S_OK;
+ }
+
+ HRESULT SetItemCommandType(UINT uItem, UI_COMMANDTYPE type, bool bUpdate = false)
+ {
+ ATLASSERT(uItem < t_items);
+
+ m_aCmdType[uItem] = (BYTE)type;
+
+ return bUpdate ? InvalidateItems() : S_OK;
+ }
+
+// Implementation
+ HRESULT DoGetItem(UINT uItem, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ ATLASSERT(uItem < t_items);
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+
+ HRESULT hr = E_FAIL;
+ switch (k_(key))
+ {
+ case k_CommandId:
+ if (m_auCmd[uItem] == 0)
+ SetItemCommand(uItem, ribbon.OnRibbonQueryItemCommand(TCtrl::GetID(), uItem));
+ hr = SetPropertyVal(key, m_auCmd[uItem], value);
+ break;
+ case k_CommandType:
+ if (m_aCmdType[uItem] == UI_COMMANDTYPE_UNKNOWN)
+ SetItemCommandType(uItem, ribbon.OnRibbonQueryItemCommandType(TCtrl::GetID(), uItem));
+ hr = SetPropertyVal(key, UINT32(m_aCmdType[uItem]), value);
+ break;
+ case k_CategoryId:
+ default:
+ hr = Collection::DoGetItem(uItem, key, value);
+ break;
+ }
+
+ return hr;
+ }
+
+ HRESULT Select(UINT /*uItem*/, bool /*bUpdate*/ = false)
+ {
+ ATLASSERT(FALSE);
+ return S_OK;
+ }
+};
+
+// SimpleCollectionImpl: collection class for ribbon simple collection controls
+//
+template <class TCtrl, size_t t_size, UI_COMMANDTYPE t_CommandType = UI_COMMANDTYPE_ACTION>
+class SimpleCollectionImpl : public CollectionImplBase<SimpleCollectionImpl<TCtrl, t_size>, t_size>
+{
+ typedef SimpleCollectionImpl<TCtrl, t_size, t_CommandType> thisClass;
+public:
+ typedef CollectionImplBase<thisClass, t_size> CollectionBase;
+ typedef thisClass SimpleCollection;
+
+// Implementation
+ HRESULT OnGetItem(UINT uItem, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ ATLASSERT(uItem < t_size);
+ TCtrl::WndRibbon& ribbon = static_cast<TCtrl*>(this)->GetWndRibbon();
+
+ HRESULT hr = E_NOTIMPL;
+ switch (k_(key))
+ {
+ case k_ItemImage:
+ if (HBITMAP hbm = ribbon.DefRibbonQueryItemImage(TCtrl::GetID(), uItem))
+ hr = SetPropertyVal(key, GetImage(hbm, UI_OWNERSHIP_TRANSFER), value);
+ break;
+ case k_Label:
+ if (LPCWSTR sText = ribbon.DefRibbonQueryItemText(TCtrl::GetID(), uItem))
+ hr = SetPropertyVal(key, (LPCWSTR)sText, value);
+ break;
+ case k_CommandType:
+ hr = SetPropertyVal(key, t_CommandType, value);
+ break;
+ case k_CommandId:
+ hr = SetPropertyVal(key, ribbon.DefRibbonQueryItemCommand(TCtrl::GetID(), uItem), value);
+ break;
+ case k_CategoryId:
+ hr = SetPropertyVal(key, UI_COLLECTION_INVALIDINDEX, value);
+ break;
+ default:
+ ATLASSERT(FALSE);
+ break;
+ }
+
+ return hr;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Ribbon collection control classes
+
+// CollectionCtrlImpl: specializable class for ribbon collection controls
+//
+template <class T, UINT t_ID, class TCollection>
+class CollectionCtrlImpl : public CommandCtrlImpl<T, t_ID>, public TCollection
+{
+ typedef CollectionCtrlImpl<T, t_ID, TCollection> thisClass;
+public:
+ typedef CommandCtrlImpl<T, t_ID> CommandCtrl;
+ typedef TCollection Collection;
+
+ // Implementation
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ ATLASSERT(nCmdID == GetID());
+ ATLASSERT(ppropvarNewValue);
+
+ HRESULT hr = Collection::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ if FAILED(hr)
+ hr = CommandCtrl::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+
+ return hr;
+ }
+
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* /*pCommandExecutionProperties*/)
+ {
+ ATLASSERT (nCmdID == GetID());
+ nCmdID; // avoid level4 warning
+
+ if (key == NULL) // gallery button pressed
+ {
+ GetWndRibbon().OnRibbonItemSelected(GetID(), UI_EXECUTIONVERB_EXECUTE, UI_COLLECTION_INVALIDINDEX);
+ return S_OK;
+ }
+
+ ATLASSERT(k_(*key) == k_SelectedItem);
+ ATLASSERT(ppropvarValue);
+
+ HRESULT hr = S_OK;
+ UINT32 uSel = 0xffff;
+ hr = UIPropertyToUInt32(*key, *ppropvarValue, &uSel);
+
+ if (SUCCEEDED(hr))
+ {
+ if (GetWndRibbon().OnRibbonItemSelected(GetID(), verb, uSel))
+ TCollection::Select(uSel);
+ }
+
+ return hr;
+ }
+};
+
+// ToolbarGalleryCtrlImpl: base class for ribbon toolbar gallery controls
+//
+template <class T, UINT t_ID, UINT t_idTB, size_t t_size>
+class ToolbarGalleryCtrlImpl : public CollectionCtrlImpl<T, t_ID, CommandCollectionImpl<ToolbarGalleryCtrlImpl<T, t_ID, t_idTB, t_size>, t_size>>
+{
+public:
+ ToolbarGalleryCtrlImpl()
+ {
+ CResource tbres;
+ ATLVERIFY(tbres.Load(RT_TOOLBAR, t_idTB));
+ _AtlToolBarData* pData = (_AtlToolBarData*)tbres.Lock();
+ ATLASSERT(pData);
+ ATLASSERT(pData->wVersion == 1);
+
+ WORD* pItems = pData->items();
+ INT j = 0;
+ for (int i = 0; (i < pData->wItemCount) && (j < t_size); i++)
+ {
+ if (pItems[i] != 0)
+ {
+ m_aCmdType[j] = UI_COMMANDTYPE_ACTION;
+ m_auCmd[j++] = pItems[i];
+ }
+ }
+
+ if (j < t_size)
+ Resize(j);
+ }
+
+ HRESULT DoGetItem(UINT uItem, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ ATLASSERT(uItem < m_size);
+ ATLASSERT(m_auCmd[uItem]);
+
+ HRESULT hr = E_FAIL;
+ switch (k_(key))
+ {
+ case k_CommandId:
+ hr = SetPropertyVal(key, m_auCmd[uItem], value);
+ break;
+ case k_CommandType:
+ hr = SetPropertyVal(key, UINT32(m_aCmdType[uItem]), value);
+ break;
+ case k_CategoryId:
+ hr = SetPropertyVal(key, UI_COLLECTION_INVALIDINDEX, value);
+ break;
+ default:
+ ATLASSERT(FALSE);
+ break;
+ }
+
+ return hr;
+ }
+};
+
+
+// SimpleCollectionCtrlImpl: base class for simple gallery and listbox controls
+//
+template <class T, UINT t_ID, size_t t_size, UI_COMMANDTYPE t_CommandType = UI_COMMANDTYPE_ACTION>
+class SimpleCollectionCtrlImpl :
+ public CommandCtrlImpl<T, t_ID>,
+ public SimpleCollectionImpl<SimpleCollectionCtrlImpl<T, t_ID, t_size, t_CommandType>, t_size, t_CommandType>
+{
+ typedef SimpleCollectionCtrlImpl<T, t_ID, t_size, t_CommandType> thisClass;
+public:
+ typedef thisClass SimpleCollection;
+
+ SimpleCollectionCtrlImpl() : m_uSelected(0)
+ { }
+
+ UINT m_uSelected;
+
+ HRESULT Select(UINT uItem, bool bUpdate = false)
+ {
+ ATLASSERT((uItem < t_size) || (uItem == UI_COLLECTION_INVALIDINDEX));
+
+ m_uSelected = uItem;
+
+ return bUpdate ?
+ GetWndRibbon().SetProperty(GetID(), UI_PKEY_SelectedItem, uItem) :
+ S_OK;
+ }
+
+ // Implementation
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ ATLASSERT(nCmdID == GetID());
+ ATLASSERT(ppropvarNewValue != NULL);
+
+ HRESULT hr = S_OK;
+ switch (k_(key))
+ {
+ case k_ItemsSource:
+ {
+ ATL::CComQIPtr<IUICollection> pIUICollection(ppropvarCurrentValue->punkVal);
+ ATLASSERT(pIUICollection.p);
+ hr = pIUICollection->Clear();
+ for (UINT i = 0; i < t_size; i++)
+ {
+ if FAILED(hr = pIUICollection->Add(m_apItems[i]))
+ break;
+ }
+ ATLASSERT(SUCCEEDED(hr));
+ }
+ break;
+ case k_SelectedItem:
+ hr = SetPropertyVal(UI_PKEY_SelectedItem, m_uSelected, ppropvarNewValue);
+ break;
+ default:
+ hr = CommandCtrlImpl::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ break;
+ }
+
+ return hr;
+ }
+
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* /*pCommandExecutionProperties*/)
+ {
+ ATLASSERT (nCmdID == GetID());
+ nCmdID; // avoid level 4 warning
+
+ HRESULT hr = S_OK;
+ if (key == NULL) // gallery button pressed
+ {
+ GetWndRibbon().OnRibbonItemSelected(GetID(), UI_EXECUTIONVERB_EXECUTE, UI_COLLECTION_INVALIDINDEX);
+ return hr;
+ }
+ ATLASSERT(k_(*key) == k_SelectedItem);
+ ATLASSERT(ppropvarValue);
+
+ if SUCCEEDED(hr = UIPropertyToUInt32(*key, *ppropvarValue, &m_uSelected))
+ GetWndRibbon().OnRibbonItemSelected(GetID(), verb, m_uSelected);
+
+ return hr;
+ }
+};
+
+// RecentItemsCtrlImpl
+//
+template <class T, UINT t_ID, class TDocList = CRecentDocumentList>
+class RecentItemsCtrlImpl :
+ public CtrlImpl<T, t_ID>,
+ public CollectionImplBase<RecentItemsCtrlImpl<T, t_ID, TDocList>, TDocList::m_nMaxEntries_Max>,
+ public TDocList
+{
+ typedef RecentItemsCtrlImpl<T, t_ID, TDocList> thisClass;
+public:
+ typedef thisClass RecentItems;
+
+ // Implementation
+ HRESULT OnGetItem(UINT uItem, REFPROPERTYKEY key, PROPVARIANT *value)
+ {
+ ATLASSERT((INT)uItem < GetMaxEntries());
+
+ LPCWSTR sPath = m_arrDocs[uItem].szDocName;
+ HRESULT hr = E_NOTIMPL;
+ switch (k_(key))
+ {
+ case k_Label:
+ hr = SetPropertyVal(key, GetWndRibbon().OnRibbonQueryRecentItemName(sPath), value);
+ break;
+ case k_LabelDescription:
+ hr = SetPropertyVal(key, sPath, value);
+ break;
+ default:
+ ATLASSERT(FALSE);
+ break;
+ }
+
+ return hr;
+ }
+
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ ATLASSERT(nCmdID == GetID());
+ ATLASSERT(ppropvarNewValue);
+
+ HRESULT hr = S_OK;
+ switch (k_(key))
+ {
+ case k_RecentItems:
+ if (SAFEARRAY* psa = SafeArrayCreateVector(VT_UNKNOWN, 0, m_arrDocs.GetSize()))
+ {
+ const int iLastIndex = m_arrDocs.GetSize() - 1;
+ for (LONG i = 0; i <= iLastIndex; i++)
+ SafeArrayPutElement(psa, &i, m_apItems[iLastIndex - i]); // reverse order
+
+ hr = SetPropertyVal(key, psa, ppropvarNewValue);
+ SafeArrayDestroy(psa);
+ }
+ break;
+ default:
+ hr = CtrlImpl::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ break;
+ }
+
+ return hr;
+ }
+
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* /*pCommandExecutionProperties*/)
+ {
+ ATLASSERT(nCmdID == GetID());
+ nCmdID; // avoid level 4 warning
+ ATLASSERT(verb == UI_EXECUTIONVERB_EXECUTE);
+ verb; // avoid level 4 warning
+ ATLASSERT((key) && (k_(*key) == k_SelectedItem));
+ ATLASSERT(ppropvarValue);
+
+ UINT32 uSel = 0xffff;
+ HRESULT hr = UIPropertyToUInt32(*key, *ppropvarValue, &uSel);
+ if SUCCEEDED(hr)
+ {
+ ATLASSERT(uSel < (UINT)GetMaxEntries());
+ GetWndRibbon().DefCommandExecute(ID_FILE_MRU_FIRST + uSel);
+ }
+
+ return hr;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Ribbon stand-alone control classes
+
+// FontCtrlImpl
+//
+template <class T, UINT t_ID>
+class FontCtrlImpl : public CtrlImpl<T, t_ID>
+{
+public:
+
+ CharFormat m_cf;
+
+// Implementation
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* pCommandExecutionProperties)
+ {
+ ATLASSERT (nCmdID == GetID());
+ nCmdID; // avoid level 4 warning
+ ATLASSERT ((key) && (k_(*key) == k_FontProperties));
+ key; // avoid level 4 warning
+
+ HRESULT hr = E_INVALIDARG;
+ switch (verb)
+ {
+ case UI_EXECUTIONVERB_PREVIEW:
+ case UI_EXECUTIONVERB_EXECUTE:
+ ATLASSERT(pCommandExecutionProperties);
+ PROPVARIANT propvar;
+
+ if (SUCCEEDED(hr = pCommandExecutionProperties->GetValue(UI_PKEY_FontProperties_ChangedProperties, &propvar)))
+ m_cf << ATL::CComQIPtr<IPropertyStore>(propvar.punkVal);
+ break;
+
+ case UI_EXECUTIONVERB_CANCELPREVIEW:
+ ATLASSERT(ppropvarValue);
+ ATL::CComPtr<IPropertyStore> pStore;
+
+ if (SUCCEEDED(hr = UIPropertyToInterface(UI_PKEY_FontProperties, *ppropvarValue, &pStore)))
+ m_cf << pStore;
+ break;
+ }
+
+ if (SUCCEEDED(hr))
+ GetWndRibbon().OnRibbonFontCtrlExecute(GetID(), verb, &m_cf);
+ else
+ ATLASSERT(FALSE);
+
+ return hr;
+ }
+
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ if ((k_(key) == k_FontProperties) && (GetWndRibbon().OnRibbonQueryFont(t_ID, m_cf)))
+ {
+ ATL::CComQIPtr<IPropertyStore> pStore(ppropvarCurrentValue->punkVal);
+ m_cf >> pStore;
+ return SetPropertyVal(key, pStore.p, ppropvarNewValue);
+ }
+ else
+ {
+ return CtrlImpl::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ }
+ }
+};
+
+// ColorCtrlImpl
+//
+template <class T, UINT t_ID>
+class ColorCtrlImpl : public CommandCtrlImpl<T, t_ID>
+{
+public:
+ ColorCtrlImpl() : m_colorType(UI_SWATCHCOLORTYPE_NOCOLOR), m_color(0x800080) /*MAGENTA*/
+ { }
+
+ COLORREF m_color;
+ UINT32 m_colorType; // value in UI_SWATCHCOLORTYPE
+ Text m_sLabels[6]; // k_MoreColorsLabel to k_ThemeColorsCategoryLabel
+ ATL::CSimpleArray<COLORREF> m_aColors[2];
+ ATL::CSimpleArray<LPCWSTR> m_aTooltips[2];
+
+ // Operations
+ HRESULT SetColor(COLORREF color, bool bUpdate = false)
+ {
+ if (m_colorType != UI_SWATCHCOLORTYPE_RGB)
+ SetColorType(UI_SWATCHCOLORTYPE_RGB, bUpdate);
+ m_color = color;
+ return bUpdate ? SetProperty(UI_PKEY_Color, color) : S_OK;
+ }
+
+ HRESULT SetColorType(UI_SWATCHCOLORTYPE type, bool bUpdate = false)
+ {
+ m_colorType = type;
+ return bUpdate ? SetProperty(UI_PKEY_ColorType, type) : S_OK;
+ }
+
+ HRESULT SetColorLabel(REFPROPERTYKEY key, LPCWSTR sLabel, bool bUpdate = false)
+ {
+ ATLASSERT((k_(key) >= k_ThemeColorsCategoryLabel) && (k_(key) <= k_MoreColorsLabel));
+ m_sLabels[k_(key) - k_ThemeColorsCategoryLabel] = sLabel;
+ return bUpdate ? SetProperty(key, sLabel) : S_OK;
+ }
+
+ HRESULT SetColorArray(REFPROPERTYKEY key, COLORREF* pColor, bool bUpdate = false)
+ {
+ ATLASSERT((k_(key) == k_ThemeColors) || (k_(key) == k_StandardColors));
+
+ const INT ic = k_(key) - k_ThemeColors;
+ m_aColors[ic].RemoveAll();
+ while (*pColor != 0x800080) /*MAGENTA*/
+ m_aColors[ic].Add(*pColor++);
+
+ if (bUpdate)
+ {
+ PROPVARIANT var;
+ if SUCCEEDED(InitPropVariantFromUInt32Vector(m_aColors[ic].GetData(), m_aColors[ic].GetSize(), &var))
+ return SetProperty(key, var);
+ else
+ return E_INVALIDARG;
+ }
+ else
+ {
+ return S_OK;
+ }
+ }
+
+ HRESULT SetColorTooltips(REFPROPERTYKEY key, LPCWSTR* ppsTT, bool bUpdate = false)
+ {
+ ATLASSERT((k_(key) == k_ThemeColorsTooltips) || (k_(key) == k_StandardColorsTooltips));
+
+ const INT ic = k_(key) - k_ThemeColorsTooltips;
+ m_aTooltips[ic].RemoveAll();
+ while (*ppsTT)
+ m_aTooltips[ic].Add(*ppsTT++);
+
+ if (bUpdate)
+ {
+ PROPVARIANT var;
+ if SUCCEEDED(InitPropVariantFromStringVector(m_aTooltips[ic].GetData(), m_aTooltips[ic].GetSize(), &var))
+ return SetProperty(key, var);
+ else
+ return E_INVALIDARG;
+ }
+ else
+ {
+ return S_OK;
+ }
+ }
+
+ // Implementation
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* pCommandExecutionProperties)
+ {
+ ATLASSERT (nCmdID == GetID());
+ nCmdID; // avoid level 4 warning
+ ATLASSERT (key && (k_(*key) == k_ColorType));
+ key; // avoid level 4 warning
+ ATLASSERT (ppropvarValue);
+
+ HRESULT hr = PropVariantToUInt32(*ppropvarValue, &m_colorType);
+ ATLASSERT(SUCCEEDED(hr));
+
+ if (SUCCEEDED(hr) && (m_colorType == UI_SWATCHCOLORTYPE_RGB))
+ {
+ ATLASSERT(pCommandExecutionProperties);
+ PROPVARIANT var;
+ if SUCCEEDED(hr = pCommandExecutionProperties->GetValue(UI_PKEY_Color, &var))
+ hr = PropVariantToUInt32(var, &m_color);
+ }
+
+ if SUCCEEDED(hr)
+ GetWndRibbon().OnRibbonColorCtrlExecute(GetID(), verb, (UI_SWATCHCOLORTYPE)m_colorType/*uType*/, m_color);
+ else
+ ATLASSERT(FALSE); // something was wrong
+
+ return hr;
+ }
+
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ ATLASSERT (nCmdID == GetID());
+
+ HRESULT hr = E_NOTIMPL;
+
+ switch (k_(key))
+ {
+ case k_ColorType:
+ hr = SetPropertyVal(key, m_colorType, ppropvarNewValue);
+ break;
+ case k_Color:
+ if (m_color == 0x800080) /*MAGENTA*/
+ m_color = GetWndRibbon().OnRibbonQueryColor(GetID());
+ hr = SetPropertyVal(key, m_color, ppropvarNewValue);
+ break;
+ case k_ColorMode:
+ break;
+ case k_ThemeColorsCategoryLabel:
+ case k_StandardColorsCategoryLabel:
+ case k_RecentColorsCategoryLabel:
+ case k_AutomaticColorLabel:
+ case k_NoColorLabel:
+ case k_MoreColorsLabel:
+ {
+ const UINT iLabel = k_(key) - k_ThemeColorsCategoryLabel;
+ if (m_sLabels[iLabel].IsEmpty())
+ if (LPCWSTR psLabel = GetWndRibbon().OnRibbonQueryColorLabel(GetID(), key))
+ m_sLabels[iLabel] = psLabel;
+ if (!m_sLabels[iLabel].IsEmpty())
+ hr = SetPropertyVal(key, (LPCWSTR)m_sLabels[iLabel], ppropvarNewValue);
+ }
+ break;
+ case k_ThemeColors:
+ case k_StandardColors:
+ {
+ const INT ic = k_(key) - k_ThemeColors;
+ if (!m_aColors[ic].GetSize())
+ if (COLORREF* pColor = GetWndRibbon().OnRibbonQueryColorArray(GetID(), key))
+ SetColorArray(key, pColor);
+ if (INT iMax = m_aColors[ic].GetSize())
+ hr = InitPropVariantFromUInt32Vector(m_aColors[ic].GetData(), iMax, ppropvarNewValue);
+ }
+ break;
+ case k_ThemeColorsTooltips:
+ case k_StandardColorsTooltips:
+ {
+ const INT ic = k_(key) - k_ThemeColorsTooltips;
+ if (m_aTooltips[ic].GetSize() == 0)
+ if (LPCWSTR* ppsTT = GetWndRibbon().OnRibbonQueryColorTooltips(GetID(), key))
+ SetColorTooltips(key, ppsTT);
+ if (INT iMax = m_aTooltips[ic].GetSize())
+ hr = InitPropVariantFromStringVector(m_aTooltips[ic].GetData(), iMax, ppropvarNewValue);
+ }
+ break;
+ default:
+ hr = CommandCtrlImpl::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ break;
+ }
+
+ return hr;
+ }
+};
+
+// SpinnerCtrlImpl
+//
+template <class T, UINT t_ID, typename V = LONG>
+class SpinnerCtrlImpl : public CtrlImpl<T, t_ID>
+{
+public:
+ SpinnerCtrlImpl()
+ {
+ m_Values[0] = m_Values[2] = m_Values[4] = 0;
+ m_Values[1] = 100;
+ m_Values[3] = 1;
+ }
+
+ V m_Values[5];
+ // k_DecimalValue = 201, k_MaxValue = 203, k_MinValue, k_Increment, k_DecimalPlaces
+
+ Text m_FormatString;
+ Text m_RepresentativeString;
+
+ // Operations
+ HRESULT SetDecimalPlaces(V vPlaces, bool bUpdate = false)
+ {
+ return SetValue(UI_PKEY_DecimalPlaces, vPlaces, bUpdate);
+ }
+
+ HRESULT SetMin(V vMin, bool bUpdate = false)
+ {
+ return SetValue(UI_PKEY_MinValue, vMin, bUpdate);
+ }
+
+ HRESULT SetMax(V vMax, bool bUpdate = false)
+ {
+ return SetValue(UI_PKEY_MaxValue, vMax, bUpdate);
+ }
+
+ HRESULT SetVal(V vVal, bool bUpdate = false)
+ {
+ return SetValue(UI_PKEY_DecimalValue, vVal, bUpdate);
+ }
+
+ HRESULT SetIncrement(V vIncrement, bool bUpdate = false)
+ {
+ return SetValue(UI_PKEY_Increment, vIncrement, bUpdate);
+ }
+
+ HRESULT SetFormatString(LPCWSTR sFormat, bool bUpdate = false)
+ {
+ return SetText(UI_PKEY_FormatString, sFormat, bUpdate);
+ }
+
+ HRESULT SetRepresentativeString(LPCWSTR sRepresentative, bool bUpdate = false)
+ {
+ return SetText(UI_PKEY_RepresentativeString, sRepresentative, bUpdate);
+ }
+
+ // Implementation
+ HRESULT SetText(REFPROPERTYKEY key, LPCWSTR sText, bool bUpdate = false)
+ {
+ switch (k_(key))
+ {
+ case k_FormatString:
+ m_FormatString = sText;
+ break;
+ case k_RepresentativeString:
+ m_RepresentativeString = sText;
+ break;
+ default:
+ return CtrlImpl::SetText(key, sText, bUpdate);
+ }
+
+ return bUpdate ?
+ GetWndRibbon().InvalidateProperty(GetID(), key) :
+ S_OK;
+ }
+
+ HRESULT SetValue(REFPROPERTYKEY key, V val, bool bUpdate = false)
+ {
+ ATLASSERT((k_(key) <= k_DecimalPlaces) && (k_(key) >= k_DecimalValue));
+
+ const INT iVal = k_(key) == k_DecimalValue ? 0 : k_(key) - k_StringValue;
+ m_Values[iVal] = val;
+
+ if (bUpdate)
+ {
+ if(k_(key) == k_DecimalValue)
+ {
+ DECIMAL decVal;
+ InitDecimal(val, &decVal);
+ return SetProperty(key, &decVal);
+ }
+ else
+ {
+ return GetWndRibbon().InvalidateProperty(GetID(), key);
+ }
+ }
+ else
+ {
+ return S_OK;
+ }
+ }
+
+ HRESULT QueryValue(REFPROPERTYKEY key, LONG* plVal)
+ {
+ return GetWndRibbon().OnRibbonQuerySpinnerValue(GetID(), key, plVal);
+ }
+
+ HRESULT QueryValue(REFPROPERTYKEY key, DOUBLE* pdVal)
+ {
+ return GetWndRibbon().OnRibbonQueryFloatSpinnerValue(GetID(), key, pdVal);
+ }
+
+ HRESULT OnGetValue(REFPROPERTYKEY key, PROPVARIANT* ppv)
+ {
+ ATLASSERT((k_(key) <= k_DecimalPlaces) && (k_(key) >= k_DecimalValue));
+
+ const INT iVal = k_(key) == k_DecimalValue ? 0 : k_(key) - k_StringValue;
+
+ QueryValue(key, m_Values + iVal);
+
+ if (k_(key) == k_DecimalPlaces)
+ {
+ return SetPropertyVal(key, m_Values[iVal], ppv);
+ }
+ else
+ {
+ DECIMAL decVal;
+ InitDecimal(m_Values[iVal], &decVal);
+ return SetPropertyVal(key, &decVal, ppv);
+ }
+ }
+
+ HRESULT OnGetText(REFPROPERTYKEY key, Text& sVal, PROPVARIANT* ppv)
+ {
+ if (LPCWSTR sNew = GetWndRibbon().OnRibbonQueryText(GetID(), key))
+ sVal = sNew;
+ return SetPropertyVal(key, (LPCWSTR)sVal, ppv);
+ }
+
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* /*pCommandExecutionProperties*/)
+ {
+ ATLASSERT (nCmdID == GetID());
+ nCmdID; // avoid level 4 warning
+ ATLASSERT (key && (k_(*key) == k_DecimalValue));
+ key; // avoid level 4 warning
+ ATLASSERT (verb == UI_EXECUTIONVERB_EXECUTE);
+ verb; // avoid level 4 warning
+
+ DECIMAL decVal;
+
+ HRESULT hr = UIPropertyToDecimal(UI_PKEY_DecimalValue, *ppropvarValue, &decVal);
+ hr = InitVal(m_Values[0], &decVal);
+
+ GetWndRibbon().OnRibbonSpinnerCtrlExecute(GetID(), &m_Values[0]);
+
+ return hr;
+ }
+
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ ATLASSERT (nCmdID == GetID());
+
+ HRESULT hr = E_NOTIMPL;
+ switch (k_(key))
+ {
+ case k_DecimalPlaces:
+ case k_DecimalValue:
+ case k_Increment:
+ case k_MaxValue:
+ case k_MinValue:
+ hr = OnGetValue(key, ppropvarNewValue);
+ break;
+ case k_FormatString:
+ if (m_FormatString.IsEmpty())
+ return OnGetText(key, m_FormatString, ppropvarNewValue);
+ break;
+ case k_RepresentativeString:
+ if (m_RepresentativeString.IsEmpty())
+ return OnGetText(key, m_RepresentativeString, ppropvarNewValue);
+ break;
+ default:
+ hr = CtrlImpl::DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ break;
+ }
+
+ return hr;
+ }
+
+ // decimal conversion helpers
+ static HRESULT InitDecimal(LONG& val, DECIMAL* pDecimal)
+ {
+ return ::VarDecFromI4(val, pDecimal);
+ }
+
+ static HRESULT InitDecimal(DOUBLE& val, DECIMAL* pDecimal)
+ {
+ return ::VarDecFromR8(val, pDecimal);
+ }
+
+ static HRESULT InitVal(LONG& val, const DECIMAL* pDecimal)
+ {
+ return ::VarI4FromDec(pDecimal, &val);
+ }
+
+ static HRESULT InitVal(DOUBLE& val, const DECIMAL* pDecimal)
+ {
+ return ::VarR8FromDec(pDecimal, &val);
+ }
+};
+
+// CRibbonImpl Ribbon implementation class
+//
+template <class T>
+class CRibbonImpl :
+ public CRibbonUpdateUI<T>,
+ public ICtrl,
+ public IUIApplication,
+ public IUICommandHandler
+{
+ typedef CRibbonImpl<T> thisClass;
+public:
+ typedef thisClass Ribbon;
+ typedef T WndRibbon;
+
+ CRibbonImpl() : m_bRibbonUI(false), m_hgRibbonSettings(NULL)
+ {
+#ifdef _DEBUG
+ m_cRef = 1;
+#endif
+ pWndRibbon = static_cast<T*>(this);
+ HRESULT hr = ::CoInitialize(NULL);
+ if(SUCCEEDED(hr))
+ if (RunTimeHelper::IsRibbonUIAvailable())
+ hr = m_pIUIFramework.CoCreateInstance(CLSID_UIRibbonFramework);
+ else
+ ATLTRACE(L"Ribbon UI not available\n");
+
+ if FAILED(hr)
+ ATLTRACE(L"Ribbon construction failed\n");
+
+ ATLASSERT(SUCCEEDED(hr));
+ }
+
+ ~CRibbonImpl()
+ {
+ ::GlobalFree(m_hgRibbonSettings);
+ m_pIUIFramework.Release();
+ ::CoUninitialize();
+ }
+
+ ICtrl& GetRibbonCtrl(UINT)
+ {
+ return static_cast<ICtrl&>(*this);
+ }
+
+ ATL::CComPtr<IUIFramework> m_pIUIFramework;
+ HGLOBAL m_hgRibbonSettings;
+ bool m_bRibbonUI;
+
+ bool IsRibbonUI()
+ {
+ return m_bRibbonUI;
+ }
+
+ IUIFramework* GetIUIFrameworkPtr()
+ {
+ return m_pIUIFramework;
+ }
+
+ template <typename I>
+ I* GetRibbonViewPtr(UINT32 uID)
+ {
+ ATLASSERT(m_pIUIFramework);
+ ATL::CComPtr<I> pI;
+ return m_pIUIFramework->GetView(uID, __uuidof(I), (void**) &pI) == S_OK ?
+ pI :
+ NULL;
+ }
+
+ IUIRibbon* GetRibbonPtr()
+ {
+ return GetRibbonViewPtr<IUIRibbon>(0);
+ }
+
+ IUIContextualUI* GetMenuPtr(UINT32 uID)
+ {
+ ATLASSERT(uID);
+ return GetRibbonViewPtr<IUIContextualUI>(uID);
+ }
+
+ UINT GetRibbonHeight()
+ {
+ ATLASSERT(IsRibbonUI());
+
+ UINT32 cy = 0;
+ if (ATL::CComPtr<IUIRibbon> pIUIRibbon = GetRibbonPtr())
+ pIUIRibbon->GetHeight(&cy);
+ return cy;
+ }
+
+ HRESULT CreateRibbon(LPCWSTR sResName = L"APPLICATION_RIBBON")
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(GetIUIFrameworkPtr() && !IsRibbonUI());
+ ATLASSERT(pT->IsWindow());
+
+ HRESULT hr = m_pIUIFramework->Initialize(pT->m_hWnd, this);
+
+ if (hr == S_OK)
+ hr = m_pIUIFramework->LoadUI(ModuleHelper::GetResourceInstance(), sResName);
+
+ return hr;
+ }
+
+ HRESULT DestroyRibbon()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(GetIUIFrameworkPtr() && IsRibbonUI());
+ ATLASSERT(pT->IsWindow());
+
+ HRESULT hRes = m_pIUIFramework->Destroy();
+ if (!RunTimeHelper::IsWin7())
+ pT->SetWindowRgn(NULL, TRUE); // Vista Basic bug workaround
+ return hRes;
+ }
+
+// Ribbon persistency
+ HRESULT operator >>(IStream* pIStream)
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(pIStream);
+
+ HRESULT hr = E_FAIL;
+ if (ATL::CComPtr<IUIRibbon> pIUIRibbon = GetRibbonPtr())
+ {
+ const LARGE_INTEGER li0 = { 0 };
+ pIStream->Seek(li0, STREAM_SEEK_SET, NULL);
+ hr = pIUIRibbon->SaveSettingsToStream(pIStream);
+ pIStream->Commit(STGC_DEFAULT);
+ }
+
+ return hr;
+ }
+
+ HRESULT operator <<(IStream* pIStream)
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(pIStream);
+
+ HRESULT hr = E_FAIL;
+ if (ATL::CComPtr<IUIRibbon> pIUIRibbon = GetRibbonPtr())
+ {
+ const LARGE_INTEGER li0 = { 0 };
+ pIStream->Seek(li0, STREAM_SEEK_SET, NULL);
+ hr = pIUIRibbon->LoadSettingsFromStream(pIStream);
+ }
+
+ return hr;
+ }
+
+ void ResetRibbonSettings()
+ {
+ if (m_hgRibbonSettings != NULL)
+ {
+ ::GlobalFree(m_hgRibbonSettings);
+ m_hgRibbonSettings = NULL;
+ }
+ }
+
+ HRESULT SaveRibbonSettings()
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(static_cast<T*>(this)->IsWindow());
+
+ HRESULT hr = E_FAIL;
+ ATL::CComPtr<IStream> pIStream;
+
+ if SUCCEEDED(hr = ::CreateStreamOnHGlobal(m_hgRibbonSettings, FALSE, &pIStream))
+ hr = *this >> pIStream;
+
+ if (SUCCEEDED(hr) && (m_hgRibbonSettings == NULL))
+ hr = ::GetHGlobalFromStream(pIStream, &m_hgRibbonSettings);
+
+ if FAILED(hr)
+ ResetRibbonSettings();
+
+ return hr;
+ }
+
+ HRESULT RestoreRibbonSettings()
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(m_hgRibbonSettings);
+ ATLASSERT(static_cast<T*>(this)->IsWindow());
+
+ HRESULT hr = E_FAIL;
+ ATL::CComPtr<IStream> pIStream;
+
+ if SUCCEEDED(hr = ::CreateStreamOnHGlobal(m_hgRibbonSettings, FALSE, &pIStream))
+ hr = *this << pIStream;
+
+ if FAILED(hr)
+ ResetRibbonSettings();
+
+ return hr;
+ }
+
+// QAT dock states
+ UI_CONTROLDOCK GetQATDock()
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(IsRibbonUI());
+
+ UINT32 uDock = 0;
+ PROPVARIANT propvar;
+ ATL::CComQIPtr<IPropertyStore>pIPS(GetRibbonPtr());
+
+ if ((pIPS != NULL) && SUCCEEDED(pIPS->GetValue(UI_PKEY_QuickAccessToolbarDock, &propvar)) &&
+ SUCCEEDED(UIPropertyToUInt32(UI_PKEY_QuickAccessToolbarDock, propvar, &uDock)))
+ return (UI_CONTROLDOCK)uDock;
+
+ ATLASSERT(FALSE); // something was wrong
+ return (UI_CONTROLDOCK)0;
+ }
+
+ bool SetQATDock(UI_CONTROLDOCK dockState)
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(IsRibbonUI());
+
+ PROPVARIANT propvar;
+ ATLVERIFY(SUCCEEDED(SetPropertyVal(UI_PKEY_QuickAccessToolbarDock, dockState, &propvar)));
+
+ ATL::CComQIPtr<IPropertyStore>pIPS(GetRibbonPtr());
+ if ((pIPS != NULL) && SUCCEEDED(pIPS->SetValue(UI_PKEY_QuickAccessToolbarDock, propvar)))
+ {
+ pIPS->Commit();
+ return true;
+ }
+
+ ATLASSERT(FALSE); // something was wrong
+ return false;
+ }
+
+// Ribbon display states
+ bool GetRibbonDisplayState(REFPROPERTYKEY key)
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(IsRibbonUI());
+ ATLASSERT((k_(key) == k_Viewable) || (k_(key) == k_Minimized));
+
+ PROPVARIANT propvar;
+ ATL::CComQIPtr<IPropertyStore>pIPS(GetRibbonPtr());
+
+ if ((pIPS != NULL) && SUCCEEDED(pIPS->GetValue(key, &propvar)))
+ {
+ BOOL bState = FALSE;
+ if SUCCEEDED(UIPropertyToBoolean(key, propvar, &bState))
+ return (bState != FALSE);
+ }
+
+ ATLASSERT(FALSE); // something was wrong
+ return false;
+ }
+
+ bool SetRibbonDisplayState(REFPROPERTYKEY key, bool bState = true)
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(IsRibbonUI());
+ ATLASSERT((k_(key) == k_Viewable) || (k_(key) == k_Minimized));
+
+ PROPVARIANT propvar;
+ ATLVERIFY(SUCCEEDED(SetPropertyVal(key, bState, &propvar)));
+
+ ATL::CComQIPtr<IPropertyStore>pIPS(GetRibbonPtr());
+
+ if ((pIPS != NULL) && SUCCEEDED(pIPS->SetValue(key, propvar)))
+ {
+ pIPS->Commit();
+ return true;
+ }
+
+ ATLASSERT(FALSE); // something was wrong
+ return false;
+ }
+
+ bool IsRibbonMinimized()
+ {
+ return GetRibbonDisplayState(UI_PKEY_Minimized);
+ }
+
+ bool MinimizeRibbon(bool bMinimize = true)
+ {
+ return SetRibbonDisplayState(UI_PKEY_Minimized, bMinimize);
+ }
+
+ bool IsRibbonHidden()
+ {
+ return !GetRibbonDisplayState(UI_PKEY_Viewable);
+ }
+
+ bool HideRibbon(bool bHide = true)
+ {
+ return SetRibbonDisplayState(UI_PKEY_Viewable, !bHide);
+ }
+
+// Ribbon colors
+ UI_HSBCOLOR GetRibbonColor(REFPROPERTYKEY key)
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(IsRibbonUI());
+ ATLASSERT((k_(key) >= k_GlobalBackgroundColor) && (k_(key) <= k_GlobalTextColor));
+
+ PROPVARIANT propvar;
+ ATL::CComQIPtr<IPropertyStore>pIPS(GetIUIFrameworkPtr());
+
+ if ((pIPS != NULL) && SUCCEEDED(pIPS->GetValue(key, &propvar)))
+ {
+ UINT32 color = 0;
+ if SUCCEEDED(UIPropertyToUInt32(key, propvar, &color))
+ return color;
+ }
+
+ ATLASSERT(FALSE); // something was wrong
+ return 0;
+ }
+
+ bool SetRibbonColor(REFPROPERTYKEY key, UI_HSBCOLOR color)
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+ ATLASSERT(IsRibbonUI());
+ ATLASSERT((k_(key) >= k_GlobalBackgroundColor) && (k_(key) <= k_GlobalTextColor));
+
+ PROPVARIANT propvar;
+ ATLVERIFY(SUCCEEDED(SetPropertyVal(key, color, &propvar)));
+
+ ATL::CComQIPtr<IPropertyStore>pIPS(GetIUIFrameworkPtr());
+
+ if ((pIPS != NULL) && SUCCEEDED(pIPS->SetValue(key, propvar)))
+ {
+ pIPS->Commit();
+ return true;
+ }
+
+ ATLASSERT(FALSE); // something was wrong
+ return false;
+ }
+
+// Ribbon modes
+ HRESULT SetRibbonModes(INT32 iModes)
+ {
+ ATLASSERT(IsRibbonUI());
+ return GetIUIFrameworkPtr()->SetModes(iModes);
+ }
+
+// Ribbon contextual tab
+ UI_CONTEXTAVAILABILITY GetRibbonContextAvail(UINT32 uID)
+ {
+ ATLASSERT(GetIUIFrameworkPtr());
+
+ PROPVARIANT propvar;
+ if (IsRibbonUI() &&
+ SUCCEEDED(GetIUIFrameworkPtr()->GetUICommandProperty(uID, UI_PKEY_ContextAvailable, &propvar)))
+ {
+ UINT uav;
+ if (SUCCEEDED(PropVariantToUInt32(propvar, &uav)))
+ {
+ CUpdateUIBase::UIEnable(uID, uav != UI_CONTEXTAVAILABILITY_NOTAVAILABLE);
+ CUpdateUIBase::UISetCheck(uID, uav == UI_CONTEXTAVAILABILITY_ACTIVE);
+ return (UI_CONTEXTAVAILABILITY)uav;
+ }
+ }
+
+ return UI_CONTEXTAVAILABILITY_NOTAVAILABLE;
+ }
+
+ HRESULT SetRibbonContextAvail(UINT32 uID, UI_CONTEXTAVAILABILITY cav)
+ {
+ CUpdateUIBase::UIEnable(uID, cav != UI_CONTEXTAVAILABILITY_NOTAVAILABLE);
+ CUpdateUIBase::UISetCheck(uID, cav == UI_CONTEXTAVAILABILITY_ACTIVE);
+
+ return SetProperty((WORD)uID, UI_PKEY_ContextAvailable, UINT32(cav));
+ }
+
+// Ribbon context menu
+ bool HasRibbonMenu(UINT32 uID)
+ {
+ ATL::CComPtr<IUIContextualUI> pI = GetMenuPtr(uID);
+ return pI != NULL;
+ }
+
+ HRESULT TrackRibbonMenu(UINT32 uID, INT32 x, INT32 y)
+ {
+ ATLASSERT(HasRibbonMenu(uID));
+
+ return IsRibbonUI() ?
+ ATL::CComPtr<IUIContextualUI>(GetMenuPtr(uID))->ShowAtLocation(x, y) :
+ E_FAIL;
+ }
+
+ HRESULT TrackRibbonMenu(UINT32 uID, LPARAM lParam)
+ {
+ return TrackRibbonMenu(uID, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam));
+ }
+
+// Overrideables
+ HBITMAP OnRibbonQueryImage(UINT nCmdID, REFPROPERTYKEY /*key*/)
+ {
+ return DefRibbonQueryImage(nCmdID);
+ }
+
+ LPCWSTR OnRibbonQueryText(UINT nCmdID, REFPROPERTYKEY key)
+ {
+ return DefRibbonQueryText(nCmdID, key);
+ }
+
+ bool OnRibbonQueryState(UINT nCmdID, REFPROPERTYKEY key)
+ {
+ return DefRibbonQueryState(nCmdID, key);
+ }
+
+ UI_CONTEXTAVAILABILITY OnRibbonQueryTabAvail(UINT nCmdID)
+ {
+ DWORD dwState = UIGetState(nCmdID);
+ return ((dwState & UPDUI_DISABLED) == UPDUI_DISABLED) ?
+ UI_CONTEXTAVAILABILITY_NOTAVAILABLE :
+ (((dwState & UPDUI_CHECKED) == UPDUI_CHECKED) ?
+ UI_CONTEXTAVAILABILITY_ACTIVE :
+ UI_CONTEXTAVAILABILITY_AVAILABLE);
+ }
+
+ LPCWSTR OnRibbonQueryComboText(UINT32 /*uCtrlID*/)
+ {
+ return NULL;
+ }
+
+ LPCWSTR OnRibbonQueryCategoryText(UINT32 /*uCtrlID*/, UINT32 /*uCat*/)
+ {
+ return L"Category";
+ }
+
+ UINT32 OnRibbonQueryItemCategory(UINT32 /*uCtrlID*/, UINT32 /*uItem*/)
+ {
+ return 0;
+ }
+
+ LPCWSTR OnRibbonQueryItemText(UINT32 uCtrlID, UINT32 uItem)
+ {
+ return DefRibbonQueryItemText(uCtrlID, uItem);
+ }
+
+ bool OnRibbonQuerySelectedItem(UINT32 /*uCtrlID*/, UINT32& /*uSel*/)
+ {
+ return false;
+ }
+
+ HBITMAP OnRibbonQueryItemImage(UINT32 uCtrlID, UINT32 uItem)
+ {
+ return DefRibbonQueryItemImage(uCtrlID, uItem);
+ }
+
+ UINT32 OnRibbonQueryItemCommand(UINT32 uCtrlID, UINT32 uItem)
+ {
+ return DefRibbonQueryItemCommand(uCtrlID, uItem);
+ }
+
+ UI_COMMANDTYPE OnRibbonQueryItemCommandType(UINT32 /*uCtrlID*/, UINT32 /*uItem*/)
+ {
+ return UI_COMMANDTYPE_ACTION;
+ }
+
+ LPCWSTR OnRibbonQueryRecentItemName(LPCWSTR sPath)
+ {
+ return ::PathFindFileName(sPath);
+ }
+
+ bool OnRibbonQueryFont(UINT /*nId*/, CHARFORMAT2& /*cf*/)
+ {
+ return false;
+ }
+
+ bool OnRibbonQuerySpinnerValue(UINT /*nCmdID*/, REFPROPERTYKEY /*key*/, LONG* /*pVal*/)
+ {
+ return false;
+ }
+
+ bool OnRibbonQueryFloatSpinnerValue(UINT /*nCmdID*/, REFPROPERTYKEY /*key*/, DOUBLE* /*pVal*/)
+ {
+ return false;
+ }
+
+ COLORREF OnRibbonQueryColor(UINT /*nCmdID*/)
+ {
+ return 0x800080; /*MAGENTA*/
+ }
+
+ LPCWSTR OnRibbonQueryColorLabel(UINT /*nCmdID*/, REFPROPERTYKEY /*key*/)
+ {
+ return NULL;
+ }
+
+ COLORREF* OnRibbonQueryColorArray(UINT /*nCmdID*/, REFPROPERTYKEY /*key*/)
+ {
+ return NULL;
+ }
+
+ LPCWSTR* OnRibbonQueryColorTooltips(UINT /*nCmdID*/, REFPROPERTYKEY /*key*/)
+ {
+ return NULL;
+ }
+
+ bool OnRibbonItemSelected(UINT32 uCtrlID, UI_EXECUTIONVERB verb, UINT32 uItem)
+ {
+ DefCommandExecute(MAKELONG(uCtrlID, verb), uItem);
+ return true;
+ }
+
+ void OnRibbonColorCtrlExecute(UINT32 uCtrlID, UI_EXECUTIONVERB verb, UI_SWATCHCOLORTYPE uType, COLORREF color)
+ {
+ DefRibbonColorCtrlExecute(uCtrlID, verb, uType, color);
+ }
+
+ void OnRibbonFontCtrlExecute(UINT32 uCtrlID, UI_EXECUTIONVERB verb, CHARFORMAT2* pcf)
+ {
+ DefCommandExecute(MAKELONG(uCtrlID, verb), (LPARAM)pcf);
+ }
+
+ void OnRibbonSpinnerCtrlExecute(UINT32 uCtrlID, LONG* pVal)
+ {
+ DefCommandExecute(uCtrlID, *pVal);
+ }
+
+ void OnRibbonSpinnerCtrlExecute(UINT32 uCtrlID, DOUBLE* pVal)
+ {
+ DefCommandExecute(uCtrlID, (LPARAM)pVal);
+ }
+
+ void OnRibbonCommandExecute(UINT32 uCmdID)
+ {
+ DefCommandExecute(uCmdID);
+ }
+
+// Default implementations
+ HBITMAP DefRibbonQueryImage(UINT nCmdID)
+ {
+ return AtlLoadBitmapImage(nCmdID, LR_CREATEDIBSECTION);
+ }
+
+ bool DefRibbonQueryState(UINT nCmdID, REFPROPERTYKEY key)
+ {
+ DWORD dwState = UIGetState(nCmdID);
+ bool bRet = false;
+ switch (k_(key))
+ {
+ case k_BooleanValue:
+ bRet = (dwState & UPDUI_CHECKED) == UPDUI_CHECKED;
+ break;
+ case k_Enabled:
+ bRet = (dwState & UPDUI_DISABLED) != UPDUI_DISABLED;
+ break;
+ default:
+ ATLASSERT(FALSE);
+ break;
+ }
+
+ return bRet;
+ }
+
+ LPCTSTR DefRibbonQueryText(UINT nCmdID, REFPROPERTYKEY key)
+ {
+ static WCHAR sText[RIBBONUI_MAX_TEXT] = { 0 };
+
+ if (k_(key) == k_Label)
+ return UIGetText(nCmdID);
+
+ if (AtlLoadString(nCmdID, sText, RIBBONUI_MAX_TEXT))
+ {
+ PWCHAR pTitle = wcschr(sText, L'\n');
+ switch (k_(key))
+ {
+ case k_Keytip:
+ if (PWCHAR pAmp = wcschr(sText, L'&'))
+ pTitle = pAmp;
+ if (pTitle != NULL)
+ *(pTitle + 2) = NULL; // fall through
+ case k_TooltipTitle:
+ return pTitle ? ++pTitle : NULL;
+ case k_TooltipDescription:
+ case k_LabelDescription:
+ if (pTitle != NULL)
+ *pTitle = NULL;
+ return sText;
+ }
+ }
+
+ return NULL;
+ }
+
+ LPCWSTR DefRibbonQueryItemText(UINT32 uCtrlID, UINT32 uItem)
+ {
+ return DefRibbonQueryText(uCtrlID + 1 + uItem, UI_PKEY_LabelDescription);
+ }
+
+ HBITMAP DefRibbonQueryItemImage(UINT32 uCtrlID, UINT32 uItem)
+ {
+ return DefRibbonQueryImage(uCtrlID + 1 + uItem);
+ }
+
+ UINT32 DefRibbonQueryItemCommand(UINT32 uCtrlID, UINT32 uItem)
+ {
+ return uCtrlID + 1 + uItem;
+ }
+
+ void DefRibbonColorCtrlExecute(UINT32 uCtrlID, UI_EXECUTIONVERB verb, UI_SWATCHCOLORTYPE uType, COLORREF color)
+ {
+ switch(uType)
+ {
+ case UI_SWATCHCOLORTYPE_RGB:
+ break;
+ case UI_SWATCHCOLORTYPE_AUTOMATIC:
+ color = ::GetSysColor(COLOR_WINDOWTEXT);
+ break;
+ case UI_SWATCHCOLORTYPE_NOCOLOR:
+ color = ::GetSysColor(COLOR_WINDOW);
+ break;
+ default:
+ ATLASSERT(FALSE);
+ break;
+ }
+
+ DefCommandExecute(MAKELONG(uCtrlID, verb), color);
+ }
+
+ void DefCommandExecute(UINT32 uCmd, LPARAM lParam = 0)
+ {
+ static_cast<T*>(this)->PostMessage(WM_COMMAND, uCmd, lParam);
+ }
+
+// Elements setting helpers
+ HRESULT InvalidateCtrl(UINT32 nID)
+ {
+ return IsRibbonUI() ?
+ GetIUIFrameworkPtr()->InvalidateUICommand(nID, UI_INVALIDATIONS_ALLPROPERTIES, NULL) :
+ E_FAIL;
+ }
+
+ HRESULT InvalidateProperty(UINT32 nID, REFPROPERTYKEY key, UI_INVALIDATIONS flags = UI_INVALIDATIONS_PROPERTY)
+ {
+ return IsRibbonUI() ?
+ GetIUIFrameworkPtr()->InvalidateUICommand(nID, flags, &key) :
+ E_FAIL;
+ }
+
+ template <typename V>
+ HRESULT SetProperty(WORD wID, REFPROPERTYKEY key, V val)
+ {
+ if (IsRibbonUI())
+ {
+ PROPVARIANT var;
+ if (SUCCEEDED(RibbonUI::SetPropertyVal(key, val, &var)))
+ {
+ return SetProperty(wID, key, var);
+ }
+ return E_INVALIDARG;
+ }
+ else
+ {
+ return E_FAIL;
+ }
+ }
+
+ template <>
+ HRESULT SetProperty(WORD nID, REFPROPERTYKEY key, PROPVARIANT var)
+ {
+ return IsRibbonUI() ?
+ GetIUIFrameworkPtr()->SetUICommandProperty(nID, key, var) :
+ E_FAIL;
+ }
+
+// Interfaces
+ // IUIApplication
+ STDMETHODIMP OnViewChanged(UINT32, UI_VIEWTYPE, IUnknown*, UI_VIEWVERB verb, INT32)
+ {
+ switch (verb)
+ {
+ case UI_VIEWVERB_CREATE:
+ m_bRibbonUI = true;
+ if (m_hgRibbonSettings != NULL)
+ RestoreRibbonSettings();
+ break;
+ case UI_VIEWVERB_SIZE:
+ static_cast<T*>(this)->UpdateLayout(FALSE);
+ break;
+ case UI_VIEWVERB_DESTROY:
+ SaveRibbonSettings();
+ m_bRibbonUI = false;
+ break;
+ }
+
+ return S_OK;
+ }
+
+ STDMETHODIMP OnCreateUICommand(UINT32 nCmdID, UI_COMMANDTYPE typeID, IUICommandHandler** ppCommandHandler)
+ {
+ UIAddRibbonElement(nCmdID);
+ if (typeID == UI_COMMANDTYPE_CONTEXT)
+ CUpdateUIBase::UIEnable(nCmdID, false);
+ *ppCommandHandler = this;
+ return S_OK;
+ }
+
+ STDMETHODIMP OnDestroyUICommand(UINT32 nCmdID, UI_COMMANDTYPE, IUICommandHandler*)
+ {
+ UIRemoveRibbonElement(nCmdID);
+ return S_OK;
+ }
+
+ // IUICommandHandler
+ STDMETHODIMP Execute(UINT nCmdID,
+ UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key,
+ const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* pCommandExecutionProperties)
+ {
+ T* pT =static_cast<T*>(this);
+ return pT->GetRibbonCtrl(nCmdID).DoExecute(nCmdID, verb, key, ppropvarValue, pCommandExecutionProperties);
+ }
+
+ STDMETHODIMP UpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* ppropvarCurrentValue, PROPVARIANT* ppropvarNewValue)
+ {
+ T* pT =static_cast<T*>(this);
+ return pT->GetRibbonCtrl(nCmdID).DoUpdateProperty(nCmdID, key, ppropvarCurrentValue, ppropvarNewValue);
+ }
+
+#ifdef _DEBUG
+ // IUnknown methods (heavyweight)
+ STDMETHODIMP_(ULONG) AddRef()
+ {
+ return InterlockedIncrement(&m_cRef);
+ }
+
+ STDMETHODIMP_(ULONG) Release()
+ {
+ LONG cRef = InterlockedDecrement(&m_cRef);
+ if (cRef == 0) // NoOp for breakpoint
+ {
+ cRef = 0;
+ }
+
+ return cRef;
+ }
+
+ STDMETHODIMP QueryInterface(REFIID iid, void** ppv)
+ {
+ if (ppv == NULL)
+ {
+ return E_POINTER;
+ }
+ else if ((iid == __uuidof(IUnknown)) ||
+ (iid == __uuidof(IUICommandHandler)) ||
+ (iid == __uuidof(IUIApplication)))
+ {
+ *ppv = this;
+ AddRef();
+ return S_OK;
+ }
+ else
+ {
+ return E_NOINTERFACE;
+ }
+ }
+
+ LONG m_cRef;
+#else
+ // IUnknown methods (lightweight)
+ STDMETHODIMP QueryInterface(REFIID iid, void** ppv)
+ {
+ if ((iid == __uuidof(IUnknown)) ||
+ (iid == __uuidof(IUICommandHandler)) ||
+ (iid == __uuidof(IUIApplication)))
+ {
+ *ppv = this;
+ return S_OK;
+ }
+ return E_NOINTERFACE;
+ }
+ ULONG STDMETHODCALLTYPE AddRef()
+ {
+ return 1;
+ }
+ ULONG STDMETHODCALLTYPE Release()
+ {
+ return 1;
+ }
+#endif
+
+// CRibbonImpl ICtrl implementation
+ virtual HRESULT DoExecute(UINT nCmdID, UI_EXECUTIONVERB verb,
+ const PROPERTYKEY* key, const PROPVARIANT* ppropvarValue,
+ IUISimplePropertySet* /*pCommandExecutionProperties*/)
+ {
+ if (key != NULL)
+ {
+ if(k_(*key) != k_BooleanValue)
+ {
+ ATLTRACE(L"Control ID %d is not handled\n", nCmdID);
+ return E_NOTIMPL;
+ }
+ BOOL bChecked = FALSE;
+ ATLVERIFY(SUCCEEDED(PropVariantToBoolean(*ppropvarValue, &bChecked)));
+ CUpdateUIBase::UISetCheck(nCmdID, bChecked);
+ }
+
+ ATLASSERT(verb == UI_EXECUTIONVERB_EXECUTE);
+ verb; // avoid level 4 warning
+
+ static_cast<T*>(this)->OnRibbonCommandExecute(nCmdID);
+
+ return S_OK;
+ }
+
+ virtual HRESULT DoUpdateProperty(UINT nCmdID, REFPROPERTYKEY key,
+ const PROPVARIANT* /*ppropvarCurrentValue*/, PROPVARIANT* ppropvarNewValue)
+ {
+ T* pT = static_cast<T*>(this);
+ HRESULT hr = E_NOTIMPL;
+ switch (k_(key))
+ {
+ case k_LargeImage:
+ case k_LargeHighContrastImage:
+ case k_SmallImage:
+ case k_SmallHighContrastImage:
+ if (HBITMAP hbm = pT->OnRibbonQueryImage(nCmdID, key))
+ hr = SetPropertyVal(key, GetImage(hbm, UI_OWNERSHIP_TRANSFER), ppropvarNewValue);
+ break;
+ case k_Label:
+ case k_Keytip:
+ case k_TooltipTitle:
+ case k_TooltipDescription:
+ case k_LabelDescription:
+ if (LPCWSTR sText = pT->OnRibbonQueryText(nCmdID, key))
+ hr = SetPropertyVal(key, sText, ppropvarNewValue);
+ break;
+ case k_BooleanValue:
+ case k_Enabled:
+ hr = SetPropertyVal(key, pT->OnRibbonQueryState(nCmdID, key), ppropvarNewValue);
+ break;
+ case k_ContextAvailable:
+ hr = SetPropertyVal(key, pT->OnRibbonQueryTabAvail(nCmdID), ppropvarNewValue);
+ break;
+ }
+
+ return hr;
+ }
+
+// CRibbonImpl::CRibbonXXXCtrl specialized classes
+ //CRibbonComboCtrl
+ template <UINT t_ID, size_t t_items, size_t t_categories = 0>
+ class CRibbonComboCtrl : public CollectionCtrlImpl<T, t_ID, ComboCollectionImpl<CRibbonComboCtrl<t_ID, t_items, t_categories>, t_items, t_categories>>
+ {
+ public:
+ CRibbonComboCtrl()
+ { }
+ };
+
+ // CRibbonItemGalleryCtrl
+ template <UINT t_ID, size_t t_items, size_t t_categories = 0>
+ class CRibbonItemGalleryCtrl : public CollectionCtrlImpl<T, t_ID, ItemCollectionImpl<CRibbonItemGalleryCtrl<t_ID, t_items, t_categories>, t_items, t_categories>>
+ {
+ public:
+ CRibbonItemGalleryCtrl()
+ { }
+ };
+
+ // CRibbonCommandGalleryCtrl
+ template <UINT t_ID, size_t t_items, size_t t_categories = 0>
+ class CRibbonCommandGalleryCtrl : public CollectionCtrlImpl<T, t_ID, CommandCollectionImpl<CRibbonCommandGalleryCtrl<t_ID, t_items, t_categories>, t_items, t_categories>>
+ {
+ public:
+ CRibbonCommandGalleryCtrl()
+ { }
+ };
+
+ // CRibbonToolbarGalleryCtrl
+ template <UINT t_ID, UINT t_idTB, size_t t_size>
+ class CRibbonToolbarGalleryCtrl : public ToolbarGalleryCtrlImpl<T, t_ID, t_idTB, t_size>
+ { };
+
+ // CRibbonSimpleComboCtrl
+ template <UINT t_ID, size_t t_size>
+ class CRibbonSimpleComboCtrl : public SimpleCollectionCtrlImpl<T, t_ID, t_size>
+ { };
+
+ // CRibbonSimpleGalleryCtrl
+ template <UINT t_ID, size_t t_size, UI_COMMANDTYPE t_CommandType = UI_COMMANDTYPE_ACTION>
+ class CRibbonSimpleGalleryCtrl : public SimpleCollectionCtrlImpl<T, t_ID, t_size, t_CommandType>
+ { };
+
+ //CRibbonRecentItemsCtrl
+ template <UINT t_ID, class TDocList = CRecentDocumentList>
+ class CRibbonRecentItemsCtrl : public RecentItemsCtrlImpl<T, t_ID, TDocList>
+ {
+ public:
+ CRibbonRecentItemsCtrl()
+ { }
+ };
+
+ // CRibbonColorCtrl
+ template <UINT t_ID>
+ class CRibbonColorCtrl : public ColorCtrlImpl<T, t_ID>
+ {
+ public:
+ CRibbonColorCtrl()
+ { }
+ };
+
+ //CRibbonFontCtrl
+ template <UINT t_ID>
+ class CRibbonFontCtrl : public FontCtrlImpl<T, t_ID>
+ {
+ public:
+ CRibbonFontCtrl()
+ { }
+ };
+
+ // CRibbonSpinnerCtrl
+ template <UINT t_ID>
+ class CRibbonSpinnerCtrl : public SpinnerCtrlImpl<T, t_ID, LONG>
+ {
+ public:
+ CRibbonSpinnerCtrl()
+ { }
+ };
+
+ // CRibbonFloatSpinnerCtrl
+ template <UINT t_ID>
+ class CRibbonFloatSpinnerCtrl : public SpinnerCtrlImpl<T, t_ID, DOUBLE>
+ {
+ public:
+ CRibbonFloatSpinnerCtrl()
+ {
+ m_Values[4] = 1; // 1 decimal
+ }
+ };
+
+ // CRibbonCommandCtrl
+ template <UINT t_ID>
+ class CRibbonCommandCtrl : public CommandCtrlImpl<T, t_ID>
+ {
+ public:
+ CRibbonCommandCtrl()
+ { }
+ };
+
+// Control classes access to T instance (re-initialized in constructor)
+ static T* pWndRibbon;
+};
+
+template <class T>
+__declspec(selectany) T* CRibbonImpl<T>::pWndRibbon;
+
+// Control map element
+#pragma warning (disable : 4510 610) // missing default constructor
+typedef struct
+{
+ UINT uID;
+ ICtrl& ctrl;
+} _ribbonCtrl;
+#pragma warning (default : 4510 610) // missing default constructor
+
+}; // namespace RibbonUI
+
+
+///////////////////////////////////////////////////////////////////////////////
+// RibbonUI Control map
+
+// Control map macros
+#define BEGIN_RIBBON_CONTROL_MAP(theClass) \
+ RibbonUI::ICtrl& GetRibbonCtrl(UINT id) \
+ { \
+ RibbonUI::_ribbonCtrl _ctrls[] = \
+ {
+
+#define RIBBON_CONTROL(member) {member.GetID(), static_cast<RibbonUI::ICtrl&>(member)},
+
+#define END_RIBBON_CONTROL_MAP() \
+ {0, *this} \
+ }; \
+ int i = 0; \
+ for(; i < _countof(_ctrls) - 1; i++) \
+ if (_ctrls[i].uID == id) \
+ break; \
+ return _ctrls[i].ctrl; \
+}
+
+// Control message map macros
+#define RIBBON_GALLERY_CONTROL_HANDLER(id, func) \
+ if(uMsg == WM_COMMAND && id == LOWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((UI_EXECUTIONVERB)HIWORD(wParam), LOWORD(wParam), (UINT)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define RIBBON_COMBO_CONTROL_HANDLER(id, func) \
+ RIBBON_GALLERY_CONTROL_HANDLER(id, func)
+
+#define RIBBON_FONT_CONTROL_HANDLER(id, func) \
+ if(uMsg == WM_COMMAND && id == LOWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((UI_EXECUTIONVERB)HIWORD(wParam), LOWORD(wParam), (CHARFORMAT2*)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define RIBBON_COLOR_CONTROL_HANDLER(id, func) \
+ if(uMsg == WM_COMMAND && id == LOWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((UI_EXECUTIONVERB)HIWORD(wParam), LOWORD(wParam), (COLORREF)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define RIBBON_SPINNER_CONTROL_HANDLER(id, func) \
+ if(uMsg == WM_COMMAND && id == wParam) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((WORD)wParam, (LONG)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define RIBBON_FLOATSPINNER_CONTROL_HANDLER(id, func) \
+ if(uMsg == WM_COMMAND && id == wParam) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((WORD)wParam, (DOUBLE*)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+// Handler prototypes
+/*
+ LRESULT OnRibbonGalleryCtrl(UI_EXECUTIONVERB verb, WORD wID, UINT uSel, BOOL& bHandled);
+ LRESULT OnRibbonComboCtrl(UI_EXECUTIONVERB verb, WORD wID, UINT uSel, BOOL& bHandled);
+ LRESULT OnRibbonFontCtrl(UI_EXECUTIONVERB verb, WORD wID, CHARFORMAT2* pcf, BOOL& bHandled);
+ LRESULT OnRibbonColorCtrl(UI_EXECUTIONVERB verb, WORD wID, COLORREF color, BOOL& bHandled);
+ LRESULT OnRibbonSpinnerCtrl(WORD wID, LONG lVal, BOOL& bHandled);
+ LRESULT OnRibbonFloatSpinnerCtrl(WORD wID, DOUBLE* pdVal, BOOL& bHandled);
+*/
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Ribbon frame classes
+
+// CRibbonFrameWindowImplBase
+//
+template <class T, class TFrameImpl>
+class ATL_NO_VTABLE CRibbonFrameWindowImplBase : public TFrameImpl, public RibbonUI::CRibbonImpl<T>
+{
+ typedef TFrameImpl baseFrame;
+ bool m_bUseCommandBarBitmaps;
+ bool m_bWin7Fix;
+
+public:
+// Construction
+ CRibbonFrameWindowImplBase(bool bUseCommandBarBitmaps = true) :
+ m_bUseCommandBarBitmaps(bUseCommandBarBitmaps), m_bWin7Fix(false)
+ {
+ __if_not_exists(T::m_CmdBar)
+ {
+ m_bUseCommandBarBitmaps = false;
+ }
+ }
+
+// Win7 Aero fix helpers
+ void ResetFrame()
+ {
+ const MARGINS margins = { 0 };
+ ::DwmExtendFrameIntoClientArea(m_hWnd, &margins);
+ }
+
+ INT CalcWin7Fix()
+ {
+ ResetFrame();
+ RECT rc = { 0 };
+ ::AdjustWindowRectEx(&rc, T::GetWndStyle(0), GetMenu() != NULL, T::GetWndExStyle(0));
+ return -rc.top;
+ }
+
+ bool NeedWin7Fix()
+ {
+ BOOL bComp = FALSE;
+ return m_bWin7Fix && RunTimeHelper::IsWin7() && SUCCEEDED(DwmIsCompositionEnabled(&bComp)) && bComp;
+ }
+
+// Operations
+ bool UseCommandBarBitmaps(bool bUse)
+ {
+ __if_exists(T::m_CmdBar)
+ {
+ return m_bUseCommandBarBitmaps = bUse;
+ }
+ __if_not_exists(T::m_CmdBar)
+ {
+ bUse; // avoid level 4 warning
+ return false;
+ }
+ }
+
+ bool ShowRibbonUI(bool bShow, INT32 imodes = UI_MAKEAPPMODE(0), LPCWSTR sResName = L"APPLICATION_RIBBON")
+ {
+ if (!RunTimeHelper::IsRibbonUIAvailable())
+ return false;
+
+ ATLASSERT(GetIUIFrameworkPtr());
+
+ if (IsRibbonUI() == bShow)
+ return bShow;
+
+ bool bVisible = (IsWindowVisible() != FALSE);
+ if(bVisible && !bShow)
+ SetRedraw(FALSE);
+
+ if (bShow && ::IsWindow(m_hWndToolBar))
+ {
+ ::ShowWindow(m_hWndToolBar, SW_HIDE);
+ UpdateLayout();
+ }
+
+ m_bWin7Fix = !bShow;
+
+ HRESULT hr = bShow ? CreateRibbon(sResName) : DestroyRibbon();
+
+ m_bWin7Fix = SUCCEEDED(hr) && !bShow;
+
+ if (SUCCEEDED(hr))
+ {
+ if(::IsWindow(m_hWndToolBar) && !bShow)
+ {
+ ::ShowWindow(m_hWndToolBar, SW_SHOWNA);
+ UpdateLayout();
+ }
+ else if (bShow)
+ {
+ PostMessage(WM_SIZE);
+ SetRibbonModes(imodes);
+ }
+ }
+
+ if(bVisible && !bShow)
+ {
+ SetRedraw(TRUE);
+ RedrawWindow(NULL, NULL, RDW_FRAME | RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN);
+ }
+
+ return SUCCEEDED(hr) ? bShow : !bShow;
+ }
+
+// Overrideables
+ HBITMAP OnRibbonQueryImage(UINT nCmdID, REFPROPERTYKEY key)
+ {
+ if ((key == UI_PKEY_SmallImage) && m_bUseCommandBarBitmaps)
+ {
+ if (HBITMAP hbm = GetCommandBarBitmap(nCmdID))
+ return (HBITMAP)::CopyImage(hbm, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);
+ }
+
+ return DefRibbonQueryImage(nCmdID);
+ }
+
+ BEGIN_MSG_MAP(CRibbonFrameWindowImplBase)
+ if (!IsRibbonUI() && NeedWin7Fix())
+ {
+ MESSAGE_HANDLER(WM_SIZING, OnSizing)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ MESSAGE_HANDLER(WM_ACTIVATE, OnActivate)
+ MESSAGE_HANDLER(WM_NCCALCSIZE, OnNCCalcSize)
+ }
+ CHAIN_MSG_MAP(CRibbonUpdateUI<T>)
+ CHAIN_MSG_MAP(baseFrame)
+ END_MSG_MAP()
+
+// Message handlers for Win7 Aero
+ LRESULT OnSizing(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ switch (wParam)
+ {
+ case WMSZ_TOP:
+ case WMSZ_TOPLEFT:
+ case WMSZ_TOPRIGHT:
+ SetWindowPos(NULL, (LPRECT)lParam, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
+ break;
+ default:
+ DefWindowProc();
+ break;
+ }
+
+ return 1; // handled
+ }
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if (wParam != SIZE_MINIMIZED)
+ SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(wParam != WA_INACTIVE)
+ SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED);
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnNCCalcSize(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ ATLASSERT(!IsRibbonUI() && NeedWin7Fix());
+
+ LRESULT lRet = DefWindowProc();
+
+ if(wParam)
+ {
+ LPNCCALCSIZE_PARAMS pParams = (LPNCCALCSIZE_PARAMS)lParam;
+ pParams->rgrc[0].top = pParams->rgrc[1].top + CalcWin7Fix();
+ }
+
+ return lRet;
+ }
+
+// Overrides
+ void UpdateLayout(BOOL bResizeBars = TRUE)
+ {
+ RECT rect = { 0 };
+ GetClientRect(&rect);
+
+ if (IsRibbonUI() && !IsRibbonHidden())
+ {
+ rect.top += GetRibbonHeight();
+ }
+ else if (!IsRibbonUI() && NeedWin7Fix())
+ {
+ ResetFrame();
+ }
+
+ // position bars and offset their dimensions
+ UpdateBarsPosition(rect, bResizeBars);
+
+ // resize client window
+ if(m_hWndClient != NULL)
+ ::SetWindowPos(m_hWndClient, NULL, rect.left, rect.top,
+ rect.right - rect.left, rect.bottom - rect.top,
+ SWP_NOZORDER | SWP_NOACTIVATE);
+ }
+
+ // Implementation
+ HBITMAP GetCommandBarBitmap(UINT nCmdID)
+ {
+ __if_exists (T::m_CmdBar)
+ {
+ ATLASSERT(RunTimeHelper::IsVista());
+ T* pT =static_cast<T*>(this);
+ int nIndex = pT->m_CmdBar.m_arrCommand.Find((WORD&)nCmdID);
+ return (nIndex == -1) ? NULL : pT->m_CmdBar.m_arrVistaBitmap[nIndex];
+ }
+ __if_not_exists (T::m_CmdBar)
+ {
+ nCmdID; // avoid level 4 warning
+ return NULL;
+ }
+ }
+};
+
+// CRibbonFrameWindowImpl
+//
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CFrameWinTraits>
+class ATL_NO_VTABLE CRibbonFrameWindowImpl : public CRibbonFrameWindowImplBase<T, CFrameWindowImpl<T, TBase, TWinTraits>>
+{ };
+
+// CRibbonMDIFrameWindowImpl
+//
+template <class T, class TBase = CMDIWindow, class TWinTraits = ATL::CFrameWinTraits>
+class ATL_NO_VTABLE CRibbonMDIFrameWindowImpl : public CRibbonFrameWindowImplBase<T, CMDIFrameWindowImpl<T, TBase, TWinTraits>>
+{ };
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CRibbonPersist helper for RibbonUI persistency
+
+class CRibbonPersist
+{
+public:
+ CRibbonPersist(LPCWSTR sAppKey)
+ {
+ ATLASSERT(sAppKey && *sAppKey);
+ m_Key.Create(HKEY_CURRENT_USER, sAppKey);
+ ATLASSERT(m_Key.m_hKey);
+ }
+
+ CRegKeyEx m_Key;
+
+ LONG Save(bool bRibbonUI, HGLOBAL hgSettings = NULL)
+ {
+ CRegKeyEx key;
+ const DWORD dwUI = bRibbonUI;
+
+ LONG lRet = key.Create(m_Key, L"Ribbon");
+ if(lRet != ERROR_SUCCESS)
+ return lRet;
+
+ lRet = key.SetDWORDValue(L"UI", dwUI);
+ if(lRet != ERROR_SUCCESS)
+ return lRet;
+
+ if (hgSettings != NULL)
+ {
+ LPBYTE pVal = (LPBYTE)::GlobalLock(hgSettings);
+ if (pVal != NULL)
+ {
+ lRet = key.SetBinaryValue(L"Settings", pVal, ::GlobalSize(hgSettings));
+ ::GlobalUnlock(hgSettings);
+ }
+ else
+ {
+ lRet = GetLastError();
+ }
+ }
+
+ return lRet;
+ }
+
+ LONG Restore(bool& bRibbonUI, HGLOBAL& hgSettings)
+ {
+ ATLASSERT(hgSettings == NULL);
+
+ CRegKeyEx key;
+
+ LONG lRet = key.Open(m_Key, L"Ribbon");
+ if(lRet != ERROR_SUCCESS)
+ return lRet;
+
+ DWORD dwUI = 0xffff;
+ lRet = key.QueryDWORDValue(L"UI", dwUI);
+ if(lRet == ERROR_SUCCESS)
+ bRibbonUI = dwUI == 1;
+ else
+ return lRet;
+
+ ULONG ulSize = 0;
+ lRet = key.QueryBinaryValue(L"Settings", NULL, &ulSize);
+ if (lRet == ERROR_SUCCESS)
+ {
+ ATLASSERT(ulSize != 0);
+
+ hgSettings = ::GlobalAlloc(GHND, ulSize);
+ if (hgSettings != NULL)
+ {
+ LPBYTE pData = (LPBYTE)::GlobalLock(hgSettings);
+ if (pData != NULL)
+ {
+ lRet = key.QueryBinaryValue(L"Settings", pData, &ulSize);
+ }
+ else
+ {
+ lRet = GetLastError();
+ ::GlobalFree(hgSettings);
+ hgSettings = NULL;
+ }
+ }
+ else
+ {
+ lRet = GetLastError();
+ }
+ }
+ return lRet;
+ }
+
+ LONG Delete()
+ {
+ return m_Key.DeleteSubKey(L"Ribbon");
+ }
+};
+
+} // namespace WTL
+
+#endif // __ATLRIBBON_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlscrl.h b/plugins/SmartAutoReplier/wtl/atlscrl.h
new file mode 100644
index 0000000000..0f59c9dd58
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlscrl.h
@@ -0,0 +1,2011 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLSCRL_H__
+#define __ATLSCRL_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlscrl.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atlscrl.h requires atlwin.h to be included first
+#endif
+
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ #include <zmouse.h>
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+
+#ifndef GET_WHEEL_DELTA_WPARAM
+ #define GET_WHEEL_DELTA_WPARAM(wParam) ((short)HIWORD(wParam))
+#endif
+
+#ifndef WM_MOUSEHWHEEL
+ #define WM_MOUSEHWHEEL 0x020E
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CScrollImpl<T>
+// CScrollWindowImpl<T, TBase, TWinTraits>
+// CMapScrollImpl<T>
+// CMapScrollWindowImpl<T, TBase, TWinTraits>
+// CFSBWindowT<TBase>
+// CZoomScrollImpl<T>
+// CZoomScrollWindowImpl<T, TBase, TWinTraits>
+// CScrollContainerImpl<T, TBase, TWinTraits>
+// CScrollContainer
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CScrollImpl - Provides scrolling support to any window
+
+// Scroll extended styles
+#define SCRL_SCROLLCHILDREN 0x00000001
+#define SCRL_ERASEBACKGROUND 0x00000002
+#define SCRL_NOTHUMBTRACKING 0x00000004
+#if (WINVER >= 0x0500)
+#define SCRL_SMOOTHSCROLL 0x00000008
+#endif // (WINVER >= 0x0500)
+#define SCRL_DISABLENOSCROLLV 0x00000010
+#define SCRL_DISABLENOSCROLLH 0x00000020
+#define SCRL_DISABLENOSCROLL (SCRL_DISABLENOSCROLLV | SCRL_DISABLENOSCROLLH)
+
+
+template <class T>
+class CScrollImpl
+{
+public:
+ enum { uSCROLL_FLAGS = SW_INVALIDATE };
+
+ POINT m_ptOffset;
+ SIZE m_sizeAll;
+ SIZE m_sizeLine;
+ SIZE m_sizePage;
+ SIZE m_sizeClient;
+ int m_zDelta; // current wheel value
+ int m_nWheelLines; // number of lines to scroll on wheel
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ // Note that this message must be forwarded from a top level window
+ UINT m_uMsgMouseWheel; // MSH_MOUSEWHEEL
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ int m_zHDelta; // current horizontal wheel value
+ int m_nHWheelChars; // number of chars to scroll on horizontal wheel
+ UINT m_uScrollFlags;
+ DWORD m_dwExtendedStyle; // scroll specific extended styles
+
+// Constructor
+ CScrollImpl() : m_zDelta(0), m_nWheelLines(3),
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ m_uMsgMouseWheel(0U),
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ m_zHDelta(0), m_nHWheelChars(3),
+ m_uScrollFlags(0U), m_dwExtendedStyle(0)
+ {
+ m_ptOffset.x = 0;
+ m_ptOffset.y = 0;
+ m_sizeAll.cx = 0;
+ m_sizeAll.cy = 0;
+ m_sizePage.cx = 0;
+ m_sizePage.cy = 0;
+ m_sizeLine.cx = 0;
+ m_sizeLine.cy = 0;
+ m_sizeClient.cx = 0;
+ m_sizeClient.cy = 0;
+
+ SetScrollExtendedStyle(SCRL_SCROLLCHILDREN | SCRL_ERASEBACKGROUND);
+ }
+
+// Attributes & Operations
+ DWORD GetScrollExtendedStyle() const
+ {
+ return m_dwExtendedStyle;
+ }
+
+ DWORD SetScrollExtendedStyle(DWORD dwExtendedStyle, DWORD dwMask = 0)
+ {
+ DWORD dwPrevStyle = m_dwExtendedStyle;
+ if(dwMask == 0)
+ m_dwExtendedStyle = dwExtendedStyle;
+ else
+ m_dwExtendedStyle = (m_dwExtendedStyle & ~dwMask) | (dwExtendedStyle & dwMask);
+ // cache scroll flags
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ m_uScrollFlags = pT->uSCROLL_FLAGS | (IsScrollingChildren() ? SW_SCROLLCHILDREN : 0) | (IsErasingBackground() ? SW_ERASE : 0);
+#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ m_uScrollFlags |= (IsSmoothScroll() ? SW_SMOOTHSCROLL : 0);
+#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ return dwPrevStyle;
+ }
+
+ // offset operations
+ void SetScrollOffset(int x, int y, BOOL bRedraw = TRUE)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ pT->AdjustScrollOffset(x, y);
+
+ int dx = m_ptOffset.x - x;
+ int dy = m_ptOffset.y - y;
+ m_ptOffset.x = x;
+ m_ptOffset.y = y;
+
+ // block: set horizontal scroll bar
+ {
+ SCROLLINFO si = { sizeof(SCROLLINFO) };
+ si.fMask = SIF_POS;
+ if((m_dwExtendedStyle & SCRL_DISABLENOSCROLLH) != 0)
+ si.fMask |= SIF_DISABLENOSCROLL;
+ si.nPos = m_ptOffset.x;
+ pT->SetScrollInfo(SB_HORZ, &si, bRedraw);
+ }
+
+ // block: set vertical scroll bar
+ {
+ SCROLLINFO si = { sizeof(SCROLLINFO) };
+ si.fMask = SIF_POS;
+ if((m_dwExtendedStyle & SCRL_DISABLENOSCROLLV) != 0)
+ si.fMask |= SIF_DISABLENOSCROLL;
+ si.nPos = m_ptOffset.y;
+ pT->SetScrollInfo(SB_VERT, &si, bRedraw);
+ }
+
+ // Move all children if needed
+ if(IsScrollingChildren() && (dx != 0 || dy != 0))
+ {
+ for(HWND hWndChild = ::GetWindow(pT->m_hWnd, GW_CHILD); hWndChild != NULL; hWndChild = ::GetWindow(hWndChild, GW_HWNDNEXT))
+ {
+ RECT rect = { 0 };
+ ::GetWindowRect(hWndChild, &rect);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rect, 1);
+ ::SetWindowPos(hWndChild, NULL, rect.left + dx, rect.top + dy, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
+ }
+ }
+
+ if(bRedraw)
+ pT->Invalidate();
+ }
+
+ void SetScrollOffset(POINT ptOffset, BOOL bRedraw = TRUE)
+ {
+ SetScrollOffset(ptOffset.x, ptOffset.y, bRedraw);
+ }
+
+ void GetScrollOffset(POINT& ptOffset) const
+ {
+ ptOffset = m_ptOffset;
+ }
+
+ // size operations
+ void SetScrollSize(int cx, int cy, BOOL bRedraw = TRUE, bool bResetOffset = true)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ m_sizeAll.cx = cx;
+ m_sizeAll.cy = cy;
+
+ int x = 0;
+ int y = 0;
+ if(!bResetOffset)
+ {
+ x = m_ptOffset.x;
+ y = m_ptOffset.y;
+ pT->AdjustScrollOffset(x, y);
+ }
+
+ int dx = m_ptOffset.x - x;
+ int dy = m_ptOffset.y - y;
+ m_ptOffset.x = x;
+ m_ptOffset.y = y;
+
+ // block: set horizontal scroll bar
+ {
+ SCROLLINFO si = { sizeof(SCROLLINFO) };
+ si.fMask = SIF_PAGE | SIF_RANGE | SIF_POS;
+ if((m_dwExtendedStyle & SCRL_DISABLENOSCROLLH) != 0)
+ si.fMask |= SIF_DISABLENOSCROLL;
+ si.nMin = 0;
+ si.nMax = m_sizeAll.cx - 1;
+ si.nPage = m_sizeClient.cx;
+ si.nPos = m_ptOffset.x;
+ pT->SetScrollInfo(SB_HORZ, &si, bRedraw);
+ }
+
+ // block: set vertical scroll bar
+ {
+ SCROLLINFO si = { sizeof(SCROLLINFO) };
+ si.fMask = SIF_PAGE | SIF_RANGE | SIF_POS;
+ if((m_dwExtendedStyle & SCRL_DISABLENOSCROLLV) != 0)
+ si.fMask |= SIF_DISABLENOSCROLL;
+ si.nMin = 0;
+ si.nMax = m_sizeAll.cy - 1;
+ si.nPage = m_sizeClient.cy;
+ si.nPos = m_ptOffset.y;
+ pT->SetScrollInfo(SB_VERT, &si, bRedraw);
+ }
+
+ // Move all children if needed
+ if(IsScrollingChildren() && (dx != 0 || dy != 0))
+ {
+ for(HWND hWndChild = ::GetWindow(pT->m_hWnd, GW_CHILD); hWndChild != NULL; hWndChild = ::GetWindow(hWndChild, GW_HWNDNEXT))
+ {
+ RECT rect = { 0 };
+ ::GetWindowRect(hWndChild, &rect);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rect, 1);
+ ::SetWindowPos(hWndChild, NULL, rect.left + dx, rect.top + dy, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
+ }
+ }
+
+ SetScrollLine(0, 0);
+ SetScrollPage(0, 0);
+
+ if(bRedraw)
+ pT->Invalidate();
+ }
+
+ void SetScrollSize(SIZE size, BOOL bRedraw = TRUE, bool bResetOffset = true)
+ {
+ SetScrollSize(size.cx, size.cy, bRedraw, bResetOffset);
+ }
+
+ void GetScrollSize(SIZE& sizeWnd) const
+ {
+ sizeWnd = m_sizeAll;
+ }
+
+ // line operations
+ void SetScrollLine(int cxLine, int cyLine)
+ {
+ ATLASSERT(cxLine >= 0 && cyLine >= 0);
+ ATLASSERT(m_sizeAll.cx != 0 && m_sizeAll.cy != 0);
+
+ m_sizeLine.cx = T::CalcLineOrPage(cxLine, m_sizeAll.cx, 100);
+ m_sizeLine.cy = T::CalcLineOrPage(cyLine, m_sizeAll.cy, 100);
+ }
+
+ void SetScrollLine(SIZE sizeLine)
+ {
+ SetScrollLine(sizeLine.cx, sizeLine.cy);
+ }
+
+ void GetScrollLine(SIZE& sizeLine) const
+ {
+ sizeLine = m_sizeLine;
+ }
+
+ // page operations
+ void SetScrollPage(int cxPage, int cyPage)
+ {
+ ATLASSERT(cxPage >= 0 && cyPage >= 0);
+ ATLASSERT(m_sizeAll.cx != 0 && m_sizeAll.cy != 0);
+
+ m_sizePage.cx = T::CalcLineOrPage(cxPage, m_sizeAll.cx, 10);
+ m_sizePage.cy = T::CalcLineOrPage(cyPage, m_sizeAll.cy, 10);
+ }
+
+ void SetScrollPage(SIZE sizePage)
+ {
+ SetScrollPage(sizePage.cx, sizePage.cy);
+ }
+
+ void GetScrollPage(SIZE& sizePage) const
+ {
+ sizePage = m_sizePage;
+ }
+
+ // commands
+ void ScrollLineDown()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_VERT, SB_LINEDOWN, (int&)m_ptOffset.y, m_sizeAll.cy, m_sizePage.cy, m_sizeLine.cy);
+ }
+
+ void ScrollLineUp()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_VERT, SB_LINEUP, (int&)m_ptOffset.y, m_sizeAll.cy, m_sizePage.cy, m_sizeLine.cy);
+ }
+
+ void ScrollPageDown()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_VERT, SB_PAGEDOWN, (int&)m_ptOffset.y, m_sizeAll.cy, m_sizePage.cy, m_sizeLine.cy);
+ }
+
+ void ScrollPageUp()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_VERT, SB_PAGEUP, (int&)m_ptOffset.y, m_sizeAll.cy, m_sizePage.cy, m_sizeLine.cy);
+ }
+
+ void ScrollTop()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_VERT, SB_TOP, (int&)m_ptOffset.y, m_sizeAll.cy, m_sizePage.cy, m_sizeLine.cy);
+ }
+
+ void ScrollBottom()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_VERT, SB_BOTTOM, (int&)m_ptOffset.y, m_sizeAll.cy, m_sizePage.cy, m_sizeLine.cy);
+ }
+
+ void ScrollLineRight()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_HORZ, SB_LINEDOWN, (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ }
+
+ void ScrollLineLeft()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_HORZ, SB_LINEUP, (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ }
+
+ void ScrollPageRight()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_HORZ, SB_PAGEDOWN, (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ }
+
+ void ScrollPageLeft()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_HORZ, SB_PAGEUP, (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ }
+
+ void ScrollAllLeft()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_HORZ, SB_TOP, (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ }
+
+ void ScrollAllRight()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_HORZ, SB_BOTTOM, (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ }
+
+ // scroll to make point/view/window visible
+ void ScrollToView(POINT pt)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ RECT rect = { pt.x, pt.y, pt.x, pt.y };
+ pT->ScrollToView(rect);
+ }
+
+ void ScrollToView(RECT& rect)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ RECT rcClient = { 0 };
+ pT->GetClientRect(&rcClient);
+
+ int x = m_ptOffset.x;
+ if(rect.left < m_ptOffset.x)
+ x = rect.left;
+ else if(rect.right > (m_ptOffset.x + rcClient.right))
+ x = rect.right - rcClient.right;
+
+ int y = m_ptOffset.y;
+ if(rect.top < m_ptOffset.y)
+ y = rect.top;
+ else if(rect.bottom > (m_ptOffset.y + rcClient.bottom))
+ y = rect.bottom - rcClient.bottom;
+
+ SetScrollOffset(x, y);
+ }
+
+ void ScrollToView(HWND hWnd)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ RECT rect = { 0 };
+ ::GetWindowRect(hWnd, &rect);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rect, 2);
+ ScrollToView(rect);
+ }
+
+ BEGIN_MSG_MAP(CScrollImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_VSCROLL, OnVScroll)
+ MESSAGE_HANDLER(WM_HSCROLL, OnHScroll)
+ MESSAGE_HANDLER(WM_MOUSEWHEEL, OnMouseWheel)
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ MESSAGE_HANDLER(m_uMsgMouseWheel, OnMouseWheel)
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ MESSAGE_HANDLER(WM_MOUSEHWHEEL, OnMouseHWheel)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+#endif // !_WIN32_WCE
+ // standard scroll commands
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_SCROLL_UP, OnScrollUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_DOWN, OnScrollDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_UP, OnScrollPageUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_DOWN, OnScrollPageDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_TOP, OnScrollTop)
+ COMMAND_ID_HANDLER(ID_SCROLL_BOTTOM, OnScrollBottom)
+ COMMAND_ID_HANDLER(ID_SCROLL_LEFT, OnScrollLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_RIGHT, OnScrollRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_LEFT, OnScrollPageLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_RIGHT, OnScrollPageRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_LEFT, OnScrollAllLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_RIGHT, OnScrollAllRight)
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ GetSystemSettings();
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnVScroll(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_VERT, (int)(short)LOWORD(wParam), (int&)m_ptOffset.y, m_sizeAll.cy, m_sizePage.cy, m_sizeLine.cy);
+ return 0;
+ }
+
+ LRESULT OnHScroll(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ pT->DoScroll(SB_HORZ, (int)(short)LOWORD(wParam), (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ return 0;
+ }
+
+ LRESULT OnMouseWheel(UINT uMsg, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+#if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) || defined(_WIN32_WCE)
+ uMsg;
+ int zDelta = (int)GET_WHEEL_DELTA_WPARAM(wParam);
+#else
+ int zDelta = (uMsg == WM_MOUSEWHEEL) ? (int)GET_WHEEL_DELTA_WPARAM(wParam) : (int)wParam;
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) || defined(_WIN32_WCE))
+ int nScrollCode = (m_nWheelLines == WHEEL_PAGESCROLL) ? ((zDelta > 0) ? SB_PAGEUP : SB_PAGEDOWN) : ((zDelta > 0) ? SB_LINEUP : SB_LINEDOWN);
+ m_zDelta += zDelta; // cumulative
+ int zTotal = (m_nWheelLines == WHEEL_PAGESCROLL) ? abs(m_zDelta) : abs(m_zDelta) * m_nWheelLines;
+ if(m_sizeAll.cy > m_sizeClient.cy)
+ {
+ for(int i = 0; i < zTotal; i += WHEEL_DELTA)
+ {
+ pT->DoScroll(SB_VERT, nScrollCode, (int&)m_ptOffset.y, m_sizeAll.cy, m_sizePage.cy, m_sizeLine.cy);
+ pT->UpdateWindow();
+ }
+ }
+ else // can't scroll vertically, scroll horizontally
+ {
+ for(int i = 0; i < zTotal; i += WHEEL_DELTA)
+ {
+ pT->DoScroll(SB_HORZ, nScrollCode, (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ pT->UpdateWindow();
+ }
+ }
+ m_zDelta %= WHEEL_DELTA;
+
+ return 0;
+ }
+
+ LRESULT OnMouseHWheel(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ int zDelta = (int)GET_WHEEL_DELTA_WPARAM(wParam);
+ int nScrollCode = (m_nHWheelChars == WHEEL_PAGESCROLL) ? ((zDelta > 0) ? SB_PAGERIGHT : SB_PAGELEFT) : ((zDelta > 0) ? SB_LINERIGHT : SB_LINELEFT);
+ m_zHDelta += zDelta; // cumulative
+ int zTotal = (m_nHWheelChars == WHEEL_PAGESCROLL) ? abs(m_zHDelta) : abs(m_zHDelta) * m_nHWheelChars;
+ if(m_sizeAll.cx > m_sizeClient.cx)
+ {
+ for(int i = 0; i < zTotal; i += WHEEL_DELTA)
+ {
+ pT->DoScroll(SB_HORZ, nScrollCode, (int&)m_ptOffset.x, m_sizeAll.cx, m_sizePage.cx, m_sizeLine.cx);
+ pT->UpdateWindow();
+ }
+ }
+ m_zHDelta %= WHEEL_DELTA;
+
+ return 0;
+ }
+
+ LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ GetSystemSettings();
+ return 0;
+ }
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ m_sizeClient.cx = GET_X_LPARAM(lParam);
+ m_sizeClient.cy = GET_Y_LPARAM(lParam);
+
+ // block: set horizontal scroll bar
+ {
+ SCROLLINFO si = { sizeof(SCROLLINFO) };
+ si.fMask = SIF_PAGE | SIF_RANGE | SIF_POS;
+ si.nMin = 0;
+ si.nMax = m_sizeAll.cx - 1;
+ if((m_dwExtendedStyle & SCRL_DISABLENOSCROLLH) != 0)
+ si.fMask |= SIF_DISABLENOSCROLL;
+ si.nPage = m_sizeClient.cx;
+ si.nPos = m_ptOffset.x;
+ pT->SetScrollInfo(SB_HORZ, &si, TRUE);
+ }
+
+ // block: set vertical scroll bar
+ {
+ SCROLLINFO si = { sizeof(SCROLLINFO) };
+ si.fMask = SIF_PAGE | SIF_RANGE | SIF_POS;
+ si.nMin = 0;
+ si.nMax = m_sizeAll.cy - 1;
+ if((m_dwExtendedStyle & SCRL_DISABLENOSCROLLV) != 0)
+ si.fMask |= SIF_DISABLENOSCROLL;
+ si.nPage = m_sizeClient.cy;
+ si.nPos = m_ptOffset.y;
+ pT->SetScrollInfo(SB_VERT, &si, TRUE);
+ }
+
+ int x = m_ptOffset.x;
+ int y = m_ptOffset.y;
+ if(pT->AdjustScrollOffset(x, y))
+ {
+ // Children will be moved in SetScrollOffset, if needed
+ pT->ScrollWindowEx(m_ptOffset.x - x, m_ptOffset.y - y, (m_uScrollFlags & ~SCRL_SCROLLCHILDREN));
+ SetScrollOffset(x, y, FALSE);
+ }
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ if(wParam != NULL)
+ {
+ CDCHandle dc = (HDC)wParam;
+ POINT ptViewportOrg = { 0, 0 };
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y, &ptViewportOrg);
+ pT->DoPaint(dc);
+ dc.SetViewportOrg(ptViewportOrg);
+ }
+ else
+ {
+ CPaintDC dc(pT->m_hWnd);
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y);
+ pT->DoPaint(dc.m_hDC);
+ }
+ return 0;
+ }
+
+ // scrolling handlers
+ LRESULT OnScrollUp(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollLineUp();
+ return 0;
+ }
+
+ LRESULT OnScrollDown(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollLineDown();
+ return 0;
+ }
+
+ LRESULT OnScrollPageUp(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollPageUp();
+ return 0;
+ }
+
+ LRESULT OnScrollPageDown(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollPageDown();
+ return 0;
+ }
+
+ LRESULT OnScrollTop(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollTop();
+ return 0;
+ }
+
+ LRESULT OnScrollBottom(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollBottom();
+ return 0;
+ }
+
+ LRESULT OnScrollLeft(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollLineLeft();
+ return 0;
+ }
+
+ LRESULT OnScrollRight(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollLineRight();
+ return 0;
+ }
+
+ LRESULT OnScrollPageLeft(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollPageLeft();
+ return 0;
+ }
+
+ LRESULT OnScrollPageRight(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollPageRight();
+ return 0;
+ }
+
+ LRESULT OnScrollAllLeft(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollAllLeft();
+ return 0;
+ }
+
+ LRESULT OnScrollAllRight(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ ScrollAllRight();
+ return 0;
+ }
+
+// Overrideables
+ void DoPaint(CDCHandle /*dc*/)
+ {
+ // must be implemented in a derived class
+ ATLASSERT(FALSE);
+ }
+
+// Implementation
+ void DoScroll(int nType, int nScrollCode, int& cxyOffset, int cxySizeAll, int cxySizePage, int cxySizeLine)
+ {
+ T* pT = static_cast<T*>(this);
+ RECT rect = { 0 };
+ pT->GetClientRect(&rect);
+ int cxyClient = (nType == SB_VERT) ? rect.bottom : rect.right;
+ int cxyMax = cxySizeAll - cxyClient;
+
+ if(cxyMax < 0) // can't scroll, client area is bigger
+ return;
+
+ bool bUpdate = true;
+ int cxyScroll = 0;
+
+ switch(nScrollCode)
+ {
+ case SB_TOP: // top or all left
+ cxyScroll = cxyOffset;
+ cxyOffset = 0;
+ break;
+ case SB_BOTTOM: // bottom or all right
+ cxyScroll = cxyOffset - cxyMax;
+ cxyOffset = cxyMax;
+ break;
+ case SB_LINEUP: // line up or line left
+ if(cxyOffset >= cxySizeLine)
+ {
+ cxyScroll = cxySizeLine;
+ cxyOffset -= cxySizeLine;
+ }
+ else
+ {
+ cxyScroll = cxyOffset;
+ cxyOffset = 0;
+ }
+ break;
+ case SB_LINEDOWN: // line down or line right
+ if(cxyOffset < cxyMax - cxySizeLine)
+ {
+ cxyScroll = -cxySizeLine;
+ cxyOffset += cxySizeLine;
+ }
+ else
+ {
+ cxyScroll = cxyOffset - cxyMax;
+ cxyOffset = cxyMax;
+ }
+ break;
+ case SB_PAGEUP: // page up or page left
+ if(cxyOffset >= cxySizePage)
+ {
+ cxyScroll = cxySizePage;
+ cxyOffset -= cxySizePage;
+ }
+ else
+ {
+ cxyScroll = cxyOffset;
+ cxyOffset = 0;
+ }
+ break;
+ case SB_PAGEDOWN: // page down or page right
+ if(cxyOffset < cxyMax - cxySizePage)
+ {
+ cxyScroll = -cxySizePage;
+ cxyOffset += cxySizePage;
+ }
+ else
+ {
+ cxyScroll = cxyOffset - cxyMax;
+ cxyOffset = cxyMax;
+ }
+ break;
+ case SB_THUMBTRACK:
+ if(IsNoThumbTracking())
+ break;
+ // else fall through
+ case SB_THUMBPOSITION:
+ {
+ SCROLLINFO si = { sizeof(SCROLLINFO), SIF_TRACKPOS };
+ if(pT->GetScrollInfo(nType, &si))
+ {
+ cxyScroll = cxyOffset - si.nTrackPos;
+ cxyOffset = si.nTrackPos;
+ }
+ }
+ break;
+ case SB_ENDSCROLL:
+ default:
+ bUpdate = false;
+ break;
+ }
+
+ if(bUpdate && cxyScroll != 0)
+ {
+ pT->SetScrollPos(nType, cxyOffset, TRUE);
+ if(nType == SB_VERT)
+ pT->ScrollWindowEx(0, cxyScroll, m_uScrollFlags);
+ else
+ pT->ScrollWindowEx(cxyScroll, 0, m_uScrollFlags);
+ }
+ }
+
+ static int CalcLineOrPage(int nVal, int nMax, int nDiv)
+ {
+ if(nVal == 0)
+ {
+ nVal = nMax / nDiv;
+ if(nVal < 1)
+ nVal = 1;
+ }
+ else if(nVal > nMax)
+ {
+ nVal = nMax;
+ }
+
+ return nVal;
+ }
+
+ bool AdjustScrollOffset(int& x, int& y)
+ {
+ int xOld = x;
+ int yOld = y;
+
+ int cxMax = m_sizeAll.cx - m_sizeClient.cx;
+ if(x > cxMax)
+ x = (cxMax >= 0) ? cxMax : 0;
+ else if(x < 0)
+ x = 0;
+
+ int cyMax = m_sizeAll.cy - m_sizeClient.cy;
+ if(y > cyMax)
+ y = (cyMax >= 0) ? cyMax : 0;
+ else if(y < 0)
+ y = 0;
+
+ return (x != xOld || y != yOld);
+ }
+
+ void GetSystemSettings()
+ {
+#ifndef _WIN32_WCE
+#ifndef SPI_GETWHEELSCROLLLINES
+ const UINT SPI_GETWHEELSCROLLLINES = 104;
+#endif // !SPI_GETWHEELSCROLLLINES
+ ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &m_nWheelLines, 0);
+
+#ifndef SPI_GETWHEELSCROLLCHARS
+ const UINT SPI_GETWHEELSCROLLCHARS = 0x006C;
+#endif // !SPI_GETWHEELSCROLLCHARS
+ ::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &m_nHWheelChars, 0);
+
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ if(m_uMsgMouseWheel != 0)
+ m_uMsgMouseWheel = ::RegisterWindowMessage(MSH_MOUSEWHEEL);
+
+ HWND hWndWheel = FindWindow(MSH_WHEELMODULE_CLASS, MSH_WHEELMODULE_TITLE);
+ if(::IsWindow(hWndWheel))
+ {
+ UINT uMsgScrollLines = ::RegisterWindowMessage(MSH_SCROLL_LINES);
+ if(uMsgScrollLines != 0)
+ m_nWheelLines = (int)::SendMessage(hWndWheel, uMsgScrollLines, 0, 0L);
+ }
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+#endif // !_WIN32_WCE
+ }
+
+ bool IsScrollingChildren() const
+ {
+ return (m_dwExtendedStyle & SCRL_SCROLLCHILDREN) != 0;
+ }
+
+ bool IsErasingBackground() const
+ {
+ return (m_dwExtendedStyle & SCRL_ERASEBACKGROUND) != 0;
+ }
+
+ bool IsNoThumbTracking() const
+ {
+ return (m_dwExtendedStyle & SCRL_NOTHUMBTRACKING) != 0;
+ }
+
+#if (WINVER >= 0x0500)
+ bool IsSmoothScroll() const
+ {
+ return (m_dwExtendedStyle & SCRL_SMOOTHSCROLL) != 0;
+ }
+#endif // (WINVER >= 0x0500)
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CScrollWindowImpl - Implements a scrollable window
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CScrollWindowImpl : public ATL::CWindowImpl<T, TBase, TWinTraits>, public CScrollImpl< T >
+{
+public:
+ BEGIN_MSG_MAP(CScrollWindowImpl)
+ MESSAGE_HANDLER(WM_VSCROLL, CScrollImpl< T >::OnVScroll)
+ MESSAGE_HANDLER(WM_HSCROLL, CScrollImpl< T >::OnHScroll)
+ MESSAGE_HANDLER(WM_MOUSEWHEEL, CScrollImpl< T >::OnMouseWheel)
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ MESSAGE_HANDLER(m_uMsgMouseWheel, CScrollImpl< T >::OnMouseWheel)
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400)) && !defined(_WIN32_WCE)
+ MESSAGE_HANDLER(WM_MOUSEHWHEEL, CScrollImpl< T >::OnMouseHWheel)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, CScrollImpl< T >::OnSettingChange)
+ MESSAGE_HANDLER(WM_SIZE, CScrollImpl< T >::OnSize)
+ MESSAGE_HANDLER(WM_PAINT, CScrollImpl< T >::OnPaint)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_PRINTCLIENT, CScrollImpl< T >::OnPaint)
+#endif // !_WIN32_WCE
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_SCROLL_UP, CScrollImpl< T >::OnScrollUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_DOWN, CScrollImpl< T >::OnScrollDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_UP, CScrollImpl< T >::OnScrollPageUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_DOWN, CScrollImpl< T >::OnScrollPageDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_TOP, CScrollImpl< T >::OnScrollTop)
+ COMMAND_ID_HANDLER(ID_SCROLL_BOTTOM, CScrollImpl< T >::OnScrollBottom)
+ COMMAND_ID_HANDLER(ID_SCROLL_LEFT, CScrollImpl< T >::OnScrollLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_RIGHT, CScrollImpl< T >::OnScrollRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_LEFT, CScrollImpl< T >::OnScrollPageLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_RIGHT, CScrollImpl< T >::OnScrollPageRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_LEFT, CScrollImpl< T >::OnScrollAllLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_RIGHT, CScrollImpl< T >::OnScrollAllRight)
+ END_MSG_MAP()
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMapScrollImpl - Provides mapping and scrolling support to any window
+
+#ifndef _WIN32_WCE
+
+template <class T>
+class CMapScrollImpl : public CScrollImpl< T >
+{
+public:
+ int m_nMapMode;
+ RECT m_rectLogAll;
+ SIZE m_sizeLogLine;
+ SIZE m_sizeLogPage;
+
+// Constructor
+ CMapScrollImpl() : m_nMapMode(MM_TEXT)
+ {
+ ::SetRectEmpty(&m_rectLogAll);
+ m_sizeLogPage.cx = 0;
+ m_sizeLogPage.cy = 0;
+ m_sizeLogLine.cx = 0;
+ m_sizeLogLine.cy = 0;
+ }
+
+// Attributes & Operations
+ // mapping mode operations
+ void SetScrollMapMode(int nMapMode)
+ {
+ ATLASSERT(nMapMode >= MM_MIN && nMapMode <= MM_MAX_FIXEDSCALE);
+ m_nMapMode = nMapMode;
+ }
+
+ int GetScrollMapMode() const
+ {
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+ return m_nMapMode;
+ }
+
+ // offset operations
+ void SetScrollOffset(int x, int y, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+ POINT ptOff = { x, y };
+ // block: convert logical to device units
+ {
+ CWindowDC dc(NULL);
+ dc.SetMapMode(m_nMapMode);
+ dc.LPtoDP(&ptOff);
+ }
+ CScrollImpl< T >::SetScrollOffset(ptOff, bRedraw);
+ }
+
+ void SetScrollOffset(POINT ptOffset, BOOL bRedraw = TRUE)
+ {
+ SetScrollOffset(ptOffset.x, ptOffset.y, bRedraw);
+ }
+
+ void GetScrollOffset(POINT& ptOffset) const
+ {
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+ ptOffset = m_ptOffset;
+ // block: convert device to logical units
+ {
+ CWindowDC dc(NULL);
+ dc.SetMapMode(m_nMapMode);
+ dc.DPtoLP(&ptOffset);
+ }
+ }
+
+ // size operations
+ void SetScrollSize(int xMin, int yMin, int xMax, int yMax, BOOL bRedraw = TRUE, bool bResetOffset = true)
+ {
+ ATLASSERT(xMax > xMin && yMax > yMin);
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+
+ ::SetRect(&m_rectLogAll, xMin, yMin, xMax, yMax);
+
+ SIZE sizeAll = { 0 };
+ sizeAll.cx = xMax - xMin + 1;
+ sizeAll.cy = yMax - yMin + 1;
+ // block: convert logical to device units
+ {
+ CWindowDC dc(NULL);
+ dc.SetMapMode(m_nMapMode);
+ dc.LPtoDP(&sizeAll);
+ }
+ CScrollImpl< T >::SetScrollSize(sizeAll, bRedraw, bResetOffset);
+ SetScrollLine(0, 0);
+ SetScrollPage(0, 0);
+ }
+
+ void SetScrollSize(RECT& rcScroll, BOOL bRedraw = TRUE, bool bResetOffset = true)
+ {
+ SetScrollSize(rcScroll.left, rcScroll.top, rcScroll.right, rcScroll.bottom, bRedraw, bResetOffset);
+ }
+
+ void SetScrollSize(int cx, int cy, BOOL bRedraw = TRUE, bool bResetOffset = true)
+ {
+ SetScrollSize(0, 0, cx, cy, bRedraw, bResetOffset);
+ }
+
+ void SetScrollSize(SIZE size, BOOL bRedraw = TRUE, bool bResetOffset = true)
+ {
+ SetScrollSize(0, 0, size.cx, size.cy, bRedraw, bResetOffset);
+ }
+
+ void GetScrollSize(RECT& rcScroll) const
+ {
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+ rcScroll = m_rectLogAll;
+ }
+
+ // line operations
+ void SetScrollLine(int cxLine, int cyLine)
+ {
+ ATLASSERT(cxLine >= 0 && cyLine >= 0);
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+
+ m_sizeLogLine.cx = cxLine;
+ m_sizeLogLine.cy = cyLine;
+ SIZE sizeLine = m_sizeLogLine;
+ // block: convert logical to device units
+ {
+ CWindowDC dc(NULL);
+ dc.SetMapMode(m_nMapMode);
+ dc.LPtoDP(&sizeLine);
+ }
+ CScrollImpl< T >::SetScrollLine(sizeLine);
+ }
+
+ void SetScrollLine(SIZE sizeLine)
+ {
+ SetScrollLine(sizeLine.cx, sizeLine.cy);
+ }
+
+ void GetScrollLine(SIZE& sizeLine) const
+ {
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+ sizeLine = m_sizeLogLine;
+ }
+
+ // page operations
+ void SetScrollPage(int cxPage, int cyPage)
+ {
+ ATLASSERT(cxPage >= 0 && cyPage >= 0);
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+
+ m_sizeLogPage.cx = cxPage;
+ m_sizeLogPage.cy = cyPage;
+ SIZE sizePage = m_sizeLogPage;
+ // block: convert logical to device units
+ {
+ CWindowDC dc(NULL);
+ dc.SetMapMode(m_nMapMode);
+ dc.LPtoDP(&sizePage);
+ }
+ CScrollImpl< T >::SetScrollPage(sizePage);
+ }
+
+ void SetScrollPage(SIZE sizePage)
+ {
+ SetScrollPage(sizePage.cx, sizePage.cy);
+ }
+
+ void GetScrollPage(SIZE& sizePage) const
+ {
+ ATLASSERT(m_nMapMode >= MM_MIN && m_nMapMode <= MM_MAX_FIXEDSCALE);
+ sizePage = m_sizeLogPage;
+ }
+
+ BEGIN_MSG_MAP(CMapScrollImpl)
+ MESSAGE_HANDLER(WM_VSCROLL, CScrollImpl< T >::OnVScroll)
+ MESSAGE_HANDLER(WM_HSCROLL, CScrollImpl< T >::OnHScroll)
+ MESSAGE_HANDLER(WM_MOUSEWHEEL, CScrollImpl< T >::OnMouseWheel)
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(m_uMsgMouseWheel, CScrollImpl< T >::OnMouseWheel)
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(WM_MOUSEHWHEEL, CScrollImpl< T >::OnMouseHWheel)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, CScrollImpl< T >::OnSettingChange)
+ MESSAGE_HANDLER(WM_SIZE, CScrollImpl< T >::OnSize)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_SCROLL_UP, CScrollImpl< T >::OnScrollUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_DOWN, CScrollImpl< T >::OnScrollDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_UP, CScrollImpl< T >::OnScrollPageUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_DOWN, CScrollImpl< T >::OnScrollPageDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_TOP, CScrollImpl< T >::OnScrollTop)
+ COMMAND_ID_HANDLER(ID_SCROLL_BOTTOM, CScrollImpl< T >::OnScrollBottom)
+ COMMAND_ID_HANDLER(ID_SCROLL_LEFT, CScrollImpl< T >::OnScrollLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_RIGHT, CScrollImpl< T >::OnScrollRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_LEFT, CScrollImpl< T >::OnScrollPageLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_RIGHT, CScrollImpl< T >::OnScrollPageRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_LEFT, CScrollImpl< T >::OnScrollAllLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_RIGHT, CScrollImpl< T >::OnScrollAllRight)
+ END_MSG_MAP()
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ if(wParam != NULL)
+ {
+ CDCHandle dc = (HDC)wParam;
+ int nMapModeSav = dc.GetMapMode();
+ dc.SetMapMode(m_nMapMode);
+ POINT ptViewportOrg = { 0, 0 };
+ if(m_nMapMode == MM_TEXT)
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y, &ptViewportOrg);
+ else
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y + m_sizeAll.cy, &ptViewportOrg);
+ POINT ptWindowOrg = { 0, 0 };
+ dc.SetWindowOrg(m_rectLogAll.left, m_rectLogAll.top, &ptWindowOrg);
+
+ pT->DoPaint(dc);
+
+ dc.SetMapMode(nMapModeSav);
+ dc.SetViewportOrg(ptViewportOrg);
+ dc.SetWindowOrg(ptWindowOrg);
+ }
+ else
+ {
+ CPaintDC dc(pT->m_hWnd);
+ dc.SetMapMode(m_nMapMode);
+ if(m_nMapMode == MM_TEXT)
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y);
+ else
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y + m_sizeAll.cy);
+ dc.SetWindowOrg(m_rectLogAll.left, m_rectLogAll.top);
+ pT->DoPaint(dc.m_hDC);
+ }
+ return 0;
+ }
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMapScrollWindowImpl - Implements scrolling window with mapping
+
+#ifndef _WIN32_WCE
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CMapScrollWindowImpl : public ATL::CWindowImpl< T, TBase, TWinTraits >, public CMapScrollImpl< T >
+{
+public:
+ BEGIN_MSG_MAP(CMapScrollWindowImpl)
+ MESSAGE_HANDLER(WM_VSCROLL, CScrollImpl< T >::OnVScroll)
+ MESSAGE_HANDLER(WM_HSCROLL, CScrollImpl< T >::OnHScroll)
+ MESSAGE_HANDLER(WM_MOUSEWHEEL, CScrollImpl< T >::OnMouseWheel)
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(m_uMsgMouseWheel, CScrollImpl< T >::OnMouseWheel)
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(WM_MOUSEHWHEEL, CScrollImpl< T >::OnMouseHWheel)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, CScrollImpl< T >::OnSettingChange)
+ MESSAGE_HANDLER(WM_SIZE, CScrollImpl< T >::OnSize)
+ MESSAGE_HANDLER(WM_PAINT, CMapScrollImpl< T >::OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, CMapScrollImpl< T >::OnPaint)
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_SCROLL_UP, CScrollImpl< T >::OnScrollUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_DOWN, CScrollImpl< T >::OnScrollDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_UP, CScrollImpl< T >::OnScrollPageUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_DOWN, CScrollImpl< T >::OnScrollPageDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_TOP, CScrollImpl< T >::OnScrollTop)
+ COMMAND_ID_HANDLER(ID_SCROLL_BOTTOM, CScrollImpl< T >::OnScrollBottom)
+ COMMAND_ID_HANDLER(ID_SCROLL_LEFT, CScrollImpl< T >::OnScrollLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_RIGHT, CScrollImpl< T >::OnScrollRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_LEFT, CScrollImpl< T >::OnScrollPageLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_RIGHT, CScrollImpl< T >::OnScrollPageRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_LEFT, CScrollImpl< T >::OnScrollAllLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_RIGHT, CScrollImpl< T >::OnScrollAllRight)
+ END_MSG_MAP()
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CFSBWindow - Use as a base instead of CWindow to get flat scroll bar support
+
+#if defined(__ATLCTRLS_H__) && (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+template <class TBase = ATL::CWindow>
+class CFSBWindowT : public TBase, public CFlatScrollBarImpl<CFSBWindowT< TBase > >
+{
+public:
+// Constructors
+ CFSBWindowT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CFSBWindowT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+// CWindow overrides that use flat scroll bar API
+// (only those methods that are used by scroll window classes)
+ int SetScrollPos(int nBar, int nPos, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return FlatSB_SetScrollPos(nBar, nPos, bRedraw);
+ }
+
+ BOOL GetScrollInfo(int nBar, LPSCROLLINFO lpScrollInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return FlatSB_GetScrollInfo(nBar, lpScrollInfo);
+ }
+
+ BOOL SetScrollInfo(int nBar, LPSCROLLINFO lpScrollInfo, BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return FlatSB_SetScrollInfo(nBar, lpScrollInfo, bRedraw);
+ }
+};
+
+typedef CFSBWindowT<ATL::CWindow> CFSBWindow;
+
+#endif // defined(__ATLCTRLS_H__) && (_WIN32_IE >= 0x0400) && !defined(_WIN32_WCE)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CZoomScrollImpl - Provides zooming and scrolling support to any window
+
+#ifndef _WIN32_WCE
+
+// The zoom modes that can be set with the SetZoomMode method
+enum
+{
+ ZOOMMODE_OFF,
+ ZOOMMODE_IN, // If left mouse button is clicked or dragged, zoom in on point clicked or rectangle dragged.
+ ZOOMMODE_OUT // If left mouse button clicked, zoom out on point clicked.
+};
+
+// Notification to parent that zoom scale changed as a result of user mouse action.
+#define ZSN_ZOOMCHANGED (NM_FIRST - 50)
+
+template <class T>
+class CZoomScrollImpl : public CScrollImpl< T >
+{
+public:
+ enum { m_cxyMinZoomRect = 12 }; // min rect size to zoom in on rect.
+
+// Data members
+ SIZE m_sizeLogAll;
+ SIZE m_sizeLogLine;
+ SIZE m_sizeLogPage;
+ float m_fZoomScale;
+ float m_fZoomScaleMin;
+ float m_fZoomDelta; // Used in ZOOMMODE_IN and ZOOMMODE_OUT on left-button click.
+ int m_nZoomMode;
+ RECT m_rcTrack;
+ bool m_bTracking;
+
+// Constructor
+ CZoomScrollImpl():
+ m_fZoomScale(1.0),
+ m_fZoomScaleMin(0.5),
+ m_fZoomDelta(0.5),
+ m_nZoomMode(ZOOMMODE_OFF),
+ m_bTracking(false)
+ {
+ m_sizeLogAll.cx = 0;
+ m_sizeLogAll.cy = 0;
+ m_sizeLogPage.cx = 0;
+ m_sizeLogPage.cy = 0;
+ m_sizeLogLine.cx = 0;
+ m_sizeLogLine.cy = 0;
+ ::SetRectEmpty(&m_rcTrack);
+ }
+
+// Attributes & Operations
+
+ // size operations
+ void SetScrollSize(int cxLog, int cyLog, BOOL bRedraw = TRUE, bool bResetOffset = true)
+ {
+ ATLASSERT(cxLog >= 0 && cyLog >= 0);
+
+ // Set up the defaults
+ if (cxLog == 0 && cyLog == 0)
+ {
+ cxLog = 1;
+ cyLog = 1;
+ }
+
+ m_sizeLogAll.cx = cxLog;
+ m_sizeLogAll.cy = cyLog;
+ SIZE sizeAll = { 0 };
+ sizeAll.cx = (int)((float)m_sizeLogAll.cx * m_fZoomScale);
+ sizeAll.cy = (int)((float)m_sizeLogAll.cy * m_fZoomScale);
+
+ CScrollImpl< T >::SetScrollSize(sizeAll, bRedraw, bResetOffset);
+ }
+
+ void SetScrollSize(SIZE sizeLog, BOOL bRedraw = TRUE, bool bResetOffset = true)
+ {
+ SetScrollSize(sizeLog.cx, sizeLog.cy, bRedraw, bResetOffset);
+ }
+
+ void GetScrollSize(SIZE& sizeLog) const
+ {
+ sizeLog = m_sizeLogAll;
+ }
+
+ // line operations
+ void SetScrollLine(int cxLogLine, int cyLogLine)
+ {
+ ATLASSERT(cxLogLine >= 0 && cyLogLine >= 0);
+
+ m_sizeLogLine.cx = cxLogLine;
+ m_sizeLogLine.cy = cyLogLine;
+
+ SIZE sizeLine = { 0 };
+ sizeLine.cx = (int)((float)m_sizeLogLine.cx * m_fZoomScale);
+ sizeLine.cy = (int)((float)m_sizeLogLine.cy * m_fZoomScale);
+ CScrollImpl< T >::SetScrollLine(sizeLine);
+ }
+
+ void SetScrollLine(SIZE sizeLogLine)
+ {
+ SetScrollLine(sizeLogLine.cx, sizeLogLine.cy);
+ }
+
+ void GetScrollLine(SIZE& sizeLogLine) const
+ {
+ sizeLogLine = m_sizeLogLine;
+ }
+
+ // page operations
+ void SetScrollPage(int cxLogPage, int cyLogPage)
+ {
+ ATLASSERT(cxLogPage >= 0 && cyLogPage >= 0);
+
+ m_sizeLogPage.cx = cxLogPage;
+ m_sizeLogPage.cy = cyLogPage;
+
+ SIZE sizePage = { 0 };
+ sizePage.cx = (int)((float)m_sizeLogPage.cx * m_fZoomScale);
+ sizePage.cy = (int)((float)m_sizeLogPage.cy * m_fZoomScale);
+
+ CScrollImpl< T >::SetScrollPage(sizePage);
+ }
+
+ void SetScrollPage(SIZE sizeLogPage)
+ {
+ SetScrollPage(sizeLogPage.cx, sizeLogPage.cy);
+ }
+
+ void GetScrollPage(SIZE& sizeLogPage) const
+ {
+ sizeLogPage = m_sizeLogPage;
+ }
+
+ void SetZoomScale(float fZoomScale)
+ {
+ ATLASSERT(fZoomScale > 0);
+
+ if(fZoomScale > 0 && fZoomScale >= m_fZoomScaleMin)
+ m_fZoomScale = fZoomScale;
+ }
+
+ float GetZoomScale() const
+ {
+ return m_fZoomScale;
+ }
+
+ void SetZoomScaleMin(float fZoomScaleMin)
+ {
+ m_fZoomScaleMin = fZoomScaleMin;
+ }
+
+ float GetZoomScaleMin() const
+ {
+ return m_fZoomScaleMin;
+ }
+
+ void SetZoomDelta(float fZoomDelta)
+ {
+ ATLASSERT(fZoomDelta >= 0);
+
+ if(fZoomDelta >= 0)
+ m_fZoomDelta = fZoomDelta;
+ }
+
+ float GetZoomDelta() const
+ {
+ return m_fZoomDelta;
+ }
+
+ void SetZoomMode(int nZoomMode)
+ {
+ m_nZoomMode = nZoomMode;
+ }
+
+ int GetZoomMode() const
+ {
+ return m_nZoomMode;
+ }
+
+ void Zoom(int x, int y, float fZoomScale)
+ {
+ if(fZoomScale <= 0)
+ return;
+
+ fZoomScale = max(fZoomScale, m_fZoomScaleMin);
+
+ T* pT = static_cast<T*>(this);
+ POINT pt = { x, y };
+ if(!pT->PtInDevRect(pt))
+ return;
+
+ pT->ViewDPtoLP(&pt);
+ pT->Zoom(fZoomScale, false);
+ pT->CenterOnLogicalPoint(pt);
+ }
+
+ void Zoom(POINT pt, float fZoomScale)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Zoom(pt.x, pt.y, fZoomScale);
+ }
+
+ void Zoom(RECT& rc)
+ {
+ T* pT = static_cast<T*>(this);
+ RECT rcZoom = rc;
+ pT->NormalizeRect(rcZoom);
+ SIZE size = { rcZoom.right - rcZoom.left, rcZoom.bottom - rcZoom.top };
+ POINT pt = { rcZoom.left + size.cx / 2, rcZoom.top + size.cy / 2 };
+ if(size.cx < m_cxyMinZoomRect || size.cy < m_cxyMinZoomRect)
+ {
+ pT->Zoom(pt, m_fZoomScale + m_fZoomDelta);
+ return;
+ }
+
+ ATLASSERT(size.cx > 0 && size.cy > 0);
+
+ float fScaleH = (float)(m_sizeClient.cx + 1) / (float)size.cx;
+ float fScaleV = (float)(m_sizeClient.cy + 1) / (float)size.cy;
+ float fZoomScale = min(fScaleH, fScaleV) * m_fZoomScale;
+ pT->Zoom(pt, fZoomScale);
+ }
+
+ void Zoom(float fZoomScale, bool bCenter = true)
+ {
+ if(fZoomScale <= 0)
+ return;
+
+ fZoomScale = max(fZoomScale, m_fZoomScaleMin);
+
+
+ T* pT = static_cast<T*>(this);
+ POINT pt = { 0 };
+ if(bCenter)
+ {
+ RECT rc;
+ ::GetClientRect(pT->m_hWnd, &rc);
+ pt.x = rc.right / 2;
+ pt.y = rc.bottom / 2;
+ pT->ViewDPtoLP(&pt);
+ }
+
+ // Modify the Viewport extent
+ m_fZoomScale = fZoomScale;
+ SIZE sizeAll = { 0 };
+ sizeAll.cx = (int)((float)m_sizeLogAll.cx * fZoomScale);
+ sizeAll.cy = (int)((float)m_sizeLogAll.cy * fZoomScale);
+
+ // Update scroll bars and window
+ CScrollImpl< T >::SetScrollSize(sizeAll);
+
+ if(bCenter)
+ pT->CenterOnLogicalPoint(pt);
+ }
+
+ // Helper functions
+ void PrepareDC(CDCHandle dc)
+ {
+ ATLASSERT(m_sizeAll.cx >= 0 && m_sizeAll.cy >= 0);
+ dc.SetMapMode(MM_ANISOTROPIC);
+ dc.SetWindowExt(m_sizeLogAll);
+ dc.SetViewportExt(m_sizeAll);
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y);
+ }
+
+ void ViewDPtoLP(LPPOINT lpPoints, int nCount = 1)
+ {
+ ATLASSERT(lpPoints);
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ CWindowDC dc(pT->m_hWnd);
+ pT->PrepareDC(dc.m_hDC);
+ dc.DPtoLP(lpPoints, nCount);
+ }
+
+ void ViewLPtoDP(LPPOINT lpPoints, int nCount = 1)
+ {
+ ATLASSERT(lpPoints);
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+
+ CWindowDC dc(pT->m_hWnd);
+ pT->PrepareDC(dc.m_hDC);
+ dc.LPtoDP(lpPoints, nCount);
+ }
+
+ void ClientToDevice(POINT &pt)
+ {
+ pt.x += m_ptOffset.x;
+ pt.y += m_ptOffset.y;
+ }
+
+ void DeviceToClient(POINT &pt)
+ {
+ pt.x -= m_ptOffset.x;
+ pt.y -= m_ptOffset.y;
+ }
+
+ void CenterOnPoint(POINT pt)
+ {
+ T* pT = static_cast<T*>(this);
+ RECT rect;
+ pT->GetClientRect(&rect);
+
+ int xOfs = pt.x - (rect.right / 2) + m_ptOffset.x;
+ if(xOfs < 0)
+ {
+ xOfs = 0;
+ }
+ else
+ {
+ int xMax = max((int)(m_sizeAll.cx - rect.right), 0);
+ if(xOfs > xMax)
+ xOfs = xMax;
+ }
+
+ int yOfs = pt.y - (rect.bottom / 2) + m_ptOffset.y;
+ if(yOfs < 0)
+ {
+ yOfs = 0;
+ }
+ else
+ {
+ int yMax = max((int)(m_sizeAll.cy - rect.bottom), 0);
+ if(yOfs > yMax)
+ yOfs = yMax;
+ }
+
+ CScrollImpl< T >::SetScrollOffset(xOfs, yOfs);
+ }
+
+ void CenterOnLogicalPoint(POINT ptLog)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->ViewLPtoDP(&ptLog);
+ pT->DeviceToClient(ptLog);
+ pT->CenterOnPoint(ptLog);
+ }
+
+ BOOL PtInDevRect(POINT pt)
+ {
+ RECT rc = { 0, 0, m_sizeAll.cx, m_sizeAll.cy };
+ ::OffsetRect(&rc, -m_ptOffset.x, -m_ptOffset.y);
+ return ::PtInRect(&rc, pt);
+ }
+
+ void NormalizeRect(RECT& rc)
+ {
+ if(rc.left > rc.right)
+ {
+ int r = rc.right;
+ rc.right = rc.left;
+ rc.left = r;
+ }
+ if(rc.top > rc.bottom)
+ {
+ int b = rc.bottom;
+ rc.bottom = rc.top;
+ rc.top = b;
+ }
+ }
+
+ void DrawTrackRect()
+ {
+ T* pT = static_cast<T*>(this);
+ const SIZE sizeLines = { 2, 2 };
+ RECT rc = m_rcTrack;
+ pT->NormalizeRect(rc);
+ if(!::IsRectEmpty(&rc))
+ {
+ ::MapWindowPoints(pT->m_hWnd, NULL, (LPPOINT)&rc, 2);
+ CWindowDC dc(NULL);
+ dc.DrawDragRect(&rc, sizeLines, NULL, sizeLines);
+ }
+ }
+
+ void NotifyParentZoomChanged()
+ {
+ T* pT = static_cast<T*>(this);
+ int nId = pT->GetDlgCtrlID();
+ NMHDR nmhdr = { pT->m_hWnd, nId, ZSN_ZOOMCHANGED };
+ ::SendMessage(pT->GetParent(), WM_NOTIFY, (WPARAM)nId, (LPARAM)&nmhdr);
+ }
+
+ BEGIN_MSG_MAP(CZoomScrollImpl)
+ MESSAGE_HANDLER(WM_SETCURSOR, OnSetCursor)
+ MESSAGE_HANDLER(WM_VSCROLL, CScrollImpl< T >::OnVScroll)
+ MESSAGE_HANDLER(WM_HSCROLL, CScrollImpl< T >::OnHScroll)
+ MESSAGE_HANDLER(WM_MOUSEWHEEL, CScrollImpl< T >::OnMouseWheel)
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(m_uMsgMouseWheel, CScrollImpl< T >::OnMouseWheel)
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(WM_MOUSEHWHEEL, CScrollImpl< T >::OnMouseHWheel)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, CScrollImpl< T >::OnSettingChange)
+ MESSAGE_HANDLER(WM_SIZE, CScrollImpl< T >::OnSize)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+ MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
+ MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
+ MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
+ MESSAGE_HANDLER(WM_CAPTURECHANGED, OnCaptureChanged)
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_SCROLL_UP, CScrollImpl< T >::OnScrollUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_DOWN, CScrollImpl< T >::OnScrollDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_UP, CScrollImpl< T >::OnScrollPageUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_DOWN, CScrollImpl< T >::OnScrollPageDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_TOP, CScrollImpl< T >::OnScrollTop)
+ COMMAND_ID_HANDLER(ID_SCROLL_BOTTOM, CScrollImpl< T >::OnScrollBottom)
+ COMMAND_ID_HANDLER(ID_SCROLL_LEFT, CScrollImpl< T >::OnScrollLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_RIGHT, CScrollImpl< T >::OnScrollRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_LEFT, CScrollImpl< T >::OnScrollPageLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_RIGHT, CScrollImpl< T >::OnScrollPageRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_LEFT, CScrollImpl< T >::OnScrollAllLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_RIGHT, CScrollImpl< T >::OnScrollAllRight)
+ END_MSG_MAP()
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ ATLASSERT(m_sizeLogAll.cx >= 0 && m_sizeLogAll.cy >= 0);
+ ATLASSERT(m_sizeAll.cx >= 0 && m_sizeAll.cy >= 0);
+
+ if(wParam != NULL)
+ {
+ CDCHandle dc = (HDC)wParam;
+ int nMapModeSav = dc.GetMapMode();
+ dc.SetMapMode(MM_ANISOTROPIC);
+ SIZE szWindowExt = { 0, 0 };
+ dc.SetWindowExt(m_sizeLogAll, &szWindowExt);
+ SIZE szViewportExt = { 0, 0 };
+ dc.SetViewportExt(m_sizeAll, &szViewportExt);
+ POINT ptViewportOrg = { 0, 0 };
+ dc.SetViewportOrg(-m_ptOffset.x, -m_ptOffset.y, &ptViewportOrg);
+
+ pT->DoPaint(dc);
+
+ dc.SetMapMode(nMapModeSav);
+ dc.SetWindowExt(szWindowExt);
+ dc.SetViewportExt(szViewportExt);
+ dc.SetViewportOrg(ptViewportOrg);
+ }
+ else
+ {
+ CPaintDC dc(pT->m_hWnd);
+ pT->PrepareDC(dc.m_hDC);
+ pT->DoPaint(dc.m_hDC);
+ }
+ return 0;
+ }
+
+ LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(m_nZoomMode == ZOOMMODE_IN && !m_bTracking)
+ {
+ T* pT = static_cast<T*>(this);
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ if(pT->PtInDevRect(pt))
+ {
+ pT->SetCapture();
+ m_bTracking = true;
+ ::SetRect(&m_rcTrack, pt.x, pt.y, pt.x, pt.y);
+ }
+ }
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ if(m_bTracking)
+ {
+ T* pT = static_cast<T*>(this);
+ POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+ if(pT->PtInDevRect(pt))
+ {
+ pT->DrawTrackRect();
+ m_rcTrack.right = pt.x;
+ m_rcTrack.bottom = pt.y;
+ pT->DrawTrackRect();
+ }
+ }
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ ::ReleaseCapture();
+ if(m_nZoomMode == ZOOMMODE_OUT)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->Zoom(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam), m_fZoomScale - m_fZoomDelta);
+ pT->NotifyParentZoomChanged();
+ }
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnCaptureChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_bTracking)
+ {
+ m_bTracking = false;
+ T* pT = static_cast<T*>(this);
+ pT->DrawTrackRect();
+ pT->Zoom(m_rcTrack);
+ pT->NotifyParentZoomChanged();
+ ::SetRectEmpty(&m_rcTrack);
+ }
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnSetCursor(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ if(LOWORD(lParam) == HTCLIENT && m_nZoomMode != ZOOMMODE_OFF)
+ {
+ T* pT = static_cast<T*>(this);
+ if((HWND)wParam == pT->m_hWnd)
+ {
+ DWORD dwPos = ::GetMessagePos();
+ POINT pt = { GET_X_LPARAM(dwPos), GET_Y_LPARAM(dwPos) };
+ pT->ScreenToClient(&pt);
+ if(pT->PtInDevRect(pt))
+ {
+ ::SetCursor(::LoadCursor(NULL, IDC_CROSS));
+ return 1;
+ }
+ }
+ }
+ bHandled = FALSE;
+ return 0;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CZoomScrollWindowImpl - Implements scrolling window with zooming
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CZoomScrollWindowImpl : public ATL::CWindowImpl< T, TBase, TWinTraits >, public CZoomScrollImpl< T >
+{
+public:
+ BEGIN_MSG_MAP(CZoomScrollWindowImpl)
+ MESSAGE_HANDLER(WM_SETCURSOR, CZoomScrollImpl< T >::OnSetCursor)
+ MESSAGE_HANDLER(WM_VSCROLL, CScrollImpl< T >::OnVScroll)
+ MESSAGE_HANDLER(WM_HSCROLL, CScrollImpl< T >::OnHScroll)
+ MESSAGE_HANDLER(WM_MOUSEWHEEL, CScrollImpl< T >::OnMouseWheel)
+#if !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(m_uMsgMouseWheel, CScrollImpl< T >::OnMouseWheel)
+#endif // !((_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400))
+ MESSAGE_HANDLER(WM_MOUSEHWHEEL, CScrollImpl< T >::OnMouseHWheel)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, CScrollImpl< T >::OnSettingChange)
+ MESSAGE_HANDLER(WM_SIZE, CScrollImpl< T >::OnSize)
+ MESSAGE_HANDLER(WM_PAINT, CZoomScrollImpl< T >::OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, CZoomScrollImpl< T >::OnPaint)
+ MESSAGE_HANDLER(WM_LBUTTONDOWN, CZoomScrollImpl< T >::OnLButtonDown)
+ MESSAGE_HANDLER(WM_MOUSEMOVE, CZoomScrollImpl< T >::OnMouseMove)
+ MESSAGE_HANDLER(WM_LBUTTONUP, CZoomScrollImpl< T >::OnLButtonUp)
+ MESSAGE_HANDLER(WM_CAPTURECHANGED, CZoomScrollImpl< T >::OnCaptureChanged)
+ ALT_MSG_MAP(1)
+ COMMAND_ID_HANDLER(ID_SCROLL_UP, CScrollImpl< T >::OnScrollUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_DOWN, CScrollImpl< T >::OnScrollDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_UP, CScrollImpl< T >::OnScrollPageUp)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_DOWN, CScrollImpl< T >::OnScrollPageDown)
+ COMMAND_ID_HANDLER(ID_SCROLL_TOP, CScrollImpl< T >::OnScrollTop)
+ COMMAND_ID_HANDLER(ID_SCROLL_BOTTOM, CScrollImpl< T >::OnScrollBottom)
+ COMMAND_ID_HANDLER(ID_SCROLL_LEFT, CScrollImpl< T >::OnScrollLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_RIGHT, CScrollImpl< T >::OnScrollRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_LEFT, CScrollImpl< T >::OnScrollPageLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_PAGE_RIGHT, CScrollImpl< T >::OnScrollPageRight)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_LEFT, CScrollImpl< T >::OnScrollAllLeft)
+ COMMAND_ID_HANDLER(ID_SCROLL_ALL_RIGHT, CScrollImpl< T >::OnScrollAllRight)
+ END_MSG_MAP()
+};
+
+#endif // !_WIN32_WCE
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CScrollContainer
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CScrollContainerImpl : public CScrollWindowImpl< T, TBase, TWinTraits >
+{
+public:
+ DECLARE_WND_CLASS_EX(NULL, 0, -1)
+
+ typedef CScrollWindowImpl< T, TBase, TWinTraits > _baseClass;
+
+// Data members
+ ATL::CWindow m_wndClient;
+ bool m_bAutoSizeClient;
+ bool m_bDrawEdgeIfEmpty;
+
+// Constructor
+ CScrollContainerImpl() : m_bAutoSizeClient(true), m_bDrawEdgeIfEmpty(false)
+ {
+ // Set CScrollWindowImpl extended style
+ SetScrollExtendedStyle(SCRL_SCROLLCHILDREN);
+ }
+
+// Attributes
+ HWND GetClient() const
+ {
+ return m_wndClient;
+ }
+
+ HWND SetClient(HWND hWndClient, bool bClientSizeAsMin = true)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ HWND hWndOldClient = m_wndClient;
+ m_wndClient = hWndClient;
+
+ SetRedraw(FALSE);
+ SetScrollSize(1, 1, FALSE);
+
+ if(m_wndClient.m_hWnd != NULL)
+ {
+ m_wndClient.SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
+
+ if(bClientSizeAsMin)
+ {
+ RECT rect = { 0 };
+ m_wndClient.GetWindowRect(&rect);
+ if((rect.right - rect.left) > 0 && (rect.bottom - rect.top) > 0)
+ SetScrollSize(rect.right - rect.left, rect.bottom - rect.top, FALSE);
+ }
+
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+ }
+
+ SetRedraw(TRUE);
+ RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_FRAME | RDW_UPDATENOW | RDW_ALLCHILDREN);
+
+ return hWndOldClient;
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CScrollContainerImpl)
+ MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ CHAIN_MSG_MAP(_baseClass)
+ FORWARD_NOTIFICATIONS()
+ ALT_MSG_MAP(1)
+ CHAIN_MSG_MAP_ALT(_baseClass, 1)
+ END_MSG_MAP()
+
+ LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(m_wndClient.m_hWnd != NULL)
+ m_wndClient.SetFocus();
+
+ return 0;
+ }
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1; // no background needed
+ }
+
+ LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ BOOL bTmp = TRUE;
+ LRESULT lRet = _baseClass::OnSize(uMsg, wParam, lParam, bTmp);
+
+ T* pT = static_cast<T*>(this);
+ pT->UpdateLayout();
+
+ return lRet;
+ }
+
+// Overrides for CScrollWindowImpl
+ void DoPaint(CDCHandle dc)
+ {
+ if(!m_bAutoSizeClient || m_wndClient.m_hWnd == NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ RECT rect = { 0 };
+ pT->GetContainerRect(rect);
+
+ if(m_bDrawEdgeIfEmpty && m_wndClient.m_hWnd == NULL)
+ dc.DrawEdge(&rect, EDGE_SUNKEN, BF_RECT | BF_ADJUST);
+
+ dc.FillRect(&rect, COLOR_APPWORKSPACE);
+ }
+ }
+
+ void ScrollToView(POINT pt)
+ {
+ CScrollWindowImpl< T, TBase, TWinTraits >::ScrollToView(pt);
+ }
+
+ void ScrollToView(RECT& rect)
+ {
+ CScrollWindowImpl< T, TBase, TWinTraits >::ScrollToView(rect);
+ }
+
+ void ScrollToView(HWND hWnd) // client window coordinates
+ {
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ ATLASSERT(m_wndClient.IsWindow());
+
+ RECT rect = { 0 };
+ ::GetWindowRect(hWnd, &rect);
+ ::MapWindowPoints(NULL, m_wndClient.m_hWnd, (LPPOINT)&rect, 2);
+ ScrollToView(rect);
+ }
+
+// Implementation - overrideable methods
+ void UpdateLayout()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+
+ if(m_bAutoSizeClient && m_wndClient.m_hWnd != NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ RECT rect = { 0 };
+ pT->GetContainerRect(rect);
+
+ m_wndClient.SetWindowPos(NULL, &rect, SWP_NOZORDER | SWP_NOMOVE);
+ }
+ else
+ {
+ Invalidate();
+ }
+ }
+
+ void GetContainerRect(RECT& rect)
+ {
+ GetClientRect(&rect);
+
+ if(rect.right < m_sizeAll.cx)
+ rect.right = m_sizeAll.cx;
+
+ if(rect.bottom < m_sizeAll.cy)
+ rect.bottom = m_sizeAll.cy;
+ }
+};
+
+class CScrollContainer : public CScrollContainerImpl<CScrollContainer>
+{
+public:
+ DECLARE_WND_CLASS_EX(_T("WTL_ScrollContainer"), 0, -1)
+};
+
+}; // namespace WTL
+
+#endif // __ATLSCRL_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlsplit.h b/plugins/SmartAutoReplier/wtl/atlsplit.h
new file mode 100644
index 0000000000..f94fa099e9
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlsplit.h
@@ -0,0 +1,917 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLSPLIT_H__
+#define __ATLSPLIT_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlsplit.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atlsplit.h requires atlwin.h to be included first
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CSplitterImpl<T, t_bVertical>
+// CSplitterWindowImpl<T, t_bVertical, TBase, TWinTraits>
+// CSplitterWindowT<t_bVertical>
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CSplitterImpl - Provides splitter support to any window
+
+// Splitter panes constants
+#define SPLIT_PANE_LEFT 0
+#define SPLIT_PANE_RIGHT 1
+#define SPLIT_PANE_TOP SPLIT_PANE_LEFT
+#define SPLIT_PANE_BOTTOM SPLIT_PANE_RIGHT
+#define SPLIT_PANE_NONE -1
+
+// Splitter extended styles
+#define SPLIT_PROPORTIONAL 0x00000001
+#define SPLIT_NONINTERACTIVE 0x00000002
+#define SPLIT_RIGHTALIGNED 0x00000004
+#define SPLIT_BOTTOMALIGNED SPLIT_RIGHTALIGNED
+#define SPLIT_GRADIENTBAR 0x00000008
+#define SPLIT_FIXEDBARSIZE 0x00000010
+
+// Note: SPLIT_PROPORTIONAL and SPLIT_RIGHTALIGNED/SPLIT_BOTTOMALIGNED are
+// mutually exclusive. If both are set, splitter defaults to SPLIT_PROPORTIONAL
+
+
+template <class T, bool t_bVertical = true>
+class CSplitterImpl
+{
+public:
+ enum { m_nPanesCount = 2, m_nPropMax = 10000 };
+
+ HWND m_hWndPane[m_nPanesCount];
+ RECT m_rcSplitter;
+ int m_xySplitterPos;
+ int m_nDefActivePane;
+ int m_cxySplitBar; // splitter bar width/height
+ static HCURSOR m_hCursor;
+ int m_cxyMin; // minimum pane size
+ int m_cxyBarEdge; // splitter bar edge
+ bool m_bFullDrag;
+ int m_cxyDragOffset;
+ int m_nProportionalPos;
+ bool m_bUpdateProportionalPos;
+ DWORD m_dwExtendedStyle; // splitter specific extended styles
+ int m_nSinglePane; // single pane mode
+
+// Constructor
+ CSplitterImpl() :
+ m_xySplitterPos(-1), m_nDefActivePane(SPLIT_PANE_NONE),
+ m_cxySplitBar(4), m_cxyMin(0), m_cxyBarEdge(0), m_bFullDrag(true),
+ m_cxyDragOffset(0), m_nProportionalPos(0), m_bUpdateProportionalPos(true),
+ m_dwExtendedStyle(SPLIT_PROPORTIONAL),
+ m_nSinglePane(SPLIT_PANE_NONE)
+ {
+ m_hWndPane[SPLIT_PANE_LEFT] = NULL;
+ m_hWndPane[SPLIT_PANE_RIGHT] = NULL;
+
+ ::SetRectEmpty(&m_rcSplitter);
+
+ if(m_hCursor == NULL)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CSplitterImpl::CSplitterImpl.\n"));
+ ATLASSERT(FALSE);
+ return;
+ }
+
+ if(m_hCursor == NULL)
+ m_hCursor = ::LoadCursor(NULL, t_bVertical ? IDC_SIZEWE : IDC_SIZENS);
+
+ lock.Unlock();
+ }
+ }
+
+// Attributes
+ void SetSplitterRect(LPRECT lpRect = NULL, bool bUpdate = true)
+ {
+ if(lpRect == NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->GetClientRect(&m_rcSplitter);
+ }
+ else
+ {
+ m_rcSplitter = *lpRect;
+ }
+
+ if(IsProportional())
+ UpdateProportionalPos();
+ else if(IsRightAligned())
+ UpdateRightAlignPos();
+
+ if(bUpdate)
+ UpdateSplitterLayout();
+ }
+
+ void GetSplitterRect(LPRECT lpRect) const
+ {
+ ATLASSERT(lpRect != NULL);
+ *lpRect = m_rcSplitter;
+ }
+
+ bool SetSplitterPos(int xyPos = -1, bool bUpdate = true)
+ {
+ if(xyPos == -1) // -1 == middle
+ {
+ if(t_bVertical)
+ xyPos = (m_rcSplitter.right - m_rcSplitter.left - m_cxySplitBar - m_cxyBarEdge) / 2;
+ else
+ xyPos = (m_rcSplitter.bottom - m_rcSplitter.top - m_cxySplitBar - m_cxyBarEdge) / 2;
+ }
+
+ // Adjust if out of valid range
+ int cxyMax = 0;
+ if(t_bVertical)
+ cxyMax = m_rcSplitter.right - m_rcSplitter.left;
+ else
+ cxyMax = m_rcSplitter.bottom - m_rcSplitter.top;
+
+ if(xyPos < m_cxyMin + m_cxyBarEdge)
+ xyPos = m_cxyMin;
+ else if(xyPos > (cxyMax - m_cxySplitBar - m_cxyBarEdge - m_cxyMin))
+ xyPos = cxyMax - m_cxySplitBar - m_cxyBarEdge - m_cxyMin;
+
+ // Set new position and update if requested
+ bool bRet = (m_xySplitterPos != xyPos);
+ m_xySplitterPos = xyPos;
+
+ if(m_bUpdateProportionalPos)
+ {
+ if(IsProportional())
+ StoreProportionalPos();
+ else if(IsRightAligned())
+ StoreRightAlignPos();
+ }
+ else
+ {
+ m_bUpdateProportionalPos = true;
+ }
+
+ if(bUpdate && bRet)
+ UpdateSplitterLayout();
+
+ return bRet;
+ }
+
+ void SetSplitterPosPct(int nPct, bool bUpdate = true)
+ {
+ ATLASSERT(nPct >= 0 && nPct <= 100);
+
+ m_nProportionalPos = ::MulDiv(nPct, m_nPropMax, 100);
+ UpdateProportionalPos();
+
+ if(bUpdate)
+ UpdateSplitterLayout();
+ }
+
+ int GetSplitterPos() const
+ {
+ return m_xySplitterPos;
+ }
+
+ bool SetSinglePaneMode(int nPane = SPLIT_PANE_NONE)
+ {
+ ATLASSERT(nPane == SPLIT_PANE_LEFT || nPane == SPLIT_PANE_RIGHT || nPane == SPLIT_PANE_NONE);
+ if(!(nPane == SPLIT_PANE_LEFT || nPane == SPLIT_PANE_RIGHT || nPane == SPLIT_PANE_NONE))
+ return false;
+
+ if(nPane != SPLIT_PANE_NONE)
+ {
+ if(!::IsWindowVisible(m_hWndPane[nPane]))
+ ::ShowWindow(m_hWndPane[nPane], SW_SHOW);
+ int nOtherPane = (nPane == SPLIT_PANE_LEFT) ? SPLIT_PANE_RIGHT : SPLIT_PANE_LEFT;
+ ::ShowWindow(m_hWndPane[nOtherPane], SW_HIDE);
+ if(m_nDefActivePane != nPane)
+ m_nDefActivePane = nPane;
+ }
+ else if(m_nSinglePane != SPLIT_PANE_NONE)
+ {
+ int nOtherPane = (m_nSinglePane == SPLIT_PANE_LEFT) ? SPLIT_PANE_RIGHT : SPLIT_PANE_LEFT;
+ ::ShowWindow(m_hWndPane[nOtherPane], SW_SHOW);
+ }
+
+ m_nSinglePane = nPane;
+ UpdateSplitterLayout();
+ return true;
+ }
+
+ int GetSinglePaneMode() const
+ {
+ return m_nSinglePane;
+ }
+
+ DWORD GetSplitterExtendedStyle() const
+ {
+ return m_dwExtendedStyle;
+ }
+
+ DWORD SetSplitterExtendedStyle(DWORD dwExtendedStyle, DWORD dwMask = 0)
+ {
+ DWORD dwPrevStyle = m_dwExtendedStyle;
+ if(dwMask == 0)
+ m_dwExtendedStyle = dwExtendedStyle;
+ else
+ m_dwExtendedStyle = (m_dwExtendedStyle & ~dwMask) | (dwExtendedStyle & dwMask);
+#ifdef _DEBUG
+ if(IsProportional() && IsRightAligned())
+ ATLTRACE2(atlTraceUI, 0, _T("CSplitterImpl::SetSplitterExtendedStyle - SPLIT_PROPORTIONAL and SPLIT_RIGHTALIGNED are mutually exclusive, defaulting to SPLIT_PROPORTIONAL.\n"));
+#endif // _DEBUG
+ return dwPrevStyle;
+ }
+
+// Splitter operations
+ void SetSplitterPanes(HWND hWndLeftTop, HWND hWndRightBottom, bool bUpdate = true)
+ {
+ m_hWndPane[SPLIT_PANE_LEFT] = hWndLeftTop;
+ m_hWndPane[SPLIT_PANE_RIGHT] = hWndRightBottom;
+ ATLASSERT(m_hWndPane[SPLIT_PANE_LEFT] == NULL || m_hWndPane[SPLIT_PANE_RIGHT] == NULL || m_hWndPane[SPLIT_PANE_LEFT] != m_hWndPane[SPLIT_PANE_RIGHT]);
+ if(bUpdate)
+ UpdateSplitterLayout();
+ }
+
+ bool SetSplitterPane(int nPane, HWND hWnd, bool bUpdate = true)
+ {
+ ATLASSERT(nPane == SPLIT_PANE_LEFT || nPane == SPLIT_PANE_RIGHT);
+
+ if(nPane != SPLIT_PANE_LEFT && nPane != SPLIT_PANE_RIGHT)
+ return false;
+ m_hWndPane[nPane] = hWnd;
+ ATLASSERT(m_hWndPane[SPLIT_PANE_LEFT] == NULL || m_hWndPane[SPLIT_PANE_RIGHT] == NULL || m_hWndPane[SPLIT_PANE_LEFT] != m_hWndPane[SPLIT_PANE_RIGHT]);
+ if(bUpdate)
+ UpdateSplitterLayout();
+ return true;
+ }
+
+ HWND GetSplitterPane(int nPane) const
+ {
+ ATLASSERT(nPane == SPLIT_PANE_LEFT || nPane == SPLIT_PANE_RIGHT);
+
+ if(nPane != SPLIT_PANE_LEFT && nPane != SPLIT_PANE_RIGHT)
+ return false;
+ return m_hWndPane[nPane];
+ }
+
+ bool SetActivePane(int nPane)
+ {
+ ATLASSERT(nPane == SPLIT_PANE_LEFT || nPane == SPLIT_PANE_RIGHT);
+
+ if(nPane != SPLIT_PANE_LEFT && nPane != SPLIT_PANE_RIGHT)
+ return false;
+ if(m_nSinglePane != SPLIT_PANE_NONE && nPane != m_nSinglePane)
+ return false;
+ ::SetFocus(m_hWndPane[nPane]);
+ m_nDefActivePane = nPane;
+ return true;
+ }
+
+ int GetActivePane() const
+ {
+ int nRet = SPLIT_PANE_NONE;
+ HWND hWndFocus = ::GetFocus();
+ if(hWndFocus != NULL)
+ {
+ for(int nPane = 0; nPane < m_nPanesCount; nPane++)
+ {
+ if(hWndFocus == m_hWndPane[nPane] || ::IsChild(m_hWndPane[nPane], hWndFocus))
+ {
+ nRet = nPane;
+ break;
+ }
+ }
+ }
+ return nRet;
+ }
+
+ bool ActivateNextPane(bool bNext = true)
+ {
+ int nPane = m_nSinglePane;
+ if(nPane == SPLIT_PANE_NONE)
+ {
+ switch(GetActivePane())
+ {
+ case SPLIT_PANE_LEFT:
+ nPane = SPLIT_PANE_RIGHT;
+ break;
+ case SPLIT_PANE_RIGHT:
+ nPane = SPLIT_PANE_LEFT;
+ break;
+ default:
+ nPane = bNext ? SPLIT_PANE_LEFT : SPLIT_PANE_RIGHT;
+ break;
+ }
+ }
+ return SetActivePane(nPane);
+ }
+
+ bool SetDefaultActivePane(int nPane)
+ {
+ ATLASSERT(nPane == SPLIT_PANE_LEFT || nPane == SPLIT_PANE_RIGHT);
+
+ if(nPane != SPLIT_PANE_LEFT && nPane != SPLIT_PANE_RIGHT)
+ return false;
+ m_nDefActivePane = nPane;
+ return true;
+ }
+
+ bool SetDefaultActivePane(HWND hWnd)
+ {
+ for(int nPane = 0; nPane < m_nPanesCount; nPane++)
+ {
+ if(hWnd == m_hWndPane[nPane])
+ {
+ m_nDefActivePane = nPane;
+ return true;
+ }
+ }
+ return false; // not found
+ }
+
+ int GetDefaultActivePane() const
+ {
+ return m_nDefActivePane;
+ }
+
+ void DrawSplitter(CDCHandle dc)
+ {
+ ATLASSERT(dc.m_hDC != NULL);
+ if(m_nSinglePane == SPLIT_PANE_NONE && m_xySplitterPos == -1)
+ return;
+
+ T* pT = static_cast<T*>(this);
+ if(m_nSinglePane == SPLIT_PANE_NONE)
+ {
+ pT->DrawSplitterBar(dc);
+
+ for(int nPane = 0; nPane < m_nPanesCount; nPane++)
+ {
+ if(m_hWndPane[nPane] == NULL)
+ pT->DrawSplitterPane(dc, nPane);
+ }
+ }
+ else
+ {
+ if(m_hWndPane[m_nSinglePane] == NULL)
+ pT->DrawSplitterPane(dc, m_nSinglePane);
+ }
+ }
+
+// Overrideables
+ void DrawSplitterBar(CDCHandle dc)
+ {
+ RECT rect = { 0 };
+ if(GetSplitterBarRect(&rect))
+ {
+ dc.FillRect(&rect, COLOR_3DFACE);
+
+#if (!defined(_WIN32_WCE) || (_WIN32_WCE >= 420))
+ if((m_dwExtendedStyle & SPLIT_GRADIENTBAR) != 0)
+ {
+ RECT rect2 = rect;
+ if(t_bVertical)
+ rect2.left = (rect.left + rect.right) / 2 - 1;
+ else
+ rect2.top = (rect.top + rect.bottom) / 2 - 1;
+
+ dc.GradientFillRect(rect2, ::GetSysColor(COLOR_3DFACE), ::GetSysColor(COLOR_3DSHADOW), t_bVertical);
+ }
+#endif // !defined(_WIN32_WCE) || (_WIN32_WCE >= 420)
+
+ // draw 3D edge if needed
+ T* pT = static_cast<T*>(this);
+ if((pT->GetExStyle() & WS_EX_CLIENTEDGE) != 0)
+ dc.DrawEdge(&rect, EDGE_RAISED, t_bVertical ? (BF_LEFT | BF_RIGHT) : (BF_TOP | BF_BOTTOM));
+ }
+ }
+
+ // called only if pane is empty
+ void DrawSplitterPane(CDCHandle dc, int nPane)
+ {
+ RECT rect = { 0 };
+ if(GetSplitterPaneRect(nPane, &rect))
+ {
+ T* pT = static_cast<T*>(this);
+ if((pT->GetExStyle() & WS_EX_CLIENTEDGE) == 0)
+ dc.DrawEdge(&rect, EDGE_SUNKEN, BF_RECT | BF_ADJUST);
+ dc.FillRect(&rect, COLOR_APPWORKSPACE);
+ }
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CSplitterImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+#endif // !_WIN32_WCE
+ if(IsInteractive())
+ {
+ MESSAGE_HANDLER(WM_SETCURSOR, OnSetCursor)
+ MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
+ MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
+ MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
+ MESSAGE_HANDLER(WM_LBUTTONDBLCLK, OnLButtonDoubleClick)
+ MESSAGE_HANDLER(WM_CAPTURECHANGED, OnCaptureChanged)
+ }
+ MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus)
+#ifndef _WIN32_WCE
+ MESSAGE_HANDLER(WM_MOUSEACTIVATE, OnMouseActivate)
+#endif // !_WIN32_WCE
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->GetSystemSettings(false);
+
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ // try setting position if not set
+ if(m_nSinglePane == SPLIT_PANE_NONE && m_xySplitterPos == -1)
+ pT->SetSplitterPos();
+ // do painting
+ CPaintDC dc(pT->m_hWnd);
+ pT->DrawSplitter(dc.m_hDC);
+ return 0;
+ }
+
+ LRESULT OnSetCursor(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ if((HWND)wParam == pT->m_hWnd && LOWORD(lParam) == HTCLIENT)
+ {
+ DWORD dwPos = ::GetMessagePos();
+ POINT ptPos = { GET_X_LPARAM(dwPos), GET_Y_LPARAM(dwPos) };
+ pT->ScreenToClient(&ptPos);
+ if(IsOverSplitterBar(ptPos.x, ptPos.y))
+ return 1;
+ }
+
+ bHandled = FALSE;
+ return 0;
+ }
+
+ LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ int xPos = GET_X_LPARAM(lParam);
+ int yPos = GET_Y_LPARAM(lParam);
+ if((wParam & MK_LBUTTON) && ::GetCapture() == pT->m_hWnd)
+ {
+ int xyNewSplitPos = 0;
+ if(t_bVertical)
+ xyNewSplitPos = xPos - m_rcSplitter.left - m_cxyDragOffset;
+ else
+ xyNewSplitPos = yPos - m_rcSplitter.top - m_cxyDragOffset;
+
+ if(xyNewSplitPos == -1) // avoid -1, that means middle
+ xyNewSplitPos = -2;
+
+ if(m_xySplitterPos != xyNewSplitPos)
+ {
+ if(m_bFullDrag)
+ {
+ if(pT->SetSplitterPos(xyNewSplitPos, true))
+ pT->UpdateWindow();
+ }
+ else
+ {
+ DrawGhostBar();
+ pT->SetSplitterPos(xyNewSplitPos, false);
+ DrawGhostBar();
+ }
+ }
+ }
+ else // not dragging, just set cursor
+ {
+ if(IsOverSplitterBar(xPos, yPos))
+ ::SetCursor(m_hCursor);
+ bHandled = FALSE;
+ }
+
+ return 0;
+ }
+
+ LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
+ {
+ int xPos = GET_X_LPARAM(lParam);
+ int yPos = GET_Y_LPARAM(lParam);
+ if(IsOverSplitterBar(xPos, yPos))
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetCapture();
+ ::SetCursor(m_hCursor);
+ if(!m_bFullDrag)
+ DrawGhostBar();
+ if(t_bVertical)
+ m_cxyDragOffset = xPos - m_rcSplitter.left - m_xySplitterPos;
+ else
+ m_cxyDragOffset = yPos - m_rcSplitter.top - m_xySplitterPos;
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ ::ReleaseCapture();
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnLButtonDoubleClick(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetSplitterPos(); // middle
+ return 0;
+ }
+
+ LRESULT OnCaptureChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ if(!m_bFullDrag)
+ {
+ DrawGhostBar();
+ UpdateSplitterLayout();
+ T* pT = static_cast<T*>(this);
+ pT->UpdateWindow();
+ }
+ return 0;
+ }
+
+ LRESULT OnSetFocus(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM, BOOL& bHandled)
+ {
+ if(m_nSinglePane == SPLIT_PANE_NONE)
+ {
+ if(m_nDefActivePane == SPLIT_PANE_LEFT || m_nDefActivePane == SPLIT_PANE_RIGHT)
+ ::SetFocus(m_hWndPane[m_nDefActivePane]);
+ }
+ else
+ {
+ ::SetFocus(m_hWndPane[m_nSinglePane]);
+ }
+ bHandled = FALSE;
+ return 1;
+ }
+
+#ifndef _WIN32_WCE
+ LRESULT OnMouseActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ LRESULT lRet = pT->DefWindowProc(uMsg, wParam, lParam);
+ if(lRet == MA_ACTIVATE || lRet == MA_ACTIVATEANDEAT)
+ {
+ DWORD dwPos = ::GetMessagePos();
+ POINT pt = { GET_X_LPARAM(dwPos), GET_Y_LPARAM(dwPos) };
+ pT->ScreenToClient(&pt);
+ RECT rcPane = { 0 };
+ for(int nPane = 0; nPane < m_nPanesCount; nPane++)
+ {
+ if(GetSplitterPaneRect(nPane, &rcPane) && ::PtInRect(&rcPane, pt))
+ {
+ m_nDefActivePane = nPane;
+ break;
+ }
+ }
+ }
+ return lRet;
+ }
+#endif // !_WIN32_WCE
+
+ LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->GetSystemSettings(true);
+
+ return 0;
+ }
+
+// Implementation - internal helpers
+ void UpdateSplitterLayout()
+ {
+ if(m_nSinglePane == SPLIT_PANE_NONE && m_xySplitterPos == -1)
+ return;
+
+ T* pT = static_cast<T*>(this);
+ RECT rect = { 0 };
+ if(m_nSinglePane == SPLIT_PANE_NONE)
+ {
+ if(GetSplitterBarRect(&rect))
+ pT->InvalidateRect(&rect);
+
+ for(int nPane = 0; nPane < m_nPanesCount; nPane++)
+ {
+ if(GetSplitterPaneRect(nPane, &rect))
+ {
+ if(m_hWndPane[nPane] != NULL)
+ ::SetWindowPos(m_hWndPane[nPane], NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER);
+ else
+ pT->InvalidateRect(&rect);
+ }
+ }
+ }
+ else
+ {
+ if(GetSplitterPaneRect(m_nSinglePane, &rect))
+ {
+ if(m_hWndPane[m_nSinglePane] != NULL)
+ ::SetWindowPos(m_hWndPane[m_nSinglePane], NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER);
+ else
+ pT->InvalidateRect(&rect);
+ }
+ }
+ }
+
+ bool GetSplitterBarRect(LPRECT lpRect) const
+ {
+ ATLASSERT(lpRect != NULL);
+ if(m_nSinglePane != SPLIT_PANE_NONE || m_xySplitterPos == -1)
+ return false;
+
+ if(t_bVertical)
+ {
+ lpRect->left = m_rcSplitter.left + m_xySplitterPos;
+ lpRect->top = m_rcSplitter.top;
+ lpRect->right = m_rcSplitter.left + m_xySplitterPos + m_cxySplitBar + m_cxyBarEdge;
+ lpRect->bottom = m_rcSplitter.bottom;
+ }
+ else
+ {
+ lpRect->left = m_rcSplitter.left;
+ lpRect->top = m_rcSplitter.top + m_xySplitterPos;
+ lpRect->right = m_rcSplitter.right;
+ lpRect->bottom = m_rcSplitter.top + m_xySplitterPos + m_cxySplitBar + m_cxyBarEdge;
+ }
+
+ return true;
+ }
+
+ bool GetSplitterPaneRect(int nPane, LPRECT lpRect) const
+ {
+ ATLASSERT(nPane == SPLIT_PANE_LEFT || nPane == SPLIT_PANE_RIGHT);
+ ATLASSERT(lpRect != NULL);
+ bool bRet = true;
+ if(m_nSinglePane != SPLIT_PANE_NONE)
+ {
+ if(nPane == m_nSinglePane)
+ *lpRect = m_rcSplitter;
+ else
+ bRet = false;
+ }
+ else if(nPane == SPLIT_PANE_LEFT)
+ {
+ if(t_bVertical)
+ {
+ lpRect->left = m_rcSplitter.left;
+ lpRect->top = m_rcSplitter.top;
+ lpRect->right = m_rcSplitter.left + m_xySplitterPos;
+ lpRect->bottom = m_rcSplitter.bottom;
+ }
+ else
+ {
+ lpRect->left = m_rcSplitter.left;
+ lpRect->top = m_rcSplitter.top;
+ lpRect->right = m_rcSplitter.right;
+ lpRect->bottom = m_rcSplitter.top + m_xySplitterPos;
+ }
+ }
+ else if(nPane == SPLIT_PANE_RIGHT)
+ {
+ if(t_bVertical)
+ {
+ lpRect->left = m_rcSplitter.left + m_xySplitterPos + m_cxySplitBar + m_cxyBarEdge;
+ lpRect->top = m_rcSplitter.top;
+ lpRect->right = m_rcSplitter.right;
+ lpRect->bottom = m_rcSplitter.bottom;
+ }
+ else
+ {
+ lpRect->left = m_rcSplitter.left;
+ lpRect->top = m_rcSplitter.top + m_xySplitterPos + m_cxySplitBar + m_cxyBarEdge;
+ lpRect->right = m_rcSplitter.right;
+ lpRect->bottom = m_rcSplitter.bottom;
+ }
+ }
+ else
+ {
+ bRet = false;
+ }
+ return bRet;
+ }
+
+ bool IsOverSplitterRect(int x, int y) const
+ {
+ // -1 == don't check
+ return ((x == -1 || (x >= m_rcSplitter.left && x <= m_rcSplitter.right)) &&
+ (y == -1 || (y >= m_rcSplitter.top && y <= m_rcSplitter.bottom)));
+ }
+
+ bool IsOverSplitterBar(int x, int y) const
+ {
+ if(m_nSinglePane != SPLIT_PANE_NONE)
+ return false;
+ if(m_xySplitterPos == -1 || !IsOverSplitterRect(x, y))
+ return false;
+ int xy = t_bVertical ? x : y;
+ int xyOff = t_bVertical ? m_rcSplitter.left : m_rcSplitter.top;
+ return ((xy >= (xyOff + m_xySplitterPos)) && (xy < xyOff + m_xySplitterPos + m_cxySplitBar + m_cxyBarEdge));
+ }
+
+ void DrawGhostBar()
+ {
+ RECT rect = { 0 };
+ if(GetSplitterBarRect(&rect))
+ {
+ // convert client to window coordinates
+ T* pT = static_cast<T*>(this);
+ RECT rcWnd = { 0 };
+ pT->GetWindowRect(&rcWnd);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rcWnd, 2);
+ ::OffsetRect(&rect, -rcWnd.left, -rcWnd.top);
+
+ // invert the brush pattern (looks just like frame window sizing)
+ CWindowDC dc(pT->m_hWnd);
+ CBrush brush = CDCHandle::GetHalftoneBrush();
+ if(brush.m_hBrush != NULL)
+ {
+ CBrushHandle brushOld = dc.SelectBrush(brush);
+ dc.PatBlt(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, PATINVERT);
+ dc.SelectBrush(brushOld);
+ }
+ }
+ }
+
+ void GetSystemSettings(bool bUpdate)
+ {
+ if((m_dwExtendedStyle & SPLIT_FIXEDBARSIZE) == 0)
+ {
+#ifndef _WIN32_WCE
+ m_cxySplitBar = ::GetSystemMetrics(t_bVertical ? SM_CXSIZEFRAME : SM_CYSIZEFRAME);
+#else // CE specific
+ m_cxySplitBar = 2 * ::GetSystemMetrics(t_bVertical ? SM_CXEDGE : SM_CYEDGE);
+#endif // _WIN32_WCE
+ }
+
+ T* pT = static_cast<T*>(this);
+ if((pT->GetExStyle() & WS_EX_CLIENTEDGE))
+ {
+ m_cxyBarEdge = 2 * ::GetSystemMetrics(t_bVertical ? SM_CXEDGE : SM_CYEDGE);
+ m_cxyMin = 0;
+ }
+ else
+ {
+ m_cxyBarEdge = 0;
+ m_cxyMin = 2 * ::GetSystemMetrics(t_bVertical ? SM_CXEDGE : SM_CYEDGE);
+ }
+
+#ifndef _WIN32_WCE
+ ::SystemParametersInfo(SPI_GETDRAGFULLWINDOWS, 0, &m_bFullDrag, 0);
+#endif // !_WIN32_WCE
+
+ if(bUpdate)
+ UpdateSplitterLayout();
+ }
+
+ bool IsProportional() const
+ {
+ return ((m_dwExtendedStyle & SPLIT_PROPORTIONAL) != 0);
+ }
+
+ void StoreProportionalPos()
+ {
+ int cxyTotal = t_bVertical ? (m_rcSplitter.right - m_rcSplitter.left - m_cxySplitBar - m_cxyBarEdge) : (m_rcSplitter.bottom - m_rcSplitter.top - m_cxySplitBar - m_cxyBarEdge);
+ if(cxyTotal > 0)
+ m_nProportionalPos = ::MulDiv(m_xySplitterPos, m_nPropMax, cxyTotal);
+ else
+ m_nProportionalPos = 0;
+ ATLTRACE2(atlTraceUI, 0, _T("CSplitterImpl::StoreProportionalPos - %i\n"), m_nProportionalPos);
+ }
+
+ void UpdateProportionalPos()
+ {
+ int cxyTotal = t_bVertical ? (m_rcSplitter.right - m_rcSplitter.left - m_cxySplitBar - m_cxyBarEdge) : (m_rcSplitter.bottom - m_rcSplitter.top - m_cxySplitBar - m_cxyBarEdge);
+ if(cxyTotal > 0)
+ {
+ int xyNewPos = ::MulDiv(m_nProportionalPos, cxyTotal, m_nPropMax);
+ m_bUpdateProportionalPos = false;
+ T* pT = static_cast<T*>(this);
+ pT->SetSplitterPos(xyNewPos, false);
+ }
+ }
+
+ bool IsRightAligned() const
+ {
+ return ((m_dwExtendedStyle & SPLIT_RIGHTALIGNED) != 0);
+ }
+
+ void StoreRightAlignPos()
+ {
+ int cxyTotal = t_bVertical ? (m_rcSplitter.right - m_rcSplitter.left - m_cxySplitBar - m_cxyBarEdge) : (m_rcSplitter.bottom - m_rcSplitter.top - m_cxySplitBar - m_cxyBarEdge);
+ if(cxyTotal > 0)
+ m_nProportionalPos = cxyTotal - m_xySplitterPos;
+ else
+ m_nProportionalPos = 0;
+ ATLTRACE2(atlTraceUI, 0, _T("CSplitterImpl::StoreRightAlignPos - %i\n"), m_nProportionalPos);
+ }
+
+ void UpdateRightAlignPos()
+ {
+ int cxyTotal = t_bVertical ? (m_rcSplitter.right - m_rcSplitter.left - m_cxySplitBar - m_cxyBarEdge) : (m_rcSplitter.bottom - m_rcSplitter.top - m_cxySplitBar - m_cxyBarEdge);
+ if(cxyTotal > 0)
+ {
+ m_bUpdateProportionalPos = false;
+ T* pT = static_cast<T*>(this);
+ pT->SetSplitterPos(cxyTotal - m_nProportionalPos, false);
+ }
+ }
+
+ bool IsInteractive() const
+ {
+ return ((m_dwExtendedStyle & SPLIT_NONINTERACTIVE) == 0);
+ }
+};
+
+template <class T, bool t_bVertical> HCURSOR CSplitterImpl< T, t_bVertical>::m_hCursor = NULL;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CSplitterWindowImpl - Implements a splitter window
+
+template <class T, bool t_bVertical = true, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CSplitterWindowImpl : public ATL::CWindowImpl< T, TBase, TWinTraits >, public CSplitterImpl< T , t_bVertical >
+{
+public:
+ DECLARE_WND_CLASS_EX(NULL, CS_DBLCLKS, COLOR_WINDOW)
+
+ typedef CSplitterImpl< T , t_bVertical > _baseClass;
+
+ BEGIN_MSG_MAP(CSplitterWindowImpl)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_SIZE, OnSize)
+ CHAIN_MSG_MAP(_baseClass)
+ FORWARD_NOTIFICATIONS()
+ END_MSG_MAP()
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ // handled, no background painting needed
+ return 1;
+ }
+
+ LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(wParam != SIZE_MINIMIZED)
+ SetSplitterRect();
+
+ bHandled = FALSE;
+ return 1;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CSplitterWindow - Implements a splitter window to be used as is
+
+template <bool t_bVertical = true>
+class CSplitterWindowT : public CSplitterWindowImpl<CSplitterWindowT<t_bVertical>, t_bVertical>
+{
+public:
+ DECLARE_WND_CLASS_EX(_T("WTL_SplitterWindow"), CS_DBLCLKS, COLOR_WINDOW)
+};
+
+typedef CSplitterWindowT<true> CSplitterWindow;
+typedef CSplitterWindowT<false> CHorSplitterWindow;
+
+}; // namespace WTL
+
+#endif // __ATLSPLIT_H__
diff --git a/plugins/SmartAutoReplier/wtl/atltheme.h b/plugins/SmartAutoReplier/wtl/atltheme.h
new file mode 100644
index 0000000000..ff7ee59817
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atltheme.h
@@ -0,0 +1,1218 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLTHEME_H__
+#define __ATLTHEME_H__
+
+#pragma once
+
+#ifdef _WIN32_WCE
+ #error atltheme.h is not supported on Windows CE
+#endif
+
+#ifndef __ATLAPP_H__
+ #error atltheme.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atltheme.h requires atlwin.h to be included first
+#endif
+
+#if (_WIN32_WINNT < 0x0501)
+ #error atltheme.h requires _WIN32_WINNT >= 0x0501
+#endif // (_WIN32_WINNT < 0x0501)
+
+#if defined(_WTL_USE_VSSYM32) || (defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN))
+ #include <vssym32.h>
+#else
+ #ifndef TMSCHEMA_H
+ #include <tmschema.h>
+ #endif
+#endif
+
+#ifndef _UXTHEME_H_
+#include <uxtheme.h>
+#endif
+#pragma comment(lib, "uxtheme.lib")
+
+// Note: To create an application that also runs on older versions of Windows,
+// use delay load of uxtheme.dll and ensure that no calls to the Theme API are
+// made if theming is not supported. It is enough to check if m_hTheme is NULL.
+// Example:
+// if(m_hTheme != NULL)
+// {
+// DrawThemeBackground(dc, BP_PUSHBUTTON, PBS_NORMAL, &rect, NULL);
+// DrawThemeText(dc, BP_PUSHBUTTON, PBS_NORMAL, L"Button", -1, DT_SINGLELINE | DT_CENTER | DT_VCENTER, 0, &rect);
+// }
+// else
+// {
+// dc.DrawFrameControl(&rect, DFC_BUTTON, DFCS_BUTTONPUSH);
+// dc.DrawText(_T("Button"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
+// }
+//
+// Delay load is NOT AUTOMATIC for VC++ 7, you have to link to delayimp.lib,
+// and add uxtheme.dll in the Linker.Input.Delay Loaded DLLs section of the
+// project properties.
+#if (_MSC_VER < 1300) && !defined(_WTL_NO_THEME_DELAYLOAD)
+ #pragma comment(lib, "delayimp.lib")
+ #pragma comment(linker, "/delayload:uxtheme.dll")
+#endif // (_MSC_VER < 1300) && !defined(_WTL_NO_THEME_DELAYLOAD)
+
+// Hack: Signatures in uxtheme.h changed - the only way to check which variant of uxtheme.h
+// is included is to check for presence of new defines MAX_THEMECOLOR and MAX_THEMESIZE
+#ifndef _WTL_NEW_UXTHEME
+ #if defined(MAX_THEMECOLOR) && defined(MAX_THEMESIZE)
+ #define _WTL_NEW_UXTHEME
+ #endif // defined(MAX_THEMECOLOR) && defined(MAX_THEMESIZE)
+#endif // _WTL_NEW_UXTHEME
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CTheme
+// CThemeImpl<T, TBase>
+//
+// CBufferedPaint
+// CBufferedPaintImpl<T>
+// CBufferedPaintWindowImpl<T, TBase, TWinTraits>
+// CBufferedAnimation
+// CBufferedAnimationImpl<T, TState>
+// CBufferedAnimationWindowImpl<T, TState, TBase, TWinTraits>
+//
+// Global functions:
+// AtlDrawThemeClientEdge()
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// CTheme - wrapper for theme handle
+
+class CTheme
+{
+public:
+// Data members
+ HTHEME m_hTheme;
+ static int m_nIsThemingSupported;
+
+// Constructor
+ CTheme(HTHEME hTheme = NULL) : m_hTheme(hTheme)
+ {
+ IsThemingSupported();
+ }
+
+// Operators and helpers
+ bool IsThemeNull() const
+ {
+ return (m_hTheme == NULL);
+ }
+
+ CTheme& operator =(HTHEME hTheme)
+ {
+ m_hTheme = hTheme;
+ return *this;
+ }
+
+ operator HTHEME() const
+ {
+ return m_hTheme;
+ }
+
+ void Attach(HTHEME hTheme)
+ {
+ m_hTheme = hTheme;
+ }
+
+ HTHEME Detach()
+ {
+ HTHEME hTheme = m_hTheme;
+ m_hTheme = NULL;
+ return hTheme;
+ }
+
+// Theme support helper
+ static bool IsThemingSupported()
+ {
+ if(m_nIsThemingSupported == -1)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CTheme::IsThemingSupported.\n"));
+ ATLASSERT(FALSE);
+ return false;
+ }
+
+ if(m_nIsThemingSupported == -1)
+ {
+ HMODULE hThemeDLL = ::LoadLibrary(_T("uxtheme.dll"));
+ m_nIsThemingSupported = (hThemeDLL != NULL) ? 1 : 0;
+ if(hThemeDLL != NULL)
+ ::FreeLibrary(hThemeDLL);
+ }
+
+ lock.Unlock();
+ }
+
+ ATLASSERT(m_nIsThemingSupported != -1);
+ return (m_nIsThemingSupported == 1);
+ }
+
+// Operations and theme properties
+ HTHEME OpenThemeData(HWND hWnd, LPCWSTR pszClassList)
+ {
+ if(!IsThemingSupported())
+ return NULL;
+
+ ATLASSERT(m_hTheme == NULL);
+ m_hTheme = ::OpenThemeData(hWnd, pszClassList);
+ return m_hTheme;
+ }
+
+ HRESULT CloseThemeData()
+ {
+ HRESULT hRet = S_FALSE;
+ if(m_hTheme != NULL)
+ {
+ hRet = ::CloseThemeData(m_hTheme);
+ if(SUCCEEDED(hRet))
+ m_hTheme = NULL;
+ }
+ return hRet;
+ }
+
+ HRESULT DrawThemeBackground(HDC hDC, int nPartID, int nStateID, LPCRECT pRect, LPCRECT pClipRect = NULL)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::DrawThemeBackground(m_hTheme, hDC, nPartID, nStateID, pRect, pClipRect);
+ }
+
+ HRESULT DrawThemeBackgroundEx(HDC hDC, int nPartID, int nStateID, LPCRECT pRect, const DTBGOPTS* pOptions = NULL)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::DrawThemeBackgroundEx(m_hTheme, hDC, nPartID, nStateID, pRect, pOptions);
+ }
+
+ HRESULT DrawThemeText(HDC hDC, int nPartID, int nStateID, LPCWSTR pszText, int nCharCount, DWORD dwTextFlags, DWORD dwTextFlags2, LPCRECT pRect)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::DrawThemeText(m_hTheme, hDC, nPartID, nStateID, pszText, nCharCount, dwTextFlags, dwTextFlags2, pRect);
+ }
+
+ HRESULT GetThemeBackgroundContentRect(HDC hDC, int nPartID, int nStateID, LPCRECT pBoundingRect, LPRECT pContentRect) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeBackgroundContentRect(m_hTheme, hDC, nPartID, nStateID, pBoundingRect, pContentRect);
+ }
+
+ HRESULT GetThemeBackgroundExtent(HDC hDC, int nPartID, int nStateID, LPCRECT pContentRect, LPRECT pExtentRect) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeBackgroundExtent(m_hTheme, hDC, nPartID, nStateID, pContentRect, pExtentRect);
+ }
+
+ HRESULT GetThemePartSize(HDC hDC, int nPartID, int nStateID, LPRECT pRect, enum THEMESIZE eSize, LPSIZE pSize) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemePartSize(m_hTheme, hDC, nPartID, nStateID, pRect, eSize, pSize);
+ }
+
+ HRESULT GetThemeTextExtent(HDC hDC, int nPartID, int nStateID, LPCWSTR pszText, int nCharCount, DWORD dwTextFlags, LPCRECT pBoundingRect, LPRECT pExtentRect) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeTextExtent(m_hTheme, hDC, nPartID, nStateID, pszText, nCharCount, dwTextFlags, pBoundingRect, pExtentRect);
+ }
+
+ HRESULT GetThemeTextMetrics(HDC hDC, int nPartID, int nStateID, PTEXTMETRICW pTextMetric) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+#ifdef _WTL_NEW_UXTHEME
+ return ::GetThemeTextMetrics(m_hTheme, hDC, nPartID, nStateID, pTextMetric);
+#else // !_WTL_NEW_UXTHEME
+ // Note: The cast to PTEXTMETRIC is because uxtheme.h incorrectly uses it instead of PTEXTMETRICW
+ return ::GetThemeTextMetrics(m_hTheme, hDC, nPartID, nStateID, (PTEXTMETRIC)pTextMetric);
+#endif // !_WTL_NEW_UXTHEME
+ }
+
+ HRESULT GetThemeBackgroundRegion(HDC hDC, int nPartID, int nStateID, LPCRECT pRect, HRGN* pRegion) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeBackgroundRegion(m_hTheme, hDC, nPartID, nStateID, pRect, pRegion);
+ }
+
+ HRESULT HitTestThemeBackground(HDC hDC, int nPartID, int nStateID, DWORD dwOptions, LPCRECT pRect, HRGN hrgn, POINT ptTest, WORD* pwHitTestCode) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::HitTestThemeBackground(m_hTheme, hDC, nPartID, nStateID, dwOptions, pRect, hrgn, ptTest, pwHitTestCode);
+ }
+
+ HRESULT DrawThemeEdge(HDC hDC, int nPartID, int nStateID, LPCRECT pDestRect, UINT uEdge, UINT uFlags, LPRECT pContentRect = NULL)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::DrawThemeEdge(m_hTheme, hDC, nPartID, nStateID, pDestRect, uEdge, uFlags, pContentRect);
+ }
+
+ HRESULT DrawThemeIcon(HDC hDC, int nPartID, int nStateID, LPCRECT pRect, HIMAGELIST himl, int nImageIndex)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::DrawThemeIcon(m_hTheme, hDC, nPartID, nStateID, pRect, himl, nImageIndex);
+ }
+
+ BOOL IsThemePartDefined(int nPartID, int nStateID) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::IsThemePartDefined(m_hTheme, nPartID, nStateID);
+ }
+
+ BOOL IsThemeBackgroundPartiallyTransparent(int nPartID, int nStateID) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::IsThemeBackgroundPartiallyTransparent(m_hTheme, nPartID, nStateID);
+ }
+
+ HRESULT GetThemeColor(int nPartID, int nStateID, int nPropID, COLORREF* pColor) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeColor(m_hTheme, nPartID, nStateID, nPropID, pColor);
+ }
+
+ HRESULT GetThemeMetric(HDC hDC, int nPartID, int nStateID, int nPropID, int* pnVal) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeMetric(m_hTheme, hDC, nPartID, nStateID, nPropID, pnVal);
+ }
+
+ HRESULT GetThemeString(int nPartID, int nStateID, int nPropID, LPWSTR pszBuff, int cchMaxBuffChars) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeString(m_hTheme, nPartID, nStateID, nPropID, pszBuff, cchMaxBuffChars);
+ }
+
+ HRESULT GetThemeBool(int nPartID, int nStateID, int nPropID, BOOL* pfVal) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeBool(m_hTheme, nPartID, nStateID, nPropID, pfVal);
+ }
+
+ HRESULT GetThemeInt(int nPartID, int nStateID, int nPropID, int* pnVal) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeInt(m_hTheme, nPartID, nStateID, nPropID, pnVal);
+ }
+
+ HRESULT GetThemeEnumValue(int nPartID, int nStateID, int nPropID, int* pnVal) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeEnumValue(m_hTheme, nPartID, nStateID, nPropID, pnVal);
+ }
+
+ HRESULT GetThemePosition(int nPartID, int nStateID, int nPropID, LPPOINT pPoint) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemePosition(m_hTheme, nPartID, nStateID, nPropID, pPoint);
+ }
+
+ // deprecated
+ HRESULT GetThemeFont(int nPartID, HDC hDC, int nStateID, int nPropID, LOGFONTW* pFont) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+#ifdef _WTL_NEW_UXTHEME
+ return ::GetThemeFont(m_hTheme, hDC, nPartID, nStateID, nPropID, pFont);
+#else // !_WTL_NEW_UXTHEME
+ // Note: The cast to LOGFONT* is because uxtheme.h incorrectly uses it instead of LOGFONTW*
+ return ::GetThemeFont(m_hTheme, hDC, nPartID, nStateID, nPropID, (LOGFONT*)pFont);
+#endif // !_WTL_NEW_UXTHEME
+ }
+
+ HRESULT GetThemeFont(HDC hDC, int nPartID, int nStateID, int nPropID, LOGFONTW* pFont) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+#ifdef _WTL_NEW_UXTHEME
+ return ::GetThemeFont(m_hTheme, hDC, nPartID, nStateID, nPropID, pFont);
+#else // !_WTL_NEW_UXTHEME
+ // Note: The cast to LOGFONT* is because uxtheme.h incorrectly uses it instead of LOGFONTW*
+ return ::GetThemeFont(m_hTheme, hDC, nPartID, nStateID, nPropID, (LOGFONT*)pFont);
+#endif // !_WTL_NEW_UXTHEME
+ }
+
+ HRESULT GetThemeRect(int nPartID, int nStateID, int nPropID, LPRECT pRect) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeRect(m_hTheme, nPartID, nStateID, nPropID, pRect);
+ }
+
+ HRESULT GetThemeMargins(HDC hDC, int nPartID, int nStateID, int nPropID, LPRECT pRect, PMARGINS pMargins) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeMargins(m_hTheme, hDC, nPartID, nStateID, nPropID, pRect, pMargins);
+ }
+
+ HRESULT GetThemeIntList(int nPartID, int nStateID, int nPropID, INTLIST* pIntList) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeIntList(m_hTheme, nPartID, nStateID, nPropID, pIntList);
+ }
+
+ HRESULT GetThemePropertyOrigin(int nPartID, int nStateID, int nPropID, enum PROPERTYORIGIN* pOrigin) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemePropertyOrigin(m_hTheme, nPartID, nStateID, nPropID, pOrigin);
+ }
+
+ HRESULT GetThemeFilename(int nPartID, int nStateID, int nPropID, LPWSTR pszThemeFileName, int cchMaxBuffChars) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeFilename(m_hTheme, nPartID, nStateID, nPropID, pszThemeFileName, cchMaxBuffChars);
+ }
+
+ COLORREF GetThemeSysColor(int nColorID) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeSysColor(m_hTheme, nColorID);
+ }
+
+ HBRUSH GetThemeSysColorBrush(int nColorID) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeSysColorBrush(m_hTheme, nColorID);
+ }
+
+ int GetThemeSysSize(int nSizeID) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeSysSize(m_hTheme, nSizeID);
+ }
+
+ BOOL GetThemeSysBool(int nBoolID) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeSysBool(m_hTheme, nBoolID);
+ }
+
+ HRESULT GetThemeSysFont(int nFontID, LOGFONTW* plf) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+#ifdef _WTL_NEW_UXTHEME
+ return ::GetThemeSysFont(m_hTheme, nFontID, plf);
+#else // !_WTL_NEW_UXTHEME
+ // Note: The cast to LOGFONT* is because uxtheme.h incorrectly uses it instead of LOGFONTW*
+ return ::GetThemeSysFont(m_hTheme, nFontID, (LOGFONT*)plf);
+#endif // !_WTL_NEW_UXTHEME
+ }
+
+ HRESULT GetThemeSysString(int nStringID, LPWSTR pszStringBuff, int cchMaxStringChars) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeSysString(m_hTheme, nStringID, pszStringBuff, cchMaxStringChars);
+ }
+
+ HRESULT GetThemeSysInt(int nIntID, int* pnValue) const
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeSysInt(m_hTheme, nIntID, pnValue);
+ }
+
+#ifdef _WTL_NEW_UXTHEME
+ HTHEME OpenThemeDataEx(HWND hWnd, LPCWSTR pszClassList, DWORD dwFlags)
+ {
+ if(!IsThemingSupported())
+ return NULL;
+
+ ATLASSERT(m_hTheme == NULL);
+ m_hTheme = ::OpenThemeDataEx(hWnd, pszClassList, dwFlags);
+ return m_hTheme;
+ }
+
+ HRESULT DrawThemeTextEx(HDC hDC, int nPartID, int nStateID, LPCWSTR pszText, int cchText, DWORD dwTextFlags, LPRECT lpRect, const DTTOPTS* pOptions)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::DrawThemeTextEx(m_hTheme, hDC, nPartID, nStateID, pszText, cchText, dwTextFlags, lpRect, pOptions);
+ }
+
+ HRESULT GetThemeTransitionDuration(int nPartID, int nFromStateID, int nToStateID, int nPropID, DWORD& dwDuration)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeTransitionDuration(m_hTheme, nPartID, nFromStateID, nToStateID, nPropID, &dwDuration);
+ }
+#endif // _WTL_NEW_UXTHEME
+
+#if (_WIN32_WINNT >= 0x0600)
+ HRESULT GetThemeBitmap(int nPartID, int nStateID, int nPropID, ULONG uFlags, HBITMAP& hBitmap)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeBitmap(m_hTheme, nPartID, nStateID, nPropID, uFlags, &hBitmap);
+ }
+
+ HRESULT GetThemeStream(int nPartID, int nStateID, int nPropID, VOID** ppvStream, DWORD* pcbStream, HINSTANCE hInstance)
+ {
+ ATLASSERT(m_hTheme != NULL);
+ return ::GetThemeStream(m_hTheme, nPartID, nStateID, nPropID, ppvStream, pcbStream, hInstance);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+};
+
+__declspec(selectany) int CTheme::m_nIsThemingSupported = -1;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CThemeImpl - theme support implementation
+
+// Derive from this class to implement window with theme support.
+// Example:
+// class CMyThemeWindow : public CWindowImpl<CMyThemeWindow>, public CThemeImpl<CMyThemeWindow>
+// {
+// ...
+// BEGIN_MSG_MAP(CMyThemeWindow)
+// CHAIN_MSG_MAP(CThemeImpl<CMyThemeWindow>)
+// ...
+// END_MSG_MAP()
+// ...
+// };
+//
+// If you set theme class list, the class will automaticaly open/close/reopen theme data.
+
+
+// Helper for drawing theme client edge
+inline bool AtlDrawThemeClientEdge(HTHEME hTheme, HWND hWnd, HRGN hRgnUpdate = NULL, HBRUSH hBrush = NULL, int nPartID = 0, int nStateID = 0)
+{
+ ATLASSERT(hTheme != NULL);
+ ATLASSERT(::IsWindow(hWnd));
+
+ CWindowDC dc(hWnd);
+ if(dc.IsNull())
+ return false;
+
+ // Get border size
+ int cxBorder = GetSystemMetrics(SM_CXBORDER);
+ int cyBorder = GetSystemMetrics(SM_CYBORDER);
+ if(SUCCEEDED(::GetThemeInt(hTheme, nPartID, nStateID, TMT_SIZINGBORDERWIDTH, &cxBorder)))
+ cyBorder = cxBorder;
+
+ RECT rect;
+ ::GetWindowRect(hWnd, &rect);
+
+ // Remove the client edge from the update region
+ int cxEdge = GetSystemMetrics(SM_CXEDGE);
+ int cyEdge = GetSystemMetrics(SM_CYEDGE);
+ ::InflateRect(&rect, -cxEdge, -cyEdge);
+ CRgn rgn;
+ rgn.CreateRectRgnIndirect(&rect);
+ if(rgn.IsNull())
+ return false;
+
+ if(hRgnUpdate != NULL)
+ rgn.CombineRgn(hRgnUpdate, rgn, RGN_AND);
+
+ ::OffsetRect(&rect, -rect.left, -rect.top);
+
+ ::OffsetRect(&rect, cxEdge, cyEdge);
+ dc.ExcludeClipRect(&rect);
+ ::InflateRect(&rect, cxEdge, cyEdge);
+
+ ::DrawThemeBackground(hTheme, dc, nPartID, nStateID, &rect, NULL);
+
+ // Use background brush too, since theme border might not cover everything
+ if(cxBorder < cxEdge && cyBorder < cyEdge)
+ {
+ if(hBrush == NULL)
+// need conditional code because types don't match in winuser.h
+#ifdef _WIN64
+ hBrush = (HBRUSH)::GetClassLongPtr(hWnd, GCLP_HBRBACKGROUND);
+#else
+ hBrush = (HBRUSH)UlongToPtr(::GetClassLongPtr(hWnd, GCLP_HBRBACKGROUND));
+#endif
+
+ ::InflateRect(&rect, cxBorder - cxEdge, cyBorder - cyEdge);
+ dc.FillRect(&rect, hBrush);
+ }
+
+ ::DefWindowProc(hWnd, WM_NCPAINT, (WPARAM)rgn.m_hRgn, 0L);
+
+ return true;
+}
+
+
+// Theme extended styles
+#define THEME_EX_3DCLIENTEDGE 0x00000001
+#define THEME_EX_THEMECLIENTEDGE 0x00000002
+
+template <class T, class TBase = CTheme>
+class CThemeImpl : public TBase
+{
+public:
+// Data members
+ LPWSTR m_lpstrThemeClassList;
+ DWORD m_dwExtendedStyle; // theme specific extended styles
+
+// Constructor & destructor
+ CThemeImpl() : m_lpstrThemeClassList(NULL), m_dwExtendedStyle(0)
+ { }
+
+ ~CThemeImpl()
+ {
+ delete [] m_lpstrThemeClassList;
+ }
+
+// Attributes
+ bool SetThemeClassList(LPCWSTR lpstrThemeClassList)
+ {
+ if(m_lpstrThemeClassList != NULL)
+ {
+ delete [] m_lpstrThemeClassList;
+ m_lpstrThemeClassList = NULL;
+ }
+
+ if(lpstrThemeClassList == NULL)
+ return true;
+
+ int cchLen = lstrlenW(lpstrThemeClassList) + 1;
+ ATLTRY(m_lpstrThemeClassList = new WCHAR[cchLen]);
+ if(m_lpstrThemeClassList == NULL)
+ return false;
+
+ SecureHelper::strcpyW_x(m_lpstrThemeClassList, cchLen, lpstrThemeClassList);
+
+ return true;
+ }
+
+ bool GetThemeClassList(LPWSTR lpstrThemeClassList, int cchListBuffer) const
+ {
+ int cchLen = lstrlenW(m_lpstrThemeClassList) + 1;
+ if(cchListBuffer < cchLen)
+ return false;
+
+ SecureHelper::strcpyW_x(lpstrThemeClassList, cchListBuffer, m_lpstrThemeClassList);
+
+ return true;
+ }
+
+ LPCWSTR GetThemeClassList() const
+ {
+ return m_lpstrThemeClassList;
+ }
+
+ DWORD SetThemeExtendedStyle(DWORD dwExtendedStyle, DWORD dwMask = 0)
+ {
+ DWORD dwPrevStyle = m_dwExtendedStyle;
+ if(dwMask == 0)
+ m_dwExtendedStyle = dwExtendedStyle;
+ else
+ m_dwExtendedStyle = (m_dwExtendedStyle & ~dwMask) | (dwExtendedStyle & dwMask);
+ return dwPrevStyle;
+ }
+
+ DWORD GetThemeExtendedStyle() const
+ {
+ return m_dwExtendedStyle;
+ }
+
+// Operations
+ HTHEME OpenThemeData()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ ATLASSERT(m_lpstrThemeClassList != NULL);
+ if(m_lpstrThemeClassList == NULL)
+ return NULL;
+ CloseThemeData();
+ return TBase::OpenThemeData(pT->m_hWnd, m_lpstrThemeClassList);
+ }
+
+ HTHEME OpenThemeData(LPCWSTR pszClassList)
+ {
+ if(!SetThemeClassList(pszClassList))
+ return NULL;
+ return OpenThemeData();
+ }
+
+ HRESULT SetWindowTheme(LPCWSTR pszSubAppName, LPCWSTR pszSubIDList)
+ {
+ if(!IsThemingSupported())
+ return S_FALSE;
+
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::SetWindowTheme(pT->m_hWnd, pszSubAppName, pszSubIDList);
+ }
+
+ HTHEME GetWindowTheme() const
+ {
+ if(!IsThemingSupported())
+ return NULL;
+
+ const T* pT = static_cast<const T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::GetWindowTheme(pT->m_hWnd);
+ }
+
+ HRESULT EnableThemeDialogTexture(DWORD dwFlags)
+ {
+ if(!IsThemingSupported())
+ return S_FALSE;
+
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::EnableThemeDialogTexture(pT->m_hWnd, dwFlags);
+ }
+
+ BOOL IsThemeDialogTextureEnabled() const
+ {
+ if(!IsThemingSupported())
+ return FALSE;
+
+ const T* pT = static_cast<const T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::IsThemeDialogTextureEnabled(pT->m_hWnd);
+ }
+
+ HRESULT DrawThemeParentBackground(HDC hDC, const RECT* pRect = NULL)
+ {
+ if(!IsThemingSupported())
+ return S_FALSE;
+
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+#ifdef _WTL_NEW_UXTHEME
+ return ::DrawThemeParentBackground(pT->m_hWnd, hDC, pRect);
+#else
+ return ::DrawThemeParentBackground(pT->m_hWnd, hDC, (RECT*)pRect);
+#endif
+ }
+
+#ifdef _WTL_NEW_UXTHEME
+ HRESULT SetWindowThemeAttribute(WINDOWTHEMEATTRIBUTETYPE type, PVOID pvAttribute, DWORD cbAttribute)
+ {
+ if(!IsThemingSupported())
+ return S_FALSE;
+
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::SetWindowThemeAttribute(pT->m_hWnd, type, pvAttribute, cbAttribute);
+ }
+
+ HRESULT SetWindowThemeNonClientAttributes(DWORD dwAttributes, DWORD dwMask)
+ {
+ if(!IsThemingSupported())
+ return S_FALSE;
+
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ WTA_OPTIONS opt = { dwAttributes, dwMask };
+ return ::SetWindowThemeAttribute(pT->m_hWnd, WTA_NONCLIENT, (PVOID)&opt, sizeof(opt));
+ }
+
+ HRESULT DrawThemeParentBackgroundEx(HDC hDC, DWORD dwFlags, const RECT* lpRect = NULL)
+ {
+ if(!IsThemingSupported())
+ return S_FALSE;
+
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ return ::DrawThemeParentBackgroundEx(pT->m_hWnd, hDC, dwFlags, lpRect);
+ }
+#endif // _WTL_NEW_UXTHEME
+
+// Message map and handlers
+ // Note: If you handle any of these messages in your derived class,
+ // it is better to put CHAIN_MSG_MAP at the start of your message map.
+ BEGIN_MSG_MAP(CThemeImpl)
+ MESSAGE_HANDLER(WM_CREATE, OnCreate)
+ MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
+ MESSAGE_HANDLER(WM_THEMECHANGED, OnThemeChanged)
+ MESSAGE_HANDLER(WM_NCPAINT, OnNcPaint)
+ END_MSG_MAP()
+
+ LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if(m_lpstrThemeClassList != NULL)
+ OpenThemeData();
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ CloseThemeData();
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnThemeChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ CloseThemeData();
+ if(m_lpstrThemeClassList != NULL)
+ OpenThemeData();
+ bHandled = FALSE;
+ return 1;
+ }
+
+ LRESULT OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ LRESULT lRet = 0;
+ bHandled = FALSE;
+ if(IsThemingSupported() && ((pT->GetExStyle() & WS_EX_CLIENTEDGE) != 0))
+ {
+ if((m_dwExtendedStyle & THEME_EX_3DCLIENTEDGE) != 0)
+ {
+ lRet = ::DefWindowProc(pT->m_hWnd, uMsg, wParam, lParam);
+ bHandled = TRUE;
+ }
+ else if((m_hTheme != NULL) && ((m_dwExtendedStyle & THEME_EX_THEMECLIENTEDGE) != 0))
+ {
+ HRGN hRgn = (wParam != 1) ? (HRGN)wParam : NULL;
+ if(pT->DrawThemeClientEdge(hRgn))
+ bHandled = TRUE;
+ }
+ }
+ return lRet;
+ }
+
+// Drawing helper
+ bool DrawThemeClientEdge(HRGN hRgnUpdate)
+ {
+ T* pT = static_cast<T*>(this);
+ return AtlDrawThemeClientEdge(m_hTheme, pT->m_hWnd, hRgnUpdate, NULL, 0, 0);
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Buffered Paint and Animation
+
+#ifdef _WTL_NEW_UXTHEME
+
+///////////////////////////////////////////////////////////////////////////////
+// CBufferedPaintBase - Buffered Paint support for othe classes
+
+class CBufferedPaintBase
+{
+public:
+ static int m_nIsBufferedPaintSupported;
+
+ CBufferedPaintBase()
+ {
+ if(IsBufferedPaintSupported())
+ ATLVERIFY(SUCCEEDED(::BufferedPaintInit()));
+ }
+
+ ~CBufferedPaintBase()
+ {
+ if(IsBufferedPaintSupported())
+ ATLVERIFY(SUCCEEDED(::BufferedPaintUnInit()));
+ }
+
+ static bool IsBufferedPaintSupported()
+ {
+ if(m_nIsBufferedPaintSupported == -1)
+ {
+ CStaticDataInitCriticalSectionLock lock;
+ if(FAILED(lock.Lock()))
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("ERROR : Unable to lock critical section in CBufferedPaintBase::IsBufferedPaintSupported.\n"));
+ ATLASSERT(FALSE);
+ return false;
+ }
+
+ if(m_nIsBufferedPaintSupported == -1)
+ m_nIsBufferedPaintSupported = RunTimeHelper::IsVista() ? 1 : 0;
+
+ lock.Unlock();
+ }
+
+ ATLASSERT(m_nIsBufferedPaintSupported != -1);
+ return (m_nIsBufferedPaintSupported == 1);
+ }
+};
+
+__declspec(selectany) int CBufferedPaintBase::m_nIsBufferedPaintSupported = -1;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CBufferedPaint - support for buffered paint functions
+
+class CBufferedPaint
+{
+public:
+ HPAINTBUFFER m_hPaintBuffer;
+
+ CBufferedPaint() : m_hPaintBuffer(NULL)
+ { }
+
+ ~CBufferedPaint()
+ {
+ ATLVERIFY(SUCCEEDED(End()));
+ }
+
+ bool IsNull() const
+ {
+ return (m_hPaintBuffer == NULL);
+ }
+
+ HPAINTBUFFER Begin(HDC hdcTarget, const RECT* prcTarget, BP_BUFFERFORMAT dwFormat, BP_PAINTPARAMS* pPaintParams, HDC* phdcPaint)
+ {
+ ATLASSERT(m_hPaintBuffer == NULL);
+ m_hPaintBuffer = ::BeginBufferedPaint(hdcTarget, prcTarget, dwFormat, pPaintParams, phdcPaint);
+ return m_hPaintBuffer;
+ }
+
+ HRESULT End(BOOL bUpdate = TRUE)
+ {
+ HRESULT hRet = S_FALSE;
+ if(m_hPaintBuffer != NULL)
+ {
+ hRet = ::EndBufferedPaint(m_hPaintBuffer, bUpdate);
+ m_hPaintBuffer = NULL;
+ }
+ return hRet;
+ }
+
+ HRESULT GetTargetRect(LPRECT pRect) const
+ {
+ ATLASSERT(m_hPaintBuffer != NULL);
+ return ::GetBufferedPaintTargetRect(m_hPaintBuffer, pRect);
+ }
+
+ HDC GetTargetDC() const
+ {
+ ATLASSERT(m_hPaintBuffer != NULL);
+ return ::GetBufferedPaintTargetDC(m_hPaintBuffer);
+ }
+
+ HDC GetPaintDC() const
+ {
+ ATLASSERT(m_hPaintBuffer != NULL);
+ return ::GetBufferedPaintDC(m_hPaintBuffer);
+ }
+
+ HRESULT GetBits(RGBQUAD** ppbBuffer, int* pcxRow) const
+ {
+ ATLASSERT(m_hPaintBuffer != NULL);
+ return ::GetBufferedPaintBits(m_hPaintBuffer, ppbBuffer, pcxRow);
+ }
+
+ HRESULT Clear(const RECT* pRect = NULL)
+ {
+ ATLASSERT(m_hPaintBuffer != NULL);
+ return ::BufferedPaintClear(m_hPaintBuffer, pRect);
+ }
+
+ HRESULT SetAlpha(BYTE alpha, const RECT* pRect = NULL)
+ {
+ ATLASSERT(m_hPaintBuffer != NULL);
+ return ::BufferedPaintSetAlpha(m_hPaintBuffer, pRect, alpha);
+ }
+
+ HRESULT MakeOpaque(const RECT* pRect = NULL)
+ {
+ ATLASSERT(m_hPaintBuffer != NULL);
+ return ::BufferedPaintSetAlpha(m_hPaintBuffer, pRect, 255);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CBufferedPaintImpl - provides buffered paint for any window
+
+template <class T>
+class ATL_NO_VTABLE CBufferedPaintImpl : public CBufferedPaintBase
+{
+public:
+ CBufferedPaint m_BufferedPaint;
+ BP_BUFFERFORMAT m_dwFormat;
+ BP_PAINTPARAMS m_PaintParams;
+
+ CBufferedPaintImpl() : m_dwFormat(BPBF_TOPDOWNDIB)
+ {
+ memset(&m_PaintParams, 0, sizeof(BP_PAINTPARAMS));
+ m_PaintParams.cbSize = sizeof(BP_PAINTPARAMS);
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CBufferedPaintImpl)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+ END_MSG_MAP()
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1; // no background needed
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ if(wParam != NULL)
+ {
+ RECT rect = { 0 };
+ pT->GetClientRect(&rect);
+ pT->DoPaint((HDC)wParam, rect);
+ }
+ else
+ {
+ CPaintDC dc(pT->m_hWnd);
+ pT->DoBufferedPaint(dc.m_hDC, dc.m_ps.rcPaint);
+ }
+
+ return 0;
+ }
+
+// Overrideables
+ void DoBufferedPaint(CDCHandle dc, RECT& rect)
+ {
+ HDC hDCPaint = NULL;
+ if(IsBufferedPaintSupported())
+ m_BufferedPaint.Begin(dc, &rect, m_dwFormat, &m_PaintParams, &hDCPaint);
+
+ T* pT = static_cast<T*>(this);
+ if(hDCPaint != NULL)
+ pT->DoPaint(hDCPaint, rect);
+ else
+ pT->DoPaint(dc.m_hDC, rect);
+
+ if(IsBufferedPaintSupported())
+ m_BufferedPaint.End();
+ }
+
+ void DoPaint(CDCHandle /*dc*/, RECT& /*rect*/)
+ {
+ // must be implemented in a derived class
+ ATLASSERT(FALSE);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CBufferedPaintWindowImpl - implements a window that uses buffered paint
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CBufferedPaintWindowImpl :
+ public ATL::CWindowImpl<T, TBase, TWinTraits>,
+ public CBufferedPaintImpl< T >
+{
+public:
+ BEGIN_MSG_MAP(CBufferedPaintWindowImpl)
+ CHAIN_MSG_MAP(CBufferedPaintImpl< T >)
+ END_MSG_MAP()
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CBufferedAnimation - support for buffered animation
+
+class CBufferedAnimation
+{
+public:
+ HANIMATIONBUFFER m_hAnimationBuffer;
+
+ CBufferedAnimation() : m_hAnimationBuffer(NULL)
+ { }
+
+ ~CBufferedAnimation()
+ {
+ ATLVERIFY(SUCCEEDED(End()));
+ }
+
+ bool IsNull() const
+ {
+ return (m_hAnimationBuffer == NULL);
+ }
+
+ HANIMATIONBUFFER Begin(HWND hWnd, HDC hDCTarget, const RECT* pRectTarget, BP_BUFFERFORMAT dwFormat, BP_PAINTPARAMS* pPaintParams, BP_ANIMATIONPARAMS* pAnimationParams, HDC* phdcFrom, HDC* phdcTo)
+ {
+ ATLASSERT(m_hAnimationBuffer == NULL);
+ m_hAnimationBuffer = ::BeginBufferedAnimation(hWnd, hDCTarget, pRectTarget, dwFormat, pPaintParams, pAnimationParams, phdcFrom, phdcTo);
+ return m_hAnimationBuffer;
+ }
+
+ HRESULT End(BOOL bUpdate = TRUE)
+ {
+ HRESULT hRet = S_FALSE;
+ if(m_hAnimationBuffer != NULL)
+ {
+ hRet = ::EndBufferedAnimation(m_hAnimationBuffer, bUpdate);
+ m_hAnimationBuffer = NULL;
+ }
+ return hRet;
+ }
+
+ static bool IsRendering(HWND hWnd, HDC hDC)
+ {
+ return (::BufferedPaintRenderAnimation(hWnd, hDC) != FALSE);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CBufferedAnimationImpl - provides buffered animation support for any window
+
+// Note: You can either use m_State and m_NewState to store the state information
+// for the animation change, or map your state to those data members. DoPaint()
+// should only rely on the state information that is passed to it.
+
+template <class T, class TState = DWORD_PTR>
+class ATL_NO_VTABLE CBufferedAnimationImpl : public CBufferedPaintBase
+{
+public:
+ BP_BUFFERFORMAT m_dwFormat;
+ BP_PAINTPARAMS m_PaintParams;
+ BP_ANIMATIONPARAMS m_AnimationParams;
+
+ TState m_State;
+ TState m_NewState;
+
+ CBufferedAnimationImpl(TState InitialState) : m_dwFormat(BPBF_TOPDOWNDIB)
+ {
+ memset(&m_PaintParams, 0, sizeof(BP_PAINTPARAMS));
+ m_PaintParams.cbSize = sizeof(BP_PAINTPARAMS);
+
+ memset(&m_AnimationParams, 0, sizeof(BP_ANIMATIONPARAMS));
+ m_AnimationParams.cbSize = sizeof(BP_ANIMATIONPARAMS);
+ m_AnimationParams.style = BPAS_LINEAR;
+ m_AnimationParams.dwDuration = 500;
+
+ T* pT = static_cast<T*>(this);
+ pT->SetState(InitialState);
+ pT->SetNewState(InitialState);
+ }
+
+ DWORD GetDuration() const
+ {
+ return m_AnimationParams.dwDuration;
+ }
+
+ void SetDuration(DWORD dwDuration)
+ {
+ m_AnimationParams.dwDuration = dwDuration;
+ }
+
+ void DoAnimation(TState NewState, const RECT* pRect = NULL)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->SetNewState(NewState);
+
+ pT->InvalidateRect(pRect, FALSE);
+ pT->UpdateWindow();
+
+ pT->SetState(NewState);
+ }
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CBufferedAnimationImpl)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
+ MESSAGE_HANDLER(WM_PAINT, OnPaint)
+ MESSAGE_HANDLER(WM_PRINTCLIENT, OnPaint)
+ END_MSG_MAP()
+
+ LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ return 1; // no background needed
+ }
+
+ LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ if(wParam != NULL)
+ {
+ RECT rect = { 0 };
+ pT->GetClientRect(&rect);
+ pT->DoPaint((HDC)wParam, rect, m_NewState);
+ }
+ else
+ {
+ CPaintDC dc(pT->m_hWnd);
+ pT->DoAnimationPaint(dc.m_hDC, dc.m_ps.rcPaint);
+ }
+
+ return 0;
+ }
+
+// Overrideables
+ void SetState(TState State)
+ {
+ m_State = State;
+ }
+
+ void SetNewState(TState State)
+ {
+ m_NewState = State;
+ }
+
+ bool AreStatesEqual() const
+ {
+ return (m_State == m_NewState);
+ }
+
+ void DoAnimationPaint(CDCHandle dc, RECT& rect)
+ {
+ T* pT = static_cast<T*>(this);
+ if(IsBufferedPaintSupported() && CBufferedAnimation::IsRendering(pT->m_hWnd, dc))
+ return;
+
+ DWORD dwDurationSave = m_AnimationParams.dwDuration;
+ if(pT->AreStatesEqual())
+ m_AnimationParams.dwDuration = 0;
+
+ HDC hdcFrom = NULL, hdcTo = NULL;
+ CBufferedAnimation ba;
+ if(IsBufferedPaintSupported())
+ ba.Begin(pT->m_hWnd, dc, &rect, m_dwFormat, &m_PaintParams, &m_AnimationParams, &hdcFrom, &hdcTo);
+
+ if(!ba.IsNull())
+ {
+ if(hdcFrom != NULL)
+ pT->DoPaint(hdcFrom, rect, m_State);
+
+ if (hdcTo != NULL)
+ pT->DoPaint(hdcTo, rect, m_NewState);
+ }
+ else
+ {
+ pT->DoPaint(dc.m_hDC, rect, m_NewState);
+ }
+
+ m_AnimationParams.dwDuration = dwDurationSave;
+ }
+
+ void DoPaint(CDCHandle /*dc*/, RECT& /*rect*/, TState /*State*/)
+ {
+ // must be implemented in a derived class
+ ATLASSERT(FALSE);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CBufferedAnimationWindowImpl - implements a window that uses buffered animation
+
+template <class T, class TState = DWORD_PTR, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CBufferedAnimationWindowImpl :
+ public ATL::CWindowImpl<T, TBase, TWinTraits>,
+ public CBufferedAnimationImpl< T, TState >
+{
+public:
+ CBufferedAnimationWindowImpl(TState InitialState) : CBufferedAnimationImpl< T, TState >(InitialState)
+ { }
+
+ typedef CBufferedAnimationImpl< T, TState > _baseBufferedAnimation;
+ BEGIN_MSG_MAP(CBufferedAnimationWindowImpl)
+ CHAIN_MSG_MAP(_baseBufferedAnimation)
+ END_MSG_MAP()
+};
+
+#endif // _WTL_NEW_UXTHEME
+
+}; // namespace WTL
+
+#endif // __ATLTHEME_H__
diff --git a/plugins/SmartAutoReplier/wtl/atluser.h b/plugins/SmartAutoReplier/wtl/atluser.h
new file mode 100644
index 0000000000..6cd8205a73
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atluser.h
@@ -0,0 +1,1391 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLUSER_H__
+#define __ATLUSER_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atluser.h requires atlapp.h to be included first
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CMenuItemInfo
+// CMenuT<t_bManaged>
+// CAcceleratorT<t_bManaged>
+// CIconT<t_bManaged>
+// CCursorT<t_bManaged>
+// CResource
+//
+// Global functions:
+// AtlMessageBox()
+//
+// AtlLoadAccelerators()
+// AtlLoadMenu()
+// AtlLoadBitmap()
+// AtlLoadSysBitmap()
+// AtlLoadCursor()
+// AtlLoadSysCursor()
+// AtlLoadIcon()
+// AtlLoadSysIcon()
+// AtlLoadBitmapImage()
+// AtlLoadCursorImage()
+// AtlLoadIconImage()
+// AtlLoadSysBitmapImage()
+// AtlLoadSysCursorImage()
+// AtlLoadSysIconImage()
+// AtlLoadString()
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// AtlMessageBox - accepts both memory and resource based strings
+
+inline int AtlMessageBox(HWND hWndOwner, ATL::_U_STRINGorID message, ATL::_U_STRINGorID title = (LPCTSTR)NULL, UINT uType = MB_OK | MB_ICONINFORMATION)
+{
+ ATLASSERT(hWndOwner == NULL || ::IsWindow(hWndOwner));
+
+ LPTSTR lpstrMessage = NULL;
+ if(IS_INTRESOURCE(message.m_lpstr))
+ {
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ ATLTRY(lpstrMessage = new TCHAR[nLen]);
+ if(lpstrMessage == NULL)
+ {
+ ATLASSERT(FALSE);
+ return 0;
+ }
+ int nRes = ::LoadString(ModuleHelper::GetResourceInstance(), LOWORD(message.m_lpstr), lpstrMessage, nLen);
+ if(nRes < nLen - 1)
+ break;
+ delete [] lpstrMessage;
+ lpstrMessage = NULL;
+ }
+
+ message.m_lpstr = lpstrMessage;
+ }
+
+ LPTSTR lpstrTitle = NULL;
+ if(IS_INTRESOURCE(title.m_lpstr) && LOWORD(title.m_lpstr) != 0)
+ {
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ ATLTRY(lpstrTitle = new TCHAR[nLen]);
+ if(lpstrTitle == NULL)
+ {
+ ATLASSERT(FALSE);
+ return 0;
+ }
+ int nRes = ::LoadString(ModuleHelper::GetResourceInstance(), LOWORD(title.m_lpstr), lpstrTitle, nLen);
+ if(nRes < nLen - 1)
+ break;
+ delete [] lpstrTitle;
+ lpstrTitle = NULL;
+ }
+
+ title.m_lpstr = lpstrTitle;
+ }
+
+ int nRet = ::MessageBox(hWndOwner, message.m_lpstr, title.m_lpstr, uType);
+
+ delete [] lpstrMessage;
+ delete [] lpstrTitle;
+
+ return nRet;
+}
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CMenu
+
+#if (WINVER >= 0x0500)
+ #ifndef MII_SIZEOF_STRUCT
+ #define MII_SIZEOF_STRUCT(structname, member) (((int)((LPBYTE)(&((structname*)0)->member) - ((LPBYTE)((structname*)0)))) + sizeof(((structname*)0)->member))
+ #endif
+ #define MENUITEMINFO_SIZE_VERSION_400A MII_SIZEOF_STRUCT(MENUITEMINFOA, cch)
+ #define MENUITEMINFO_SIZE_VERSION_400W MII_SIZEOF_STRUCT(MENUITEMINFOW, cch)
+ #ifdef UNICODE
+ #define MENUITEMINFO_SIZE_VERSION_400 MENUITEMINFO_SIZE_VERSION_400W
+ #else
+ #define MENUITEMINFO_SIZE_VERSION_400 MENUITEMINFO_SIZE_VERSION_400A
+ #endif // !UNICODE
+#endif // (WINVER >= 0x0500)
+
+class CMenuItemInfo : public MENUITEMINFO
+{
+public:
+ CMenuItemInfo()
+ {
+ memset(this, 0, sizeof(MENUITEMINFO));
+ cbSize = sizeof(MENUITEMINFO);
+#if (WINVER >= 0x0500)
+ // adjust struct size if running on older version of Windows
+ if(AtlIsOldWindows())
+ {
+ ATLASSERT(cbSize > MENUITEMINFO_SIZE_VERSION_400); // must be
+ cbSize = MENUITEMINFO_SIZE_VERSION_400;
+ }
+#endif // (WINVER >= 0x0500)
+ }
+};
+
+
+// forward declarations
+template <bool t_bManaged> class CMenuT;
+typedef CMenuT<false> CMenuHandle;
+typedef CMenuT<true> CMenu;
+
+
+template <bool t_bManaged>
+class CMenuT
+{
+public:
+// Data members
+ HMENU m_hMenu;
+
+// Constructor/destructor/operators
+ CMenuT(HMENU hMenu = NULL) : m_hMenu(hMenu)
+ { }
+
+ ~CMenuT()
+ {
+ if(t_bManaged && m_hMenu != NULL)
+ DestroyMenu();
+ }
+
+ CMenuT<t_bManaged>& operator =(HMENU hMenu)
+ {
+ Attach(hMenu);
+ return *this;
+ }
+
+ void Attach(HMENU hMenuNew)
+ {
+ ATLASSERT(::IsMenu(hMenuNew));
+ if(t_bManaged && m_hMenu != NULL && m_hMenu != hMenuNew)
+ ::DestroyMenu(m_hMenu);
+ m_hMenu = hMenuNew;
+ }
+
+ HMENU Detach()
+ {
+ HMENU hMenu = m_hMenu;
+ m_hMenu = NULL;
+ return hMenu;
+ }
+
+ operator HMENU() const { return m_hMenu; }
+
+ bool IsNull() const { return (m_hMenu == NULL); }
+
+ BOOL IsMenu() const
+ {
+ return ::IsMenu(m_hMenu);
+ }
+
+// Create/destroy methods
+ BOOL CreateMenu()
+ {
+ ATLASSERT(m_hMenu == NULL);
+ m_hMenu = ::CreateMenu();
+ return (m_hMenu != NULL) ? TRUE : FALSE;
+ }
+
+ BOOL CreatePopupMenu()
+ {
+ ATLASSERT(m_hMenu == NULL);
+ m_hMenu = ::CreatePopupMenu();
+ return (m_hMenu != NULL) ? TRUE : FALSE;
+ }
+
+ BOOL LoadMenu(ATL::_U_STRINGorID menu)
+ {
+ ATLASSERT(m_hMenu == NULL);
+ m_hMenu = ::LoadMenu(ModuleHelper::GetResourceInstance(), menu.m_lpstr);
+ return (m_hMenu != NULL) ? TRUE : FALSE;
+ }
+
+#ifndef _WIN32_WCE
+ BOOL LoadMenuIndirect(const void* lpMenuTemplate)
+ {
+ ATLASSERT(m_hMenu == NULL);
+ m_hMenu = ::LoadMenuIndirect(lpMenuTemplate);
+ return (m_hMenu != NULL) ? TRUE : FALSE;
+ }
+#endif // !_WIN32_WCE
+
+ BOOL DestroyMenu()
+ {
+ if (m_hMenu == NULL)
+ return FALSE;
+ BOOL bRet = ::DestroyMenu(m_hMenu);
+ if(bRet)
+ m_hMenu = NULL;
+ return bRet;
+ }
+
+// Menu Operations
+ BOOL DeleteMenu(UINT nPosition, UINT nFlags)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::DeleteMenu(m_hMenu, nPosition, nFlags);
+ }
+
+ BOOL TrackPopupMenu(UINT nFlags, int x, int y, HWND hWnd, LPCRECT lpRect = NULL)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+#ifndef _WIN32_WCE
+#if (WINVER >= 0x0500)
+ x = _FixTrackMenuPopupX(x, y);
+#endif // !(WINVER >= 0x0500)
+ return ::TrackPopupMenu(m_hMenu, nFlags, x, y, 0, hWnd, lpRect);
+#else // CE specific
+ lpRect;
+ return ::TrackPopupMenuEx(m_hMenu, nFlags, x, y, hWnd, NULL);
+#endif // _WIN32_WCE
+ }
+
+ BOOL TrackPopupMenuEx(UINT uFlags, int x, int y, HWND hWnd, LPTPMPARAMS lptpm = NULL)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ x = _FixTrackMenuPopupX(x, y);
+#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ return ::TrackPopupMenuEx(m_hMenu, uFlags, x, y, hWnd, lptpm);
+ }
+
+#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ // helper that fixes popup menu X position when it's off-screen
+ static int _FixTrackMenuPopupX(int x, int y)
+ {
+ POINT pt = { x, y };
+ HMONITOR hMonitor = ::MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
+ if(hMonitor == NULL)
+ {
+ HMONITOR hMonitorNear = ::MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
+ if(hMonitorNear != NULL)
+ {
+ MONITORINFO mi = { 0 };
+ mi.cbSize = sizeof(MONITORINFO);
+ if(::GetMonitorInfo(hMonitorNear, &mi) != FALSE)
+ {
+ if(x < mi.rcWork.left)
+ x = mi.rcWork.left;
+ else if(x > mi.rcWork.right)
+ x = mi.rcWork.right;
+ }
+ }
+ }
+
+ return x;
+ }
+
+ BOOL GetMenuInfo(LPMENUINFO lpMenuInfo) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuInfo(m_hMenu, lpMenuInfo);
+ }
+
+ BOOL SetMenuInfo(LPCMENUINFO lpMenuInfo)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::SetMenuInfo(m_hMenu, lpMenuInfo);
+ }
+#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+
+// Menu Item Operations
+ BOOL AppendMenu(UINT nFlags, UINT_PTR nIDNewItem = 0, LPCTSTR lpszNewItem = NULL)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::AppendMenu(m_hMenu, nFlags, nIDNewItem, lpszNewItem);
+ }
+
+ BOOL AppendMenu(UINT nFlags, HMENU hSubMenu, LPCTSTR lpszNewItem)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ ATLASSERT(::IsMenu(hSubMenu));
+ return ::AppendMenu(m_hMenu, nFlags | MF_POPUP, (UINT_PTR)hSubMenu, lpszNewItem);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL AppendMenu(UINT nFlags, UINT_PTR nIDNewItem, HBITMAP hBmp)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::AppendMenu(m_hMenu, nFlags | MF_BITMAP, nIDNewItem, (LPCTSTR)hBmp);
+ }
+
+ BOOL AppendMenu(UINT nFlags, HMENU hSubMenu, HBITMAP hBmp)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ ATLASSERT(::IsMenu(hSubMenu));
+ return ::AppendMenu(m_hMenu, nFlags | (MF_BITMAP | MF_POPUP), (UINT_PTR)hSubMenu, (LPCTSTR)hBmp);
+ }
+#endif // !_WIN32_WCE
+
+ UINT CheckMenuItem(UINT nIDCheckItem, UINT nCheck)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return (UINT)::CheckMenuItem(m_hMenu, nIDCheckItem, nCheck);
+ }
+
+ UINT EnableMenuItem(UINT nIDEnableItem, UINT nEnable)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::EnableMenuItem(m_hMenu, nIDEnableItem, nEnable);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL HiliteMenuItem(HWND hWnd, UINT uIDHiliteItem, UINT uHilite)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::HiliteMenuItem(hWnd, m_hMenu, uIDHiliteItem, uHilite);
+ }
+
+ int GetMenuItemCount() const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuItemCount(m_hMenu);
+ }
+
+ UINT GetMenuItemID(int nPos) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuItemID(m_hMenu, nPos);
+ }
+
+ UINT GetMenuState(UINT nID, UINT nFlags) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuState(m_hMenu, nID, nFlags);
+ }
+
+ int GetMenuString(UINT nIDItem, LPTSTR lpString, int nMaxCount, UINT nFlags) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuString(m_hMenu, nIDItem, lpString, nMaxCount, nFlags);
+ }
+
+ int GetMenuStringLen(UINT nIDItem, UINT nFlags) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuString(m_hMenu, nIDItem, NULL, 0, nFlags);
+ }
+
+#ifndef _ATL_NO_COM
+ BOOL GetMenuString(UINT nIDItem, BSTR& bstrText, UINT nFlags) const
+ {
+ USES_CONVERSION;
+ ATLASSERT(::IsMenu(m_hMenu));
+ ATLASSERT(bstrText == NULL);
+
+ int nLen = GetMenuStringLen(nIDItem, nFlags);
+ if(nLen == 0)
+ {
+ bstrText = ::SysAllocString(OLESTR(""));
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+
+ nLen++; // increment to include terminating NULL char
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ LPTSTR lpszText = buff.Allocate(nLen);
+ if(lpszText == NULL)
+ return FALSE;
+
+ if(!GetMenuString(nIDItem, lpszText, nLen, nFlags))
+ return FALSE;
+
+ bstrText = ::SysAllocString(T2OLE(lpszText));
+ return (bstrText != NULL) ? TRUE : FALSE;
+ }
+#endif // !_ATL_NO_COM
+
+#elif (_ATL_VER >= 0x0800)
+ int GetMenuItemCount() const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ATL::GetMenuItemCount(m_hMenu);
+ }
+
+ UINT GetMenuItemID(int nPos) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ATL::GetMenuItemID(m_hMenu, nPos);
+ }
+
+ UINT GetMenuState(UINT nID, UINT nFlags) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ATL::GetMenuState(m_hMenu, nID, nFlags);
+ }
+
+ int GetMenuString(UINT nIDItem, LPTSTR lpString, int nMaxCount, UINT nFlags) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ATL::GetMenuString(m_hMenu, nIDItem, lpString, nMaxCount, nFlags);
+ }
+
+ int GetMenuStringLen(UINT nIDItem, UINT nFlags) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ATL::GetMenuString(m_hMenu, nIDItem, NULL, 0, nFlags);
+ }
+#endif // (_ATL_VER >= 0x0800)
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ int GetMenuString(UINT nIDItem, _CSTRING_NS::CString& strText, UINT nFlags) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+
+ int nLen = GetMenuStringLen(nIDItem, nFlags);
+ if(nLen == 0)
+ return 0;
+
+ nLen++; // increment to include terminating NULL char
+ LPTSTR lpstr = strText.GetBufferSetLength(nLen);
+ if(lpstr == NULL)
+ return 0;
+ int nRet = GetMenuString(nIDItem, lpstr, nLen, nFlags);
+ strText.ReleaseBuffer();
+ return nRet;
+ }
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ CMenuHandle GetSubMenu(int nPos) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return CMenuHandle(::GetSubMenu(m_hMenu, nPos));
+ }
+
+ BOOL InsertMenu(UINT nPosition, UINT nFlags, UINT_PTR nIDNewItem = 0, LPCTSTR lpszNewItem = NULL)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::InsertMenu(m_hMenu, nPosition, nFlags, nIDNewItem, lpszNewItem);
+ }
+
+ BOOL InsertMenu(UINT nPosition, UINT nFlags, HMENU hSubMenu, LPCTSTR lpszNewItem)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ ATLASSERT(::IsMenu(hSubMenu));
+ return ::InsertMenu(m_hMenu, nPosition, nFlags | MF_POPUP, (UINT_PTR)hSubMenu, lpszNewItem);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL InsertMenu(UINT nPosition, UINT nFlags, UINT_PTR nIDNewItem, HBITMAP hBmp)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::InsertMenu(m_hMenu, nPosition, nFlags | MF_BITMAP, nIDNewItem, (LPCTSTR)hBmp);
+ }
+
+ BOOL InsertMenu(UINT nPosition, UINT nFlags, HMENU hSubMenu, HBITMAP hBmp)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ ATLASSERT(::IsMenu(hSubMenu));
+ return ::InsertMenu(m_hMenu, nPosition, nFlags | (MF_BITMAP | MF_POPUP), (UINT_PTR)hSubMenu, (LPCTSTR)hBmp);
+ }
+
+ BOOL ModifyMenu(UINT nPosition, UINT nFlags, UINT_PTR nIDNewItem = 0, LPCTSTR lpszNewItem = NULL)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::ModifyMenu(m_hMenu, nPosition, nFlags, nIDNewItem, lpszNewItem);
+ }
+
+ BOOL ModifyMenu(UINT nPosition, UINT nFlags, HMENU hSubMenu, LPCTSTR lpszNewItem)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ ATLASSERT(::IsMenu(hSubMenu));
+ return ::ModifyMenu(m_hMenu, nPosition, nFlags | MF_POPUP, (UINT_PTR)hSubMenu, lpszNewItem);
+ }
+
+ BOOL ModifyMenu(UINT nPosition, UINT nFlags, UINT_PTR nIDNewItem, HBITMAP hBmp)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::ModifyMenu(m_hMenu, nPosition, nFlags | MF_BITMAP, nIDNewItem, (LPCTSTR)hBmp);
+ }
+
+ BOOL ModifyMenu(UINT nPosition, UINT nFlags, HMENU hSubMenu, HBITMAP hBmp)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ ATLASSERT(::IsMenu(hSubMenu));
+ return ::ModifyMenu(m_hMenu, nPosition, nFlags | (MF_BITMAP | MF_POPUP), (UINT_PTR)hSubMenu, (LPCTSTR)hBmp);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL RemoveMenu(UINT nPosition, UINT nFlags)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::RemoveMenu(m_hMenu, nPosition, nFlags);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL SetMenuItemBitmaps(UINT nPosition, UINT nFlags, HBITMAP hBmpUnchecked, HBITMAP hBmpChecked)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::SetMenuItemBitmaps(m_hMenu, nPosition, nFlags, hBmpUnchecked, hBmpChecked);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL CheckMenuRadioItem(UINT nIDFirst, UINT nIDLast, UINT nIDItem, UINT nFlags)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::CheckMenuRadioItem(m_hMenu, nIDFirst, nIDLast, nIDItem, nFlags);
+ }
+
+ BOOL GetMenuItemInfo(UINT uItem, BOOL bByPosition, LPMENUITEMINFO lpmii) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return (BOOL)::GetMenuItemInfo(m_hMenu, uItem, bByPosition, lpmii);
+ }
+
+ BOOL SetMenuItemInfo(UINT uItem, BOOL bByPosition, LPMENUITEMINFO lpmii)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return (BOOL)::SetMenuItemInfo(m_hMenu, uItem, bByPosition, lpmii);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL InsertMenuItem(UINT uItem, BOOL bByPosition, LPMENUITEMINFO lpmii)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return (BOOL)::InsertMenuItem(m_hMenu, uItem, bByPosition, lpmii);
+ }
+
+ UINT GetMenuDefaultItem(BOOL bByPosition = FALSE, UINT uFlags = 0U) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuDefaultItem(m_hMenu, (UINT)bByPosition, uFlags);
+ }
+
+ BOOL SetMenuDefaultItem(UINT uItem = (UINT)-1, BOOL bByPosition = FALSE)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::SetMenuDefaultItem(m_hMenu, uItem, (UINT)bByPosition);
+ }
+
+ BOOL GetMenuItemRect(HWND hWnd, UINT uItem, LPRECT lprcItem) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuItemRect(hWnd, m_hMenu, uItem, lprcItem);
+ }
+
+ int MenuItemFromPoint(HWND hWnd, POINT point) const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::MenuItemFromPoint(hWnd, m_hMenu, point);
+ }
+
+// Context Help Functions
+ BOOL SetMenuContextHelpId(DWORD dwContextHelpId)
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::SetMenuContextHelpId(m_hMenu, dwContextHelpId);
+ }
+
+ DWORD GetMenuContextHelpId() const
+ {
+ ATLASSERT(::IsMenu(m_hMenu));
+ return ::GetMenuContextHelpId(m_hMenu);
+ }
+#endif // !_WIN32_WCE
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAccelerator
+
+template <bool t_bManaged>
+class CAcceleratorT
+{
+public:
+ HACCEL m_hAccel;
+
+// Constructor/destructor/operators
+ CAcceleratorT(HACCEL hAccel = NULL) : m_hAccel(hAccel)
+ { }
+
+ ~CAcceleratorT()
+ {
+ if(t_bManaged && m_hAccel != NULL)
+ ::DestroyAcceleratorTable(m_hAccel);
+ }
+
+ CAcceleratorT<t_bManaged>& operator =(HACCEL hAccel)
+ {
+ Attach(hAccel);
+ return *this;
+ }
+
+ void Attach(HACCEL hAccel)
+ {
+ if(t_bManaged && m_hAccel != NULL)
+ ::DestroyAcceleratorTable(m_hAccel);
+ m_hAccel = hAccel;
+ }
+
+ HACCEL Detach()
+ {
+ HACCEL hAccel = m_hAccel;
+ m_hAccel = NULL;
+ return hAccel;
+ }
+
+ operator HACCEL() const { return m_hAccel; }
+
+ bool IsNull() const { return m_hAccel == NULL; }
+
+// Create/destroy methods
+ HACCEL LoadAccelerators(ATL::_U_STRINGorID accel)
+ {
+ ATLASSERT(m_hAccel == NULL);
+ m_hAccel = ::LoadAccelerators(ModuleHelper::GetResourceInstance(), accel.m_lpstr);
+ return m_hAccel;
+ }
+
+ HACCEL CreateAcceleratorTable(LPACCEL pAccel, int cEntries)
+ {
+ ATLASSERT(m_hAccel == NULL);
+ ATLASSERT(pAccel != NULL);
+ m_hAccel = ::CreateAcceleratorTable(pAccel, cEntries);
+ return m_hAccel;
+ }
+
+ void DestroyObject()
+ {
+ if(m_hAccel != NULL)
+ {
+ ::DestroyAcceleratorTable(m_hAccel);
+ m_hAccel = NULL;
+ }
+ }
+
+// Operations
+#ifndef _WIN32_WCE
+ int CopyAcceleratorTable(LPACCEL lpAccelDst, int cEntries)
+ {
+ ATLASSERT(m_hAccel != NULL);
+ ATLASSERT(lpAccelDst != NULL);
+ return ::CopyAcceleratorTable(m_hAccel, lpAccelDst, cEntries);
+ }
+
+ int GetEntriesCount() const
+ {
+ ATLASSERT(m_hAccel != NULL);
+ return ::CopyAcceleratorTable(m_hAccel, NULL, 0);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL TranslateAccelerator(HWND hWnd, LPMSG pMsg)
+ {
+ ATLASSERT(m_hAccel != NULL);
+ ATLASSERT(::IsWindow(hWnd));
+ ATLASSERT(pMsg != NULL);
+ return ::TranslateAccelerator(hWnd, m_hAccel, pMsg);
+ }
+};
+
+typedef CAcceleratorT<false> CAcceleratorHandle;
+typedef CAcceleratorT<true> CAccelerator;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CIcon
+
+template <bool t_bManaged>
+class CIconT
+{
+public:
+ HICON m_hIcon;
+
+// Constructor/destructor/operators
+ CIconT(HICON hIcon = NULL) : m_hIcon(hIcon)
+ { }
+
+ ~CIconT()
+ {
+ if(t_bManaged && m_hIcon != NULL)
+ ::DestroyIcon(m_hIcon);
+ }
+
+ CIconT<t_bManaged>& operator =(HICON hIcon)
+ {
+ Attach(hIcon);
+ return *this;
+ }
+
+ void Attach(HICON hIcon)
+ {
+ if(t_bManaged && m_hIcon != NULL)
+ ::DestroyIcon(m_hIcon);
+ m_hIcon = hIcon;
+ }
+
+ HICON Detach()
+ {
+ HICON hIcon = m_hIcon;
+ m_hIcon = NULL;
+ return hIcon;
+ }
+
+ operator HICON() const { return m_hIcon; }
+
+ bool IsNull() const { return m_hIcon == NULL; }
+
+// Create/destroy methods
+ HICON LoadIcon(ATL::_U_STRINGorID icon)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ m_hIcon = ::LoadIcon(ModuleHelper::GetResourceInstance(), icon.m_lpstr);
+ return m_hIcon;
+ }
+
+ HICON LoadIcon(ATL::_U_STRINGorID icon, int cxDesired, int cyDesired, UINT fuLoad = 0)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ m_hIcon = (HICON) ::LoadImage(ModuleHelper::GetResourceInstance(), icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad);
+ return m_hIcon;
+ }
+
+#ifndef _WIN32_WCE
+ HICON LoadOEMIcon(LPCTSTR lpstrIconName)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(IsOEMIcon(lpstrIconName));
+ m_hIcon = ::LoadIcon(NULL, lpstrIconName);
+ return m_hIcon;
+ }
+
+ HICON CreateIcon(int nWidth, int nHeight, BYTE cPlanes, BYTE cBitsPixel, CONST BYTE* lpbANDbits, CONST BYTE *lpbXORbits)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(lpbANDbits != NULL);
+ ATLASSERT(lpbXORbits != NULL);
+ m_hIcon = ::CreateIcon(ModuleHelper::GetResourceInstance(), nWidth, nHeight, cPlanes, cBitsPixel, lpbANDbits, lpbXORbits);
+ return m_hIcon;
+ }
+
+ HICON CreateIconFromResource(PBYTE pBits, DWORD dwResSize, DWORD dwVersion = 0x00030000)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(pBits != NULL);
+ m_hIcon = ::CreateIconFromResource(pBits, dwResSize, TRUE, dwVersion);
+ return m_hIcon;
+ }
+
+ HICON CreateIconFromResourceEx(PBYTE pbBits, DWORD cbBits, DWORD dwVersion = 0x00030000, int cxDesired = 0, int cyDesired = 0, UINT uFlags = LR_DEFAULTCOLOR)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(pbBits != NULL);
+ ATLASSERT(cbBits > 0);
+ m_hIcon = ::CreateIconFromResourceEx(pbBits, cbBits, TRUE, dwVersion, cxDesired, cyDesired, uFlags);
+ return m_hIcon;
+ }
+#endif // !_WIN32_WCE
+
+ HICON CreateIconIndirect(PICONINFO pIconInfo)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(pIconInfo != NULL);
+ m_hIcon = ::CreateIconIndirect(pIconInfo);
+ return m_hIcon;
+ }
+
+#ifndef _WIN32_WCE
+ HICON ExtractIcon(LPCTSTR lpszExeFileName, UINT nIconIndex)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(lpszExeFileName != NULL);
+ m_hIcon = ::ExtractIcon(ModuleHelper::GetModuleInstance(), lpszExeFileName, nIconIndex);
+ return m_hIcon;
+ }
+
+ HICON ExtractAssociatedIcon(HINSTANCE hInst, LPTSTR lpIconPath, LPWORD lpiIcon)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(lpIconPath != NULL);
+ ATLASSERT(lpiIcon != NULL);
+ m_hIcon = ::ExtractAssociatedIcon(hInst, lpIconPath, lpiIcon);
+ return m_hIcon;
+ }
+#endif // !_WIN32_WCE
+
+ BOOL DestroyIcon()
+ {
+ ATLASSERT(m_hIcon != NULL);
+ BOOL bRet = ::DestroyIcon(m_hIcon);
+ if(bRet != FALSE)
+ m_hIcon = NULL;
+ return bRet;
+ }
+
+// Operations
+#ifndef _WIN32_WCE
+ HICON CopyIcon()
+ {
+ ATLASSERT(m_hIcon != NULL);
+ return ::CopyIcon(m_hIcon);
+ }
+
+ HICON DuplicateIcon()
+ {
+ ATLASSERT(m_hIcon != NULL);
+ return ::DuplicateIcon(NULL, m_hIcon);
+ }
+#endif // !_WIN32_WCE
+
+ BOOL DrawIcon(HDC hDC, int x, int y)
+ {
+ ATLASSERT(m_hIcon != NULL);
+#ifndef _WIN32_WCE
+ return ::DrawIcon(hDC, x, y, m_hIcon);
+#else // CE specific
+ return ::DrawIconEx(hDC, x, y, m_hIcon, 0, 0, 0, NULL, DI_NORMAL);
+#endif // _WIN32_WCE
+ }
+
+ BOOL DrawIcon(HDC hDC, POINT pt)
+ {
+ ATLASSERT(m_hIcon != NULL);
+#ifndef _WIN32_WCE
+ return ::DrawIcon(hDC, pt.x, pt.y, m_hIcon);
+#else // CE specific
+ return ::DrawIconEx(hDC, pt.x, pt.y, m_hIcon, 0, 0, 0, NULL, DI_NORMAL);
+#endif // _WIN32_WCE
+ }
+
+ BOOL DrawIconEx(HDC hDC, int x, int y, int cxWidth, int cyWidth, UINT uStepIfAniCur = 0, HBRUSH hbrFlickerFreeDraw = NULL, UINT uFlags = DI_NORMAL)
+ {
+ ATLASSERT(m_hIcon != NULL);
+ return ::DrawIconEx(hDC, x, y, m_hIcon, cxWidth, cyWidth, uStepIfAniCur, hbrFlickerFreeDraw, uFlags);
+ }
+
+ BOOL DrawIconEx(HDC hDC, POINT pt, SIZE size, UINT uStepIfAniCur = 0, HBRUSH hbrFlickerFreeDraw = NULL, UINT uFlags = DI_NORMAL)
+ {
+ ATLASSERT(m_hIcon != NULL);
+ return ::DrawIconEx(hDC, pt.x, pt.y, m_hIcon, size.cx, size.cy, uStepIfAniCur, hbrFlickerFreeDraw, uFlags);
+ }
+
+#ifndef _WIN32_WCE
+ BOOL GetIconInfo(PICONINFO pIconInfo) const
+ {
+ ATLASSERT(m_hIcon != NULL);
+ ATLASSERT(pIconInfo != NULL);
+ return ::GetIconInfo(m_hIcon, pIconInfo);
+ }
+
+#if (_WIN32_WINNT >= 0x0600)
+ BOOL GetIconInfoEx(PICONINFOEX pIconInfo) const
+ {
+ ATLASSERT(m_hIcon != NULL);
+ ATLASSERT(pIconInfo != NULL);
+ return ::GetIconInfoEx(m_hIcon, pIconInfo);
+ }
+#endif // (_WIN32_WINNT >= 0x0600)
+
+#if defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+ HRESULT LoadIconMetric(ATL::_U_STRINGorID icon, int lims)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ USES_CONVERSION;
+ return ::LoadIconMetric(ModuleHelper::GetResourceInstance(), T2CW(icon.m_lpstr), lims, &m_hIcon);
+ }
+
+ HRESULT LoadIconWithScaleDown(ATL::_U_STRINGorID icon, int cx, int cy)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ USES_CONVERSION;
+ return ::LoadIconWithScaleDown(ModuleHelper::GetResourceInstance(), T2CW(icon.m_lpstr), cx, cy, &m_hIcon);
+ }
+
+ HRESULT LoadOEMIconMetric(LPCTSTR lpstrIconName, int lims)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(IsOEMIcon(lpstrIconName));
+ return ::LoadIconMetric(NULL, (LPCWSTR)lpstrIconName, lims, &m_hIcon);
+ }
+
+ HRESULT LoadOEMIconWithScaleDown(LPCTSTR lpstrIconName, int cx, int cy)
+ {
+ ATLASSERT(m_hIcon == NULL);
+ ATLASSERT(IsOEMIcon(lpstrIconName));
+ USES_CONVERSION;
+ return ::LoadIconWithScaleDown(NULL, (LPCWSTR)lpstrIconName, cx, cy, &m_hIcon);
+ }
+#endif // defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
+#endif // !_WIN32_WCE
+
+ // Helper
+#ifndef _WIN32_WCE
+ static bool IsOEMIcon(LPCTSTR lpstrIconName)
+ {
+#if (WINVER >= 0x0600)
+ return (lpstrIconName == IDI_APPLICATION || lpstrIconName == IDI_ASTERISK || lpstrIconName == IDI_EXCLAMATION ||
+ lpstrIconName == IDI_HAND || lpstrIconName == IDI_QUESTION || lpstrIconName == IDI_WINLOGO ||
+ lpstrIconName == IDI_SHIELD);
+#else // !(WINVER >= 0x0600)
+ return (lpstrIconName == IDI_APPLICATION || lpstrIconName == IDI_ASTERISK || lpstrIconName == IDI_EXCLAMATION ||
+ lpstrIconName == IDI_HAND || lpstrIconName == IDI_QUESTION || lpstrIconName == IDI_WINLOGO);
+#endif // !(WINVER >= 0x0600)
+ }
+#endif // !_WIN32_WCE
+};
+
+typedef CIconT<false> CIconHandle;
+typedef CIconT<true> CIcon;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CCursor
+
+// protect template member from a winuser.h macro
+#ifdef CopyCursor
+ #undef CopyCursor
+#endif
+
+template <bool t_bManaged>
+class CCursorT
+{
+public:
+ HCURSOR m_hCursor;
+
+// Constructor/destructor/operators
+ CCursorT(HCURSOR hCursor = NULL) : m_hCursor(hCursor)
+ { }
+
+ ~CCursorT()
+ {
+ if(t_bManaged && m_hCursor != NULL)
+ DestroyCursor();
+ }
+
+ CCursorT<t_bManaged>& operator =(HCURSOR hCursor)
+ {
+ Attach(hCursor);
+ return *this;
+ }
+
+ void Attach(HCURSOR hCursor)
+ {
+ if(t_bManaged && m_hCursor != NULL)
+ DestroyCursor();
+ m_hCursor = hCursor;
+ }
+
+ HCURSOR Detach()
+ {
+ HCURSOR hCursor = m_hCursor;
+ m_hCursor = NULL;
+ return hCursor;
+ }
+
+ operator HCURSOR() const { return m_hCursor; }
+
+ bool IsNull() const { return m_hCursor == NULL; }
+
+// Create/destroy methods
+ HCURSOR LoadCursor(ATL::_U_STRINGorID cursor)
+ {
+ ATLASSERT(m_hCursor == NULL);
+ m_hCursor = ::LoadCursor(ModuleHelper::GetResourceInstance(), cursor.m_lpstr);
+ return m_hCursor;
+ }
+
+ HCURSOR LoadSysCursor(LPCTSTR lpstrCursorName)
+ {
+ ATLASSERT(m_hCursor == NULL);
+#if (WINVER >= 0x0500)
+ ATLASSERT(lpstrCursorName == IDC_ARROW || lpstrCursorName == IDC_IBEAM || lpstrCursorName == IDC_WAIT ||
+ lpstrCursorName == IDC_CROSS || lpstrCursorName == IDC_UPARROW || lpstrCursorName == IDC_SIZE ||
+ lpstrCursorName == IDC_ICON || lpstrCursorName == IDC_SIZENWSE || lpstrCursorName == IDC_SIZENESW ||
+ lpstrCursorName == IDC_SIZEWE || lpstrCursorName == IDC_SIZENS || lpstrCursorName == IDC_SIZEALL ||
+ lpstrCursorName == IDC_NO || lpstrCursorName == IDC_APPSTARTING || lpstrCursorName == IDC_HELP ||
+ lpstrCursorName == IDC_HAND);
+#else // !(WINVER >= 0x0500)
+ ATLASSERT(lpstrCursorName == IDC_ARROW || lpstrCursorName == IDC_IBEAM || lpstrCursorName == IDC_WAIT ||
+ lpstrCursorName == IDC_CROSS || lpstrCursorName == IDC_UPARROW || lpstrCursorName == IDC_SIZE ||
+ lpstrCursorName == IDC_ICON || lpstrCursorName == IDC_SIZENWSE || lpstrCursorName == IDC_SIZENESW ||
+ lpstrCursorName == IDC_SIZEWE || lpstrCursorName == IDC_SIZENS || lpstrCursorName == IDC_SIZEALL ||
+ lpstrCursorName == IDC_NO || lpstrCursorName == IDC_APPSTARTING || lpstrCursorName == IDC_HELP);
+#endif // !(WINVER >= 0x0500)
+ m_hCursor = ::LoadCursor(NULL, lpstrCursorName);
+ return m_hCursor;
+ }
+
+ // deprecated
+ HCURSOR LoadOEMCursor(LPCTSTR lpstrCursorName)
+ {
+ return LoadSysCursor(lpstrCursorName);
+ }
+
+ HCURSOR LoadCursor(ATL::_U_STRINGorID cursor, int cxDesired, int cyDesired, UINT fuLoad = 0)
+ {
+ ATLASSERT(m_hCursor == NULL);
+ m_hCursor = (HCURSOR) ::LoadImage(ModuleHelper::GetResourceInstance(), cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad);
+ return m_hCursor;
+ }
+
+#ifndef _WIN32_WCE
+ HCURSOR LoadCursorFromFile(LPCTSTR pstrFilename)
+ {
+ ATLASSERT(m_hCursor == NULL);
+ ATLASSERT(pstrFilename != NULL);
+ m_hCursor = ::LoadCursorFromFile(pstrFilename);
+ return m_hCursor;
+ }
+#endif // !_WIN32_WCE
+
+#if !defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)))
+ HCURSOR CreateCursor(int xHotSpot, int yHotSpot, int nWidth, int nHeight, CONST VOID *pvANDPlane, CONST VOID *pvXORPlane)
+ {
+ ATLASSERT(m_hCursor == NULL);
+ m_hCursor = ::CreateCursor(ModuleHelper::GetResourceInstance(), xHotSpot, yHotSpot, nWidth, nHeight, pvANDPlane, pvXORPlane);
+ return m_hCursor;
+ }
+#endif // !defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)))
+
+#ifndef _WIN32_WCE
+ HCURSOR CreateCursorFromResource(PBYTE pBits, DWORD dwResSize, DWORD dwVersion = 0x00030000)
+ {
+ ATLASSERT(m_hCursor == NULL);
+ ATLASSERT(pBits != NULL);
+ m_hCursor = (HCURSOR)::CreateIconFromResource(pBits, dwResSize, FALSE, dwVersion);
+ return m_hCursor;
+ }
+
+ HCURSOR CreateCursorFromResourceEx(PBYTE pbBits, DWORD cbBits, DWORD dwVersion = 0x00030000, int cxDesired = 0, int cyDesired = 0, UINT uFlags = LR_DEFAULTCOLOR)
+ {
+ ATLASSERT(m_hCursor == NULL);
+ ATLASSERT(pbBits != NULL);
+ ATLASSERT(cbBits > 0);
+ m_hCursor = (HCURSOR)::CreateIconFromResourceEx(pbBits, cbBits, FALSE, dwVersion, cxDesired, cyDesired, uFlags);
+ return m_hCursor;
+ }
+#endif // !_WIN32_WCE
+
+ BOOL DestroyCursor()
+ {
+ ATLASSERT(m_hCursor != NULL);
+#if !defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)))
+ BOOL bRet = ::DestroyCursor(m_hCursor);
+ if(bRet != FALSE)
+ m_hCursor = NULL;
+ return bRet;
+#else // !(!defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP))))
+ ATLTRACE2(atlTraceUI, 0, _T("Warning: This version of Windows CE does not have ::DestroyCursor()\n"));
+ return FALSE;
+#endif // !(!defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP))))
+ }
+
+// Operations
+#ifndef _WIN32_WCE
+ HCURSOR CopyCursor()
+ {
+ ATLASSERT(m_hCursor != NULL);
+ return (HCURSOR)::CopyIcon((HICON)m_hCursor);
+ }
+#endif // !_WIN32_WCE
+
+#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+ BOOL GetCursorInfo(LPCURSORINFO pCursorInfo)
+ {
+ ATLASSERT(m_hCursor != NULL);
+ ATLASSERT(pCursorInfo != NULL);
+ return ::GetCursorInfo(pCursorInfo);
+ }
+#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
+};
+
+typedef CCursorT<false> CCursorHandle;
+typedef CCursorT<true> CCursor;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CResource - Wraps a generic Windows resource.
+// Use it with custom resource types other than the
+// standard RT_CURSOR, RT_BITMAP, etc.
+
+class CResource
+{
+public:
+ HGLOBAL m_hGlobal;
+ HRSRC m_hResource;
+
+// Constructor/destructor
+ CResource() : m_hGlobal(NULL), m_hResource(NULL)
+ { }
+
+ ~CResource()
+ {
+ Release();
+ }
+
+// Load methods
+ bool Load(ATL::_U_STRINGorID Type, ATL::_U_STRINGorID ID)
+ {
+ ATLASSERT(m_hResource == NULL);
+ ATLASSERT(m_hGlobal == NULL);
+
+ m_hResource = ::FindResource(ModuleHelper::GetResourceInstance(), ID.m_lpstr, Type.m_lpstr);
+ if(m_hResource == NULL)
+ return false;
+
+ m_hGlobal = ::LoadResource(ModuleHelper::GetResourceInstance(), m_hResource);
+ if(m_hGlobal == NULL)
+ {
+ m_hResource = NULL;
+ return false;
+ }
+
+ return true;
+ }
+
+#ifndef _WIN32_WCE
+ bool LoadEx(ATL::_U_STRINGorID Type, ATL::_U_STRINGorID ID, WORD wLanguage)
+ {
+ ATLASSERT(m_hResource == NULL);
+ ATLASSERT(m_hGlobal == NULL);
+
+ m_hResource = ::FindResourceEx(ModuleHelper::GetResourceInstance(), ID.m_lpstr, Type.m_lpstr, wLanguage);
+ if(m_hResource == NULL)
+ return false;
+
+ m_hGlobal = ::LoadResource(ModuleHelper::GetResourceInstance(), m_hResource);
+ if(m_hGlobal == NULL)
+ {
+ m_hResource = NULL;
+ return false;
+ }
+
+ return true;
+ }
+#endif // !_WIN32_WCE
+
+// Misc. operations
+ DWORD GetSize() const
+ {
+ ATLASSERT(m_hResource != NULL);
+ return ::SizeofResource(ModuleHelper::GetResourceInstance(), m_hResource);
+ }
+
+ LPVOID Lock()
+ {
+ ATLASSERT(m_hResource != NULL);
+ ATLASSERT(m_hGlobal != NULL);
+ LPVOID pVoid = ::LockResource(m_hGlobal);
+ ATLASSERT(pVoid != NULL);
+ return pVoid;
+ }
+
+ void Release()
+ {
+ if(m_hGlobal != NULL)
+ {
+ FreeResource(m_hGlobal);
+ m_hGlobal = NULL;
+ m_hResource = NULL;
+ }
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Toolbar resource descriptor
+
+struct _AtlToolBarData
+{
+ WORD wVersion;
+ WORD wWidth;
+ WORD wHeight;
+ WORD wItemCount;
+
+ WORD* items()
+ { return (WORD*)(this+1); }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Global functions for loading resources
+
+inline HACCEL AtlLoadAccelerators(ATL::_U_STRINGorID table)
+{
+ return ::LoadAccelerators(ModuleHelper::GetResourceInstance(), table.m_lpstr);
+}
+
+inline HMENU AtlLoadMenu(ATL::_U_STRINGorID menu)
+{
+ return ::LoadMenu(ModuleHelper::GetResourceInstance(), menu.m_lpstr);
+}
+
+inline HBITMAP AtlLoadBitmap(ATL::_U_STRINGorID bitmap)
+{
+ return ::LoadBitmap(ModuleHelper::GetResourceInstance(), bitmap.m_lpstr);
+}
+
+#ifdef OEMRESOURCE
+inline HBITMAP AtlLoadSysBitmap(ATL::_U_STRINGorID bitmap)
+{
+#ifdef _DEBUG
+ WORD wID = (WORD)bitmap.m_lpstr;
+ ATLASSERT(wID >= 32734 && wID <= 32767);
+#endif // _DEBUG
+ return ::LoadBitmap(NULL, bitmap.m_lpstr);
+}
+#endif // OEMRESOURCE
+
+inline HCURSOR AtlLoadCursor(ATL::_U_STRINGorID cursor)
+{
+ return ::LoadCursor(ModuleHelper::GetResourceInstance(), cursor.m_lpstr);
+}
+
+inline HCURSOR AtlLoadSysCursor(LPCTSTR lpCursorName)
+{
+#if (WINVER >= 0x0500)
+ ATLASSERT(lpCursorName == IDC_ARROW || lpCursorName == IDC_IBEAM || lpCursorName == IDC_WAIT ||
+ lpCursorName == IDC_CROSS || lpCursorName == IDC_UPARROW || lpCursorName == IDC_SIZE ||
+ lpCursorName == IDC_ICON || lpCursorName == IDC_SIZENWSE || lpCursorName == IDC_SIZENESW ||
+ lpCursorName == IDC_SIZEWE || lpCursorName == IDC_SIZENS || lpCursorName == IDC_SIZEALL ||
+ lpCursorName == IDC_NO || lpCursorName == IDC_APPSTARTING || lpCursorName == IDC_HELP ||
+ lpCursorName == IDC_HAND);
+#else // !(WINVER >= 0x0500)
+ ATLASSERT(lpCursorName == IDC_ARROW || lpCursorName == IDC_IBEAM || lpCursorName == IDC_WAIT ||
+ lpCursorName == IDC_CROSS || lpCursorName == IDC_UPARROW || lpCursorName == IDC_SIZE ||
+ lpCursorName == IDC_ICON || lpCursorName == IDC_SIZENWSE || lpCursorName == IDC_SIZENESW ||
+ lpCursorName == IDC_SIZEWE || lpCursorName == IDC_SIZENS || lpCursorName == IDC_SIZEALL ||
+ lpCursorName == IDC_NO || lpCursorName == IDC_APPSTARTING || lpCursorName == IDC_HELP);
+#endif // !(WINVER >= 0x0500)
+ return ::LoadCursor(NULL, lpCursorName);
+}
+
+inline HICON AtlLoadIcon(ATL::_U_STRINGorID icon)
+{
+ return ::LoadIcon(ModuleHelper::GetResourceInstance(), icon.m_lpstr);
+}
+
+#ifndef _WIN32_WCE
+inline HICON AtlLoadSysIcon(LPCTSTR lpIconName)
+{
+#if (WINVER >= 0x0600)
+ ATLASSERT(lpIconName == IDI_APPLICATION || lpIconName == IDI_ASTERISK || lpIconName == IDI_EXCLAMATION ||
+ lpIconName == IDI_HAND || lpIconName == IDI_QUESTION || lpIconName == IDI_WINLOGO ||
+ lpIconName == IDI_SHIELD);
+#else // !(WINVER >= 0x0600)
+ ATLASSERT(lpIconName == IDI_APPLICATION || lpIconName == IDI_ASTERISK || lpIconName == IDI_EXCLAMATION ||
+ lpIconName == IDI_HAND || lpIconName == IDI_QUESTION || lpIconName == IDI_WINLOGO);
+#endif // !(WINVER >= 0x0600)
+ return ::LoadIcon(NULL, lpIconName);
+}
+#endif // !_WIN32_WCE
+
+inline HBITMAP AtlLoadBitmapImage(ATL::_U_STRINGorID bitmap, UINT fuLoad = LR_DEFAULTCOLOR)
+{
+ return (HBITMAP)::LoadImage(ModuleHelper::GetResourceInstance(), bitmap.m_lpstr, IMAGE_BITMAP, 0, 0, fuLoad);
+}
+
+inline HCURSOR AtlLoadCursorImage(ATL::_U_STRINGorID cursor, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0)
+{
+ return (HCURSOR)::LoadImage(ModuleHelper::GetResourceInstance(), cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad);
+}
+
+inline HICON AtlLoadIconImage(ATL::_U_STRINGorID icon, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0)
+{
+ return (HICON)::LoadImage(ModuleHelper::GetResourceInstance(), icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad);
+}
+
+#ifdef OEMRESOURCE
+inline HBITMAP AtlLoadSysBitmapImage(WORD wBitmapID, UINT fuLoad = LR_DEFAULTCOLOR)
+{
+ ATLASSERT(wBitmapID >= 32734 && wBitmapID <= 32767);
+ ATLASSERT((fuLoad & LR_LOADFROMFILE) == 0); // this one doesn't load from a file
+ return (HBITMAP)::LoadImage(NULL, MAKEINTRESOURCE(wBitmapID), IMAGE_BITMAP, 0, 0, fuLoad);
+}
+#endif // OEMRESOURCE
+
+inline HCURSOR AtlLoadSysCursorImage(ATL::_U_STRINGorID cursor, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0)
+{
+#ifdef _DEBUG
+ WORD wID = (WORD)cursor.m_lpstr;
+ ATLASSERT((wID >= 32512 && wID <= 32516) || (wID >= 32640 && wID <= 32648) || (wID == 32650) || (wID == 32651));
+ ATLASSERT((fuLoad & LR_LOADFROMFILE) == 0); // this one doesn't load from a file
+#endif // _DEBUG
+ return (HCURSOR)::LoadImage(NULL, cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad);
+}
+
+inline HICON AtlLoadSysIconImage(ATL::_U_STRINGorID icon, UINT fuLoad = LR_DEFAULTCOLOR | LR_DEFAULTSIZE, int cxDesired = 0, int cyDesired = 0)
+{
+#ifdef _DEBUG
+ WORD wID = (WORD)icon.m_lpstr;
+ ATLASSERT(wID >= 32512 && wID <= 32517);
+ ATLASSERT((fuLoad & LR_LOADFROMFILE) == 0); // this one doesn't load from a file
+#endif // _DEBUG
+ return (HICON)::LoadImage(NULL, icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad);
+}
+
+#if (_ATL_VER < 0x0700)
+inline int AtlLoadString(UINT uID, LPTSTR lpBuffer, int nBufferMax)
+{
+ return ::LoadString(ModuleHelper::GetResourceInstance(), uID, lpBuffer, nBufferMax);
+}
+#else
+
+using ATL::AtlLoadString;
+
+#endif // (_ATL_VER < 0x0700)
+
+#ifdef _WIN32_WCE // CE only direct access to the resource
+inline LPCTSTR AtlLoadString(UINT uID)
+{
+ LPCTSTR s = (LPCTSTR)::LoadString(ModuleHelper::GetResourceInstance(), uID, NULL, 0);
+#ifdef DEBUG // Check for null-termination
+ if(s != NULL)
+ // Note: RC -n <file.rc> compiles null-terminated resource strings
+ ATLASSERT(s[*((WORD*)s -1) - 1] == L'\0');
+#endif
+ return s;
+}
+#endif // _WIN32_WCE
+
+inline bool AtlLoadString(UINT uID, BSTR& bstrText)
+{
+ USES_CONVERSION;
+ ATLASSERT(bstrText == NULL);
+
+ LPTSTR lpstrText = NULL;
+ int nRes = 0;
+ for(int nLen = 256; ; nLen *= 2)
+ {
+ ATLTRY(lpstrText = new TCHAR[nLen]);
+ if(lpstrText == NULL)
+ break;
+ nRes = ::LoadString(ModuleHelper::GetResourceInstance(), uID, lpstrText, nLen);
+ if(nRes < nLen - 1)
+ break;
+ delete [] lpstrText;
+ lpstrText = NULL;
+ }
+
+ if(lpstrText != NULL)
+ {
+ if(nRes != 0)
+ bstrText = ::SysAllocString(T2OLE(lpstrText));
+ delete [] lpstrText;
+ }
+
+ return (bstrText != NULL) ? true : false;
+}
+
+}; // namespace WTL
+
+#endif // __ATLUSER_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlwince.h b/plugins/SmartAutoReplier/wtl/atlwince.h
new file mode 100644
index 0000000000..a845949217
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlwince.h
@@ -0,0 +1,2987 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLWINCE_H__
+#define __ATLWINCE_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlwince.h requires atlapp.h to be included first
+#endif
+
+#ifndef __ATLWIN_H__
+ #error atlwince.h requires atlwin.h to be included first
+#endif
+
+#ifndef _WIN32_WCE
+ #error atlwince.h compiles under Windows CE only
+#endif
+
+#if (_WIN32_WCE < 300)
+ #error atlwince.h requires Windows CE 3.0 or higher.
+#endif
+
+#if defined(WIN32_PLATFORM_WFSP) && _MSC_VER < 1400 // EVC compiling SmartPhone code
+ #if (WIN32_PLATFORM_WFSP < 200)
+ #error atlwince.h requires Smartphone 2003 or higher
+ #endif
+#endif // WIN32_PLATFORM_WFSP
+
+#if defined(WIN32_PLATFORM_PSPC) && _MSC_VER < 1400 // EVC compiling Pocket PC code
+ #if (WIN32_PLATFORM_PSPC < 310)
+ #error atlwince.h requires Pocket PC 2002 or higher
+ #endif
+#endif // WIN32_PLATFORM_PSPC
+
+#if !defined(_AYGSHELL_H_) && !defined(__AYGSHELL_H__)
+ #error atlwince.h requires aygshell.h to be included first
+#else
+ #if defined(WIN32_PLATFORM_WFSP) && !defined(_TPCSHELL_H_)
+ #error SmartPhone dialog classes require tpcshell.h to be included first
+ #endif
+#endif
+
+#if (_MSC_VER >= 1400) // VS2005
+ #include <DeviceResolutionAware.h>
+ #define _WTL_CE_DRA
+#endif // (_MSC_VER >= 1400)
+
+#if !defined(_WTL_CE_NO_DIALOGS) && !defined(__ATLFRAME_H__)
+ #error Orientation aware dialog classes require atlframe.h to be included first
+#endif
+
+#if !defined(_WTL_CE_NO_APPWINDOW) && !defined(__ATLFRAME_H__)
+ #error Application window class require atlframe.h to be included first
+#endif
+
+#if !defined(_WTL_CE_NO_ZOOMSCROLL) && !defined(__ATLSCRL_H__)
+ #error ZoomScroll implementation requires atlscrl.h to be included first
+#endif
+
+#if !defined(_WTL_CE_NO_ZOOMSCROLL)
+ #if !(defined(__ATLTYPES_H__) || (defined(__ATLMISC_H__) && !defined(_WTL_NO_WTYPES)))
+ #error ZoomScroll requires _WTL_NO_WTYPES not to be defined and either atlmisc.h or atltypes.h to be included first
+ #endif // !(defined(__ATLTYPES_H__) || (defined(__ATLMISC_H__) && !defined(_WTL_NO_WTYPES)))
+#endif // !defined(_WTL_CE_NO_ZOOMSCROLL)
+
+#if !defined(WIN32_PLATFORM_WFSP) && !defined(WIN32_PLATFORM_PSPC)
+ #define _WTL_CE_NO_CONTROLS
+#endif // !defined(WIN32_PLATFORM_WFSP) && !defined(WIN32_PLATFORM_PSPC)
+
+#ifndef _WTL_CE_NO_CONTROLS
+ #ifndef __ATLCTRLS_H__
+ #error The PPC/SmartPhone controls classes require atlctrls.h to be included first
+ #endif
+
+ #include <htmlctrl.h>
+ #pragma comment(lib, "htmlview.lib")
+
+ #include <voicectl.h>
+ #pragma comment(lib, "voicectl.lib")
+
+ #ifdef WIN32_PLATFORM_PSPC
+ #include <richink.h>
+ #pragma comment(lib, "richink.lib")
+
+ #include <inkx.h>
+ #pragma comment(lib, "inkx.lib")
+
+ #include <doclist.h>
+ #pragma comment(lib, "doclist.lib")
+ #endif
+#endif
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// CStdDialogBase<T, t_shidiFlags, t_bModal> : Standard PPC/SmartPhone dialog base class
+// CStdDialogImplBase - Base implementation of standard dialog
+// CStdDialogImpl<T, t_shidiFlags, t_bModal> : Standard dialog implementation
+// CStdIndirectDialogImpl - implementation of standard indirect PPC/SmartPhone dialog
+// CStdAxDialogImpl<T, t_shidiFlags, t_bModal> : Standard AxDialog implementation
+// CStdSimpleDialog<t_wDlgTemplateID, t_shidiFlags> : Standard simple dialog
+// CStdDialogResizeImplBase - Base implementation of orientation resizing standard dialog
+// CStdDialogResizeImpl<T, t_shidiFlags, t_bModal> : Orientation resizing standard dialog implementation
+// CStdAxDialogResizeImpl - implementation of orientation resizing standard AxDialog
+// CStdSimpleDialogResizeImpl<T, t_wDlgTemplateID, t_shidiFlags> : Standard resizing simple dialog implementation
+// CStdOrientedDialogBase - Oriented PPC standard dialog base class
+// CStdOrientedDialogImplBase - Oriented PPC standard dialog base implementation
+// CStdOrientedDialogImpl<T, t_shidiFlags, t_bModal> : Oriented PPC standard dialog implementation
+// CStdAxOrientedDialogImpl - Oriented PPC standard AxDialog implementation
+// CStdSimpleOrientedDialog<t_wDlgTemplateID, t_wDlgLandscapeID, t_shidiFlags> : Standard simple orientable dialog
+//
+// CAppInfoBase : Helper for application state save/restore to registry
+// CAppInfoT<T> : CAppInfoBase constructed from a CAppWindow<T>
+// CAppWindowBase<T> : Base class for PPC/SmartPhone well-behaved application window or dialog
+// CAppWindow<T> : PPC/SmartPhone well-behaved application window class
+// CAppDialog<T> : PPC/SmartPhone well-behaved application dialog class
+// CAppStdDialogImplBase - Base implementation of standard application dialogs
+// CAppStdDialogImpl<T, t_shidiFlags, t_bModal> : Implementation of standard application dialog
+// CAppStdDialogResizeImpl - implementation of orientation resizing standard application dialog
+// CAppStdAxDialogImpl - Implementation of standard application AxDialog
+// CAppStdAxDialogResizeImpl - implementation of orientation resizing standard application AxDialog
+// CAppStdOrientedDialogImpl - implementation of oriented PPC standard application dialog
+// CAppStdAxOrientedDialogImpl - implementation of oriented PPC standard application AxDialog
+//
+// CFullScreenFrame<T, t_bHasSip> : Full screen frame class
+//
+// CZoomScrollImpl<T> : WinCE zooming implementation
+//
+// CBottomTabViewImpl<T, TBase, TWinTraits> - CBottomTabView
+// CHtmlCtrlT<TBase> - CHtmlCtrl
+// CRichInkCtrlT<TBase> - CRichInkCtrl
+// CInkXCtrlT<TBase> - CInkXCtrl
+// CVoiceRecorderCtrlT<TBase> - CVoiceRecorderCtrl
+// CDocListCtrlT<TBase> - CDocListCtrl
+// CCapEditT<TBase> - CCapEdit
+// CTTStaticT<TBase> - CTTStatic
+// CTTButtonT<TBase> - CTTButton
+//
+// CSpinCtrlT<TBase> - CSpinCtrl : SmartPhone specific UpDown control
+// CSpinned<TBase, t_bExpandOnly> : SmartPhone association of control and Spin
+// CSpinListBox : SmartPhone spinned ListBox control
+// CExpandListBox : SmartPhone expandable ListBox control
+// CExpandEdit : SmartPhone expandable Edit control
+// CExpandCapEdit : SmartPhone expandable CapEdit control
+//
+// Global functions:
+// AtlCreateMenuBar()
+// AtlCreateEmptyMenuBar()
+// AtlIsEditFocus()
+// AtlActivateBackKey()
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// MenuBar creation functions for property sheets and dialogs
+// Frame windows use CreateSimpleCEMenuBar
+
+inline HWND AtlCreateMenuBar(SHMENUBARINFO& mbi)
+{
+ ATLASSERT(::IsWindow(mbi.hwndParent));
+ ATLVERIFY(::SHCreateMenuBar(&mbi) != FALSE);
+ return mbi.hwndMB;
+};
+
+inline HWND AtlCreateMenuBar(HWND hWnd, UINT nToolBarId = ATL_IDW_TOOLBAR, DWORD dwFlags = 0, int nBmpId = 0, int cBmpImages = 0, COLORREF clrBk = 0)
+{
+ SHMENUBARINFO mbi = { sizeof(mbi), hWnd, dwFlags, nToolBarId, ModuleHelper::GetResourceInstance(), nBmpId, cBmpImages, 0, clrBk };
+ return AtlCreateMenuBar(mbi);
+}
+
+inline HWND AtlCreateEmptyMenuBar(HWND hWnd, bool bSip = true)
+{
+ SHMENUBARINFO embi = { sizeof(SHMENUBARINFO), hWnd, SHCMBF_EMPTYBAR };
+ if (!bSip)
+ embi.dwFlags |= SHCMBF_HIDESIPBUTTON;
+
+ return AtlCreateMenuBar(embi);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// Helper functions for SmartPhone back key handling
+
+inline bool AtlIsEditFocus()
+{
+ ATL::CWindow wCtrl = GetFocus();
+ if (wCtrl.IsWindow())
+ {
+ TCHAR szClassName[8] = {0};
+ ATLVERIFY(::GetClassName(wCtrl.m_hWnd, szClassName, 8));
+ return !_tcscmp(szClassName, _T("Edit")) || !_tcscmp(szClassName, WC_CAPEDIT);
+ }
+ return false;
+}
+
+#if defined WIN32_PLATFORM_WFSP
+inline void AtlActivateBackKey(HWND hMenuBar)
+{
+ ATLASSERT(::IsWindow(hMenuBar));
+ ::SendMessage(hMenuBar, SHCMBM_OVERRIDEKEY, VK_TBACK,
+ MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY, SHMBOF_NODEFAULT | SHMBOF_NOTIFY));
+}
+#endif // WIN32_PLATFORM_WFSP
+
+// --- Standard PPC/SmartPhone dialogs ---
+
+#ifndef _WTL_CE_NO_DIALOGS
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdDialogBase - base class for standard PPC/SmartPhone dialogs
+
+#define WTL_STD_SHIDIF SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN
+#define WTL_SP_SHIDIF SHIDIF_SIZEDLGFULLSCREEN
+
+// Title setting macros
+#define WTL_DLG_TITLEHEIGHT(iHeight) static const int GetTitleHeight(){return iHeight;}
+#define WTL_DLG_NOTITLE WTL_DLG_TITLEHEIGHT(0)
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdDialogBase - Base class for standard PPC/SmartPhone dialog
+
+template <class T, UINT t_shidiFlags, bool t_bModal = true>
+class CStdDialogBase
+{
+public:
+#ifdef WIN32_PLATFORM_PSPC
+// Pocket PC only Dialog title handling
+ const int nTitleHeight;
+
+ CStdDialogBase() : nTitleHeight(T::GetTitleHeight())
+ { }
+
+// Overloads
+ BOOL GetClientRect(LPRECT lpRect)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+ BOOL bRes = ::GetClientRect(pT->m_hWnd, lpRect);
+ if (nTitleHeight)
+ lpRect->top += nTitleHeight + 1;
+ return bRes;
+ }
+
+ BOOL SetWindowText(LPCTSTR lpszString)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+ BOOL bRes = ::SetWindowText(pT->m_hWnd, lpszString);
+ if (nTitleHeight != 0)
+ pT->DoPaintTitle();
+ return bRes;
+ }
+
+// Overrideables
+ static const int GetTitleHeight()
+ {
+ #ifdef _WTL_CE_DRA
+ return DRA::SCALEY(24);
+ #else // !_WTL_CE_DRA
+ CWindowDC dc(NULL);
+ return dc.GetDeviceCaps(LOGPIXELSY) >> 2; // LOGPIXELSY * 24 / 96,
+ #endif // !_WTL_CE_DRA
+ }
+
+ // Title painting
+ bool DoPaintTitle()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+ TCHAR sTitle[48];
+
+ // Preparation
+ CPaintDC dc(pT->m_hWnd);
+ CFont fontTitle = AtlCreateBoldFont();
+ CFontHandle fontOld = dc.SelectFont(fontTitle);
+ dc.SetTextColor(GetSysColor(COLOR_HIGHLIGHT));
+ int nLen = pT->GetWindowText(sTitle, 48);
+ int nWidth = dc.GetDeviceCaps(HORZRES);
+
+ // Display title text
+ RECT rTitle = { 0, 0, nWidth, nTitleHeight };
+ dc.FillRect(&rTitle, COLOR_3DHIGHLIGHT);
+ #ifdef _WTL_CE_DRA
+ rTitle.left = DRA::SCALEX(8);
+ #else // !_WTL_CE_DRA
+ rTitle.left = nTitleHeight / 3; // 8 == 24 / 3
+ #endif // !_WTL_CE_DRA
+ dc.DrawText(sTitle, nLen, &rTitle, DT_VCENTER | DT_SINGLELINE);
+ dc.SelectFont(fontOld);
+
+ // Draw bottom line, 2 pixels thick if HI_RES_AWARE
+ CPenHandle penOld = dc.SelectStockPen(BLACK_PEN);
+ POINT line[4] = {{0, nTitleHeight}, {nWidth, nTitleHeight}, {0, nTitleHeight - 1}, {nWidth, nTitleHeight - 1}};
+
+ #ifdef _WTL_CE_DRA
+ int nSeg = DRA::SCALEY(1);
+ #else // !_WTL_CE_DRA
+ int nSeg = nTitleHeight / 24;
+ #endif // !_WTL_CE_DRA
+
+ dc.Polyline(line, nSeg <= 2 ? nSeg * 2 : 4);
+ dc.SelectPen(penOld);
+
+ return false;
+ }
+
+ // Title preparation: move the dialog controls down to make room for title
+ void DialogTitleInit()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+
+ ATL::CWindow wCtl = pT->GetWindow(GW_CHILD);
+ while (wCtl.IsWindow())
+ {
+ RECT rCtl = { 0 };
+ wCtl.GetWindowRect(&rCtl);
+ ::MapWindowPoints(NULL, pT->m_hWnd, (LPPOINT)&rCtl, 2);
+ ::OffsetRect(&rCtl, 0, nTitleHeight);
+ wCtl.MoveWindow(&rCtl, FALSE);
+ wCtl = wCtl.GetWindow(GW_HWNDNEXT);
+ }
+ }
+
+ // SIP management
+ void DoSipInfo()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+
+ SIPINFO si = {sizeof(SIPINFO)};
+ SipGetInfo(&si);
+ if ((si.fdwFlags & SIPF_ON) ^ SIPF_ON)
+ si.rcVisibleDesktop.bottom = si.rcSipRect.bottom;
+ pT->MoveWindow(&si.rcVisibleDesktop, FALSE);
+ }
+
+// Title painting handler
+ LRESULT OnPaintTitle(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ return bHandled = nTitleHeight ? pT->DoPaintTitle() : FALSE;
+ }
+
+// SIP handler
+ LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ if (wParam == SPI_SETSIPINFO)
+ {
+ pT->DoSipInfo();
+ return TRUE;
+ }
+ return bHandled = FALSE;
+ }
+
+#elif defined WIN32_PLATFORM_WFSP
+// SmartPhone VK_TBACK key standard management
+ LRESULT OnHotKey(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ const UINT uModif = (UINT)LOWORD(lParam);
+ const UINT uVirtKey = (UINT)HIWORD(lParam);
+
+ if(uVirtKey == VK_TBACK)
+ if (AtlIsEditFocus())
+ ::SHSendBackToFocusWindow(uMsg, wParam, lParam);
+ else if (uModif & MOD_KEYUP)
+ pT->StdCloseDialog(IDCANCEL);
+ return 1;
+ }
+
+ // SmartPhone MenuBar and VK_TBACK key initialization
+ void StdSPInit()
+ {
+ T* pT = static_cast<T*>(this);
+ HWND hMenuBar = ::SHFindMenuBar(pT->m_hWnd);
+
+ if (!hMenuBar && (t_shidiFlags & SHIDIF_DONEBUTTON))
+ hMenuBar = CreateMenuBar(ATL_IDM_MENU_DONE);
+
+ if(hMenuBar != NULL)
+ AtlActivateBackKey(hMenuBar);
+ }
+
+ void SetStaticBold()
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+
+ CFontHandle fontBold = AtlCreateBoldFont(pT->GetFont());
+
+ ATL::CWindow wCtl = pT->GetWindow(GW_CHILD);
+
+ while (wCtl.IsWindow())
+ {
+ if ((short int)wCtl.GetDlgCtrlID() == IDC_STATIC)
+ wCtl.SetFont(fontBold);
+ wCtl = wCtl.GetWindow(GW_HWNDNEXT);
+ }
+ }
+#endif // WIN32_PLATFORM_WFSP
+
+// Platform dependant initialization
+ void StdPlatformInit()
+ {
+ T* pT = static_cast<T*>(this);
+#ifdef WIN32_PLATFORM_PSPC // Pocket PC title initialization
+ if (nTitleHeight != 0)
+ pT->DialogTitleInit();
+#elif defined(WIN32_PLATFORM_WFSP)
+ pT->StdSPInit();
+ SetStaticBold();
+#endif // WIN32_PLATFORM_WFSP
+ }
+
+ // Menu bar creation
+ HWND CreateMenuBar(UINT uiMB = T::IDD, int nBmpImages = 0)
+ {
+ T* pT = static_cast<T*>(this);
+ return AtlCreateMenuBar(pT->m_hWnd, uiMB, 0, nBmpImages ? uiMB : 0, nBmpImages);
+ }
+
+ // Dialog closing
+ void StdCloseDialog(WORD wID)
+ {
+ T* pT = static_cast<T*>(this);
+ if (t_bModal)
+ ::EndDialog(pT->m_hWnd, wID);
+ else
+ pT->DestroyWindow();
+ }
+
+ // Shell dialog layout initialization
+ void StdShidInit()
+ {
+ T* pT = static_cast<T*>(this);
+ SHINITDLGINFO shidi = { SHIDIM_FLAGS, pT->m_hWnd, t_shidiFlags };
+ ::SHInitDialog(&shidi);
+ }
+
+// IDC_INFOSTATIC background setting
+ LRESULT OnColorStatic(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ if (::GetDlgCtrlID((HWND)lParam) == IDC_INFOSTATIC)
+ {
+ ::SetBkMode((HDC)wParam, TRANSPARENT);
+ return (LRESULT)::GetSysColorBrush(COLOR_INFOBK);
+ }
+ return bHandled = FALSE;
+ }
+
+// Menu dialog ending
+ LRESULT OnMenuClose(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->StdCloseDialog((WORD)(wID - ID_MENU_OK + IDOK));
+ return 0;
+ }
+
+// Standard dialog ending: may be used with any command
+ LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->StdCloseDialog(wID);
+ return 0;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdDialogImplBase - Base implementation of standard PPC/SmartPhone dialog
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true, class TBase = ATL::CDialogImpl< T > >
+class ATL_NO_VTABLE CStdDialogImplBase :
+ public TBase,
+ public CStdDialogBase<T, t_shidiFlags, t_bModal>
+{
+public:
+#ifdef WIN32_PLATFORM_PSPC
+ BOOL GetClientRect(LPRECT lpRect)
+ {
+ return CStdDialogBase<T, t_shidiFlags, t_bModal>::GetClientRect(lpRect);
+ }
+
+ BOOL SetWindowText(LPCTSTR lpszString)
+ {
+ return CStdDialogBase<T, t_shidiFlags, t_bModal>::SetWindowText(lpszString);
+ }
+#endif
+
+ BEGIN_MSG_MAP(CStdDialogImplBase)
+#ifdef WIN32_PLATFORM_PSPC // Pocket PC title and SIP
+ MESSAGE_HANDLER(WM_PAINT, OnPaintTitle)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
+#elif defined(WIN32_PLATFORM_WFSP) // SmartPhone VK_TBACK key
+ MESSAGE_HANDLER(WM_HOTKEY, OnHotKey)
+#endif
+ MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnColorStatic)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ COMMAND_RANGE_HANDLER(IDOK, IDCANCEL, OnCloseCmd)
+ COMMAND_RANGE_HANDLER(ID_MENU_OK, ID_MENU_CANCEL, OnMenuClose)
+ END_MSG_MAP()
+
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _DEBUG
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(t_bModal == pT->m_bModal);
+#endif
+ StdPlatformInit();
+ StdShidInit();
+ return bHandled = FALSE;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdDialogImpl - implementation of standard PPC/SmartPhone dialog
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true >
+class ATL_NO_VTABLE CStdDialogImpl : public CStdDialogImplBase< T, t_shidiFlags, t_bModal>
+{};
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdIndirectDialogImpl - implementation of standard indirect PPC/SmartPhone dialog
+
+#if defined __ATLDLGS_H__
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true>
+class ATL_NO_VTABLE CStdIndirectDialogImpl :
+ public CIndirectDialogImpl< T, CMemDlgTemplate, CStdDialogImpl<T, t_shidiFlags, t_bModal> >
+{
+public:
+ typedef CIndirectDialogImpl< T, CMemDlgTemplate, CStdDialogImpl<T, t_shidiFlags, t_bModal> > _baseClass;
+ typedef CStdDialogImpl<T, t_shidiFlags, t_bModal> _baseStd;
+
+ void CheckStyle()
+ {
+ // Mobile devices don't support DLGTEMPLATEEX
+ ATLASSERT(!m_Template.IsTemplateEx());
+
+ // Standard dialogs need only DS_CENTER
+ DWORD &dwStyle = m_Template.GetTemplatePtr()->style;
+ if (dwStyle & DS_CENTER)
+ if(t_bModal)
+ {
+ ATLASSERT((dwStyle & WS_CHILD) != WS_CHILD);
+ dwStyle |= WS_POPUP;
+ }
+ else
+ {
+ if((dwStyle & WS_CHILD) != WS_CHILD)
+ dwStyle |= WS_POPUP;
+ }
+ }
+
+ INT_PTR DoModal(HWND hWndParent = ::GetActiveWindow(), LPARAM dwInitParam = NULL)
+ {
+ ATLASSERT(t_bModal);
+
+ if (!m_Template.IsValid())
+ CreateTemplate();
+
+ CheckStyle();
+
+ return _baseClass::DoModal(hWndParent, dwInitParam);
+ }
+
+ HWND Create(HWND hWndParent, LPARAM dwInitParam = NULL)
+ {
+ ATLASSERT(!t_bModal);
+
+ if (!m_Template.IsValid())
+ CreateTemplate();
+
+ CheckStyle();
+
+ return _baseClass::Create(hWndParent, dwInitParam);
+ }
+
+ BEGIN_MSG_MAP(CStdIndirectDialogImpl)
+ CHAIN_MSG_MAP(_baseStd)
+ END_MSG_MAP()
+
+};
+
+#endif // defined __ATLDLGS_H__
+
+#ifndef _ATL_NO_HOSTING
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdAxDialogImpl - implementation of standard PPC/SmartPhone AxDialog
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true >
+class ATL_NO_VTABLE CStdAxDialogImpl : public CStdDialogImplBase< T, t_shidiFlags, t_bModal, ATL::CAxDialogImpl< T > >
+{};
+#endif // _ATL_NO_HOSTING
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdSimpleDialog - standard PPC/SmartPhone simple dialog with SHIDIF_xxx flags
+
+template <WORD t_wDlgTemplateID, UINT t_shidiFlags = WTL_STD_SHIDIF>
+class CStdSimpleDialog :
+ public ATL::CSimpleDialog<t_wDlgTemplateID, FALSE>,
+ public CStdDialogBase<CStdSimpleDialog<t_wDlgTemplateID, t_shidiFlags>, t_shidiFlags>
+{
+public:
+ typedef CStdDialogBase<CStdSimpleDialog<t_wDlgTemplateID, t_shidiFlags>, t_shidiFlags> baseClass;
+
+#ifdef WIN32_PLATFORM_PSPC
+ BOOL GetClientRect(LPRECT lpRect)
+ {
+ return baseClass::GetClientRect(lpRect);
+ }
+
+ BOOL SetWindowText(LPCTSTR lpszString)
+ {
+ return baseClass::SetWindowText(lpszString);
+ }
+#endif
+
+ BEGIN_MSG_MAP(CStdSimpleDialog)
+#ifdef WIN32_PLATFORM_PSPC // Pocket PC title and SIP
+ MESSAGE_HANDLER(WM_PAINT, OnPaintTitle)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
+#elif defined(WIN32_PLATFORM_WFSP) // SmartPhone VK_TBACK key
+ MESSAGE_HANDLER(WM_HOTKEY, OnHotKey)
+#endif
+ MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnColorStatic)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ COMMAND_RANGE_HANDLER(ID_MENU_OK, ID_MENU_CANCEL, OnMenuClose)
+ COMMAND_RANGE_HANDLER(IDOK, IDCANCEL, baseClass::OnCloseCmd)
+ END_MSG_MAP()
+
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ StdPlatformInit();
+ StdShidInit();
+ return bHandled = FALSE;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdDialogResizeImplBase - Base implementation of orientation resizing standard PPC/SmartPhone dialog
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true, class TBase = ATL::CDialogImpl<T> >
+class ATL_NO_VTABLE CStdDialogResizeImplBase :
+ public CStdDialogImplBase< T, t_shidiFlags, t_bModal, TBase>,
+ public CDialogResize<T>
+{
+public:
+ // Note: BEGIN_DLGRESIZE_MAP is required in the derived class.
+
+ BEGIN_MSG_MAP(CStdResizeDialogImplBase)
+#ifdef WIN32_PLATFORM_PSPC // Pocket PC title
+ MESSAGE_HANDLER(WM_PAINT, OnPaintTitle)
+#elif defined(WIN32_PLATFORM_WFSP) // SmartPhone VK_TBACK key
+ MESSAGE_HANDLER(WM_HOTKEY, OnHotKey)
+#endif
+ MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnColorStatic)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ COMMAND_RANGE_HANDLER(IDOK, IDCANCEL, OnCloseCmd)
+ COMMAND_RANGE_HANDLER(ID_MENU_OK, ID_MENU_CANCEL, OnMenuClose)
+ CHAIN_MSG_MAP(CDialogResize< T >)
+ END_MSG_MAP()
+
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifdef _DEBUG
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(t_bModal == pT->m_bModal);
+#endif
+ StdPlatformInit();
+ DlgResize_Init(FALSE);
+ StdShidInit();
+ return bHandled = FALSE;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdDialogResizeImpl - implementation of orientation resizing standard PPC/SmartPhone dialog
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true >
+class ATL_NO_VTABLE CStdDialogResizeImpl : public CStdDialogResizeImplBase< T, t_shidiFlags, t_bModal>
+{};
+
+#ifndef _ATL_NO_HOSTING
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdAxDialogResizeImpl - implementation of orientation resizing standard PPC/SmartPhone AxDialog
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true >
+class ATL_NO_VTABLE CStdAxDialogResizeImpl : public CStdDialogResizeImplBase< T, t_shidiFlags, t_bModal, ATL::CAxDialogImpl<T> >
+{};
+#endif // _ATL_NO_HOSTING
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdSimpleDialogResizeImpl - implementation of standard resizing simple dialog with SHIDIF_xxx flags
+
+// Usage:
+// class CMyDlg : public CStdSimpleDialogResize<CMyDlg,
+// IDD_MYDLG, SHIDIF_DONEBUTTON | SHIDIF_FULLSCREENNOMENUBAR>
+// {
+// public:
+// BEGIN_DLGRESIZE_MAP(CMyDlg)
+// ...
+// END_DLGRESIZE_MAP()
+// };
+
+template <class T, WORD t_wDlgTemplateID, UINT t_shidiFlags = WTL_STD_SHIDIF>
+class ATL_NO_VTABLE CStdSimpleDialogResizeImpl :
+ public CStdSimpleDialog<t_wDlgTemplateID, t_shidiFlags>,
+ public CDialogResize< T >
+{
+public:
+ typedef CStdSimpleDialog<t_wDlgTemplateID, t_shidiFlags>::baseClass baseClass;
+
+ BEGIN_MSG_MAP(CStdSimpleDialogResizeImpl)
+#ifdef WIN32_PLATFORM_PSPC // Pocket PC title
+ MESSAGE_HANDLER(WM_PAINT, OnPaintTitle)
+#elif defined(WIN32_PLATFORM_WFSP) // SmartPhone VK_TBACK key
+ MESSAGE_HANDLER(WM_HOTKEY, OnHotKey)
+#endif
+ MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnColorStatic)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ COMMAND_RANGE_HANDLER(IDOK, IDCANCEL, baseClass::OnCloseCmd)
+ COMMAND_RANGE_HANDLER(ID_MENU_OK, ID_MENU_CANCEL, OnMenuClose)
+ CHAIN_MSG_MAP(CDialogResize< T >)
+ END_MSG_MAP()
+
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ StdPlatformInit();
+ DlgResize_Init(FALSE);
+ StdShidInit();
+ return bHandled = FALSE;
+ }
+};
+
+#if defined(_WTL_CE_DRA) && defined(WIN32_PLATFORM_PSPC)
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdOrientedDialogBase - Oriented PPC standard dialog base class
+
+template <class T>
+class CStdOrientedDialogBase
+{
+public:
+// Operation
+ BOOL SetOrientation(DRA::DisplayMode mode)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+ ATLASSERT(mode == DRA::GetDisplayMode());
+
+ // Derived dialog must enumerate TWO dialog templates with the same control ids and types ie:
+ // enum { IDD = IDD_MYDLG, IDD_LANDSCAPE = IDD_MYDLG_L };
+ UINT iResource = (mode == DRA::Landscape)? T::IDD_LANDSCAPE : T::IDD;
+
+ BOOL bRes = DRA::RelayoutDialog(ModuleHelper::GetResourceInstance(), pT->m_hWnd, MAKEINTRESOURCE(iResource));
+ pT->OnOrientation(mode);
+ return bRes;
+ }
+
+// Override
+ void OnOrientation(DRA::DisplayMode /*mode*/)
+ {}
+
+// Message handlers
+ LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+ if (wParam == SETTINGCHANGE_RESET)
+ {
+ SetOrientation(DRA::GetDisplayMode());
+ pT->StdPlatformInit();
+ pT->StdShidInit();
+ }
+ else if (wParam == SPI_SETSIPINFO)
+ {
+ pT->DoSipInfo();
+ return TRUE;
+ }
+ return bHandled = FALSE;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdOrientedDialogImplBase - Oriented PPC standard dialog base implementation
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true, class TBase = ATL::CDialogImpl<T> >
+class ATL_NO_VTABLE CStdOrientedDialogImplBase :
+ public CStdDialogImplBase< T, t_shidiFlags, t_bModal, TBase>,
+ public CStdOrientedDialogBase<T>
+{
+public:
+ BEGIN_MSG_MAP(CStdOrientedDialogImpl)
+ MESSAGE_HANDLER(WM_PAINT, OnPaintTitle)
+ MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnColorStatic)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, CStdOrientedDialogBase<T>::OnSettingChange)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ COMMAND_RANGE_HANDLER(IDOK, IDCANCEL, OnCloseCmd)
+ COMMAND_RANGE_HANDLER(ID_MENU_OK, ID_MENU_CANCEL, OnMenuClose)
+ END_MSG_MAP()
+
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+#ifdef _DEBUG
+ ATLASSERT(t_bModal == pT->m_bModal);
+#endif
+ if (DRA::GetDisplayMode() == DRA::Landscape)
+ SetOrientation(DRA::Landscape);
+ pT->StdPlatformInit();
+ pT->StdShidInit();
+ return bHandled = FALSE;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdOrientedDialogImpl - Oriented PPC standard dialog implementation
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true >
+class ATL_NO_VTABLE CStdOrientedDialogImpl : public CStdOrientedDialogImplBase< T, t_shidiFlags, t_bModal>
+{};
+
+#ifndef _ATL_NO_HOSTING
+///////////////////////////////////////////////////////////////////////////////
+// CStdAxOrientedDialogImpl - Oriented PPC standard AxDialog implementation
+
+template <class T, UINT t_shidiFlags = WTL_STD_SHIDIF, bool t_bModal = true >
+class ATL_NO_VTABLE CStdAxOrientedDialogImpl : public CStdOrientedDialogImplBase< T, t_shidiFlags, t_bModal, ATL::CAxDialogImpl<T> >
+{};
+#endif // _ATL_NO_HOSTING
+
+///////////////////////////////////////////////////////////////////////////////
+// CStdSimpleOrientedDialog - Standard simple orientable dialog
+
+template <WORD t_wDlgTemplateID, WORD t_wDlgLandscapeID, UINT t_shidiFlags = WTL_STD_SHIDIF>
+class CStdSimpleOrientedDialog :
+ public CStdSimpleDialog<t_wDlgTemplateID, t_shidiFlags>,
+ public CStdOrientedDialogBase<CStdSimpleOrientedDialog<t_wDlgTemplateID, t_wDlgLandscapeID, t_shidiFlags> >
+{
+public:
+ typedef CStdSimpleDialog<t_wDlgTemplateID, t_shidiFlags>::baseClass baseClass;
+ typedef CStdOrientedDialogBase<CStdSimpleOrientedDialog<t_wDlgTemplateID, t_wDlgLandscapeID, t_shidiFlags> > baseOriented;
+
+ enum {IDD = t_wDlgTemplateID, IDD_LANDSCAPE = t_wDlgLandscapeID};
+
+ BEGIN_MSG_MAP(CStdSimpleDialog)
+ MESSAGE_HANDLER(WM_PAINT, OnPaintTitle)
+ MESSAGE_HANDLER(WM_CTLCOLORSTATIC, OnColorStatic)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, baseOriented::OnSettingChange)
+ MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
+ COMMAND_RANGE_HANDLER(IDOK, IDCANCEL, baseClass::OnCloseCmd)
+ COMMAND_RANGE_HANDLER(ID_MENU_OK, ID_MENU_CANCEL, OnMenuClose)
+ END_MSG_MAP()
+
+ LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if (DRA::GetDisplayMode() == DRA::Landscape)
+ SetOrientation(DRA::Landscape);
+ StdPlatformInit();
+ StdShidInit();
+ return bHandled = FALSE;
+ }
+};
+
+#endif // _WTL_CE_DRA
+
+
+#endif // _WTL_CE_NO_DIALOGS
+
+
+// --- PPC/SmartPhone application window and helpers ---
+
+#ifndef _WTL_CE_NO_APPWINDOW
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppInfoBase - Helper for application state save/restore to registry
+
+class CAppInfoBase
+{
+public:
+ CRegKeyEx m_Key;
+
+ CAppInfoBase(ATL::_U_STRINGorID sAppKey)
+ {
+ m_Key.Create(HKEY_CURRENT_USER, sAppKey.m_lpstr);
+ ATLASSERT(m_Key.m_hKey);
+ }
+
+ template <class V>
+ LONG Save(V& val, ATL::_U_STRINGorID sName)
+ {
+ return m_Key.SetBinaryValue(sName.m_lpstr, &val, sizeof(V));
+ }
+
+ template <class V>
+ LONG Save(int nb, V& val0, ATL::_U_STRINGorID sName)
+ {
+ return m_Key.SetBinaryValue(sName.m_lpstr, &val0, nb * sizeof(V));
+ }
+
+ template <class V>
+ LONG Restore(V& val, ATL::_U_STRINGorID sName)
+ {
+ ULONG bufSize = sizeof(V);
+ return m_Key.QueryBinaryValue(sName.m_lpstr, &val, &bufSize);
+ }
+
+ template <class V>
+ LONG Restore(int nb, V& val0, ATL::_U_STRINGorID sName)
+ {
+ ULONG bufSize = nb * sizeof(V);
+ return m_Key.QueryBinaryValue(sName.m_lpstr, &val0, &bufSize);
+ }
+
+#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+ LONG Save(_CSTRING_NS::CString& sval, ATL::_U_STRINGorID sName)
+ {
+ return m_Key.SetStringValue(sName.m_lpstr, sval);
+ }
+
+ LONG Restore(_CSTRING_NS::CString& sval, ATL::_U_STRINGorID sName)
+ {
+ DWORD size = MAX_PATH;
+ LONG res = m_Key.QueryStringValue(sName.m_lpstr, sval.GetBuffer(size), &size);
+ sval.ReleaseBuffer();
+ return res;
+ }
+#else
+ #pragma message("Warning: CAppInfoBase compiles without CString support. Do not use CString in Save or Restore.")
+#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
+
+ LONG Save(LPCTSTR sval, ATL::_U_STRINGorID sName)
+ {
+ return m_Key.SetStringValue(sName.m_lpstr, sval);
+ }
+
+ LONG Restore(LPTSTR sval, ATL::_U_STRINGorID sName, DWORD *plength)
+ {
+ return m_Key.QueryStringValue(sName.m_lpstr, sval, plength);
+ }
+
+ LONG Delete(ATL::_U_STRINGorID sName)
+ {
+ return m_Key.DeleteValue(sName.m_lpstr);
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppInfoT - CAppInfoBase constructed from a class with T::GetAppKey()
+
+// Macro for declaring AppKey
+#define DECLARE_APPKEY(uAppKey) \
+ static LPCTSTR GetAppKey() \
+ { \
+ static LPCTSTR sAppKey = ATL::_U_STRINGorID(uAppKey).m_lpstr; \
+ return sAppKey; \
+ }
+
+template <class T>
+class CAppInfoT : public CAppInfoBase
+{
+public:
+ CAppInfoT() : CAppInfoBase(T::GetAppKey()){}
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppWindowBase - Base class for PPC/SmartPhone "well-behaved" application window or dialog
+
+// Macros for declaring frame WNDCLASS and AppKey
+#define DECLARE_APP_FRAME_CLASS(WndClassName, uCommonResourceID, uAppKey) \
+ DECLARE_FRAME_WND_CLASS(WndClassName, uCommonResourceID) \
+ DECLARE_APPKEY(uAppKey)
+
+#define DECLARE_APP_FRAME_CLASS_EX(WndClassName, uCommonResourceID, style, bkgnd, uAppKey) \
+ DECLARE_FRAME_WND_CLASS_EX(WndClassName, uCommonResourceID, style, bkgnd) \
+ DECLARE_APPKEY(uAppKey)
+
+template <class T>
+class CAppWindowBase
+{
+public:
+ typedef class CAppInfoT< T > CAppInfo;
+
+#ifndef WIN32_PLATFORM_WFSP
+ SHACTIVATEINFO m_sai; // NoOp on SmartPhones
+#endif // WIN32_PLATFORM_WFSP
+
+ bool m_bHibernate;
+
+ CAppWindowBase< T >() : m_bHibernate(false)
+ {
+#ifndef WIN32_PLATFORM_WFSP
+ SHACTIVATEINFO sai = { sizeof(SHACTIVATEINFO) };
+ m_sai = sai;
+#endif // WIN32_PLATFORM_WFSP
+ };
+
+ // Same as WTL 7.1 AppWizard generated ActivatePreviousInstance + SendMessage WM_COPYDATA
+ static HRESULT ActivatePreviousInstance(HINSTANCE hInstance, LPCTSTR lpstrCmdLine, bool bDialog)
+ {
+ // requires T does DECLARE_APP_FRAME_CLASS, DECLARE_APP_FRAME_CLASS_EX or DECLARE_APP_DLG_CLASS
+ CFrameWndClassInfo& classInfo = T::GetWndClassInfo();
+
+ ATLVERIFY(::LoadString(hInstance, classInfo.m_uCommonResourceID, classInfo.m_szAutoName, sizeof(classInfo.m_szAutoName)/sizeof(classInfo.m_szAutoName[0])) != 0);
+
+ classInfo.m_wc.lpszClassName = classInfo.m_szAutoName;
+
+ const TCHAR* pszClass = classInfo.m_wc.lpszClassName;
+
+ if(NULL == pszClass || '\0' == *pszClass)
+ {
+ return E_FAIL;
+ }
+
+ const DWORD dRetryInterval = 100;
+ const int iMaxRetries = 25;
+
+ for(int i = 0; i < iMaxRetries; ++i)
+ {
+ HANDLE hMutex = CreateMutex(NULL, FALSE, pszClass);
+
+ DWORD dw = GetLastError();
+
+ if(NULL == hMutex)
+ {
+ HRESULT hr;
+
+ switch(dw)
+ {
+ case ERROR_INVALID_HANDLE:
+ // A non-mutext object with this name already exists.
+ hr = E_INVALIDARG;
+ break;
+ default:
+ // This should never happen...
+ hr = E_FAIL;
+ }
+
+ return hr;
+ }
+
+ // If the mutex already exists, then there should be another instance running
+ if(dw == ERROR_ALREADY_EXISTS)
+ {
+ CloseHandle(hMutex);
+
+ HWND hwnd = NULL;
+ if (bDialog)
+ hwnd = FindWindow(NULL, pszClass);
+ else
+ hwnd = FindWindow(pszClass, NULL);
+
+ if(hwnd == NULL)
+ {
+ Sleep(dRetryInterval);
+ continue;
+ }
+ else
+ {
+ // Transmit our params to previous instance
+ if (lpstrCmdLine && *lpstrCmdLine)
+ {
+ COPYDATASTRUCT cd = { NULL, sizeof(TCHAR) * (wcslen(lpstrCmdLine) + 1), (PVOID)lpstrCmdLine };
+ ::SendMessage(hwnd, WM_COPYDATA, NULL, (LPARAM)&cd);
+ }
+ // Set the previous instance as the foreground window
+ if(0 != SetForegroundWindow(reinterpret_cast<HWND>(reinterpret_cast<ULONG>(hwnd) | 0x1)))
+ return S_FALSE;
+ }
+ }
+ else
+ {
+ return S_OK;
+ }
+ }
+ return S_OK;
+ }
+
+// Operations overriden in derived class
+ bool AppHibernate(bool /*bHibernate*/)
+ {
+ return false;
+ }
+
+ bool AppNewInstance(LPCTSTR /*lpstrCmdLine*/)
+ {
+ return false;
+ }
+
+ void AppSave()
+ {
+ }
+
+#ifdef WIN32_PLATFORM_WFSP
+ void AppBackKey()
+ {
+ ::SHNavigateBack();
+ }
+#endif
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CAppWindowBase)
+ MESSAGE_HANDLER(WM_ACTIVATE, OnActivate)
+#ifdef WIN32_PLATFORM_WFSP
+ MESSAGE_HANDLER(WM_HOTKEY, OnHotKey)
+#else
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
+#endif // WIN32_PLATFORM_WFSP
+ MESSAGE_HANDLER(WM_HIBERNATE, OnHibernate)
+ MESSAGE_HANDLER(WM_COPYDATA, OnNewInstance)
+ MESSAGE_HANDLER(WM_CLOSE, OnClose)
+ END_MSG_MAP()
+
+ LRESULT OnActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ if (m_bHibernate)
+ m_bHibernate = pT->AppHibernate(false);
+#ifndef WIN32_PLATFORM_WFSP
+ ::SHHandleWMActivate(pT->m_hWnd, wParam, lParam, &m_sai, 0);
+#else
+ wParam;
+ lParam;
+#endif // WIN32_PLATFORM_WFSP
+ return bHandled = FALSE;
+ }
+
+#ifdef WIN32_PLATFORM_WFSP
+// SmartPhone VK_TBACK key standard management
+ LRESULT OnHotKey(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ const UINT uModif = (UINT)LOWORD(lParam);
+ const UINT uVirtKey = (UINT)HIWORD(lParam);
+ if(uVirtKey == VK_TBACK)
+ if (AtlIsEditFocus())
+ ::SHSendBackToFocusWindow(uMsg, wParam, lParam);
+ else if (uModif & MOD_KEYUP)
+ pT->AppBackKey();
+ return 1;
+ }
+
+#else // !WIN32_PLATFORM_WFSP
+// PPC SIP handling
+ LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ bHandled = FALSE;
+ return ::SHHandleWMSettingChange(pT->m_hWnd, wParam, lParam, &m_sai);
+ }
+#endif // !WIN32_PLATFORM_WFSP
+
+ LRESULT OnHibernate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ return m_bHibernate = pT->AppHibernate(true);
+ }
+
+ LRESULT OnNewInstance(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ PCOPYDATASTRUCT pcds = (PCOPYDATASTRUCT)lParam;
+ return pT->AppNewInstance((LPCTSTR)pcds->lpData);
+ }
+
+ LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->AppSave();
+ bHandled = FALSE;
+ return 1;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppWindow - PPC/SmartPhone "well-behaved" application window class
+
+template <class T>
+class CAppWindow : public CAppWindowBase< T >
+{
+public:
+ // Same as WTL 7.1 AppWizard generated Run + lpstrCmdLine in CreateEx
+ static int AppRun(LPTSTR lpstrCmdLine = NULL, int nCmdShow = SW_SHOWNORMAL)
+ {
+ CMessageLoop theLoop;
+ _Module.AddMessageLoop(&theLoop);
+
+ T wndMain;
+
+ if(wndMain.CreateEx(NULL, NULL, 0, 0, lpstrCmdLine) == NULL)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("Main window creation failed!\n"));
+ return 0;
+ }
+
+ wndMain.ShowWindow(nCmdShow);
+
+ int nRet = theLoop.Run();
+
+ _Module.RemoveMessageLoop();
+ return nRet;
+ }
+
+ static HRESULT ActivatePreviousInstance(HINSTANCE hInstance, LPCTSTR lpstrCmdLine)
+ {
+ return CAppWindowBase< T >::ActivatePreviousInstance(hInstance, lpstrCmdLine, false);
+ }
+};
+
+
+#ifndef _WTL_CE_NO_DIALOGS
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppDialog - PPC/SmartPhone "well-behaved" dialog application class
+
+// Macro for declaring dialog WNDCLASS and AppKey
+#define DECLARE_APP_DLG_CLASS(WndClassName, uCommonResourceID, uAppKey) \
+ static WTL::CFrameWndClassInfo& GetWndClassInfo() \
+ { \
+ static WTL::CFrameWndClassInfo wc = \
+ { \
+ { 0, (WNDPROC)StartDialogProc, \
+ 0, 0, NULL, NULL, NULL, (HBRUSH)(COLOR_WINDOW + 1), NULL, WndClassName }, \
+ NULL, NULL, IDC_ARROW, TRUE, 0, _T(""), uCommonResourceID \
+ }; \
+ return wc; \
+ }; \
+ DECLARE_APPKEY(uAppKey)
+
+template <class T>
+class CAppDialog : public CAppWindowBase< T >
+{
+public:
+ static int AppRun(LPTSTR lpstrCmdLine = NULL, int nCmdShow = SW_SHOWNORMAL)
+ {
+ CMessageLoop theLoop;
+ _Module.AddMessageLoop(&theLoop);
+
+ T dlgMain;
+
+ if(dlgMain.Create(NULL, (LPARAM)lpstrCmdLine) == NULL)
+ {
+ ATLTRACE2(atlTraceUI, 0, _T("Main dialog creation failed!\n"));
+ return 0;
+ }
+
+ dlgMain.ShowWindow(nCmdShow);
+
+ int nRet = theLoop.Run();
+
+ _Module.RemoveMessageLoop();
+ return nRet;
+ }
+
+ static HRESULT ActivatePreviousInstance(HINSTANCE hInstance, LPCTSTR lpstrCmdLine)
+ {
+ return CAppWindowBase< T >::ActivatePreviousInstance(hInstance, lpstrCmdLine, true);
+ };
+};
+
+// PPC/SmartPhone standard application dialogs
+
+#ifdef WIN32_PLATFORM_WFSP
+#define WTL_APP_SHIDIF WTL_SP_SHIDIF
+#else
+#define WTL_APP_SHIDIF WTL_STD_SHIDIF
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppStdDialogImplBase - Base implementation of standard application dialogs
+
+template <class T, class TImplBase, UINT t_shidiFlags = WTL_APP_SHIDIF, bool t_bModal = false>
+class ATL_NO_VTABLE CAppStdDialogImplBase :
+ public TImplBase,
+ public CAppDialog< T >
+{
+public:
+ WTL_DLG_NOTITLE;
+
+ void StdCloseDialog(int nVal)
+ {
+ T* pT = static_cast<T*>(this);
+ if (nVal != IDCANCEL)
+ pT->AppSave();
+ if (t_bModal == false)
+ {
+ pT->DestroyWindow();
+ ::PostQuitMessage(nVal);
+ }
+ else
+ ::EndDialog(pT->m_hWnd, nVal);
+ }
+
+ BEGIN_MSG_MAP(CAppStdDialogImplBase)
+ MESSAGE_HANDLER(WM_CLOSE, OnSystemClose)
+ CHAIN_MSG_MAP(TImplBase)
+ CHAIN_MSG_MAP(CAppDialog< T >)
+ END_MSG_MAP()
+
+ LRESULT OnSystemClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
+ {
+ T* pT = static_cast<T*>(this);
+ pT->StdCloseDialog(IDCANCEL);
+ return 0;
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppStdDialogImpl - Implementation of standard application dialog
+
+template <class T, UINT t_shidiFlags = WTL_APP_SHIDIF, bool t_bModal = false>
+class ATL_NO_VTABLE CAppStdDialogImpl :
+ public CAppStdDialogImplBase<T, CStdDialogImpl<T, t_shidiFlags, t_bModal>, t_shidiFlags, t_bModal>
+{};
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppStdDialogResizeImpl - implementation of orientation resizing standard application dialog
+
+template <class T, UINT t_shidiFlags = WTL_APP_SHIDIF, bool t_bModal = false>
+class ATL_NO_VTABLE CAppStdDialogResizeImpl :
+ public CAppStdDialogImplBase<T, CStdDialogResizeImpl<T, t_shidiFlags, t_bModal>, t_shidiFlags, t_bModal>
+{};
+
+#ifndef _ATL_NO_HOSTING
+///////////////////////////////////////////////////////////////////////////////
+// CAppStdAxDialogImpl - Implementation of standard application AxDialog
+
+template <class T, UINT t_shidiFlags = WTL_APP_SHIDIF, bool t_bModal = false>
+class ATL_NO_VTABLE CAppStdAxDialogImpl :
+ public CAppStdDialogImplBase<T, CStdAxDialogImpl<T, t_shidiFlags, t_bModal>, t_shidiFlags, t_bModal>
+{};
+
+///////////////////////////////////////////////////////////////////////////////
+// CAppStdAxDialogResizeImpl - implementation of orientation resizing standard application AxDialog
+
+template <class T, UINT t_shidiFlags = WTL_APP_SHIDIF, bool t_bModal = false>
+class ATL_NO_VTABLE CAppStdAxDialogResizeImpl :
+ public CAppStdDialogImplBase<T, CStdAxDialogResizeImpl<T, t_shidiFlags, t_bModal>, t_shidiFlags, t_bModal>
+{};
+#endif // _ATL_NO_HOSTING
+
+#if defined(_WTL_CE_DRA) && defined(WIN32_PLATFORM_PSPC)
+///////////////////////////////////////////////////////////////////////////////
+// CAppStdOrientedDialogImpl - implementation of oriented PPC standard application dialog
+
+template <class T, UINT t_shidiFlags = WTL_APP_SHIDIF, bool t_bModal = false>
+class ATL_NO_VTABLE CAppStdOrientedDialogImpl :
+ public CAppStdDialogImplBase<T, CStdOrientedDialogImpl<T, t_shidiFlags, t_bModal>, t_shidiFlags, t_bModal>
+{};
+
+#ifndef _ATL_NO_HOSTING
+///////////////////////////////////////////////////////////////////////////////
+// CAppStdAxOrientedDialogImpl - implementation of oriented PPC standard application AxDialog
+
+template <class T, UINT t_shidiFlags = WTL_APP_SHIDIF, bool t_bModal = false>
+class ATL_NO_VTABLE CAppStdAxOrientedDialogImpl :
+ public CAppStdDialogImplBase<T, CStdAxOrientedDialogImpl<T, t_shidiFlags, t_bModal>, t_shidiFlags, t_bModal>
+{};
+#endif // _ATL_NO_HOSTING
+
+#endif // defined(_WTL_CE_DRA) && defined(WIN32_PLATFORM_PSPC)
+
+#endif // _WTL_CE_NO_DIALOGS
+
+#endif // _WTL_CE_NO_APPWINDOW
+
+
+// --- Full screen support ---
+
+#ifndef _WTL_CE_NO_FULLSCREEN
+
+///////////////////////////////////////////////////////////////////////////////
+// CFullScreenFrame - full screen frame implementation
+
+template <class T, bool t_bHasSip = true>
+class CFullScreenFrame
+{
+public:
+ bool m_bFullScreen;
+
+ CFullScreenFrame() : m_bFullScreen(false)
+ { }
+
+// Operation
+ void SetFullScreen(bool bFull)
+ {
+ m_bFullScreen = bFull;
+ ShowTaskBar(!bFull, false);
+ ShowMenuBar(!bFull);
+ }
+
+// Manage TaskBar for modal dialogs and property sheets
+ template <class D>
+ int FSDoModal(D& dlg)
+ {
+ T* pT = static_cast<T*>(this);
+ pT; // avoid level 4 warning
+ ATLASSERT(pT->IsWindow());
+ if (m_bFullScreen) // Show taskbar if hidden
+ ShowTaskBar(true, false);
+ int iRet = dlg.DoModal();
+ if (m_bFullScreen) // Hide taskbar if restored
+ ShowTaskBar(false);
+ return iRet;
+ }
+
+// Implementation
+ void ShowMenuBar(bool bShow)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+ ATL::CWindow MenuBar = pT->m_hWndCECommandBar;
+ ATLASSERT(MenuBar.IsWindow());
+ MenuBar.ShowWindow(bShow ? SW_SHOWNORMAL : SW_HIDE);
+ pT->SizeToMenuBar();
+ }
+
+ void ShowTaskBar(bool bShow, bool bRepaint = true)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(pT->IsWindow());
+ RECT rect = { 0 };
+ SystemParametersInfo(SPI_GETWORKAREA, NULL, &rect, FALSE);
+ if (!bShow)
+ rect.top = 0;
+
+#ifdef WIN32_PLATFORM_PSPC // Pocket PC code
+ UINT uShow = t_bHasSip ? SHFS_SHOWTASKBAR | SHFS_SHOWSIPBUTTON : SHFS_SHOWTASKBAR | SHFS_HIDESIPBUTTON;
+ SHFullScreen(pT->m_hWnd, bShow ? uShow : SHFS_HIDETASKBAR | SHFS_HIDESIPBUTTON);
+#elif _WIN32_WCE > 0x500 // Smartphone 2005 code
+ SHFullScreen(pT->m_hWnd, bShow ? SHFS_SHOWTASKBAR : SHFS_HIDETASKBAR);
+#else // Smartphone 2003
+ HWND hTaskBar = FindWindow(_T("tray"), NULL);
+ ATLASSERT(::IsWindow(hTaskBar));
+ ::ShowWindow(hTaskBar, bShow ? SW_SHOW : SW_HIDE);
+#endif // WIN32_PLATFORM_PSPC
+
+ pT->MoveWindow(&rect, bRepaint);
+ }
+
+// Message map and handler
+ BEGIN_MSG_MAP(CFullScreenFrame)
+ MESSAGE_HANDLER(WM_SETTINGCHANGE, OnSettingChange)
+ MESSAGE_HANDLER(WM_ACTIVATE, OnActivate)
+ END_MSG_MAP()
+
+ LRESULT OnSettingChange(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+#ifndef SETTINGCHANGE_RESET // not defined for PPC 2002
+ #define SETTINGCHANGE_RESET SPI_SETWORKAREA
+#endif
+ if (m_bFullScreen && (wParam == SETTINGCHANGE_RESET))
+ SetFullScreen(m_bFullScreen);
+ return bHandled = FALSE;
+ }
+
+ LRESULT OnActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ if (m_bFullScreen)
+ {
+ ShowTaskBar(!wParam);
+ ShowMenuBar(!wParam);
+ }
+ return bHandled = FALSE;
+ }
+};
+
+#endif // _WTL_CE_NO_FULLSCREEN
+
+
+// --- WinCE zoom support ---
+
+#ifndef _WTL_CE_NO_ZOOMSCROLL
+
+///////////////////////////////////////////////////////////////////////////////
+// CZoomScrollImpl - WinCE zooming implementation on top of CScrollImpl
+
+template <class T>
+class CZoomScrollImpl: public CScrollImpl< T >
+{
+public:
+// Data members
+ _WTYPES_NS::CSize m_sizeTrue;
+ double m_fzoom;
+
+// Creation
+ CZoomScrollImpl() : m_sizeTrue(0), m_fzoom(1.)
+ { }
+
+// Zoom operations and access
+ void SetZoomScrollSize(_WTYPES_NS::CSize sizeTrue, double fzoom = 1., BOOL bRedraw = TRUE)
+ {
+ ATLASSERT(fzoom > 0.);
+ m_sizeTrue = sizeTrue;
+ m_fzoom = fzoom;
+
+ CScrollImpl< T >::SetScrollSize(sizeTrue / fzoom, bRedraw);
+ }
+
+ void SetZoomScrollSize(int cx, int cy, double fzoom=1., BOOL bRedraw = TRUE)
+ {
+ SetZoomScrollSize(_WTYPES_NS::CSize(cx, cy), fzoom, bRedraw);
+ }
+
+ void SetZoom(double fzoom, BOOL bRedraw = TRUE)
+ {
+ _WTYPES_NS::CPoint ptCenter = WndtoTrue(m_sizeClient / 2);
+ _WTYPES_NS::CSize sizePage = GetScrollPage();
+ _WTYPES_NS::CSize sizeLine = GetScrollLine();
+
+ SetZoomScrollSize(GetScrollSize(), fzoom, bRedraw);
+
+ SetScrollLine(sizeLine);
+ SetScrollPage(sizePage);
+ _WTYPES_NS::CPoint ptOffset = ptCenter - (m_sizeClient / 2) * fzoom;
+ SetScrollOffset(ptOffset, bRedraw);
+ }
+
+ double GetZoom()
+ {
+ return m_fzoom;
+ }
+
+// CScrollImpl overrides
+ void SetScrollOffset(int x, int y, BOOL bRedraw = TRUE)
+ {
+ CScrollImpl< T >::SetScrollOffset((int)(x / m_fzoom), (int)(y / m_fzoom), bRedraw);
+ }
+
+ void SetScrollOffset(POINT ptOffset, BOOL bRedraw = TRUE)
+ {
+ SetScrollOffset(ptOffset.x, ptOffset.y, bRedraw);
+ }
+
+ void GetScrollOffset(POINT& ptOffset)
+ {
+ ptOffset.x = (LONG)(m_ptOffset.x * m_fzoom);
+ ptOffset.y = (LONG)(m_ptOffset.y * m_fzoom);
+ }
+
+ void SetScrollSize(int cx, int cy, BOOL bRedraw = TRUE)
+ {
+ SetZoomScrollSize(cx, cy, GetZoom(), bRedraw);
+ }
+
+ void SetScrollSize(SIZE sizeTrue, BOOL bRedraw = TRUE)
+ {
+ SetZoomScrollSize(sizeTrue, GetZoom(), bRedraw);
+ }
+
+ void GetScrollSize(SIZE& sizeTrue) const
+ {
+ sizeTrue = m_sizeTrue;
+ }
+
+ void SetScrollPage(int cxPage, int cyPage)
+ {
+ SetScrollPage(_WTYPES_NS::CSize(cxPage, cyPage));
+ }
+
+ void SetScrollPage(SIZE sizePage)
+ {
+ CScrollImpl< T >::SetScrollPage(sizePage / m_fzoom);
+ }
+
+ void GetScrollPage(SIZE& sizePage) const
+ {
+ sizePage = m_sizePage * m_fzoom;
+ }
+
+ void SetScrollLine(int cxLine, int cyLine)
+ {
+ SetScrollLine(_WTYPES_NS::CSize(cxLine, cyLine));
+ }
+
+ void SetScrollLine(SIZE sizeLine)
+ {
+ CScrollImpl< T >::SetScrollLine(sizeLine / m_fzoom);
+ }
+
+ void GetScrollLine(SIZE& sizeLine) const
+ {
+ sizeLine = m_sizeLine * m_fzoom;
+ }
+
+// Data access complements
+ _WTYPES_NS::CSize GetScrollSize()
+ {
+ return m_sizeTrue;
+ }
+
+ _WTYPES_NS::CSize GetScrollPage()
+ {
+ return m_sizePage * m_fzoom;
+ }
+
+ _WTYPES_NS::CSize GetScrollLine()
+ {
+ return m_sizeLine * m_fzoom;
+ }
+
+ _WTYPES_NS::CPoint GetScrollOffset()
+ {
+ return (_WTYPES_NS::CSize)m_ptOffset * m_fzoom;
+ }
+
+// Helper coordinate functions
+ _WTYPES_NS::CPoint WndtoTrue(CPoint ptW)
+ {
+ return (_WTYPES_NS::CSize)ptW * GetZoom() + GetScrollOffset();
+ }
+
+ void WndtoTrue(LPPOINT aptW, int nPts) // in place coord transformation
+ {
+ for (int i = 0 ; i < nPts ; i++)
+ aptW[i] = WndtoTrue(aptW[i]);
+ }
+
+ void WndtoTrue(LPRECT prectW) // in place coord transformation
+ {
+ WndtoTrue((LPPOINT)prectW, 2);
+ }
+
+ _WTYPES_NS::CPoint TruetoWnd(CPoint ptT)
+ {
+ return (ptT - GetScrollOffset()) / GetZoom();
+ }
+
+ void TruetoWnd(LPPOINT aptT, int nPts) // in place coord transformation
+ {
+ for (int i = 0 ; i < nPts ; i++)
+ aptT[i] = TruetoWnd(aptT[i]);
+ }
+
+ void TruetoWnd(LPRECT prectT) // in place coord transformation
+ {
+ TruetoWnd((LPPOINT)prectT, 2);
+ }
+
+// Drawing operations : assume adequate setting of data members
+ BOOL Draw(HBITMAP hbm, HDC hdestDC, DWORD dwROP = SRCCOPY)
+ {
+ CDC memDC = CreateCompatibleDC(hdestDC);
+ CBitmapHandle bmpOld = memDC.SelectBitmap(hbm);
+ BOOL bRes = Draw(memDC, hdestDC, dwROP);
+ memDC.SelectBitmap(bmpOld);
+ return bRes;
+ }
+
+ BOOL Draw(HDC hsourceDC, HDC hdestDC, DWORD dwROP = SRCCOPY)
+ {
+ CDCHandle destDC = hdestDC;
+ destDC.SetViewportOrg(0,0);
+ _WTYPES_NS::CPoint ptOffset = GetScrollOffset();
+ _WTYPES_NS::CSize sizeZClient = m_sizeClient * GetZoom();
+ return destDC.StretchBlt(0, 0, m_sizeClient.cx, m_sizeClient.cy, hsourceDC, ptOffset.x, ptOffset.y, sizeZClient.cx, sizeZClient.cy, dwROP);
+ }
+
+#ifdef _IMAGING_H
+ BOOL Draw(IImage* pIImage, HDC hdestDC)
+ {
+ CDCHandle destDC = hdestDC;
+ destDC.SetViewportOrg(0,0);
+ return SUCCEEDED(pIImage->Draw(destDC, _WTYPES_NS::CRect(-_WTYPES_NS::CPoint(m_ptOffset), m_sizeAll), NULL));
+ }
+#endif
+
+// Message map and handlers
+ BEGIN_MSG_MAP(CZoomScrollImpl< T >)
+ MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
+ CHAIN_MSG_MAP(CScrollImpl< T >)
+ END_MSG_MAP()
+
+ LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
+ {
+ T* pT = static_cast<T*>(this);
+ ATLASSERT(::IsWindow(pT->m_hWnd));
+ if ((GetScrollExtendedStyle() & SCRL_ERASEBACKGROUND))
+ {
+ _WTYPES_NS::CRect rect;
+ pT->GetClientRect(rect);
+ _WTYPES_NS::CSize sizeClient=rect.Size();
+
+ if (m_sizeAll.cx < sizeClient.cx || m_sizeAll.cy < sizeClient.cy)
+ {
+ CDCHandle hdc = (HDC)wParam;
+ HBRUSH hbr = GetSysColorBrush((int)T::GetWndClassInfo().m_wc.hbrBackground - 1);
+
+ if (m_sizeAll.cx < sizeClient.cx)
+ {
+ _WTYPES_NS::CRect rectBG(_WTYPES_NS::CPoint(m_sizeAll.cx, 0), sizeClient);
+ hdc.FillRect(rectBG, hbr);
+ }
+
+ if (m_sizeAll.cy < sizeClient.cy)
+ {
+ _WTYPES_NS::CRect rectBG(_WTYPES_NS::CPoint(0, m_sizeAll.cy), sizeClient);
+ hdc.FillRect(rectBG, hbr);
+ }
+ }
+ }
+ else
+ {
+ bHandled = FALSE;
+ }
+
+ return 1;
+ }
+};
+
+#endif // _WTL_CE_NO_ZOOMSCROLL
+
+#ifndef _WTL_CE_NO_CONTROLS
+
+// --- PPC bottom TabView control ---
+
+#if defined(__ATLCTRLX_H__) && defined(WIN32_PLATFORM_PSPC)
+
+///////////////////////////////////////////////////////////////////////////////
+// CBottomTabViewImpl
+
+template <class T, class TBase = ATL::CWindow, class TWinTraits = ATL::CControlWinTraits>
+class ATL_NO_VTABLE CBottomTabViewImpl : public CTabViewImpl<T, TBase, TWinTraits>
+{
+public:
+ DECLARE_WND_CLASS_EX(NULL, 0, COLOR_APPWORKSPACE)
+
+// Implementation overrideables
+ bool CreateTabControl()
+ {
+ m_tab.Create(m_hWnd, rcDefault, NULL, WS_CHILD | TCS_BOTTOM, 0, m_nTabID);
+
+ ATLASSERT(m_tab.m_hWnd != NULL);
+ if(m_tab.m_hWnd == NULL)
+ return false;
+
+ m_tab.SendMessage(CCM_SETVERSION, COMCTL32_VERSION);
+ m_tab.SetItemExtra(sizeof(TABVIEWPAGE));
+
+ T* pT = static_cast<T*>(this);
+ m_cyTabHeight = pT->CalcTabHeight();
+
+ return true;
+ }
+
+ int CalcTabHeight()
+ {
+ int nCount = m_tab.GetItemCount();
+ TCITEMEXTRA tcix = { 0 };
+ tcix.tciheader.mask = TCIF_TEXT;
+ tcix.tciheader.pszText = _T("NS");
+ int nIndex = m_tab.InsertItem(nCount, tcix);
+
+ RECT rect = { 0 };
+ SystemParametersInfo(SPI_GETWORKAREA, 0, &rect, 0);
+ RECT rcWnd = rect;
+
+ m_tab.AdjustRect(FALSE, &rect);
+ rcWnd.top = rect.bottom;
+ ::AdjustWindowRectEx(&rcWnd, m_tab.GetStyle(), FALSE, m_tab.GetExStyle());
+ m_tab.DeleteItem(nIndex);
+
+ return rcWnd.bottom - rcWnd.top;
+ }
+
+ void UpdateLayout()
+ {
+ RECT rect;
+ GetClientRect(&rect);
+
+ if(m_tab.IsWindow() && ((m_tab.GetStyle() & WS_VISIBLE) != 0))
+ m_tab.SetWindowPos(NULL, 0, rect.bottom - m_cyTabHeight, rect.right - rect.left, m_cyTabHeight, SWP_NOZORDER /*| SWP_SHOWWINDOW*/);
+
+ if(m_nActivePage != -1)
+ ::SetWindowPos(GetPageHWND(m_nActivePage), NULL, 0, 0, rect.right - rect.left, rect.bottom - m_cyTabHeight, SWP_NOZORDER);
+ }
+
+};
+
+class CBottomTabView : public CBottomTabViewImpl<CBottomTabView>
+{
+public:
+ DECLARE_WND_CLASS_EX(_T("WTL_BottomTabView"), 0, COLOR_APPWORKSPACE)
+};
+
+#endif // defined(__ATLCTRLX_H__) && defined(WIN32_PLATFORM_PSPC)
+
+
+// --- PPC/SmartPhone controls ---
+
+////////////////////////////////////////////////////////////////////////////////
+// These are wrapper classes for the Pocket PC 2002/2003 and SmartPhone 2003 controls
+// To implement a window based on a control, use following:
+// Example: Implementing a window based on a Html control
+//
+// class CMyHtml : CWindowImpl<CMyHtml, CHtmlCtrl>
+// {
+// public:
+// BEGIN_MSG_MAP(CMyHtml)
+// // put your message handler entries here
+// END_MSG_MAP()
+// };
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// CHtmlCtrl
+
+template <class TBase>
+class CHtmlCtrlT : public TBase
+{
+public:
+// Constructors
+ CHtmlCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CHtmlCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ ATLASSERT(hWnd != NULL); // Did you remember to call InitHTMLControl(hInstance) ??
+ return hWnd;
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_HTML;
+ }
+
+#if (_WIN32_WCE >= 400)
+ void AddStyle(LPCWSTR pszStyle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ADDSTYLE, 0, (LPARAM)pszStyle);
+ }
+#endif // (_WIN32_WCE >= 400)
+
+ void AddText(BOOL bPlainText, LPCSTR pszText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ADDTEXT, (WPARAM)bPlainText, (LPARAM)pszText);
+ }
+
+ void AddHTML(LPCSTR pszHTML)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ADDTEXT, (WPARAM)FALSE, (LPARAM)pszHTML);
+ }
+
+ void AddText(BOOL bPlainText, LPCWSTR pszText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ADDTEXTW, (WPARAM)bPlainText, (LPARAM)pszText);
+ }
+
+ void AddHTML(LPCWSTR pszHTML)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ADDTEXTW, (WPARAM)FALSE, (LPARAM)pszHTML);
+ }
+
+ void Anchor(LPCSTR pszAnchor)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ANCHOR, 0, (LPARAM)pszAnchor);
+ }
+
+ void Anchor(LPCWSTR pszAnchor)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ANCHORW, 0, (LPARAM)pszAnchor);
+ }
+
+#if (_WIN32_WCE >= 420)
+ void GetBrowserDispatch(IDispatch** ppDispatch)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(ppDispatch);
+ ATLASSERT(*ppDispatch==NULL);
+ ::SendMessage(m_hWnd, DTM_BROWSERDISPATCH, 0, (LPARAM)ppDispatch);
+ }
+ void GetDocumentDispatch(IDispatch** ppDispatch)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(ppDispatch);
+ ATLASSERT(*ppDispatch==NULL);
+ ::SendMessage(m_hWnd, DTM_DOCUMENTDISPATCH , 0, (LPARAM)ppDispatch);
+ }
+#endif // (_WIN32_WCE >= 420)
+
+ void Clear()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_CLEAR, 0, 0L);
+ }
+
+ void EnableClearType(BOOL bEnable = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ENABLECLEARTYPE, 0, (LPARAM)bEnable);
+ }
+
+ void EnableContextMenu(BOOL bEnable = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ENABLECONTEXTMENU, 0, (LPARAM)bEnable);
+ }
+
+ void EnableScripting(BOOL bEnable = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ENABLESCRIPTING, 0, (LPARAM)bEnable);
+ }
+
+ void EnableShrink(BOOL bEnable = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ENABLESHRINK, 0, (LPARAM)bEnable);
+ }
+
+ void EndOfSource()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ENDOFSOURCE, 0, 0L);
+ }
+
+ void ImageFail(DWORD dwCookie)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_IMAGEFAIL, 0, (LPARAM)dwCookie);
+ }
+
+ int GetLayoutHeight() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, DTM_LAYOUTHEIGHT, 0, 0L);
+ }
+
+ int GetLayoutWidth() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, DTM_LAYOUTWIDTH, 0, 0L);
+ }
+
+ void Navigate(LPCTSTR pstrURL, UINT uFlags = 0)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pstrURL);
+ ::SendMessage(m_hWnd, DTM_NAVIGATE, (WPARAM)uFlags, (LPARAM)pstrURL);
+ }
+
+ void SelectAll()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_SELECTALL, 0, 0L);
+ }
+
+ void SetImage(INLINEIMAGEINFO* pImageInfo)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pImageInfo);
+ ::SendMessage(m_hWnd, DTM_SETIMAGE, 0, (LPARAM)pImageInfo);
+ }
+
+ void ZoomLevel(int iLevel)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_ZOOMLEVEL, 0, (LPARAM)iLevel);
+ }
+
+#if (_WIN32_WCE >= 400)
+ void Stop()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DTM_STOP, 0, 0L);
+ }
+#endif // (_WIN32_WCE >= 400)
+
+ void GetScriptDispatch(IDispatch** ppDispatch)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(ppDispatch);
+ ATLASSERT(*ppDispatch==NULL);
+ ::SendMessage(m_hWnd, DTM_SCRIPTDISPATCH, 0, (LPARAM)ppDispatch);
+ }
+};
+
+typedef CHtmlCtrlT<ATL::CWindow> CHtmlCtrl;
+
+
+#ifdef WIN32_PLATFORM_PSPC
+
+///////////////////////////////////////////////////////////////////////////////
+// CRichInkCtrl
+
+template <class TBase>
+class CRichInkCtrlT : public TBase
+{
+public:
+// Constructors
+ CRichInkCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CRichInkCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ ATLASSERT(hWnd != NULL); // Did you remember to call InitRichInkDLL() ??
+ return hWnd;
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_RICHINK;
+ }
+
+ BOOL CanPaste(UINT uFormat = 0) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_CANPASTE, (WPARAM)uFormat, 0L);
+ }
+
+ BOOL CanRedo() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_CANREDO, 0, 0L);
+ }
+
+ BOOL CanUndo() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_CANUNDO, 0, 0L);
+ }
+
+ void ClearAll(BOOL bRepaint = TRUE) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_CLEARALL, (WPARAM)bRepaint, 0L);
+ }
+
+ BOOL GetModify() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, EM_GETMODIFY, 0, 0L);
+ }
+
+ UINT GetPageStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_GETPAGESTYLE, 0, 0L);
+ }
+
+ UINT GetPenMode() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_GETPENMODE, 0, 0L);
+ }
+
+ UINT GetViewStyle() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_GETVIEW, 0, 0L);
+ }
+
+ UINT GetWrapMode() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_GETWRAPMODE, 0, 0L);
+ }
+
+ UINT GetZoomPercent() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_GETZOOMPERCENT, 0, 0L);
+ }
+
+ void InsertLinks(LPWSTR lpString, int cchLength = -1)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ if(cchLength == -1)
+ cchLength = lstrlen(lpString);
+ ::SendMessage(m_hWnd, EM_INSERTLINKS, (WPARAM)cchLength, (LPARAM)lpString);
+ }
+
+ void RedoEvent()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_REDOEVENT, 0, 0L);
+ }
+
+ UINT SetInkLayer(UINT uLayer)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (UINT)::SendMessage(m_hWnd, EM_SETINKLAYER, (WPARAM)uLayer, 0L);
+ }
+
+ void SetPageStyle(UINT uStyle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETPAGESTYLE, (WPARAM)uStyle, 0L);
+ }
+
+ void SetPenMode(UINT uMode)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETPENMODE, (WPARAM)uMode, 0L);
+ }
+
+ void SetViewStyle(UINT uStyle)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETVIEW, (WPARAM)uStyle, 0L);
+ }
+
+ void SetViewAttributes(VIEWATTRIBUTES* pAttribs)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pAttribs);
+ ::SendMessage(m_hWnd, EM_SETVIEWATTRIBUTES, 0, (LPARAM)pAttribs);
+ }
+
+ void SetWrapMode(UINT uMode)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETWRAPMODE, (WPARAM)uMode, 0L);
+ }
+
+ void SetZoomPercent(UINT uPercent)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETZOOMPERCENT, (WPARAM)uPercent, 0L);
+ }
+
+ LONG StreamIn(UINT uFormat, EDITSTREAM& es)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_STREAMIN, (WPARAM)uFormat, (LPARAM)&es);
+ }
+
+ LONG StreamOut(UINT uFormat, EDITSTREAM& es)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (LONG)::SendMessage(m_hWnd, EM_STREAMOUT, (WPARAM)uFormat, (LPARAM)&es);
+ }
+
+ void UndoEvent()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_UNDOEVENT, 0, 0L);
+ }
+
+ void Undo()
+ {
+ UndoEvent();
+ }
+
+// Standard EM_xxx messages
+ DWORD GetSel() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetViewStyle() != VT_DRAWINGVIEW);
+ return (DWORD)::SendMessage(m_hWnd, EM_GETSEL, 0, 0L);
+ }
+
+ void GetSel(int& nStartChar, int& nEndChar) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetViewStyle() != VT_DRAWINGVIEW);
+ ::SendMessage(m_hWnd, EM_GETSEL, (WPARAM)&nStartChar, (LPARAM)&nEndChar);
+ }
+
+ void SetSel(int nStartChar, int nEndChar)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetViewStyle() != VT_DRAWINGVIEW);
+ ::SendMessage(m_hWnd, EM_SETSEL, nStartChar, nEndChar);
+ }
+
+ void ReplaceSel(LPCTSTR lpszNewText, BOOL bCanUndo = FALSE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(GetViewStyle() != VT_DRAWINGVIEW);
+ ::SendMessage(m_hWnd, EM_REPLACESEL, (WPARAM)bCanUndo, (LPARAM)lpszNewText);
+ }
+
+ void SetModify(BOOL bModified = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, EM_SETMODIFY, (WPARAM)bModified, 0L);
+ }
+
+ int GetTextLength() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, WM_GETTEXTLENGTH, 0, 0L);
+ }
+
+// Clipboard operations
+ void Clear()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_CLEAR, 0, 0L);
+ }
+
+ void Copy()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_COPY, 0, 0L);
+ }
+
+ void Cut()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_CUT, 0, 0L);
+ }
+
+ void Paste()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, WM_PASTE, 0, 0L);
+ }
+};
+
+typedef CRichInkCtrlT<ATL::CWindow> CRichInkCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CInkXCtrl
+
+template <class TBase>
+class CInkXCtrlT : public TBase
+{
+public:
+// Constructors
+ CInkXCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CInkXCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ ATLASSERT(hWnd != NULL); // Did you remember to call InitInkX() ??
+ return hWnd;
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_INKX;
+ }
+
+ static UINT GetHotRecordingMessage()
+ {
+ return ::RegisterWindowMessage(szHotRecording);
+ }
+
+ void ClearAll()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IM_CLEARALL, 0, 0L);
+ }
+
+ int GetData(BYTE* lpBuffer, INT cbBuffer) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpBuffer);
+ return (int)::SendMessage(m_hWnd, IM_GETDATA, (WPARAM)cbBuffer, (LPARAM)lpBuffer);
+ }
+
+ int GetDataLen() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, IM_GETDATALEN, 0, 0L);
+ }
+
+ CRichInkCtrl GetRichInk() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HWND)::SendMessage(m_hWnd, IM_GETRICHINK, 0, 0L);
+ }
+
+ BOOL IsRecording() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, IM_RECORDING, 0, 0L);
+ }
+
+ void ReInit()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IM_REINIT, 0, 0L);
+ }
+
+ void SetData(const BYTE* lpInkData, INT cbInkData)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(lpInkData);
+ ::SendMessage(m_hWnd, IM_SETDATA, (WPARAM)cbInkData, (LPARAM)lpInkData);
+ }
+
+ void VoicePlay()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IM_VOICE_PLAY, 0, 0L);
+ }
+
+ BOOL IsVoicePlaying() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, IM_VOICE_PLAYING, 0, 0L);
+ }
+
+ BOOL VoiceRecord()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, IM_VOICE_RECORD, 0, 0L);
+ }
+
+ void VoiceStop()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IM_VOICE_STOP, 0, 0L);
+ }
+
+ void ShowVoiceBar(BOOL bShow = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, IM_VOICEBAR, (WPARAM)bShow, 0L);
+ }
+};
+
+typedef CInkXCtrlT<ATL::CWindow> CInkXCtrl;
+
+#endif // WIN32_PLATFORM_PSPC
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CVoiceRecorderCtrl
+
+template <class TBase>
+class CVoiceRecorderCtrlT : public TBase
+{
+public:
+// Constructors
+ CVoiceRecorderCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CVoiceRecorderCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, const POINT pt, LPTSTR pstrFileName, UINT nID, DWORD dwStyle = 0)
+ {
+ ATLASSERT(pstrFileName != NULL);
+ CM_VOICE_RECORDER cmvr = { 0 };
+ cmvr.cb = sizeof(CM_VOICE_RECORDER);
+ cmvr.dwStyle = dwStyle;
+ cmvr.xPos = pt.x;
+ cmvr.yPos = pt.y;
+ cmvr.hwndParent = hWndParent;
+ cmvr.id = nID;
+ cmvr.lpszRecordFileName = pstrFileName;
+ m_hWnd = VoiceRecorder_Create(&cmvr);
+ return m_hWnd;
+ }
+
+ HWND Create(LPCM_VOICE_RECORDER pAttribs)
+ {
+ ATLASSERT(pAttribs);
+ m_hWnd = VoiceRecorder_Create(pAttribs);
+ return m_hWnd;
+ }
+
+// Attributes
+ void Record()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, VRM_RECORD, 0, 0L);
+ }
+
+ void Play()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, VRM_PLAY, 0, 0L);
+ }
+
+ void Stop()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, VRM_STOP, 0, 0L);
+ }
+
+ void Cancel()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, VRM_CANCEL, 0, 0L);
+ }
+
+ void Done()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, VRM_OK, 0, 0L);
+ }
+};
+
+typedef CVoiceRecorderCtrlT<ATL::CWindow> CVoiceRecorderCtrl;
+
+
+#ifdef WIN32_PLATFORM_PSPC
+
+///////////////////////////////////////////////////////////////////////////////
+// CDocListCtrl
+
+template <class TBase>
+class CDocListCtrlT : public TBase
+{
+public:
+// Attributes
+ DOCLISTCREATE m_dlc;
+ TCHAR m_szPath[MAX_PATH];
+
+// Constructors
+ CDocListCtrlT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CDocListCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, WORD wId, LPCTSTR pszFolder = NULL, LPCTSTR pstrFilter = NULL,
+ WORD wFilterIndex = 0, DWORD dwFlags = DLF_SHOWEXTENSION)
+ {
+ ATLASSERT(pstrFilter != NULL); // It seems to need a filter badly!!
+ ::ZeroMemory(&m_dlc, sizeof(DOCLISTCREATE));
+ ::ZeroMemory(m_szPath, sizeof(m_szPath));
+ if(pszFolder != NULL)
+ SecureHelper::strncpy_x(m_szPath, MAX_PATH, pszFolder, MAX_PATH - 1);
+ m_dlc.dwStructSize = sizeof(DOCLISTCREATE);
+ m_dlc.hwndParent = hWndParent;
+ m_dlc.pszFolder = m_szPath;
+ m_dlc.pstrFilter = pstrFilter;
+ m_dlc.wFilterIndex = wFilterIndex;
+ m_dlc.wId = wId;
+ m_dlc.dwFlags = dwFlags;
+ m_hWnd = DocList_Create(&m_dlc);
+ return m_hWnd;
+ }
+
+ HWND Create(DOCLISTCREATE* pDlc)
+ {
+ m_dlc = *pDlc;
+ m_hWnd = DocList_Create(&m_dlc);
+ return m_hWnd;
+ }
+
+// Attributes
+ void DeleteSel()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DLM_DELETESEL, 0, 0L);
+ }
+
+ void DisableUpdates()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DLM_DISABLEUPDATES, 0, 0L);
+ }
+
+ void EnableUpdates()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DLM_ENABLEUPDATES, 0, 0L);
+ }
+
+ int GetFilterIndex() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, DLM_GETFILTERINDEX, 0, 0L);
+ }
+
+ int GetItemCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, DLM_GETITEMCOUNT, 0, 0L);
+ }
+
+ int GetNextItem(int iIndex, DWORD dwRelation = LVNI_ALL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, DLM_GETNEXTITEM, (WPARAM)iIndex, (LPARAM)dwRelation);
+ }
+
+ int GetFirstItem(DWORD dwRelation = LVNI_ALL) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, DLM_GETNEXTITEM, (WPARAM)-1, (LPARAM)dwRelation);
+ }
+
+ BOOL GetNextWave(int* pIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pIndex);
+ return (BOOL)::SendMessage(m_hWnd, DLM_GETNEXTWAVE, 0, (LPARAM)pIndex);
+ }
+
+ BOOL GetPrevWave(int* pIndex) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pIndex);
+ return (BOOL)::SendMessage(m_hWnd, DLM_GETPREVWAVE, 0, (LPARAM)pIndex);
+ }
+
+ int GetSelCount() const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, DLM_GETSELCOUNT, 0, 0L);
+ }
+
+ BOOL GetSelPathName(LPTSTR pstrPath, int cchMax) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pstrPath);
+ return (BOOL)::SendMessage(m_hWnd, DLM_GETSELPATHNAME, (WPARAM)cchMax, (LPARAM)pstrPath);
+ }
+
+ void ReceiveIR(LPCTSTR pstrPath) const
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pstrPath);
+ ::SendMessage(m_hWnd, DLM_RECEIVEIR, 0, (LPARAM)pstrPath);
+ }
+
+ void Refresh()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DLM_REFRESH, 0, 0L);
+ }
+
+ BOOL RenameMoveSelectedItems()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, DLM_RENAMEMOVE, 0, 0L);
+ }
+
+ int SelectAll()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (int)::SendMessage(m_hWnd, DLM_SELECTALL, 0, 0L);
+ }
+
+ HRESULT SelectItem(LPCTSTR pstrPath, BOOL bVisible = TRUE)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pstrPath);
+ return (HRESULT)::SendMessage(m_hWnd, DLM_SELECTITEM, (WPARAM)bVisible, (LPARAM)pstrPath);
+ }
+
+ void SendEMail(LPCTSTR pstrAttachment)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DLM_SENDEMAIL, 0, (LPARAM)pstrAttachment);
+ }
+
+ void SendIR(LPCTSTR pstrPath)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DLM_SENDIR, 0, (LPARAM)pstrPath);
+ }
+
+ HRESULT SetFilterIndex(int iIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HRESULT)::SendMessage(m_hWnd, DLM_SETFILTERINDEX, (WPARAM)iIndex, 0L);
+ }
+
+ void SetFolder(LPCTSTR pstrPath)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pstrPath);
+ ::SendMessage(m_hWnd, DLM_SETFOLDER, 0, (LPARAM)pstrPath);
+ }
+
+ BOOL SetItemState(int iIndex, const LVITEM* pItem)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pItem);
+ return (BOOL)::SendMessage(m_hWnd, DLM_SETITEMSTATE, (WPARAM)iIndex, (LPARAM)pItem);
+ }
+
+ BOOL SetItemState(int iIndex, UINT uState, UINT uMask)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ LV_ITEM lvi = { 0 };
+ lvi.stateMask = uMask;
+ lvi.state = uState;
+ return (BOOL)::SendMessage(m_hWnd, DLM_SETITEMSTATE, (WPARAM)iIndex, (LPARAM)&lvi);
+ }
+
+ void SetOneItem(int iIndex, LPCVOID pPA)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DLM_SETONEITEM, (WPARAM)iIndex, (LPARAM)pPA);
+ }
+
+ void SetSelect(int iIndex)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ::SendMessage(m_hWnd, DLM_SETSELECT, (WPARAM)iIndex, 0L);
+ }
+
+ void SetSelPathName(LPCTSTR pstrPath)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pstrPath);
+ ::SendMessage(m_hWnd, DLM_SETSELPATHNAME, 0, (LPARAM)pstrPath);
+ }
+
+ BOOL SetSortOrder()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, DLM_SETSORTORDER, 0, 0L);
+ }
+
+ HRESULT Update()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (HRESULT)::SendMessage(m_hWnd, DLM_UPDATE, 0, 0L);
+ }
+
+ BOOL ValidateFolder()
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return (BOOL)::SendMessage(m_hWnd, DLM_VALIDATEFOLDER, 0, 0L);
+ }
+
+// Functions
+ BOOL GetFirstSelectedWaveFile(int* pIndex, LPTSTR szPath, const size_t cchPath)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return DocList_GetFirstSelectedWaveFile(m_hWnd, pIndex, szPath, cchPath);
+ }
+
+ BOOL GetNextSelectedWaveFile(int* pIndex, LPTSTR szPath, const size_t cchPath)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ return DocList_GetNextSelectedWaveFile(m_hWnd, pIndex, szPath, cchPath);
+ }
+};
+
+typedef CDocListCtrlT<ATL::CWindow> CDocListCtrl;
+
+#endif // WIN32_PLATFORM_PSPC
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CCapEdit
+
+template <class TBase>
+class CCapEditT : public TBase
+{
+public:
+// Constructors
+ CCapEditT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CCapEditT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ HWND hWnd = /*TBase*/CWindow::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ ATLASSERT(hWnd != NULL); // Did you remember to call SHInitExtraControls() ??
+ return hWnd;
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_CAPEDIT;
+ }
+};
+
+typedef CCapEditT<WTL::CEdit> CCapEdit;
+
+///////////////////////////////////////////////////////////////////////////////
+// CTTStatic
+
+#ifndef WIN32_PLATFORM_WFSP // Tooltips not supported on SmartPhone
+
+template <class TBase>
+class CTTStaticT : public TBase
+{
+public:
+// Constructors
+ CTTStaticT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CTTStaticT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ HWND hWnd = TBase::Create(hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ ATLASSERT(hWnd != NULL); // Did you remember to call SHInitExtraControls() ??
+ return hWnd;
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_TSTATIC;
+ }
+
+// Operations
+ BOOL SetToolTipText(LPCTSTR pstrTipText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pstrTipText);
+ ATLASSERT(lstrlen(pstrTipText) <= 253);
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ int cchLen = lstrlen(pstrTipText) + 3;
+ LPTSTR pstr = buff.Allocate(cchLen);
+ if(pstr == NULL)
+ return FALSE;
+ SecureHelper::strcpy_x(pstr, cchLen, _T("~~"));
+ SecureHelper::strcat_x(pstr, cchLen, pstrTipText);
+ return SetWindowText(pstr);
+ }
+};
+
+typedef CTTStaticT<WTL::CStatic> CTTStatic;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CTTButton
+
+template <class TBase>
+class CTTButtonT : public TBase
+{
+public:
+// Constructors
+ CTTButtonT(HWND hWnd = NULL) : TBase(hWnd)
+ { }
+
+ CTTButtonT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+ HWND hWnd = TBase::Create(hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
+ ATLASSERT(hWnd != NULL); // Did you remember to call SHInitExtraControls() ??
+ return hWnd;
+ }
+
+// Attributes
+ static LPCTSTR GetWndClassName()
+ {
+ return WC_TBUTTON;
+ }
+
+// Operations
+ BOOL SetToolTipText(LPCTSTR pstrTipText)
+ {
+ ATLASSERT(::IsWindow(m_hWnd));
+ ATLASSERT(pstrTipText);
+ ATLASSERT(lstrlen(pstrTipText) <= 253);
+ CTempBuffer<TCHAR, _WTL_STACK_ALLOC_THRESHOLD> buff;
+ int cchLen = lstrlen(pstrTipText) + 3;
+ LPTSTR pstr = buff.Allocate(cchLen);
+ if(pstr == NULL)
+ return FALSE;
+ SecureHelper::strcpy_x(pstr, cchLen, _T("~~"));
+ SecureHelper::strcat_x(pstr, cchLen, pstrTipText);
+ return SetWindowText(pstr);
+ }
+};
+
+typedef CTTButtonT<WTL::CButton> CTTButton;
+
+#endif // !WIN32_PLATFORM_WFSP
+
+
+// --- SmartPhone specific controls ---
+
+#ifdef WIN32_PLATFORM_WFSP
+
+///////////////////////////////////////////////////////////////////////////////
+// CSpinCtrlT - CSpinCtrl : SmartPhone adapted UpDown control
+
+template <class TBase>
+class CSpinCtrlT : public CUpDownCtrlT< TBase >
+{
+public:
+// Constructors
+ CSpinCtrlT(HWND hWnd = NULL) : CUpDownCtrlT< TBase >(hWnd)
+ { }
+
+ CSpinCtrlT< TBase >& operator =(HWND hWnd)
+ {
+ m_hWnd = hWnd;
+ return *this;
+ }
+
+ HWND Create(HWND hWndParent, HWND hBuddy, DWORD dwStyle, int nID, LPCTSTR szExpandedName = NULL)
+ {
+ ATLASSERT(::IsWindow(hWndParent));
+ CUpDownCtrlT< TBase >::Create(hWndParent, NULL, szExpandedName, dwStyle, 0, nID, NULL);
+ ATLASSERT(m_hWnd != NULL); // Did you remember to call AtlInitCommonControls(ICC_UPDOWN_CLASS)?
+ if (hBuddy != NULL)
+ {
+ ATLASSERT(::IsWindow(hBuddy));
+ SetBuddy(hBuddy);
+ }
+ return m_hWnd;
+ }
+};
+
+typedef CSpinCtrlT<ATL::CWindow> CSpinCtrl;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CSpinned - SmartPhone association of control and Spin
+
+template <class TBase, bool t_bExpandOnly>
+class CSpinned : public TBase
+{
+public:
+ CSpinCtrl m_SpinCtrl;
+ DWORD m_dwSpinnedStyle;
+
+// Constructors
+ CSpinned(HWND hWnd = NULL) : TBase(hWnd)
+ {
+ m_dwSpinnedStyle = WS_VISIBLE | UDS_ALIGNRIGHT | UDS_EXPANDABLE;
+
+ if (t_bExpandOnly == true)
+ m_dwSpinnedStyle |= UDS_NOSCROLL;
+ else
+ m_dwSpinnedStyle |= UDS_HORZ | UDS_ARROWKEYS | UDS_SETBUDDYINT | UDS_WRAP;
+
+ if (hWnd != NULL)
+ AttachOrCreateSpinCtrl();
+ }
+
+ CSpinned<TBase, t_bExpandOnly>& operator =(HWND hWnd)
+ {
+ Attach(hWnd);
+ return *this;
+ }
+
+ void Attach(HWND hWnd)
+ {
+ ATLASSERT(!IsWindow());
+ TBase* pT = static_cast<TBase*>(this);
+ pT->m_hWnd = hWnd;
+ if (hWnd != NULL)
+ AttachOrCreateSpinCtrl();
+ }
+
+ HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szExpandedName = NULL,
+ DWORD dwStyle = 0, DWORD dwExStyle = 0,
+ ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
+ {
+
+ TBase* pT = static_cast<TBase*>(this);
+ TBase::Create(hWndParent, rect, NULL, dwStyle, dwExStyle, MenuOrID, lpCreateParam);
+ ATLASSERT(pT->m_hWnd != NULL);
+
+ m_SpinCtrl.Create(hWndParent, pT->m_hWnd, m_dwSpinnedStyle, ATL_IDW_SPIN_ID + (int)MenuOrID.m_hMenu, szExpandedName);
+
+ ATLASSERT(m_SpinCtrl.m_hWnd != NULL); // Did you remember to call AtlInitCommonControls(ICC_UPDOWN_CLASS)?
+
+ return pT->m_hWnd;
+ }
+
+// Attributes
+ CSpinCtrl& GetSpinCtrl()
+ {
+ return m_SpinCtrl;
+ }
+
+// Implementation
+ // Attach our existing SpinCtrl or create one
+ bool AttachOrCreateSpinCtrl()
+ {
+ TBase* pT = static_cast<TBase*>(this);
+
+ HWND hSpin = ::GetDlgItem(pT->GetParent(), ATL_IDW_SPIN_ID + pT->GetDlgCtrlID());
+
+ if (hSpin != NULL)
+ {
+ m_SpinCtrl.Attach(hSpin);
+#ifdef DEBUG
+ TCHAR sClassName[16];
+ ::GetClassName(hSpin, sClassName, 16);
+ ATLASSERT(!_tcscmp(sClassName, UPDOWN_CLASS));
+ ATLASSERT(m_SpinCtrl.GetBuddy().m_hWnd == pT->m_hWnd);
+#endif // DEBUG
+ }
+ else
+ {
+ m_SpinCtrl.Create(pT->GetParent(), pT->m_hWnd, m_dwSpinnedStyle, ATL_IDW_SPIN_ID + pT->GetDlgCtrlID());
+ }
+
+ return m_SpinCtrl.m_hWnd != NULL;
+ }
+};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// CSpinListBox - SmartPhone spinned ListBox control
+// CExpandListBox - SmartPhone expandable ListBox control
+// CExpandEdit - SmartPhone expandable Edit control
+// CExpandCapEdit - SmartPhone expandable CapEdit control
+
+typedef CSpinned<CListBox, false> CSpinListBox;
+typedef CSpinned<CListBox, true> CExpandListBox;
+typedef CSpinned<CEdit, true> CExpandEdit;
+typedef CSpinned<CCapEdit, true> CExpandCapEdit;
+
+#endif // WIN32_PLATFORM_WFSP
+
+#endif // _WTL_CE_NO_CONTROLS
+
+}; // namespace WTL
+
+#endif // __ATLWINCE_H__
diff --git a/plugins/SmartAutoReplier/wtl/atlwinx.h b/plugins/SmartAutoReplier/wtl/atlwinx.h
new file mode 100644
index 0000000000..629d29778f
--- /dev/null
+++ b/plugins/SmartAutoReplier/wtl/atlwinx.h
@@ -0,0 +1,525 @@
+// Windows Template Library - WTL version 8.1
+// Copyright (C) Microsoft Corporation. All rights reserved.
+//
+// This file is a part of the Windows Template Library.
+// The use and distribution terms for this software are covered by the
+// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
+// which can be found in the file CPL.TXT at the root of this distribution.
+// By using this software in any fashion, you are agreeing to be bound by
+// the terms of this license. You must not remove this notice, or
+// any other, from this software.
+
+#ifndef __ATLWINX_H__
+#define __ATLWINX_H__
+
+#pragma once
+
+#ifndef __ATLAPP_H__
+ #error atlwinx.h requires atlapp.h to be included first
+#endif
+
+#if (_ATL_VER >= 0x0700)
+ #include <atlwin.h>
+#endif // (_ATL_VER >= 0x0700)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Classes in this file:
+//
+// _U_RECT
+// _U_MENUorID
+// _U_STRINGorID
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Command Chaining Macros
+
+#define CHAIN_COMMANDS(theChainClass) \
+ if(uMsg == WM_COMMAND) \
+ CHAIN_MSG_MAP(theChainClass)
+
+#define CHAIN_COMMANDS_ALT(theChainClass, msgMapID) \
+ if(uMsg == WM_COMMAND) \
+ CHAIN_MSG_MAP_ALT(theChainClass, msgMapID)
+
+#define CHAIN_COMMANDS_MEMBER(theChainMember) \
+ if(uMsg == WM_COMMAND) \
+ CHAIN_MSG_MAP_MEMBER(theChainMember)
+
+#define CHAIN_COMMANDS_ALT_MEMBER(theChainMember, msgMapID) \
+ if(uMsg == WM_COMMAND) \
+ CHAIN_MSG_MAP_ALT_MEMBER(theChainMember, msgMapID)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Macros for parent message map to selectively reflect control messages
+
+// NOTE: ReflectNotifications is a member of ATL's CWindowImplRoot
+// (and overridden in 2 cases - CContainedWindowT and CAxHostWindow)
+// Since we can't modify ATL, we'll provide the needed additions
+// in a separate function (that is not a member of CWindowImplRoot)
+
+namespace WTL
+{
+
+inline LRESULT WtlReflectNotificationsFiltered(HWND hWndParent, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled,
+ UINT uMsgFilter = WM_NULL, UINT_PTR idFromFilter = 0, HWND hWndChildFilter = NULL)
+{
+ if((uMsgFilter != WM_NULL) && (uMsgFilter != uMsg))
+ {
+ // The notification message doesn't match the filter.
+ bHandled = FALSE;
+ return 1;
+ }
+
+ HWND hWndChild = NULL;
+ UINT_PTR idFrom = 0;
+
+ switch(uMsg)
+ {
+ case WM_COMMAND:
+ if(lParam != NULL) // not from a menu
+ {
+ hWndChild = (HWND)lParam;
+ idFrom = (UINT_PTR)LOWORD(wParam);
+ }
+ break;
+ case WM_NOTIFY:
+ hWndChild = ((LPNMHDR)lParam)->hwndFrom;
+ idFrom = ((LPNMHDR)lParam)->idFrom;
+ break;
+#ifndef _WIN32_WCE
+ case WM_PARENTNOTIFY:
+ switch(LOWORD(wParam))
+ {
+ case WM_CREATE:
+ case WM_DESTROY:
+ hWndChild = (HWND)lParam;
+ idFrom = (UINT_PTR)HIWORD(wParam);
+ break;
+ default:
+ hWndChild = ::GetDlgItem(hWndParent, HIWORD(wParam));
+ idFrom = (UINT_PTR)::GetDlgCtrlID(hWndChild);
+ break;
+ }
+ break;
+#endif // !_WIN32_WCE
+ case WM_DRAWITEM:
+ if(wParam) // not from a menu
+ {
+ hWndChild = ((LPDRAWITEMSTRUCT)lParam)->hwndItem;
+ idFrom = (UINT_PTR)wParam;
+ }
+ break;
+ case WM_MEASUREITEM:
+ if(wParam) // not from a menu
+ {
+ hWndChild = ::GetDlgItem(hWndParent, ((LPMEASUREITEMSTRUCT)lParam)->CtlID);
+ idFrom = (UINT_PTR)wParam;
+ }
+ break;
+ case WM_COMPAREITEM:
+ if(wParam) // not from a menu
+ {
+ hWndChild = ((LPCOMPAREITEMSTRUCT)lParam)->hwndItem;
+ idFrom = (UINT_PTR)wParam;
+ }
+ break;
+ case WM_DELETEITEM:
+ if(wParam) // not from a menu
+ {
+ hWndChild = ((LPDELETEITEMSTRUCT)lParam)->hwndItem;
+ idFrom = (UINT_PTR)wParam;
+ }
+ break;
+ case WM_VKEYTOITEM:
+ case WM_CHARTOITEM:
+ case WM_HSCROLL:
+ case WM_VSCROLL:
+ hWndChild = (HWND)lParam;
+ idFrom = (UINT_PTR)::GetDlgCtrlID(hWndChild);
+ break;
+ case WM_CTLCOLORBTN:
+ case WM_CTLCOLORDLG:
+ case WM_CTLCOLOREDIT:
+ case WM_CTLCOLORLISTBOX:
+ case WM_CTLCOLORMSGBOX:
+ case WM_CTLCOLORSCROLLBAR:
+ case WM_CTLCOLORSTATIC:
+ hWndChild = (HWND)lParam;
+ idFrom = (UINT_PTR)::GetDlgCtrlID(hWndChild);
+ break;
+ default:
+ break;
+ }
+
+ if((hWndChild == NULL) ||
+ ((hWndChildFilter != NULL) && (hWndChildFilter != hWndChild)))
+ {
+ // Either hWndChild isn't valid, or
+ // hWndChild doesn't match the filter.
+ bHandled = FALSE;
+ return 1;
+ }
+
+ if((idFromFilter != 0) && (idFromFilter != idFrom))
+ {
+ // The dialog control id doesn't match the filter.
+ bHandled = FALSE;
+ return 1;
+ }
+
+ ATLASSERT(::IsWindow(hWndChild));
+ LRESULT lResult = ::SendMessage(hWndChild, OCM__BASE + uMsg, wParam, lParam);
+ if((lResult == 0) && (uMsg >= WM_CTLCOLORMSGBOX) && (uMsg <= WM_CTLCOLORSTATIC))
+ {
+ // Try to prevent problems with WM_CTLCOLOR* messages when
+ // the message wasn't really handled
+ bHandled = FALSE;
+ }
+
+ return lResult;
+}
+
+}; // namespace WTL
+
+// Try to prevent problems with WM_CTLCOLOR* messages when
+// the message wasn't really handled
+#define REFLECT_NOTIFICATIONS_EX() \
+{ \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if((lResult == 0) && (uMsg >= WM_CTLCOLORMSGBOX) && (uMsg <= WM_CTLCOLORSTATIC)) \
+ bHandled = FALSE; \
+ if(bHandled) \
+ return TRUE; \
+}
+
+#define REFLECT_NOTIFICATIONS_MSG_FILTERED(uMsgFilter) \
+ { \
+ bHandled = TRUE; \
+ lResult = WTL::WtlReflectNotificationsFiltered(m_hWnd, uMsg, wParam, lParam, bHandled, uMsgFilter, 0, NULL); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFICATIONS_ID_FILTERED(idFromFilter) \
+ { \
+ bHandled = TRUE; \
+ lResult = WTL::WtlReflectNotificationsFiltered(m_hWnd, uMsg, wParam, lParam, bHandled, WM_NULL, idFromFilter, NULL); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFICATIONS_HWND_FILTERED(hWndChildFilter) \
+ { \
+ bHandled = TRUE; \
+ lResult = WTL::WtlReflectNotificationsFiltered(m_hWnd, uMsg, wParam, lParam, bHandled, WM_NULL, 0, hWndChildFilter); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFICATIONS_MSG_ID_FILTERED(uMsgFilter, idFromFilter) \
+ { \
+ bHandled = TRUE; \
+ lResult = WTL::WtlReflectNotificationsFiltered(m_hWnd, uMsg, wParam, lParam, bHandled, uMsgFilter, idFromFilter, NULL); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFICATIONS_MSG_HWND_FILTERED(uMsgFilter, hWndChildFilter) \
+ { \
+ bHandled = TRUE; \
+ lResult = WTL::WtlReflectNotificationsFiltered(m_hWnd, uMsg, wParam, lParam, bHandled, uMsgFilter, 0, hWndChildFilter); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_COMMAND(id, code) \
+ if(uMsg == WM_COMMAND && id == LOWORD(wParam) && code == HIWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_COMMAND_ID(id) \
+ if(uMsg == WM_COMMAND && id == LOWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_COMMAND_CODE(code) \
+ if(uMsg == WM_COMMAND && code == HIWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_COMMAND_RANGE(idFirst, idLast) \
+ if(uMsg == WM_COMMAND && LOWORD(wParam) >= idFirst && LOWORD(wParam) <= idLast) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_COMMAND_RANGE_CODE(idFirst, idLast, code) \
+ if(uMsg == WM_COMMAND && code == HIWORD(wParam) && LOWORD(wParam) >= idFirst && LOWORD(wParam) <= idLast) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFY(id, cd) \
+ if(uMsg == WM_NOTIFY && id == ((LPNMHDR)lParam)->idFrom && cd == ((LPNMHDR)lParam)->code) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFY_ID(id) \
+ if(uMsg == WM_NOTIFY && id == ((LPNMHDR)lParam)->idFrom) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFY_CODE(cd) \
+ if(uMsg == WM_NOTIFY && cd == ((LPNMHDR)lParam)->code) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFY_RANGE(idFirst, idLast) \
+ if(uMsg == WM_NOTIFY && ((LPNMHDR)lParam)->idFrom >= idFirst && ((LPNMHDR)lParam)->idFrom <= idLast) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECT_NOTIFY_RANGE_CODE(idFirst, idLast, cd) \
+ if(uMsg == WM_NOTIFY && cd == ((LPNMHDR)lParam)->code && ((LPNMHDR)lParam)->idFrom >= idFirst && ((LPNMHDR)lParam)->idFrom <= idLast) \
+ { \
+ bHandled = TRUE; \
+ lResult = ReflectNotifications(uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Reflected message handler macros for message maps (for ATL 3.0)
+
+#if (_ATL_VER < 0x0700)
+
+#define REFLECTED_COMMAND_HANDLER(id, code, func) \
+ if(uMsg == OCM_COMMAND && id == LOWORD(wParam) && code == HIWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = func(HIWORD(wParam), LOWORD(wParam), (HWND)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_COMMAND_ID_HANDLER(id, func) \
+ if(uMsg == OCM_COMMAND && id == LOWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = func(HIWORD(wParam), LOWORD(wParam), (HWND)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_COMMAND_CODE_HANDLER(code, func) \
+ if(uMsg == OCM_COMMAND && code == HIWORD(wParam)) \
+ { \
+ bHandled = TRUE; \
+ lResult = func(HIWORD(wParam), LOWORD(wParam), (HWND)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_COMMAND_RANGE_HANDLER(idFirst, idLast, func) \
+ if(uMsg == OCM_COMMAND && LOWORD(wParam) >= idFirst && LOWORD(wParam) <= idLast) \
+ { \
+ bHandled = TRUE; \
+ lResult = func(HIWORD(wParam), LOWORD(wParam), (HWND)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_COMMAND_RANGE_CODE_HANDLER(idFirst, idLast, code, func) \
+ if(uMsg == OCM_COMMAND && code == HIWORD(wParam) && LOWORD(wParam) >= idFirst && LOWORD(wParam) <= idLast) \
+ { \
+ bHandled = TRUE; \
+ lResult = func(HIWORD(wParam), LOWORD(wParam), (HWND)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_NOTIFY_HANDLER(id, cd, func) \
+ if(uMsg == OCM_NOTIFY && id == ((LPNMHDR)lParam)->idFrom && cd == ((LPNMHDR)lParam)->code) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((int)wParam, (LPNMHDR)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_NOTIFY_ID_HANDLER(id, func) \
+ if(uMsg == OCM_NOTIFY && id == ((LPNMHDR)lParam)->idFrom) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((int)wParam, (LPNMHDR)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_NOTIFY_CODE_HANDLER(cd, func) \
+ if(uMsg == OCM_NOTIFY && cd == ((LPNMHDR)lParam)->code) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((int)wParam, (LPNMHDR)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_NOTIFY_RANGE_HANDLER(idFirst, idLast, func) \
+ if(uMsg == OCM_NOTIFY && ((LPNMHDR)lParam)->idFrom >= idFirst && ((LPNMHDR)lParam)->idFrom <= idLast) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((int)wParam, (LPNMHDR)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#define REFLECTED_NOTIFY_RANGE_CODE_HANDLER(idFirst, idLast, cd, func) \
+ if(uMsg == OCM_NOTIFY && cd == ((LPNMHDR)lParam)->code && ((LPNMHDR)lParam)->idFrom >= idFirst && ((LPNMHDR)lParam)->idFrom <= idLast) \
+ { \
+ bHandled = TRUE; \
+ lResult = func((int)wParam, (LPNMHDR)lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+#endif // (_ATL_VER < 0x0700)
+
+
+///////////////////////////////////////////////////////////////////////////////
+// Dual argument helper classes (for ATL 3.0)
+
+#if (_ATL_VER < 0x0700)
+
+namespace ATL
+{
+
+class _U_RECT
+{
+public:
+ _U_RECT(LPRECT lpRect) : m_lpRect(lpRect)
+ { }
+ _U_RECT(RECT& rc) : m_lpRect(&rc)
+ { }
+ LPRECT m_lpRect;
+};
+
+class _U_MENUorID
+{
+public:
+ _U_MENUorID(HMENU hMenu) : m_hMenu(hMenu)
+ { }
+ _U_MENUorID(UINT nID) : m_hMenu((HMENU)LongToHandle(nID))
+ { }
+ HMENU m_hMenu;
+};
+
+class _U_STRINGorID
+{
+public:
+ _U_STRINGorID(LPCTSTR lpString) : m_lpstr(lpString)
+ { }
+ _U_STRINGorID(UINT nID) : m_lpstr(MAKEINTRESOURCE(nID))
+ { }
+ LPCTSTR m_lpstr;
+};
+
+}; // namespace ATL
+
+#endif // (_ATL_VER < 0x0700)
+
+
+namespace WTL
+{
+
+///////////////////////////////////////////////////////////////////////////////
+// Forward notifications support for message maps (for ATL 3.0)
+
+#if (_ATL_VER < 0x0700)
+
+// forward notifications support
+#define FORWARD_NOTIFICATIONS() \
+ { \
+ bHandled = TRUE; \
+ lResult = WTL::Atl3ForwardNotifications(m_hWnd, uMsg, wParam, lParam, bHandled); \
+ if(bHandled) \
+ return TRUE; \
+ }
+
+static LRESULT Atl3ForwardNotifications(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
+{
+ LRESULT lResult = 0;
+ switch(uMsg)
+ {
+ case WM_COMMAND:
+ case WM_NOTIFY:
+#ifndef _WIN32_WCE
+ case WM_PARENTNOTIFY:
+#endif // !_WIN32_WCE
+ case WM_DRAWITEM:
+ case WM_MEASUREITEM:
+ case WM_COMPAREITEM:
+ case WM_DELETEITEM:
+ case WM_VKEYTOITEM:
+ case WM_CHARTOITEM:
+ case WM_HSCROLL:
+ case WM_VSCROLL:
+ case WM_CTLCOLORBTN:
+ case WM_CTLCOLORDLG:
+ case WM_CTLCOLOREDIT:
+ case WM_CTLCOLORLISTBOX:
+ case WM_CTLCOLORMSGBOX:
+ case WM_CTLCOLORSCROLLBAR:
+ case WM_CTLCOLORSTATIC:
+ lResult = ::SendMessage(::GetParent(hWnd), uMsg, wParam, lParam);
+ break;
+ default:
+ bHandled = FALSE;
+ break;
+ }
+ return lResult;
+}
+
+#endif // (_ATL_VER < 0x0700)
+
+}; // namespace WTL
+
+#endif // __ATLWINX_H__
diff --git a/plugins/XSoundNotify/DebugLogger.hpp b/plugins/XSoundNotify/DebugLogger.hpp
new file mode 100644
index 0000000000..3b2c5a5fc1
--- /dev/null
+++ b/plugins/XSoundNotify/DebugLogger.hpp
@@ -0,0 +1,91 @@
+#ifndef _GRS_DEBUG_LOGGER_H
+#define _GRS_DEBUG_LOGGER_H
+
+#include <fstream>
+#include <sstream>
+#include <ctime>
+#include <memory>
+
+/**
+ * ������� ������, ������� ����� ������������ � ����� ����� ��� ������ ���������� ����������
+ * ��� ������ �������� ��������� ���� ������������ ������ GRS_DEBUG_LOG
+ * ��� ������ �������� ��������� � �������������� ���������� �����/������ ������ GRS_DEBUG_FORMAT_LOG
+ * ��� ����������� � ������� �������� ��� ������ : grs_debug.log
+ */
+
+namespace grs
+{
+
+class DebugLogger
+{
+public:
+ class Except : public std::exception
+ {
+ public:
+ virtual const char * what() const throw() { return "pizda rulu"; }
+ };
+
+ DebugLogger()
+ {
+ try
+ {
+ _strm.open("D:\\grs_debug.log", std::ios::app);
+ }
+ catch (...)
+ {
+ throw Except();
+ }
+ if (!_strm.is_open())
+ throw Except();
+
+ log("Logger started");
+ }
+
+ void log(const std::string & str, const char * fileStr = 0, int line = 0)
+ {
+ if (!_strm.is_open())
+ return ;
+
+ time_t t(time(0));
+ struct tm * timeinfo;
+ timeinfo = localtime (&t);
+ char timeStr[9];
+ strftime (timeStr, 9, "%H:%M:%S", timeinfo);
+ _strm << "[" << timeStr << "] ";
+ if (fileStr)
+ _strm << fileStr << ":" << line<<" ";
+ _strm <<"# "<< str << std::endl;
+ }
+
+ static DebugLogger * instance()
+ {
+ //static DebugLogger * logger = 0;
+ static std::auto_ptr<DebugLogger> loggerPtr;
+ if (loggerPtr.get() == 0)
+ loggerPtr.reset(new DebugLogger());
+ return loggerPtr.get();
+ }
+
+private:
+ std::ofstream _strm;
+};
+
+}
+
+#define GRS_DEBUG_FORMAT_LOG(data) {\
+ grs::DebugLogger * l = grs::DebugLogger::instance();\
+ if (l != 0) \
+ {\
+ std::stringstream strm;\
+ strm << data;\
+ l->log(strm.str(), __FILE__, __LINE__);\
+ }\
+ }
+
+#define GRS_DEBUG_LOG(data) {\
+ grs::DebugLogger * l = grs::DebugLogger::instance();\
+ if (l != 0)\
+ l->log(data, __FILE__, __LINE__);\
+ }
+
+#endif
diff --git a/plugins/XSoundNotify/EventProcessor.cpp b/plugins/XSoundNotify/EventProcessor.cpp
new file mode 100644
index 0000000000..6a97b6b125
--- /dev/null
+++ b/plugins/XSoundNotify/EventProcessor.cpp
@@ -0,0 +1,84 @@
+#include "EventProcessor.h"
+#include <m_database.h>
+#include "m_protocols.h"
+#include <memory>
+#include "DebugLogger.hpp"
+
+// static area
+
+static std::unique_ptr<XSN_EventProcessor> XSN_EventProcessorPtr;
+
+void XSN_EventProcessor::make(PLUGINLINK * pl)
+{
+ XSN_EventProcessorPtr.reset(new XSN_EventProcessor(pl));
+}
+
+XSN_EventProcessor & XSN_EventProcessor::instance()
+{
+ return *XSN_EventProcessorPtr;
+}
+
+// class methods
+
+XSN_EventProcessor::XSN_EventProcessor(PLUGINLINK * pl) : pluginLink(pl)
+{
+
+}
+
+void XSN_EventProcessor::process(WPARAM wParam, LPARAM lParam)
+{
+ if (!wParam || !lParam || !isReceiveMessage(lParam))
+ return ;
+ try
+ {
+ MessageBox(0, "Receive message", "INFO", MB_OK);
+ /*GRS_DEBUG_LOG("Receive message");
+ HANDLE contact = (HANDLE)wParam;
+ MessageBox(0, "Get protocol", "INFO", MB_OK);
+ GRS_DEBUG_LOG("Protocol : ");
+ xsn_string proto = getProtocol(wParam);
+ MessageBox(0, "Protocol is", proto.c_str(), MB_OK);
+ GRS_DEBUG_FORMAT_LOG(proto)
+ //xsn_string nick = getNick(wParam, proto.c_str());
+ XSN_Variant sound;
+ DBGetContactSettingTString(contact, proto.c_str(), "XSNPlugin_sound", &sound);
+ if (!sound.empty())
+ {
+ GRS_DEBUG_LOG("Sound for user exist");
+ GRS_DEBUG_FORMAT_LOG("Playing sound : " << sound.ptszVal << ", for user : " << getNick(wParam, proto.c_str()));
+ PlaySound(sound.toString().c_str(), nullptr, SND_FILENAME | SND_ASYNC);
+ }*/
+ }
+ catch (std::runtime_error &)
+ {
+ //MessageBoxA(0, e.what(), "Runtime error", MB_OK);
+ }
+ catch (...)
+ {
+ //MessageBoxA(0, "Unknown error occured", "Exception", MB_OK);
+ }
+}
+
+bool XSN_EventProcessor::isReceiveMessage(LPARAM event)
+{
+ DBEVENTINFO info ={ sizeof(info) };
+ CallService(MS_DB_EVENT_GET, event, (LPARAM)&info);
+
+ // TODO : rec msg flag : 16, send msg flag : 18 - WTF?
+ // return (info.eventType == EVENTTYPE_MESSAGE) && (info.flags & DBEF_READ);
+ // It's condition work well - magic?
+ return !(((info.eventType != EVENTTYPE_MESSAGE) && !(info.flags & DBEF_READ)) || (info.flags & DBEF_SENT));
+}
+
+xsn_string XSN_EventProcessor::getProtocol(WPARAM contact)
+{
+ char *pszProto = (char *)CallService(MS_PROTO_GETCONTACTBASEPROTO, contact, 0);
+ return xsn_string(pszProto);
+}
+
+xsn_string XSN_EventProcessor::getNick(WPARAM contact, LPCTSTR protocol)
+{
+ XSN_Variant nick;
+ DBGetContactSettingTString((HANDLE)contact, protocol, "Nick", &nick);
+ return nick.toString();
+}
diff --git a/plugins/XSoundNotify/EventProcessor.h b/plugins/XSoundNotify/EventProcessor.h
new file mode 100644
index 0000000000..6de14f8f98
--- /dev/null
+++ b/plugins/XSoundNotify/EventProcessor.h
@@ -0,0 +1,27 @@
+#ifndef __XSN_EVENT_PROCESSOR
+#define __XSN_EVENT_PROCESSOR
+
+#include <windows.h>
+#include "xsn_types.h"
+#include <newpluginapi.h>
+
+
+class XSN_EventProcessor
+{
+public:
+ static void make(PLUGINLINK * pl);
+ static XSN_EventProcessor & instance();
+
+ void process(WPARAM wParam, LPARAM lParam);
+
+protected:
+ XSN_EventProcessor(PLUGINLINK * pl);
+
+ bool isReceiveMessage(LPARAM event);
+ xsn_string getProtocol(WPARAM contact);
+ xsn_string getNick(WPARAM contact, LPCTSTR protocol);
+
+ PLUGINLINK * pluginLink;
+};
+
+#endif
diff --git a/plugins/XSoundNotify/README b/plugins/XSoundNotify/README
new file mode 100644
index 0000000000..d855b95460
--- /dev/null
+++ b/plugins/XSoundNotify/README
@@ -0,0 +1 @@
+Choose release mode (debug mode not configured) and configure Visual Studio environment for boost and WTL libraries include/libs paths
diff --git a/plugins/XSoundNotify/SettingsDialog.cpp b/plugins/XSoundNotify/SettingsDialog.cpp
new file mode 100644
index 0000000000..69b64d776f
--- /dev/null
+++ b/plugins/XSoundNotify/SettingsDialog.cpp
@@ -0,0 +1,124 @@
+#include "SettingsDialog.h"
+//#include "DebugLogger.hpp"
+
+template <typename T>
+T * GetComboBoxData(CComboBox & ctrl)
+{
+ return (T*)(ctrl.GetItemData(ctrl.GetCurSel()));
+}
+
+SettingsDialog::SettingsDialog(SoundNotifyDataStorage & storage) : _dataStorage(storage)
+{
+
+}
+
+BOOL SettingsDialog::PreTranslateMessage(MSG* pMsg)
+{
+ return ::IsDialogMessage(m_hWnd, pMsg);
+}
+
+LRESULT SettingsDialog::onInitDialog(UINT, WPARAM, LPARAM, BOOL&)
+{
+ _userCombo = GetDlgItem(IDC_COMBO_USERS);
+ _protoCombo = GetDlgItem(IDC_COMBO_PROTO);
+ _chooseButton = GetDlgItem(IDC_BUTTON_CHOOSE_SOUND);
+ _resetButton = GetDlgItem(IDC_BUTTON_RESET_SOUND);
+ _playButton = GetDlgItem(IDC_BUTTON_TEST_PLAY);
+ _soundLabel = GetDlgItem(IDC_LABEL_SOUND);
+
+ auto & protocols = _dataStorage.getData();
+ for (auto it = protocols.begin(), end = protocols.end(); it != end; ++it)
+ addProtocolItem(*it);
+
+ _userCombo.EnableWindow(0);
+ GetDlgItem(IDC_BUTTON_CHOOSE_SOUND).EnableWindow(0);
+ GetDlgItem(IDC_BUTTON_RESET_SOUND).EnableWindow(0);
+ GetDlgItem(IDC_BUTTON_TEST_PLAY).EnableWindow(0);
+ return TRUE;
+}
+
+LRESULT SettingsDialog::onOk(WORD, WORD wID, HWND, BOOL&)
+{
+ EndDialog(wID);
+ return 0;
+}
+
+LRESULT SettingsDialog::onCancel(WORD, WORD wID, HWND, BOOL&)
+{
+ EndDialog(wID);
+ return 0;
+}
+
+LRESULT SettingsDialog::onSelectProtocol(WORD, WORD, HWND, BOOL&)
+{
+ _userCombo.ResetContent();
+ auto data = GetComboBoxData<ProtocolTable::value_type>(_protoCombo);
+ for (auto it = data->second.begin(), end = data->second.end(); it != end; ++it)
+ {
+ int id = _userCombo.AddString(it->first.c_str());
+ _userCombo.SetItemData(id, (DWORD_PTR)(&(*it)));
+ }
+ _userCombo.EnableWindow(TRUE);
+ _playButton.EnableWindow(FALSE);
+ _resetButton.EnableWindow(FALSE);
+ _chooseButton.EnableWindow(FALSE);
+ _soundLabel.SetWindowText(TEXT(""));
+ return 0;
+}
+
+LRESULT SettingsDialog::onSelectUser(WORD, WORD, HWND, BOOL &)
+{
+ auto user = GetComboBoxData<UserDataTable::value_type>(_userCombo);
+ _chooseButton.EnableWindow(TRUE);
+
+ BOOL soundSelected = !user->second->soundPath().empty();
+ _resetButton.EnableWindow(soundSelected);
+ _playButton.EnableWindow(soundSelected);
+ setSoundLabelText(user->second->soundPath().c_str());
+
+ return 0;
+}
+
+LRESULT SettingsDialog::onChooseSound(WORD, WORD, HWND , BOOL&)
+{
+ CFileDialog fileDlg(1, 0, 0, OFN_FILEMUSTEXIST, TEXT("WAV files\0*.wav\0\0"));
+ if (fileDlg.DoModal() != IDOK)
+ return 0;
+
+ setSoundLabelText(fileDlg.m_szFileName);
+ auto user = GetComboBoxData<UserDataTable::value_type>(_userCombo);
+ user->second->setSound(xsn_string(fileDlg.m_szFileName));
+ _resetButton.EnableWindow(TRUE);
+ _playButton.EnableWindow(TRUE);
+ return 0;
+}
+
+LRESULT SettingsDialog::onResetSound(WORD, WORD wID, HWND , BOOL&)
+{
+ auto user = GetComboBoxData<UserDataTable::value_type>(_userCombo);
+ user->second->setSound(xsn_string());
+ _resetButton.EnableWindow(FALSE);
+ _playButton.EnableWindow(FALSE);
+ _soundLabel.SetWindowText(TEXT(""));
+ return 0;
+}
+
+LRESULT SettingsDialog::onTestPlay(WORD, WORD wID, HWND , BOOL&)
+{
+ auto user = GetComboBoxData<UserDataTable::value_type>(_userCombo);
+ PlaySound(user->second->soundPath().c_str(), nullptr, SND_FILENAME | SND_ASYNC);
+ return 0;
+}
+
+void SettingsDialog::setSoundLabelText(LPCTSTR text)
+{
+ _soundLabel.SetWindowText(PathFindFileName(text));
+}
+
+void SettingsDialog::addProtocolItem(ProtocolTable::value_type & value)
+{
+ wchar_t protocol[30];
+ mbstowcs(protocol, value.first.c_str(), 30);
+ int idx = _protoCombo.AddString(protocol);
+ _protoCombo.SetItemData(idx, (DWORD_PTR)(&value));
+}
diff --git a/plugins/XSoundNotify/SettingsDialog.h b/plugins/XSoundNotify/SettingsDialog.h
new file mode 100644
index 0000000000..c68503a6e8
--- /dev/null
+++ b/plugins/XSoundNotify/SettingsDialog.h
@@ -0,0 +1,60 @@
+#ifndef __XSN_SETTINGS_DIALOG_H
+#define __XSN_SETTINGS_DIALOG_H
+
+#include <atlbase.h>
+#include <atlwin.h>
+#include <atlapp.h>
+#include <atlctrls.h>
+#include <atldlgs.h>
+#include "resource.h"
+#include "SoundNotifyDataStorage.h"
+
+class SettingsDialog : public CDialogImpl<SettingsDialog>
+{
+private:
+ CComboBox _userCombo;
+ CComboBox _protoCombo;
+ CButton _chooseButton;
+ CButton _resetButton;
+ CButton _playButton;
+ CStatic _soundLabel;
+ SoundNotifyDataStorage & _dataStorage;
+
+public:
+ SettingsDialog(SoundNotifyDataStorage & dataStorage);
+ virtual ~SettingsDialog() {}
+ static BOOL DlgProcCluiOpts(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+public:
+ enum {IDD = IDD_DIALOG1};
+
+ BEGIN_MSG_MAP(SettingsDialog)
+ MESSAGE_HANDLER(WM_INITDIALOG, onInitDialog)
+ COMMAND_HANDLER(IDC_COMBO_PROTO, CBN_SELCHANGE, onSelectProtocol)
+ COMMAND_HANDLER(IDC_COMBO_USERS, CBN_SELCHANGE, onSelectUser)
+ COMMAND_ID_HANDLER(IDOK, onOk)
+ COMMAND_ID_HANDLER(IDCANCEL, onCancel)
+ COMMAND_ID_HANDLER(IDC_BUTTON_CHOOSE_SOUND, onChooseSound)
+ COMMAND_ID_HANDLER(IDC_BUTTON_RESET_SOUND, onResetSound)
+ COMMAND_ID_HANDLER(IDC_BUTTON_TEST_PLAY, onTestPlay)
+ END_MSG_MAP()
+
+ virtual BOOL PreTranslateMessage(MSG* pMsg);
+
+protected:
+ LRESULT onInitDialog(UINT, WPARAM, LPARAM, BOOL&);
+
+ LRESULT onOk(WORD, WORD, HWND, BOOL&);
+ LRESULT onCancel(WORD, WORD, HWND, BOOL &);
+ LRESULT onSelectProtocol(WORD, WORD, HWND, BOOL&);
+ LRESULT onSelectUser(WORD, WORD, HWND, BOOL &);
+ LRESULT onChooseSound(WORD, WORD, HWND , BOOL&);
+ LRESULT onResetSound(WORD, WORD, HWND , BOOL&);
+ LRESULT onTestPlay(WORD, WORD, HWND , BOOL&);
+
+ void addProtocolItem(ProtocolTable::value_type & value);
+
+ void setSoundLabelText(LPCTSTR text);
+};
+
+#endif
diff --git a/plugins/XSoundNotify/SoundNotifyData.cpp b/plugins/XSoundNotify/SoundNotifyData.cpp
new file mode 100644
index 0000000000..1876db6ba0
--- /dev/null
+++ b/plugins/XSoundNotify/SoundNotifyData.cpp
@@ -0,0 +1,37 @@
+#include "SoundNotifyData.h"
+
+SoundNotifyData::SoundNotifyData() : _contact(0), _soundChanged(false)
+{
+
+}
+
+SoundNotifyData::SoundNotifyData(HANDLE contact, const ModuleString & module, const xsn_string & sound) :
+ _contact(contact), _soundPath(sound), _soundChanged(false)
+{
+}
+
+void SoundNotifyData::setSound(const xsn_string & sound)
+{
+ _soundChanged = true;
+ _soundPath = sound;
+}
+
+HANDLE SoundNotifyData::contact() const
+{
+ return _contact;
+}
+
+const xsn_string & SoundNotifyData::soundPath() const
+{
+ return _soundPath;
+}
+
+const ModuleString & SoundNotifyData::module() const
+{
+ return _module;
+}
+
+bool SoundNotifyData::isSoundChanged() const
+{
+ return _soundChanged;
+}
diff --git a/plugins/XSoundNotify/SoundNotifyData.h b/plugins/XSoundNotify/SoundNotifyData.h
new file mode 100644
index 0000000000..18cb4844a4
--- /dev/null
+++ b/plugins/XSoundNotify/SoundNotifyData.h
@@ -0,0 +1,33 @@
+#ifndef __XSN_DATA_H
+#define __XSN_DATA_H
+
+#include <unordered_map>
+#include "xsn_types.h"
+#include <windows.h>
+
+class SoundNotifyData
+{
+public:
+ SoundNotifyData();
+ SoundNotifyData(HANDLE contact, const ModuleString & module, const xsn_string & sound);
+
+ void setSound(const xsn_string & sound);
+
+ HANDLE contact() const;
+ const xsn_string & soundPath() const;
+ const ModuleString & module() const;
+ bool isSoundChanged() const;
+
+private:
+ HANDLE _contact;
+ ModuleString _module;
+ xsn_string _soundPath;
+ bool _soundChanged;
+};
+typedef std::shared_ptr<SoundNotifyData> SoundNotifyDataPtr;
+
+typedef std::unordered_map<xsn_string, SoundNotifyDataPtr> UserDataTable;
+typedef std::unordered_map<ProtocolString, UserDataTable> ProtocolTable;
+typedef std::unordered_map<ModuleString, ProtocolString> ModuleConvertTable;
+
+#endif
diff --git a/plugins/XSoundNotify/SoundNotifyDataStorage.cpp b/plugins/XSoundNotify/SoundNotifyDataStorage.cpp
new file mode 100644
index 0000000000..bd1b90df52
--- /dev/null
+++ b/plugins/XSoundNotify/SoundNotifyDataStorage.cpp
@@ -0,0 +1,74 @@
+#include "SoundNotifyDataStorage.h"
+#include <m_database.h>
+#include <m_protocols.h>
+#include "xsn_utils.h"
+//#include "DebugLogger.hpp"
+
+SoundNotifyDataStorage::SoundNotifyDataStorage(PLUGINLINK * pl) : pluginLink(pl)
+{
+
+}
+
+void SoundNotifyDataStorage::init()
+{
+ initModuleConvertTable(_moduleTable);
+ registerProtocols();
+
+ HANDLE contact = (HANDLE)CallService(MS_DB_CONTACT_FINDFIRST,0,0);
+ for(; contact; contact = (HANDLE)CallService(MS_DB_CONTACT_FINDNEXT,(WPARAM)contact,0))
+ {
+ try
+ {
+ addContact(contact);
+ }
+ catch (...)
+ {
+ // log
+ }
+ }
+}
+
+void SoundNotifyDataStorage::commit()
+{
+ for (auto it = _protocolTable.begin(), end = _protocolTable.end(); it != end; ++it)
+ for (auto user = it->second.begin(), userEnd = it->second.end(); user != userEnd; ++user)
+ if (user->second->isSoundChanged())
+ {
+ if (user->second->soundPath().empty())
+ DBDeleteContactSetting(user->second->contact(), XSN_ModuleInfo::name(), XSN_ModuleInfo::soundSetting());
+ else
+ DBWriteContactSettingTString(user->second->contact(), XSN_ModuleInfo::name(), XSN_ModuleInfo::soundSetting(), user->second->soundPath().c_str());
+ }
+}
+
+void SoundNotifyDataStorage::addContact(HANDLE contact)
+{
+ ModuleString module = getContactModule(contact);
+ ProtocolString proto = _moduleTable[module];
+ xsn_string user = getContactId(contact, module, proto);
+ if (user.empty())
+ return ;
+
+ XSN_Variant sound;
+ DBGetContactSettingTString(contact, XSN_ModuleInfo::name(), XSN_ModuleInfo::soundSetting(), &sound);
+ _protocolTable[proto][user] = SoundNotifyDataPtr(new SoundNotifyData(contact, module, sound.toString()));
+}
+
+xsn_string SoundNotifyDataStorage::getContactId(HANDLE contact, const ModuleString & module, const ProtocolString & proto)
+{
+ auto it = _registeredProtocols.find(proto);
+ if (it == _registeredProtocols.end())
+ return xsn_string();
+ return it->second(contact, module);
+}
+
+ProtocolTable & SoundNotifyDataStorage::getData()
+{
+ return _protocolTable;
+}
+
+void SoundNotifyDataStorage::registerProtocols()
+{
+ _registeredProtocols["ICQ"] = &getIcqContactId;
+ _registeredProtocols["JABBER"] = &getJabberContactId;
+}
diff --git a/plugins/XSoundNotify/SoundNotifyDataStorage.h b/plugins/XSoundNotify/SoundNotifyDataStorage.h
new file mode 100644
index 0000000000..7dbf03c494
--- /dev/null
+++ b/plugins/XSoundNotify/SoundNotifyDataStorage.h
@@ -0,0 +1,34 @@
+#ifndef _XSN_DATA_STORAGE
+#define _XSN_DATA_STORAGE
+
+#include "SoundNotifyData.h"
+#include <newpluginapi.h>
+#include <boost/function.hpp>
+
+class SoundNotifyDataStorage
+{
+public:
+ SoundNotifyDataStorage(PLUGINLINK * pl);
+
+ void init();
+ void commit();
+
+ ProtocolTable & getData();
+
+protected:
+ void addContact(HANDLE contact);
+ xsn_string getContactId(HANDLE contact, const ModuleString & module, const ProtocolString & proto);
+ void registerProtocols();
+
+private:
+ PLUGINLINK * pluginLink;
+
+ ProtocolTable _protocolTable;
+ ModuleConvertTable _moduleTable;
+
+ typedef boost::function<xsn_string (HANDLE contact, const ModuleString & module)> getContactIdFunc;
+ typedef std::unordered_map<ProtocolString, getContactIdFunc> RegisteredProtocols;
+ RegisteredProtocols _registeredProtocols;
+};
+
+#endif
diff --git a/plugins/XSoundNotify/XSound Notify Miranda Plugin.sln b/plugins/XSoundNotify/XSound Notify Miranda Plugin.sln
new file mode 100644
index 0000000000..5d60e3c4be
--- /dev/null
+++ b/plugins/XSoundNotify/XSound Notify Miranda Plugin.sln
@@ -0,0 +1,20 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "XSoundNotify", "testplug.vcxproj", "{2339A0F0-9A42-C426-1D80-3FAFB55AFAF4}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Win32 = Debug|Win32
+ Release|Win32 = Release|Win32
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {2339A0F0-9A42-C426-1D80-3FAFB55AFAF4}.Debug|Win32.ActiveCfg = Debug|Win32
+ {2339A0F0-9A42-C426-1D80-3FAFB55AFAF4}.Debug|Win32.Build.0 = Debug|Win32
+ {2339A0F0-9A42-C426-1D80-3FAFB55AFAF4}.Release|Win32.ActiveCfg = Release|Win32
+ {2339A0F0-9A42-C426-1D80-3FAFB55AFAF4}.Release|Win32.Build.0 = Release|Win32
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/plugins/XSoundNotify/XSoundNotify.rc b/plugins/XSoundNotify/XSoundNotify.rc
new file mode 100644
index 0000000000..ab42834a08
--- /dev/null
+++ b/plugins/XSoundNotify/XSoundNotify.rc
Binary files differ
diff --git a/plugins/XSoundNotify/resource.h b/plugins/XSoundNotify/resource.h
new file mode 100644
index 0000000000..fcd39e7cf3
--- /dev/null
+++ b/plugins/XSoundNotify/resource.h
Binary files differ
diff --git a/plugins/XSoundNotify/testplug.vcxproj b/plugins/XSoundNotify/testplug.vcxproj
new file mode 100644
index 0000000000..ebd0a0009f
--- /dev/null
+++ b/plugins/XSoundNotify/testplug.vcxproj
@@ -0,0 +1,167 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug|Win32">
+ <Configuration>Debug</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release|Win32">
+ <Configuration>Release</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <SccProjectName />
+ <SccLocalPath />
+ <ProjectName>XSoundNotify</ProjectName>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.Cpp.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <OutDir>.\Release\</OutDir>
+ <IntDir>.\Release\</IntDir>
+ <LinkIncremental>false</LinkIncremental>
+ <IncludePath>E:\Programming\libs\WTL\Include;$(IncludePath)</IncludePath>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <OutDir>.\Debug\</OutDir>
+ <IntDir>.\Debug\</IntDir>
+ <LinkIncremental>true</LinkIncremental>
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <StringPooling>true</StringPooling>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <Optimization>MaxSpeed</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <AdditionalIncludeDirectories>e:\Programming\libs\boost_1_46_1\;../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>_CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;TESTPLUG_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AssemblerListingLocation>.\Release\</AssemblerListingLocation>
+ <PrecompiledHeaderOutputFile>.\Release\testplug.pch</PrecompiledHeaderOutputFile>
+ <ObjectFileName>.\Release\</ObjectFileName>
+ <ProgramDataBaseFileName>.\Release\</ProgramDataBaseFileName>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Release\testplug.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>.\Release\testplug.bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <SubSystem>Console</SubSystem>
+ <OutputFile>release/xsoundnotify.dll</OutputFile>
+ <ImportLibrary>.\Release\testplug.lib</ImportLibrary>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalLibraryDirectories>e:\Programming\libs\wxWidgets-2.9.3\lib\vc_lib\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+ <ClCompile>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <InlineFunctionExpansion>Default</InlineFunctionExpansion>
+ <FunctionLevelLinking>false</FunctionLevelLinking>
+ <Optimization>Disabled</Optimization>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <WarningLevel>Level3</WarningLevel>
+ <MinimalRebuild>true</MinimalRebuild>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ <AdditionalIncludeDirectories>e:\Programming\libs\wxWidgets-2.9.3\include\msvc\;e:\Programming\libs\wxWidgets-2.9.3\include\;../../include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;XSOUNDNOTIFY_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AssemblerListingLocation>.\Debug\</AssemblerListingLocation>
+ <PrecompiledHeaderOutputFile>.\Debug\testplug.pch</PrecompiledHeaderOutputFile>
+ <ObjectFileName>.\Debug\</ObjectFileName>
+ <ProgramDataBaseFileName>.\Debug\</ProgramDataBaseFileName>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ </ClCompile>
+ <Midl>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <TypeLibraryName>.\Debug\testplug.tlb</TypeLibraryName>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ </Midl>
+ <ResourceCompile>
+ <Culture>0x0809</Culture>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>.\Debug\testplug.bsc</OutputFile>
+ </Bscmake>
+ <Link>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <LinkDLL>true</LinkDLL>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <SubSystem>Console</SubSystem>
+ <OutputFile>.\Debug\xsoundnotify.dll</OutputFile>
+ <ImportLibrary>.\Debug\xsoundnotify.lib</ImportLibrary>
+ <AdditionalDependencies>wxmsw29u_adv.lib;wxmsw29u_core.lib;wxbase29u.lib;wxtiff.lib;wxjpeg.lib;wxpng.lib;wxzlib.lib;wxregexu.lib;wxexpat.lib;odbc32.lib;odbccp32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <IgnoreSpecificDefaultLibraries>
+ </IgnoreSpecificDefaultLibraries>
+ <AdditionalLibraryDirectories>e:\Programming\libs\wxWidgets-2.9.3\lib\vc_lib\;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="SettingsDialog.cpp" />
+ <ClCompile Include="SoundNotifyData.cpp" />
+ <ClCompile Include="SoundNotifyDataStorage.cpp" />
+ <ClCompile Include="xsn_main.cpp" />
+ <ClCompile Include="xsn_types.cpp" />
+ <ClCompile Include="xsn_utils.cpp" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="DebugLogger.hpp" />
+ <ClInclude Include="SettingsDialog.h" />
+ <ClInclude Include="resource.h" />
+ <ClInclude Include="SoundNotifyData.h" />
+ <ClInclude Include="SoundNotifyDataStorage.h" />
+ <ClInclude Include="xsn_types.h" />
+ <ClInclude Include="xsn_utils.h" />
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="XSoundNotify.rc" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+ <ProjectExtensions>
+ <VisualStudio>
+ <UserProperties RESOURCE_FILE="XSoundNotify.rc" />
+ </VisualStudio>
+ </ProjectExtensions>
+</Project> \ No newline at end of file
diff --git a/plugins/XSoundNotify/xsn_main.cpp b/plugins/XSoundNotify/xsn_main.cpp
new file mode 100644
index 0000000000..49d45e3a57
--- /dev/null
+++ b/plugins/XSoundNotify/xsn_main.cpp
@@ -0,0 +1,122 @@
+/*
+Miranda plugin template, originally by Richard Hughes
+http://miranda-icq.sourceforge.net/
+
+This file is placed in the public domain. Anybody is free to use or
+modify it as they wish with no restriction.
+There is no warranty.
+*/
+
+#include "SettingsDialog.h"
+
+#include <windows.h>
+#include <newpluginapi.h>
+#include <m_langpack.h>
+#include <m_clist.h>
+#include <m_skin.h>
+#include <m_database.h>
+#include <m_protocols.h>
+#include "xsn_utils.h"
+//#include "DebugLogger.hpp"
+
+HINSTANCE hInst;
+PLUGINLINK *pluginLink;
+HANDLE AddEventHook;
+
+PLUGININFOEX pluginInfo = {
+ sizeof(PLUGININFOEX), // ������ ��������
+ "XSoundNotify", // �������� ��� �������
+ PLUGIN_MAKE_VERSION(1,0,0,0), // ������ �������
+ "Provides extended options for sound notifications", // �������� �������
+ "Roman Torsten", // �����
+ "rs_torsten-public@yahoo.com", // ������ ������
+ "� 2011 Copyright", // ��������
+ "https://plus.google.com/117081718640940130539", // ������ ����� ������������ �������
+ 0,
+ 0,
+ {0x8b86253, 0xec6e, 0x4d09, { 0xb7, 0xa9, 0x64, 0xac, 0xdf, 0x6, 0x27, 0xb8 }} //{08B86253-EC6E-4d09-B7A9-64ACDF0627B8}
+};
+
+extern "C" BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
+{
+ hInst = hinstDLL;
+ return TRUE;
+}
+
+static int PluginMenuCommand(WPARAM wParam,LPARAM lParam)
+{
+ try
+ {
+ SoundNotifyDataStorage storage(pluginLink);
+ storage.init();
+ SettingsDialog dlg(storage);
+ if (dlg.DoModal() == IDOK)
+ storage.commit();
+ }
+ catch (...)
+ {
+ MessageBox(0, TEXT("Unknown error occured while configuring"), TEXT("XSoundNotify Error"), MB_OK | MB_ICONERROR);
+ }
+
+ return 0;
+}
+
+extern "C" __declspec(dllexport) PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
+{
+ return &pluginInfo;
+}
+
+static const MUUID interfaces[] = {MIID_TESTPLUGIN, MIID_LAST};
+extern "C" __declspec(dllexport) const MUUID* MirandaPluginInterfaces(void)
+{
+ return interfaces;
+}
+
+INT processEvent(WPARAM wParam, LPARAM lParam)
+{
+ try
+ {
+ if (!isReceiveMessage(lParam))
+ return 0;
+
+ xsn_string sound = getContactSound((HANDLE)wParam);
+ if (!sound.empty())
+ PlaySound(sound.c_str(), nullptr, SND_ASYNC | SND_FILENAME);
+ }
+ catch (std::exception & )
+ {
+ // log
+ }
+ catch (...)
+ {
+ // log
+ }
+
+ return 0;
+}
+
+extern "C" int __declspec(dllexport) Load(PLUGINLINK *link)
+{
+ CLISTMENUITEM mi;
+
+ pluginLink=link;
+ CreateServiceFunction("XSoundNotify/MenuCommand", PluginMenuCommand);
+ ZeroMemory(&mi,sizeof(mi));
+ mi.cbSize=sizeof(mi);
+ mi.position=-0x7FFFFFFF;
+ mi.flags=0;
+ mi.hIcon=LoadSkinnedIcon(SKINICON_OTHER_MIRANDA);
+ mi.pszName=LPGEN("&XSoundNotify Plugin");
+ mi.pszService="XSoundNotify/MenuCommand";
+ CallService(MS_CLIST_ADDMAINMENUITEM,0,(LPARAM)&mi);
+ AddEventHook = HookEvent(ME_DB_EVENT_ADDED, processEvent);
+
+ return 0;
+}
+
+extern "C" int __declspec(dllexport) Unload(void)
+{
+ UnhookEvent(AddEventHook);
+ return 0;
+}
+
diff --git a/plugins/XSoundNotify/xsn_types.cpp b/plugins/XSoundNotify/xsn_types.cpp
new file mode 100644
index 0000000000..da0cc5b3f9
--- /dev/null
+++ b/plugins/XSoundNotify/xsn_types.cpp
@@ -0,0 +1,32 @@
+#include "xsn_types.h"
+
+XSN_Variant::XSN_Variant()
+{
+ ptszVal = nullptr;
+}
+
+XSN_Variant::~XSN_Variant()
+{
+ if (ptszVal)
+ DBFreeVariant(this);
+}
+
+xsn_string XSN_Variant::toString() const
+{
+ return ptszVal == nullptr ? xsn_string() : xsn_string(ptszVal);
+}
+
+bool XSN_Variant::empty() const
+{
+ return ptszVal == nullptr;
+}
+
+const char * XSN_ModuleInfo::name()
+{
+ return "XSoundNotify";
+}
+
+const char * XSN_ModuleInfo::soundSetting()
+{
+ return "XSNPlugin_sound";
+}
diff --git a/plugins/XSoundNotify/xsn_types.h b/plugins/XSoundNotify/xsn_types.h
new file mode 100644
index 0000000000..43f4434fea
--- /dev/null
+++ b/plugins/XSoundNotify/xsn_types.h
@@ -0,0 +1,33 @@
+#ifndef __XSN_TYPES
+#define __XSN_TYPES
+
+#include <string>
+#include <windows.h>
+#include <newpluginapi.h>
+#include <m_database.h>
+
+#ifndef UNICODE
+ typedef std::string xsn_string;
+#else
+ typedef std::wstring xsn_string;
+#endif
+
+typedef std::string ModuleString;
+typedef std::string ProtocolString;
+
+struct XSN_Variant : DBVARIANT
+{
+ XSN_Variant();
+ ~XSN_Variant();
+
+ xsn_string toString() const;
+ bool empty() const;
+};
+
+struct XSN_ModuleInfo
+{
+ static const char * name();
+ static const char * soundSetting();
+};
+
+#endif
diff --git a/plugins/XSoundNotify/xsn_utils.cpp b/plugins/XSoundNotify/xsn_utils.cpp
new file mode 100644
index 0000000000..d597776e8d
--- /dev/null
+++ b/plugins/XSoundNotify/xsn_utils.cpp
@@ -0,0 +1,60 @@
+#include "xsn_utils.h"
+#include <m_protocols.h>
+#include <boost/lexical_cast.hpp>
+
+void initModuleConvertTable(ModuleConvertTable & table)
+{
+ int number = 0;
+ // may be need to free PROTOACCOUNT, but did't found information about it
+ PROTOACCOUNT ** accounts;
+ ProtoEnumAccounts(&number, &accounts);
+ for (int i = 0; i < number; ++i)
+ table[ModuleString(accounts[i]->szModuleName)] = ProtocolString(accounts[i]->szProtoName);
+}
+
+bool isReceiveMessage(LPARAM event)
+{
+ DBEVENTINFO info = { sizeof(info) };
+ CallService(MS_DB_EVENT_GET, event, (LPARAM)&info);
+ // i don't understand why it works and how it works, but it works correctly - practice way (������� ����)
+ // so, i think correct condition would be : eventType == EVENTTYPE_MESSAGE && info.flags & DBEF_READ, but it really isn't
+ return !(((info.eventType != EVENTTYPE_MESSAGE) && !(info.flags & DBEF_READ)) || (info.flags & DBEF_SENT));
+}
+
+xsn_string getContactSound(HANDLE contact)
+{
+ XSN_Variant sound;
+ DBGetContactSettingTString(contact, XSN_ModuleInfo::name(), XSN_ModuleInfo::soundSetting(), &sound);
+ return sound.toString();
+}
+
+ModuleString getContactModule(HANDLE contact)
+{
+ char * proto = (char *)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)contact, 0);
+ if (proto == nullptr)
+ throw std::runtime_error("MS_PROTO_GETCONTACTBASEPROTO failed");
+ return ModuleString(proto);
+}
+
+xsn_string getIcqContactId(HANDLE contact, const ModuleString & module)
+{
+ XSN_Variant nick;
+ DBGetContactSettingTString(contact, module.c_str(), "CustomNick", &nick);
+ if (nick.empty())
+ DBGetContactSettingTString(contact, module.c_str(), "Nick", &nick);
+ DWORD uin = DBGetContactSettingDword(contact, module.c_str(), "UIN", 0);
+ xsn_string uinStr = boost::lexical_cast<xsn_string>(uin);
+ if (nick.empty())
+ return uinStr;
+ return nick.toString() + TEXT(" (") + uinStr + TEXT(")");
+}
+
+xsn_string getJabberContactId(HANDLE contact, const ModuleString & module)
+{
+ XSN_Variant jid, nick;
+ DBGetContactSettingTString(contact, module.c_str(), "jid", &jid);
+ DBGetContactSettingTString(contact, "CList", "MyHandle", &nick);
+ if (nick.empty())
+ return jid.toString();
+ return nick.toString() + TEXT(" (") + jid.toString() + TEXT(")");
+}
diff --git a/plugins/XSoundNotify/xsn_utils.h b/plugins/XSoundNotify/xsn_utils.h
new file mode 100644
index 0000000000..66bdef2526
--- /dev/null
+++ b/plugins/XSoundNotify/xsn_utils.h
@@ -0,0 +1,18 @@
+#ifndef _XSN_UTILS_H
+#define _XSN_UTILS_H
+
+#include "xsn_types.h"
+#include "SoundNotifyData.h"
+
+void initModuleConvertTable(ModuleConvertTable & table);
+
+bool isReceiveMessage(LPARAM event);
+
+xsn_string getContactSound(HANDLE contact);
+ModuleString getContactModule(HANDLE contact);
+
+xsn_string getIcqContactId(HANDLE contact, const ModuleString & module);
+xsn_string getJabberContactId(HANDLE contact, const ModuleString & module);
+
+
+#endif
diff --git a/protocols/Tlen/codec/gsm.h b/protocols/Tlen/codec/gsm.h
new file mode 100644
index 0000000000..fba1bcb1ac
--- /dev/null
+++ b/protocols/Tlen/codec/gsm.h
@@ -0,0 +1,65 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+This program is based on GSM 06.10 source code developed by
+Jutta Degener and Carsten Bormann,
+Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
+Technische Universitaet Berlin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include <windows.h>
+
+#define P_MAX 8 /* order p of LPC analysis, typically 8..14 */
+
+typedef struct {
+ int LARpp[2][8]; /* LAR coefficients for previous and current frame */
+ int j; /* current frame index in LARpp[j][] */
+ int qLARs[8]; /* quantized LARs for current frame */
+ int u[8]; /* used by short term analysis filter */
+ int v[9]; /* used by short term synthesis filter */
+ int subframe; /* subframe index (0..3)*/
+ short dp0[ 280 ]; /* previous short-term filter output/prediction, used by long term analysis*/
+ int e[160]; /* errors (residuals) */
+ int nrp; /* long term synthesis */
+ int Nc[4], bc[4]; /* long-term lag and gain for current frame */
+ int Mc[4]; /* RPE grid index (0..3) */
+ int xMaxc[4]; /* RPE maximum error quantized and encoded (mantissa + exp) */
+ int xMc[52]; /* quantized residuals (errors) 4 * 13 */
+
+ int z1; /* preprocessing.c, Offset_com. */
+ int z2; /* Offset_com. */
+ int mp; /* Preemphasis */
+ int msr; /* decoder.c, Postprocessing */
+
+ unsigned char gsmFrame[33];
+}gsm_state;
+
+extern gsm_state * gsm_create() ;
+extern void gsm_release(gsm_state *ptr);
+extern void gsm_encode(gsm_state *state, short *in);
+extern void gsm_decode(gsm_state *state, short *out);
+
+extern void gsm_preprocessing( gsm_state *state, short *in, short *out);
+extern void shortTermAnalysis(gsm_state *state, short *in);
+extern void longTermAnalysis(gsm_state *state, short *in);
+extern void encodeRPE(gsm_state *state);
+extern void decodeRPE(gsm_state *state);
+extern void longTermSynthesis(gsm_state *state);
+extern void shortTermSynthesis(gsm_state *state, short *in, short *out);
+extern void gsm_postprocessing( gsm_state *state, short *in, short *out);
diff --git a/protocols/Tlen/codec/gsm_codec.c b/protocols/Tlen/codec/gsm_codec.c
new file mode 100644
index 0000000000..1d0a08a41e
--- /dev/null
+++ b/protocols/Tlen/codec/gsm_codec.c
@@ -0,0 +1,283 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+This program is based on GSM 06.10 source code developed by
+Jutta Degener and Carsten Bormann,
+Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
+Technische Universitaet Berlin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "gsm.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#define GSM_MAGIC 0xD
+
+gsm_state * gsm_create()
+{
+ gsm_state * state = (gsm_state *)malloc(sizeof(gsm_state));
+ memset(state, 0, sizeof(gsm_state));
+ state->nrp = 40;
+ return state;
+}
+
+void gsm_release(gsm_state *ptr)
+{
+ free(ptr);
+}
+
+void gsm_encode(gsm_state *state, short *in)
+{ int i, j;
+ unsigned char *c = state->gsmFrame;
+ short temp_in[160];
+
+ gsm_preprocessing(state, in, temp_in);
+ shortTermAnalysis(state, temp_in);
+ for (i = 0; i < 4; i++) {
+ state->subframe = i;
+ longTermAnalysis(state, temp_in + 40 * i);
+ encodeRPE(state);
+ for (j = 0; j < 40; j++) {
+ int ii = (int) state->dp0[120 + i * 40 + j] + state->e[i * 40 + j];
+ if (ii<-32768) ii = -32768;
+ else if (ii>32767) ii=32767;
+ state->dp0[120 + i * 40 + j] = ii;
+ }
+ }
+ memcpy(state->dp0, state->dp0 + 160, 120 * sizeof(short));
+ state->j ^= 1;
+ *c++ = ((GSM_MAGIC & 0xF) << 4)
+ | ((state->qLARs[0] >> 2) & 0xF);
+ *c++ = ((state->qLARs[0] & 0x3) << 6)
+ | (state->qLARs[1] & 0x3F);
+ *c++ = ((state->qLARs[2] & 0x1F) << 3)
+ | ((state->qLARs[3] >> 2) & 0x7);
+ *c++ = ((state->qLARs[3] & 0x3) << 6)
+ | ((state->qLARs[4] & 0xF) << 2)
+ | ((state->qLARs[5] >> 2) & 0x3);
+ *c++ = ((state->qLARs[5] & 0x3) << 6)
+ | ((state->qLARs[6] & 0x7) << 3)
+ | (state->qLARs[7] & 0x7);
+ *c++ = ((state->Nc[0] & 0x7F) << 1)
+ | ((state->bc[0] >> 1) & 0x1);
+ *c++ = ((state->bc[0] & 0x1) << 7)
+ | ((state->Mc[0] & 0x3) << 5)
+ | ((state->xMaxc[0] >> 1) & 0x1F);
+ *c++ = ((state->xMaxc[0] & 0x1) << 7)
+ | ((state->xMc[0] & 0x7) << 4)
+ | ((state->xMc[1] & 0x7) << 1)
+ | ((state->xMc[2] >> 2) & 0x1);
+ *c++ = ((state->xMc[2] & 0x3) << 6)
+ | ((state->xMc[3] & 0x7) << 3)
+ | (state->xMc[4] & 0x7);
+ *c++ = ((state->xMc[5] & 0x7) << 5)
+ | ((state->xMc[6] & 0x7) << 2)
+ | ((state->xMc[7] >> 1) & 0x3);
+ *c++ = ((state->xMc[7] & 0x1) << 7)
+ | ((state->xMc[8] & 0x7) << 4)
+ | ((state->xMc[9] & 0x7) << 1)
+ | ((state->xMc[10] >> 2) & 0x1);
+ *c++ = ((state->xMc[10] & 0x3) << 6)
+ | ((state->xMc[11] & 0x7) << 3)
+ | (state->xMc[12] & 0x7);
+ *c++ = ((state->Nc[1] & 0x7F) << 1)
+ | ((state->bc[1] >> 1) & 0x1);
+ *c++ = ((state->bc[1] & 0x1) << 7)
+ | ((state->Mc[1] & 0x3) << 5)
+ | ((state->xMaxc[1] >> 1) & 0x1F);
+ *c++ = ((state->xMaxc[1] & 0x1) << 7)
+ | ((state->xMc[13] & 0x7) << 4)
+ | ((state->xMc[14] & 0x7) << 1)
+ | ((state->xMc[15] >> 2) & 0x1);
+ *c++ = ((state->xMc[15] & 0x3) << 6)
+ | ((state->xMc[16] & 0x7) << 3)
+ | (state->xMc[17] & 0x7);
+ *c++ = ((state->xMc[18] & 0x7) << 5)
+ | ((state->xMc[19] & 0x7) << 2)
+ | ((state->xMc[20] >> 1) & 0x3);
+ *c++ = ((state->xMc[20] & 0x1) << 7)
+ | ((state->xMc[21] & 0x7) << 4)
+ | ((state->xMc[22] & 0x7) << 1)
+ | ((state->xMc[23] >> 2) & 0x1);
+ *c++ = ((state->xMc[23] & 0x3) << 6)
+ | ((state->xMc[24] & 0x7) << 3)
+ | (state->xMc[25] & 0x7);
+ *c++ = ((state->Nc[2] & 0x7F) << 1)
+ | ((state->bc[2] >> 1) & 0x1);
+ *c++ = ((state->bc[2] & 0x1) << 7)
+ | ((state->Mc[2] & 0x3) << 5)
+ | ((state->xMaxc[2] >> 1) & 0x1F);
+ *c++ = ((state->xMaxc[2] & 0x1) << 7)
+ | ((state->xMc[26] & 0x7) << 4)
+ | ((state->xMc[27] & 0x7) << 1)
+ | ((state->xMc[28] >> 2) & 0x1);
+ *c++ = ((state->xMc[28] & 0x3) << 6)
+ | ((state->xMc[29] & 0x7) << 3)
+ | (state->xMc[30] & 0x7);
+ *c++ = ((state->xMc[31] & 0x7) << 5)
+ | ((state->xMc[32] & 0x7) << 2)
+ | ((state->xMc[33] >> 1) & 0x3);
+ *c++ = ((state->xMc[33] & 0x1) << 7)
+ | ((state->xMc[34] & 0x7) << 4)
+ | ((state->xMc[35] & 0x7) << 1)
+ | ((state->xMc[36] >> 2) & 0x1);
+ *c++ = ((state->xMc[36] & 0x3) << 6)
+ | ((state->xMc[37] & 0x7) << 3)
+ | (state->xMc[38] & 0x7);
+ *c++ = ((state->Nc[3] & 0x7F) << 1)
+ | ((state->bc[3] >> 1) & 0x1);
+ *c++ = ((state->bc[3] & 0x1) << 7)
+ | ((state->Mc[3] & 0x3) << 5)
+ | ((state->xMaxc[3] >> 1) & 0x1F);
+ *c++ = ((state->xMaxc[3] & 0x1) << 7)
+ | ((state->xMc[39] & 0x7) << 4)
+ | ((state->xMc[40] & 0x7) << 1)
+ | ((state->xMc[41] >> 2) & 0x1);
+ *c++ = ((state->xMc[41] & 0x3) << 6)
+ | ((state->xMc[42] & 0x7) << 3)
+ | (state->xMc[43] & 0x7);
+ *c++ = ((state->xMc[44] & 0x7) << 5)
+ | ((state->xMc[45] & 0x7) << 2)
+ | ((state->xMc[46] >> 1) & 0x3);
+ *c++ = ((state->xMc[46] & 0x1) << 7)
+ | ((state->xMc[47] & 0x7) << 4)
+ | ((state->xMc[48] & 0x7) << 1)
+ | ((state->xMc[49] >> 2) & 0x1);
+ *c++ = ((state->xMc[49] & 0x3) << 6)
+ | ((state->xMc[50] & 0x7) << 3)
+ | (state->xMc[51] & 0x7);
+}
+
+void gsm_decode(gsm_state *state, short *out)
+{
+ int i;
+ unsigned char *c = state->gsmFrame;
+
+ if (((*c >> 4) & 0x0F) != GSM_MAGIC) return ;
+ state->qLARs[0] = (*c++ & 0xF) << 2;
+ state->qLARs[0] |= (*c >> 6) & 0x3;
+ state->qLARs[1] = *c++ & 0x3F;
+ state->qLARs[2] = (*c >> 3) & 0x1F;
+ state->qLARs[3] = (*c++ & 0x7) << 2;
+ state->qLARs[3] |= (*c >> 6) & 0x3;
+ state->qLARs[4] = (*c >> 2) & 0xF;
+ state->qLARs[5] = (*c++ & 0x3) << 2;
+ state->qLARs[5] |= (*c >> 6) & 0x3;
+ state->qLARs[6] = (*c >> 3) & 0x7;
+ state->qLARs[7] = *c++ & 0x7;
+ state->Nc[0] = (*c >> 1) & 0x7F;
+ state->bc[0] = (*c++ & 0x1) << 1;
+ state->bc[0] |= (*c >> 7) & 0x1;
+ state->Mc[0] = (*c >> 5) & 0x3;
+ state->xMaxc[0] = (*c++ & 0x1F) << 1;
+ state->xMaxc[0] |= (*c >> 7) & 0x1;
+ state->xMc[0] = (*c >> 4) & 0x7;
+ state->xMc[1] = (*c >> 1) & 0x7;
+ state->xMc[2] = (*c++ & 0x1) << 2;
+ state->xMc[2] |= (*c >> 6) & 0x3;
+ state->xMc[3] = (*c >> 3) & 0x7;
+ state->xMc[4] = *c++ & 0x7;
+ state->xMc[5] = (*c >> 5) & 0x7;
+ state->xMc[6] = (*c >> 2) & 0x7;
+ state->xMc[7] = (*c++ & 0x3) << 1;
+ state->xMc[7] |= (*c >> 7) & 0x1;
+ state->xMc[8] = (*c >> 4) & 0x7;
+ state->xMc[9] = (*c >> 1) & 0x7;
+ state->xMc[10] = (*c++ & 0x1) << 2;
+ state->xMc[10] |= (*c >> 6) & 0x3;
+ state->xMc[11] = (*c >> 3) & 0x7;
+ state->xMc[12] = *c++ & 0x7;
+ state->Nc[1] = (*c >> 1) & 0x7F;
+ state->bc[1] = (*c++ & 0x1) << 1;
+ state->bc[1] |= (*c >> 7) & 0x1;
+ state->Mc[1] = (*c >> 5) & 0x3;
+ state->xMaxc[1] = (*c++ & 0x1F) << 1;
+ state->xMaxc[1] |= (*c >> 7) & 0x1;
+ state->xMc[13] = (*c >> 4) & 0x7;
+ state->xMc[14] = (*c >> 1) & 0x7;
+ state->xMc[15] = (*c++ & 0x1) << 2;
+ state->xMc[15] |= (*c >> 6) & 0x3;
+ state->xMc[16] = (*c >> 3) & 0x7;
+ state->xMc[17] = *c++ & 0x7;
+ state->xMc[18] = (*c >> 5) & 0x7;
+ state->xMc[19] = (*c >> 2) & 0x7;
+ state->xMc[20] = (*c++ & 0x3) << 1;
+ state->xMc[20] |= (*c >> 7) & 0x1;
+ state->xMc[21] = (*c >> 4) & 0x7;
+ state->xMc[22] = (*c >> 1) & 0x7;
+ state->xMc[23] = (*c++ & 0x1) << 2;
+ state->xMc[23] |= (*c >> 6) & 0x3;
+ state->xMc[24] = (*c >> 3) & 0x7;
+ state->xMc[25] = *c++ & 0x7;
+ state->Nc[2] = (*c >> 1) & 0x7F;
+ state->bc[2] = (*c++ & 0x1) << 1;
+ state->bc[2] |= (*c >> 7) & 0x1;
+ state->Mc[2] = (*c >> 5) & 0x3;
+ state->xMaxc[2] = (*c++ & 0x1F) << 1;
+ state->xMaxc[2] |= (*c >> 7) & 0x1;
+ state->xMc[26] = (*c >> 4) & 0x7;
+ state->xMc[27] = (*c >> 1) & 0x7;
+ state->xMc[28] = (*c++ & 0x1) << 2;
+ state->xMc[28] |= (*c >> 6) & 0x3;
+ state->xMc[29] = (*c >> 3) & 0x7;
+ state->xMc[30] = *c++ & 0x7;
+ state->xMc[31] = (*c >> 5) & 0x7;
+ state->xMc[32] = (*c >> 2) & 0x7;
+ state->xMc[33] = (*c++ & 0x3) << 1;
+ state->xMc[33] |= (*c >> 7) & 0x1;
+ state->xMc[34] = (*c >> 4) & 0x7;
+ state->xMc[35] = (*c >> 1) & 0x7;
+ state->xMc[36] = (*c++ & 0x1) << 2;
+ state->xMc[36] |= (*c >> 6) & 0x3;
+ state->xMc[37] = (*c >> 3) & 0x7;
+ state->xMc[38] = *c++ & 0x7;
+ state->Nc[3] = (*c >> 1) & 0x7F;
+ state->bc[3] = (*c++ & 0x1) << 1;
+ state->bc[3] |= (*c >> 7) & 0x1;
+ state->Mc[3] = (*c >> 5) & 0x3;
+ state->xMaxc[3] = (*c++ & 0x1F) << 1;
+ state->xMaxc[3] |= (*c >> 7) & 0x1;
+ state->xMc[39] = (*c >> 4) & 0x7;
+ state->xMc[40] = (*c >> 1) & 0x7;
+ state->xMc[41] = (*c++ & 0x1) << 2;
+ state->xMc[41] |= (*c >> 6) & 0x3;
+ state->xMc[42] = (*c >> 3) & 0x7;
+ state->xMc[43] = *c++ & 0x7;
+ state->xMc[44] = (*c >> 5) & 0x7;
+ state->xMc[45] = (*c >> 2) & 0x7;
+ state->xMc[46] = (*c++ & 0x3) << 1;
+ state->xMc[46] |= (*c >> 7) & 0x1;
+ state->xMc[47] = (*c >> 4) & 0x7;
+ state->xMc[48] = (*c >> 1) & 0x7;
+ state->xMc[49] = (*c++ & 0x1) << 2;
+ state->xMc[49] |= (*c >> 6) & 0x3;
+ state->xMc[50] = (*c >> 3) & 0x7;
+ state->xMc[51] = *c & 0x7;
+
+ for (i = 0; i < 4; i++) {
+ state->subframe = i;
+ decodeRPE(state);
+ longTermSynthesis(state);
+ }
+ memcpy(state->dp0, state->dp0 + 160, 120 * sizeof(short));
+ shortTermSynthesis(state, &state->dp0[120], out);
+ gsm_postprocessing(state, out, out);
+ state->j ^= 1;
+}
diff --git a/protocols/Tlen/codec/gsm_long.c b/protocols/Tlen/codec/gsm_long.c
new file mode 100644
index 0000000000..7d9148061c
--- /dev/null
+++ b/protocols/Tlen/codec/gsm_long.c
@@ -0,0 +1,183 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+This program is based on GSM 06.10 source code developed by
+Jutta Degener and Carsten Bormann,
+Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
+Technische Universitaet Berlin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include "gsm.h"
+#include <stdio.h>
+#include <math.h>
+#include <stdlib.h>
+
+/* Decision levels */
+const static int gsm_DLB[4] = { 6554, 16384, 26214, 32767 };
+/* Quantization levels */
+const static int gsm_QLB[4] = { 3277, 11469, 21299, 32767 };
+
+/*
+ * Long term parameters calculation - lag (Nc) and gain (bc).
+ */
+static void longTermLTPCalculation(gsm_state *state, short *in, short *in_1)
+{
+ int k, lambda;
+ int Nc, bc;
+ float in_1_float_base[120], * in_1_float = in_1_float_base + 120;
+ float in_float[40];
+ float L_result, L_max, L_power;
+
+ for (k = -120; k < 0; k++) in_1_float[k] = (float)in_1[k];
+ for (k = 0; k < 40; k++) in_float[k] = (float)in[k];
+
+ /* Search for the maximum cross-correlation and coding of the LTP lag */
+
+ L_max = 0;
+ Nc = 40; /* index for the maximum cross-correlation */
+
+ for (lambda = 40; lambda < 121; lambda++) {
+ for (L_result = 0, L_power = 0, k = 0; k < 40; k++) {
+ L_result += in_float[k] * in_1_float[k - lambda];
+// L_power += in_1_float[k - lambda] * in_1_float[k - lambda];
+ }
+// L_result = L_result / L_power;
+ if (L_result > L_max) {
+ Nc = lambda;
+ L_max = L_result;
+ }
+ }
+ state->Nc[state->subframe] = Nc;
+ if (L_max <= 0.) {
+ state->bc[state->subframe] = 0;
+ return;
+ }
+ /* Compute the power of the reconstructed short term residual signal dp[..] */
+ in_1_float -= Nc;
+ L_power = 0;
+ for (k = 0; k < 40; k++) {
+ float f = in_1_float[k];
+ L_power += f * f;
+ }
+ if (L_max >= L_power) { //1.0
+ state->bc[state->subframe] = 3;
+ return;
+ }
+ /* Coding of the LTP gain
+ * Table gsm_DLB must be used to obtain the level DLB[i] for the
+ * quantization of the LTP gain b to get the coded version bc.
+ */
+// lambda = L_max * 32768.;
+ lambda = (int)(L_max * 32768. / L_power);
+ for (bc = 0; bc <= 2; ++bc) if (lambda <= gsm_DLB[bc]) break;
+ state->bc[state->subframe] = bc;
+}
+
+/*
+ * Here we decode the bc parameter and compute samples of the estimate out[0..39].
+ * The decoding of bc needs the gsm_QLB table.
+ * The long term residual signal e[0..39] is then calculated to be fed to the
+ * RPE encoding section.
+ */
+static void longTermAnalysisFilter(int Nc, int bc, short *in, short *in_1, short *out, int *e)
+{
+ int gain, k, l;
+ gain = gsm_QLB[bc];
+ for (k = 0; k < 40; k++) {
+ l = (gain * (int)in_1[k - Nc] + 16384) >> 15;
+ if (l < -32768) l = -32768;
+ else if (l > 32767) l = 32767;
+ out[k] = l;
+ e[k] = in[k] - l;
+ }
+}
+
+/*
+ * This procedure uses the bcr and Ncr parameter to realize the
+ * long term synthesis filtering. The decoding of bcr needs table gsm_QLB.
+ */
+static void longTermSynthesisFilter(gsm_state * state, int Ncr, int bcr, int *e, short *out)
+{
+ int k;
+ int brp, Nr;
+
+ /* Check the limits of Nr. */
+ Nr = Ncr < 40 || Ncr > 120 ? state->nrp : Ncr;
+ state->nrp = Nr;
+ /* Decoding of the LTP gain bcr */
+ brp = gsm_QLB[ bcr ];
+
+ /* Computation of the reconstructed short term residual
+ * signal drp[0..39]
+ */
+ for (k = 0; k < 40; k++) {
+ int temp = (brp * (int)out[ k-Nr ] + 16384) >> 15;
+ out[k] = e[k] + temp;
+ }
+}
+
+/*
+ * This procedure performs long term analysis.
+ */
+void longTermAnalysis(gsm_state *state, short *in)
+{
+ short *in_1 = state->dp0 + 120 + state->subframe * 40;
+ short *out = state->dp0 + 120 + state->subframe * 40;
+ int *e = state->e + state->subframe * 40;
+/*
+
+ int i;
+ printf("Long-term in: \n");
+ for (i=0;i<40;i++) {
+ printf("%7d ", in[i]);
+ }
+ printf("\n");
+ */
+ longTermLTPCalculation(state, in, in_1);
+ /* printf("Nc: %d, bc: %d \n", state->Nc[state->subframe], state->bc[state->subframe]);
+ */
+ longTermAnalysisFilter(state->Nc[state->subframe], state->bc[state->subframe], in, in_1, out, e);
+/*
+ printf("Long-term out: \n");
+ for (i=0;i<40;i++) {
+ printf("%7d ", out[i]);
+ }
+ printf("\n");
+ */
+}
+
+/*
+ * This procedure performs long term synthesis.
+ */
+void longTermSynthesis(gsm_state *state)
+{
+ int Nc = state->Nc[state->subframe];
+ int bc = state->bc[state->subframe];
+ int *e = state->e + state->subframe * 40;
+ short *out = state->dp0 + 120 + state->subframe * 40;
+ //int i;
+ longTermSynthesisFilter(state, Nc, bc, e, out);
+ /*
+ printf("Long-term reconstructed: \n");
+ for (i=0;i<160;i++) {
+ printf("%7d ", state->dp0[i]);
+ }
+ printf("\n");
+ */
+}
diff --git a/protocols/Tlen/codec/gsm_lpc.c b/protocols/Tlen/codec/gsm_lpc.c
new file mode 100644
index 0000000000..519612baff
--- /dev/null
+++ b/protocols/Tlen/codec/gsm_lpc.c
@@ -0,0 +1,208 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+This program is based on GSM 06.10 source code developed by
+Jutta Degener and Carsten Bormann,
+Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
+Technische Universitaet Berlin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+/* LPC- and Reflection Coefficients
+ * The next two functions calculate linear prediction coefficients
+ * and/or the related reflection coefficients from the first P_MAX+1
+ * values of the autocorrelation function.
+ */
+#include "gsm.h" /* for P_MAX */
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+/* Compute the autocorrelation
+ * ,--,
+ * ac(l) = > x(i) * x(i-l) for all i
+ * `--'
+ * for lags l between 0 and lag-1, and x(i) == 0 for i < 0 or i >= n
+ * @param n: number of samples
+ * @param lax: max lag (order)
+ * @param in: [0...n-1] samples x
+ * @param out: [0...lag-1] autocorrelation
+ */
+static void autocorrelation(int n, float const *x, int lag, float *ac)
+{
+ float d;
+ int i, j;
+ for (j = 0; j < lag; j++) {
+ for (i = j, d = 0; i < n; i++) d += x[i] * x[i-j];
+ ac[j] = d;
+ }
+ d = (float)fabs(ac[0]);
+ if (d != 0) {
+ for (j = 0; j < lag; j++) ac[j] /= d;
+ }
+}
+
+/* The Levinson-Durbin algorithm was invented by N. Levinson in 1947
+ * and modified by J. Durbin in 1959.
+ * @param in: [0...p] autocorrelation values
+ * @param out: [0...p-1] reflection coefficients
+ * @param lpc: [0...p-1] LPC coefficients
+ * @return minimum mean square error
+ */
+/*
+static float levinson_durbin (float const *ac, float *ref, float *lpc)
+{
+ int i, j;
+ float r, error = ac[0];
+
+ if (ac[0] == 0) {
+ for (i = 0; i < P_MAX; i++) ref[i] = 0;
+ return 0;
+ }
+
+ for (i = 0; i < P_MAX; i++) {
+
+ r = -ac[i + 1];
+ for (j = 0; j < i; j++) r -= lpc[j] * ac[i - j];
+ ref[i] = r /= error;
+
+ // Update LPC coefficients and total error.
+ lpc[i] = r;
+ for (j = 0; j < i / 2; j++) {
+ float tmp = lpc[j];
+ lpc[j] = r * lpc[i - 1 - j];
+ lpc[i - 1 - j] += r * tmp;
+ }
+ if (i % 2) lpc[j] += lpc[j] * r;
+
+ error *= 1 - r * r;
+ }
+ return error;
+}
+*/
+/* I. Schur's recursion from 1917 is related to the Levinson-Durbin method,
+ * but faster on parallel architectures; where Levinson-Durbin would take time
+ * proportional to p * log(p), Schur only requires time proportional to p. The
+ * GSM coder uses an integer version of the Schur recursion.
+ * @param in: [0...p] autocorrelation values
+ * @param out: [0...p-1] reflection coefficients
+ * @return the minimum mean square error
+ */
+static float schur(float const *ac, float *ref)
+{
+ int i, m;
+ float error=ac[0], r, G[2][P_MAX];
+
+ if (ac[0] == 0.0) {
+ for (i = 0; i < P_MAX; i++) ref[i] = 0;
+ return 0;
+ }
+
+ /* Initialize the rows of the generator matrix G to ac[1...p]. */
+ for (i = 0; i < P_MAX; i++) G[0][i] = G[1][i] = ac[i + 1];
+
+ for (i = 0;;) {
+ /* Calculate this iteration's reflection coefficient and error. */
+ ref[i] = r = -G[1][0] / error;
+ error += G[1][0] * r;
+
+ if (++i >= P_MAX) return error;
+
+ /* Update the generator matrix. Unlike Levinson-Durbin's summing of
+ * reflection coefficients, this loop could be executed in parallel
+ * by p processors in constant time.
+ */
+ for (m = 0; m < P_MAX - i; m++) {
+ G[1][m] = G[1][m + 1] + r * G[0][m];
+ G[0][m] = G[1][m + 1] * r + G[0][m];
+ }
+ }
+}
+
+
+ /* 0..7 IN/OUT */
+static void rToLAR(int *r)
+/*
+ * The following scaling for r[..] and LAR[..] has been used:
+ *
+ * r[..] = integer( real_r[..]*32768. ); -1 <= real_r < 1.
+ * LAR[..] = integer( real_LAR[..] * 16384 );
+ * with -1.625 <= real_LAR <= 1.625
+ */
+{
+ int temp;
+ int i;
+
+ /* Computation of the LAR[0..7] from the r[0..7]
+ */
+ for (i = 0; i < 8; i++) {
+ temp = abs(r[i]); //GSM_ABS(temp);
+ if (temp < 22118) {
+ temp >>= 1;
+ } else if (temp < 31130) {
+ temp -= 11059;
+ } else {
+ temp -= 26112;
+ temp <<= 2;
+ }
+ r[i] = r[i] < 0 ? -temp : temp;
+ }
+}
+
+static void quantizeLARs(int *LARs, int *qLARs)
+{ int qA[]={20480, 20480, 20480, 20480, 13964, 15360, 8534, 9036};
+ int qB[]={0, 0, 2048, -2560, 94, -1792, -341, -1144};
+ int qMin[]={-32, -32, -16, -16, -8, -8, -4, -4};
+ int qMax[]={31, 31, 15, 15, 7, 7, 3, 3};
+ int i;
+ for (i = 0; i < 8; i++) {
+ int temp;
+ temp = (((LARs[i] * qA[i]) >> 15) + qB[i] + 256) >> 9;
+ if (temp < qMin[i]) temp = 0;
+ else if (temp > qMax[i]) temp = qMax[i] - qMin[i];
+ else temp = temp - qMin[i];
+ qLARs[i] = temp;
+ }
+}
+
+void lpcAnalysis(gsm_state *state, short *in)
+{ float error;
+ float samples[160];
+ float ac[9];
+ float ref[8];
+ int i;
+ int * qLARs = state->qLARs;
+ for (i = 0; i < 160; i++) {
+ samples[i] = in[i];
+ }
+ autocorrelation(160, samples, 9, ac);
+ error=schur(ac, ref);
+ /*
+ printf("reff: ");
+ for (i=0;i<8;i++) {
+ printf("%5.5f ", ref[i]);//((float)i_lpc[i])/32768.0f);
+ }
+ printf("\n");
+ */
+ for (i = 0; i < 8; i++) {
+ qLARs[i] = (int) (32768 * ref[i]);
+ }
+ rToLAR(qLARs);
+ quantizeLARs(qLARs, qLARs);
+}
diff --git a/protocols/Tlen/codec/gsm_preprocess.c b/protocols/Tlen/codec/gsm_preprocess.c
new file mode 100644
index 0000000000..b3d11bb7b1
--- /dev/null
+++ b/protocols/Tlen/codec/gsm_preprocess.c
@@ -0,0 +1,103 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+This program is based on GSM 06.10 source code developed by
+Jutta Degener and Carsten Bormann,
+Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
+Technische Universitaet Berlin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include "gsm.h"
+#include <stdio.h>
+
+/* 4.2.0 .. 4.2.3 PREPROCESSING SECTION
+ *
+ * After A-law to linear conversion (or directly from the
+ * Ato D converter) the following scaling is assumed for
+ * input to the RPE-LTP algorithm:
+ *
+ *
+ * Where S is the sign bit, v a valid bit, and * a "don't care" bit.
+ * The original signal is called sop[..]
+ *
+ */
+
+
+void gsm_preprocessing( gsm_state *state, short *in, short *out)
+{
+ int z1 = state->z1;
+ int z2 = state->z2;
+ int mp = state->mp;
+ int so, s1;
+ int msp, lsp;
+
+ int k = 160;
+
+ while (k--) {
+ /* Downscaling of the input signal
+ * in: 0.1.....................12
+ * S.v.v.v.v.v.v.v.v.v.v.v.v.*.*.*
+ * out: 0.1................... 12
+ * S.S.v.v.v.v.v.v.v.v.v.v.v.v.0.0
+ */
+ so = (*in >> 3) << 2;
+ in++;
+ /* 4.2.2 Offset compensation
+ *
+ * This part implements a high-pass filter and requires extended
+ * arithmetic precision for the recursive part of this filter.
+ * The input of this procedure is the array so[0...159] and the
+ * output the array sof[ 0...159 ].
+ */
+ /* Compute the non-recursive part
+ */
+ s1 = (so - z1) << 15;
+ z1 = so;
+ msp = z2 >> 15;
+ lsp = z2 - (msp << 15);
+ s1 += ((lsp * 32735) + 16384) >> 15;
+ z2 = msp * 32735 + s1;
+ /* 4.2.3 Preemphasis
+ */
+ msp = (-28180 * mp + 16384) >> 15;
+ mp = (z2 + 16384) >> 15;
+ *out++ = mp + msp;
+ }
+ state->z1 = z1;
+ state->z2 = z2;
+ state->mp = mp;
+/*
+ printf("preprocessed: \n");
+ for (k=0;k<160;k++) {
+ printf("%7d ", out[k]);//((float)i_lpc[i])/32768.0f);
+ }
+ printf("\n");
+ */
+}
+
+void gsm_postprocessing( gsm_state *state, short *in, short *out)
+{
+ int k;
+ int msr = state->msr;
+ for (k = 160; k--; in++, out++) {
+ msr = *in + ((msr * 28180 + 16384) >>15); /* Deemphasis */
+ *out = (msr + msr ) & 0xFFF8; /* Truncation & Upscaling */
+ }
+ state->msr = msr;
+}
diff --git a/protocols/Tlen/codec/gsm_rpe.c b/protocols/Tlen/codec/gsm_rpe.c
new file mode 100644
index 0000000000..ad7234e606
--- /dev/null
+++ b/protocols/Tlen/codec/gsm_rpe.c
@@ -0,0 +1,248 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+This program is based on GSM 06.10 source code developed by
+Jutta Degener and Carsten Bormann,
+Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
+Technische Universitaet Berlin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include "gsm.h"
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+static const int gsm_H[11] = {-134, -374, 0, 2054, 5741, 8192, 5741, 2054, 0, -374, -134 };
+static const int gsm_NRFAC[8] = { 29128, 26215, 23832, 21846, 20165, 18725, 17476, 16384 };
+static const int gsm_FAC[8] = { 18431, 20479, 22527, 24575, 26623, 28671, 30719, 32767 };
+/*
+ * The coefficients of the weighting filter are stored in the gsm_H table.
+ * The following scaling is used:
+ *
+ * gsm_H[0..10] = integer( real_H[ 0..10] * 8192 );
+ */
+static void weightingFilter (int *e, int *x)
+{
+ int L_result;
+ int k, i;
+ for (k = 0; k < 40; k++) {
+ L_result = 4096;
+ for (i = 0; i < 11; i++) {
+ int ix = i + k;
+ if (ix>4 && ix<45) L_result += e[ix - 5] * gsm_H[i];
+ }
+ L_result >>= 13;
+ x[k] = (L_result < -32768 ? -32768 : (L_result > 32767 ? 32767 : L_result));
+ }
+}
+
+/*
+ * The signal x[0..39] is used to select the RPE grid which is
+ * represented by Mc.
+ */
+static void gridSelection( int *x, int *xM, int *Mc_out)
+{
+ int m, i;
+ int L_result, L_temp;
+ int EM, Mc;
+
+ EM = 0;
+ Mc = 0;
+
+ for (m = 0; m < 4; m++) {
+ L_result = 0;
+ for (i = 0; i < 13; i++) {
+ int temp = x[m + 3*i] >> 2;
+ L_temp = temp * temp << 1;
+ L_result += L_temp;
+ }
+ if (L_result > EM) {
+ Mc = m;
+ EM = L_result;
+ }
+ }
+ /* Down-sampling by a factor 3 to get the selected xM[0..12]
+ * RPE sequence.
+ */
+ for (i = 0; i < 13; i ++) xM[i] = x[Mc + 3*i];
+ *Mc_out = Mc;
+}
+
+/*
+ * This procedure computes the reconstructed long term residual signal
+ * ep[0..39] for the LTP analysis filter. The inputs are the Mc
+ * which is the grid position selection and the xMp[0..12] decoded
+ * RPE samples which are upsampled by a factor of 3 by inserting zero
+ * values.
+ */
+static void gridPositioning (int Mc, int *xMp, int *ep)
+{
+ int i, k;
+ for (k = 0; k < 40; k++) ep[k] = 0;
+ for (i = 0; i < 13; i++) {
+ ep[ Mc + (3*i) ] = xMp[i];
+ }
+}
+
+static void APCMXmaxcToExpMant (int xmaxc, int *exp_out, int *mant_out )
+{
+ int exp, mant;
+ /* Compute exponent and mantissa of the decoded version of xmaxc
+ */
+ exp = 0;
+ if (xmaxc > 15) exp = (xmaxc >> 3) - 1;
+ mant = xmaxc - (exp << 3);
+
+ if (mant == 0) {
+ exp = -4;
+ mant = 7;
+ }
+ else {
+ while (mant < 8) {
+ mant = mant << 1 | 1;
+ exp--;
+ }
+ mant -= 8;
+ }
+
+ *exp_out = exp;
+ *mant_out = mant;
+}
+
+static void APCMQuantization (int *xM, int *xMc, int *mant_out, int *exp_out, int *xmaxc_out)
+{
+ int i, itest;
+ int xmax, xmaxc, temp, temp1, temp2;
+ int exp, mant;
+
+
+ /* Find the maximum absolute value xmax of xM[0..12].
+ */
+
+ xmax = 0;
+ for (i = 0; i < 13; i++) {
+ temp = abs(xM[i]);
+ if (temp > xmax) xmax = temp;
+ }
+ if (xmax > 32767) xmax = 32767;
+ /* Qantizing and coding of xmax to get xmaxc.
+ */
+
+ exp = 0;
+ temp = xmax >> 9;
+ itest = 0;
+
+ for (i = 0; i < 6; i++) {
+ if (temp != 0) exp++;
+ temp = temp >> 1;
+ }
+
+ temp = exp + 5;
+
+ xmaxc = (xmax >> temp) + (exp << 3);
+
+ /* Quantizing and coding of the xM[0..12] RPE sequence
+ * to get the xMc[0..12]
+ */
+ APCMXmaxcToExpMant( xmaxc, &exp, &mant );
+
+ /* This computation uses the fact that the decoded version of xmaxc
+ * can be calculated by using the exponent and the mantissa part of
+ * xmaxc (logarithmic table).
+ * So, this method avoids any division and uses only a scaling
+ * of the RPE samples by a function of the exponent. A direct
+ * multiplication by the inverse of the mantissa (NRFAC[0..7]
+ * found in table 4.5) gives the 3 bit coded version xMc[0..12]
+ * of the RPE samples.
+ */
+
+ /* Direct computation of xMc[0..12] using table 4.5
+ */
+ temp = (mant|8)<<(5+exp);
+ temp1 = 6 - exp;
+ temp2 = gsm_NRFAC[ mant ];
+ for (i = 0; i < 13; i++) {
+ xMc[i] = ((xM[i] << temp1) * temp2 >> 27) + 4;
+ }
+
+ /* NOTE: This equation is used to make all the xMc[i] positive.
+ */
+
+ *mant_out = mant;
+ *exp_out = exp;
+ *xmaxc_out = xmaxc;
+}
+
+static void APCMDequantization (int *xMc, int mant, int exp, int *xMp)
+{
+ int i, temp1, temp2, temp3;
+ temp1 = gsm_FAC[ mant ];
+ temp2 = 6 - exp;
+ if (temp2 <= 0) {
+ temp3 = 1 >> (1 - temp2);
+ } else {
+ temp3 = 1 << (temp2 - 1);
+ }
+ for (i = 0; i < 13; i++) {
+ xMp[i] = ((((((xMc[i]<<1)-7)<<12)*temp1+16384)>>15)+temp3)>>temp2;
+ }
+}
+
+void encodeRPE(gsm_state *state)
+{ int x[40];
+ int xM[13], xMp[13];
+ int mant, exp;
+ int *Mc = state->Mc + state->subframe;
+ int *xMaxc = state->xMaxc + state->subframe;
+ int *xMc = state->xMc + state->subframe * 13;
+ int *e = state->e + state->subframe * 40;
+ //int i;
+ /*
+ printf("RPE in: \n");
+ for (i=0;i<40;i++) {
+ printf("%7d ", e[i]);
+ }
+ printf("\n");
+ */
+ weightingFilter(e, x);
+ /*
+ printf("RPE weighting filter: \n");
+ for (i=0;i<40;i++) {
+ printf("%7d ", x[i]);
+ }
+ printf("\n");
+ */
+ gridSelection(x, xM, Mc);
+ APCMQuantization(xM, xMc, &mant, &exp, xMaxc);
+ /* printf("RPE Mc(grid #)=%d xmaxc=%d mant=%d exp=%d \n", *Mc, *xMaxc, mant, exp); */
+ APCMDequantization(xMc, mant, exp, xMp);
+ gridPositioning(*Mc, xMp, e);
+}
+
+void decodeRPE(gsm_state *state)
+{
+ int exp, mant;
+ int xMp[ 13 ];
+ int *xMc = state->xMc + state->subframe * 13;
+ int *e = state->e + state->subframe * 40;
+
+ APCMXmaxcToExpMant(state->xMaxc[state->subframe], &exp, &mant);
+ APCMDequantization(xMc, mant, exp, xMp);
+ gridPositioning(state->Mc[state->subframe], xMp, e);
+}
diff --git a/protocols/Tlen/codec/gsm_short.c b/protocols/Tlen/codec/gsm_short.c
new file mode 100644
index 0000000000..c461484639
--- /dev/null
+++ b/protocols/Tlen/codec/gsm_short.c
@@ -0,0 +1,211 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+This program is based on GSM 06.10 source code developed by
+Jutta Degener and Carsten Bormann,
+Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
+Technische Universitaet Berlin
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include "gsm.h"
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+extern void lpcAnalysis(gsm_state *state, short *in);
+
+/*
+ * Dequantize LAR coefficients
+ */
+static void dequantizeLARs(int *qLARs, int *LARs)
+{
+ int dqA[]={13107, 13107, 13107, 13107, 19223, 17476, 31454, 29708};
+ int dqB[]={0, 0, 2048, -2560, 94, -1792, -341, -1144};
+ int dqMin[]={-32, -32, -16, -16, -8, -8, -4, -4};
+ int i;
+ for (i = 0; i < 8; i++) {
+ int temp;
+ temp = ((((qLARs[i] + dqMin[i]) << 10) - (dqB[i] << 1)) * dqA[i] + 16384) >> 15;
+ LARs[i] = temp + temp;
+ }
+}
+/*
+ * Interpolate LAR coefficients (samples 0..12)
+ */
+static void interpolateLARs_0_12 (int *LARpp_j_1, int *LARpp_j, int *LARp)
+{ int i;
+ for (i = 0; i < 8; i++) {
+ LARp[i] = (LARpp_j_1[i] >> 1) + (LARpp_j_1[i] >> 2) + (LARpp_j[i] >> 2);
+ }
+}
+/*
+ * Interpolate LAR coefficients (samples 13..26)
+ */
+static void interpolateLARs_13_26 (int *LARpp_j_1, int *LARpp_j, int *LARp)
+{ int i;
+ for (i = 0; i < 8; i++) {
+ LARp[i] = (LARpp_j_1[i] >> 1) + (LARpp_j[i] >> 1);
+ }
+}
+/*
+ * Interpolate LAR coefficients (samples 27..39)
+ */
+static void interpolateLARs_27_39 (int *LARpp_j_1, int *LARpp_j, int *LARp)
+{ int i;
+ for (i = 0; i < 8; i++) {
+ LARp[i] = (LARpp_j[i] >> 1) + (LARpp_j_1[i] >> 2) + (LARpp_j[i] >> 2);
+ }
+}
+/*
+ * Interpolate LAR coefficients (samples 40..159)
+ */
+static void interpolateLARs_40_159 (int *LARpp_j_1, int *LARpp_j, int *LARp)
+{ int i;
+ for (i = 0; i < 8; i++) {
+ LARp[i] = LARpp_j[i];
+ }
+}
+/*
+ * Convert LAR coefficients to reflection coefficients
+ */
+static void LARToR( int * LARp)
+{
+ int i;
+ int temp;
+ for (i = 0; i < 8; i++) {
+ temp = abs(LARp[i]);
+ if (temp < 11059) temp <<= 1;
+ else if (temp < 20070) temp += 11059;
+ else temp = (temp >> 2) + 26112;
+ LARp[i] = LARp[i] < 0 ? -temp : temp;
+ }
+}
+
+/*
+ * This procedure computes the short term residual signal d[..] to be fed
+ * to the RPE-LTP loop from the s[..] signal and from the local rp[..]
+ * array (quantized reflection coefficients). As the call of this
+ * procedure can be done in many ways (see the interpolation of the LAR
+ * coefficient), it is assumed that the computation begins with index
+ * k_start (for arrays d[..] and s[..]) and stops with index k_end
+ * (k_start and k_end are defined in 4.2.9.1). This procedure also
+ * needs to keep the array u[0..7] in memory for each call.
+ */
+static void shortTermAnalysisFilter (gsm_state * state, int * rp, int len, short * in)
+{
+ int * u = state->u;
+ int i;
+ int di, ui, sav, rpi;
+ for (; len--; in++) {
+ di = sav = *in;
+ for (i = 0; i < 8; i++) {
+ ui = u[i];
+ rpi = rp[i];
+ u[i] = sav;
+ sav = ui + ((rpi * di + 16384) >> 15);
+ di = di + ((rpi * ui + 16384) >> 15);
+ }
+ *in = di;
+ }
+}
+
+static void shortTermSynthesisFilter(gsm_state * state, int * rrp, int len, short * in, short *out)
+{
+ int * v = state->v;
+ int i;
+ int sri;
+ for (; len--; in++, out++) {
+ sri = *in;
+ for (i = 8; i--;) {
+ sri -= (rrp[i] * v[i] + 16384) >> 15;
+ if (sri < -32768) sri = -32768;
+ else if (sri > 32767) sri = 32767;
+ v[i+1] = v[i] + ((rrp[i] * sri + 16384) >> 15);
+ if (v[i+1] < -32768) v[i+1] = -32768;
+ else if (v[i+1] > 32767) v[i+1] = 32767;
+ }
+ *out = v[0] = sri;
+ }
+}
+
+void shortTermAnalysis(gsm_state *state, short *in)
+{
+ int * qLARs = state->qLARs;
+ int * LARpp_j = state->LARpp[state->j];
+ int * LARpp_j_1 = state->LARpp[state->j ^1];
+ int LARp[8];
+// int i;
+
+ lpcAnalysis(state, in);//i_samples);
+/*
+ printf("short term in: \n");
+ for (i=0;i<160;i++) {
+ printf("%7d ", in[i]);//((float)i_lpc[i])/32768.0f);
+ }
+ printf("\n");
+ */
+ dequantizeLARs(qLARs, LARpp_j);
+ interpolateLARs_0_12(LARpp_j_1, LARpp_j, LARp);
+ LARToR(LARp);
+ shortTermAnalysisFilter(state, LARp, 13, in);
+ interpolateLARs_13_26(LARpp_j_1, LARpp_j, LARp);
+ LARToR(LARp);
+ shortTermAnalysisFilter(state, LARp, 14, in+13);
+ interpolateLARs_27_39(LARpp_j_1, LARpp_j, LARp);
+ LARToR(LARp);
+ shortTermAnalysisFilter(state, LARp, 13, in+27);
+ interpolateLARs_40_159(LARpp_j_1, LARpp_j, LARp);
+ LARToR(LARp);
+ shortTermAnalysisFilter(state, LARp, 120, in+40);
+ /*
+ printf("short-term residuals: \n");
+ for (i=0;i<160;i++) {
+ printf("%7d ", in[i]);//((float)i_lpc[i])/32768.0f);
+ }
+ printf("\n");
+ */
+}
+
+void shortTermSynthesis(gsm_state *state, short *in, short *out)
+{
+ int * qLARs = state->qLARs;
+ int * LARpp_j = state->LARpp[state->j];
+ int * LARpp_j_1 = state->LARpp[state->j ^1];
+ int LARp[8];
+// int i;
+
+ dequantizeLARs(qLARs, LARpp_j);
+ interpolateLARs_0_12(LARpp_j_1, LARpp_j, LARp);
+ LARToR(LARp);
+ shortTermSynthesisFilter(state, LARp, 13, in, out);
+ interpolateLARs_13_26(LARpp_j_1, LARpp_j, LARp);
+ LARToR(LARp);
+ shortTermSynthesisFilter(state, LARp, 14, in+13, out+13);
+ interpolateLARs_27_39(LARpp_j_1, LARpp_j, LARp);
+ LARToR(LARp);
+ shortTermSynthesisFilter(state, LARp, 13, in+27, out+27);
+ interpolateLARs_40_159(LARpp_j_1, LARpp_j, LARp);
+ LARToR(LARp);
+ shortTermSynthesisFilter(state, LARp, 120, in+40, out+40);
+ /*
+ printf("samples[reconstructed]: \n");
+ for (i=0;i<160;i++) {
+ printf("%7d ", out[i]);
+ }
+ */
+}
diff --git a/protocols/Tlen/commons.h b/protocols/Tlen/commons.h
new file mode 100644
index 0000000000..af5a9bbcd7
--- /dev/null
+++ b/protocols/Tlen/commons.h
@@ -0,0 +1,32 @@
+#ifndef _TLENCOMMONS_INC
+#define _TLENCOMMONS_INC
+
+
+#define TLENMUCC_MAJOR_VERSION 2
+#define TLENMUCC_MINOR_VERSION 0
+#define TLENMUCC_RELEASE_NUM 5
+#define TLENMUCC_BUILD_NUM 0
+#define TLENMUCC_VERSION_STRING "2.0.5.0"
+
+
+
+//consts for tlen.dll
+#define TLEN_MAJOR_VERSION TLENMUCC_MAJOR_VERSION
+#define TLEN_MINOR_VERSION TLENMUCC_MINOR_VERSION
+#define TLEN_RELEASE_NUM TLENMUCC_RELEASE_NUM
+#define TLEN_BUILD_NUM TLENMUCC_BUILD_NUM
+
+#define TLEN_FILEVERSION_STRING TLEN_MAJOR_VERSION,TLEN_MINOR_VERSION,TLEN_RELEASE_NUM,TLEN_BUILD_NUM
+#define TLEN_VERSION_STRING TLENMUCC_VERSION_STRING
+
+//consts for tlen_czaty.dll
+#define MUCC_MAJOR_VERSION TLENMUCC_MAJOR_VERSION
+#define MUCC_MINOR_VERSION TLENMUCC_MINOR_VERSION
+#define MUCC_RELEASE_NUM TLENMUCC_RELEASE_NUM
+#define MUCC_BUILD_NUM TLENMUCC_BUILD_NUM
+
+#define MUCC_FILEVERSION_STRING MUCC_MAJOR_VERSION,MUCC_MINOR_VERSION,MUCC_RELEASE_NUM,MUCC_BUILD_NUM
+#define MUCC_VERSION_STRING TLENMUCC_VERSION_STRING
+
+
+#endif //ifndef _TLENCOMMONS_INC
diff --git a/protocols/Tlen/crypto/aes.c b/protocols/Tlen/crypto/aes.c
new file mode 100644
index 0000000000..7bccdf93a1
--- /dev/null
+++ b/protocols/Tlen/crypto/aes.c
@@ -0,0 +1,1336 @@
+/*
+ * FIPS-197 compliant AES implementation
+ *
+ * Copyright (C) 2006-2010, Brainspark B.V.
+ *
+ * This file is part of PolarSSL (http://www.polarssl.org)
+ * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+/*
+ * The AES block cipher was designed by Vincent Rijmen and Joan Daemen.
+ *
+ * http://csrc.nist.gov/encryption/aes/rijndael/Rijndael.pdf
+ * http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf
+ */
+
+#include "polarssl/config.h"
+
+#if defined(POLARSSL_AES_C)
+
+#include "polarssl/aes.h"
+#include "polarssl/padlock.h"
+
+/*
+ * 32-bit integer manipulation macros (little endian)
+ */
+#ifndef GET_ULONG_LE
+#define GET_ULONG_LE(n,b,i) \
+{ \
+ (n) = ( (unsigned long) (b)[(i) ] ) \
+ | ( (unsigned long) (b)[(i) + 1] << 8 ) \
+ | ( (unsigned long) (b)[(i) + 2] << 16 ) \
+ | ( (unsigned long) (b)[(i) + 3] << 24 ); \
+}
+#endif
+
+#ifndef PUT_ULONG_LE
+#define PUT_ULONG_LE(n,b,i) \
+{ \
+ (b)[(i) ] = (unsigned char) ( (n) ); \
+ (b)[(i) + 1] = (unsigned char) ( (n) >> 8 ); \
+ (b)[(i) + 2] = (unsigned char) ( (n) >> 16 ); \
+ (b)[(i) + 3] = (unsigned char) ( (n) >> 24 ); \
+}
+#endif
+
+#if defined(POLARSSL_AES_ROM_TABLES)
+/*
+ * Forward S-box
+ */
+static const unsigned char FSb[256] =
+{
+ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5,
+ 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,
+ 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,
+ 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,
+ 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC,
+ 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
+ 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A,
+ 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,
+ 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,
+ 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,
+ 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B,
+ 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
+ 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85,
+ 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,
+ 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,
+ 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,
+ 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17,
+ 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
+ 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88,
+ 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,
+ 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,
+ 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,
+ 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9,
+ 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
+ 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6,
+ 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,
+ 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,
+ 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,
+ 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94,
+ 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
+ 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68,
+ 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16
+};
+
+/*
+ * Forward tables
+ */
+#define FT \
+\
+ V(A5,63,63,C6), V(84,7C,7C,F8), V(99,77,77,EE), V(8D,7B,7B,F6), \
+ V(0D,F2,F2,FF), V(BD,6B,6B,D6), V(B1,6F,6F,DE), V(54,C5,C5,91), \
+ V(50,30,30,60), V(03,01,01,02), V(A9,67,67,CE), V(7D,2B,2B,56), \
+ V(19,FE,FE,E7), V(62,D7,D7,B5), V(E6,AB,AB,4D), V(9A,76,76,EC), \
+ V(45,CA,CA,8F), V(9D,82,82,1F), V(40,C9,C9,89), V(87,7D,7D,FA), \
+ V(15,FA,FA,EF), V(EB,59,59,B2), V(C9,47,47,8E), V(0B,F0,F0,FB), \
+ V(EC,AD,AD,41), V(67,D4,D4,B3), V(FD,A2,A2,5F), V(EA,AF,AF,45), \
+ V(BF,9C,9C,23), V(F7,A4,A4,53), V(96,72,72,E4), V(5B,C0,C0,9B), \
+ V(C2,B7,B7,75), V(1C,FD,FD,E1), V(AE,93,93,3D), V(6A,26,26,4C), \
+ V(5A,36,36,6C), V(41,3F,3F,7E), V(02,F7,F7,F5), V(4F,CC,CC,83), \
+ V(5C,34,34,68), V(F4,A5,A5,51), V(34,E5,E5,D1), V(08,F1,F1,F9), \
+ V(93,71,71,E2), V(73,D8,D8,AB), V(53,31,31,62), V(3F,15,15,2A), \
+ V(0C,04,04,08), V(52,C7,C7,95), V(65,23,23,46), V(5E,C3,C3,9D), \
+ V(28,18,18,30), V(A1,96,96,37), V(0F,05,05,0A), V(B5,9A,9A,2F), \
+ V(09,07,07,0E), V(36,12,12,24), V(9B,80,80,1B), V(3D,E2,E2,DF), \
+ V(26,EB,EB,CD), V(69,27,27,4E), V(CD,B2,B2,7F), V(9F,75,75,EA), \
+ V(1B,09,09,12), V(9E,83,83,1D), V(74,2C,2C,58), V(2E,1A,1A,34), \
+ V(2D,1B,1B,36), V(B2,6E,6E,DC), V(EE,5A,5A,B4), V(FB,A0,A0,5B), \
+ V(F6,52,52,A4), V(4D,3B,3B,76), V(61,D6,D6,B7), V(CE,B3,B3,7D), \
+ V(7B,29,29,52), V(3E,E3,E3,DD), V(71,2F,2F,5E), V(97,84,84,13), \
+ V(F5,53,53,A6), V(68,D1,D1,B9), V(00,00,00,00), V(2C,ED,ED,C1), \
+ V(60,20,20,40), V(1F,FC,FC,E3), V(C8,B1,B1,79), V(ED,5B,5B,B6), \
+ V(BE,6A,6A,D4), V(46,CB,CB,8D), V(D9,BE,BE,67), V(4B,39,39,72), \
+ V(DE,4A,4A,94), V(D4,4C,4C,98), V(E8,58,58,B0), V(4A,CF,CF,85), \
+ V(6B,D0,D0,BB), V(2A,EF,EF,C5), V(E5,AA,AA,4F), V(16,FB,FB,ED), \
+ V(C5,43,43,86), V(D7,4D,4D,9A), V(55,33,33,66), V(94,85,85,11), \
+ V(CF,45,45,8A), V(10,F9,F9,E9), V(06,02,02,04), V(81,7F,7F,FE), \
+ V(F0,50,50,A0), V(44,3C,3C,78), V(BA,9F,9F,25), V(E3,A8,A8,4B), \
+ V(F3,51,51,A2), V(FE,A3,A3,5D), V(C0,40,40,80), V(8A,8F,8F,05), \
+ V(AD,92,92,3F), V(BC,9D,9D,21), V(48,38,38,70), V(04,F5,F5,F1), \
+ V(DF,BC,BC,63), V(C1,B6,B6,77), V(75,DA,DA,AF), V(63,21,21,42), \
+ V(30,10,10,20), V(1A,FF,FF,E5), V(0E,F3,F3,FD), V(6D,D2,D2,BF), \
+ V(4C,CD,CD,81), V(14,0C,0C,18), V(35,13,13,26), V(2F,EC,EC,C3), \
+ V(E1,5F,5F,BE), V(A2,97,97,35), V(CC,44,44,88), V(39,17,17,2E), \
+ V(57,C4,C4,93), V(F2,A7,A7,55), V(82,7E,7E,FC), V(47,3D,3D,7A), \
+ V(AC,64,64,C8), V(E7,5D,5D,BA), V(2B,19,19,32), V(95,73,73,E6), \
+ V(A0,60,60,C0), V(98,81,81,19), V(D1,4F,4F,9E), V(7F,DC,DC,A3), \
+ V(66,22,22,44), V(7E,2A,2A,54), V(AB,90,90,3B), V(83,88,88,0B), \
+ V(CA,46,46,8C), V(29,EE,EE,C7), V(D3,B8,B8,6B), V(3C,14,14,28), \
+ V(79,DE,DE,A7), V(E2,5E,5E,BC), V(1D,0B,0B,16), V(76,DB,DB,AD), \
+ V(3B,E0,E0,DB), V(56,32,32,64), V(4E,3A,3A,74), V(1E,0A,0A,14), \
+ V(DB,49,49,92), V(0A,06,06,0C), V(6C,24,24,48), V(E4,5C,5C,B8), \
+ V(5D,C2,C2,9F), V(6E,D3,D3,BD), V(EF,AC,AC,43), V(A6,62,62,C4), \
+ V(A8,91,91,39), V(A4,95,95,31), V(37,E4,E4,D3), V(8B,79,79,F2), \
+ V(32,E7,E7,D5), V(43,C8,C8,8B), V(59,37,37,6E), V(B7,6D,6D,DA), \
+ V(8C,8D,8D,01), V(64,D5,D5,B1), V(D2,4E,4E,9C), V(E0,A9,A9,49), \
+ V(B4,6C,6C,D8), V(FA,56,56,AC), V(07,F4,F4,F3), V(25,EA,EA,CF), \
+ V(AF,65,65,CA), V(8E,7A,7A,F4), V(E9,AE,AE,47), V(18,08,08,10), \
+ V(D5,BA,BA,6F), V(88,78,78,F0), V(6F,25,25,4A), V(72,2E,2E,5C), \
+ V(24,1C,1C,38), V(F1,A6,A6,57), V(C7,B4,B4,73), V(51,C6,C6,97), \
+ V(23,E8,E8,CB), V(7C,DD,DD,A1), V(9C,74,74,E8), V(21,1F,1F,3E), \
+ V(DD,4B,4B,96), V(DC,BD,BD,61), V(86,8B,8B,0D), V(85,8A,8A,0F), \
+ V(90,70,70,E0), V(42,3E,3E,7C), V(C4,B5,B5,71), V(AA,66,66,CC), \
+ V(D8,48,48,90), V(05,03,03,06), V(01,F6,F6,F7), V(12,0E,0E,1C), \
+ V(A3,61,61,C2), V(5F,35,35,6A), V(F9,57,57,AE), V(D0,B9,B9,69), \
+ V(91,86,86,17), V(58,C1,C1,99), V(27,1D,1D,3A), V(B9,9E,9E,27), \
+ V(38,E1,E1,D9), V(13,F8,F8,EB), V(B3,98,98,2B), V(33,11,11,22), \
+ V(BB,69,69,D2), V(70,D9,D9,A9), V(89,8E,8E,07), V(A7,94,94,33), \
+ V(B6,9B,9B,2D), V(22,1E,1E,3C), V(92,87,87,15), V(20,E9,E9,C9), \
+ V(49,CE,CE,87), V(FF,55,55,AA), V(78,28,28,50), V(7A,DF,DF,A5), \
+ V(8F,8C,8C,03), V(F8,A1,A1,59), V(80,89,89,09), V(17,0D,0D,1A), \
+ V(DA,BF,BF,65), V(31,E6,E6,D7), V(C6,42,42,84), V(B8,68,68,D0), \
+ V(C3,41,41,82), V(B0,99,99,29), V(77,2D,2D,5A), V(11,0F,0F,1E), \
+ V(CB,B0,B0,7B), V(FC,54,54,A8), V(D6,BB,BB,6D), V(3A,16,16,2C)
+
+#define V(a,b,c,d) 0x##a##b##c##d
+static const unsigned long FT0[256] = { FT };
+#undef V
+
+#define V(a,b,c,d) 0x##b##c##d##a
+static const unsigned long FT1[256] = { FT };
+#undef V
+
+#define V(a,b,c,d) 0x##c##d##a##b
+static const unsigned long FT2[256] = { FT };
+#undef V
+
+#define V(a,b,c,d) 0x##d##a##b##c
+static const unsigned long FT3[256] = { FT };
+#undef V
+
+#undef FT
+
+/*
+ * Reverse S-box
+ */
+static const unsigned char RSb[256] =
+{
+ 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38,
+ 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB,
+ 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87,
+ 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB,
+ 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D,
+ 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
+ 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2,
+ 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25,
+ 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16,
+ 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92,
+ 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA,
+ 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
+ 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A,
+ 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06,
+ 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02,
+ 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B,
+ 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA,
+ 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
+ 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85,
+ 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E,
+ 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89,
+ 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B,
+ 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20,
+ 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
+ 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31,
+ 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F,
+ 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D,
+ 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF,
+ 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0,
+ 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
+ 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26,
+ 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D
+};
+
+/*
+ * Reverse tables
+ */
+#define RT \
+\
+ V(50,A7,F4,51), V(53,65,41,7E), V(C3,A4,17,1A), V(96,5E,27,3A), \
+ V(CB,6B,AB,3B), V(F1,45,9D,1F), V(AB,58,FA,AC), V(93,03,E3,4B), \
+ V(55,FA,30,20), V(F6,6D,76,AD), V(91,76,CC,88), V(25,4C,02,F5), \
+ V(FC,D7,E5,4F), V(D7,CB,2A,C5), V(80,44,35,26), V(8F,A3,62,B5), \
+ V(49,5A,B1,DE), V(67,1B,BA,25), V(98,0E,EA,45), V(E1,C0,FE,5D), \
+ V(02,75,2F,C3), V(12,F0,4C,81), V(A3,97,46,8D), V(C6,F9,D3,6B), \
+ V(E7,5F,8F,03), V(95,9C,92,15), V(EB,7A,6D,BF), V(DA,59,52,95), \
+ V(2D,83,BE,D4), V(D3,21,74,58), V(29,69,E0,49), V(44,C8,C9,8E), \
+ V(6A,89,C2,75), V(78,79,8E,F4), V(6B,3E,58,99), V(DD,71,B9,27), \
+ V(B6,4F,E1,BE), V(17,AD,88,F0), V(66,AC,20,C9), V(B4,3A,CE,7D), \
+ V(18,4A,DF,63), V(82,31,1A,E5), V(60,33,51,97), V(45,7F,53,62), \
+ V(E0,77,64,B1), V(84,AE,6B,BB), V(1C,A0,81,FE), V(94,2B,08,F9), \
+ V(58,68,48,70), V(19,FD,45,8F), V(87,6C,DE,94), V(B7,F8,7B,52), \
+ V(23,D3,73,AB), V(E2,02,4B,72), V(57,8F,1F,E3), V(2A,AB,55,66), \
+ V(07,28,EB,B2), V(03,C2,B5,2F), V(9A,7B,C5,86), V(A5,08,37,D3), \
+ V(F2,87,28,30), V(B2,A5,BF,23), V(BA,6A,03,02), V(5C,82,16,ED), \
+ V(2B,1C,CF,8A), V(92,B4,79,A7), V(F0,F2,07,F3), V(A1,E2,69,4E), \
+ V(CD,F4,DA,65), V(D5,BE,05,06), V(1F,62,34,D1), V(8A,FE,A6,C4), \
+ V(9D,53,2E,34), V(A0,55,F3,A2), V(32,E1,8A,05), V(75,EB,F6,A4), \
+ V(39,EC,83,0B), V(AA,EF,60,40), V(06,9F,71,5E), V(51,10,6E,BD), \
+ V(F9,8A,21,3E), V(3D,06,DD,96), V(AE,05,3E,DD), V(46,BD,E6,4D), \
+ V(B5,8D,54,91), V(05,5D,C4,71), V(6F,D4,06,04), V(FF,15,50,60), \
+ V(24,FB,98,19), V(97,E9,BD,D6), V(CC,43,40,89), V(77,9E,D9,67), \
+ V(BD,42,E8,B0), V(88,8B,89,07), V(38,5B,19,E7), V(DB,EE,C8,79), \
+ V(47,0A,7C,A1), V(E9,0F,42,7C), V(C9,1E,84,F8), V(00,00,00,00), \
+ V(83,86,80,09), V(48,ED,2B,32), V(AC,70,11,1E), V(4E,72,5A,6C), \
+ V(FB,FF,0E,FD), V(56,38,85,0F), V(1E,D5,AE,3D), V(27,39,2D,36), \
+ V(64,D9,0F,0A), V(21,A6,5C,68), V(D1,54,5B,9B), V(3A,2E,36,24), \
+ V(B1,67,0A,0C), V(0F,E7,57,93), V(D2,96,EE,B4), V(9E,91,9B,1B), \
+ V(4F,C5,C0,80), V(A2,20,DC,61), V(69,4B,77,5A), V(16,1A,12,1C), \
+ V(0A,BA,93,E2), V(E5,2A,A0,C0), V(43,E0,22,3C), V(1D,17,1B,12), \
+ V(0B,0D,09,0E), V(AD,C7,8B,F2), V(B9,A8,B6,2D), V(C8,A9,1E,14), \
+ V(85,19,F1,57), V(4C,07,75,AF), V(BB,DD,99,EE), V(FD,60,7F,A3), \
+ V(9F,26,01,F7), V(BC,F5,72,5C), V(C5,3B,66,44), V(34,7E,FB,5B), \
+ V(76,29,43,8B), V(DC,C6,23,CB), V(68,FC,ED,B6), V(63,F1,E4,B8), \
+ V(CA,DC,31,D7), V(10,85,63,42), V(40,22,97,13), V(20,11,C6,84), \
+ V(7D,24,4A,85), V(F8,3D,BB,D2), V(11,32,F9,AE), V(6D,A1,29,C7), \
+ V(4B,2F,9E,1D), V(F3,30,B2,DC), V(EC,52,86,0D), V(D0,E3,C1,77), \
+ V(6C,16,B3,2B), V(99,B9,70,A9), V(FA,48,94,11), V(22,64,E9,47), \
+ V(C4,8C,FC,A8), V(1A,3F,F0,A0), V(D8,2C,7D,56), V(EF,90,33,22), \
+ V(C7,4E,49,87), V(C1,D1,38,D9), V(FE,A2,CA,8C), V(36,0B,D4,98), \
+ V(CF,81,F5,A6), V(28,DE,7A,A5), V(26,8E,B7,DA), V(A4,BF,AD,3F), \
+ V(E4,9D,3A,2C), V(0D,92,78,50), V(9B,CC,5F,6A), V(62,46,7E,54), \
+ V(C2,13,8D,F6), V(E8,B8,D8,90), V(5E,F7,39,2E), V(F5,AF,C3,82), \
+ V(BE,80,5D,9F), V(7C,93,D0,69), V(A9,2D,D5,6F), V(B3,12,25,CF), \
+ V(3B,99,AC,C8), V(A7,7D,18,10), V(6E,63,9C,E8), V(7B,BB,3B,DB), \
+ V(09,78,26,CD), V(F4,18,59,6E), V(01,B7,9A,EC), V(A8,9A,4F,83), \
+ V(65,6E,95,E6), V(7E,E6,FF,AA), V(08,CF,BC,21), V(E6,E8,15,EF), \
+ V(D9,9B,E7,BA), V(CE,36,6F,4A), V(D4,09,9F,EA), V(D6,7C,B0,29), \
+ V(AF,B2,A4,31), V(31,23,3F,2A), V(30,94,A5,C6), V(C0,66,A2,35), \
+ V(37,BC,4E,74), V(A6,CA,82,FC), V(B0,D0,90,E0), V(15,D8,A7,33), \
+ V(4A,98,04,F1), V(F7,DA,EC,41), V(0E,50,CD,7F), V(2F,F6,91,17), \
+ V(8D,D6,4D,76), V(4D,B0,EF,43), V(54,4D,AA,CC), V(DF,04,96,E4), \
+ V(E3,B5,D1,9E), V(1B,88,6A,4C), V(B8,1F,2C,C1), V(7F,51,65,46), \
+ V(04,EA,5E,9D), V(5D,35,8C,01), V(73,74,87,FA), V(2E,41,0B,FB), \
+ V(5A,1D,67,B3), V(52,D2,DB,92), V(33,56,10,E9), V(13,47,D6,6D), \
+ V(8C,61,D7,9A), V(7A,0C,A1,37), V(8E,14,F8,59), V(89,3C,13,EB), \
+ V(EE,27,A9,CE), V(35,C9,61,B7), V(ED,E5,1C,E1), V(3C,B1,47,7A), \
+ V(59,DF,D2,9C), V(3F,73,F2,55), V(79,CE,14,18), V(BF,37,C7,73), \
+ V(EA,CD,F7,53), V(5B,AA,FD,5F), V(14,6F,3D,DF), V(86,DB,44,78), \
+ V(81,F3,AF,CA), V(3E,C4,68,B9), V(2C,34,24,38), V(5F,40,A3,C2), \
+ V(72,C3,1D,16), V(0C,25,E2,BC), V(8B,49,3C,28), V(41,95,0D,FF), \
+ V(71,01,A8,39), V(DE,B3,0C,08), V(9C,E4,B4,D8), V(90,C1,56,64), \
+ V(61,84,CB,7B), V(70,B6,32,D5), V(74,5C,6C,48), V(42,57,B8,D0)
+
+#define V(a,b,c,d) 0x##a##b##c##d
+static const unsigned long RT0[256] = { RT };
+#undef V
+
+#define V(a,b,c,d) 0x##b##c##d##a
+static const unsigned long RT1[256] = { RT };
+#undef V
+
+#define V(a,b,c,d) 0x##c##d##a##b
+static const unsigned long RT2[256] = { RT };
+#undef V
+
+#define V(a,b,c,d) 0x##d##a##b##c
+static const unsigned long RT3[256] = { RT };
+#undef V
+
+#undef RT
+
+/*
+ * Round constants
+ */
+static const unsigned long RCON[10] =
+{
+ 0x00000001, 0x00000002, 0x00000004, 0x00000008,
+ 0x00000010, 0x00000020, 0x00000040, 0x00000080,
+ 0x0000001B, 0x00000036
+};
+
+#else
+
+/*
+ * Forward S-box & tables
+ */
+static unsigned char FSb[256];
+static unsigned long FT0[256];
+static unsigned long FT1[256];
+static unsigned long FT2[256];
+static unsigned long FT3[256];
+
+/*
+ * Reverse S-box & tables
+ */
+static unsigned char RSb[256];
+static unsigned long RT0[256];
+static unsigned long RT1[256];
+static unsigned long RT2[256];
+static unsigned long RT3[256];
+
+/*
+ * Round constants
+ */
+static unsigned long RCON[10];
+
+/*
+ * Tables generation code
+ */
+#define ROTL8(x) ( ( x << 8 ) & 0xFFFFFFFF ) | ( x >> 24 )
+#define XTIME(x) ( ( x << 1 ) ^ ( ( x & 0x80 ) ? 0x1B : 0x00 ) )
+#define MUL(x,y) ( ( x && y ) ? pow[(log[x]+log[y]) % 255] : 0 )
+
+static int aes_init_done = 0;
+
+static void aes_gen_tables( void )
+{
+ int i, x, y, z;
+ int pow[256];
+ int log[256];
+
+ /*
+ * compute pow and log tables over GF(2^8)
+ */
+ for( i = 0, x = 1; i < 256; i++ )
+ {
+ pow[i] = x;
+ log[x] = i;
+ x = ( x ^ XTIME( x ) ) & 0xFF;
+ }
+
+ /*
+ * calculate the round constants
+ */
+ for( i = 0, x = 1; i < 10; i++ )
+ {
+ RCON[i] = (unsigned long) x;
+ x = XTIME( x ) & 0xFF;
+ }
+
+ /*
+ * generate the forward and reverse S-boxes
+ */
+ FSb[0x00] = 0x63;
+ RSb[0x63] = 0x00;
+
+ for( i = 1; i < 256; i++ )
+ {
+ x = pow[255 - log[i]];
+
+ y = x; y = ( (y << 1) | (y >> 7) ) & 0xFF;
+ x ^= y; y = ( (y << 1) | (y >> 7) ) & 0xFF;
+ x ^= y; y = ( (y << 1) | (y >> 7) ) & 0xFF;
+ x ^= y; y = ( (y << 1) | (y >> 7) ) & 0xFF;
+ x ^= y ^ 0x63;
+
+ FSb[i] = (unsigned char) x;
+ RSb[x] = (unsigned char) i;
+ }
+
+ /*
+ * generate the forward and reverse tables
+ */
+ for( i = 0; i < 256; i++ )
+ {
+ x = FSb[i];
+ y = XTIME( x ) & 0xFF;
+ z = ( y ^ x ) & 0xFF;
+
+ FT0[i] = ( (unsigned long) y ) ^
+ ( (unsigned long) x << 8 ) ^
+ ( (unsigned long) x << 16 ) ^
+ ( (unsigned long) z << 24 );
+
+ FT1[i] = ROTL8( FT0[i] );
+ FT2[i] = ROTL8( FT1[i] );
+ FT3[i] = ROTL8( FT2[i] );
+
+ x = RSb[i];
+
+ RT0[i] = ( (unsigned long) MUL( 0x0E, x ) ) ^
+ ( (unsigned long) MUL( 0x09, x ) << 8 ) ^
+ ( (unsigned long) MUL( 0x0D, x ) << 16 ) ^
+ ( (unsigned long) MUL( 0x0B, x ) << 24 );
+
+ RT1[i] = ROTL8( RT0[i] );
+ RT2[i] = ROTL8( RT1[i] );
+ RT3[i] = ROTL8( RT2[i] );
+ }
+}
+
+#endif
+
+/*
+ * AES key schedule (encryption)
+ */
+int aes_setkey_enc( aes_context *ctx, const unsigned char *key, unsigned int keysize )
+{
+ unsigned int i;
+ unsigned long *RK;
+
+#if !defined(POLARSSL_AES_ROM_TABLES)
+ if( aes_init_done == 0 )
+ {
+ aes_gen_tables();
+ aes_init_done = 1;
+ }
+#endif
+
+ switch( keysize )
+ {
+ case 128: ctx->nr = 10; break;
+ case 192: ctx->nr = 12; break;
+ case 256: ctx->nr = 14; break;
+ default : return( POLARSSL_ERR_AES_INVALID_KEY_LENGTH );
+ }
+
+#if defined(PADLOCK_ALIGN16)
+ ctx->rk = RK = PADLOCK_ALIGN16( ctx->buf );
+#else
+ ctx->rk = RK = ctx->buf;
+#endif
+
+ for( i = 0; i < (keysize >> 5); i++ )
+ {
+ GET_ULONG_LE( RK[i], key, i << 2 );
+ }
+
+ switch( ctx->nr )
+ {
+ case 10:
+
+ for( i = 0; i < 10; i++, RK += 4 )
+ {
+ RK[4] = RK[0] ^ RCON[i] ^
+ ( (unsigned long) FSb[ ( RK[3] >> 8 ) & 0xFF ] ) ^
+ ( (unsigned long) FSb[ ( RK[3] >> 16 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) FSb[ ( RK[3] >> 24 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) FSb[ ( RK[3] ) & 0xFF ] << 24 );
+
+ RK[5] = RK[1] ^ RK[4];
+ RK[6] = RK[2] ^ RK[5];
+ RK[7] = RK[3] ^ RK[6];
+ }
+ break;
+
+ case 12:
+
+ for( i = 0; i < 8; i++, RK += 6 )
+ {
+ RK[6] = RK[0] ^ RCON[i] ^
+ ( (unsigned long) FSb[ ( RK[5] >> 8 ) & 0xFF ] ) ^
+ ( (unsigned long) FSb[ ( RK[5] >> 16 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) FSb[ ( RK[5] >> 24 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) FSb[ ( RK[5] ) & 0xFF ] << 24 );
+
+ RK[7] = RK[1] ^ RK[6];
+ RK[8] = RK[2] ^ RK[7];
+ RK[9] = RK[3] ^ RK[8];
+ RK[10] = RK[4] ^ RK[9];
+ RK[11] = RK[5] ^ RK[10];
+ }
+ break;
+
+ case 14:
+
+ for( i = 0; i < 7; i++, RK += 8 )
+ {
+ RK[8] = RK[0] ^ RCON[i] ^
+ ( (unsigned long) FSb[ ( RK[7] >> 8 ) & 0xFF ] ) ^
+ ( (unsigned long) FSb[ ( RK[7] >> 16 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) FSb[ ( RK[7] >> 24 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) FSb[ ( RK[7] ) & 0xFF ] << 24 );
+
+ RK[9] = RK[1] ^ RK[8];
+ RK[10] = RK[2] ^ RK[9];
+ RK[11] = RK[3] ^ RK[10];
+
+ RK[12] = RK[4] ^
+ ( (unsigned long) FSb[ ( RK[11] ) & 0xFF ] ) ^
+ ( (unsigned long) FSb[ ( RK[11] >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) FSb[ ( RK[11] >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) FSb[ ( RK[11] >> 24 ) & 0xFF ] << 24 );
+
+ RK[13] = RK[5] ^ RK[12];
+ RK[14] = RK[6] ^ RK[13];
+ RK[15] = RK[7] ^ RK[14];
+ }
+ break;
+
+ default:
+
+ break;
+ }
+
+ return( 0 );
+}
+
+/*
+ * AES key schedule (decryption)
+ */
+int aes_setkey_dec( aes_context *ctx, const unsigned char *key, unsigned int keysize )
+{
+ int i, j;
+ aes_context cty;
+ unsigned long *RK;
+ unsigned long *SK;
+ int ret;
+
+ switch( keysize )
+ {
+ case 128: ctx->nr = 10; break;
+ case 192: ctx->nr = 12; break;
+ case 256: ctx->nr = 14; break;
+ default : return( POLARSSL_ERR_AES_INVALID_KEY_LENGTH );
+ }
+
+#if defined(PADLOCK_ALIGN16)
+ ctx->rk = RK = PADLOCK_ALIGN16( ctx->buf );
+#else
+ ctx->rk = RK = ctx->buf;
+#endif
+
+ ret = aes_setkey_enc( &cty, key, keysize );
+ if( ret != 0 )
+ return( ret );
+
+ SK = cty.rk + cty.nr * 4;
+
+ *RK++ = *SK++;
+ *RK++ = *SK++;
+ *RK++ = *SK++;
+ *RK++ = *SK++;
+
+ for( i = ctx->nr - 1, SK -= 8; i > 0; i--, SK -= 8 )
+ {
+ for( j = 0; j < 4; j++, SK++ )
+ {
+ *RK++ = RT0[ FSb[ ( *SK ) & 0xFF ] ] ^
+ RT1[ FSb[ ( *SK >> 8 ) & 0xFF ] ] ^
+ RT2[ FSb[ ( *SK >> 16 ) & 0xFF ] ] ^
+ RT3[ FSb[ ( *SK >> 24 ) & 0xFF ] ];
+ }
+ }
+
+ *RK++ = *SK++;
+ *RK++ = *SK++;
+ *RK++ = *SK++;
+ *RK++ = *SK++;
+
+ memset( &cty, 0, sizeof( aes_context ) );
+
+ return( 0 );
+}
+
+#define AES_FROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \
+{ \
+ X0 = *RK++ ^ FT0[ ( Y0 ) & 0xFF ] ^ \
+ FT1[ ( Y1 >> 8 ) & 0xFF ] ^ \
+ FT2[ ( Y2 >> 16 ) & 0xFF ] ^ \
+ FT3[ ( Y3 >> 24 ) & 0xFF ]; \
+ \
+ X1 = *RK++ ^ FT0[ ( Y1 ) & 0xFF ] ^ \
+ FT1[ ( Y2 >> 8 ) & 0xFF ] ^ \
+ FT2[ ( Y3 >> 16 ) & 0xFF ] ^ \
+ FT3[ ( Y0 >> 24 ) & 0xFF ]; \
+ \
+ X2 = *RK++ ^ FT0[ ( Y2 ) & 0xFF ] ^ \
+ FT1[ ( Y3 >> 8 ) & 0xFF ] ^ \
+ FT2[ ( Y0 >> 16 ) & 0xFF ] ^ \
+ FT3[ ( Y1 >> 24 ) & 0xFF ]; \
+ \
+ X3 = *RK++ ^ FT0[ ( Y3 ) & 0xFF ] ^ \
+ FT1[ ( Y0 >> 8 ) & 0xFF ] ^ \
+ FT2[ ( Y1 >> 16 ) & 0xFF ] ^ \
+ FT3[ ( Y2 >> 24 ) & 0xFF ]; \
+}
+
+#define AES_RROUND(X0,X1,X2,X3,Y0,Y1,Y2,Y3) \
+{ \
+ X0 = *RK++ ^ RT0[ ( Y0 ) & 0xFF ] ^ \
+ RT1[ ( Y3 >> 8 ) & 0xFF ] ^ \
+ RT2[ ( Y2 >> 16 ) & 0xFF ] ^ \
+ RT3[ ( Y1 >> 24 ) & 0xFF ]; \
+ \
+ X1 = *RK++ ^ RT0[ ( Y1 ) & 0xFF ] ^ \
+ RT1[ ( Y0 >> 8 ) & 0xFF ] ^ \
+ RT2[ ( Y3 >> 16 ) & 0xFF ] ^ \
+ RT3[ ( Y2 >> 24 ) & 0xFF ]; \
+ \
+ X2 = *RK++ ^ RT0[ ( Y2 ) & 0xFF ] ^ \
+ RT1[ ( Y1 >> 8 ) & 0xFF ] ^ \
+ RT2[ ( Y0 >> 16 ) & 0xFF ] ^ \
+ RT3[ ( Y3 >> 24 ) & 0xFF ]; \
+ \
+ X3 = *RK++ ^ RT0[ ( Y3 ) & 0xFF ] ^ \
+ RT1[ ( Y2 >> 8 ) & 0xFF ] ^ \
+ RT2[ ( Y1 >> 16 ) & 0xFF ] ^ \
+ RT3[ ( Y0 >> 24 ) & 0xFF ]; \
+}
+
+/*
+ * AES-ECB block encryption/decryption
+ */
+int aes_crypt_ecb( aes_context *ctx,
+ int mode,
+ const unsigned char input[16],
+ unsigned char output[16] )
+{
+ int i;
+ unsigned long *RK, X0, X1, X2, X3, Y0, Y1, Y2, Y3;
+
+#if defined(POLARSSL_PADLOCK_C) && defined(POLARSSL_HAVE_X86)
+ if( padlock_supports( PADLOCK_ACE ) )
+ {
+ if( padlock_xcryptecb( ctx, mode, input, output ) == 0 )
+ return( 0 );
+
+ // If padlock data misaligned, we just fall back to
+ // unaccelerated mode
+ //
+ }
+#endif
+
+ RK = ctx->rk;
+
+ GET_ULONG_LE( X0, input, 0 ); X0 ^= *RK++;
+ GET_ULONG_LE( X1, input, 4 ); X1 ^= *RK++;
+ GET_ULONG_LE( X2, input, 8 ); X2 ^= *RK++;
+ GET_ULONG_LE( X3, input, 12 ); X3 ^= *RK++;
+
+ if( mode == AES_DECRYPT )
+ {
+ for( i = (ctx->nr >> 1) - 1; i > 0; i-- )
+ {
+ AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
+ AES_RROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );
+ }
+
+ AES_RROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
+
+ X0 = *RK++ ^ \
+ ( (unsigned long) RSb[ ( Y0 ) & 0xFF ] ) ^
+ ( (unsigned long) RSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) RSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) RSb[ ( Y1 >> 24 ) & 0xFF ] << 24 );
+
+ X1 = *RK++ ^ \
+ ( (unsigned long) RSb[ ( Y1 ) & 0xFF ] ) ^
+ ( (unsigned long) RSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) RSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) RSb[ ( Y2 >> 24 ) & 0xFF ] << 24 );
+
+ X2 = *RK++ ^ \
+ ( (unsigned long) RSb[ ( Y2 ) & 0xFF ] ) ^
+ ( (unsigned long) RSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) RSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) RSb[ ( Y3 >> 24 ) & 0xFF ] << 24 );
+
+ X3 = *RK++ ^ \
+ ( (unsigned long) RSb[ ( Y3 ) & 0xFF ] ) ^
+ ( (unsigned long) RSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) RSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) RSb[ ( Y0 >> 24 ) & 0xFF ] << 24 );
+ }
+ else /* AES_ENCRYPT */
+ {
+ for( i = (ctx->nr >> 1) - 1; i > 0; i-- )
+ {
+ AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
+ AES_FROUND( X0, X1, X2, X3, Y0, Y1, Y2, Y3 );
+ }
+
+ AES_FROUND( Y0, Y1, Y2, Y3, X0, X1, X2, X3 );
+
+ X0 = *RK++ ^ \
+ ( (unsigned long) FSb[ ( Y0 ) & 0xFF ] ) ^
+ ( (unsigned long) FSb[ ( Y1 >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) FSb[ ( Y2 >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) FSb[ ( Y3 >> 24 ) & 0xFF ] << 24 );
+
+ X1 = *RK++ ^ \
+ ( (unsigned long) FSb[ ( Y1 ) & 0xFF ] ) ^
+ ( (unsigned long) FSb[ ( Y2 >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) FSb[ ( Y3 >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) FSb[ ( Y0 >> 24 ) & 0xFF ] << 24 );
+
+ X2 = *RK++ ^ \
+ ( (unsigned long) FSb[ ( Y2 ) & 0xFF ] ) ^
+ ( (unsigned long) FSb[ ( Y3 >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) FSb[ ( Y0 >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) FSb[ ( Y1 >> 24 ) & 0xFF ] << 24 );
+
+ X3 = *RK++ ^ \
+ ( (unsigned long) FSb[ ( Y3 ) & 0xFF ] ) ^
+ ( (unsigned long) FSb[ ( Y0 >> 8 ) & 0xFF ] << 8 ) ^
+ ( (unsigned long) FSb[ ( Y1 >> 16 ) & 0xFF ] << 16 ) ^
+ ( (unsigned long) FSb[ ( Y2 >> 24 ) & 0xFF ] << 24 );
+ }
+
+ PUT_ULONG_LE( X0, output, 0 );
+ PUT_ULONG_LE( X1, output, 4 );
+ PUT_ULONG_LE( X2, output, 8 );
+ PUT_ULONG_LE( X3, output, 12 );
+
+ return( 0 );
+}
+
+/*
+ * AES-CBC buffer encryption/decryption
+ */
+int aes_crypt_cbc( aes_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output )
+{
+ int i;
+ unsigned char temp[16];
+
+ if( length % 16 )
+ return( POLARSSL_ERR_AES_INVALID_INPUT_LENGTH );
+
+#if defined(POLARSSL_PADLOCK_C) && defined(POLARSSL_HAVE_X86)
+ if( padlock_supports( PADLOCK_ACE ) )
+ {
+ if( padlock_xcryptcbc( ctx, mode, length, iv, input, output ) == 0 )
+ return( 0 );
+
+ // If padlock data misaligned, we just fall back to
+ // unaccelerated mode
+ //
+ }
+#endif
+
+ if( mode == AES_DECRYPT )
+ {
+ while( length > 0 )
+ {
+ memcpy( temp, input, 16 );
+ aes_crypt_ecb( ctx, mode, input, output );
+
+ for( i = 0; i < 16; i++ )
+ output[i] = (unsigned char)( output[i] ^ iv[i] );
+
+ memcpy( iv, temp, 16 );
+
+ input += 16;
+ output += 16;
+ length -= 16;
+ }
+ }
+ else
+ {
+ while( length > 0 )
+ {
+ for( i = 0; i < 16; i++ )
+ output[i] = (unsigned char)( input[i] ^ iv[i] );
+
+ aes_crypt_ecb( ctx, mode, output, output );
+ memcpy( iv, output, 16 );
+
+ input += 16;
+ output += 16;
+ length -= 16;
+ }
+ }
+
+ return( 0 );
+}
+
+#if defined(POLARSSL_CIPHER_MODE_CFB)
+/*
+ * AES-CFB128 buffer encryption/decryption
+ */
+int aes_crypt_cfb128( aes_context *ctx,
+ int mode,
+ size_t length,
+ size_t *iv_off,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output )
+{
+ int c;
+ size_t n = *iv_off;
+
+ if( mode == AES_DECRYPT )
+ {
+ while( length-- )
+ {
+ if( n == 0 )
+ aes_crypt_ecb( ctx, AES_ENCRYPT, iv, iv );
+
+ c = *input++;
+ *output++ = (unsigned char)( c ^ iv[n] );
+ iv[n] = (unsigned char) c;
+
+ n = (n + 1) & 0x0F;
+ }
+ }
+ else
+ {
+ while( length-- )
+ {
+ if( n == 0 )
+ aes_crypt_ecb( ctx, AES_ENCRYPT, iv, iv );
+
+ iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ );
+
+ n = (n + 1) & 0x0F;
+ }
+ }
+
+ *iv_off = n;
+
+ return( 0 );
+}
+#endif /*POLARSSL_CIPHER_MODE_CFB */
+
+#if defined(POLARSSL_CIPHER_MODE_CTR)
+/*
+ * AES-CTR buffer encryption/decryption
+ */
+int aes_crypt_ctr( aes_context *ctx,
+ size_t length,
+ size_t *nc_off,
+ unsigned char nonce_counter[16],
+ unsigned char stream_block[16],
+ const unsigned char *input,
+ unsigned char *output )
+{
+ int c, i, cb;
+ size_t n = *nc_off;
+
+ while( length-- )
+ {
+ if( n == 0 ) {
+ aes_crypt_ecb( ctx, AES_ENCRYPT, nonce_counter, stream_block );
+
+ i = 15;
+ do {
+ nonce_counter[i]++;
+ cb = nonce_counter[i] == 0;
+ } while( i-- && cb );
+
+ }
+ c = *input++;
+ *output++ = (unsigned char)( c ^ stream_block[n] );
+
+ n = (n + 1) & 0x0F;
+ }
+
+ *nc_off = n;
+
+ return( 0 );
+}
+#endif /* POLARSSL_CIPHER_MODE_CTR */
+
+#if defined(POLARSSL_SELF_TEST)
+
+#include <stdio.h>
+
+/*
+ * AES test vectors from:
+ *
+ * http://csrc.nist.gov/archive/aes/rijndael/rijndael-vals.zip
+ */
+static const unsigned char aes_test_ecb_dec[3][16] =
+{
+ { 0x44, 0x41, 0x6A, 0xC2, 0xD1, 0xF5, 0x3C, 0x58,
+ 0x33, 0x03, 0x91, 0x7E, 0x6B, 0xE9, 0xEB, 0xE0 },
+ { 0x48, 0xE3, 0x1E, 0x9E, 0x25, 0x67, 0x18, 0xF2,
+ 0x92, 0x29, 0x31, 0x9C, 0x19, 0xF1, 0x5B, 0xA4 },
+ { 0x05, 0x8C, 0xCF, 0xFD, 0xBB, 0xCB, 0x38, 0x2D,
+ 0x1F, 0x6F, 0x56, 0x58, 0x5D, 0x8A, 0x4A, 0xDE }
+};
+
+static const unsigned char aes_test_ecb_enc[3][16] =
+{
+ { 0xC3, 0x4C, 0x05, 0x2C, 0xC0, 0xDA, 0x8D, 0x73,
+ 0x45, 0x1A, 0xFE, 0x5F, 0x03, 0xBE, 0x29, 0x7F },
+ { 0xF3, 0xF6, 0x75, 0x2A, 0xE8, 0xD7, 0x83, 0x11,
+ 0x38, 0xF0, 0x41, 0x56, 0x06, 0x31, 0xB1, 0x14 },
+ { 0x8B, 0x79, 0xEE, 0xCC, 0x93, 0xA0, 0xEE, 0x5D,
+ 0xFF, 0x30, 0xB4, 0xEA, 0x21, 0x63, 0x6D, 0xA4 }
+};
+
+static const unsigned char aes_test_cbc_dec[3][16] =
+{
+ { 0xFA, 0xCA, 0x37, 0xE0, 0xB0, 0xC8, 0x53, 0x73,
+ 0xDF, 0x70, 0x6E, 0x73, 0xF7, 0xC9, 0xAF, 0x86 },
+ { 0x5D, 0xF6, 0x78, 0xDD, 0x17, 0xBA, 0x4E, 0x75,
+ 0xB6, 0x17, 0x68, 0xC6, 0xAD, 0xEF, 0x7C, 0x7B },
+ { 0x48, 0x04, 0xE1, 0x81, 0x8F, 0xE6, 0x29, 0x75,
+ 0x19, 0xA3, 0xE8, 0x8C, 0x57, 0x31, 0x04, 0x13 }
+};
+
+static const unsigned char aes_test_cbc_enc[3][16] =
+{
+ { 0x8A, 0x05, 0xFC, 0x5E, 0x09, 0x5A, 0xF4, 0x84,
+ 0x8A, 0x08, 0xD3, 0x28, 0xD3, 0x68, 0x8E, 0x3D },
+ { 0x7B, 0xD9, 0x66, 0xD5, 0x3A, 0xD8, 0xC1, 0xBB,
+ 0x85, 0xD2, 0xAD, 0xFA, 0xE8, 0x7B, 0xB1, 0x04 },
+ { 0xFE, 0x3C, 0x53, 0x65, 0x3E, 0x2F, 0x45, 0xB5,
+ 0x6F, 0xCD, 0x88, 0xB2, 0xCC, 0x89, 0x8F, 0xF0 }
+};
+
+#if defined(POLARSSL_CIPHER_MODE_CFB)
+/*
+ * AES-CFB128 test vectors from:
+ *
+ * http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
+ */
+static const unsigned char aes_test_cfb128_key[3][32] =
+{
+ { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6,
+ 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C },
+ { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52,
+ 0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5,
+ 0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B },
+ { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE,
+ 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81,
+ 0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7,
+ 0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 }
+};
+
+static const unsigned char aes_test_cfb128_iv[16] =
+{
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
+};
+
+static const unsigned char aes_test_cfb128_pt[64] =
+{
+ 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96,
+ 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A,
+ 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C,
+ 0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51,
+ 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11,
+ 0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF,
+ 0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17,
+ 0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10
+};
+
+static const unsigned char aes_test_cfb128_ct[3][64] =
+{
+ { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20,
+ 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A,
+ 0xC8, 0xA6, 0x45, 0x37, 0xA0, 0xB3, 0xA9, 0x3F,
+ 0xCD, 0xE3, 0xCD, 0xAD, 0x9F, 0x1C, 0xE5, 0x8B,
+ 0x26, 0x75, 0x1F, 0x67, 0xA3, 0xCB, 0xB1, 0x40,
+ 0xB1, 0x80, 0x8C, 0xF1, 0x87, 0xA4, 0xF4, 0xDF,
+ 0xC0, 0x4B, 0x05, 0x35, 0x7C, 0x5D, 0x1C, 0x0E,
+ 0xEA, 0xC4, 0xC6, 0x6F, 0x9F, 0xF7, 0xF2, 0xE6 },
+ { 0xCD, 0xC8, 0x0D, 0x6F, 0xDD, 0xF1, 0x8C, 0xAB,
+ 0x34, 0xC2, 0x59, 0x09, 0xC9, 0x9A, 0x41, 0x74,
+ 0x67, 0xCE, 0x7F, 0x7F, 0x81, 0x17, 0x36, 0x21,
+ 0x96, 0x1A, 0x2B, 0x70, 0x17, 0x1D, 0x3D, 0x7A,
+ 0x2E, 0x1E, 0x8A, 0x1D, 0xD5, 0x9B, 0x88, 0xB1,
+ 0xC8, 0xE6, 0x0F, 0xED, 0x1E, 0xFA, 0xC4, 0xC9,
+ 0xC0, 0x5F, 0x9F, 0x9C, 0xA9, 0x83, 0x4F, 0xA0,
+ 0x42, 0xAE, 0x8F, 0xBA, 0x58, 0x4B, 0x09, 0xFF },
+ { 0xDC, 0x7E, 0x84, 0xBF, 0xDA, 0x79, 0x16, 0x4B,
+ 0x7E, 0xCD, 0x84, 0x86, 0x98, 0x5D, 0x38, 0x60,
+ 0x39, 0xFF, 0xED, 0x14, 0x3B, 0x28, 0xB1, 0xC8,
+ 0x32, 0x11, 0x3C, 0x63, 0x31, 0xE5, 0x40, 0x7B,
+ 0xDF, 0x10, 0x13, 0x24, 0x15, 0xE5, 0x4B, 0x92,
+ 0xA1, 0x3E, 0xD0, 0xA8, 0x26, 0x7A, 0xE2, 0xF9,
+ 0x75, 0xA3, 0x85, 0x74, 0x1A, 0xB9, 0xCE, 0xF8,
+ 0x20, 0x31, 0x62, 0x3D, 0x55, 0xB1, 0xE4, 0x71 }
+};
+#endif /* POLARSSL_CIPHER_MODE_CFB */
+
+#if defined(POLARSSL_CIPHER_MODE_CTR)
+/*
+ * AES-CTR test vectors from:
+ *
+ * http://www.faqs.org/rfcs/rfc3686.html
+ */
+
+static const unsigned char aes_test_ctr_key[3][16] =
+{
+ { 0xAE, 0x68, 0x52, 0xF8, 0x12, 0x10, 0x67, 0xCC,
+ 0x4B, 0xF7, 0xA5, 0x76, 0x55, 0x77, 0xF3, 0x9E },
+ { 0x7E, 0x24, 0x06, 0x78, 0x17, 0xFA, 0xE0, 0xD7,
+ 0x43, 0xD6, 0xCE, 0x1F, 0x32, 0x53, 0x91, 0x63 },
+ { 0x76, 0x91, 0xBE, 0x03, 0x5E, 0x50, 0x20, 0xA8,
+ 0xAC, 0x6E, 0x61, 0x85, 0x29, 0xF9, 0xA0, 0xDC }
+};
+
+static const unsigned char aes_test_ctr_nonce_counter[3][16] =
+{
+ { 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },
+ { 0x00, 0x6C, 0xB6, 0xDB, 0xC0, 0x54, 0x3B, 0x59,
+ 0xDA, 0x48, 0xD9, 0x0B, 0x00, 0x00, 0x00, 0x01 },
+ { 0x00, 0xE0, 0x01, 0x7B, 0x27, 0x77, 0x7F, 0x3F,
+ 0x4A, 0x17, 0x86, 0xF0, 0x00, 0x00, 0x00, 0x01 }
+};
+
+static const unsigned char aes_test_ctr_pt[3][48] =
+{
+ { 0x53, 0x69, 0x6E, 0x67, 0x6C, 0x65, 0x20, 0x62,
+ 0x6C, 0x6F, 0x63, 0x6B, 0x20, 0x6D, 0x73, 0x67 },
+
+ { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F },
+
+ { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
+ 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
+ 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
+ 0x20, 0x21, 0x22, 0x23 }
+};
+
+static const unsigned char aes_test_ctr_ct[3][48] =
+{
+ { 0xE4, 0x09, 0x5D, 0x4F, 0xB7, 0xA7, 0xB3, 0x79,
+ 0x2D, 0x61, 0x75, 0xA3, 0x26, 0x13, 0x11, 0xB8 },
+ { 0x51, 0x04, 0xA1, 0x06, 0x16, 0x8A, 0x72, 0xD9,
+ 0x79, 0x0D, 0x41, 0xEE, 0x8E, 0xDA, 0xD3, 0x88,
+ 0xEB, 0x2E, 0x1E, 0xFC, 0x46, 0xDA, 0x57, 0xC8,
+ 0xFC, 0xE6, 0x30, 0xDF, 0x91, 0x41, 0xBE, 0x28 },
+ { 0xC1, 0xCF, 0x48, 0xA8, 0x9F, 0x2F, 0xFD, 0xD9,
+ 0xCF, 0x46, 0x52, 0xE9, 0xEF, 0xDB, 0x72, 0xD7,
+ 0x45, 0x40, 0xA4, 0x2B, 0xDE, 0x6D, 0x78, 0x36,
+ 0xD5, 0x9A, 0x5C, 0xEA, 0xAE, 0xF3, 0x10, 0x53,
+ 0x25, 0xB2, 0x07, 0x2F }
+};
+
+static const int aes_test_ctr_len[3] =
+ { 16, 32, 36 };
+#endif /* POLARSSL_CIPHER_MODE_CTR */
+
+/*
+ * Checkup routine
+ */
+int aes_self_test( int verbose )
+{
+ int i, j, u, v;
+ unsigned char key[32];
+ unsigned char buf[64];
+ unsigned char prv[16];
+ unsigned char iv[16];
+#if defined(POLARSSL_CIPHER_MODE_CTR) || defined(POLARSSL_CIPHER_MODE_CFB)
+ size_t offset;
+#endif
+#if defined(POLARSSL_CIPHER_MODE_CTR)
+ int len;
+ unsigned char nonce_counter[16];
+ unsigned char stream_block[16];
+#endif
+ aes_context ctx;
+
+ memset( key, 0, 32 );
+
+ /*
+ * ECB mode
+ */
+ for( i = 0; i < 6; i++ )
+ {
+ u = i >> 1;
+ v = i & 1;
+
+ if( verbose != 0 )
+ printf( " AES-ECB-%3d (%s): ", 128 + u * 64,
+ ( v == AES_DECRYPT ) ? "dec" : "enc" );
+
+ memset( buf, 0, 16 );
+
+ if( v == AES_DECRYPT )
+ {
+ aes_setkey_dec( &ctx, key, 128 + u * 64 );
+
+ for( j = 0; j < 10000; j++ )
+ aes_crypt_ecb( &ctx, v, buf, buf );
+
+ if( memcmp( buf, aes_test_ecb_dec[u], 16 ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+ }
+ else
+ {
+ aes_setkey_enc( &ctx, key, 128 + u * 64 );
+
+ for( j = 0; j < 10000; j++ )
+ aes_crypt_ecb( &ctx, v, buf, buf );
+
+ if( memcmp( buf, aes_test_ecb_enc[u], 16 ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+ }
+
+ if( verbose != 0 )
+ printf( "\n" );
+
+ /*
+ * CBC mode
+ */
+ for( i = 0; i < 6; i++ )
+ {
+ u = i >> 1;
+ v = i & 1;
+
+ if( verbose != 0 )
+ printf( " AES-CBC-%3d (%s): ", 128 + u * 64,
+ ( v == AES_DECRYPT ) ? "dec" : "enc" );
+
+ memset( iv , 0, 16 );
+ memset( prv, 0, 16 );
+ memset( buf, 0, 16 );
+
+ if( v == AES_DECRYPT )
+ {
+ aes_setkey_dec( &ctx, key, 128 + u * 64 );
+
+ for( j = 0; j < 10000; j++ )
+ aes_crypt_cbc( &ctx, v, 16, iv, buf, buf );
+
+ if( memcmp( buf, aes_test_cbc_dec[u], 16 ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+ }
+ else
+ {
+ aes_setkey_enc( &ctx, key, 128 + u * 64 );
+
+ for( j = 0; j < 10000; j++ )
+ {
+ unsigned char tmp[16];
+
+ aes_crypt_cbc( &ctx, v, 16, iv, buf, buf );
+
+ memcpy( tmp, prv, 16 );
+ memcpy( prv, buf, 16 );
+ memcpy( buf, tmp, 16 );
+ }
+
+ if( memcmp( prv, aes_test_cbc_enc[u], 16 ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+ }
+
+ if( verbose != 0 )
+ printf( "\n" );
+
+#if defined(POLARSSL_CIPHER_MODE_CFB)
+ /*
+ * CFB128 mode
+ */
+ for( i = 0; i < 6; i++ )
+ {
+ u = i >> 1;
+ v = i & 1;
+
+ if( verbose != 0 )
+ printf( " AES-CFB128-%3d (%s): ", 128 + u * 64,
+ ( v == AES_DECRYPT ) ? "dec" : "enc" );
+
+ memcpy( iv, aes_test_cfb128_iv, 16 );
+ memcpy( key, aes_test_cfb128_key[u], 16 + u * 8 );
+
+ offset = 0;
+ aes_setkey_enc( &ctx, key, 128 + u * 64 );
+
+ if( v == AES_DECRYPT )
+ {
+ memcpy( buf, aes_test_cfb128_ct[u], 64 );
+ aes_crypt_cfb128( &ctx, v, 64, &offset, iv, buf, buf );
+
+ if( memcmp( buf, aes_test_cfb128_pt, 64 ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+ }
+ else
+ {
+ memcpy( buf, aes_test_cfb128_pt, 64 );
+ aes_crypt_cfb128( &ctx, v, 64, &offset, iv, buf, buf );
+
+ if( memcmp( buf, aes_test_cfb128_ct[u], 64 ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+ }
+
+ if( verbose != 0 )
+ printf( "\n" );
+#endif /* POLARSSL_CIPHER_MODE_CFB */
+
+#if defined(POLARSSL_CIPHER_MODE_CTR)
+ /*
+ * CTR mode
+ */
+ for( i = 0; i < 6; i++ )
+ {
+ u = i >> 1;
+ v = i & 1;
+
+ if( verbose != 0 )
+ printf( " AES-CTR-128 (%s): ",
+ ( v == AES_DECRYPT ) ? "dec" : "enc" );
+
+ memcpy( nonce_counter, aes_test_ctr_nonce_counter[u], 16 );
+ memcpy( key, aes_test_ctr_key[u], 16 );
+
+ offset = 0;
+ aes_setkey_enc( &ctx, key, 128 );
+
+ if( v == AES_DECRYPT )
+ {
+ len = aes_test_ctr_len[u];
+ memcpy( buf, aes_test_ctr_ct[u], len );
+
+ aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block, buf, buf );
+
+ if( memcmp( buf, aes_test_ctr_pt[u], len ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+ }
+ else
+ {
+ len = aes_test_ctr_len[u];
+ memcpy( buf, aes_test_ctr_pt[u], len );
+
+ aes_crypt_ctr( &ctx, len, &offset, nonce_counter, stream_block, buf, buf );
+
+ if( memcmp( buf, aes_test_ctr_ct[u], len ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+ }
+
+ if( verbose != 0 )
+ printf( "\n" );
+#endif /* POLARSSL_CIPHER_MODE_CTR */
+
+ return( 0 );
+}
+
+#endif
+
+#endif
diff --git a/protocols/Tlen/crypto/bignum.c b/protocols/Tlen/crypto/bignum.c
new file mode 100644
index 0000000000..eabfbfe6f9
--- /dev/null
+++ b/protocols/Tlen/crypto/bignum.c
@@ -0,0 +1,2097 @@
+/*
+ * Multi-precision integer library
+ *
+ * Copyright (C) 2006-2010, Brainspark B.V.
+ *
+ * This file is part of PolarSSL (http://www.polarssl.org)
+ * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+/*
+ * This MPI implementation is based on:
+ *
+ * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
+ * http://www.stillhq.com/extracted/gnupg-api/mpi/
+ * http://math.libtomcrypt.com/files/tommath.pdf
+ */
+
+#include "polarssl/config.h"
+
+#if defined(POLARSSL_BIGNUM_C)
+
+#include "polarssl/bignum.h"
+#include "polarssl/bn_mul.h"
+
+#include <stdlib.h>
+
+#define ciL (sizeof(t_uint)) /* chars in limb */
+#define biL (ciL << 3) /* bits in limb */
+#define biH (ciL << 2) /* half limb size */
+
+/*
+ * Convert between bits/chars and number of limbs
+ */
+#define BITS_TO_LIMBS(i) (((i) + biL - 1) / biL)
+#define CHARS_TO_LIMBS(i) (((i) + ciL - 1) / ciL)
+
+/*
+ * Initialize one MPI
+ */
+void mpi_init( mpi *X )
+{
+ if( X == NULL )
+ return;
+
+ X->s = 1;
+ X->n = 0;
+ X->p = NULL;
+}
+
+/*
+ * Unallocate one MPI
+ */
+void mpi_free( mpi *X )
+{
+ if( X == NULL )
+ return;
+
+ if( X->p != NULL )
+ {
+ memset( X->p, 0, X->n * ciL );
+ free( X->p );
+ }
+
+ X->s = 1;
+ X->n = 0;
+ X->p = NULL;
+}
+
+/*
+ * Enlarge to the specified number of limbs
+ */
+int mpi_grow( mpi *X, size_t nblimbs )
+{
+ t_uint *p;
+
+ if( nblimbs > POLARSSL_MPI_MAX_LIMBS )
+ return( 1 );
+
+ if( X->n < nblimbs )
+ {
+ if( ( p = (t_uint *) malloc( nblimbs * ciL ) ) == NULL )
+ return( 1 );
+
+ memset( p, 0, nblimbs * ciL );
+
+ if( X->p != NULL )
+ {
+ memcpy( p, X->p, X->n * ciL );
+ memset( X->p, 0, X->n * ciL );
+ free( X->p );
+ }
+
+ X->n = nblimbs;
+ X->p = p;
+ }
+
+ return( 0 );
+}
+
+/*
+ * Copy the contents of Y into X
+ */
+int mpi_copy( mpi *X, const mpi *Y )
+{
+ int ret;
+ size_t i;
+
+ if( X == Y )
+ return( 0 );
+
+ for( i = Y->n - 1; i > 0; i-- )
+ if( Y->p[i] != 0 )
+ break;
+ i++;
+
+ X->s = Y->s;
+
+ MPI_CHK( mpi_grow( X, i ) );
+
+ memset( X->p, 0, X->n * ciL );
+ memcpy( X->p, Y->p, i * ciL );
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Swap the contents of X and Y
+ */
+void mpi_swap( mpi *X, mpi *Y )
+{
+ mpi T;
+
+ memcpy( &T, X, sizeof( mpi ) );
+ memcpy( X, Y, sizeof( mpi ) );
+ memcpy( Y, &T, sizeof( mpi ) );
+}
+
+/*
+ * Set value from integer
+ */
+int mpi_lset( mpi *X, t_sint z )
+{
+ int ret;
+
+ MPI_CHK( mpi_grow( X, 1 ) );
+ memset( X->p, 0, X->n * ciL );
+
+ X->p[0] = ( z < 0 ) ? -z : z;
+ X->s = ( z < 0 ) ? -1 : 1;
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Get a specific bit
+ */
+int mpi_get_bit( mpi *X, size_t pos )
+{
+ if( X->n * biL <= pos )
+ return( 0 );
+
+ return ( X->p[pos / biL] >> ( pos % biL ) ) & 0x01;
+}
+
+/*
+ * Set a bit to a specific value of 0 or 1
+ */
+int mpi_set_bit( mpi *X, size_t pos, unsigned char val )
+{
+ int ret = 0;
+ size_t off = pos / biL;
+ size_t idx = pos % biL;
+
+ if( val != 0 && val != 1 )
+ return POLARSSL_ERR_MPI_BAD_INPUT_DATA;
+
+ if( X->n * biL <= pos )
+ {
+ if( val == 0 )
+ return ( 0 );
+
+ MPI_CHK( mpi_grow( X, off + 1 ) );
+ }
+
+ X->p[off] = ( X->p[off] & ~( 0x01 << idx ) ) | ( val << idx );
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Return the number of least significant bits
+ */
+size_t mpi_lsb( const mpi *X )
+{
+ size_t i, j, count = 0;
+
+ for( i = 0; i < X->n; i++ )
+ for( j = 0; j < biL; j++, count++ )
+ if( ( ( X->p[i] >> j ) & 1 ) != 0 )
+ return( count );
+
+ return( 0 );
+}
+
+/*
+ * Return the number of most significant bits
+ */
+size_t mpi_msb( const mpi *X )
+{
+ size_t i, j;
+
+ for( i = X->n - 1; i > 0; i-- )
+ if( X->p[i] != 0 )
+ break;
+
+ for( j = biL; j > 0; j-- )
+ if( ( ( X->p[i] >> ( j - 1 ) ) & 1 ) != 0 )
+ break;
+
+ return( ( i * biL ) + j );
+}
+
+/*
+ * Return the total size in bytes
+ */
+size_t mpi_size( const mpi *X )
+{
+ return( ( mpi_msb( X ) + 7 ) >> 3 );
+}
+
+/*
+ * Convert an ASCII character to digit value
+ */
+static int mpi_get_digit( t_uint *d, int radix, char c )
+{
+ *d = 255;
+
+ if( c >= 0x30 && c <= 0x39 ) *d = c - 0x30;
+ if( c >= 0x41 && c <= 0x46 ) *d = c - 0x37;
+ if( c >= 0x61 && c <= 0x66 ) *d = c - 0x57;
+
+ if( *d >= (t_uint) radix )
+ return( POLARSSL_ERR_MPI_INVALID_CHARACTER );
+
+ return( 0 );
+}
+
+/*
+ * Import from an ASCII string
+ */
+int mpi_read_string( mpi *X, int radix, const char *s )
+{
+ int ret;
+ size_t i, j, slen, n;
+ t_uint d;
+ mpi T;
+
+ if( radix < 2 || radix > 16 )
+ return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
+
+ mpi_init( &T );
+
+ slen = strlen( s );
+
+ if( radix == 16 )
+ {
+ n = BITS_TO_LIMBS( slen << 2 );
+
+ MPI_CHK( mpi_grow( X, n ) );
+ MPI_CHK( mpi_lset( X, 0 ) );
+
+ for( i = slen, j = 0; i > 0; i--, j++ )
+ {
+ if( i == 1 && s[i - 1] == '-' )
+ {
+ X->s = -1;
+ break;
+ }
+
+ MPI_CHK( mpi_get_digit( &d, radix, s[i - 1] ) );
+ X->p[j / (2 * ciL)] |= d << ( (j % (2 * ciL)) << 2 );
+ }
+ }
+ else
+ {
+ MPI_CHK( mpi_lset( X, 0 ) );
+
+ for( i = 0; i < slen; i++ )
+ {
+ if( i == 0 && s[i] == '-' )
+ {
+ X->s = -1;
+ continue;
+ }
+
+ MPI_CHK( mpi_get_digit( &d, radix, s[i] ) );
+ MPI_CHK( mpi_mul_int( &T, X, radix ) );
+
+ if( X->s == 1 )
+ {
+ MPI_CHK( mpi_add_int( X, &T, d ) );
+ }
+ else
+ {
+ MPI_CHK( mpi_sub_int( X, &T, d ) );
+ }
+ }
+ }
+
+cleanup:
+
+ mpi_free( &T );
+
+ return( ret );
+}
+
+/*
+ * Helper to write the digits high-order first
+ */
+static int mpi_write_hlp( mpi *X, int radix, char **p )
+{
+ int ret;
+ t_uint r;
+
+ if( radix < 2 || radix > 16 )
+ return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
+
+ MPI_CHK( mpi_mod_int( &r, X, radix ) );
+ MPI_CHK( mpi_div_int( X, NULL, X, radix ) );
+
+ if( mpi_cmp_int( X, 0 ) != 0 )
+ MPI_CHK( mpi_write_hlp( X, radix, p ) );
+
+ if( r < 10 )
+ *(*p)++ = (char)( r + 0x30 );
+ else
+ *(*p)++ = (char)( r + 0x37 );
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Export into an ASCII string
+ */
+int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen )
+{
+ int ret = 0;
+ size_t n;
+ char *p;
+ mpi T;
+
+ if( radix < 2 || radix > 16 )
+ return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
+
+ n = mpi_msb( X );
+ if( radix >= 4 ) n >>= 1;
+ if( radix >= 16 ) n >>= 1;
+ n += 3;
+
+ if( *slen < n )
+ {
+ *slen = n;
+ return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL );
+ }
+
+ p = s;
+ mpi_init( &T );
+
+ if( X->s == -1 )
+ *p++ = '-';
+
+ if( radix == 16 )
+ {
+ int c;
+ size_t i, j, k;
+
+ for( i = X->n, k = 0; i > 0; i-- )
+ {
+ for( j = ciL; j > 0; j-- )
+ {
+ c = ( X->p[i - 1] >> ( ( j - 1 ) << 3) ) & 0xFF;
+
+ if( c == 0 && k == 0 && ( i + j + 3 ) != 0 )
+ continue;
+
+ p += sprintf( p, "%02X", c );
+ k = 1;
+ }
+ }
+ }
+ else
+ {
+ MPI_CHK( mpi_copy( &T, X ) );
+
+ if( T.s == -1 )
+ T.s = 1;
+
+ MPI_CHK( mpi_write_hlp( &T, radix, &p ) );
+ }
+
+ *p++ = '\0';
+ *slen = p - s;
+
+cleanup:
+
+ mpi_free( &T );
+
+ return( ret );
+}
+
+#if defined(POLARSSL_FS_IO)
+/*
+ * Read X from an opened file
+ */
+int mpi_read_file( mpi *X, int radix, FILE *fin )
+{
+ t_uint d;
+ size_t slen;
+ char *p;
+ char s[1024];
+
+ memset( s, 0, sizeof( s ) );
+ if( fgets( s, sizeof( s ) - 1, fin ) == NULL )
+ return( POLARSSL_ERR_MPI_FILE_IO_ERROR );
+
+ slen = strlen( s );
+ if( s[slen - 1] == '\n' ) { slen--; s[slen] = '\0'; }
+ if( s[slen - 1] == '\r' ) { slen--; s[slen] = '\0'; }
+
+ p = s + slen;
+ while( --p >= s )
+ if( mpi_get_digit( &d, radix, *p ) != 0 )
+ break;
+
+ return( mpi_read_string( X, radix, p + 1 ) );
+}
+
+/*
+ * Write X into an opened file (or stdout if fout == NULL)
+ */
+int mpi_write_file( const char *p, const mpi *X, int radix, FILE *fout )
+{
+ int ret;
+ size_t n, slen, plen;
+ char s[2048];
+
+ n = sizeof( s );
+ memset( s, 0, n );
+ n -= 2;
+
+ MPI_CHK( mpi_write_string( X, radix, s, (size_t *) &n ) );
+
+ if( p == NULL ) p = "";
+
+ plen = strlen( p );
+ slen = strlen( s );
+ s[slen++] = '\r';
+ s[slen++] = '\n';
+
+ if( fout != NULL )
+ {
+ if( fwrite( p, 1, plen, fout ) != plen ||
+ fwrite( s, 1, slen, fout ) != slen )
+ return( POLARSSL_ERR_MPI_FILE_IO_ERROR );
+ }
+ else
+ printf( "%s%s", p, s );
+
+cleanup:
+
+ return( ret );
+}
+#endif /* POLARSSL_FS_IO */
+
+/*
+ * Import X from unsigned binary data, big endian
+ */
+int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen )
+{
+ int ret;
+ size_t i, j, n;
+
+ for( n = 0; n < buflen; n++ )
+ if( buf[n] != 0 )
+ break;
+
+ MPI_CHK( mpi_grow( X, CHARS_TO_LIMBS( buflen - n ) ) );
+ MPI_CHK( mpi_lset( X, 0 ) );
+
+ for( i = buflen, j = 0; i > n; i--, j++ )
+ X->p[j / ciL] |= ((t_uint) buf[i - 1]) << ((j % ciL) << 3);
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Export X into unsigned binary data, big endian
+ */
+int mpi_write_binary( const mpi *X, unsigned char *buf, size_t buflen )
+{
+ size_t i, j, n;
+
+ n = mpi_size( X );
+
+ if( buflen < n )
+ return( POLARSSL_ERR_MPI_BUFFER_TOO_SMALL );
+
+ memset( buf, 0, buflen );
+
+ for( i = buflen - 1, j = 0; n > 0; i--, j++, n-- )
+ buf[i] = (unsigned char)( X->p[j / ciL] >> ((j % ciL) << 3) );
+
+ return( 0 );
+}
+
+/*
+ * Left-shift: X <<= count
+ */
+int mpi_shift_l( mpi *X, size_t count )
+{
+ int ret;
+ size_t i, v0, t1;
+ t_uint r0 = 0, r1;
+
+ v0 = count / (biL );
+ t1 = count & (biL - 1);
+
+ i = mpi_msb( X ) + count;
+
+ if( X->n * biL < i )
+ MPI_CHK( mpi_grow( X, BITS_TO_LIMBS( i ) ) );
+
+ ret = 0;
+
+ /*
+ * shift by count / limb_size
+ */
+ if( v0 > 0 )
+ {
+ for( i = X->n; i > v0; i-- )
+ X->p[i - 1] = X->p[i - v0 - 1];
+
+ for( ; i > 0; i-- )
+ X->p[i - 1] = 0;
+ }
+
+ /*
+ * shift by count % limb_size
+ */
+ if( t1 > 0 )
+ {
+ for( i = v0; i < X->n; i++ )
+ {
+ r1 = X->p[i] >> (biL - t1);
+ X->p[i] <<= t1;
+ X->p[i] |= r0;
+ r0 = r1;
+ }
+ }
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Right-shift: X >>= count
+ */
+int mpi_shift_r( mpi *X, size_t count )
+{
+ size_t i, v0, v1;
+ t_uint r0 = 0, r1;
+
+ v0 = count / biL;
+ v1 = count & (biL - 1);
+
+ /*
+ * shift by count / limb_size
+ */
+ if( v0 > 0 )
+ {
+ for( i = 0; i < X->n - v0; i++ )
+ X->p[i] = X->p[i + v0];
+
+ for( ; i < X->n; i++ )
+ X->p[i] = 0;
+ }
+
+ /*
+ * shift by count % limb_size
+ */
+ if( v1 > 0 )
+ {
+ for( i = X->n; i > 0; i-- )
+ {
+ r1 = X->p[i - 1] << (biL - v1);
+ X->p[i - 1] >>= v1;
+ X->p[i - 1] |= r0;
+ r0 = r1;
+ }
+ }
+
+ return( 0 );
+}
+
+/*
+ * Compare unsigned values
+ */
+int mpi_cmp_abs( const mpi *X, const mpi *Y )
+{
+ size_t i, j;
+
+ for( i = X->n; i > 0; i-- )
+ if( X->p[i - 1] != 0 )
+ break;
+
+ for( j = Y->n; j > 0; j-- )
+ if( Y->p[j - 1] != 0 )
+ break;
+
+ if( i == 0 && j == 0 )
+ return( 0 );
+
+ if( i > j ) return( 1 );
+ if( j > i ) return( -1 );
+
+ for( ; i > 0; i-- )
+ {
+ if( X->p[i - 1] > Y->p[i - 1] ) return( 1 );
+ if( X->p[i - 1] < Y->p[i - 1] ) return( -1 );
+ }
+
+ return( 0 );
+}
+
+/*
+ * Compare signed values
+ */
+int mpi_cmp_mpi( const mpi *X, const mpi *Y )
+{
+ size_t i, j;
+
+ for( i = X->n; i > 0; i-- )
+ if( X->p[i - 1] != 0 )
+ break;
+
+ for( j = Y->n; j > 0; j-- )
+ if( Y->p[j - 1] != 0 )
+ break;
+
+ if( i == 0 && j == 0 )
+ return( 0 );
+
+ if( i > j ) return( X->s );
+ if( j > i ) return( -X->s );
+
+ if( X->s > 0 && Y->s < 0 ) return( 1 );
+ if( Y->s > 0 && X->s < 0 ) return( -1 );
+
+ for( ; i > 0; i-- )
+ {
+ if( X->p[i - 1] > Y->p[i - 1] ) return( X->s );
+ if( X->p[i - 1] < Y->p[i - 1] ) return( -X->s );
+ }
+
+ return( 0 );
+}
+
+/*
+ * Compare signed values
+ */
+int mpi_cmp_int( const mpi *X, t_sint z )
+{
+ mpi Y;
+ t_uint p[1];
+
+ *p = ( z < 0 ) ? -z : z;
+ Y.s = ( z < 0 ) ? -1 : 1;
+ Y.n = 1;
+ Y.p = p;
+
+ return( mpi_cmp_mpi( X, &Y ) );
+}
+
+/*
+ * Unsigned addition: X = |A| + |B| (HAC 14.7)
+ */
+int mpi_add_abs( mpi *X, const mpi *A, const mpi *B )
+{
+ int ret;
+ size_t i, j;
+ t_uint *o, *p, c;
+
+ if( X == B )
+ {
+ const mpi *T = A; A = X; B = T;
+ }
+
+ if( X != A )
+ MPI_CHK( mpi_copy( X, A ) );
+
+ /*
+ * X should always be positive as a result of unsigned additions.
+ */
+ X->s = 1;
+
+ for( j = B->n; j > 0; j-- )
+ if( B->p[j - 1] != 0 )
+ break;
+
+ MPI_CHK( mpi_grow( X, j ) );
+
+ o = B->p; p = X->p; c = 0;
+
+ for( i = 0; i < j; i++, o++, p++ )
+ {
+ *p += c; c = ( *p < c );
+ *p += *o; c += ( *p < *o );
+ }
+
+ while( c != 0 )
+ {
+ if( i >= X->n )
+ {
+ MPI_CHK( mpi_grow( X, i + 1 ) );
+ p = X->p + i;
+ }
+
+ *p += c; c = ( *p < c ); i++;
+ }
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Helper for mpi substraction
+ */
+static void mpi_sub_hlp( size_t n, t_uint *s, t_uint *d )
+{
+ size_t i;
+ t_uint c, z;
+
+ for( i = c = 0; i < n; i++, s++, d++ )
+ {
+ z = ( *d < c ); *d -= c;
+ c = ( *d < *s ) + z; *d -= *s;
+ }
+
+ while( c != 0 )
+ {
+ z = ( *d < c ); *d -= c;
+ c = z; i++; d++;
+ }
+}
+
+/*
+ * Unsigned substraction: X = |A| - |B| (HAC 14.9)
+ */
+int mpi_sub_abs( mpi *X, const mpi *A, const mpi *B )
+{
+ mpi TB;
+ int ret;
+ size_t n;
+
+ if( mpi_cmp_abs( A, B ) < 0 )
+ return( POLARSSL_ERR_MPI_NEGATIVE_VALUE );
+
+ mpi_init( &TB );
+
+ if( X == B )
+ {
+ MPI_CHK( mpi_copy( &TB, B ) );
+ B = &TB;
+ }
+
+ if( X != A )
+ MPI_CHK( mpi_copy( X, A ) );
+
+ /*
+ * X should always be positive as a result of unsigned substractions.
+ */
+ X->s = 1;
+
+ ret = 0;
+
+ for( n = B->n; n > 0; n-- )
+ if( B->p[n - 1] != 0 )
+ break;
+
+ mpi_sub_hlp( n, B->p, X->p );
+
+cleanup:
+
+ mpi_free( &TB );
+
+ return( ret );
+}
+
+/*
+ * Signed addition: X = A + B
+ */
+int mpi_add_mpi( mpi *X, const mpi *A, const mpi *B )
+{
+ int ret, s = A->s;
+
+ if( A->s * B->s < 0 )
+ {
+ if( mpi_cmp_abs( A, B ) >= 0 )
+ {
+ MPI_CHK( mpi_sub_abs( X, A, B ) );
+ X->s = s;
+ }
+ else
+ {
+ MPI_CHK( mpi_sub_abs( X, B, A ) );
+ X->s = -s;
+ }
+ }
+ else
+ {
+ MPI_CHK( mpi_add_abs( X, A, B ) );
+ X->s = s;
+ }
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Signed substraction: X = A - B
+ */
+int mpi_sub_mpi( mpi *X, const mpi *A, const mpi *B )
+{
+ int ret, s = A->s;
+
+ if( A->s * B->s > 0 )
+ {
+ if( mpi_cmp_abs( A, B ) >= 0 )
+ {
+ MPI_CHK( mpi_sub_abs( X, A, B ) );
+ X->s = s;
+ }
+ else
+ {
+ MPI_CHK( mpi_sub_abs( X, B, A ) );
+ X->s = -s;
+ }
+ }
+ else
+ {
+ MPI_CHK( mpi_add_abs( X, A, B ) );
+ X->s = s;
+ }
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Signed addition: X = A + b
+ */
+int mpi_add_int( mpi *X, const mpi *A, t_sint b )
+{
+ mpi _B;
+ t_uint p[1];
+
+ p[0] = ( b < 0 ) ? -b : b;
+ _B.s = ( b < 0 ) ? -1 : 1;
+ _B.n = 1;
+ _B.p = p;
+
+ return( mpi_add_mpi( X, A, &_B ) );
+}
+
+/*
+ * Signed substraction: X = A - b
+ */
+int mpi_sub_int( mpi *X, const mpi *A, t_sint b )
+{
+ mpi _B;
+ t_uint p[1];
+
+ p[0] = ( b < 0 ) ? -b : b;
+ _B.s = ( b < 0 ) ? -1 : 1;
+ _B.n = 1;
+ _B.p = p;
+
+ return( mpi_sub_mpi( X, A, &_B ) );
+}
+
+/*
+ * Helper for mpi multiplication
+ */
+static void mpi_mul_hlp( size_t i, t_uint *s, t_uint *d, t_uint b )
+{
+ t_uint c = 0, t = 0;
+
+#if defined(MULADDC_HUIT)
+ for( ; i >= 8; i -= 8 )
+ {
+ MULADDC_INIT
+ MULADDC_HUIT
+ MULADDC_STOP
+ }
+
+ for( ; i > 0; i-- )
+ {
+ MULADDC_INIT
+ MULADDC_CORE
+ MULADDC_STOP
+ }
+#else
+ for( ; i >= 16; i -= 16 )
+ {
+ MULADDC_INIT
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_CORE MULADDC_CORE
+
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_STOP
+ }
+
+ for( ; i >= 8; i -= 8 )
+ {
+ MULADDC_INIT
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_CORE MULADDC_CORE
+
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_CORE MULADDC_CORE
+ MULADDC_STOP
+ }
+
+ for( ; i > 0; i-- )
+ {
+ MULADDC_INIT
+ MULADDC_CORE
+ MULADDC_STOP
+ }
+#endif
+
+ t++;
+
+ do {
+ *d += c; c = ( *d < c ); d++;
+ }
+ while( c != 0 );
+}
+
+/*
+ * Baseline multiplication: X = A * B (HAC 14.12)
+ */
+int mpi_mul_mpi( mpi *X, const mpi *A, const mpi *B )
+{
+ int ret;
+ size_t i, j;
+ mpi TA, TB;
+
+ mpi_init( &TA ); mpi_init( &TB );
+
+ if( X == A ) { MPI_CHK( mpi_copy( &TA, A ) ); A = &TA; }
+ if( X == B ) { MPI_CHK( mpi_copy( &TB, B ) ); B = &TB; }
+
+ for( i = A->n; i > 0; i-- )
+ if( A->p[i - 1] != 0 )
+ break;
+
+ for( j = B->n; j > 0; j-- )
+ if( B->p[j - 1] != 0 )
+ break;
+
+ MPI_CHK( mpi_grow( X, i + j ) );
+ MPI_CHK( mpi_lset( X, 0 ) );
+
+ for( i++; j > 0; j-- )
+ mpi_mul_hlp( i - 1, A->p, X->p + j - 1, B->p[j - 1] );
+
+ X->s = A->s * B->s;
+
+cleanup:
+
+ mpi_free( &TB ); mpi_free( &TA );
+
+ return( ret );
+}
+
+/*
+ * Baseline multiplication: X = A * b
+ */
+int mpi_mul_int( mpi *X, const mpi *A, t_sint b )
+{
+ mpi _B;
+ t_uint p[1];
+
+ _B.s = 1;
+ _B.n = 1;
+ _B.p = p;
+ p[0] = b;
+
+ return( mpi_mul_mpi( X, A, &_B ) );
+}
+
+/*
+ * Division by mpi: A = Q * B + R (HAC 14.20)
+ */
+int mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B )
+{
+ int ret;
+ size_t i, n, t, k;
+ mpi X, Y, Z, T1, T2;
+
+ if( mpi_cmp_int( B, 0 ) == 0 )
+ return( POLARSSL_ERR_MPI_DIVISION_BY_ZERO );
+
+ mpi_init( &X ); mpi_init( &Y ); mpi_init( &Z );
+ mpi_init( &T1 ); mpi_init( &T2 );
+
+ if( mpi_cmp_abs( A, B ) < 0 )
+ {
+ if( Q != NULL ) MPI_CHK( mpi_lset( Q, 0 ) );
+ if( R != NULL ) MPI_CHK( mpi_copy( R, A ) );
+ return( 0 );
+ }
+
+ MPI_CHK( mpi_copy( &X, A ) );
+ MPI_CHK( mpi_copy( &Y, B ) );
+ X.s = Y.s = 1;
+
+ MPI_CHK( mpi_grow( &Z, A->n + 2 ) );
+ MPI_CHK( mpi_lset( &Z, 0 ) );
+ MPI_CHK( mpi_grow( &T1, 2 ) );
+ MPI_CHK( mpi_grow( &T2, 3 ) );
+
+ k = mpi_msb( &Y ) % biL;
+ if( k < biL - 1 )
+ {
+ k = biL - 1 - k;
+ MPI_CHK( mpi_shift_l( &X, k ) );
+ MPI_CHK( mpi_shift_l( &Y, k ) );
+ }
+ else k = 0;
+
+ n = X.n - 1;
+ t = Y.n - 1;
+ mpi_shift_l( &Y, biL * (n - t) );
+
+ while( mpi_cmp_mpi( &X, &Y ) >= 0 )
+ {
+ Z.p[n - t]++;
+ mpi_sub_mpi( &X, &X, &Y );
+ }
+ mpi_shift_r( &Y, biL * (n - t) );
+
+ for( i = n; i > t ; i-- )
+ {
+ if( X.p[i] >= Y.p[t] )
+ Z.p[i - t - 1] = ~0;
+ else
+ {
+#if defined(POLARSSL_HAVE_LONGLONG)
+ t_dbl r;
+
+ r = (t_dbl) X.p[i] << biL;
+ r |= (t_dbl) X.p[i - 1];
+ r /= Y.p[t];
+ if( r > ((t_dbl) 1 << biL) - 1)
+ r = ((t_dbl) 1 << biL) - 1;
+
+ Z.p[i - t - 1] = (t_uint) r;
+#else
+ /*
+ * __udiv_qrnnd_c, from gmp/longlong.h
+ */
+ t_uint q0, q1, r0, r1;
+ t_uint d0, d1, d, m;
+
+ d = Y.p[t];
+ d0 = ( d << biH ) >> biH;
+ d1 = ( d >> biH );
+
+ q1 = X.p[i] / d1;
+ r1 = X.p[i] - d1 * q1;
+ r1 <<= biH;
+ r1 |= ( X.p[i - 1] >> biH );
+
+ m = q1 * d0;
+ if( r1 < m )
+ {
+ q1--, r1 += d;
+ while( r1 >= d && r1 < m )
+ q1--, r1 += d;
+ }
+ r1 -= m;
+
+ q0 = r1 / d1;
+ r0 = r1 - d1 * q0;
+ r0 <<= biH;
+ r0 |= ( X.p[i - 1] << biH ) >> biH;
+
+ m = q0 * d0;
+ if( r0 < m )
+ {
+ q0--, r0 += d;
+ while( r0 >= d && r0 < m )
+ q0--, r0 += d;
+ }
+ r0 -= m;
+
+ Z.p[i - t - 1] = ( q1 << biH ) | q0;
+#endif
+ }
+
+ Z.p[i - t - 1]++;
+ do
+ {
+ Z.p[i - t - 1]--;
+
+ MPI_CHK( mpi_lset( &T1, 0 ) );
+ T1.p[0] = (t < 1) ? 0 : Y.p[t - 1];
+ T1.p[1] = Y.p[t];
+ MPI_CHK( mpi_mul_int( &T1, &T1, Z.p[i - t - 1] ) );
+
+ MPI_CHK( mpi_lset( &T2, 0 ) );
+ T2.p[0] = (i < 2) ? 0 : X.p[i - 2];
+ T2.p[1] = (i < 1) ? 0 : X.p[i - 1];
+ T2.p[2] = X.p[i];
+ }
+ while( mpi_cmp_mpi( &T1, &T2 ) > 0 );
+
+ MPI_CHK( mpi_mul_int( &T1, &Y, Z.p[i - t - 1] ) );
+ MPI_CHK( mpi_shift_l( &T1, biL * (i - t - 1) ) );
+ MPI_CHK( mpi_sub_mpi( &X, &X, &T1 ) );
+
+ if( mpi_cmp_int( &X, 0 ) < 0 )
+ {
+ MPI_CHK( mpi_copy( &T1, &Y ) );
+ MPI_CHK( mpi_shift_l( &T1, biL * (i - t - 1) ) );
+ MPI_CHK( mpi_add_mpi( &X, &X, &T1 ) );
+ Z.p[i - t - 1]--;
+ }
+ }
+
+ if( Q != NULL )
+ {
+ mpi_copy( Q, &Z );
+ Q->s = A->s * B->s;
+ }
+
+ if( R != NULL )
+ {
+ mpi_shift_r( &X, k );
+ mpi_copy( R, &X );
+
+ R->s = A->s;
+ if( mpi_cmp_int( R, 0 ) == 0 )
+ R->s = 1;
+ }
+
+cleanup:
+
+ mpi_free( &X ); mpi_free( &Y ); mpi_free( &Z );
+ mpi_free( &T1 ); mpi_free( &T2 );
+
+ return( ret );
+}
+
+/*
+ * Division by int: A = Q * b + R
+ *
+ * Returns 0 if successful
+ * 1 if memory allocation failed
+ * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0
+ */
+int mpi_div_int( mpi *Q, mpi *R, const mpi *A, t_sint b )
+{
+ mpi _B;
+ t_uint p[1];
+
+ p[0] = ( b < 0 ) ? -b : b;
+ _B.s = ( b < 0 ) ? -1 : 1;
+ _B.n = 1;
+ _B.p = p;
+
+ return( mpi_div_mpi( Q, R, A, &_B ) );
+}
+
+/*
+ * Modulo: R = A mod B
+ */
+int mpi_mod_mpi( mpi *R, const mpi *A, const mpi *B )
+{
+ int ret;
+
+ if( mpi_cmp_int( B, 0 ) < 0 )
+ return POLARSSL_ERR_MPI_NEGATIVE_VALUE;
+
+ MPI_CHK( mpi_div_mpi( NULL, R, A, B ) );
+
+ while( mpi_cmp_int( R, 0 ) < 0 )
+ MPI_CHK( mpi_add_mpi( R, R, B ) );
+
+ while( mpi_cmp_mpi( R, B ) >= 0 )
+ MPI_CHK( mpi_sub_mpi( R, R, B ) );
+
+cleanup:
+
+ return( ret );
+}
+
+/*
+ * Modulo: r = A mod b
+ */
+int mpi_mod_int( t_uint *r, const mpi *A, t_sint b )
+{
+ size_t i;
+ t_uint x, y, z;
+
+ if( b == 0 )
+ return( POLARSSL_ERR_MPI_DIVISION_BY_ZERO );
+
+ if( b < 0 )
+ return POLARSSL_ERR_MPI_NEGATIVE_VALUE;
+
+ /*
+ * handle trivial cases
+ */
+ if( b == 1 )
+ {
+ *r = 0;
+ return( 0 );
+ }
+
+ if( b == 2 )
+ {
+ *r = A->p[0] & 1;
+ return( 0 );
+ }
+
+ /*
+ * general case
+ */
+ for( i = A->n, y = 0; i > 0; i-- )
+ {
+ x = A->p[i - 1];
+ y = ( y << biH ) | ( x >> biH );
+ z = y / b;
+ y -= z * b;
+
+ x <<= biH;
+ y = ( y << biH ) | ( x >> biH );
+ z = y / b;
+ y -= z * b;
+ }
+
+ /*
+ * If A is negative, then the current y represents a negative value.
+ * Flipping it to the positive side.
+ */
+ if( A->s < 0 && y != 0 )
+ y = b - y;
+
+ *r = y;
+
+ return( 0 );
+}
+
+/*
+ * Fast Montgomery initialization (thanks to Tom St Denis)
+ */
+static void mpi_montg_init( t_uint *mm, const mpi *N )
+{
+ t_uint x, m0 = N->p[0];
+
+ x = m0;
+ x += ( ( m0 + 2 ) & 4 ) << 1;
+ x *= ( 2 - ( m0 * x ) );
+
+ if( biL >= 16 ) x *= ( 2 - ( m0 * x ) );
+ if( biL >= 32 ) x *= ( 2 - ( m0 * x ) );
+ if( biL >= 64 ) x *= ( 2 - ( m0 * x ) );
+
+ *mm = ~x + 1;
+}
+
+/*
+ * Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36)
+ */
+static void mpi_montmul( mpi *A, const mpi *B, const mpi *N, t_uint mm, const mpi *T )
+{
+ size_t i, n, m;
+ t_uint u0, u1, *d;
+
+ memset( T->p, 0, T->n * ciL );
+
+ d = T->p;
+ n = N->n;
+ m = ( B->n < n ) ? B->n : n;
+
+ for( i = 0; i < n; i++ )
+ {
+ /*
+ * T = (T + u0*B + u1*N) / 2^biL
+ */
+ u0 = A->p[i];
+ u1 = ( d[0] + u0 * B->p[0] ) * mm;
+
+ mpi_mul_hlp( m, B->p, d, u0 );
+ mpi_mul_hlp( n, N->p, d, u1 );
+
+ *d++ = u0; d[n + 1] = 0;
+ }
+
+ memcpy( A->p, d, (n + 1) * ciL );
+
+ if( mpi_cmp_abs( A, N ) >= 0 )
+ mpi_sub_hlp( n, N->p, A->p );
+ else
+ /* prevent timing attacks */
+ mpi_sub_hlp( n, A->p, T->p );
+}
+
+/*
+ * Montgomery reduction: A = A * R^-1 mod N
+ */
+static void mpi_montred( mpi *A, const mpi *N, t_uint mm, const mpi *T )
+{
+ t_uint z = 1;
+ mpi U;
+
+ U.n = U.s = z;
+ U.p = &z;
+
+ mpi_montmul( A, &U, N, mm, T );
+}
+
+/*
+ * Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
+ */
+int mpi_exp_mod( mpi *X, const mpi *A, const mpi *E, const mpi *N, mpi *_RR )
+{
+ int ret;
+ size_t wbits, wsize, one = 1;
+ size_t i, j, nblimbs;
+ size_t bufsize, nbits;
+ t_uint ei, mm, state;
+ mpi RR, T, W[64];
+
+ if( mpi_cmp_int( N, 0 ) < 0 || ( N->p[0] & 1 ) == 0 )
+ return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
+
+ /*
+ * Init temps and window size
+ */
+ mpi_montg_init( &mm, N );
+ mpi_init( &RR ); mpi_init( &T );
+ memset( W, 0, sizeof( W ) );
+
+ i = mpi_msb( E );
+
+ wsize = ( i > 671 ) ? 6 : ( i > 239 ) ? 5 :
+ ( i > 79 ) ? 4 : ( i > 23 ) ? 3 : 1;
+
+ j = N->n + 1;
+ MPI_CHK( mpi_grow( X, j ) );
+ MPI_CHK( mpi_grow( &W[1], j ) );
+ MPI_CHK( mpi_grow( &T, j * 2 ) );
+
+ /*
+ * If 1st call, pre-compute R^2 mod N
+ */
+ if( _RR == NULL || _RR->p == NULL )
+ {
+ MPI_CHK( mpi_lset( &RR, 1 ) );
+ MPI_CHK( mpi_shift_l( &RR, N->n * 2 * biL ) );
+ MPI_CHK( mpi_mod_mpi( &RR, &RR, N ) );
+
+ if( _RR != NULL )
+ memcpy( _RR, &RR, sizeof( mpi ) );
+ }
+ else
+ memcpy( &RR, _RR, sizeof( mpi ) );
+
+ /*
+ * W[1] = A * R^2 * R^-1 mod N = A * R mod N
+ */
+ if( mpi_cmp_mpi( A, N ) >= 0 )
+ mpi_mod_mpi( &W[1], A, N );
+ else mpi_copy( &W[1], A );
+
+ mpi_montmul( &W[1], &RR, N, mm, &T );
+
+ /*
+ * X = R^2 * R^-1 mod N = R mod N
+ */
+ MPI_CHK( mpi_copy( X, &RR ) );
+ mpi_montred( X, N, mm, &T );
+
+ if( wsize > 1 )
+ {
+ /*
+ * W[1 << (wsize - 1)] = W[1] ^ (wsize - 1)
+ */
+ j = one << (wsize - 1);
+
+ MPI_CHK( mpi_grow( &W[j], N->n + 1 ) );
+ MPI_CHK( mpi_copy( &W[j], &W[1] ) );
+
+ for( i = 0; i < wsize - 1; i++ )
+ mpi_montmul( &W[j], &W[j], N, mm, &T );
+
+ /*
+ * W[i] = W[i - 1] * W[1]
+ */
+ for( i = j + 1; i < (one << wsize); i++ )
+ {
+ MPI_CHK( mpi_grow( &W[i], N->n + 1 ) );
+ MPI_CHK( mpi_copy( &W[i], &W[i - 1] ) );
+
+ mpi_montmul( &W[i], &W[1], N, mm, &T );
+ }
+ }
+
+ nblimbs = E->n;
+ bufsize = 0;
+ nbits = 0;
+ wbits = 0;
+ state = 0;
+
+ while( 1 )
+ {
+ if( bufsize == 0 )
+ {
+ if( nblimbs-- == 0 )
+ break;
+
+ bufsize = sizeof( t_uint ) << 3;
+ }
+
+ bufsize--;
+
+ ei = (E->p[nblimbs] >> bufsize) & 1;
+
+ /*
+ * skip leading 0s
+ */
+ if( ei == 0 && state == 0 )
+ continue;
+
+ if( ei == 0 && state == 1 )
+ {
+ /*
+ * out of window, square X
+ */
+ mpi_montmul( X, X, N, mm, &T );
+ continue;
+ }
+
+ /*
+ * add ei to current window
+ */
+ state = 2;
+
+ nbits++;
+ wbits |= (ei << (wsize - nbits));
+
+ if( nbits == wsize )
+ {
+ /*
+ * X = X^wsize R^-1 mod N
+ */
+ for( i = 0; i < wsize; i++ )
+ mpi_montmul( X, X, N, mm, &T );
+
+ /*
+ * X = X * W[wbits] R^-1 mod N
+ */
+ mpi_montmul( X, &W[wbits], N, mm, &T );
+
+ state--;
+ nbits = 0;
+ wbits = 0;
+ }
+ }
+
+ /*
+ * process the remaining bits
+ */
+ for( i = 0; i < nbits; i++ )
+ {
+ mpi_montmul( X, X, N, mm, &T );
+
+ wbits <<= 1;
+
+ if( (wbits & (one << wsize)) != 0 )
+ mpi_montmul( X, &W[1], N, mm, &T );
+ }
+
+ /*
+ * X = A^E * R * R^-1 mod N = A^E mod N
+ */
+ mpi_montred( X, N, mm, &T );
+
+cleanup:
+
+ for( i = (one << (wsize - 1)); i < (one << wsize); i++ )
+ mpi_free( &W[i] );
+
+ mpi_free( &W[1] ); mpi_free( &T );
+
+ if( _RR == NULL )
+ mpi_free( &RR );
+
+ return( ret );
+}
+
+/*
+ * Greatest common divisor: G = gcd(A, B) (HAC 14.54)
+ */
+int mpi_gcd( mpi *G, const mpi *A, const mpi *B )
+{
+ int ret;
+ size_t lz, lzt;
+ mpi TG, TA, TB;
+
+ mpi_init( &TG ); mpi_init( &TA ); mpi_init( &TB );
+
+ MPI_CHK( mpi_copy( &TA, A ) );
+ MPI_CHK( mpi_copy( &TB, B ) );
+
+ lz = mpi_lsb( &TA );
+ lzt = mpi_lsb( &TB );
+
+ if ( lzt < lz )
+ lz = lzt;
+
+ MPI_CHK( mpi_shift_r( &TA, lz ) );
+ MPI_CHK( mpi_shift_r( &TB, lz ) );
+
+ TA.s = TB.s = 1;
+
+ while( mpi_cmp_int( &TA, 0 ) != 0 )
+ {
+ MPI_CHK( mpi_shift_r( &TA, mpi_lsb( &TA ) ) );
+ MPI_CHK( mpi_shift_r( &TB, mpi_lsb( &TB ) ) );
+
+ if( mpi_cmp_mpi( &TA, &TB ) >= 0 )
+ {
+ MPI_CHK( mpi_sub_abs( &TA, &TA, &TB ) );
+ MPI_CHK( mpi_shift_r( &TA, 1 ) );
+ }
+ else
+ {
+ MPI_CHK( mpi_sub_abs( &TB, &TB, &TA ) );
+ MPI_CHK( mpi_shift_r( &TB, 1 ) );
+ }
+ }
+
+ MPI_CHK( mpi_shift_l( &TB, lz ) );
+ MPI_CHK( mpi_copy( G, &TB ) );
+
+cleanup:
+
+ mpi_free( &TG ); mpi_free( &TA ); mpi_free( &TB );
+
+ return( ret );
+}
+
+int mpi_fill_random( mpi *X, size_t size, int (*f_rng)(void *), void *p_rng )
+{
+ int ret;
+ size_t k;
+ unsigned char *p;
+
+ MPI_CHK( mpi_grow( X, size ) );
+ MPI_CHK( mpi_lset( X, 0 ) );
+
+ p = (unsigned char *) X->p;
+ for( k = 0; k < X->n * ciL; k++ )
+ *p++ = (unsigned char) f_rng( p_rng );
+
+cleanup:
+ return( ret );
+}
+
+#if defined(POLARSSL_GENPRIME)
+
+/*
+ * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
+ */
+int mpi_inv_mod( mpi *X, const mpi *A, const mpi *N )
+{
+ int ret;
+ mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
+
+ if( mpi_cmp_int( N, 0 ) <= 0 )
+ return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
+
+ mpi_init( &TA ); mpi_init( &TU ); mpi_init( &U1 ); mpi_init( &U2 );
+ mpi_init( &G ); mpi_init( &TB ); mpi_init( &TV );
+ mpi_init( &V1 ); mpi_init( &V2 );
+
+ MPI_CHK( mpi_gcd( &G, A, N ) );
+
+ if( mpi_cmp_int( &G, 1 ) != 0 )
+ {
+ ret = POLARSSL_ERR_MPI_NOT_ACCEPTABLE;
+ goto cleanup;
+ }
+
+ MPI_CHK( mpi_mod_mpi( &TA, A, N ) );
+ MPI_CHK( mpi_copy( &TU, &TA ) );
+ MPI_CHK( mpi_copy( &TB, N ) );
+ MPI_CHK( mpi_copy( &TV, N ) );
+
+ MPI_CHK( mpi_lset( &U1, 1 ) );
+ MPI_CHK( mpi_lset( &U2, 0 ) );
+ MPI_CHK( mpi_lset( &V1, 0 ) );
+ MPI_CHK( mpi_lset( &V2, 1 ) );
+
+ do
+ {
+ while( ( TU.p[0] & 1 ) == 0 )
+ {
+ MPI_CHK( mpi_shift_r( &TU, 1 ) );
+
+ if( ( U1.p[0] & 1 ) != 0 || ( U2.p[0] & 1 ) != 0 )
+ {
+ MPI_CHK( mpi_add_mpi( &U1, &U1, &TB ) );
+ MPI_CHK( mpi_sub_mpi( &U2, &U2, &TA ) );
+ }
+
+ MPI_CHK( mpi_shift_r( &U1, 1 ) );
+ MPI_CHK( mpi_shift_r( &U2, 1 ) );
+ }
+
+ while( ( TV.p[0] & 1 ) == 0 )
+ {
+ MPI_CHK( mpi_shift_r( &TV, 1 ) );
+
+ if( ( V1.p[0] & 1 ) != 0 || ( V2.p[0] & 1 ) != 0 )
+ {
+ MPI_CHK( mpi_add_mpi( &V1, &V1, &TB ) );
+ MPI_CHK( mpi_sub_mpi( &V2, &V2, &TA ) );
+ }
+
+ MPI_CHK( mpi_shift_r( &V1, 1 ) );
+ MPI_CHK( mpi_shift_r( &V2, 1 ) );
+ }
+
+ if( mpi_cmp_mpi( &TU, &TV ) >= 0 )
+ {
+ MPI_CHK( mpi_sub_mpi( &TU, &TU, &TV ) );
+ MPI_CHK( mpi_sub_mpi( &U1, &U1, &V1 ) );
+ MPI_CHK( mpi_sub_mpi( &U2, &U2, &V2 ) );
+ }
+ else
+ {
+ MPI_CHK( mpi_sub_mpi( &TV, &TV, &TU ) );
+ MPI_CHK( mpi_sub_mpi( &V1, &V1, &U1 ) );
+ MPI_CHK( mpi_sub_mpi( &V2, &V2, &U2 ) );
+ }
+ }
+ while( mpi_cmp_int( &TU, 0 ) != 0 );
+
+ while( mpi_cmp_int( &V1, 0 ) < 0 )
+ MPI_CHK( mpi_add_mpi( &V1, &V1, N ) );
+
+ while( mpi_cmp_mpi( &V1, N ) >= 0 )
+ MPI_CHK( mpi_sub_mpi( &V1, &V1, N ) );
+
+ MPI_CHK( mpi_copy( X, &V1 ) );
+
+cleanup:
+
+ mpi_free( &TA ); mpi_free( &TU ); mpi_free( &U1 ); mpi_free( &U2 );
+ mpi_free( &G ); mpi_free( &TB ); mpi_free( &TV );
+ mpi_free( &V1 ); mpi_free( &V2 );
+
+ return( ret );
+}
+
+static const int small_prime[] =
+{
+ 3, 5, 7, 11, 13, 17, 19, 23,
+ 29, 31, 37, 41, 43, 47, 53, 59,
+ 61, 67, 71, 73, 79, 83, 89, 97,
+ 101, 103, 107, 109, 113, 127, 131, 137,
+ 139, 149, 151, 157, 163, 167, 173, 179,
+ 181, 191, 193, 197, 199, 211, 223, 227,
+ 229, 233, 239, 241, 251, 257, 263, 269,
+ 271, 277, 281, 283, 293, 307, 311, 313,
+ 317, 331, 337, 347, 349, 353, 359, 367,
+ 373, 379, 383, 389, 397, 401, 409, 419,
+ 421, 431, 433, 439, 443, 449, 457, 461,
+ 463, 467, 479, 487, 491, 499, 503, 509,
+ 521, 523, 541, 547, 557, 563, 569, 571,
+ 577, 587, 593, 599, 601, 607, 613, 617,
+ 619, 631, 641, 643, 647, 653, 659, 661,
+ 673, 677, 683, 691, 701, 709, 719, 727,
+ 733, 739, 743, 751, 757, 761, 769, 773,
+ 787, 797, 809, 811, 821, 823, 827, 829,
+ 839, 853, 857, 859, 863, 877, 881, 883,
+ 887, 907, 911, 919, 929, 937, 941, 947,
+ 953, 967, 971, 977, 983, 991, 997, -103
+};
+
+/*
+ * Miller-Rabin primality test (HAC 4.24)
+ */
+int mpi_is_prime( mpi *X, int (*f_rng)(void *), void *p_rng )
+{
+ int ret, xs;
+ size_t i, j, n, s;
+ mpi W, R, T, A, RR;
+
+ if( mpi_cmp_int( X, 0 ) == 0 ||
+ mpi_cmp_int( X, 1 ) == 0 )
+ return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE );
+
+ if( mpi_cmp_int( X, 2 ) == 0 )
+ return( 0 );
+
+ mpi_init( &W ); mpi_init( &R ); mpi_init( &T ); mpi_init( &A );
+ mpi_init( &RR );
+
+ xs = X->s; X->s = 1;
+
+ /*
+ * test trivial factors first
+ */
+ if( ( X->p[0] & 1 ) == 0 )
+ return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE );
+
+ for( i = 0; small_prime[i] > 0; i++ )
+ {
+ t_uint r;
+
+ if( mpi_cmp_int( X, small_prime[i] ) <= 0 )
+ return( 0 );
+
+ MPI_CHK( mpi_mod_int( &r, X, small_prime[i] ) );
+
+ if( r == 0 )
+ return( POLARSSL_ERR_MPI_NOT_ACCEPTABLE );
+ }
+
+ /*
+ * W = |X| - 1
+ * R = W >> lsb( W )
+ */
+ MPI_CHK( mpi_sub_int( &W, X, 1 ) );
+ s = mpi_lsb( &W );
+ MPI_CHK( mpi_copy( &R, &W ) );
+ MPI_CHK( mpi_shift_r( &R, s ) );
+
+ i = mpi_msb( X );
+ /*
+ * HAC, table 4.4
+ */
+ n = ( ( i >= 1300 ) ? 2 : ( i >= 850 ) ? 3 :
+ ( i >= 650 ) ? 4 : ( i >= 350 ) ? 8 :
+ ( i >= 250 ) ? 12 : ( i >= 150 ) ? 18 : 27 );
+
+ for( i = 0; i < n; i++ )
+ {
+ /*
+ * pick a random A, 1 < A < |X| - 1
+ */
+ mpi_fill_random( &A, X->n, f_rng, p_rng );
+
+ if( mpi_cmp_mpi( &A, &W ) >= 0 )
+ {
+ j = mpi_msb( &A ) - mpi_msb( &W );
+ MPI_CHK( mpi_shift_r( &A, j + 1 ) );
+ }
+ A.p[0] |= 3;
+
+ /*
+ * A = A^R mod |X|
+ */
+ MPI_CHK( mpi_exp_mod( &A, &A, &R, X, &RR ) );
+
+ if( mpi_cmp_mpi( &A, &W ) == 0 ||
+ mpi_cmp_int( &A, 1 ) == 0 )
+ continue;
+
+ j = 1;
+ while( j < s && mpi_cmp_mpi( &A, &W ) != 0 )
+ {
+ /*
+ * A = A * A mod |X|
+ */
+ MPI_CHK( mpi_mul_mpi( &T, &A, &A ) );
+ MPI_CHK( mpi_mod_mpi( &A, &T, X ) );
+
+ if( mpi_cmp_int( &A, 1 ) == 0 )
+ break;
+
+ j++;
+ }
+
+ /*
+ * not prime if A != |X| - 1 or A == 1
+ */
+ if( mpi_cmp_mpi( &A, &W ) != 0 ||
+ mpi_cmp_int( &A, 1 ) == 0 )
+ {
+ ret = POLARSSL_ERR_MPI_NOT_ACCEPTABLE;
+ break;
+ }
+ }
+
+cleanup:
+
+ X->s = xs;
+
+ mpi_free( &W ); mpi_free( &R ); mpi_free( &T ); mpi_free( &A );
+ mpi_free( &RR );
+
+ return( ret );
+}
+
+/*
+ * Prime number generation
+ */
+int mpi_gen_prime( mpi *X, size_t nbits, int dh_flag,
+ int (*f_rng)(void *), void *p_rng )
+{
+ int ret;
+ size_t k, n;
+ mpi Y;
+
+ if( nbits < 3 || nbits > 4096 )
+ return( POLARSSL_ERR_MPI_BAD_INPUT_DATA );
+
+ mpi_init( &Y );
+
+ n = BITS_TO_LIMBS( nbits );
+
+ mpi_fill_random( X, n, f_rng, p_rng );
+
+ k = mpi_msb( X );
+ if( k < nbits ) MPI_CHK( mpi_shift_l( X, nbits - k ) );
+ if( k > nbits ) MPI_CHK( mpi_shift_r( X, k - nbits ) );
+
+ X->p[0] |= 3;
+
+ if( dh_flag == 0 )
+ {
+ while( ( ret = mpi_is_prime( X, f_rng, p_rng ) ) != 0 )
+ {
+ if( ret != POLARSSL_ERR_MPI_NOT_ACCEPTABLE )
+ goto cleanup;
+
+ MPI_CHK( mpi_add_int( X, X, 2 ) );
+ }
+ }
+ else
+ {
+ MPI_CHK( mpi_sub_int( &Y, X, 1 ) );
+ MPI_CHK( mpi_shift_r( &Y, 1 ) );
+
+ while( 1 )
+ {
+ if( ( ret = mpi_is_prime( X, f_rng, p_rng ) ) == 0 )
+ {
+ if( ( ret = mpi_is_prime( &Y, f_rng, p_rng ) ) == 0 )
+ break;
+
+ if( ret != POLARSSL_ERR_MPI_NOT_ACCEPTABLE )
+ goto cleanup;
+ }
+
+ if( ret != POLARSSL_ERR_MPI_NOT_ACCEPTABLE )
+ goto cleanup;
+
+ MPI_CHK( mpi_add_int( &Y, X, 1 ) );
+ MPI_CHK( mpi_add_int( X, X, 2 ) );
+ MPI_CHK( mpi_shift_r( &Y, 1 ) );
+ }
+ }
+
+cleanup:
+
+ mpi_free( &Y );
+
+ return( ret );
+}
+
+#endif
+
+#if defined(POLARSSL_SELF_TEST)
+
+#define GCD_PAIR_COUNT 3
+
+static const int gcd_pairs[GCD_PAIR_COUNT][3] =
+{
+ { 693, 609, 21 },
+ { 1764, 868, 28 },
+ { 768454923, 542167814, 1 }
+};
+
+/*
+ * Checkup routine
+ */
+int mpi_self_test( int verbose )
+{
+ int ret, i;
+ mpi A, E, N, X, Y, U, V;
+
+ mpi_init( &A ); mpi_init( &E ); mpi_init( &N ); mpi_init( &X );
+ mpi_init( &Y ); mpi_init( &U ); mpi_init( &V );
+
+ MPI_CHK( mpi_read_string( &A, 16,
+ "EFE021C2645FD1DC586E69184AF4A31E" \
+ "D5F53E93B5F123FA41680867BA110131" \
+ "944FE7952E2517337780CB0DB80E61AA" \
+ "E7C8DDC6C5C6AADEB34EB38A2F40D5E6" ) );
+
+ MPI_CHK( mpi_read_string( &E, 16,
+ "B2E7EFD37075B9F03FF989C7C5051C20" \
+ "34D2A323810251127E7BF8625A4F49A5" \
+ "F3E27F4DA8BD59C47D6DAABA4C8127BD" \
+ "5B5C25763222FEFCCFC38B832366C29E" ) );
+
+ MPI_CHK( mpi_read_string( &N, 16,
+ "0066A198186C18C10B2F5ED9B522752A" \
+ "9830B69916E535C8F047518A889A43A5" \
+ "94B6BED27A168D31D4A52F88925AA8F5" ) );
+
+ MPI_CHK( mpi_mul_mpi( &X, &A, &N ) );
+
+ MPI_CHK( mpi_read_string( &U, 16,
+ "602AB7ECA597A3D6B56FF9829A5E8B85" \
+ "9E857EA95A03512E2BAE7391688D264A" \
+ "A5663B0341DB9CCFD2C4C5F421FEC814" \
+ "8001B72E848A38CAE1C65F78E56ABDEF" \
+ "E12D3C039B8A02D6BE593F0BBBDA56F1" \
+ "ECF677152EF804370C1A305CAF3B5BF1" \
+ "30879B56C61DE584A0F53A2447A51E" ) );
+
+ if( verbose != 0 )
+ printf( " MPI test #1 (mul_mpi): " );
+
+ if( mpi_cmp_mpi( &X, &U ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+
+ MPI_CHK( mpi_div_mpi( &X, &Y, &A, &N ) );
+
+ MPI_CHK( mpi_read_string( &U, 16,
+ "256567336059E52CAE22925474705F39A94" ) );
+
+ MPI_CHK( mpi_read_string( &V, 16,
+ "6613F26162223DF488E9CD48CC132C7A" \
+ "0AC93C701B001B092E4E5B9F73BCD27B" \
+ "9EE50D0657C77F374E903CDFA4C642" ) );
+
+ if( verbose != 0 )
+ printf( " MPI test #2 (div_mpi): " );
+
+ if( mpi_cmp_mpi( &X, &U ) != 0 ||
+ mpi_cmp_mpi( &Y, &V ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+
+ MPI_CHK( mpi_exp_mod( &X, &A, &E, &N, NULL ) );
+
+ MPI_CHK( mpi_read_string( &U, 16,
+ "36E139AEA55215609D2816998ED020BB" \
+ "BD96C37890F65171D948E9BC7CBAA4D9" \
+ "325D24D6A3C12710F10A09FA08AB87" ) );
+
+ if( verbose != 0 )
+ printf( " MPI test #3 (exp_mod): " );
+
+ if( mpi_cmp_mpi( &X, &U ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+
+#if defined(POLARSSL_GENPRIME)
+ MPI_CHK( mpi_inv_mod( &X, &A, &N ) );
+
+ MPI_CHK( mpi_read_string( &U, 16,
+ "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \
+ "C3DBA76456363A10869622EAC2DD84EC" \
+ "C5B8A74DAC4D09E03B5E0BE779F2DF61" ) );
+
+ if( verbose != 0 )
+ printf( " MPI test #4 (inv_mod): " );
+
+ if( mpi_cmp_mpi( &X, &U ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed\n" );
+
+ return( 1 );
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+#endif
+
+ if( verbose != 0 )
+ printf( " MPI test #5 (simple gcd): " );
+
+ for ( i = 0; i < GCD_PAIR_COUNT; i++)
+ {
+ MPI_CHK( mpi_lset( &X, gcd_pairs[i][0] ) );
+ MPI_CHK( mpi_lset( &Y, gcd_pairs[i][1] ) );
+
+ MPI_CHK( mpi_gcd( &A, &X, &Y ) );
+
+ if( mpi_cmp_int( &A, gcd_pairs[i][2] ) != 0 )
+ {
+ if( verbose != 0 )
+ printf( "failed at %d\n", i );
+
+ return( 1 );
+ }
+ }
+
+ if( verbose != 0 )
+ printf( "passed\n" );
+
+cleanup:
+
+ if( ret != 0 && verbose != 0 )
+ printf( "Unexpected error, return code = %08X\n", ret );
+
+ mpi_free( &A ); mpi_free( &E ); mpi_free( &N ); mpi_free( &X );
+ mpi_free( &Y ); mpi_free( &U ); mpi_free( &V );
+
+ if( verbose != 0 )
+ printf( "\n" );
+
+ return( ret );
+}
+
+#endif
+
+#endif
diff --git a/protocols/Tlen/crypto/padlock.c b/protocols/Tlen/crypto/padlock.c
new file mode 100644
index 0000000000..2e2e4775ff
--- /dev/null
+++ b/protocols/Tlen/crypto/padlock.c
@@ -0,0 +1,162 @@
+/*
+ * VIA PadLock support functions
+ *
+ * Copyright (C) 2006-2010, Brainspark B.V.
+ *
+ * This file is part of PolarSSL (http://www.polarssl.org)
+ * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+/*
+ * This implementation is based on the VIA PadLock Programming Guide:
+ *
+ * http://www.via.com.tw/en/downloads/whitepapers/initiatives/padlock/
+ * programming_guide.pdf
+ */
+
+#include "polarssl/config.h"
+
+#if defined(POLARSSL_PADLOCK_C)
+
+#include "polarssl/padlock.h"
+
+#if defined(POLARSSL_HAVE_X86)
+
+/*
+ * PadLock detection routine
+ */
+int padlock_supports( int feature )
+{
+ static int flags = -1;
+ int ebx, edx;
+
+ if( flags == -1 )
+ {
+ asm( "movl %%ebx, %0 \n" \
+ "movl $0xC0000000, %%eax \n" \
+ "cpuid \n" \
+ "cmpl $0xC0000001, %%eax \n" \
+ "movl $0, %%edx \n" \
+ "jb unsupported \n" \
+ "movl $0xC0000001, %%eax \n" \
+ "cpuid \n" \
+ "unsupported: \n" \
+ "movl %%edx, %1 \n" \
+ "movl %2, %%ebx \n"
+ : "=m" (ebx), "=m" (edx)
+ : "m" (ebx)
+ : "eax", "ecx", "edx" );
+
+ flags = edx;
+ }
+
+ return( flags & feature );
+}
+
+/*
+ * PadLock AES-ECB block en(de)cryption
+ */
+int padlock_xcryptecb( aes_context *ctx,
+ int mode,
+ const unsigned char input[16],
+ unsigned char output[16] )
+{
+ int ebx;
+ unsigned long *rk;
+ unsigned long *blk;
+ unsigned long *ctrl;
+ unsigned char buf[256];
+
+ rk = ctx->rk;
+ blk = PADLOCK_ALIGN16( buf );
+ memcpy( blk, input, 16 );
+
+ ctrl = blk + 4;
+ *ctrl = 0x80 | ctx->nr | ( ( ctx->nr + ( mode^1 ) - 10 ) << 9 );
+
+ asm( "pushfl; popfl \n" \
+ "movl %%ebx, %0 \n" \
+ "movl $1, %%ecx \n" \
+ "movl %2, %%edx \n" \
+ "movl %3, %%ebx \n" \
+ "movl %4, %%esi \n" \
+ "movl %4, %%edi \n" \
+ ".byte 0xf3,0x0f,0xa7,0xc8\n" \
+ "movl %1, %%ebx \n"
+ : "=m" (ebx)
+ : "m" (ebx), "m" (ctrl), "m" (rk), "m" (blk)
+ : "ecx", "edx", "esi", "edi" );
+
+ memcpy( output, blk, 16 );
+
+ return( 0 );
+}
+
+/*
+ * PadLock AES-CBC buffer en(de)cryption
+ */
+int padlock_xcryptcbc( aes_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output )
+{
+ int ebx;
+ size_t count;
+ unsigned long *rk;
+ unsigned long *iw;
+ unsigned long *ctrl;
+ unsigned char buf[256];
+
+ if( ( (long) input & 15 ) != 0 ||
+ ( (long) output & 15 ) != 0 )
+ return( POLARSSL_ERR_PADLOCK_DATA_MISALIGNED );
+
+ rk = ctx->rk;
+ iw = PADLOCK_ALIGN16( buf );
+ memcpy( iw, iv, 16 );
+
+ ctrl = iw + 4;
+ *ctrl = 0x80 | ctx->nr | ( ( ctx->nr + (mode^1) - 10 ) << 9 );
+
+ count = (length + 15) >> 4;
+
+ asm( "pushfl; popfl \n" \
+ "movl %%ebx, %0 \n" \
+ "movl %2, %%ecx \n" \
+ "movl %3, %%edx \n" \
+ "movl %4, %%ebx \n" \
+ "movl %5, %%esi \n" \
+ "movl %6, %%edi \n" \
+ "movl %7, %%eax \n" \
+ ".byte 0xf3,0x0f,0xa7,0xd0\n" \
+ "movl %1, %%ebx \n"
+ : "=m" (ebx)
+ : "m" (ebx), "m" (count), "m" (ctrl),
+ "m" (rk), "m" (input), "m" (output), "m" (iw)
+ : "eax", "ecx", "edx", "esi", "edi" );
+
+ memcpy( iv, iw, 16 );
+
+ return( 0 );
+}
+
+#endif
+
+#endif
diff --git a/protocols/Tlen/crypto/polarssl/aes.h b/protocols/Tlen/crypto/polarssl/aes.h
new file mode 100644
index 0000000000..efc13daf5b
--- /dev/null
+++ b/protocols/Tlen/crypto/polarssl/aes.h
@@ -0,0 +1,167 @@
+/**
+ * \file aes.h
+ *
+ * \brief AES block cipher
+ *
+ * Copyright (C) 2006-2010, Brainspark B.V.
+ *
+ * This file is part of PolarSSL (http://www.polarssl.org)
+ * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+#ifndef POLARSSL_AES_H
+#define POLARSSL_AES_H
+
+#include <string.h>
+
+#define AES_ENCRYPT 1
+#define AES_DECRYPT 0
+
+#define POLARSSL_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */
+#define POLARSSL_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */
+
+/**
+ * \brief AES context structure
+ */
+typedef struct
+{
+ int nr; /*!< number of rounds */
+ unsigned long *rk; /*!< AES round keys */
+ unsigned long buf[68]; /*!< unaligned data */
+}
+aes_context;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief AES key schedule (encryption)
+ *
+ * \param ctx AES context to be initialized
+ * \param key encryption key
+ * \param keysize must be 128, 192 or 256
+ *
+ * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_KEY_LENGTH
+ */
+int aes_setkey_enc( aes_context *ctx, const unsigned char *key, unsigned int keysize );
+
+/**
+ * \brief AES key schedule (decryption)
+ *
+ * \param ctx AES context to be initialized
+ * \param key decryption key
+ * \param keysize must be 128, 192 or 256
+ *
+ * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_KEY_LENGTH
+ */
+int aes_setkey_dec( aes_context *ctx, const unsigned char *key, unsigned int keysize );
+
+/**
+ * \brief AES-ECB block encryption/decryption
+ *
+ * \param ctx AES context
+ * \param mode AES_ENCRYPT or AES_DECRYPT
+ * \param input 16-byte input block
+ * \param output 16-byte output block
+ *
+ * \return 0 if successful
+ */
+int aes_crypt_ecb( aes_context *ctx,
+ int mode,
+ const unsigned char input[16],
+ unsigned char output[16] );
+
+/**
+ * \brief AES-CBC buffer encryption/decryption
+ * Length should be a multiple of the block
+ * size (16 bytes)
+ *
+ * \param ctx AES context
+ * \param mode AES_ENCRYPT or AES_DECRYPT
+ * \param length length of the input data
+ * \param iv initialization vector (updated after use)
+ * \param input buffer holding the input data
+ * \param output buffer holding the output data
+ *
+ * \return 0 if successful, or POLARSSL_ERR_AES_INVALID_INPUT_LENGTH
+ */
+int aes_crypt_cbc( aes_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output );
+
+/**
+ * \brief AES-CFB128 buffer encryption/decryption.
+ *
+ * \param ctx AES context
+ * \param mode AES_ENCRYPT or AES_DECRYPT
+ * \param length length of the input data
+ * \param iv_off offset in IV (updated after use)
+ * \param iv initialization vector (updated after use)
+ * \param input buffer holding the input data
+ * \param output buffer holding the output data
+ *
+ * \return 0 if successful
+ */
+int aes_crypt_cfb128( aes_context *ctx,
+ int mode,
+ size_t length,
+ size_t *iv_off,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output );
+
+/*
+ * \brief AES-CTR buffer encryption/decryption
+ *
+ * Warning: You have to keep the maximum use of your counter in mind!
+ *
+ * \param length The length of the data
+ * \param nc_off The offset in the current stream_block (for resuming
+ * within current cipher stream). The offset pointer to
+ * should be 0 at the start of a stream.
+ * \param nonce_counter The 128-bit nonce and counter.
+ * \param stream_block The saved stream-block for resuming. Is overwritten
+ * by the function.
+ * \param input The input data stream
+ * \param output The output data stream
+ *
+ * \return 0 if successful
+ */
+int aes_crypt_ctr( aes_context *ctx,
+ size_t length,
+ size_t *nc_off,
+ unsigned char nonce_counter[16],
+ unsigned char stream_block[16],
+ const unsigned char *input,
+ unsigned char *output );
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ */
+int aes_self_test( int verbose );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* aes.h */
diff --git a/protocols/Tlen/crypto/polarssl/bignum.h b/protocols/Tlen/crypto/polarssl/bignum.h
new file mode 100644
index 0000000000..7938406708
--- /dev/null
+++ b/protocols/Tlen/crypto/polarssl/bignum.h
@@ -0,0 +1,587 @@
+/**
+ * \file bignum.h
+ *
+ * \brief Multi-precision integer library
+ *
+ * Copyright (C) 2006-2010, Brainspark B.V.
+ *
+ * This file is part of PolarSSL (http://www.polarssl.org)
+ * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+#ifndef POLARSSL_BIGNUM_H
+#define POLARSSL_BIGNUM_H
+
+#include <stdio.h>
+#include <string.h>
+
+#define POLARSSL_ERR_MPI_FILE_IO_ERROR -0x0002 /**< An error occurred while reading from or writing to a file. */
+#define POLARSSL_ERR_MPI_BAD_INPUT_DATA -0x0004 /**< Bad input parameters to function. */
+#define POLARSSL_ERR_MPI_INVALID_CHARACTER -0x0006 /**< There is an invalid character in the digit string. */
+#define POLARSSL_ERR_MPI_BUFFER_TOO_SMALL -0x0008 /**< The output buffer is too small to write too. */
+#define POLARSSL_ERR_MPI_NEGATIVE_VALUE -0x000A /**< The input arguments are negative or result in illegal output. */
+#define POLARSSL_ERR_MPI_DIVISION_BY_ZERO -0x000C /**< The input argument for division is zero, which is not allowed. */
+#define POLARSSL_ERR_MPI_NOT_ACCEPTABLE -0x000E /**< The input arguments are not acceptable. */
+
+#define MPI_CHK(f) if( ( ret = f ) != 0 ) goto cleanup
+
+/*
+ * Maximum size MPIs are allowed to grow to in number of limbs.
+ */
+#define POLARSSL_MPI_MAX_LIMBS 10000
+
+/*
+ * Define the base integer type, architecture-wise
+ */
+#if defined(POLARSSL_HAVE_INT8)
+typedef signed char t_sint;
+typedef unsigned char t_uint;
+typedef unsigned short t_udbl;
+#else
+#if defined(POLARSSL_HAVE_INT16)
+typedef signed short t_sint;
+typedef unsigned short t_uint;
+typedef unsigned long t_udbl;
+#else
+ typedef signed long t_sint;
+ typedef unsigned long t_uint;
+ #if defined(_MSC_VER) && defined(_M_IX86)
+ typedef unsigned __int64 t_udbl;
+ #else
+ #if defined(__amd64__) || defined(__x86_64__) || \
+ defined(__ppc64__) || defined(__powerpc64__) || \
+ defined(__ia64__) || defined(__alpha__)
+ typedef unsigned int t_udbl __attribute__((mode(TI)));
+ #else
+ #if defined(POLARSSL_HAVE_LONGLONG)
+ typedef unsigned long long t_udbl;
+ #endif
+ #endif
+ #endif
+#endif
+#endif
+
+/**
+ * \brief MPI structure
+ */
+typedef struct
+{
+ int s; /*!< integer sign */
+ size_t n; /*!< total # of limbs */
+ t_uint *p; /*!< pointer to limbs */
+}
+mpi;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Initialize one MPI
+ *
+ * \param X One MPI to initialize.
+ */
+void mpi_init( mpi *X );
+
+/**
+ * \brief Unallocate one MPI
+ *
+ * \param X One MPI to unallocate.
+ */
+void mpi_free( mpi *X );
+
+/**
+ * \brief Enlarge to the specified number of limbs
+ *
+ * \param X MPI to grow
+ * \param nblimbs The target number of limbs
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_grow( mpi *X, size_t nblimbs );
+
+/**
+ * \brief Copy the contents of Y into X
+ *
+ * \param X Destination MPI
+ * \param Y Source MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_copy( mpi *X, const mpi *Y );
+
+/**
+ * \brief Swap the contents of X and Y
+ *
+ * \param X First MPI value
+ * \param Y Second MPI value
+ */
+void mpi_swap( mpi *X, mpi *Y );
+
+/**
+ * \brief Set value from integer
+ *
+ * \param X MPI to set
+ * \param z Value to use
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_lset( mpi *X, t_sint z );
+
+/*
+ * \brief Get a specific bit from X
+ *
+ * \param X MPI to use
+ * \param pos Zero-based index of the bit in X
+ *
+ * \return Either a 0 or a 1
+ */
+int mpi_get_bit( mpi *X, size_t pos );
+
+/*
+ * \brief Set a bit of X to a specific value of 0 or 1
+ *
+ * \note Will grow X if necessary to set a bit to 1 in a not yet
+ * existing limb. Will not grow if bit should be set to 0
+ *
+ * \param X MPI to use
+ * \param pos Zero-based index of the bit in X
+ * \param val The value to set the bit to (0 or 1)
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_BAD_INPUT_DATA if val is not 0 or 1
+ */
+int mpi_set_bit( mpi *X, size_t pos, unsigned char val );
+
+/**
+ * \brief Return the number of least significant bits
+ *
+ * \param X MPI to use
+ */
+size_t mpi_lsb( const mpi *X );
+
+/**
+ * \brief Return the number of most significant bits
+ *
+ * \param X MPI to use
+ */
+size_t mpi_msb( const mpi *X );
+
+/**
+ * \brief Return the total size in bytes
+ *
+ * \param X MPI to use
+ */
+size_t mpi_size( const mpi *X );
+
+/**
+ * \brief Import from an ASCII string
+ *
+ * \param X Destination MPI
+ * \param radix Input numeric base
+ * \param s Null-terminated string buffer
+ *
+ * \return 0 if successful, or an POLARSSL_ERR_MPI_XXX error code
+ */
+int mpi_read_string( mpi *X, int radix, const char *s );
+
+/**
+ * \brief Export into an ASCII string
+ *
+ * \param X Source MPI
+ * \param radix Output numeric base
+ * \param s String buffer
+ * \param slen String buffer size
+ *
+ * \return 0 if successful, or an POLARSSL_ERR_MPI_XXX error code.
+ * *slen is always updated to reflect the amount
+ * of data that has (or would have) been written.
+ *
+ * \note Call this function with *slen = 0 to obtain the
+ * minimum required buffer size in *slen.
+ */
+int mpi_write_string( const mpi *X, int radix, char *s, size_t *slen );
+
+/**
+ * \brief Read X from an opened file
+ *
+ * \param X Destination MPI
+ * \param radix Input numeric base
+ * \param fin Input file handle
+ *
+ * \return 0 if successful, or an POLARSSL_ERR_MPI_XXX error code
+ */
+int mpi_read_file( mpi *X, int radix, FILE *fin );
+
+/**
+ * \brief Write X into an opened file, or stdout if fout is NULL
+ *
+ * \param p Prefix, can be NULL
+ * \param X Source MPI
+ * \param radix Output numeric base
+ * \param fout Output file handle (can be NULL)
+ *
+ * \return 0 if successful, or an POLARSSL_ERR_MPI_XXX error code
+ *
+ * \note Set fout == NULL to print X on the console.
+ */
+int mpi_write_file( const char *p, const mpi *X, int radix, FILE *fout );
+
+/**
+ * \brief Import X from unsigned binary data, big endian
+ *
+ * \param X Destination MPI
+ * \param buf Input buffer
+ * \param buflen Input buffer size
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_read_binary( mpi *X, const unsigned char *buf, size_t buflen );
+
+/**
+ * \brief Export X into unsigned binary data, big endian
+ *
+ * \param X Source MPI
+ * \param buf Output buffer
+ * \param buflen Output buffer size
+ *
+ * \return 0 if successful,
+ * POLARSSL_ERR_MPI_BUFFER_TOO_SMALL if buf isn't large enough
+ */
+int mpi_write_binary( const mpi *X, unsigned char *buf, size_t buflen );
+
+/**
+ * \brief Left-shift: X <<= count
+ *
+ * \param X MPI to shift
+ * \param count Amount to shift
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_shift_l( mpi *X, size_t count );
+
+/**
+ * \brief Right-shift: X >>= count
+ *
+ * \param X MPI to shift
+ * \param count Amount to shift
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_shift_r( mpi *X, size_t count );
+
+/**
+ * \brief Compare unsigned values
+ *
+ * \param X Left-hand MPI
+ * \param Y Right-hand MPI
+ *
+ * \return 1 if |X| is greater than |Y|,
+ * -1 if |X| is lesser than |Y| or
+ * 0 if |X| is equal to |Y|
+ */
+int mpi_cmp_abs( const mpi *X, const mpi *Y );
+
+/**
+ * \brief Compare signed values
+ *
+ * \param X Left-hand MPI
+ * \param Y Right-hand MPI
+ *
+ * \return 1 if X is greater than Y,
+ * -1 if X is lesser than Y or
+ * 0 if X is equal to Y
+ */
+int mpi_cmp_mpi( const mpi *X, const mpi *Y );
+
+/**
+ * \brief Compare signed values
+ *
+ * \param X Left-hand MPI
+ * \param z The integer value to compare to
+ *
+ * \return 1 if X is greater than z,
+ * -1 if X is lesser than z or
+ * 0 if X is equal to z
+ */
+int mpi_cmp_int( const mpi *X, t_sint z );
+
+/**
+ * \brief Unsigned addition: X = |A| + |B|
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param B Right-hand MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_add_abs( mpi *X, const mpi *A, const mpi *B );
+
+/**
+ * \brief Unsigned substraction: X = |A| - |B|
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param B Right-hand MPI
+ *
+ * \return 0 if successful,
+ * POLARSSL_ERR_MPI_NEGATIVE_VALUE if B is greater than A
+ */
+int mpi_sub_abs( mpi *X, const mpi *A, const mpi *B );
+
+/**
+ * \brief Signed addition: X = A + B
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param B Right-hand MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_add_mpi( mpi *X, const mpi *A, const mpi *B );
+
+/**
+ * \brief Signed substraction: X = A - B
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param B Right-hand MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_sub_mpi( mpi *X, const mpi *A, const mpi *B );
+
+/**
+ * \brief Signed addition: X = A + b
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param b The integer value to add
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_add_int( mpi *X, const mpi *A, t_sint b );
+
+/**
+ * \brief Signed substraction: X = A - b
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param b The integer value to subtract
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_sub_int( mpi *X, const mpi *A, t_sint b );
+
+/**
+ * \brief Baseline multiplication: X = A * B
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param B Right-hand MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_mul_mpi( mpi *X, const mpi *A, const mpi *B );
+
+/**
+ * \brief Baseline multiplication: X = A * b
+ * Note: b is an unsigned integer type, thus
+ * Negative values of b are ignored.
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param b The integer value to multiply with
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_mul_int( mpi *X, const mpi *A, t_sint b );
+
+/**
+ * \brief Division by mpi: A = Q * B + R
+ *
+ * \param Q Destination MPI for the quotient
+ * \param R Destination MPI for the rest value
+ * \param A Left-hand MPI
+ * \param B Right-hand MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0
+ *
+ * \note Either Q or R can be NULL.
+ */
+int mpi_div_mpi( mpi *Q, mpi *R, const mpi *A, const mpi *B );
+
+/**
+ * \brief Division by int: A = Q * b + R
+ *
+ * \param Q Destination MPI for the quotient
+ * \param R Destination MPI for the rest value
+ * \param A Left-hand MPI
+ * \param b Integer to divide by
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0
+ *
+ * \note Either Q or R can be NULL.
+ */
+int mpi_div_int( mpi *Q, mpi *R, const mpi *A, t_sint b );
+
+/**
+ * \brief Modulo: R = A mod B
+ *
+ * \param R Destination MPI for the rest value
+ * \param A Left-hand MPI
+ * \param B Right-hand MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if B == 0,
+ * POLARSSL_ERR_MPI_NEGATIVE_VALUE if B < 0
+ */
+int mpi_mod_mpi( mpi *R, const mpi *A, const mpi *B );
+
+/**
+ * \brief Modulo: r = A mod b
+ *
+ * \param r Destination t_uint
+ * \param A Left-hand MPI
+ * \param b Integer to divide by
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_DIVISION_BY_ZERO if b == 0,
+ * POLARSSL_ERR_MPI_NEGATIVE_VALUE if b < 0
+ */
+int mpi_mod_int( t_uint *r, const mpi *A, t_sint b );
+
+/**
+ * \brief Sliding-window exponentiation: X = A^E mod N
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param E Exponent MPI
+ * \param N Modular MPI
+ * \param _RR Speed-up MPI used for recalculations
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or even
+ *
+ * \note _RR is used to avoid re-computing R*R mod N across
+ * multiple calls, which speeds up things a bit. It can
+ * be set to NULL if the extra performance is unneeded.
+ */
+int mpi_exp_mod( mpi *X, const mpi *A, const mpi *E, const mpi *N, mpi *_RR );
+
+/**
+ * \brief Fill an MPI X with size bytes of random
+ *
+ * \param X Destination MPI
+ * \param size Size in bytes
+ * \param f_rng RNG function
+ * \param p_rng RNG parameter
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_fill_random( mpi *X, size_t size, int (*f_rng)(void *), void *p_rng );
+
+/**
+ * \brief Greatest common divisor: G = gcd(A, B)
+ *
+ * \param G Destination MPI
+ * \param A Left-hand MPI
+ * \param B Right-hand MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed
+ */
+int mpi_gcd( mpi *G, const mpi *A, const mpi *B );
+
+/**
+ * \brief Modular inverse: X = A^-1 mod N
+ *
+ * \param X Destination MPI
+ * \param A Left-hand MPI
+ * \param N Right-hand MPI
+ *
+ * \return 0 if successful,
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_BAD_INPUT_DATA if N is negative or nil
+ POLARSSL_ERR_MPI_NOT_ACCEPTABLE if A has no inverse mod N
+ */
+int mpi_inv_mod( mpi *X, const mpi *A, const mpi *N );
+
+/**
+ * \brief Miller-Rabin primality test
+ *
+ * \param X MPI to check
+ * \param f_rng RNG function
+ * \param p_rng RNG parameter
+ *
+ * \return 0 if successful (probably prime),
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_NOT_ACCEPTABLE if X is not prime
+ */
+int mpi_is_prime( mpi *X, int (*f_rng)(void *), void *p_rng );
+
+/**
+ * \brief Prime number generation
+ *
+ * \param X Destination MPI
+ * \param nbits Required size of X in bits ( 3 <= nbits <= 4096 )
+ * \param dh_flag If 1, then (X-1)/2 will be prime too
+ * \param f_rng RNG function
+ * \param p_rng RNG parameter
+ *
+ * \return 0 if successful (probably prime),
+ * 1 if memory allocation failed,
+ * POLARSSL_ERR_MPI_BAD_INPUT_DATA if nbits is < 3
+ */
+int mpi_gen_prime( mpi *X, size_t nbits, int dh_flag,
+ int (*f_rng)(void *), void *p_rng );
+
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ */
+int mpi_self_test( int verbose );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* bignum.h */
diff --git a/protocols/Tlen/crypto/polarssl/bn_mul.h b/protocols/Tlen/crypto/polarssl/bn_mul.h
new file mode 100644
index 0000000000..59a32857cb
--- /dev/null
+++ b/protocols/Tlen/crypto/polarssl/bn_mul.h
@@ -0,0 +1,738 @@
+/**
+ * \file bn_mul.h
+ *
+ * \brief Multi-precision integer library
+ *
+ * Copyright (C) 2006-2010, Brainspark B.V.
+ *
+ * This file is part of PolarSSL (http://www.polarssl.org)
+ * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+/*
+ * Multiply source vector [s] with b, add result
+ * to destination vector [d] and set carry c.
+ *
+ * Currently supports:
+ *
+ * . IA-32 (386+) . AMD64 / EM64T
+ * . IA-32 (SSE2) . Motorola 68000
+ * . PowerPC, 32-bit . MicroBlaze
+ * . PowerPC, 64-bit . TriCore
+ * . SPARC v8 . ARM v3+
+ * . Alpha . MIPS32
+ * . C, longlong . C, generic
+ */
+#ifndef POLARSSL_BN_MUL_H
+#define POLARSSL_BN_MUL_H
+
+#include "polarssl/config.h"
+
+#if defined(POLARSSL_HAVE_ASM)
+
+#if defined(__GNUC__)
+#if defined(__i386__)
+
+#define MULADDC_INIT \
+ asm( " \
+ movl %%ebx, %0; \
+ movl %5, %%esi; \
+ movl %6, %%edi; \
+ movl %7, %%ecx; \
+ movl %8, %%ebx; \
+ "
+
+#define MULADDC_CORE \
+ " \
+ lodsl; \
+ mull %%ebx; \
+ addl %%ecx, %%eax; \
+ adcl $0, %%edx; \
+ addl (%%edi), %%eax; \
+ adcl $0, %%edx; \
+ movl %%edx, %%ecx; \
+ stosl; \
+ "
+
+#if defined(POLARSSL_HAVE_SSE2)
+
+#define MULADDC_HUIT \
+ " \
+ movd %%ecx, %%mm1; \
+ movd %%ebx, %%mm0; \
+ movd (%%edi), %%mm3; \
+ paddq %%mm3, %%mm1; \
+ movd (%%esi), %%mm2; \
+ pmuludq %%mm0, %%mm2; \
+ movd 4(%%esi), %%mm4; \
+ pmuludq %%mm0, %%mm4; \
+ movd 8(%%esi), %%mm6; \
+ pmuludq %%mm0, %%mm6; \
+ movd 12(%%esi), %%mm7; \
+ pmuludq %%mm0, %%mm7; \
+ paddq %%mm2, %%mm1; \
+ movd 4(%%edi), %%mm3; \
+ paddq %%mm4, %%mm3; \
+ movd 8(%%edi), %%mm5; \
+ paddq %%mm6, %%mm5; \
+ movd 12(%%edi), %%mm4; \
+ paddq %%mm4, %%mm7; \
+ movd %%mm1, (%%edi); \
+ movd 16(%%esi), %%mm2; \
+ pmuludq %%mm0, %%mm2; \
+ psrlq $32, %%mm1; \
+ movd 20(%%esi), %%mm4; \
+ pmuludq %%mm0, %%mm4; \
+ paddq %%mm3, %%mm1; \
+ movd 24(%%esi), %%mm6; \
+ pmuludq %%mm0, %%mm6; \
+ movd %%mm1, 4(%%edi); \
+ psrlq $32, %%mm1; \
+ movd 28(%%esi), %%mm3; \
+ pmuludq %%mm0, %%mm3; \
+ paddq %%mm5, %%mm1; \
+ movd 16(%%edi), %%mm5; \
+ paddq %%mm5, %%mm2; \
+ movd %%mm1, 8(%%edi); \
+ psrlq $32, %%mm1; \
+ paddq %%mm7, %%mm1; \
+ movd 20(%%edi), %%mm5; \
+ paddq %%mm5, %%mm4; \
+ movd %%mm1, 12(%%edi); \
+ psrlq $32, %%mm1; \
+ paddq %%mm2, %%mm1; \
+ movd 24(%%edi), %%mm5; \
+ paddq %%mm5, %%mm6; \
+ movd %%mm1, 16(%%edi); \
+ psrlq $32, %%mm1; \
+ paddq %%mm4, %%mm1; \
+ movd 28(%%edi), %%mm5; \
+ paddq %%mm5, %%mm3; \
+ movd %%mm1, 20(%%edi); \
+ psrlq $32, %%mm1; \
+ paddq %%mm6, %%mm1; \
+ movd %%mm1, 24(%%edi); \
+ psrlq $32, %%mm1; \
+ paddq %%mm3, %%mm1; \
+ movd %%mm1, 28(%%edi); \
+ addl $32, %%edi; \
+ addl $32, %%esi; \
+ psrlq $32, %%mm1; \
+ movd %%mm1, %%ecx; \
+ "
+
+#define MULADDC_STOP \
+ " \
+ emms; \
+ movl %4, %%ebx; \
+ movl %%ecx, %1; \
+ movl %%edi, %2; \
+ movl %%esi, %3; \
+ " \
+ : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \
+ : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \
+ : "eax", "ecx", "edx", "esi", "edi" \
+ );
+
+#else
+
+#define MULADDC_STOP \
+ " \
+ movl %4, %%ebx; \
+ movl %%ecx, %1; \
+ movl %%edi, %2; \
+ movl %%esi, %3; \
+ " \
+ : "=m" (t), "=m" (c), "=m" (d), "=m" (s) \
+ : "m" (t), "m" (s), "m" (d), "m" (c), "m" (b) \
+ : "eax", "ecx", "edx", "esi", "edi" \
+ );
+#endif /* SSE2 */
+#endif /* i386 */
+
+#if defined(__amd64__) || defined (__x86_64__)
+
+#define MULADDC_INIT \
+ asm( "movq %0, %%rsi " :: "m" (s)); \
+ asm( "movq %0, %%rdi " :: "m" (d)); \
+ asm( "movq %0, %%rcx " :: "m" (c)); \
+ asm( "movq %0, %%rbx " :: "m" (b)); \
+ asm( "xorq %r8, %r8 " );
+
+#define MULADDC_CORE \
+ asm( "movq (%rsi),%rax " ); \
+ asm( "mulq %rbx " ); \
+ asm( "addq $8, %rsi " ); \
+ asm( "addq %rcx, %rax " ); \
+ asm( "movq %r8, %rcx " ); \
+ asm( "adcq $0, %rdx " ); \
+ asm( "nop " ); \
+ asm( "addq %rax, (%rdi) " ); \
+ asm( "adcq %rdx, %rcx " ); \
+ asm( "addq $8, %rdi " );
+
+#define MULADDC_STOP \
+ asm( "movq %%rcx, %0 " : "=m" (c)); \
+ asm( "movq %%rdi, %0 " : "=m" (d)); \
+ asm( "movq %%rsi, %0 " : "=m" (s) :: \
+ "rax", "rcx", "rdx", "rbx", "rsi", "rdi", "r8" );
+
+#endif /* AMD64 */
+
+#if defined(__mc68020__) || defined(__mcpu32__)
+
+#define MULADDC_INIT \
+ asm( "movl %0, %%a2 " :: "m" (s)); \
+ asm( "movl %0, %%a3 " :: "m" (d)); \
+ asm( "movl %0, %%d3 " :: "m" (c)); \
+ asm( "movl %0, %%d2 " :: "m" (b)); \
+ asm( "moveq #0, %d0 " );
+
+#define MULADDC_CORE \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d4:%d1 " ); \
+ asm( "addl %d3, %d1 " ); \
+ asm( "addxl %d0, %d4 " ); \
+ asm( "moveq #0, %d3 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "addxl %d4, %d3 " );
+
+#define MULADDC_STOP \
+ asm( "movl %%d3, %0 " : "=m" (c)); \
+ asm( "movl %%a3, %0 " : "=m" (d)); \
+ asm( "movl %%a2, %0 " : "=m" (s) :: \
+ "d0", "d1", "d2", "d3", "d4", "a2", "a3" );
+
+#define MULADDC_HUIT \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d4:%d1 " ); \
+ asm( "addxl %d3, %d1 " ); \
+ asm( "addxl %d0, %d4 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d3:%d1 " ); \
+ asm( "addxl %d4, %d1 " ); \
+ asm( "addxl %d0, %d3 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d4:%d1 " ); \
+ asm( "addxl %d3, %d1 " ); \
+ asm( "addxl %d0, %d4 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d3:%d1 " ); \
+ asm( "addxl %d4, %d1 " ); \
+ asm( "addxl %d0, %d3 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d4:%d1 " ); \
+ asm( "addxl %d3, %d1 " ); \
+ asm( "addxl %d0, %d4 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d3:%d1 " ); \
+ asm( "addxl %d4, %d1 " ); \
+ asm( "addxl %d0, %d3 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d4:%d1 " ); \
+ asm( "addxl %d3, %d1 " ); \
+ asm( "addxl %d0, %d4 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "movel %a2@+, %d1 " ); \
+ asm( "mulul %d2, %d3:%d1 " ); \
+ asm( "addxl %d4, %d1 " ); \
+ asm( "addxl %d0, %d3 " ); \
+ asm( "addl %d1, %a3@+ " ); \
+ asm( "addxl %d0, %d3 " );
+
+#endif /* MC68000 */
+
+#if defined(__powerpc__) || defined(__ppc__)
+#if defined(__powerpc64__) || defined(__ppc64__)
+
+#if defined(__MACH__) && defined(__APPLE__)
+
+#define MULADDC_INIT \
+ asm( "ld r3, %0 " :: "m" (s)); \
+ asm( "ld r4, %0 " :: "m" (d)); \
+ asm( "ld r5, %0 " :: "m" (c)); \
+ asm( "ld r6, %0 " :: "m" (b)); \
+ asm( "addi r3, r3, -8 " ); \
+ asm( "addi r4, r4, -8 " ); \
+ asm( "addic r5, r5, 0 " );
+
+#define MULADDC_CORE \
+ asm( "ldu r7, 8(r3) " ); \
+ asm( "mulld r8, r7, r6 " ); \
+ asm( "mulhdu r9, r7, r6 " ); \
+ asm( "adde r8, r8, r5 " ); \
+ asm( "ld r7, 8(r4) " ); \
+ asm( "addze r5, r9 " ); \
+ asm( "addc r8, r8, r7 " ); \
+ asm( "stdu r8, 8(r4) " );
+
+#define MULADDC_STOP \
+ asm( "addze r5, r5 " ); \
+ asm( "addi r4, r4, 8 " ); \
+ asm( "addi r3, r3, 8 " ); \
+ asm( "std r5, %0 " : "=m" (c)); \
+ asm( "std r4, %0 " : "=m" (d)); \
+ asm( "std r3, %0 " : "=m" (s) :: \
+ "r3", "r4", "r5", "r6", "r7", "r8", "r9" );
+
+#else
+
+#define MULADDC_INIT \
+ asm( "ld %%r3, %0 " :: "m" (s)); \
+ asm( "ld %%r4, %0 " :: "m" (d)); \
+ asm( "ld %%r5, %0 " :: "m" (c)); \
+ asm( "ld %%r6, %0 " :: "m" (b)); \
+ asm( "addi %r3, %r3, -8 " ); \
+ asm( "addi %r4, %r4, -8 " ); \
+ asm( "addic %r5, %r5, 0 " );
+
+#define MULADDC_CORE \
+ asm( "ldu %r7, 8(%r3) " ); \
+ asm( "mulld %r8, %r7, %r6 " ); \
+ asm( "mulhdu %r9, %r7, %r6 " ); \
+ asm( "adde %r8, %r8, %r5 " ); \
+ asm( "ld %r7, 8(%r4) " ); \
+ asm( "addze %r5, %r9 " ); \
+ asm( "addc %r8, %r8, %r7 " ); \
+ asm( "stdu %r8, 8(%r4) " );
+
+#define MULADDC_STOP \
+ asm( "addze %r5, %r5 " ); \
+ asm( "addi %r4, %r4, 8 " ); \
+ asm( "addi %r3, %r3, 8 " ); \
+ asm( "std %%r5, %0 " : "=m" (c)); \
+ asm( "std %%r4, %0 " : "=m" (d)); \
+ asm( "std %%r3, %0 " : "=m" (s) :: \
+ "r3", "r4", "r5", "r6", "r7", "r8", "r9" );
+
+#endif
+
+#else /* PPC32 */
+
+#if defined(__MACH__) && defined(__APPLE__)
+
+#define MULADDC_INIT \
+ asm( "lwz r3, %0 " :: "m" (s)); \
+ asm( "lwz r4, %0 " :: "m" (d)); \
+ asm( "lwz r5, %0 " :: "m" (c)); \
+ asm( "lwz r6, %0 " :: "m" (b)); \
+ asm( "addi r3, r3, -4 " ); \
+ asm( "addi r4, r4, -4 " ); \
+ asm( "addic r5, r5, 0 " );
+
+#define MULADDC_CORE \
+ asm( "lwzu r7, 4(r3) " ); \
+ asm( "mullw r8, r7, r6 " ); \
+ asm( "mulhwu r9, r7, r6 " ); \
+ asm( "adde r8, r8, r5 " ); \
+ asm( "lwz r7, 4(r4) " ); \
+ asm( "addze r5, r9 " ); \
+ asm( "addc r8, r8, r7 " ); \
+ asm( "stwu r8, 4(r4) " );
+
+#define MULADDC_STOP \
+ asm( "addze r5, r5 " ); \
+ asm( "addi r4, r4, 4 " ); \
+ asm( "addi r3, r3, 4 " ); \
+ asm( "stw r5, %0 " : "=m" (c)); \
+ asm( "stw r4, %0 " : "=m" (d)); \
+ asm( "stw r3, %0 " : "=m" (s) :: \
+ "r3", "r4", "r5", "r6", "r7", "r8", "r9" );
+
+#else
+
+#define MULADDC_INIT \
+ asm( "lwz %%r3, %0 " :: "m" (s)); \
+ asm( "lwz %%r4, %0 " :: "m" (d)); \
+ asm( "lwz %%r5, %0 " :: "m" (c)); \
+ asm( "lwz %%r6, %0 " :: "m" (b)); \
+ asm( "addi %r3, %r3, -4 " ); \
+ asm( "addi %r4, %r4, -4 " ); \
+ asm( "addic %r5, %r5, 0 " );
+
+#define MULADDC_CORE \
+ asm( "lwzu %r7, 4(%r3) " ); \
+ asm( "mullw %r8, %r7, %r6 " ); \
+ asm( "mulhwu %r9, %r7, %r6 " ); \
+ asm( "adde %r8, %r8, %r5 " ); \
+ asm( "lwz %r7, 4(%r4) " ); \
+ asm( "addze %r5, %r9 " ); \
+ asm( "addc %r8, %r8, %r7 " ); \
+ asm( "stwu %r8, 4(%r4) " );
+
+#define MULADDC_STOP \
+ asm( "addze %r5, %r5 " ); \
+ asm( "addi %r4, %r4, 4 " ); \
+ asm( "addi %r3, %r3, 4 " ); \
+ asm( "stw %%r5, %0 " : "=m" (c)); \
+ asm( "stw %%r4, %0 " : "=m" (d)); \
+ asm( "stw %%r3, %0 " : "=m" (s) :: \
+ "r3", "r4", "r5", "r6", "r7", "r8", "r9" );
+
+#endif
+
+#endif /* PPC32 */
+#endif /* PPC64 */
+
+#if defined(__sparc__)
+
+#define MULADDC_INIT \
+ asm( "ld %0, %%o0 " :: "m" (s)); \
+ asm( "ld %0, %%o1 " :: "m" (d)); \
+ asm( "ld %0, %%o2 " :: "m" (c)); \
+ asm( "ld %0, %%o3 " :: "m" (b));
+
+#define MULADDC_CORE \
+ asm( "ld [%o0], %o4 " ); \
+ asm( "inc 4, %o0 " ); \
+ asm( "ld [%o1], %o5 " ); \
+ asm( "umul %o3, %o4, %o4 " ); \
+ asm( "addcc %o4, %o2, %o4 " ); \
+ asm( "rd %y, %g1 " ); \
+ asm( "addx %g1, 0, %g1 " ); \
+ asm( "addcc %o4, %o5, %o4 " ); \
+ asm( "st %o4, [%o1] " ); \
+ asm( "addx %g1, 0, %o2 " ); \
+ asm( "inc 4, %o1 " );
+
+#define MULADDC_STOP \
+ asm( "st %%o2, %0 " : "=m" (c)); \
+ asm( "st %%o1, %0 " : "=m" (d)); \
+ asm( "st %%o0, %0 " : "=m" (s) :: \
+ "g1", "o0", "o1", "o2", "o3", "o4", "o5" );
+
+#endif /* SPARCv8 */
+
+#if defined(__microblaze__) || defined(microblaze)
+
+#define MULADDC_INIT \
+ asm( "lwi r3, %0 " :: "m" (s)); \
+ asm( "lwi r4, %0 " :: "m" (d)); \
+ asm( "lwi r5, %0 " :: "m" (c)); \
+ asm( "lwi r6, %0 " :: "m" (b)); \
+ asm( "andi r7, r6, 0xffff" ); \
+ asm( "bsrli r6, r6, 16 " );
+
+#define MULADDC_CORE \
+ asm( "lhui r8, r3, 0 " ); \
+ asm( "addi r3, r3, 2 " ); \
+ asm( "lhui r9, r3, 0 " ); \
+ asm( "addi r3, r3, 2 " ); \
+ asm( "mul r10, r9, r6 " ); \
+ asm( "mul r11, r8, r7 " ); \
+ asm( "mul r12, r9, r7 " ); \
+ asm( "mul r13, r8, r6 " ); \
+ asm( "bsrli r8, r10, 16 " ); \
+ asm( "bsrli r9, r11, 16 " ); \
+ asm( "add r13, r13, r8 " ); \
+ asm( "add r13, r13, r9 " ); \
+ asm( "bslli r10, r10, 16 " ); \
+ asm( "bslli r11, r11, 16 " ); \
+ asm( "add r12, r12, r10 " ); \
+ asm( "addc r13, r13, r0 " ); \
+ asm( "add r12, r12, r11 " ); \
+ asm( "addc r13, r13, r0 " ); \
+ asm( "lwi r10, r4, 0 " ); \
+ asm( "add r12, r12, r10 " ); \
+ asm( "addc r13, r13, r0 " ); \
+ asm( "add r12, r12, r5 " ); \
+ asm( "addc r5, r13, r0 " ); \
+ asm( "swi r12, r4, 0 " ); \
+ asm( "addi r4, r4, 4 " );
+
+#define MULADDC_STOP \
+ asm( "swi r5, %0 " : "=m" (c)); \
+ asm( "swi r4, %0 " : "=m" (d)); \
+ asm( "swi r3, %0 " : "=m" (s) :: \
+ "r3", "r4" , "r5" , "r6" , "r7" , "r8" , \
+ "r9", "r10", "r11", "r12", "r13" );
+
+#endif /* MicroBlaze */
+
+#if defined(__tricore__)
+
+#define MULADDC_INIT \
+ asm( "ld.a %%a2, %0 " :: "m" (s)); \
+ asm( "ld.a %%a3, %0 " :: "m" (d)); \
+ asm( "ld.w %%d4, %0 " :: "m" (c)); \
+ asm( "ld.w %%d1, %0 " :: "m" (b)); \
+ asm( "xor %d5, %d5 " );
+
+#define MULADDC_CORE \
+ asm( "ld.w %d0, [%a2+] " ); \
+ asm( "madd.u %e2, %e4, %d0, %d1 " ); \
+ asm( "ld.w %d0, [%a3] " ); \
+ asm( "addx %d2, %d2, %d0 " ); \
+ asm( "addc %d3, %d3, 0 " ); \
+ asm( "mov %d4, %d3 " ); \
+ asm( "st.w [%a3+], %d2 " );
+
+#define MULADDC_STOP \
+ asm( "st.w %0, %%d4 " : "=m" (c)); \
+ asm( "st.a %0, %%a3 " : "=m" (d)); \
+ asm( "st.a %0, %%a2 " : "=m" (s) :: \
+ "d0", "d1", "e2", "d4", "a2", "a3" );
+
+#endif /* TriCore */
+
+#if defined(__arm__)
+
+#define MULADDC_INIT \
+ asm( "ldr r0, %0 " :: "m" (s)); \
+ asm( "ldr r1, %0 " :: "m" (d)); \
+ asm( "ldr r2, %0 " :: "m" (c)); \
+ asm( "ldr r3, %0 " :: "m" (b));
+
+#define MULADDC_CORE \
+ asm( "ldr r4, [r0], #4 " ); \
+ asm( "mov r5, #0 " ); \
+ asm( "ldr r6, [r1] " ); \
+ asm( "umlal r2, r5, r3, r4 " ); \
+ asm( "adds r7, r6, r2 " ); \
+ asm( "adc r2, r5, #0 " ); \
+ asm( "str r7, [r1], #4 " );
+
+#define MULADDC_STOP \
+ asm( "str r2, %0 " : "=m" (c)); \
+ asm( "str r1, %0 " : "=m" (d)); \
+ asm( "str r0, %0 " : "=m" (s) :: \
+ "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7" );
+
+#endif /* ARMv3 */
+
+#if defined(__alpha__)
+
+#define MULADDC_INIT \
+ asm( "ldq $1, %0 " :: "m" (s)); \
+ asm( "ldq $2, %0 " :: "m" (d)); \
+ asm( "ldq $3, %0 " :: "m" (c)); \
+ asm( "ldq $4, %0 " :: "m" (b));
+
+#define MULADDC_CORE \
+ asm( "ldq $6, 0($1) " ); \
+ asm( "addq $1, 8, $1 " ); \
+ asm( "mulq $6, $4, $7 " ); \
+ asm( "umulh $6, $4, $6 " ); \
+ asm( "addq $7, $3, $7 " ); \
+ asm( "cmpult $7, $3, $3 " ); \
+ asm( "ldq $5, 0($2) " ); \
+ asm( "addq $7, $5, $7 " ); \
+ asm( "cmpult $7, $5, $5 " ); \
+ asm( "stq $7, 0($2) " ); \
+ asm( "addq $2, 8, $2 " ); \
+ asm( "addq $6, $3, $3 " ); \
+ asm( "addq $5, $3, $3 " );
+
+#define MULADDC_STOP \
+ asm( "stq $3, %0 " : "=m" (c)); \
+ asm( "stq $2, %0 " : "=m" (d)); \
+ asm( "stq $1, %0 " : "=m" (s) :: \
+ "$1", "$2", "$3", "$4", "$5", "$6", "$7" );
+
+#endif /* Alpha */
+
+#if defined(__mips__)
+
+#define MULADDC_INIT \
+ asm( "lw $10, %0 " :: "m" (s)); \
+ asm( "lw $11, %0 " :: "m" (d)); \
+ asm( "lw $12, %0 " :: "m" (c)); \
+ asm( "lw $13, %0 " :: "m" (b));
+
+#define MULADDC_CORE \
+ asm( "lw $14, 0($10) " ); \
+ asm( "multu $13, $14 " ); \
+ asm( "addi $10, $10, 4 " ); \
+ asm( "mflo $14 " ); \
+ asm( "mfhi $9 " ); \
+ asm( "addu $14, $12, $14 " ); \
+ asm( "lw $15, 0($11) " ); \
+ asm( "sltu $12, $14, $12 " ); \
+ asm( "addu $15, $14, $15 " ); \
+ asm( "sltu $14, $15, $14 " ); \
+ asm( "addu $12, $12, $9 " ); \
+ asm( "sw $15, 0($11) " ); \
+ asm( "addu $12, $12, $14 " ); \
+ asm( "addi $11, $11, 4 " );
+
+#define MULADDC_STOP \
+ asm( "sw $12, %0 " : "=m" (c)); \
+ asm( "sw $11, %0 " : "=m" (d)); \
+ asm( "sw $10, %0 " : "=m" (s) :: \
+ "$9", "$10", "$11", "$12", "$13", "$14", "$15" );
+
+#endif /* MIPS */
+#endif /* GNUC */
+
+#if (defined(_MSC_VER) && defined(_M_IX86)) || defined(__WATCOMC__)
+
+#define MULADDC_INIT \
+ __asm mov esi, s \
+ __asm mov edi, d \
+ __asm mov ecx, c \
+ __asm mov ebx, b
+
+#define MULADDC_CORE \
+ __asm lodsd \
+ __asm mul ebx \
+ __asm add eax, ecx \
+ __asm adc edx, 0 \
+ __asm add eax, [edi] \
+ __asm adc edx, 0 \
+ __asm mov ecx, edx \
+ __asm stosd
+
+#if defined(POLARSSL_HAVE_SSE2)
+
+#define EMIT __asm _emit
+
+#define MULADDC_HUIT \
+ EMIT 0x0F EMIT 0x6E EMIT 0xC9 \
+ EMIT 0x0F EMIT 0x6E EMIT 0xC3 \
+ EMIT 0x0F EMIT 0x6E EMIT 0x1F \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCB \
+ EMIT 0x0F EMIT 0x6E EMIT 0x16 \
+ EMIT 0x0F EMIT 0xF4 EMIT 0xD0 \
+ EMIT 0x0F EMIT 0x6E EMIT 0x66 EMIT 0x04 \
+ EMIT 0x0F EMIT 0xF4 EMIT 0xE0 \
+ EMIT 0x0F EMIT 0x6E EMIT 0x76 EMIT 0x08 \
+ EMIT 0x0F EMIT 0xF4 EMIT 0xF0 \
+ EMIT 0x0F EMIT 0x6E EMIT 0x7E EMIT 0x0C \
+ EMIT 0x0F EMIT 0xF4 EMIT 0xF8 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCA \
+ EMIT 0x0F EMIT 0x6E EMIT 0x5F EMIT 0x04 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xDC \
+ EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x08 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xEE \
+ EMIT 0x0F EMIT 0x6E EMIT 0x67 EMIT 0x0C \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xFC \
+ EMIT 0x0F EMIT 0x7E EMIT 0x0F \
+ EMIT 0x0F EMIT 0x6E EMIT 0x56 EMIT 0x10 \
+ EMIT 0x0F EMIT 0xF4 EMIT 0xD0 \
+ EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
+ EMIT 0x0F EMIT 0x6E EMIT 0x66 EMIT 0x14 \
+ EMIT 0x0F EMIT 0xF4 EMIT 0xE0 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCB \
+ EMIT 0x0F EMIT 0x6E EMIT 0x76 EMIT 0x18 \
+ EMIT 0x0F EMIT 0xF4 EMIT 0xF0 \
+ EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x04 \
+ EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
+ EMIT 0x0F EMIT 0x6E EMIT 0x5E EMIT 0x1C \
+ EMIT 0x0F EMIT 0xF4 EMIT 0xD8 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCD \
+ EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x10 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xD5 \
+ EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x08 \
+ EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCF \
+ EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x14 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xE5 \
+ EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x0C \
+ EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCA \
+ EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x18 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xF5 \
+ EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x10 \
+ EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCC \
+ EMIT 0x0F EMIT 0x6E EMIT 0x6F EMIT 0x1C \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xDD \
+ EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x14 \
+ EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCE \
+ EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x18 \
+ EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
+ EMIT 0x0F EMIT 0xD4 EMIT 0xCB \
+ EMIT 0x0F EMIT 0x7E EMIT 0x4F EMIT 0x1C \
+ EMIT 0x83 EMIT 0xC7 EMIT 0x20 \
+ EMIT 0x83 EMIT 0xC6 EMIT 0x20 \
+ EMIT 0x0F EMIT 0x73 EMIT 0xD1 EMIT 0x20 \
+ EMIT 0x0F EMIT 0x7E EMIT 0xC9
+
+#define MULADDC_STOP \
+ EMIT 0x0F EMIT 0x77 \
+ __asm mov c, ecx \
+ __asm mov d, edi \
+ __asm mov s, esi \
+
+#else
+
+#define MULADDC_STOP \
+ __asm mov c, ecx \
+ __asm mov d, edi \
+ __asm mov s, esi \
+
+#endif /* SSE2 */
+#endif /* MSVC */
+
+#endif /* POLARSSL_HAVE_ASM */
+
+#if !defined(MULADDC_CORE)
+#if defined(POLARSSL_HAVE_LONGLONG)
+
+#define MULADDC_INIT \
+{ \
+ t_udbl r; \
+ t_uint r0, r1;
+
+#define MULADDC_CORE \
+ r = *(s++) * (t_udbl) b; \
+ r0 = r; \
+ r1 = r >> biL; \
+ r0 += c; r1 += (r0 < c); \
+ r0 += *d; r1 += (r0 < *d); \
+ c = r1; *(d++) = r0;
+
+#define MULADDC_STOP \
+}
+
+#else
+#define MULADDC_INIT \
+{ \
+ t_uint s0, s1, b0, b1; \
+ t_uint r0, r1, rx, ry; \
+ b0 = ( b << biH ) >> biH; \
+ b1 = ( b >> biH );
+
+#define MULADDC_CORE \
+ s0 = ( *s << biH ) >> biH; \
+ s1 = ( *s >> biH ); s++; \
+ rx = s0 * b1; r0 = s0 * b0; \
+ ry = s1 * b0; r1 = s1 * b1; \
+ r1 += ( rx >> biH ); \
+ r1 += ( ry >> biH ); \
+ rx <<= biH; ry <<= biH; \
+ r0 += rx; r1 += (r0 < rx); \
+ r0 += ry; r1 += (r0 < ry); \
+ r0 += c; r1 += (r0 < c); \
+ r0 += *d; r1 += (r0 < *d); \
+ c = r1; *(d++) = r0;
+
+#define MULADDC_STOP \
+}
+
+#endif /* C (generic) */
+#endif /* C (longlong) */
+
+#endif /* bn_mul.h */
diff --git a/protocols/Tlen/crypto/polarssl/config.h b/protocols/Tlen/crypto/polarssl/config.h
new file mode 100644
index 0000000000..61500a75ee
--- /dev/null
+++ b/protocols/Tlen/crypto/polarssl/config.h
@@ -0,0 +1,625 @@
+/**
+ * \file config.h
+ *
+ * \brief Configuration options (set of defines)
+ *
+ * Copyright (C) 2006-2010, Brainspark B.V.
+ *
+ * This file is part of PolarSSL (http://www.polarssl.org)
+ * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * This set of compile-time options may be used to enable
+ * or disable features selectively, and reduce the global
+ * memory footprint.
+ */
+#ifndef POLARSSL_CONFIG_H
+#define POLARSSL_CONFIG_H
+
+#ifndef _CRT_SECURE_NO_DEPRECATE
+#define _CRT_SECURE_NO_DEPRECATE 1
+#endif
+
+/**
+ * \name SECTION: System support
+ *
+ * This section sets system specific settings.
+ * \{
+ */
+
+/**
+ * \def POLARSSL_HAVE_INT8
+ *
+ * The system uses 8-bit wide native integers.
+ *
+ * Uncomment if native integers are 8-bit wide.
+#define POLARSSL_HAVE_INT8
+ */
+
+/**
+ * \def POLARSSL_HAVE_INT16
+ *
+ * The system uses 16-bit wide native integers.
+ *
+ * Uncomment if native integers are 16-bit wide.
+#define POLARSSL_HAVE_INT16
+ */
+
+/**
+ * \def POLARSSL_HAVE_LONGLONG
+ *
+ * The compiler supports the use of long long.
+ *
+ * Uncomment if the compiler supports long long.
+#define POLARSSL_HAVE_LONGLONG
+ */
+
+/**
+ * \def POLARSSL_HAVE_ASM
+ *
+ * The compiler has support for asm()
+ *
+ * Uncomment to enable the use of assembly code.
+ *
+ * Requires support for asm() in compiler.
+ *
+ * Used in:
+ * library/timing.c
+ * library/padlock.c
+ * include/polarssl/bn_mul.h
+ *
+ */
+#define POLARSSL_HAVE_ASM
+
+/**
+ * \def POLARSSL_HAVE_SSE2
+ *
+ * CPI supports SSE2 instruction set.
+ *
+ * Uncomment if the CPU supports SSE2 (IA-32 specific).
+ *
+#define POLARSSL_HAVE_SSE2
+ */
+/* \} name */
+
+/**
+ * \name SECTION: PolarSSL feature support
+ *
+ * This section sets support for features that are or are not needed
+ * within the modules that are enabled.
+ * \{
+ */
+
+/**
+ * \def POLARSSL_AES_ROM_TABLES
+ *
+ * Store the AES tables in ROM.
+ *
+ * Uncomment this macro to store the AES tables in ROM.
+ *
+#define POLARSSL_AES_ROM_TABLES
+ */
+
+/**
+ * \def POLARSSL_CIPHER_MODE_CFB
+ *
+ * Enable Cipher Feedback mode (CFB) for symmetric ciphers.
+ */
+#define POLARSSL_CIPHER_MODE_CFB
+
+/**
+ * \def POLARSSL_CIPHER_MODE_CTR
+ *
+ * Enable Counter Block Cipher mode (CTR) for symmetric ciphers.
+ */
+#define POLARSSL_CIPHER_MODE_CTR
+
+/**
+ * \def POLARSSL_DEBUG_MSG
+ *
+ * Requires: POLARSSL_DEBUG_C
+ *
+ * Enable all SSL/TLS debugging messages.
+ */
+#define POLARSSL_DEBUG_MSG
+
+/**
+ * \def POLARSSL_GENPRIME
+ *
+ * Requires: POLARSSL_BIGNUM_C, POLARSSL_RSA_C
+ *
+ * Enable the RSA prime-number generation code.
+ */
+#define POLARSSL_GENPRIME
+
+/**
+ * \def POLARSSL_FS_IO
+ *
+ * Enable functions that use the filesystem.
+ */
+#define POLARSSL_FS_IO
+
+/**
+ * \def POLARSSL_PKCS1_V21
+ *
+ * Requires: POLARSSL_MD_C, POLARSSL_RSA_C
+ *
+ * Enable support for PKCS#1 v2.1 encoding.
+ * This enables support for RSAES-OAEP and RSASSA-PSS operations.
+ */
+#define POLARSSL_PKCS1_V21
+
+/**
+ * \def POLARSSL_RSA_NO_CRT
+ *
+ * Do not use the Chinese Remainder Theorem for the RSA private operation.
+ *
+ * Uncomment this macro to disable the use of CRT in RSA.
+ *
+#define POLARSSL_RSA_NO_CRT
+ */
+
+/**
+ * \def POLARSSL_SELF_TEST
+ *
+ * Enable the checkup functions (*_self_test).
+ */
+#define POLARSSL_SELF_TEST
+
+/**
+ * \def POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION
+ *
+ * If set, the X509 parser will not break-off when parsing an X509 certificate
+ * and encountering an unknown critical extension.
+ *
+ * Uncomment to prevent an error.
+ *
+#define POLARSSL_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION
+ */
+/* \} name */
+
+/**
+ * \name SECTION: PolarSSL modules
+ *
+ * This section enables or disables entire modules in PolarSSL
+ * \{
+ */
+
+/**
+ * \def POLARSSL_AES_C
+ *
+ * Enable the AES block cipher.
+ *
+ * Module: library/aes.c
+ * Caller: library/ssl_tls.c
+ * library/pem.c
+ *
+ * This module enables the following ciphersuites:
+ * SSL_RSA_AES_128_SHA
+ * SSL_RSA_AES_256_SHA
+ * SSL_EDH_RSA_AES_256_SHA
+ */
+#define POLARSSL_AES_C
+
+/**
+ * \def POLARSSL_ARC4_C
+ *
+ * Enable the ARCFOUR stream cipher.
+ *
+ * Module: library/arc4.c
+ * Caller: library/ssl_tls.c
+ *
+ * This module enables the following ciphersuites:
+ * SSL_RSA_RC4_128_MD5
+ * SSL_RSA_RC4_128_SHA
+ */
+#define POLARSSL_ARC4_C
+
+/**
+ * \def POLARSSL_BASE64_C
+ *
+ * Enable the Base64 module.
+ *
+ * Module: library/base64.c
+ * Caller: library/pem.c
+ *
+ * This module is required for PEM support (required by X.509).
+ */
+#define POLARSSL_BASE64_C
+
+/**
+ * \def POLARSSL_BIGNUM_C
+ *
+ * Enable the multo-precision integer library.
+ *
+ * Module: library/bignum.c
+ * Caller: library/dhm.c
+ * library/rsa.c
+ * library/ssl_tls.c
+ * library/x509parse.c
+ *
+ * This module is required for RSA and DHM support.
+ */
+#define POLARSSL_BIGNUM_C
+
+/**
+ * \def POLARSSL_CAMELLIA_C
+ *
+ * Enable the Camellia block cipher.
+ *
+ * Module: library/camellia.c
+ * Caller: library/ssl_tls.c
+ *
+ * This module enabled the following cipher suites:
+ * SSL_RSA_CAMELLIA_128_SHA
+ * SSL_RSA_CAMELLIA_256_SHA
+ * SSL_EDH_RSA_CAMELLIA_256_SHA
+ */
+#define POLARSSL_CAMELLIA_C
+
+/**
+ * \def POLARSSL_CERTS_C
+ *
+ * Enable the test certificates.
+ *
+ * Module: library/certs.c
+ * Caller:
+ *
+ * This module is used for testing (ssl_client/server).
+ */
+#define POLARSSL_CERTS_C
+
+/**
+ * \def POLARSSL_CIPHER_C
+ *
+ * Enable the generic cipher layer.
+ *
+ * Module: library/cipher.c
+ * Caller:
+ *
+ * Uncomment to enable generic cipher wrappers.
+ */
+#define POLARSSL_CIPHER_C
+
+/**
+ * \def POLARSSL_DEBUG_C
+ *
+ * Enable the debug functions.
+ *
+ * Module: library/debug.c
+ * Caller: library/ssl_cli.c
+ * library/ssl_srv.c
+ * library/ssl_tls.c
+ *
+ * This module provides debugging functions.
+ */
+#define POLARSSL_DEBUG_C
+
+/**
+ * \def POLARSSL_DES_C
+ *
+ * Enable the DES block cipher.
+ *
+ * Module: library/des.c
+ * Caller: library/ssl_tls.c
+ *
+ * This module enables the following ciphersuites:
+ * SSL_RSA_DES_168_SHA
+ * SSL_EDH_RSA_DES_168_SHA
+ */
+#define POLARSSL_DES_C
+
+/**
+ * \def POLARSSL_DHM_C
+ *
+ * Enable the Diffie-Hellman-Merkle key exchange.
+ *
+ * Module: library/dhm.c
+ * Caller: library/ssl_cli.c
+ * library/ssl_srv.c
+ *
+ * This module enables the following ciphersuites:
+ * SSL_EDH_RSA_DES_168_SHA
+ * SSL_EDH_RSA_AES_256_SHA
+ * SSL_EDH_RSA_CAMELLIA_256_SHA
+ */
+#define POLARSSL_DHM_C
+
+/**
+ * \def POLARSSL_ERROR_C
+ *
+ * Enable error code to error string conversion.
+ *
+ * Module: library/error.c
+ * Caller:
+ *
+ * This module enables err_strerror().
+ */
+#define POLARSSL_ERROR_C
+
+/**
+ * \def POLARSSL_HAVEGE_C
+ *
+ * Enable the HAVEGE random generator.
+ *
+ * Module: library/havege.c
+ * Caller:
+ *
+ * Requires: POLARSSL_TIMING_C
+ *
+ * This module enables the HAVEGE random number generator.
+ */
+#define POLARSSL_HAVEGE_C
+
+/**
+ * \def POLARSSL_MD_C
+ *
+ * Enable the generic message digest layer.
+ *
+ * Module: library/md.c
+ * Caller:
+ *
+ * Uncomment to enable generic message digest wrappers.
+ */
+#define POLARSSL_MD_C
+
+/**
+ * \def POLARSSL_MD2_C
+ *
+ * Enable the MD2 hash algorithm
+ *
+ * Module: library/md2.c
+ * Caller: library/x509parse.c
+ *
+ * Uncomment to enable support for (rare) MD2-signed X.509 certs.
+ *
+#define POLARSSL_MD2_C
+ */
+
+/**
+ * \def POLARSSL_MD4_C
+ *
+ * Enable the MD4 hash algorithm
+ *
+ * Module: library/md4.c
+ * Caller: library/x509parse.c
+ *
+ * Uncomment to enable support for (rare) MD4-signed X.509 certs.
+ *
+#define POLARSSL_MD4_C
+ */
+
+/**
+ * \def POLARSSL_MD5_C
+ *
+ * Enable the MD5 hash algorithm
+ *
+ * Module: library/md5.c
+ * Caller: library/ssl_tls.c
+ * library/x509parse.c
+ *
+ * This module is required for SSL/TLS and X.509.
+ */
+#define POLARSSL_MD5_C
+
+/**
+ * \def POLARSSL_NET_C
+ *
+ * Enable the TCP/IP networking routines.
+ *
+ * Module: library/net.c
+ * Caller:
+ *
+ * This module provides TCP/IP networking routines.
+ */
+#define POLARSSL_NET_C
+
+/**
+ * \def POLARSSL_PADLOCK_C
+ *
+ * Enable VIA Padlock support on x86.
+ *
+ * Module: library/padlock.c
+ * Caller: library/aes.c
+ *
+ * This modules adds support for the VIA PadLock on x86.
+ */
+#define POLARSSL_PADLOCK_C
+
+/**
+ * \def POLARSSL_PEM_C
+ *
+ * Enable PEM decoding
+ *
+ * Module: library/pem.c
+ * Caller: library/x509parse.c
+ *
+ * Requires: POLARSSL_BASE64_C
+ *
+ * This modules adds support for decoding PEM files.
+ */
+#define POLARSSL_PEM_C
+
+/**
+ * \def POLARSSL_PKCS11_C
+ *
+ * Enable support for PKCS#11 smartcard support.
+ *
+ * Module: library/ssl_srv.c
+ * Caller: library/ssl_cli.c
+ * library/ssl_srv.c
+ *
+ * Requires: POLARSSL_SSL_TLS_C
+ *
+ * This module is required for SSL/TLS PKCS #11 smartcard support.
+ * Requires the presence of the PKCS#11 helper library (libpkcs11-helper)
+#define POLARSSL_PKCS11_C
+ */
+
+/**
+ * \def POLARSSL_RSA_C
+ *
+ * Enable the RSA public-key cryptosystem.
+ *
+ * Module: library/rsa.c
+ * Caller: library/ssl_cli.c
+ * library/ssl_srv.c
+ * library/ssl_tls.c
+ * library/x509.c
+ *
+ * Requires: POLARSSL_BIGNUM_C
+ *
+ * This module is required for SSL/TLS and MD5-signed certificates.
+ */
+#define POLARSSL_RSA_C
+
+/**
+ * \def POLARSSL_SHA1_C
+ *
+ * Enable the SHA1 cryptographic hash algorithm.
+ *
+ * Module: library/sha1.c
+ * Caller: library/ssl_cli.c
+ * library/ssl_srv.c
+ * library/ssl_tls.c
+ * library/x509parse.c
+ *
+ * This module is required for SSL/TLS and SHA1-signed certificates.
+ */
+#define POLARSSL_SHA1_C
+
+/**
+ * \def POLARSSL_SHA2_C
+ *
+ * Enable the SHA-224 and SHA-256 cryptographic hash algorithms.
+ *
+ * Module: library/sha2.c
+ * Caller: library/md_wrap.c
+ * library/x509parse.c
+ *
+ * This module adds support for SHA-224 and SHA-256.
+ */
+#define POLARSSL_SHA2_C
+
+/**
+ * \def POLARSSL_SHA4_C
+ *
+ * Enable the SHA-384 and SHA-512 cryptographic hash algorithms.
+ *
+ * Module: library/sha4.c
+ * Caller: library/md_wrap.c
+ * library/x509parse.c
+ *
+ * This module adds support for SHA-384 and SHA-512.
+ */
+#define POLARSSL_SHA4_C
+
+/**
+ * \def POLARSSL_SSL_CLI_C
+ *
+ * Enable the SSL/TLS client code.
+ *
+ * Module: library/ssl_cli.c
+ * Caller:
+ *
+ * Requires: POLARSSL_SSL_TLS_C
+ *
+ * This module is required for SSL/TLS client support.
+ */
+#define POLARSSL_SSL_CLI_C
+
+/*
+ * \def POLARSSL_SSL_SRV_C
+ *
+ * Enable the SSL/TLS server code.
+ *
+ * Module: library/ssl_srv.c
+ * Caller:
+ *
+ * Requires: POLARSSL_SSL_TLS_C
+ *
+ * This module is required for SSL/TLS server support.
+ */
+#define POLARSSL_SSL_SRV_C
+
+/**
+ * \def POLARSSL_SSL_TLS_C
+ *
+ * Enable the generic SSL/TLS code.
+ *
+ * Module: library/ssl_tls.c
+ * Caller: library/ssl_cli.c
+ * library/ssl_srv.c
+ *
+ * Requires: POLARSSL_MD5_C, POLARSSL_SHA1_C, POLARSSL_X509_PARSE_C
+ *
+ * This module is required for SSL/TLS.
+ */
+#define POLARSSL_SSL_TLS_C
+
+/**
+ * \def POLARSSL_TIMING_C
+ *
+ * Enable the portable timing interface.
+ *
+ * Module: library/timing.c
+ * Caller: library/havege.c
+ *
+ * This module is used by the HAVEGE random number generator.
+ */
+#define POLARSSL_TIMING_C
+
+/**
+ * \def POLARSSL_VERSION_C
+ *
+ * Enable run-time version information.
+ *
+ * Module: library/version.c
+ *
+ * This module provides run-time version information.
+ */
+#define POLARSSL_VERSION_C
+
+/**
+ * \def POLARSSL_X509_PARSE_C
+ *
+ * Enable X.509 certificate parsing.
+ *
+ * Module: library/x509parse.c
+ * Caller: library/ssl_cli.c
+ * library/ssl_srv.c
+ * library/ssl_tls.c
+ *
+ * Requires: POLARSSL_BIGNUM_C, POLARSSL_RSA_C
+ *
+ * This module is required for X.509 certificate parsing.
+ */
+#define POLARSSL_X509_PARSE_C
+
+/**
+ * \def POLARSSL_XTEA_C
+ *
+ * Enable the XTEA block cipher.
+ *
+ * Module: library/xtea.c
+ * Caller:
+ */
+#define POLARSSL_XTEA_C
+/* \} name */
+
+#endif /* config.h */
diff --git a/protocols/Tlen/crypto/polarssl/padlock.h b/protocols/Tlen/crypto/polarssl/padlock.h
new file mode 100644
index 0000000000..08fbe825c9
--- /dev/null
+++ b/protocols/Tlen/crypto/polarssl/padlock.h
@@ -0,0 +1,100 @@
+/**
+ * \file padlock.h
+ *
+ * \brief VIA PadLock ACE for HW encryption/decryption supported by some processors
+ *
+ * Copyright (C) 2006-2010, Brainspark B.V.
+ *
+ * This file is part of PolarSSL (http://www.polarssl.org)
+ * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
+ *
+ * All rights reserved.
+ *
+ * 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.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+#ifndef POLARSSL_PADLOCK_H
+#define POLARSSL_PADLOCK_H
+
+#include "polarssl/aes.h"
+
+#define POLARSSL_ERR_PADLOCK_DATA_MISALIGNED -0x0030 /**< Input data should be aligned. */
+
+#if defined(POLARSSL_HAVE_ASM) && defined(__GNUC__) && defined(__i386__)
+
+#ifndef POLARSSL_HAVE_X86
+#define POLARSSL_HAVE_X86
+#endif
+
+#define PADLOCK_RNG 0x000C
+#define PADLOCK_ACE 0x00C0
+#define PADLOCK_PHE 0x0C00
+#define PADLOCK_PMM 0x3000
+
+#define PADLOCK_ALIGN16(x) (unsigned long *) (16 + ((long) x & ~15))
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief PadLock detection routine
+ *
+ * \param The feature to detect
+ *
+ * \return 1 if CPU has support for the feature, 0 otherwise
+ */
+int padlock_supports( int feature );
+
+/**
+ * \brief PadLock AES-ECB block en(de)cryption
+ *
+ * \param ctx AES context
+ * \param mode AES_ENCRYPT or AES_DECRYPT
+ * \param input 16-byte input block
+ * \param output 16-byte output block
+ *
+ * \return 0 if success, 1 if operation failed
+ */
+int padlock_xcryptecb( aes_context *ctx,
+ int mode,
+ const unsigned char input[16],
+ unsigned char output[16] );
+
+/**
+ * \brief PadLock AES-CBC buffer en(de)cryption
+ *
+ * \param ctx AES context
+ * \param mode AES_ENCRYPT or AES_DECRYPT
+ * \param length length of the input data
+ * \param iv initialization vector (updated after use)
+ * \param input buffer holding the input data
+ * \param output buffer holding the output data
+ *
+ * \return 0 if success, 1 if operation failed
+ */
+int padlock_xcryptcbc( aes_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* HAVE_X86 */
+
+#endif /* padlock.h */
diff --git a/protocols/Tlen/docs/InstallScript.xml b/protocols/Tlen/docs/InstallScript.xml
new file mode 100644
index 0000000000..7d8a8f28fe
--- /dev/null
+++ b/protocols/Tlen/docs/InstallScript.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="ISO-8859-1" ?>
+<installscript>
+ <info>
+ <name>Tlen Protocol</name>
+ <author>Santithorn Bunchua</author>
+ <version>0.1.0.2</version>
+ <type>Plugin</type>
+ </info>
+
+ <packageinfo>
+ <title>Main Files</title>
+ <file>tlen.dll</file>
+ <file>tlen_czaty.dll</file>
+ </packageinfo>
+
+ <packageinfo>
+ <optional/>
+ <title>Documentation</title>
+ <file>readme_tlen.txt</file>
+ <document/>
+ </packageinfo>
+
+ <autorun>
+ <file>readme_tlen.txt</file>
+ <document/>
+ </autorun>
+</installscript>
diff --git a/protocols/Tlen/docs/changelog_tlen.txt b/protocols/Tlen/docs/changelog_tlen.txt
new file mode 100644
index 0000000000..b2c05c760a
--- /dev/null
+++ b/protocols/Tlen/docs/changelog_tlen.txt
@@ -0,0 +1,269 @@
+Version 2.0.5.0
+-------
+* Project cleanup
+ + change mucc.dll to tlen_czaty.dll
+ + compile tlen_czaty in Unicode and x64
+* fix warnings, project files changes
+Version 2.0.4.1
+-------
+- fix accounts... dialog
+Version 2.0.4.0
+-------
++ x64 version
+* set timeout to NETLIBOPENCONNECTION (patch by piotrw)
+* fix for display texts at comboboxes in unicode (patch by piotrw)
+* fixes in Find/Add Contacts search (by piotrw, dezeath and wsx22)
+* fix warnings, project files changes (add VS2010)
+Version 2.0.3.2
+-------
+* update PolarSSL library to polarssl-1.0.0
+* change compile options to not require microsoft visual studio runtime libs on user system, (100KB larger file but no problems with msvcr90.dll not found on user system)
+Version 2.0.2.0
+-------
+* "Leave status message after disconnection", "Send and receive client version information" and "Log alerts as messages" options enabled by default (AL|EN suggestion)
+Version 2.0.1.0
+-------
+merge changes from wsx22 mod
+* fix in typing notify message handling
+* fix in logging to server message
+Version 2.0.0.0
+-------
++ Image transfer
+* other bug fixes and improvements
+Version 1.8.0.2
+-------
+improved icons handling
+minor fixes on account unloading
+1.8.0.1
+-------
+* bugfix: removed ME_SYSTEM_MODULESLOADED hook
+1.8.0.0
+-------
++ support for account manager (requires MIM 0.8)
+* many bugfixes and small improvements
+1.1.0.0
+-------
+* avatar support improvements
+1.0.9.2
+-------
+* avatar management UI changes
+* user info page changes
+* some clean-up and bugfixes
+* fix for advertisement blocking
+* fix for file transfers
+1.0.9.1
+-------
+* avatar management improvements
+1.0.9.0
+-------
++ message encryption
+* improved search (up to 200 results displayed)
+* some avatar-related fixes
+* MIM 0.7 compatibility
+1.0.7.7
+-------
+* new icons by Angelika
+1.0.7.6
+-------
++ support for Tlen avatars
+1.0.7.5
+-------
+* bugfix: settings changes were not loaded properly
+1.0.7.4
+-------
+* p2p connections refactoring
+* UPnP support
+* managed services/hooks
+* support for IcoLib
+* new icons
+* support for Miranda Memory Manager
+1.0.7.3
+--------
+* bugfix: offline status message
+1.0.7.2
+--------
+! fixed compatibility issues with new versions of IEView (1.0.9.0 or higher)
++ support for Nudge plugin
+* improved avatar support
+* improved sending/receiving client version info
+1.0.7.1
+---------
+* bugfix: sending/receiving client version info
+1.0.7.0
+---------
++ full support for avatars (compatible with tAvatar 0.0.2.1 or higher)
++ sending and receiving full client version info
+* optimized DB usage
+* code cleanup
+1.0.6.9
+---------
++ experimental client recognition
++ voice chat notification sound
+* bugfix: offline message timestamp
+* code clean-up
+1.0.6.8
+---------
+* bugfix: compatibility with Unicode contact lists
+* bugfix: user login is always converted to lower case
+* bugfix: typing notifications
+* other bugfixes
+1.0.6.7
+---------
++ possibility to send files to offline users
++ public status visibility settings
+* bugfixes
+1.0.6.6
+---------
+* fixed IEView support (text scrolling issue)
+* code cleanup
+1.0.6.5
+---------
++ option to ignore advertisements
+* bugfixes
+1.0.6.4
+---------
++ alert, voice chat and group chat policies
++ received alerts are logged as messages
+* offline message timestamp improvements (thanks to Atay for the idea)
+* removed obsolete, Jabber-specific code
+* a lot of more or less important bugfixes
+1.0.6.3
+---------
++ group names encoding
++ log saving in IEView mode
+* simplified option page
+1.0.6.2
+---------
++ support for IEView group chats (IEView 1.0.3.0 or later)
++ improvements of group chats in RichEdit mode (context menu, better scrolling)
+1.0.6.1
+---------
+* bugfix: proper filename encoding
+* options page rearranged
+* code cleanup, other fixes and improvements
+1.0.6.0
+---------
++ group chat window flashing
++ message icons in tabbed mode
++ web messages grouped as a single contact
+* offline message timestamp handling fixed (again)
+1.0.5.10 RC2
+---------
++ tabbed mode available in group chat window
++ saving chat log to file
++ smiley selection button in group chat window
++ new shortcuts: ctrl+w (close), ctrl+a (select all)
++ saving chat fonts setting
++ new menu items: request and grant authorization
+* several bugfixes in MUCC plugin, better MUCC architecture
+1.0.5.9 RC
+---------
++ voice chat improvements (better sound quality and smarter delay reduction, bugfixes)
++ separate group for Global Owners in chat user list
+* bugfix: web messages receiving (fix by MoMaT)
+1.0.5.8
+---------
++ playback and recording device selection
++ sending and receiving alerts (use <alert> to send)
++ enabling/disabling Always Visible support
+* bugfixes
+1.0.5.7
+---------
++ chat room administration window (user administration and browser)
++ unban option
++ dynamic user groups
++ voice chat p2p connection negotiation
++ voice chat status display
++ incoming voice chat invitation dialog
++ removing contacts from roster on authorization denial
++ offline status message selection
+* a lot of fixes in group chats interface
+1.0.5.6
+---------
++ voice chats ! (experimental)
++ chat room administration: destroying room, changing users' roles, kick & ban
++ MUCC option: send on Enter
++ status messages of offline contacts (use mToolTip to read them)
+* bugfix: contact name encoding when adding new contact
+* bugfix: offline messages time ('more inteligent' Daylight Saving Time handling)
+* bugfix: closing all file transfers at shutdown
+* other minor fixes
+1.0.5.5
+---------
++ improved file transfer (p2p connection negotiation, error notification)
++ MUCC options page (fonts, colors, default filters)
++ chat room events logging (user has joined etc.)
++ registering and uregistering nick names
++ creating chat rooms
++ chat room topic displaying and setting
++ improved errors handling
+* look & feel improvements
+* bugfix: correct chat room name returned by search
+* bugfix: removing users from contact list groups
+* source code refactoring
+1.0.5.4
+---------
++ group chats error handling
++ message log formatting options
++ chat room searching
++ list of contacts in 'invite to group chat' dialog
++ Multi-User Conference item in contact menu
++ some look & feel improvements (better resizing, new icons)
++ internal history of messages
+* a lot of bugfixes and code improvements
+* code clean-up
+1.0.5.3
+---------
++ full text formatting (font name, font size)
++ private messaging sessions
++ displaying user details (administrator/moderator/registered nickname)
++ displaying chat room details icons (moderated/members only/anonymous nicknames not allowed)
++ browsing own chat rooms/registered nicknames
+* code clean-up
+* bugfixes
+1.0.5.2
+---------
++ text formatting (bold, italic, underline, text color for now)
++ chat rooms browsing page by page
+* bugfixes and code clean-up
+1.0.5.1
+---------
++ initial multi-user conferences and chats support
++ MUCC plugin responsible for chats GUI (manager window (groups/rooms), messanging window, helper dialogs)
+
+2004-09-23 Version 1.0.4.0
+ Jabber and Tlen now have separate source trees (Tlen plugin is compliant with GCC now)
+ File transfer with forwarding and SOCKS4/5 proxy support
+ vCard viewing and editing
+ Web messages receiving
+ Incoming email notification through the popup plugin and sounds
+ User typing notification (patch by Adam Libura)
+ Searching users by login
+ New user details page
+ Invisible status message
+ Option to leave offline status message
+ Option to show offline users with status message as invisible
+ Link to create new account
+ Fixed bug: adjust offline message time
+ A lot of other fixes and improvements
+
+2003-08-19 Version 0.1.0.2
+ Fixed bug: crash when receiving some invisible presence
+ Fixed bug: incorrect newline encoding/decoding (tlen uses \r\n while jabber uses \n)
+ Fixed bug: User detail text is not decoded
+ Use new invisible presence (now conform to Jabber invisible presence)
+ Advanced search
+ Based on Jabber plugin 0.1.1.2
+
+2003-05-12 Version 0.1.0.1
+ Fixed bug: slightly incorrect online presence
+ Based on Jabber plugin 0.1.1.0
+
+2003-01-19 Version 0.1.0.0
+ Based on Jabber plugin 0.1.0.7
+ Tlen basic user info
+ Tlen invisible status
+ Tlen visible/invisible list
+ Option to show invisible users as invisible
+ Find/add users using tlen user database
+ Rebase DLL to 0x32600000
diff --git a/protocols/Tlen/docs/gpl.txt b/protocols/Tlen/docs/gpl.txt
new file mode 100644
index 0000000000..45645b4b53
--- /dev/null
+++ b/protocols/Tlen/docs/gpl.txt
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ 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.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/protocols/Tlen/docs/gpl_comment.txt b/protocols/Tlen/docs/gpl_comment.txt
new file mode 100644
index 0000000000..ecacc17720
--- /dev/null
+++ b/protocols/Tlen/docs/gpl_comment.txt
@@ -0,0 +1,20 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2012 Santithorn Bunchua, Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
diff --git a/protocols/Tlen/docs/readme_tlen.txt b/protocols/Tlen/docs/readme_tlen.txt
new file mode 100644
index 0000000000..234e9b098b
--- /dev/null
+++ b/protocols/Tlen/docs/readme_tlen.txt
@@ -0,0 +1,60 @@
+Tlen Protocol Plugin for Miranda IM
+===================================
+
+Introduction:
+ Tlen is a protocol used by a propritary instant messaging network
+ at tlen.pl. It is based on Jabber, and, therefore, this plugin
+ is very much based on Jabber protocol plugin for Miranda. All
+ necessary helps to create this Tlen plugin are from Adam Strzelecki.
+
+Installation:
+ Copy tlen.dll and (optional) tlen_czaty.dll to Miranda's plugins directory.
+
+ If you want to have multiple Tlen accounts online at the same time,
+ you need to have multiple copies of tlen.dll, each with different name,
+ all in Miranda's plugins directory. Note that all configurations for a
+ Tlen account (including your contact list) are associated with the
+ DLL's name. In addition, it is highly recommended that you do NOT choose
+ the name that is in conflict with other plugins or any database categories
+ used by Miranda core (use DatabaseViewer or DatabaseEditor to see what
+ database categories are already in use).
+
+More information:
+ Web: http://mtlen.berlios.de
+ E-mail: the_leech@users.berlios.de
+
+Copyright (c) 2002-2012 Santithorn Bunchua (keh@au.edu), Piotr Piastucki
+
+Acknowledgement:
+ We would like to thank the following people for their helps and/or comments
+ (alphabetically listed):
+ Dmitry Balabanov
+ Nikola Dachev
+ Sam Kothari
+ Adam Libura
+ J�rgen Persson
+ Robert Rainwater
+ Adam Strzelecki
+ Michal Wojciechowski
+ Szymon Tokarz (wsx22)
+
+================================================================
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2012 Santithorn Bunchua, Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+================================================================
diff --git a/protocols/Tlen/docs/tlen-translation.txt b/protocols/Tlen/docs/tlen-translation.txt
new file mode 100644
index 0000000000..6406f204c7
--- /dev/null
+++ b/protocols/Tlen/docs/tlen-translation.txt
@@ -0,0 +1,153 @@
+;***********************************
+;******* Tlen language by raq ******
+
+[Tlen czaty]
+;[Authentication failed for]
+;[Tlen Authentication]
+[Network]
+[Advanced]
+[PopUps]
+[Accept all alerts]
+[Ignore alerts from unauthorized contacts]
+[Ignore all alerts]
+[Always ask me]
+[Accept invitations from authorized contacts]
+[Accept all invitations]
+[Ignore invitations from unauthorized contacts]
+[Ignore all invitation]
+[Always ask me]
+[<Last message>]
+[<Ask me>]
+[Online]
+[Away]
+[NA]
+[DND]
+[Free for chat]
+[Invisible]
+[These changes will take effect the next time you connect to the Tlen network.]
+[Tlen Protocol Option]
+[Forwarding]
+;[SOCKS4]
+;[SOCKS5]
+;[Tlen login]
+[Enter password for]
+[Error: Not enough memory]
+[Error: Cannot connect to the server]
+[The connection requires an OpenSSL library, which is not installed.]
+;[Jabber Connection Error]
+[%s Web Messages]
+[Web message]
+[From]
+;[E-mail]
+[An alert has been received.]
+[Private conference]
+[New mail]
+[Subject]
+;[both]
+[to]
+[from]
+[none]
+;[not on roster]
+[Error]
+[Unknown error message]
+[connection]
+[Incoming mail]
+;[Alert]
+[Multi-User Conference]
+[Tlen Chats...]
+[Voice Chat]
+[Voice chat]
+[Request authorization]
+[Grant authorization]
+[You have been kicked. Reason: %s ]
+[You cannot join this chat room, because you are banned.]
+[Chat room not found.]
+[This is a private chat room and you are not one of the members.]
+[You cannot send any message unless you join this chat room.]
+[Chat room with already created.]
+[Nickname '%s' is already registered.]
+[Nickname already in use, please try another one. Hint: '%s' is free.]
+[You cannot register more than %s nicknames.]
+[You cannot create more than %s chat rooms.]
+[You cannot join more than %s chat rooms.]
+[Anonymous nicknames are not allowed in this chat room.]
+[Unknown error code : %d]
+[Default]
+
+;tlen.rc
+
+[Username:]
+[Create a new account]
+[Password:]
+[Save password]
+[Use SSL]
+[Options]
+[Automatically reconnect after unintentional disconnection]
+[Leave status message after disconnection]
+[Ignore advertisements]
+[Automatically delete contacts not in my roster]
+[Show offline users with status messages as invisible in contact list]
+[Enable avatars]
+[Send and receive version information]
+[Use Nudge plugin]
+[Log alerts as messages]
+[Alert policy]
+[Group chat policy]
+[Voice Chats]
+[Voice chat policy]
+[Recording device:]
+[Playback device:]
+[Expert Options]
+[Login server:]
+[Connection Host:]
+;[Port:]
+[Keep connection alive]
+[Enable Always Visible and Never Visible]
+[File Transfer and Voice Chats]
+[Use proxy for incoming connections]
+[Proxy type:]
+[Proxy server:]
+[Proxy requires authorization]
+[Delay]
+[&From PopUp plugin]
+[&Custom]
+[P&ermanent]
+[Colours]
+[Background]
+[Text]
+[General Options]
+[Preview]
+[Enable incoming mail notification]
+;[OK]
+[Cancel]
+[Nick name:]
+[First name:]
+[Last name:]
+;[E-mail:]
+[Gender:]
+[Year of birth:]
+[City:]
+[School:]
+[Occupation:]
+[Looking for:]
+[Voice chats]
+[Save changes]
+;[Subscription:]
+[Age:]
+[Personal Information]
+;[Status:]
+[Plan:]
+[&Accept]
+[From:]
+[Software:]
+[Version:]
+[System:]
+[The following invitation to join a voice chat is received.]
+[Current Avatar]
+[New Avatar]
+[Public]
+[Browse...]
+[Set]
+[Delete]
+[Note: Image size max. 64x64]
+[Enable encryption]
diff --git a/protocols/Tlen/icos/auth_grant.ico b/protocols/Tlen/icos/auth_grant.ico
new file mode 100644
index 0000000000..8d1ba94308
--- /dev/null
+++ b/protocols/Tlen/icos/auth_grant.ico
Binary files differ
diff --git a/protocols/Tlen/icos/auth_request.ico b/protocols/Tlen/icos/auth_request.ico
new file mode 100644
index 0000000000..116ed47baf
--- /dev/null
+++ b/protocols/Tlen/icos/auth_request.ico
Binary files differ
diff --git a/protocols/Tlen/icos/groupchats.ico b/protocols/Tlen/icos/groupchats.ico
new file mode 100644
index 0000000000..ecd2070d20
--- /dev/null
+++ b/protocols/Tlen/icos/groupchats.ico
Binary files differ
diff --git a/protocols/Tlen/icos/image.ico b/protocols/Tlen/icos/image.ico
new file mode 100644
index 0000000000..832b9a8b69
--- /dev/null
+++ b/protocols/Tlen/icos/image.ico
Binary files differ
diff --git a/protocols/Tlen/icos/mail.ico b/protocols/Tlen/icos/mail.ico
new file mode 100644
index 0000000000..c5ded81702
--- /dev/null
+++ b/protocols/Tlen/icos/mail.ico
Binary files differ
diff --git a/protocols/Tlen/icos/microphone.ico b/protocols/Tlen/icos/microphone.ico
new file mode 100644
index 0000000000..1edeb90d1f
--- /dev/null
+++ b/protocols/Tlen/icos/microphone.ico
Binary files differ
diff --git a/protocols/Tlen/icos/speaker.ico b/protocols/Tlen/icos/speaker.ico
new file mode 100644
index 0000000000..77545c0598
--- /dev/null
+++ b/protocols/Tlen/icos/speaker.ico
Binary files differ
diff --git a/protocols/Tlen/icos/tlen.ico b/protocols/Tlen/icos/tlen.ico
new file mode 100644
index 0000000000..a166dd4c5b
--- /dev/null
+++ b/protocols/Tlen/icos/tlen.ico
Binary files differ
diff --git a/protocols/Tlen/icos/tlenchats.ico b/protocols/Tlen/icos/tlenchats.ico
new file mode 100644
index 0000000000..52ab77ff63
--- /dev/null
+++ b/protocols/Tlen/icos/tlenchats.ico
Binary files differ
diff --git a/protocols/Tlen/icos/voicechat.ico b/protocols/Tlen/icos/voicechat.ico
new file mode 100644
index 0000000000..f989d5b212
--- /dev/null
+++ b/protocols/Tlen/icos/voicechat.ico
Binary files differ
diff --git a/protocols/Tlen/jabber.h b/protocols/Tlen/jabber.h
new file mode 100644
index 0000000000..fdaabf5e43
--- /dev/null
+++ b/protocols/Tlen/jabber.h
@@ -0,0 +1,438 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#ifndef _JABBER_H_
+#define _JABBER_H_
+
+#if defined(UNICODE)
+ #ifndef _UNICODE
+ #define _UNICODE
+ #endif
+#endif
+
+#define MIRANDA_VER 0x0800
+
+#undef _WIN32_WINNT
+#undef _WIN32_IE
+#define _WIN32_WINNT 0x0501
+#define _WIN32_IE 0x0501
+
+#define __try
+#define __except(x) if (0)
+#define __finally
+
+#define _try __try
+#define _except __except
+#define _finally __finally
+
+#ifdef _DEBUG
+#define _CRTDBG_MAP_ALLOC
+#include <stdlib.h>
+#include <crtdbg.h>
+#endif
+#define ENABLE_LOGGING
+
+/*******************************************************************
+ * Global compilation flags
+ *******************************************************************/
+
+/*******************************************************************
+ * Global header files
+ *******************************************************************/
+#include <windows.h>
+#include <process.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <time.h>
+#include <limits.h>
+#include <win2k.h>
+
+#include <newpluginapi.h>
+#include <m_system.h>
+#include <m_netlib.h>
+#include <m_protomod.h>
+#include <m_protosvc.h>
+#include <m_protoint.h>
+#include <m_contacts.h>
+#include <m_clist.h>
+#include <m_clui.h>
+#include <m_options.h>
+#include <m_userinfo.h>
+#include <m_database.h>
+#include <m_langpack.h>
+#include <m_utils.h>
+#include <m_message.h>
+#include <m_skin.h>
+#include <m_popup.h>
+#include <m_avatars.h>
+
+#include "jabber_xml.h"
+#include "crypto/polarssl/aes.h"
+#include "crypto/polarssl/bignum.h"
+
+/*******************************************************************
+ * Global constants
+ *******************************************************************/
+#define TLEN_DEFAULT_PORT 443
+#define JABBER_IQID "mim_"
+#define TLEN_REGISTER "http://reg.tlen.pl/"
+#define TLEN_MAX_SEARCH_RESULTS_PER_PAGE 20
+
+// User-defined message
+#define WM_TLEN_REFRESH (WM_USER + 100)
+// Error code
+#define JABBER_ERROR_REDIRECT 302
+#define JABBER_ERROR_BAD_REQUEST 400
+#define JABBER_ERROR_UNAUTHORIZED 401
+#define JABBER_ERROR_PAYMENT_REQUIRED 402
+#define JABBER_ERROR_FORBIDDEN 403
+#define JABBER_ERROR_NOT_FOUND 404
+#define JABBER_ERROR_NOT_ALLOWED 405
+#define JABBER_ERROR_NOT_ACCEPTABLE 406
+#define JABBER_ERROR_REGISTRATION_REQUIRED 407
+#define JABBER_ERROR_REQUEST_TIMEOUT 408
+#define JABBER_ERROR_CONFLICT 409
+#define JABBER_ERROR_INTERNAL_SERVER_ERROR 500
+#define JABBER_ERROR_NOT_IMPLEMENTED 501
+#define JABBER_ERROR_REMOTE_SERVER_ERROR 502
+#define JABBER_ERROR_SERVICE_UNAVAILABLE 503
+#define JABBER_ERROR_REMOTE_SERVER_TIMEOUT 504
+
+#define TLEN_ALERTS_ACCEPT_ALL 0
+#define TLEN_ALERTS_IGNORE_NIR 1
+#define TLEN_ALERTS_IGNORE_ALL 2
+
+#define TLEN_IMAGES_ACCEPT_ALL 0
+#define TLEN_IMAGES_IGNORE_NIR 1
+#define TLEN_IMAGES_IGNORE_ALL 2
+
+#define TLEN_MUC_ASK 0
+#define TLEN_MUC_ACCEPT_IR 1
+#define TLEN_MUC_ACCEPT_ALL 2
+#define TLEN_MUC_IGNORE_NIR 3
+#define TLEN_MUC_IGNORE_ALL 4
+
+#define IDC_STATIC (-1)
+
+/*******************************************************************
+ * Global data structures and data type definitions
+ *******************************************************************/
+typedef HANDLE JABBER_SOCKET;
+
+typedef enum {
+ LIST_ROSTER, // Roster list
+ LIST_CHATROOM, // Groupchat room currently joined
+ LIST_FILE, // Current file transfer session
+ LIST_INVITATIONS,// Invitations to be sent
+ LIST_SEARCH, // Rooms names being searched
+ LIST_VOICE,
+ LIST_PICTURE
+} JABBER_LIST;
+
+typedef enum {
+ IQ_PROC_NONE,
+ IQ_PROC_GETSEARCH
+} JABBER_IQ_PROCID;
+
+typedef enum {
+ SUB_NONE,
+ SUB_TO,
+ SUB_FROM,
+ SUB_BOTH
+} JABBER_SUBSCRIPTION;
+
+typedef struct {
+ char *szOnline;
+ char *szAway;
+ char *szNa;
+ char *szDnd;
+ char *szFreechat;
+ char *szInvisible;
+} JABBER_MODEMSGS;
+
+typedef struct {
+ char mailBase[256];
+ char mailMsg[256];
+ int mailMsgMthd;
+ char mailIndex[256];
+ int mailIndexMthd;
+ char mailLogin[256];
+ int mailLoginMthd;
+ char mailCompose[256];
+ int mailComposeMthd;
+ char avatarGet[256];
+ int avatarGetMthd;
+ char avatarUpload[256];
+ int avatarUploadMthd;
+ char avatarRemove[256];
+ int avatarRemoveMthd;
+} TlenConfiguration;
+
+typedef struct {
+ BOOL useEncryption;
+ BOOL reconnect;
+ BOOL rosterSync;
+ BOOL offlineAsInvisible;
+ BOOL leaveOfflineMessage;
+ int offlineMessageOption;
+ BOOL ignoreAdvertisements;
+ int alertPolicy;
+ int groupChatPolicy;
+ int voiceChatPolicy;
+ int imagePolicy;
+ BOOL enableAvatars;
+ BOOL enableVersion;
+ BOOL useNudge;
+ BOOL logAlerts;
+ BOOL useNewP2P;
+ BOOL sendKeepAlive;
+ BOOL savePassword;
+} TlenOptions;
+
+struct JABBER_IQ_FUNC_STRUCT;
+struct JABBER_LIST_ITEM_STRUCT;
+struct TLEN_VOICE_CONTROL_STRUCT;
+
+typedef struct {
+ PROTO_INTERFACE iface;
+ HANDLE hNetlibUser;
+ HANDLE hFileNetlibUser;
+
+ JABBER_MODEMSGS modeMsgs;
+
+ struct ThreadDataStruct *threadData;
+ HANDLE hTlenNudge;
+ HANDLE hMenuMUC;
+ HANDLE hMenuChats;
+ HANDLE hMenuInbox;
+ HANDLE hMenuContactMUC;
+ HANDLE hMenuContactVoice;
+ HANDLE hMenuContactGrantAuth;
+ HANDLE hMenuContactRequestAuth;
+ HANDLE hMenuPicture;
+
+ HANDLE* hServices;
+ unsigned serviceNum;
+ HANDLE* hHooks;
+ unsigned hookNum;
+
+ int listsCount;
+ struct JABBER_LIST_ITEM_STRUCT *lists;
+ CRITICAL_SECTION csLists;
+
+ int iqCount;
+ int iqAlloced;
+ struct JABBER_IQ_FUNC_STRUCT *iqList;
+ CRITICAL_SECTION csIqList;
+
+ CRITICAL_SECTION csSerial;
+ unsigned int serial;
+ BOOL isOnline;
+ BOOL isConnected;
+
+ CRITICAL_SECTION modeMsgMutex;
+
+ HANDLE hMenuRoot;
+
+ char *searchJID;
+ int searchID;
+ int searchIndex;
+ char *searchQuery;
+ int searchQueryLen;
+
+ CRITICAL_SECTION csSend;
+
+ HWND voiceDlgHWND;
+ struct TLEN_VOICE_CONTROL_STRUCT *playbackControl;
+ struct TLEN_VOICE_CONTROL_STRUCT *recordingControl;
+ int framesAvailableForPlayback;
+ int availOverrunValue;
+
+ TlenOptions tlenOptions;
+} TlenProtocol;
+
+
+typedef struct ThreadDataStruct{
+ HANDLE hThread;
+ char *streamId;
+ char username[128];
+ char password[128];
+ char server[128];
+ char manualHost[128];
+ char avatarToken[128];
+ char avatarHash[64];
+ int avatarFormat;
+ WORD port;
+ BOOL useEncryption;
+
+ JABBER_SOCKET s; //HANDLE from CallService(MS_NETLIB_OPENCONNECTION (jabber_ws.c:68)
+ aes_context aes_in_context;
+ aes_context aes_out_context;
+ unsigned char aes_in_iv[16];
+ unsigned char aes_out_iv[16];
+
+ BOOL useAES;
+ TlenConfiguration tlenConfig;
+ TlenProtocol *proto;
+} ThreadData;
+
+
+typedef enum { FT_CONNECTING, FT_INITIALIZING, FT_RECEIVING, FT_DONE, FT_ERROR, FT_DENIED, FT_SWITCH } JABBER_FILE_STATE;
+typedef enum { FT_RECV, FT_SEND} JABBER_FILE_MODE;
+typedef struct TLEN_FILE_TRANSFER_STRUCT{
+ HANDLE hContact;
+ JABBER_SOCKET s;
+ NETLIBNEWCONNECTIONPROC_V2 pfnNewConnectionV2;
+ JABBER_FILE_STATE state;
+ char *jid;
+ int fileId;
+ char *iqId;
+ int mode;
+
+ // Used by file receiving only
+ char *hostName;
+ WORD wPort;
+ char *localName;
+ WORD wLocalPort;
+ char *szSavePath;
+ long fileReceivedBytes;
+ long fileTotalSize;
+
+ // Used by file sending only
+ HANDLE hFileEvent;
+ int fileCount;
+ char **files;
+ long *filesSize;
+ //long fileTotalSize; // Size of the current file (file being sent)
+ long allFileTotalSize;
+ long allFileReceivedBytes;
+ char *szDescription;
+ int currentFile;
+
+ // New p2p
+ BOOL newP2P;
+ char *id2;
+ SOCKET udps;
+ aes_context aes_context;
+ unsigned char aes_iv[16];
+ TlenProtocol *proto;
+
+} TLEN_FILE_TRANSFER;
+
+typedef struct {
+ PROTOSEARCHRESULT hdr;
+ char jid[256];
+} JABBER_SEARCH_RESULT;
+
+typedef struct {
+ char *iqId;
+ PROTOSEARCHRESULT hdr;
+ char jid[256];
+} TLEN_CONFERENCE;
+
+
+typedef struct {
+ int id;
+ TCHAR *name;
+} JABBER_FIELD_MAP;
+
+
+/*******************************************************************
+ * Global variables
+ *******************************************************************/
+extern HINSTANCE hInst;
+extern HANDLE hMainThread;
+
+/*******************************************************************
+ * Function declarations
+ *******************************************************************/
+HICON GetIcolibIcon(int iconId);
+void ReleaseIcolibIcon(HICON hIcon);
+
+void JabberLog(TlenProtocol *proto, const char *fmt, ...);
+void __cdecl JabberServerThread(ThreadData *info);
+// jabber_ws.c
+BOOL JabberWsInit(TlenProtocol *proto);
+void JabberWsUninit(TlenProtocol *proto);
+JABBER_SOCKET JabberWsConnect(TlenProtocol *proto, char *host, WORD port);
+int JabberWsSend(TlenProtocol *proto, JABBER_SOCKET s, char *data, int datalen);
+int JabberWsRecv(TlenProtocol *proto, JABBER_SOCKET s, char *data, long datalen);
+int JabberWsSendAES(TlenProtocol *proto, char *data, int datalen, aes_context *aes_ctx, unsigned char *aes_iv);
+int JabberWsRecvAES(TlenProtocol *proto, char *data, long datalen, aes_context *aes_ctx, unsigned char *aes_iv);
+// jabber_util.c
+HANDLE HookEventObj_Ex(const char *name, TlenProtocol *proto, MIRANDAHOOKOBJ hook);
+HANDLE CreateServiceFunction_Ex(const char *name, TlenProtocol *proto, MIRANDASERVICEOBJ service);
+void UnhookEvents_Ex(TlenProtocol *proto);
+void DestroyServices_Ex(TlenProtocol *proto);
+void JabberSerialInit(TlenProtocol *proto);
+void JabberSerialUninit(TlenProtocol *proto);
+unsigned int JabberSerialNext(TlenProtocol *proto);
+int JabberSend(TlenProtocol *proto, const char *fmt, ...);
+HANDLE JabberHContactFromJID(TlenProtocol *proto, const char *jid);
+char *JabberJIDFromHContact(TlenProtocol *proto, HANDLE hContact);
+char *JabberLoginFromJID(const char *jid);
+char *JabberResourceFromJID(const char *jid);
+char *JabberNickFromJID(const char *jid);
+char *JabberLocalNickFromJID(const char *jid);
+char *TlenGroupEncode(const char *str);
+char *TlenGroupDecode(const char *str);
+char *JabberSha1(char *str);
+char *TlenSha1(char *str, int len);
+char *TlenPasswordHash(const char *str);
+void TlenUrlDecode(char *str);
+char *TlenUrlEncode(const char *str);
+char *JabberTextEncode(const char *str);
+char *JabberTextDecode(const char *str);
+char *JabberBase64Encode(const char *buffer, int bufferLen);
+char *JabberBase64Decode(const char *buffer, int *resultLen);
+int JabberGetPictureType(const char* buf);
+void TlenLogMessage(TlenProtocol *proto, HANDLE hContact, DWORD flags, const char *message);
+BOOL IsAuthorized(TlenProtocol *proto, const char *jid);
+//char *JabberGetVersionText();
+time_t JabberIsoToUnixTime(char *stamp);
+time_t TlenTimeToUTC(time_t time);
+void JabberSendPresence(TlenProtocol *proto,int status);
+void JabberStringAppend(char **str, int *sizeAlloced, const char *fmt, ...);
+//char *JabberGetClientJID(char *jid);
+// jabber_misc.c
+void JabberDBAddEvent(TlenProtocol *proto, HANDLE hContact, int eventType, DWORD flags, PBYTE pBlob, DWORD cbBlob);
+void JabberDBAddAuthRequest(TlenProtocol *proto, char *jid, char *nick);
+HANDLE JabberDBCreateContact(TlenProtocol *proto, char *jid, char *nick, BOOL temporary);
+void JabberContactListCreateGroup(char *groupName);
+unsigned long JabberForkThread(void (__cdecl *threadcode)(void*), unsigned long stacksize, void *arg);
+// jabber_svc.c
+int JabberGetInfo(PROTO_INTERFACE *ptr, HANDLE hContact, int infoType);
+int TlenRunSearch(TlenProtocol *proto);
+// jabber_advsearch.c
+extern JABBER_FIELD_MAP tlenFieldGender[];
+extern JABBER_FIELD_MAP tlenFieldLookfor[];
+extern JABBER_FIELD_MAP tlenFieldStatus[];
+extern JABBER_FIELD_MAP tlenFieldOccupation[];
+extern JABBER_FIELD_MAP tlenFieldPlan[];
+
+INT_PTR CALLBACK TlenAdvSearchDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+char *TlenAdvSearchCreateQuery(HWND hwndDlg, int iqId);
+
+
+#endif
+
diff --git a/protocols/Tlen/jabber_iq.c b/protocols/Tlen/jabber_iq.c
new file mode 100644
index 0000000000..219f60e53d
--- /dev/null
+++ b/protocols/Tlen/jabber_iq.c
@@ -0,0 +1,114 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "jabber_iq.h"
+
+
+void JabberIqInit(TlenProtocol *proto)
+{
+ InitializeCriticalSection(&proto->csIqList);
+ proto->iqList = NULL;
+ proto->iqCount = 0;
+ proto->iqAlloced = 0;
+}
+
+void JabberIqUninit(TlenProtocol *proto)
+{
+ if (proto->iqList) mir_free(proto->iqList);
+ proto->iqList = NULL;
+ proto->iqCount = 0;
+ proto->iqAlloced = 0;
+ DeleteCriticalSection(&proto->csIqList);
+}
+
+static void JabberIqRemove(TlenProtocol *proto, int index)
+{
+ EnterCriticalSection(&proto->csIqList);
+ if (index>=0 && index<proto->iqCount) {
+ memmove(proto->iqList+index, proto->iqList+index+1, sizeof(JABBER_IQ_FUNC)*(proto->iqCount-index-1));
+ proto->iqCount--;
+ }
+ LeaveCriticalSection(&proto->csIqList);
+}
+
+static void JabberIqExpire(TlenProtocol *proto)
+{
+ int i;
+ time_t expire;
+
+ EnterCriticalSection(&proto->csIqList);
+ expire = time(NULL) - 120; // 2 minute
+ i = 0;
+ while (i < proto->iqCount) {
+ if (proto->iqList[i].requestTime < expire)
+ JabberIqRemove(proto, i);
+ else
+ i++;
+ }
+ LeaveCriticalSection(&proto->csIqList);
+}
+
+JABBER_IQ_PFUNC JabberIqFetchFunc(TlenProtocol *proto, int iqId)
+{
+ int i;
+ JABBER_IQ_PFUNC res;
+
+ EnterCriticalSection(&proto->csIqList);
+ JabberIqExpire(proto);
+ for (i=0; i<proto->iqCount && proto->iqList[i].iqId!=iqId; i++);
+ if (i < proto->iqCount) {
+ res = proto->iqList[i].func;
+ JabberIqRemove(proto, i);
+ }
+ else {
+ res = (JABBER_IQ_PFUNC) NULL;
+ }
+ LeaveCriticalSection(&proto->csIqList);
+ return res;
+}
+
+void JabberIqAdd(TlenProtocol *proto, unsigned int iqId, JABBER_IQ_PROCID procId, JABBER_IQ_PFUNC func)
+{
+ int i;
+
+ EnterCriticalSection(&proto->csIqList);
+ if (procId == IQ_PROC_NONE)
+ i = proto->iqCount;
+ else
+ for (i=0; i<proto->iqCount && proto->iqList[i].procId!=procId; i++);
+
+ if (i>=proto->iqCount && proto->iqCount>=proto->iqAlloced) {
+ proto->iqAlloced = proto->iqCount + 8;
+ proto->iqList = mir_realloc(proto->iqList, sizeof(JABBER_IQ_FUNC)*proto->iqAlloced);
+ }
+
+ if (proto->iqList != NULL) {
+ proto->iqList[i].iqId = iqId;
+ proto->iqList[i].procId = procId;
+ proto->iqList[i].func = func;
+ proto->iqList[i].requestTime = time(NULL);
+ if (i == proto->iqCount) proto->iqCount++;
+ }
+ LeaveCriticalSection(&proto->csIqList);
+}
+
diff --git a/protocols/Tlen/jabber_iq.h b/protocols/Tlen/jabber_iq.h
new file mode 100644
index 0000000000..dfdcf9e91a
--- /dev/null
+++ b/protocols/Tlen/jabber_iq.h
@@ -0,0 +1,61 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef _JABBER_IQ_H_
+#define _JABBER_IQ_H_
+
+#include "jabber_xml.h"
+#include "jabber.h"
+
+typedef void (*JABBER_IQ_PFUNC)(TlenProtocol *proto, XmlNode *iqNode);
+
+typedef struct JABBER_IQ_FUNC_STRUCT {
+ int iqId; // id to match IQ get/set with IQ result
+ JABBER_IQ_PROCID procId; // must be unique in the list, except for IQ_PROC_NONE which can have multiple entries
+ JABBER_IQ_PFUNC func; // callback function
+ time_t requestTime; // time the request was sent, used to remove relinquent entries
+} JABBER_IQ_FUNC;
+
+void JabberIqInit(TlenProtocol *proto);
+void JabberIqUninit(TlenProtocol *proto);
+JABBER_IQ_PFUNC JabberIqFetchFunc(TlenProtocol *proto, int iqId);
+void JabberIqAdd(TlenProtocol *proto, unsigned int iqId, JABBER_IQ_PROCID procId, JABBER_IQ_PFUNC func);
+
+void JabberIqResultAuth(TlenProtocol *proto, XmlNode *iqNode);
+void JabberIqResultRoster(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultVcard(TlenProtocol *proto, XmlNode *iqNode);
+void JabberIqResultSearch(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultVersion(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultInfo(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultTcfg(TlenProtocol *proto, XmlNode *iqNode);
+
+void TlenIqResultChatGroups(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultChatRooms(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultUserRooms(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultUserNicks(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultRoomSearch(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultRoomInfo(TlenProtocol *proto, XmlNode *iqNode);
+void TlenIqResultChatRoomUsers(TlenProtocol *proto, XmlNode *iqNode);
+//void JabberIqResultSetPassword(XmlNode *iqNode, void *userdata);
+
+#endif
+
diff --git a/protocols/Tlen/jabber_iqid.c b/protocols/Tlen/jabber_iqid.c
new file mode 100644
index 0000000000..2c16054038
--- /dev/null
+++ b/protocols/Tlen/jabber_iqid.c
@@ -0,0 +1,629 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "resource.h"
+#include "jabber_list.h"
+#include "jabber_iq.h"
+#include "tlen_muc.h"
+
+void JabberIqResultAuth(TlenProtocol *proto, XmlNode *iqNode)
+{
+ char *type;
+
+ // RECVED: authentication result
+ // ACTION: if successfully logged in, continue by requesting roster list and set my initial status
+ if ((type=JabberXmlGetAttrValue(iqNode, "type")) == NULL) return;
+
+ if (!strcmp(type, "result")) {
+ DBVARIANT dbv;
+
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "Nick", &dbv))
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "Nick", proto->threadData->username);
+ else
+ DBFreeVariant(&dbv);
+// iqId = JabberSerialNext();
+// JabberIqAdd(iqId, IQ_PROC_NONE, JabberIqResultGetRoster);
+// JabberSend(info, "<iq type='get' id='"JABBER_IQID"%d'><query xmlns='jabber:iq:roster'/></iq>", iqId);
+
+ JabberSend(proto, "<iq type='get' id='GetRoster'><query xmlns='jabber:iq:roster'/></iq>");
+ JabberSend(proto, "<iq to='tcfg' type='get' id='TcfgGetAfterLoggedIn'></iq>");
+ }
+ // What to do if password error? etc...
+ else if (!strcmp(type, "error")) {
+ char text[128];
+
+ JabberSend(proto, "</s>");
+ _snprintf(text, sizeof(text), "%s %s@%s.", TranslateT("Authentication failed for"), proto->threadData->username, proto->threadData->server);
+ MessageBoxA(NULL, text, Translate("Tlen Authentication"), MB_OK|MB_ICONSTOP|MB_SETFOREGROUND);
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_LOGIN, ACKRESULT_FAILED, NULL, LOGINERR_WRONGPASSWORD);
+ proto->threadData = NULL; // To disallow auto reconnect
+ }
+}
+
+void JabberResultSetRoster(TlenProtocol *proto, XmlNode *queryNode) {
+ DBVARIANT dbv;
+ XmlNode *itemNode, *groupNode;
+ JABBER_LIST_ITEM *item;
+ HANDLE hContact;
+ char *jid, *name, *nick;
+ int i;
+ char *str;
+
+ for (i=0; i<queryNode->numChild; i++) {
+ itemNode = queryNode->child[i];
+ if (!strcmp(itemNode->name, "item")) {
+ if ((jid=JabberXmlGetAttrValue(itemNode, "jid")) != NULL) {
+ str = JabberXmlGetAttrValue(itemNode, "subscription");
+ if (!strcmp(str, "remove")) {
+ if ((hContact=JabberHContactFromJID(proto, jid)) != NULL) {
+ if (DBGetContactSettingWord(hContact, proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE) != ID_STATUS_OFFLINE)
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE);
+ }
+ JabberListRemove(proto, LIST_ROSTER, jid);
+ } else {
+ item = JabberListAdd(proto, LIST_ROSTER, jid);
+ if (item != NULL) {
+ if (str == NULL) item->subscription = SUB_NONE;
+ else if (!strcmp(str, "both")) item->subscription = SUB_BOTH;
+ else if (!strcmp(str, "to")) item->subscription = SUB_TO;
+ else if (!strcmp(str, "from")) item->subscription = SUB_FROM;
+ else item->subscription = SUB_NONE;
+ if ((name=JabberXmlGetAttrValue(itemNode, "name")) != NULL) {
+ nick = JabberTextDecode(name);
+ } else {
+ nick = JabberLocalNickFromJID(jid);
+ }
+ if (nick != NULL) {
+ if (item->nick) mir_free(item->nick);
+ item->nick = nick;
+
+ if ((hContact=JabberHContactFromJID(proto, jid)) == NULL) {
+ // Received roster has a new JID.
+ // Add the jid (with empty resource) to Miranda contact list.
+ hContact = JabberDBCreateContact(proto, jid, nick, FALSE);
+ }
+ DBWriteContactSettingString(hContact, "CList", "MyHandle", nick);
+ if (item->group) mir_free(item->group);
+ if ((groupNode=JabberXmlGetChild(itemNode, "group"))!=NULL && groupNode->text!=NULL) {
+ item->group = TlenGroupDecode(groupNode->text);
+ JabberContactListCreateGroup(item->group);
+ // Don't set group again if already correct, or Miranda may show wrong group count in some case
+ if (!DBGetContactSetting(hContact, "CList", "Group", &dbv)) {
+ if (strcmp(dbv.pszVal, item->group))
+ DBWriteContactSettingString(hContact, "CList", "Group", item->group);
+ DBFreeVariant(&dbv);
+ } else
+ DBWriteContactSettingString(hContact, "CList", "Group", item->group);
+ } else {
+ item->group = NULL;
+ DBDeleteContactSetting(hContact, "CList", "Group");
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+void JabberIqResultRoster(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *queryNode;
+ char *type;
+ char *str;
+
+ // RECVED: roster information
+ // ACTION: populate LIST_ROSTER and create contact for any new rosters
+ if ((type=JabberXmlGetAttrValue(iqNode, "type")) == NULL) return;
+ if ((queryNode=JabberXmlGetChild(iqNode, "query")) == NULL) return;
+
+ if (!strcmp(type, "result")) {
+ str = JabberXmlGetAttrValue(queryNode, "xmlns");
+ if (str!=NULL && !strcmp(str, "jabber:iq:roster")) {
+ DBVARIANT dbv;
+ XmlNode *itemNode, *groupNode;
+ JABBER_SUBSCRIPTION sub;
+ JABBER_LIST_ITEM *item;
+ HANDLE hContact;
+ char *jid, *name, *nick;
+ int i, oldStatus;
+
+ for (i=0; i<queryNode->numChild; i++) {
+ itemNode = queryNode->child[i];
+ if (!strcmp(itemNode->name, "item")) {
+ str = JabberXmlGetAttrValue(itemNode, "subscription");
+ if (str==NULL) sub = SUB_NONE;
+ else if (!strcmp(str, "both")) sub = SUB_BOTH;
+ else if (!strcmp(str, "to")) sub = SUB_TO;
+ else if (!strcmp(str, "from")) sub = SUB_FROM;
+ else sub = SUB_NONE;
+ //if (str!=NULL && (!strcmp(str, "to") || !strcmp(str, "both"))) {
+ if ((jid=JabberXmlGetAttrValue(itemNode, "jid")) != NULL) {
+ if ((name=JabberXmlGetAttrValue(itemNode, "name")) != NULL) {
+ nick = JabberTextDecode(name);
+ } else {
+ nick = JabberLocalNickFromJID(jid);
+ }
+ if (nick != NULL) {
+ item = JabberListAdd(proto, LIST_ROSTER, jid);
+ if (item->nick) mir_free(item->nick);
+ item->nick = nick;
+ item->subscription = sub;
+ if ((hContact=JabberHContactFromJID(proto, jid)) == NULL) {
+ // Received roster has a new JID.
+ // Add the jid (with empty resource) to Miranda contact list.
+ hContact = JabberDBCreateContact(proto, jid, nick, FALSE);
+ }
+ DBWriteContactSettingString(hContact, "CList", "MyHandle", nick);
+ if (item->group) mir_free(item->group);
+ if ((groupNode=JabberXmlGetChild(itemNode, "group"))!=NULL && groupNode->text!=NULL) {
+ item->group = TlenGroupDecode(groupNode->text);
+ JabberContactListCreateGroup(item->group);
+ // Don't set group again if already correct, or Miranda may show wrong group count in some case
+ if (!DBGetContactSetting(hContact, "CList", "Group", &dbv)) {
+ if (strcmp(dbv.pszVal, item->group))
+ DBWriteContactSettingString(hContact, "CList", "Group", item->group);
+ DBFreeVariant(&dbv);
+ }
+ else
+ DBWriteContactSettingString(hContact, "CList", "Group", item->group);
+ }
+ else {
+ item->group = NULL;
+ DBDeleteContactSetting(hContact, "CList", "Group");
+ }
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "AvatarHash", &dbv)) {
+ if (item->avatarHash) mir_free(item->avatarHash);
+ item->avatarHash = mir_strdup(dbv.pszVal);
+ JabberLog(proto, "Setting hash [%s] = %s", nick, item->avatarHash);
+ DBFreeVariant(&dbv);
+ }
+ item->avatarFormat = DBGetContactSettingDword(hContact, proto->iface.m_szModuleName, "AvatarFormat", PA_FORMAT_UNKNOWN);
+ }
+ }
+ }
+ }
+ // Delete orphaned contacts (if roster sync is enabled)
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "RosterSync", FALSE) == TRUE) {
+ HANDLE *list;
+ int listSize, listAllocSize;
+
+ listSize = listAllocSize = 0;
+ list = NULL;
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ while (hContact != NULL) {
+ str = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if(str!=NULL && !strcmp(str, proto->iface.m_szModuleName)) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ if (!JabberListExist(proto, LIST_ROSTER, dbv.pszVal)) {
+ JabberLog(proto, "Syncing roster: preparing to delete %s (hContact=0x%x)", dbv.pszVal, hContact);
+ if (listSize >= listAllocSize) {
+ listAllocSize = listSize + 100;
+ if ((list=(HANDLE *) mir_realloc(list, listAllocSize)) == NULL) {
+ listSize = 0;
+ break;
+ }
+ }
+ list[listSize++] = hContact;
+ }
+ DBFreeVariant(&dbv);
+ }
+ }
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM) hContact, 0);
+ }
+ for (i=0; i<listSize; i++) {
+ JabberLog(proto, "Syncing roster: deleting 0x%x", list[i]);
+ CallService(MS_DB_CONTACT_DELETE, (WPARAM) list[i], 0);
+ }
+ if (list != NULL)
+ mir_free(list);
+ }
+ ///////////////////////////////////////
+ {
+ CLISTMENUITEM clmi;
+ memset(&clmi, 0, sizeof(CLISTMENUITEM));
+ clmi.cbSize = sizeof(CLISTMENUITEM);
+ clmi.flags = CMIM_FLAGS;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuMUC, (LPARAM) &clmi);
+ if (proto->hMenuChats != NULL){
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuChats, (LPARAM) &clmi);
+ }
+ }
+
+ proto->isOnline = TRUE;
+ JabberLog(proto, "Status changed via THREADSTART");
+ oldStatus = proto->iface.m_iStatus;
+ JabberSendPresence(proto, proto->iface.m_iDesiredStatus);
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, proto->iface.m_iStatus);
+ //////////////////////////////////
+ }
+ }
+}
+
+
+// Tlen actually use jabber:iq:search for other users vCard or jabber:iq:register for own vCard
+void TlenIqResultVcard(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *queryNode, *itemNode, *n;
+ char *type, *jid;
+ char text[128];
+ HANDLE hContact;
+ char *nText;
+
+// JabberLog("<iq/> iqIdGetVcard (tlen)");
+ if ((type=JabberXmlGetAttrValue(iqNode, "type")) == NULL) return;
+
+ if (!strcmp(type, "result")) {
+ BOOL hasFirst, hasLast, hasNick, hasEmail, hasCity, hasAge, hasGender, hasSchool, hasLookFor, hasOccupation;
+ DBVARIANT dbv;
+ int i;
+
+ if ((queryNode=JabberXmlGetChild(iqNode, "query")) == NULL) return;
+ if ((itemNode=JabberXmlGetChild(queryNode, "item")) == NULL) return;
+ if ((jid=JabberXmlGetAttrValue(itemNode, "jid")) != NULL) {
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) return;
+ if (strchr(jid, '@') != NULL) {
+ sprintf(text, "%s", jid);
+ } else {
+ sprintf(text, "%s@%s", jid, dbv.pszVal); // Add @tlen.pl
+ }
+ DBFreeVariant(&dbv);
+ if ((hContact=JabberHContactFromJID(proto, text)) == NULL) {
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginName", &dbv)) return;
+ if (strcmp(dbv.pszVal, jid)) {
+ DBFreeVariant(&dbv);
+ return;
+ }
+ DBFreeVariant(&dbv);
+ }
+ } else {
+ hContact = NULL;
+ }
+ hasFirst = hasLast = hasNick = hasEmail = hasCity = hasAge = hasGender = hasOccupation = hasLookFor = hasSchool = FALSE;
+ for (i=0; i<itemNode->numChild; i++) {
+ n = itemNode->child[i];
+ if (n==NULL || n->name==NULL) continue;
+ if (!strcmp(n->name, "first")) {
+ if (n->text != NULL) {
+ hasFirst = TRUE;
+ nText = JabberTextDecode(n->text);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "FirstName", nText);
+ mir_free(nText);
+ }
+ }
+ else if (!strcmp(n->name, "last")) {
+ if (n->text != NULL) {
+ hasLast = TRUE;
+ nText = JabberTextDecode(n->text);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "LastName", nText);
+ mir_free(nText);
+ }
+ }
+ else if (!strcmp(n->name, "nick")) {
+ if (n->text != NULL) {
+ hasNick = TRUE;
+ nText = JabberTextDecode(n->text);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "Nick", nText);
+ mir_free(nText);
+ }
+ }
+ else if (!strcmp(n->name, "email")) {
+ if (n->text != NULL) {
+ hasEmail = TRUE;
+ nText = JabberTextDecode(n->text);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "e-mail", nText);
+ mir_free(nText);
+ }
+ }
+ else if (!strcmp(n->name, "c")) {
+ if (n->text != NULL) {
+ hasCity = TRUE;
+ nText = JabberTextDecode(n->text);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "City", nText);
+ mir_free(nText);
+ }
+ }
+ else if (!strcmp(n->name, "b")) {
+ if (n->text != NULL) {
+ WORD nAge;
+ hasAge = TRUE;
+ nAge = atoi(n->text);
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "Age", nAge);
+ }
+ }
+ else if (!strcmp(n->name, "s")) {
+ if (n->text!=NULL && n->text[1]=='\0' && (n->text[0]=='1' || n->text[0]=='2')) {
+ hasGender = TRUE;
+ DBWriteContactSettingByte(hContact, proto->iface.m_szModuleName, "Gender", (BYTE) (n->text[0]=='1'?'M':'F'));
+ }
+ }
+ else if (!strcmp(n->name, "e")) {
+ if (n->text != NULL) {
+ hasSchool = TRUE;
+ nText = JabberTextDecode(n->text);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "School", nText);
+ mir_free(nText);
+ }
+ }
+ else if (!strcmp(n->name, "j")) {
+ if (n->text != NULL) {
+ WORD nOccupation;
+ hasOccupation = TRUE;
+ nOccupation = atoi(n->text);
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "Occupation", nOccupation);
+ }
+ }
+ else if (!strcmp(n->name, "r")) {
+ if (n->text != NULL) {
+ WORD nLookFor;
+ hasLookFor = TRUE;
+ nLookFor = atoi(n->text);
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "LookingFor", nLookFor);
+ }
+ }
+ else if (!strcmp(n->name, "g")) { // voice chat enabled
+ if (n->text != NULL) {
+ BYTE bVoice;
+ bVoice = atoi(n->text);
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "VoiceChat", bVoice);
+ }
+ }
+ else if (!strcmp(n->name, "v")) { // status visibility
+ if (n->text != NULL) {
+ BYTE bPublic;
+ bPublic = atoi(n->text);
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "PublicStatus", bPublic);
+ }
+ }
+ }
+ if (!hasFirst)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "FirstName");
+ if (!hasLast)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "LastName");
+ // We are not removing "Nick"
+// if (!hasNick)
+// DBDeleteContactSetting(hContact, iface.m_szModuleName, "Nick");
+ if (!hasEmail)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "e-mail");
+ if (!hasCity)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "City");
+ if (!hasAge)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "Age");
+ if (!hasGender)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "Gender");
+ if (!hasSchool)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "School");
+ if (!hasOccupation)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "Occupation");
+ if (!hasLookFor)
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "LookingFor");
+ ProtoBroadcastAck(proto->iface.m_szModuleName, hContact, ACKTYPE_GETINFO, ACKRESULT_SUCCESS, (HANDLE) 1, 0);
+ }
+}
+
+void JabberIqResultSearch(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *queryNode, *itemNode, *n;
+ char *type, *jid, *str;
+ int id, i, found;
+ JABBER_SEARCH_RESULT jsr = {0};
+ DBVARIANT dbv = {0};
+
+ found = 0;
+// JabberLog("<iq/> iqIdGetSearch");
+ if ((type=JabberXmlGetAttrValue(iqNode, "type")) == NULL) return;
+ if ((str=JabberXmlGetAttrValue(iqNode, "id")) == NULL) return;
+ id = atoi(str+strlen(JABBER_IQID));
+
+ if (!strcmp(type, "result")) {
+ if ((queryNode=JabberXmlGetChild(iqNode, "query")) == NULL) return;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ jsr.hdr.cbSize = sizeof(JABBER_SEARCH_RESULT);
+ for (i=0; i<queryNode->numChild; i++) {
+ itemNode = queryNode->child[i];
+ if (!strcmp(itemNode->name, "item")) {
+ if ((jid=JabberXmlGetAttrValue(itemNode, "jid")) != NULL) {
+ if (strchr(jid, '@') != NULL) {
+ _snprintf(jsr.jid, sizeof(jsr.jid), "%s", jid);
+ } else {
+ _snprintf(jsr.jid, sizeof(jsr.jid), "%s@%s", jid, dbv.pszVal);
+ }
+ jsr.jid[sizeof(jsr.jid)-1] = '\0';
+ jsr.hdr.id = jid;
+ jsr.hdr.flags = 0; //results are ansi
+ if ((n=JabberXmlGetChild(itemNode, "nick"))!=NULL && n->text!=NULL)
+ jsr.hdr.nick = JabberTextDecode(n->text);
+ else
+ jsr.hdr.nick = mir_strdup("");
+ if ((n=JabberXmlGetChild(itemNode, "first"))!=NULL && n->text!=NULL)
+ jsr.hdr.firstName = JabberTextDecode(n->text);
+ else
+ jsr.hdr.firstName = mir_strdup("");
+ if ((n=JabberXmlGetChild(itemNode, "last"))!=NULL && n->text!=NULL)
+ jsr.hdr.lastName = JabberTextDecode(n->text);
+ else
+ jsr.hdr.lastName = mir_strdup("");
+ if ((n=JabberXmlGetChild(itemNode, "email"))!=NULL && n->text!=NULL)
+ jsr.hdr.email = JabberTextDecode(n->text);
+ else
+ jsr.hdr.email = mir_strdup("");
+
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_SEARCH, ACKRESULT_DATA, (HANDLE) id, (LPARAM) &jsr);
+ found = 1;
+ mir_free(jsr.hdr.nick);
+ mir_free(jsr.hdr.firstName);
+ mir_free(jsr.hdr.lastName);
+ mir_free(jsr.hdr.email);
+ }
+ }
+ }
+ if (proto->searchJID!=NULL) {
+ if (!found) {
+ if (strchr(proto->searchJID, '@') != NULL) {
+ _snprintf(jsr.jid, sizeof(jsr.jid), "%s", proto->searchJID);
+ } else {
+ _snprintf(jsr.jid, sizeof(jsr.jid), "%s@%s", proto->searchJID, dbv.pszVal);
+ }
+ jsr.jid[sizeof(jsr.jid)-1] = '\0';
+ jsr.hdr.nick = mir_strdup("");
+ jsr.hdr.firstName = mir_strdup("");
+ jsr.hdr.lastName = mir_strdup("");
+ jsr.hdr.email = mir_strdup("");
+ jsr.hdr.id = mir_strdup("");
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_SEARCH, ACKRESULT_DATA, (HANDLE) id, (LPARAM) &jsr);
+ mir_free(jsr.hdr.nick);
+ mir_free(jsr.hdr.firstName);
+ mir_free(jsr.hdr.lastName);
+ mir_free(jsr.hdr.email);
+ }
+ mir_free(proto->searchJID);
+ proto->searchJID = NULL;
+ }
+ DBFreeVariant(&dbv);
+ }
+ found = 0;
+ if (queryNode->numChild == TLEN_MAX_SEARCH_RESULTS_PER_PAGE) {
+ found = TlenRunSearch(proto);
+ }
+ if (!found) {
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_SEARCH, ACKRESULT_SUCCESS, (HANDLE) id, 0);
+ }
+ } else if (!strcmp(type, "error")) {
+ // ProtoBroadcastAck(iface.m_szModuleName, NULL, ACKTYPE_SEARCH, ACKRESULT_FAILED, (HANDLE) id, 0);
+ // There is no ACKRESULT_FAILED for ACKTYPE_SEARCH :) look at findadd.c
+ // So we will just send a SUCCESS
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_SEARCH, ACKRESULT_SUCCESS, (HANDLE) id, 0);
+ }
+}
+
+
+void GetConfigItem(XmlNode *node, char *dest, BOOL bMethod, int *methodDest) {
+ strcpy(dest, node->text);
+ TlenUrlDecode(dest);
+ if (bMethod) {
+ char *method = JabberXmlGetAttrValue(node, "method");
+ if (method != NULL && !strcmpi(method, "POST")) {
+ *methodDest = REQUEST_POST;
+ } else {
+ *methodDest = REQUEST_GET;
+ }
+ }
+}
+
+void TlenIqResultTcfg(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *queryNode, *miniMailNode, *node;
+ char *type;
+
+ if ((type=JabberXmlGetAttrValue(iqNode, "type")) == NULL) return;
+ if (!strcmp(type, "result")) {
+ if ((queryNode=JabberXmlGetChild(iqNode, "query")) == NULL) return;
+ if ((miniMailNode=JabberXmlGetChild(queryNode, "mini-mail")) == NULL) return;
+ if ((node=JabberXmlGetChild(miniMailNode, "base")) != NULL) {
+ GetConfigItem(node, proto->threadData->tlenConfig.mailBase, FALSE, NULL);
+ }
+ if ((node=JabberXmlGetChild(miniMailNode, "msg")) != NULL) {
+ GetConfigItem(node, proto->threadData->tlenConfig.mailMsg, TRUE, &proto->threadData->tlenConfig.mailMsgMthd);
+ }
+ if ((node=JabberXmlGetChild(miniMailNode, "index")) != NULL) {
+ GetConfigItem(node, proto->threadData->tlenConfig.mailIndex, TRUE, &proto->threadData->tlenConfig.mailIndexMthd);
+ }
+ if ((node=JabberXmlGetChild(miniMailNode, "login")) != NULL) {
+ GetConfigItem(node, proto->threadData->tlenConfig.mailLogin, TRUE, &proto->threadData->tlenConfig.mailLoginMthd);
+ }
+ if ((node=JabberXmlGetChild(miniMailNode, "compose")) != NULL) {
+ GetConfigItem(node, proto->threadData->tlenConfig.mailCompose, TRUE, &proto->threadData->tlenConfig.mailComposeMthd);
+ }
+ if ((node=JabberXmlGetChild(miniMailNode, "avatar-get")) != NULL) {
+ GetConfigItem(node, proto->threadData->tlenConfig.avatarGet, TRUE, &proto->threadData->tlenConfig.avatarGetMthd);
+ }
+ if ((node=JabberXmlGetChild(miniMailNode, "avatar-upload")) != NULL) {
+ GetConfigItem(node, proto->threadData->tlenConfig.avatarUpload, TRUE, &proto->threadData->tlenConfig.avatarUploadMthd);
+ }
+ if ((node=JabberXmlGetChild(miniMailNode, "avatar-remove")) != NULL) {
+ GetConfigItem(node, proto->threadData->tlenConfig.avatarRemove, TRUE, &proto->threadData->tlenConfig.avatarRemoveMthd);
+ }
+ }
+}
+
+void TlenIqResultVersion(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *queryNode = JabberXmlGetChild(iqNode, "query");
+ if (queryNode != NULL) {
+ char* from;
+ if (( from=JabberXmlGetAttrValue( iqNode, "from" )) != NULL ) {
+ JABBER_LIST_ITEM *item;
+ if (( item=JabberListGetItemPtr( proto, LIST_ROSTER, from ))!=NULL) {
+ HANDLE hContact;
+ XmlNode *n;
+ if ( item->software ) mir_free( item->software );
+ if ( item->version ) mir_free( item->version );
+ if ( item->system ) mir_free( item->system );
+ if (( n=JabberXmlGetChild( queryNode, "name" ))!=NULL && n->text ) {
+ item->software = JabberTextDecode( n->text );
+ } else
+ item->software = NULL;
+ if (( n=JabberXmlGetChild( queryNode, "version" ))!=NULL && n->text )
+ item->version = JabberTextDecode( n->text );
+ else
+ item->version = NULL;
+ if (( n=JabberXmlGetChild( queryNode, "os" ))!=NULL && n->text )
+ item->system = JabberTextDecode( n->text );
+ else
+ item->system = NULL;
+ if (( hContact=JabberHContactFromJID(proto, item->jid )) != NULL ) {
+ if (item->software != NULL) {
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "MirVer", item->software);
+ } else {
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "MirVer");
+ }
+ }
+ }
+ }
+ }
+}
+
+void TlenIqResultInfo(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *queryNode = JabberXmlGetChild(iqNode, "query");
+ if (queryNode != NULL) {
+ char* from;
+ if (( from=JabberXmlGetAttrValue( queryNode, "from" )) != NULL ) {
+ JABBER_LIST_ITEM *item;
+ if (( item=JabberListGetItemPtr( proto, LIST_ROSTER, from ))!=NULL) {
+ HANDLE hContact;
+ XmlNode *version = JabberXmlGetChild(queryNode, "version");
+ item->protocolVersion = JabberTextDecode(version->text);
+ if (( hContact=JabberHContactFromJID(proto, item->jid )) != NULL ) {
+ if (item->software == NULL) {
+ char str[128];
+ mir_snprintf(str, sizeof(str), "Tlen Protocol %s", item->protocolVersion);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "MirVer", str);
+ }
+ }
+ }
+ }
+ }
+}
+
diff --git a/protocols/Tlen/jabber_list.c b/protocols/Tlen/jabber_list.c
new file mode 100644
index 0000000000..8b916b6584
--- /dev/null
+++ b/protocols/Tlen/jabber_list.c
@@ -0,0 +1,314 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "jabber_list.h"
+
+
+static void JabberListFreeItemInternal(JABBER_LIST_ITEM *item);
+
+void JabberListInit(TlenProtocol *proto)
+{
+ proto->lists = NULL;
+ proto->listsCount = 0;
+ InitializeCriticalSection(&proto->csLists);
+}
+
+void JabberListUninit(TlenProtocol *proto)
+{
+ JabberListWipe(proto);
+ DeleteCriticalSection(&proto->csLists);
+}
+
+void JabberListWipe(TlenProtocol *proto)
+{
+ int i;
+
+ EnterCriticalSection(&proto->csLists);
+ for(i=0; i<proto->listsCount; i++)
+ JabberListFreeItemInternal(&(proto->lists[i]));
+ if (proto->lists != NULL) {
+ mir_free(proto->lists);
+ proto->lists = NULL;
+ }
+ proto->listsCount=0;
+ LeaveCriticalSection(&proto->csLists);
+}
+
+void JabberListWipeSpecial(TlenProtocol *proto)
+{
+ int i;
+ EnterCriticalSection(&proto->csLists);
+ for(i=0; i<proto->listsCount; i++) {
+ if (proto->lists[i].list != LIST_FILE && proto->lists[i].list != LIST_VOICE) {
+ JabberListFreeItemInternal(&(proto->lists[i]));
+ proto->listsCount--;
+ memmove(proto->lists+i, proto->lists+i+1, sizeof(JABBER_LIST_ITEM)*(proto->listsCount-i));
+ i--;
+ }
+ }
+ proto->lists = (JABBER_LIST_ITEM *) mir_realloc(proto->lists, sizeof(JABBER_LIST_ITEM)*proto->listsCount);
+ LeaveCriticalSection(&proto->csLists);
+}
+
+static void JabberListFreeItemInternal(JABBER_LIST_ITEM *item)
+{
+ if (item == NULL)
+ return;
+
+ if (item->jid) mir_free(item->jid);
+ if (item->nick) mir_free(item->nick);
+ if (item->statusMessage) mir_free(item->statusMessage);
+ if (item->group) mir_free(item->group);
+ if (item->messageEventIdStr) mir_free(item->messageEventIdStr);
+// if (item->type) mir_free(item->type);
+ //if (item->ft) JabberFileFreeFt(item->ft); // No need to free (it is always free when exit from JabberFileServerThread())
+ if (item->roomName) mir_free(item->roomName);
+ if (item->version) mir_free(item->version);
+ if (item->software) mir_free(item->software);
+ if (item->system) mir_free(item->system);
+ if (item->avatarHash) mir_free(item->avatarHash);
+
+ if (item->protocolVersion) mir_free(item->protocolVersion);
+ if (item->id2) mir_free(item->id2);
+}
+
+static char * GetItemId(JABBER_LIST list, const char *jid)
+{
+ char *s, *p, *q;
+ s = mir_strdup(jid);
+ if (list != LIST_PICTURE) {
+ _strlwr(s);
+ // strip resouce name if any
+ if ((p=strchr(s, '@')) != NULL) {
+ if ((q=strchr(p, '/')) != NULL)
+ *q = '\0';
+ }
+ }
+ return s;
+}
+
+int JabberListExist(TlenProtocol *proto, JABBER_LIST list, const char *jid)
+{
+ int i;
+ size_t len;
+ char *s, *p;
+ s = GetItemId(list, jid);
+ len = strlen(s);
+
+ EnterCriticalSection(&proto->csLists);
+ for(i=0; i<proto->listsCount; i++)
+ if (proto->lists[i].list==list) {
+ p = proto->lists[i].jid;
+ if (p && strlen(p)>=len && (p[(int)len]=='\0'||p[(int)len]=='/') && !strncmp(p, s, len)) {
+ LeaveCriticalSection(&proto->csLists);
+ mir_free(s);
+ return i+1;
+ }
+ }
+ LeaveCriticalSection(&proto->csLists);
+ mir_free(s);
+ return 0;
+}
+
+JABBER_LIST_ITEM *JabberListAdd(TlenProtocol *proto, JABBER_LIST list, const char *jid)
+{
+ char *s;
+ JABBER_LIST_ITEM *item;
+
+ EnterCriticalSection(&proto->csLists);
+ if ((item=JabberListGetItemPtr(proto, list, jid)) != NULL) {
+ LeaveCriticalSection(&proto->csLists);
+ return item;
+ }
+
+ s = GetItemId(list, jid);
+ proto->lists = (JABBER_LIST_ITEM *) mir_realloc(proto->lists, sizeof(JABBER_LIST_ITEM)*(proto->listsCount+1));
+ item = &(proto->lists[proto->listsCount]);
+ memset(item, 0, sizeof(JABBER_LIST_ITEM));
+ item->list = list;
+ item->jid = s;
+ item->nick = NULL;
+ item->status = ID_STATUS_OFFLINE;
+ item->statusMessage = NULL;
+ item->group = NULL;
+ item->messageEventIdStr = NULL;
+ item->wantComposingEvent = FALSE;
+ item->isTyping = FALSE;
+// item->type = NULL;
+ item->ft = NULL;
+ item->roomName = NULL;
+ item->version = NULL;
+ item->software = NULL;
+ item->system = NULL;
+ item->avatarHash = NULL;
+ item->avatarFormat = PA_FORMAT_UNKNOWN;
+ item->newAvatarDownloading = FALSE;
+ item->versionRequested = FALSE;
+ item->infoRequested = FALSE;
+ proto->listsCount++;
+ LeaveCriticalSection(&proto->csLists);
+
+ return item;
+}
+
+void JabberListRemove(TlenProtocol *proto, JABBER_LIST list, const char *jid)
+{
+ int i;
+
+ EnterCriticalSection(&proto->csLists);
+ i = JabberListExist(proto, list, jid);
+ if (!i) {
+ LeaveCriticalSection(&proto->csLists);
+ return;
+ }
+ i--;
+ JabberListFreeItemInternal(&(proto->lists[i]));
+ proto->listsCount--;
+ memmove(proto->lists+i, proto->lists+i+1, sizeof(JABBER_LIST_ITEM)*(proto->listsCount-i));
+ proto->lists = (JABBER_LIST_ITEM *) mir_realloc(proto->lists, sizeof(JABBER_LIST_ITEM)*proto->listsCount);
+ LeaveCriticalSection(&proto->csLists);
+}
+
+void JabberListRemoveList(TlenProtocol *proto, JABBER_LIST list)
+{
+ int i;
+
+ i = 0;
+ while ((i=JabberListFindNext(proto, list, i)) >= 0) {
+ JabberListRemoveByIndex(proto, i);
+ }
+}
+
+void JabberListRemoveByIndex(TlenProtocol *proto, int index)
+{
+ EnterCriticalSection(&proto->csLists);
+ if (index>=0 && index<proto->listsCount) {
+ JabberListFreeItemInternal(&(proto->lists[index]));
+ proto->listsCount--;
+ memmove(proto->lists+index, proto->lists+index+1, sizeof(JABBER_LIST_ITEM)*(proto->listsCount-index));
+ proto->lists = (JABBER_LIST_ITEM *) mir_realloc(proto->lists, sizeof(JABBER_LIST_ITEM)*proto->listsCount);
+ }
+ LeaveCriticalSection(&proto->csLists);
+}
+
+void JabberListAddResource(TlenProtocol *proto, JABBER_LIST list, const char *jid, int status, const char *statusMessage)
+{
+ int i;
+
+ EnterCriticalSection(&proto->csLists);
+ i = JabberListExist(proto, list, jid);
+ if (!i) {
+ LeaveCriticalSection(&proto->csLists);
+ return;
+ }
+ i--;
+
+ if (proto->lists[i].statusMessage != NULL)
+ mir_free(proto->lists[i].statusMessage);
+ if (statusMessage)
+ proto->lists[i].statusMessage = mir_strdup(statusMessage);
+ else
+ proto->lists[i].statusMessage = NULL;
+ LeaveCriticalSection(&proto->csLists);
+}
+
+void JabberListRemoveResource(TlenProtocol *proto, JABBER_LIST list, const char *jid)
+{
+ int i;
+ EnterCriticalSection(&proto->csLists);
+ i = JabberListExist(proto, list, jid);
+ if (!i) {
+ LeaveCriticalSection(&proto->csLists);
+ return;
+ }
+ i--;
+ LeaveCriticalSection(&proto->csLists);
+}
+
+int JabberListFindNext(TlenProtocol *proto, JABBER_LIST list, int fromOffset)
+{
+ int i;
+
+ EnterCriticalSection(&proto->csLists);
+ i = (fromOffset>=0) ? fromOffset : 0;
+ for(; i<proto->listsCount; i++)
+ if (proto->lists[i].list == list) {
+ LeaveCriticalSection(&proto->csLists);
+ return i;
+ }
+ LeaveCriticalSection(&proto->csLists);
+ return -1;
+}
+
+JABBER_LIST_ITEM *JabberListGetItemPtr(TlenProtocol *proto, JABBER_LIST list, const char *jid)
+{
+ int i;
+
+ EnterCriticalSection(&proto->csLists);
+ i = JabberListExist(proto, list, jid);
+ if (!i) {
+ LeaveCriticalSection(&proto->csLists);
+ return NULL;
+ }
+ i--;
+ LeaveCriticalSection(&proto->csLists);
+ return &(proto->lists[i]);
+}
+
+JABBER_LIST_ITEM *JabberListFindItemPtrById2(TlenProtocol *proto, JABBER_LIST list, const char *id)
+{
+
+ int i;
+ size_t len;
+ char *p;
+
+ len = strlen(id);
+
+ EnterCriticalSection(&proto->csLists);
+ for(i=0; i<proto->listsCount; i++) {
+ if (proto->lists[i].list==list) {
+ p = proto->lists[i].id2;
+ if (p != NULL) {
+ if (!strncmp(p, id, len)) {
+ LeaveCriticalSection(&proto->csLists);
+ return &(proto->lists[i]);
+ }
+ }
+ }
+ }
+ LeaveCriticalSection(&proto->csLists);
+ return NULL;
+}
+
+JABBER_LIST_ITEM *JabberListGetItemPtrFromIndex(TlenProtocol *proto, int index)
+{
+ EnterCriticalSection(&proto->csLists);
+ if (index>=0 && index<proto->listsCount) {
+ LeaveCriticalSection(&proto->csLists);
+ return &(proto->lists[index]);
+ }
+ LeaveCriticalSection(&proto->csLists);
+ return NULL;
+}
+
diff --git a/protocols/Tlen/jabber_list.h b/protocols/Tlen/jabber_list.h
new file mode 100644
index 0000000000..116440a6a1
--- /dev/null
+++ b/protocols/Tlen/jabber_list.h
@@ -0,0 +1,90 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+
+#ifndef _JABBER_LIST_H_
+#define _JABBER_LIST_H_
+
+typedef struct JABBER_LIST_ITEM_STRUCT {
+ JABBER_LIST list;
+ char *jid;
+ char *id2;
+
+ // LIST_ROSTER
+ // jid = jid of the contact
+ char *nick;
+ int status; // Main status, currently useful for transport where no resource information is kept.
+ // On normal contact, this is the same status as shown on contact list.
+ JABBER_SUBSCRIPTION subscription;
+ char *statusMessage; // Status message when the update is to JID with no resource specified (e.g. transport user)
+ char *software;
+ char *version;
+ char *system;
+ char *group;
+ char *protocolVersion;
+ int avatarFormat;
+ char *avatarHash;
+ BOOL newAvatarDownloading;
+ BOOL versionRequested;
+ BOOL infoRequested;
+ int idMsgAckPending;
+ char *messageEventIdStr;
+ BOOL wantComposingEvent;
+ BOOL isTyping;
+
+ // LIST_ROOM
+ // jid = room JID
+ // char *name; // room name
+ //char *type; // room type
+
+ // LIST_CHATROOM
+ // jid = room JID
+ // char *nick; // my nick in this chat room (SPECIAL: in UTF8)
+ // JABBER_RESOURCE_STATUS *resource; // participant nicks in this room
+ char *roomName;
+
+ // LIST_FILE
+ struct TLEN_FILE_TRANSFER_STRUCT *ft;
+} JABBER_LIST_ITEM;
+
+
+void JabberListInit(TlenProtocol *proto);
+void JabberListUninit(TlenProtocol *proto);
+void JabberListWipe(TlenProtocol *proto);
+void JabberListWipeSpecial(TlenProtocol *proto);
+int JabberListExist(TlenProtocol *proto, JABBER_LIST list, const char *jid);
+JABBER_LIST_ITEM *JabberListAdd(TlenProtocol *proto, JABBER_LIST list, const char *jid);
+void JabberListRemove(TlenProtocol *proto, JABBER_LIST list, const char *jid);
+void JabberListRemoveList(TlenProtocol *proto, JABBER_LIST list);
+void JabberListRemoveByIndex(TlenProtocol *proto, int index);
+int JabberListFindNext(TlenProtocol *proto, JABBER_LIST list, int fromOffset);
+JABBER_LIST_ITEM *JabberListGetItemPtr(TlenProtocol *proto, JABBER_LIST list, const char *jid);
+JABBER_LIST_ITEM *JabberListGetItemPtrFromIndex(TlenProtocol *proto, int index);
+JABBER_LIST_ITEM *JabberListFindItemPtrById2(TlenProtocol *proto, JABBER_LIST list, const char *id);
+
+void JabberListAddResource(TlenProtocol *proto, JABBER_LIST list, const char *jid, int status, const char *statusMessage);
+void JabberListRemoveResource(TlenProtocol *proto, JABBER_LIST list, const char *jid);
+
+#endif
+
diff --git a/protocols/Tlen/jabber_misc.c b/protocols/Tlen/jabber_misc.c
new file mode 100644
index 0000000000..33ddf80f1e
--- /dev/null
+++ b/protocols/Tlen/jabber_misc.c
@@ -0,0 +1,219 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "jabber_list.h"
+
+void JabberDBAddEvent(TlenProtocol *proto, HANDLE hContact, int eventType, DWORD flags, PBYTE pBlob, DWORD cbBlob)
+{
+ DBEVENTINFO dbei = {0};
+ dbei.cbSize = sizeof(DBEVENTINFO);
+ dbei.szModule = proto->iface.m_szModuleName;
+ dbei.timestamp = (DWORD) time(NULL);
+ dbei.flags = flags;
+ dbei.eventType = eventType;
+ dbei.cbBlob = cbBlob;
+ dbei.pBlob = pBlob;
+ CallService(MS_DB_EVENT_ADD, (WPARAM) hContact, (LPARAM) &dbei);
+}
+void JabberDBAddAuthRequest(TlenProtocol *proto, char *jid, char *nick)
+{
+ char *s;
+ PBYTE pCurBlob;
+ PBYTE pBlob;
+ DWORD cbBlob;
+ HANDLE hContact;
+
+ if ((hContact=JabberHContactFromJID(proto, jid)) == NULL) {
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_ADD, 0, 0);
+ CallService(MS_PROTO_ADDTOCONTACT, (WPARAM) hContact, (LPARAM) proto->iface.m_szModuleName);
+ // strip resource if present
+ s = JabberLoginFromJID(jid);
+ _strlwr(s);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "jid", s);
+ mir_free(s);
+ }
+ else {
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "Hidden");
+ }
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "Nick", nick);
+ JabberLog(proto, "auth request: %s, %s", jid, nick);
+ //blob is: uin(DWORD), hContact(HANDLE), nick(ASCIIZ), first(ASCIIZ), last(ASCIIZ), email(ASCIIZ), reason(ASCIIZ)
+ //blob is: 0(DWORD), hContact(HANDLE), nick(ASCIIZ), ""(ASCIIZ), ""(ASCIIZ), email(ASCIIZ), ""(ASCIIZ)
+ cbBlob = sizeof(DWORD) + sizeof(HANDLE) + (int)strlen(nick) + (int)strlen(jid) + 5;
+ pBlob = pCurBlob = (PBYTE) mir_alloc(cbBlob);
+ *((PDWORD) pCurBlob) = 0; pCurBlob += sizeof(DWORD);
+ *((PHANDLE) pCurBlob) = hContact; pCurBlob += sizeof(HANDLE);
+ strcpy((char *) pCurBlob, nick); pCurBlob += strlen(nick)+1;
+ *pCurBlob = '\0'; pCurBlob++; //firstName
+ *pCurBlob = '\0'; pCurBlob++; //lastName
+ strcpy((char *) pCurBlob, jid); pCurBlob += strlen(jid)+1;
+ *pCurBlob = '\0'; //reason
+ JabberDBAddEvent(proto, NULL, EVENTTYPE_AUTHREQUEST, 0, pBlob, cbBlob);
+}
+
+char *JabberJIDFromHContact(TlenProtocol *proto, HANDLE hContact)
+{
+ char *p = NULL;
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ p = mir_strdup(dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ return p;
+}
+
+
+HANDLE JabberHContactFromJID(TlenProtocol *proto, const char *jid)
+{
+ HANDLE hContact, hContactMatched;
+ DBVARIANT dbv;
+ char *szProto;
+ char *p;
+ if (jid == NULL) return (HANDLE) NULL;
+ hContactMatched = NULL;
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ while (hContact != NULL) {
+ szProto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if (szProto!=NULL && !strcmp(proto->iface.m_szModuleName, szProto)) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ if ((p=dbv.pszVal) != NULL) {
+ if (!stricmp(p, jid)) { // exact match (node@domain/resource)
+ hContactMatched = hContact;
+ DBFreeVariant(&dbv);
+ break;
+ }
+ }
+ DBFreeVariant(&dbv);
+ }
+ }
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM) hContact, 0);
+ }
+ if (hContactMatched != NULL) {
+ return hContactMatched;
+ }
+ return NULL;
+}
+
+HANDLE JabberDBCreateContact(TlenProtocol *proto, char *jid, char *nick, BOOL temporary)
+{
+ HANDLE hContact;
+ if (jid==NULL || jid[0]=='\0')
+ return NULL;
+
+ if ((hContact=JabberHContactFromJID(proto, jid)) == NULL) {
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_ADD, 0, 0);
+ CallService(MS_PROTO_ADDTOCONTACT, (WPARAM) hContact, (LPARAM) proto->iface.m_szModuleName);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "jid", jid);
+ if (nick!=NULL && nick[0]!='\0')
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "Nick", nick);
+ if (temporary)
+ DBWriteContactSettingByte(hContact, "CList", "NotOnList", 1);
+ }
+ return hContact;
+}
+
+static void JabberContactListCreateClistGroup(char *groupName)
+{
+ char str[33], newName[128];
+ int i;
+ DBVARIANT dbv;
+ char *name;
+
+ for (i=0;;i++) {
+ itoa(i, str, 10);
+ if (DBGetContactSetting(NULL, "CListGroups", str, &dbv))
+ break;
+ name = dbv.pszVal;
+ if (name[0]!='\0' && !strcmp(name+1, groupName)) {
+ // Already exist, no need to create
+ DBFreeVariant(&dbv);
+ return;
+ }
+ DBFreeVariant(&dbv);
+ }
+
+ // Create new group with id = i (str is the text representation of i)
+ newName[0] = 1 | GROUPF_EXPANDED;
+ strncpy(newName+1, groupName, sizeof(newName)-1);
+ newName[sizeof(newName)-1] = '\0';
+ DBWriteContactSettingString(NULL, "CListGroups", str, newName);
+ CallService(MS_CLUI_GROUPADDED, i+1, 0);
+}
+
+void JabberContactListCreateGroup(char *groupName)
+{
+ char name[128];
+ char *p;
+
+ if (groupName==NULL || groupName[0]=='\0' || groupName[0]=='\\') return;
+
+ strncpy(name, groupName, sizeof(name));
+ name[sizeof(name)-1] = '\0';
+ for (p=name; *p!='\0'; p++) {
+ if (*p == '\\') {
+ *p = '\0';
+ JabberContactListCreateClistGroup(name);
+ *p = '\\';
+ }
+ }
+ JabberContactListCreateClistGroup(name);
+}
+
+
+struct FORK_ARG {
+ HANDLE hEvent;
+ void (__cdecl *threadcode)(void*);
+ void *arg;
+};
+
+static void __cdecl forkthread_r(struct FORK_ARG *fa)
+{
+ void (*callercode)(void*) = fa->threadcode;
+ void *arg = fa->arg;
+ CallService(MS_SYSTEM_THREAD_PUSH, 0, 0);
+ SetEvent(fa->hEvent);
+ callercode(arg);
+ CallService(MS_SYSTEM_THREAD_POP, 0, 0);
+ return;
+}
+
+unsigned long JabberForkThread(
+ void (__cdecl *threadcode)(void*),
+ unsigned long stacksize,
+ void *arg
+)
+{
+ unsigned long rc;
+ struct FORK_ARG fa;
+
+ fa.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ fa.threadcode = threadcode;
+ fa.arg = arg;
+ rc = _beginthread((void (__cdecl *)(void*))forkthread_r, stacksize, &fa);
+ if ((unsigned long) -1L != rc) {
+ WaitForSingleObject(fa.hEvent, INFINITE);
+ }
+ CloseHandle(fa.hEvent);
+ return rc;
+}
diff --git a/protocols/Tlen/jabber_opt.c b/protocols/Tlen/jabber_opt.c
new file mode 100644
index 0000000000..3ef45e4289
--- /dev/null
+++ b/protocols/Tlen/jabber_opt.c
@@ -0,0 +1,708 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "jabber_list.h"
+#include "tlen_voice.h"
+#include <commctrl.h>
+#include "resource.h"
+
+static INT_PTR CALLBACK TlenBasicOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK TlenVoiceOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK TlenAdvOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK TlenPopupsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+typedef struct TabDefStruct {
+ DLGPROC dlgProc;
+ DWORD dlgId;
+ TCHAR *tabName;
+} TabDef;
+
+static TabDef tabPages[] = {
+ {TlenBasicOptDlgProc, IDD_OPTIONS_BASIC, _T("General")},
+ {TlenVoiceOptDlgProc, IDD_OPTIONS_VOICE, _T("Voice Chats")},
+ {TlenAdvOptDlgProc, IDD_OPTIONS_ADVANCED, _T("Advanced")},
+ {TlenPopupsDlgProc, IDD_OPTIONS_POPUPS, _T("Notifications")}
+ };
+
+void TlenLoadOptions(TlenProtocol *proto)
+{
+ proto->tlenOptions.savePassword = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "SavePassword", TRUE);
+ proto->tlenOptions.useEncryption = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "UseEncryption", TRUE);
+ proto->tlenOptions.reconnect = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "Reconnect", TRUE);
+ proto->tlenOptions.alertPolicy = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "AlertPolicy", TLEN_ALERTS_IGNORE_NIR);
+ proto->tlenOptions.rosterSync = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "RosterSync", FALSE);
+ proto->tlenOptions.offlineAsInvisible = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "OfflineAsInvisible", FALSE);
+ proto->tlenOptions.leaveOfflineMessage = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "LeaveOfflineMessage", TRUE);
+ proto->tlenOptions.offlineMessageOption = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "OfflineMessageOption", 0);
+ proto->tlenOptions.ignoreAdvertisements = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "IgnoreAdvertisements", TRUE);
+ proto->tlenOptions.groupChatPolicy = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "GroupChatPolicy", TLEN_MUC_ASK);
+ proto->tlenOptions.voiceChatPolicy = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "VoiceChatPolicy", TLEN_MUC_ASK);
+ proto->tlenOptions.imagePolicy = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "ImagePolicy",TLEN_IMAGES_IGNORE_NIR);
+ proto->tlenOptions.enableAvatars = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "EnableAvatars", TRUE);
+ proto->tlenOptions.enableVersion = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "EnableVersion", TRUE);
+ proto->tlenOptions.useNudge = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "UseNudge", FALSE);
+ proto->tlenOptions.logAlerts = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "LogAlerts", TRUE);
+ proto->tlenOptions.sendKeepAlive = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "KeepAlive", TRUE);
+ proto->tlenOptions.useNewP2P = TRUE;
+}
+
+static int changed = 0;
+
+static void ApplyChanges(TlenProtocol *proto, int i) {
+ changed &= ~i;
+ if (changed == 0) {
+ TlenLoadOptions(proto);
+ }
+}
+
+static void MarkChanges(int i, HWND hWnd) {
+ SendMessage(GetParent(hWnd), PSM_CHANGED, 0, 0);
+ changed |= i;
+}
+
+
+int TlenOptionsInit(TlenProtocol *proto, WPARAM wParam, LPARAM lParam)
+{
+ int i;
+ OPTIONSDIALOGPAGE odp = { 0 };
+ odp.cbSize = sizeof(odp);
+ odp.hInstance = hInst;
+ odp.ptszGroup = TranslateT("Network");
+ odp.ptszTitle = proto->iface.m_tszUserName;
+ odp.flags = ODPF_BOLDGROUPS | ODPF_TCHAR;
+ odp.dwInitParam = (LPARAM)proto;
+ for (i = 0; i < SIZEOF(tabPages); i++) {
+ odp.pszTemplate = MAKEINTRESOURCEA(tabPages[i].dlgId);
+ odp.pfnDlgProc = tabPages[i].dlgProc;
+ odp.ptszTab = tabPages[i].tabName;
+ CallService(MS_OPT_ADDPAGE, wParam, (LPARAM) & odp);
+ }
+/*
+ if (ServiceExists(MS_POPUP_ADDPOPUP)) {
+ ZeroMemory(&odp,sizeof(odp));
+ odp.cbSize = sizeof(odp);
+ odp.position = 100000000;
+ odp.hInstance = hInst;
+ odp.flags = ODPF_BOLDGROUPS | ODPF_TCHAR;
+ odp.ptszGroup = TranslateT("PopUps");
+ odp.ptszTitle = proto->iface.m_tszUserName;
+ odp.dwInitParam = (LPARAM)proto;
+ odp.pszTemplate = MAKEINTRESOURCEA(IDD_OPTIONS_POPUPS);
+ odp.pfnDlgProc = TlenPopupsDlgProc;
+ CallService(MS_OPT_ADDPAGE,wParam,(LPARAM)&odp);
+ }
+ */
+ return 0;
+}
+
+static LRESULT CALLBACK JabberValidateUsernameWndProc(HWND hwndEdit, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ WNDPROC oldProc = (WNDPROC) GetWindowLongPtr(hwndEdit, GWLP_USERDATA);
+
+ switch (msg) {
+ case WM_CHAR:
+ if (strchr("\"&'/:<>@", wParam&0xff) != NULL)
+ return 0;
+ break;
+ }
+ return CallWindowProc(oldProc, hwndEdit, msg, wParam, lParam);
+}
+
+INT_PTR CALLBACK TlenAccMgrUIDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char text[256];
+ WNDPROC oldProc;
+
+ TlenProtocol *proto = (TlenProtocol *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ {
+ DBVARIANT dbv;
+ proto = (TlenProtocol *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)proto);
+ TranslateDialogDefault(hwndDlg);
+ if (!DBGetContactSettingTString(NULL, proto->iface.m_szModuleName, "LoginName", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_EDIT_USERNAME, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ }
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "Password", &dbv)) {
+ CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1, (LPARAM) dbv.pszVal);
+ SetDlgItemTextA(hwndDlg, IDC_EDIT_PASSWORD, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ CheckDlgButton(hwndDlg, IDC_SAVEPASSWORD, DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "SavePassword", TRUE));
+
+ oldProc = (WNDPROC) GetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT_USERNAME), GWLP_WNDPROC);
+ SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT_USERNAME), GWLP_USERDATA, (LONG_PTR) oldProc);
+ SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT_USERNAME), GWLP_WNDPROC, (LONG_PTR) JabberValidateUsernameWndProc);
+ return TRUE;
+ }
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_EDIT_USERNAME:
+ case IDC_EDIT_PASSWORD:
+ if ((HWND)lParam==GetFocus() && HIWORD(wParam)==EN_CHANGE)
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ break;
+ case IDC_SAVEPASSWORD:
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ break;
+ case IDC_REGISTERACCOUNT:
+ CallService(MS_UTILS_OPENURL, (WPARAM) 1, (LPARAM) TLEN_REGISTER);
+ break;
+ }
+ break;
+ case WM_NOTIFY:
+ switch (((LPNMHDR) lParam)->code) {
+ case PSN_APPLY:
+ {
+ BOOL reconnectRequired = FALSE;
+ DBVARIANT dbv;
+
+ GetDlgItemTextA(hwndDlg, IDC_EDIT_USERNAME, text, sizeof(text));
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginName", &dbv) || strcmp(text, dbv.pszVal))
+ reconnectRequired = TRUE;
+ if (dbv.pszVal != NULL) DBFreeVariant(&dbv);
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "LoginName", strlwr(text));
+
+ if (IsDlgButtonChecked(hwndDlg, IDC_SAVEPASSWORD)) {
+ GetDlgItemTextA(hwndDlg, IDC_EDIT_PASSWORD, text, sizeof(text));
+ CallService(MS_DB_CRYPT_ENCODESTRING, sizeof(text), (LPARAM) text);
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "Password", &dbv) || strcmp(text, dbv.pszVal))
+ reconnectRequired = TRUE;
+ if (dbv.pszVal != NULL) DBFreeVariant(&dbv);
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "Password", text);
+ }
+ else
+ DBDeleteContactSetting(NULL, proto->iface.m_szModuleName, "Password");
+
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "SavePassword", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_SAVEPASSWORD));
+ if (reconnectRequired && proto->isConnected)
+ MessageBox(hwndDlg, TranslateT("These changes will take effect the next time you connect to the Tlen network."), TranslateT("Tlen Protocol Option"), MB_OK|MB_SETFOREGROUND);
+ TlenLoadOptions(proto);
+ return TRUE;
+ }
+ }
+ break;
+ }
+ return FALSE;
+}
+
+static INT_PTR CALLBACK TlenBasicOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char text[256];
+ WNDPROC oldProc;
+
+ TlenProtocol *proto = (TlenProtocol *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ {
+ DBVARIANT dbv;
+ proto = (TlenProtocol *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)proto);
+ TranslateDialogDefault(hwndDlg);
+ if (!DBGetContactSettingTString(NULL, proto->iface.m_szModuleName, "LoginName", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_EDIT_USERNAME, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ }
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "Password", &dbv)) {
+ CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1, (LPARAM) dbv.pszVal);
+ SetDlgItemTextA(hwndDlg, IDC_EDIT_PASSWORD, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ CheckDlgButton(hwndDlg, IDC_SAVEPASSWORD, DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "SavePassword", TRUE));
+
+ CheckDlgButton(hwndDlg, IDC_RECONNECT, proto->tlenOptions.reconnect);
+ CheckDlgButton(hwndDlg, IDC_ROSTER_SYNC, proto->tlenOptions.rosterSync);
+ CheckDlgButton(hwndDlg, IDC_SHOW_OFFLINE, proto->tlenOptions.offlineAsInvisible);
+ CheckDlgButton(hwndDlg, IDC_OFFLINE_MESSAGE, proto->tlenOptions.leaveOfflineMessage);
+ CheckDlgButton(hwndDlg, IDC_IGNORE_ADVERTISEMENTS, proto->tlenOptions.ignoreAdvertisements);
+ CheckDlgButton(hwndDlg, IDC_AVATARS, proto->tlenOptions.enableAvatars);
+ CheckDlgButton(hwndDlg, IDC_VERSIONINFO, proto->tlenOptions.enableVersion);
+ CheckDlgButton(hwndDlg, IDC_NUDGE_SUPPORT, proto->tlenOptions.useNudge);
+ CheckDlgButton(hwndDlg, IDC_LOG_ALERTS, proto->tlenOptions.logAlerts);
+
+ SendDlgItemMessage(hwndDlg, IDC_ALERT_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Accept all alerts"));
+ SendDlgItemMessage(hwndDlg, IDC_ALERT_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Ignore alerts from unauthorized contacts"));
+ SendDlgItemMessage(hwndDlg, IDC_ALERT_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Ignore all alerts"));
+ SendDlgItemMessage(hwndDlg, IDC_ALERT_POLICY, CB_SETCURSEL, proto->tlenOptions.alertPolicy, 0);
+
+ SendDlgItemMessage(hwndDlg, IDC_MUC_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Always ask me"));
+ SendDlgItemMessage(hwndDlg, IDC_MUC_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Accept invitations from authorized contacts"));
+ SendDlgItemMessage(hwndDlg, IDC_MUC_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Accept all invitations"));
+ SendDlgItemMessage(hwndDlg, IDC_MUC_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Ignore invitations from unauthorized contacts"));
+ SendDlgItemMessage(hwndDlg, IDC_MUC_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Ignore all invitation"));
+ SendDlgItemMessage(hwndDlg, IDC_MUC_POLICY, CB_SETCURSEL, proto->tlenOptions.groupChatPolicy, 0);
+
+ SendDlgItemMessage(hwndDlg, IDC_IMAGE_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Accept all images"));
+ SendDlgItemMessage(hwndDlg, IDC_IMAGE_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Ignore images from unauthorized contacts"));
+ SendDlgItemMessage(hwndDlg, IDC_IMAGE_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Ignore all images"));
+ SendDlgItemMessage(hwndDlg, IDC_IMAGE_POLICY, CB_SETCURSEL, proto->tlenOptions.imagePolicy, 0);
+
+ SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_ADDSTRING, 0, (LPARAM)TranslateT("<Last message>"));
+ //SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_ADDSTRING, 0, (LPARAM)TranslateT("<Ask me>"));
+ SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_ADDSTRING, 0, (LPARAM)TranslateT("Online"));
+ SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_ADDSTRING, 0, (LPARAM)TranslateT("Away"));
+ SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_ADDSTRING, 0, (LPARAM)TranslateT("NA"));
+ SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_ADDSTRING, 0, (LPARAM)TranslateT("DND"));
+ SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_ADDSTRING, 0, (LPARAM)TranslateT("Free for chat"));
+ SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_ADDSTRING, 0, (LPARAM)TranslateT("Invisible"));
+ SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_SETCURSEL, proto->tlenOptions.offlineMessageOption, 0);
+
+ oldProc = (WNDPROC) GetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT_USERNAME), GWLP_WNDPROC);
+ SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT_USERNAME), GWLP_USERDATA, (LONG_PTR) oldProc);
+ SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT_USERNAME), GWLP_WNDPROC, (LONG_PTR) JabberValidateUsernameWndProc);
+ return TRUE;
+ }
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_EDIT_USERNAME:
+ case IDC_EDIT_PASSWORD:
+ if ((HWND)lParam==GetFocus() && HIWORD(wParam)==EN_CHANGE)
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ break;
+ // Fall through
+ case IDC_SAVEPASSWORD:
+ case IDC_RECONNECT:
+ case IDC_ROSTER_SYNC:
+ case IDC_IGNORE_ADVERTISEMENTS:
+ case IDC_SHOW_OFFLINE:
+ case IDC_OFFLINE_MESSAGE:
+ MarkChanges(1, hwndDlg);
+ break;
+ case IDC_LOG_ALERTS:
+ CheckDlgButton(hwndDlg, IDC_NUDGE_SUPPORT, BST_UNCHECKED);
+ MarkChanges(1, hwndDlg);
+ break;
+ case IDC_NUDGE_SUPPORT:
+ CheckDlgButton(hwndDlg, IDC_LOG_ALERTS, BST_UNCHECKED);
+ MarkChanges(1, hwndDlg);
+ break;
+ case IDC_REGISTERACCOUNT:
+ CallService(MS_UTILS_OPENURL, (WPARAM) 1, (LPARAM) TLEN_REGISTER);
+ break;
+ case IDC_OFFLINE_MESSAGE_OPTION:
+ case IDC_ALERT_POLICY:
+ case IDC_MUC_POLICY:
+ if (HIWORD(wParam) == CBN_SELCHANGE)
+ MarkChanges(1, hwndDlg);
+ break;
+ default:
+ MarkChanges(1, hwndDlg);
+ break;
+ }
+ break;
+ case WM_NOTIFY:
+ switch (((LPNMHDR) lParam)->code) {
+ case PSN_APPLY:
+ {
+ BOOL reconnectRequired = FALSE;
+ DBVARIANT dbv;
+
+ GetDlgItemTextA(hwndDlg, IDC_EDIT_USERNAME, text, sizeof(text));
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginName", &dbv) || strcmp(text, dbv.pszVal))
+ reconnectRequired = TRUE;
+ if (dbv.pszVal != NULL) DBFreeVariant(&dbv);
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "LoginName", strlwr(text));
+
+ if (IsDlgButtonChecked(hwndDlg, IDC_SAVEPASSWORD)) {
+ GetDlgItemTextA(hwndDlg, IDC_EDIT_PASSWORD, text, sizeof(text));
+ CallService(MS_DB_CRYPT_ENCODESTRING, sizeof(text), (LPARAM) text);
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "Password", &dbv) || strcmp(text, dbv.pszVal))
+ reconnectRequired = TRUE;
+ if (dbv.pszVal != NULL) DBFreeVariant(&dbv);
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "Password", text);
+ }
+ else
+ DBDeleteContactSetting(NULL, proto->iface.m_szModuleName, "Password");
+
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "SavePassword", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_SAVEPASSWORD));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "Reconnect", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_RECONNECT));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "RosterSync", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_ROSTER_SYNC));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "OfflineAsInvisible", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_SHOW_OFFLINE));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "IgnoreAdvertisements", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_IGNORE_ADVERTISEMENTS));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "LeaveOfflineMessage", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_OFFLINE_MESSAGE));
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "OfflineMessageOption", (WORD) SendDlgItemMessage(hwndDlg, IDC_OFFLINE_MESSAGE_OPTION, CB_GETCURSEL, 0, 0));
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "AlertPolicy", (WORD) SendDlgItemMessage(hwndDlg, IDC_ALERT_POLICY, CB_GETCURSEL, 0, 0));
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "GroupChatPolicy", (WORD) SendDlgItemMessage(hwndDlg, IDC_MUC_POLICY, CB_GETCURSEL, 0, 0));
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "ImagePolicy", (WORD) SendDlgItemMessage(hwndDlg, IDC_IMAGE_POLICY, CB_GETCURSEL, 0, 0));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "EnableAvatars", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_AVATARS));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "EnableVersion", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_VERSIONINFO));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "UseNudge", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_NUDGE_SUPPORT));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "LogAlerts", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_LOG_ALERTS));
+ if (reconnectRequired && proto->isConnected)
+ MessageBox(hwndDlg, TranslateT("These changes will take effect the next time you connect to the Tlen network."), TranslateT("Tlen Protocol Option"), MB_OK|MB_SETFOREGROUND);
+ ApplyChanges(proto, 1);
+ return TRUE;
+ }
+ }
+ break;
+ }
+ return FALSE;
+}
+
+static INT_PTR CALLBACK TlenVoiceOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ TlenProtocol *proto = (TlenProtocol *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ {
+ proto = (TlenProtocol *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)proto);
+ SendDlgItemMessage(hwndDlg, IDC_VOICE_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Always ask me"));
+ SendDlgItemMessage(hwndDlg, IDC_VOICE_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Accept invitations from authorized contacts"));
+ SendDlgItemMessage(hwndDlg, IDC_VOICE_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Accept all invitations"));
+ SendDlgItemMessage(hwndDlg, IDC_VOICE_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Ignore invitations from unauthorized contacts"));
+ SendDlgItemMessage(hwndDlg, IDC_VOICE_POLICY, CB_ADDSTRING, 0, (LPARAM)TranslateT("Ignore all invitation"));
+ SendDlgItemMessage(hwndDlg, IDC_VOICE_POLICY, CB_SETCURSEL, proto->tlenOptions.voiceChatPolicy, 0);
+ TlenVoiceBuildInDeviceList(proto, GetDlgItem(hwndDlg, IDC_VOICE_DEVICE_IN));
+ TlenVoiceBuildOutDeviceList(proto, GetDlgItem(hwndDlg, IDC_VOICE_DEVICE_OUT));
+ return TRUE;
+ }
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_VOICE_POLICY:
+ case IDC_VOICE_DEVICE_IN:
+ case IDC_VOICE_DEVICE_OUT:
+ if (HIWORD(wParam) == CBN_SELCHANGE)
+ MarkChanges(2, hwndDlg);
+ break;
+ }
+ break;
+ case WM_NOTIFY:
+ switch (((LPNMHDR) lParam)->code) {
+ case PSN_APPLY:
+ {
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "VoiceChatPolicy", (WORD) SendDlgItemMessage(hwndDlg, IDC_VOICE_POLICY, CB_GETCURSEL, 0, 0));
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "VoiceDeviceIn", (WORD) SendDlgItemMessage(hwndDlg, IDC_VOICE_DEVICE_IN, CB_GETCURSEL, 0, 0));
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "VoiceDeviceOut", (WORD) SendDlgItemMessage(hwndDlg, IDC_VOICE_DEVICE_OUT, CB_GETCURSEL, 0, 0));
+ ApplyChanges(proto, 2);
+ return TRUE;
+ }
+ }
+ break;
+ }
+
+ return FALSE;
+}
+
+static INT_PTR CALLBACK TlenAdvOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char text[256];
+ BOOL bChecked;
+ TlenProtocol *proto = (TlenProtocol *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+
+ switch (msg) {
+ case WM_INITDIALOG:
+ {
+ DBVARIANT dbv;
+ proto = (TlenProtocol *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)proto);
+ TranslateDialogDefault(hwndDlg);
+ if (!DBGetContactSettingTString(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_EDIT_LOGIN_SERVER, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ } else {
+ SetDlgItemText(hwndDlg, IDC_EDIT_LOGIN_SERVER, _T("tlen.pl"));
+ }
+
+ EnableWindow(GetDlgItem(hwndDlg, IDC_HOST), TRUE);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_HOSTPORT), TRUE);
+
+ if (!DBGetContactSettingTString(NULL, proto->iface.m_szModuleName, "ManualHost", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_HOST, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ } else
+ SetDlgItemText(hwndDlg, IDC_HOST, _T("s1.tlen.pl"));
+ SetDlgItemInt(hwndDlg, IDC_HOSTPORT, DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "ManualPort", TLEN_DEFAULT_PORT), FALSE);
+
+ CheckDlgButton(hwndDlg, IDC_KEEPALIVE, DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "KeepAlive", TRUE));
+
+ CheckDlgButton(hwndDlg, IDC_USE_SSL, DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "UseEncryption", TRUE));
+
+ CheckDlgButton(hwndDlg, IDC_VISIBILITY_SUPPORT, DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "VisibilitySupport", FALSE));
+ // File transfer options
+ bChecked = FALSE;
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "UseFileProxy", FALSE) == TRUE) {
+ bChecked = TRUE;
+ CheckDlgButton(hwndDlg, IDC_FILE_USE_PROXY, TRUE);
+ }
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_TYPE_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_TYPE), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_HOST_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_HOST), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_PORT_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_PORT), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_USE_AUTH), bChecked);
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "FileProxyAuth", FALSE) == TRUE) {
+ CheckDlgButton(hwndDlg, IDC_FILE_PROXY_USE_AUTH, TRUE);
+ } else {
+ bChecked = FALSE;
+ }
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_USER_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_USER), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_PASSWORD_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_PASSWORD), bChecked);
+
+ SendDlgItemMessage(hwndDlg, IDC_FILE_PROXY_TYPE, CB_ADDSTRING, 0, (LPARAM)TranslateT("Forwarding"));
+ SendDlgItemMessage(hwndDlg, IDC_FILE_PROXY_TYPE, CB_ADDSTRING, 0, (LPARAM)TranslateT("SOCKS4"));
+ SendDlgItemMessage(hwndDlg, IDC_FILE_PROXY_TYPE, CB_ADDSTRING, 0, (LPARAM)TranslateT("SOCKS5"));
+ SendDlgItemMessage(hwndDlg, IDC_FILE_PROXY_TYPE, CB_SETCURSEL, DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "FileProxyType", 0), 0);
+ if (!DBGetContactSettingTString(NULL, proto->iface.m_szModuleName, "FileProxyHost", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_FILE_PROXY_HOST, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ }
+ SetDlgItemInt(hwndDlg, IDC_FILE_PROXY_PORT, DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "FileProxyPort", 0), FALSE);
+ if (!DBGetContactSettingTString(NULL, proto->iface.m_szModuleName, "FileProxyUsername", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_FILE_PROXY_USER, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ }
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "FileProxyPassword", &dbv)) {
+ CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1, (LPARAM) dbv.pszVal);
+ SetDlgItemTextA(hwndDlg, IDC_FILE_PROXY_PASSWORD, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ return TRUE;
+ }
+ case WM_COMMAND:
+ {
+ switch (LOWORD(wParam)) {
+ case IDC_FILE_PROXY_TYPE:
+ if (HIWORD(wParam) == CBN_SELCHANGE)
+ MarkChanges(4, hwndDlg);
+ break;
+ case IDC_EDIT_LOGIN_SERVER:
+ case IDC_HOST:
+ case IDC_HOSTPORT:
+ case IDC_FILE_PROXY_HOST:
+ case IDC_FILE_PROXY_PORT:
+ case IDC_FILE_PROXY_USER:
+ case IDC_FILE_PROXY_PASSWORD:
+ if ((HWND)lParam==GetFocus() && HIWORD(wParam)==EN_CHANGE)
+ MarkChanges(4, hwndDlg);
+ break;
+ case IDC_FILE_USE_PROXY:
+ bChecked = IsDlgButtonChecked(hwndDlg, IDC_FILE_USE_PROXY);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_TYPE_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_TYPE), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_HOST_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_HOST), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_PORT_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_PORT), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_USE_AUTH), bChecked);
+ case IDC_FILE_PROXY_USE_AUTH:
+ bChecked = IsDlgButtonChecked(hwndDlg, IDC_FILE_PROXY_USE_AUTH) & IsDlgButtonChecked(hwndDlg, IDC_FILE_USE_PROXY);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_USER_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_USER), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_PASSWORD_LABEL), bChecked);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_FILE_PROXY_PASSWORD), bChecked);
+ MarkChanges(4, hwndDlg);
+ break;
+ case IDC_KEEPALIVE:
+ case IDC_VISIBILITY_SUPPORT:
+ case IDC_USE_SSL:
+ MarkChanges(4, hwndDlg);
+ break;
+ }
+ }
+ break;
+ case WM_NOTIFY:
+ {
+ switch (((LPNMHDR) lParam)->code) {
+ case PSN_APPLY:
+ {
+ WORD port;
+ BOOL useEncryption;
+ BOOL reconnectRequired = FALSE;
+ DBVARIANT dbv;
+ GetDlgItemTextA(hwndDlg, IDC_EDIT_LOGIN_SERVER, text, sizeof(text));
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv) || strcmp(text, dbv.pszVal))
+ reconnectRequired = TRUE;
+ if (dbv.pszVal != NULL) DBFreeVariant(&dbv);
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "LoginServer", strlwr(text));
+
+ GetDlgItemTextA(hwndDlg, IDC_HOST, text, sizeof(text));
+ if (DBGetContactSetting(NULL, proto->iface.m_szModuleName, "ManualHost", &dbv) || strcmp(text, dbv.pszVal))
+ reconnectRequired = TRUE;
+ if (dbv.pszVal != NULL) DBFreeVariant(&dbv);
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "ManualHost", text);
+
+ port = (WORD) GetDlgItemInt(hwndDlg, IDC_HOSTPORT, NULL, FALSE);
+ if (DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "ManualPort", TLEN_DEFAULT_PORT) != port)
+ reconnectRequired = TRUE;
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "ManualPort", port);
+
+ proto->tlenOptions.sendKeepAlive = IsDlgButtonChecked(hwndDlg, IDC_KEEPALIVE);
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "KeepAlive", (BYTE) proto->tlenOptions.sendKeepAlive);
+
+ useEncryption = IsDlgButtonChecked(hwndDlg, IDC_USE_SSL);
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "UseEncryption", TRUE) != useEncryption)
+ reconnectRequired = TRUE;
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "UseEncryption", (BYTE) useEncryption);
+
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "VisibilitySupport", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_VISIBILITY_SUPPORT));
+ // File transfer options
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "UseFileProxy", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_FILE_USE_PROXY));
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "FileProxyType", (WORD) SendDlgItemMessage(hwndDlg, IDC_FILE_PROXY_TYPE, CB_GETCURSEL, 0, 0));
+ GetDlgItemTextA(hwndDlg, IDC_FILE_PROXY_HOST, text, sizeof(text));
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "FileProxyHost", text);
+ DBWriteContactSettingWord(NULL, proto->iface.m_szModuleName, "FileProxyPort", (WORD) GetDlgItemInt(hwndDlg, IDC_FILE_PROXY_PORT, NULL, FALSE));
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "FileProxyAuth", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_FILE_PROXY_USE_AUTH));
+ GetDlgItemTextA(hwndDlg, IDC_FILE_PROXY_USER, text, sizeof(text));
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "FileProxyUsername", text);
+ GetDlgItemTextA(hwndDlg, IDC_FILE_PROXY_PASSWORD, text, sizeof(text));
+ CallService(MS_DB_CRYPT_ENCODESTRING, sizeof(text), (LPARAM) text);
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "FileProxyPassword", text);
+ if (reconnectRequired && proto->isConnected)
+ MessageBox(hwndDlg, TranslateT("These changes will take effect the next time you connect to the Tlen network."), TranslateT("Tlen Protocol Option"), MB_OK|MB_SETFOREGROUND);
+ ApplyChanges(proto, 4);
+ return TRUE;
+ }
+ }
+ }
+ break;
+ case WM_DESTROY:
+ break;
+ }
+
+ return FALSE;
+}
+
+#define POPUP_DEFAULT_COLORBKG 0xDCBDA5
+#define POPUP_DEFAULT_COLORTXT 0x000000
+
+static void MailPopupPreview(DWORD colorBack, DWORD colorText, char *title, char *emailInfo, int delay)
+{
+ POPUPDATAEX ppd;
+ char * lpzContactName;
+ char * lpzText;
+ HICON hIcon;
+ lpzContactName = title;
+ lpzText = emailInfo;
+ ZeroMemory(&ppd, sizeof(ppd));
+ ppd.lchContact = NULL;
+ hIcon = GetIcolibIcon(IDI_MAIL);
+ ppd.lchIcon = CopyIcon(hIcon);
+ ReleaseIcolibIcon(hIcon);
+ strcpy(ppd.lpzContactName, lpzContactName);
+ strcpy(ppd.lpzText, lpzText);
+ ppd.colorBack = colorBack;
+ ppd.colorText = colorText;
+ ppd.PluginWindowProc = NULL;
+ ppd.PluginData=NULL;
+ if ( ServiceExists( MS_POPUP_ADDPOPUPEX )) {
+ ppd.iSeconds = delay;
+ CallService(MS_POPUP_ADDPOPUPEX, (WPARAM)&ppd, 0);
+
+ }
+ else if ( ServiceExists( MS_POPUP_ADDPOPUP )) {
+ CallService(MS_POPUP_ADDPOPUP, (WPARAM)&ppd, 0);
+ }
+}
+
+static INT_PTR CALLBACK TlenPopupsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ TlenProtocol *proto = (TlenProtocol *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ {
+ BYTE delayMode;
+ proto = (TlenProtocol *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)proto);
+ TranslateDialogDefault(hwndDlg);
+ CheckDlgButton(hwndDlg, IDC_ENABLEPOPUP, DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "MailPopupEnabled", TRUE));
+ SendDlgItemMessage(hwndDlg, IDC_COLORBKG, CPM_SETCOLOUR, 0, DBGetContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupBack", POPUP_DEFAULT_COLORBKG));
+ SendDlgItemMessage(hwndDlg, IDC_COLORTXT, CPM_SETCOLOUR, 0, DBGetContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupText", POPUP_DEFAULT_COLORTXT));
+ SetDlgItemInt(hwndDlg, IDC_DELAY, DBGetContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupDelay", 4), FALSE);
+ delayMode = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "MailPopupDelayMode", 0);
+ if (delayMode==1) {
+ CheckDlgButton(hwndDlg, IDC_DELAY_CUSTOM, TRUE);
+ } else if (delayMode==2) {
+ CheckDlgButton(hwndDlg, IDC_DELAY_PERMANENT, TRUE);
+ } else {
+ CheckDlgButton(hwndDlg, IDC_DELAY_POPUP, TRUE);
+ }
+ return TRUE;
+ }
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_COLORTXT:
+ case IDC_COLORBKG:
+ case IDC_ENABLEPOPUP:
+ case IDC_DELAY:
+ case IDC_DELAY_POPUP:
+ case IDC_DELAY_CUSTOM:
+ case IDC_DELAY_PERMANENT:
+ MarkChanges(8, hwndDlg);
+ break;
+ case IDC_PREVIEW:
+ {
+ int delay;
+ char title[256];
+ if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_POPUP)) {
+ delay=0;
+ } else if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_PERMANENT)) {
+ delay=-1;
+ } else {
+ delay=GetDlgItemInt(hwndDlg, IDC_DELAY, NULL, FALSE);
+ }
+ _snprintf(title, sizeof(title), Translate("%s mail"), proto->iface.m_szProtoName);
+ MailPopupPreview((DWORD) SendDlgItemMessage(hwndDlg,IDC_COLORBKG,CPM_GETCOLOUR,0,0),
+ (DWORD) SendDlgItemMessage(hwndDlg,IDC_COLORTXT,CPM_GETCOLOUR,0,0),
+ title,
+ "From: test@test.test\nSubject: test",
+ delay);
+ }
+
+ }
+ break;
+
+
+ case WM_NOTIFY:
+ switch (((LPNMHDR) lParam)->code) {
+ case PSN_APPLY:
+ {
+ BYTE delayMode;
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "MailPopupEnabled", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_ENABLEPOPUP));
+ DBWriteContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupBack", (DWORD) SendDlgItemMessage(hwndDlg,IDC_COLORBKG,CPM_GETCOLOUR,0,0));
+ DBWriteContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupText", (DWORD) SendDlgItemMessage(hwndDlg,IDC_COLORTXT,CPM_GETCOLOUR,0,0));
+ DBWriteContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupDelay", (DWORD) GetDlgItemInt(hwndDlg,IDC_DELAY, NULL, FALSE));
+ delayMode=0;
+ if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_CUSTOM)) {
+ delayMode=1;
+ } else if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_PERMANENT)) {
+ delayMode=2;
+
+ }
+ DBWriteContactSettingByte(NULL, proto->iface.m_szModuleName, "MailPopupDelayMode", delayMode);
+ ApplyChanges(proto, 8);
+ return TRUE;
+ }
+ }
+ break;
+
+ }
+ return FALSE;
+}
+
diff --git a/protocols/Tlen/jabber_svc.c b/protocols/Tlen/jabber_svc.c
new file mode 100644
index 0000000000..ecc3b26bfb
--- /dev/null
+++ b/protocols/Tlen/jabber_svc.c
@@ -0,0 +1,1300 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include <io.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include "resource.h"
+#include "jabber_list.h"
+#include "jabber_iq.h"
+#include "tlen_p2p_old.h"
+#include "tlen_avatar.h"
+#include "tlen_file.h"
+
+extern int TlenOnModulesLoaded(void *ptr, WPARAM wParam, LPARAM lParam);
+extern int TlenOptionsInit(void *ptr, WPARAM wParam, LPARAM lParam);
+extern int TlenPreShutdown(void *ptr, WPARAM wParam, LPARAM lParam);
+DWORD_PTR TlenGetCaps(PROTO_INTERFACE *ptr, int type, HANDLE hContact)
+{
+ if (type == PFLAGNUM_1)
+ return PF1_IM|PF1_AUTHREQ|PF1_SERVERCLIST|PF1_MODEMSG|PF1_BASICSEARCH|PF1_SEARCHBYEMAIL|PF1_EXTSEARCH|PF1_EXTSEARCHUI|PF1_SEARCHBYNAME|PF1_FILE;//|PF1_VISLIST|PF1_INVISLIST;
+ if (type == PFLAGNUM_2)
+ return PF2_ONLINE|PF2_INVISIBLE|PF2_SHORTAWAY|PF2_LONGAWAY|PF2_HEAVYDND|PF2_FREECHAT;
+ if (type == PFLAGNUM_3)
+ return PF2_ONLINE|PF2_INVISIBLE|PF2_SHORTAWAY|PF2_LONGAWAY|PF2_HEAVYDND|PF2_FREECHAT;
+ if (type == PFLAGNUM_4)
+ return PF4_FORCEAUTH|PF4_NOCUSTOMAUTH|PF4_SUPPORTTYPING|PF4_AVATARS|PF4_IMSENDOFFLINE|PF4_OFFLINEFILES;
+ if (type == PFLAG_UNIQUEIDTEXT)
+ return (DWORD_PTR) Translate("Tlen login");
+ if (type == PFLAG_UNIQUEIDSETTING)
+ return (DWORD_PTR) "jid";
+ return 0;
+}
+
+INT_PTR TlenGetName(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ strncpy((char *) lParam, proto->iface.m_szProtoName, wParam);
+ return 0;
+}
+
+HICON TlenGetIcon(PROTO_INTERFACE *ptr, int iconIndex)
+{
+ if ((iconIndex&0xffff) == PLI_PROTOCOL) {
+ HICON hIcon = GetIcolibIcon(IDI_TLEN);
+ HICON hIconCopy = CopyIcon(hIcon);
+ ReleaseIcolibIcon(hIcon);
+ return hIconCopy;
+ }
+ return (HICON) NULL;
+}
+
+int TlenRunSearch(TlenProtocol *proto) {
+ int iqId = 0;
+ if (!proto->isOnline) return 0;
+ if (proto->searchQuery != NULL && proto->searchIndex < 10) {
+ iqId = proto->searchID;
+ JabberIqAdd(proto, iqId, IQ_PROC_GETSEARCH, JabberIqResultSearch);
+ if (proto->searchIndex == 0) {
+ JabberSend(proto, "<iq type='get' id='"JABBER_IQID"%d' to='tuba'><query xmlns='jabber:iq:search'>%s</query></iq>", iqId, proto->searchQuery);
+ } else {
+ JabberSend(proto, "<iq type='get' id='"JABBER_IQID"%d' to='tuba'><query xmlns='jabber:iq:search'>%s<f>%d</f></query></iq>", iqId, proto->searchQuery, proto->searchIndex * TLEN_MAX_SEARCH_RESULTS_PER_PAGE);
+ }
+ proto->searchIndex ++;
+ }
+ return iqId;
+}
+
+void TlenResetSearchQuery(TlenProtocol *proto) {
+ if (proto->searchQuery != NULL) {
+ mir_free(proto->searchQuery);
+ proto->searchQuery = NULL;
+ }
+ proto->searchQueryLen = 0;
+ proto->searchIndex = 0;
+ proto->searchID = JabberSerialNext(proto);
+}
+
+HANDLE TlenBasicSearch(PROTO_INTERFACE *ptr, const char *id)
+{
+ char *jid;
+ int iqId = 0;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (!proto->isOnline) return 0;
+ if (id == NULL) return 0;
+ if ((jid=JabberTextEncode(id)) != NULL) {
+ proto->searchJID = mir_strdup(id);
+ TlenResetSearchQuery(proto);
+ JabberStringAppend(&proto->searchQuery, &proto->searchQueryLen, "<i>%s</i>", jid);
+ iqId = TlenRunSearch(proto);
+ mir_free(jid);
+ }
+ return (HANDLE)iqId;
+}
+
+HANDLE TlenSearchByEmail(PROTO_INTERFACE *ptr, const char* email)
+{
+ char *emailEnc;
+ int iqId = 0;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline) return 0;
+ if (email == NULL) return 0;
+
+ if ((emailEnc=JabberTextEncode(email)) != NULL) {
+ TlenResetSearchQuery(proto);
+ JabberStringAppend(&proto->searchQuery, &proto->searchQueryLen, "<email>%s</email>", emailEnc);
+ iqId = TlenRunSearch(proto);
+ mir_free(emailEnc);
+ }
+ return (HANDLE)iqId;
+}
+
+HANDLE TlenSearchByName(PROTO_INTERFACE *ptr, const char* nick, const char* firstName, const char* lastName)
+{
+ char *p;
+ int iqId = 0;
+
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (!proto->isOnline) return 0;
+
+ TlenResetSearchQuery(proto);
+
+ if (nick != NULL && nick[0] != '\0') {
+ if ((p=JabberTextEncode(nick)) != NULL) {
+ JabberStringAppend(&proto->searchQuery, &proto->searchQueryLen, "<nick>%s</nick>", p);
+ mir_free(p);
+ }
+ }
+ if (firstName != NULL && firstName[0] != '\0') {
+ if ((p=JabberTextEncode(firstName)) != NULL) {
+ JabberStringAppend(&proto->searchQuery, &proto->searchQueryLen, "<first>%s</first>", p);
+ mir_free(p);
+ }
+ }
+ if (lastName != NULL && lastName[0] != '\0') {
+ if ((p=JabberTextEncode(lastName)) != NULL) {
+ JabberStringAppend(&proto->searchQuery, &proto->searchQueryLen, "<last>%s</last>", p);
+ mir_free(p);
+ }
+ }
+
+ iqId = TlenRunSearch(proto);
+ return (HANDLE)iqId;
+}
+
+HWND TlenCreateAdvSearchUI(PROTO_INTERFACE *ptr, HWND owner)
+{
+ return (HWND) CreateDialog(hInst, MAKEINTRESOURCE(IDD_ADVSEARCH), owner, TlenAdvSearchDlgProc);
+}
+
+HWND TlenSearchAdvanced(PROTO_INTERFACE *ptr, HWND owner)
+{
+ int iqId;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (!proto->isOnline) return 0;
+
+ TlenResetSearchQuery(proto);
+ iqId = JabberSerialNext(proto);
+ if ((proto->searchQuery = TlenAdvSearchCreateQuery(owner, iqId)) != NULL) {
+ iqId = TlenRunSearch(proto);
+ }
+ return (HWND)iqId;
+}
+
+static HANDLE AddToListByJID(TlenProtocol *proto, const char *newJid, DWORD flags)
+{
+ HANDLE hContact;
+ char *jid, *nick;
+
+ if ((hContact=JabberHContactFromJID(proto, newJid)) == NULL) {
+ // not already there: add
+ jid = mir_strdup(newJid); _strlwr(jid);
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_ADD, 0, 0);
+ CallService(MS_PROTO_ADDTOCONTACT, (WPARAM) hContact, (LPARAM) proto->iface.m_szModuleName);
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "jid", jid);
+ if ((nick=JabberNickFromJID(newJid)) == NULL)
+ nick = mir_strdup(newJid);
+ DBWriteContactSettingString(hContact, "CList", "MyHandle", nick);
+ mir_free(nick);
+ mir_free(jid);
+
+ // Note that by removing or disable the "NotOnList" will trigger
+ // the plugin to add a particular contact to the roster list.
+ // See DBSettingChanged hook at the bottom part of this source file.
+ // But the add module will delete "NotOnList". So we will not do it here.
+ // Also because we need "MyHandle" and "Group" info, which are set after
+ // PS_ADDTOLIST is called but before the add dialog issue deletion of
+ // "NotOnList".
+ // If temporary add, "NotOnList" won't be deleted, and that's expected.
+ DBWriteContactSettingByte(hContact, "CList", "NotOnList", 1);
+ if (flags & PALF_TEMPORARY)
+ DBWriteContactSettingByte(hContact, "CList", "Hidden", 1);
+ }
+ else {
+ // already exist
+ // Set up a dummy "NotOnList" when adding permanently only
+ if (!(flags&PALF_TEMPORARY))
+ DBWriteContactSettingByte(hContact, "CList", "NotOnList", 1);
+ }
+
+ return hContact;
+}
+
+HANDLE TlenAddToList(PROTO_INTERFACE *ptr, int flags, PROTOSEARCHRESULT *psr)
+{
+ HANDLE hContact;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ JABBER_SEARCH_RESULT *jsr = (JABBER_SEARCH_RESULT*)psr;
+ if (jsr->hdr.cbSize != sizeof(JABBER_SEARCH_RESULT))
+ return (int) NULL;
+ hContact = AddToListByJID(proto, jsr->jid, flags); // wParam is flag e.g. PALF_TEMPORARY
+ return hContact;
+}
+
+HANDLE TlenAddToListByEvent(PROTO_INTERFACE *ptr, int flags, int iContact, HANDLE hDbEvent)
+{
+ DBEVENTINFO dbei;
+ HANDLE hContact;
+ char *nick, *firstName, *lastName, *jid;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ ZeroMemory(&dbei, sizeof(dbei));
+ dbei.cbSize = sizeof(dbei);
+ if ((dbei.cbBlob=CallService(MS_DB_EVENT_GETBLOBSIZE, (WPARAM)hDbEvent, 0)) == (DWORD)(-1))
+ return (int)(HANDLE) NULL;
+ if ((dbei.pBlob=(PBYTE) mir_alloc(dbei.cbBlob)) == NULL)
+ return (int)(HANDLE) NULL;
+ if (CallService(MS_DB_EVENT_GET, (WPARAM)hDbEvent, (LPARAM) &dbei)) {
+ mir_free(dbei.pBlob);
+ return (int)(HANDLE) NULL;
+ }
+ if (strcmp(dbei.szModule, proto->iface.m_szModuleName)) {
+ mir_free(dbei.pBlob);
+ return (int)(HANDLE) NULL;
+ }
+
+/*
+ // EVENTTYPE_CONTACTS is when adding from when we receive contact list (not used in Jabber)
+ // EVENTTYPE_ADDED is when adding from when we receive "You are added" (also not used in Jabber)
+ // Jabber will only handle the case of EVENTTYPE_AUTHREQUEST
+ // EVENTTYPE_AUTHREQUEST is when adding from the authorization request dialog
+*/
+
+ if (dbei.eventType != EVENTTYPE_AUTHREQUEST) {
+ mir_free(dbei.pBlob);
+ return (int)(HANDLE) NULL;
+ }
+
+ nick = (char *) (dbei.pBlob + sizeof(DWORD) + sizeof(HANDLE));
+ firstName = nick + strlen(nick) + 1;
+ lastName = firstName + strlen(firstName) + 1;
+ jid = lastName + strlen(lastName) + 1;
+
+ hContact = (HANDLE) AddToListByJID(proto, jid, flags);
+ mir_free(dbei.pBlob);
+
+ return hContact;
+}
+
+int TlenAuthAllow(PROTO_INTERFACE *ptr, HANDLE hContact)
+{
+ DBEVENTINFO dbei;
+ char *nick, *firstName, *lastName, *jid;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline)
+ return 1;
+
+ memset(&dbei, sizeof(dbei), 0);
+ dbei.cbSize = sizeof(dbei);
+ if ((dbei.cbBlob=CallService(MS_DB_EVENT_GETBLOBSIZE, (WPARAM)hContact, 0)) == (DWORD)(-1))
+ return 1;
+ if ((dbei.pBlob=(PBYTE) mir_alloc(dbei.cbBlob)) == NULL)
+ return 1;
+ if (CallService(MS_DB_EVENT_GET, (WPARAM)hContact, (LPARAM) &dbei)) {
+ mir_free(dbei.pBlob);
+ return 1;
+ }
+ if (dbei.eventType != EVENTTYPE_AUTHREQUEST) {
+ mir_free(dbei.pBlob);
+ return 1;
+ }
+ if (strcmp(dbei.szModule, proto->iface.m_szModuleName)) {
+ mir_free(dbei.pBlob);
+ return 1;
+ }
+
+ nick = (char *) (dbei.pBlob + sizeof(DWORD) + sizeof(HANDLE));
+ firstName = nick + strlen(nick) + 1;
+ lastName = firstName + strlen(firstName) + 1;
+ jid = lastName + strlen(lastName) + 1;
+
+ JabberSend(proto, "<presence to='%s' type='subscribed'/>", jid);
+
+ // Automatically add this user to my roster if option is enabled
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "AutoAdd", TRUE) == TRUE) {
+ HANDLE hContact;
+ JABBER_LIST_ITEM *item;
+
+ if ((item=JabberListGetItemPtr(proto, LIST_ROSTER, jid))==NULL || (item->subscription!=SUB_BOTH && item->subscription!=SUB_TO)) {
+ JabberLog(proto, "Try adding contact automatically jid=%s", jid);
+ if ((hContact=AddToListByJID(proto, jid, 0)) != NULL) {
+ // Trigger actual add by removing the "NotOnList" added by AddToListByJID()
+ // See AddToListByJID() and JabberDbSettingChanged().
+ DBDeleteContactSetting(hContact, "CList", "NotOnList");
+ }
+ }
+ }
+
+ mir_free(dbei.pBlob);
+ return 0;
+}
+
+int TlenAuthDeny(PROTO_INTERFACE *ptr, HANDLE hContact, const TCHAR* szReason)
+{
+ DBEVENTINFO dbei;
+ char *nick, *firstName, *lastName, *jid;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline)
+ return 1;
+
+ memset(&dbei, sizeof(dbei), 0);
+ dbei.cbSize = sizeof(dbei);
+ if ((dbei.cbBlob=CallService(MS_DB_EVENT_GETBLOBSIZE, (WPARAM)hContact, 0)) == (DWORD)(-1))
+ return 1;
+ if ((dbei.pBlob=(PBYTE) mir_alloc(dbei.cbBlob)) == NULL)
+ return 1;
+ if (CallService(MS_DB_EVENT_GET, (WPARAM)hContact, (LPARAM) &dbei)) {
+ mir_free(dbei.pBlob);
+ return 1;
+ }
+ if (dbei.eventType != EVENTTYPE_AUTHREQUEST) {
+ mir_free(dbei.pBlob);
+ return 1;
+ }
+ if (strcmp(dbei.szModule, proto->iface.m_szModuleName)) {
+ mir_free(dbei.pBlob);
+ return 1;
+ }
+
+ nick = (char *) (dbei.pBlob + sizeof(DWORD) + sizeof(HANDLE));
+ firstName = nick + strlen(nick) + 1;
+ lastName = firstName + strlen(firstName) + 1;
+ jid = lastName + strlen(lastName) + 1;
+
+ JabberSend(proto, "<presence to='%s' type='unsubscribed'/>", jid);
+ JabberSend(proto, "<iq type='set'><query xmlns='jabber:iq:roster'><item jid='%s' subscription='remove'/></query></iq>", jid);
+ mir_free(dbei.pBlob);
+ return 0;
+}
+
+static void TlenConnect(TlenProtocol *proto, int initialStatus)
+{
+ if (!proto->isConnected) {
+ ThreadData *thread;
+ int oldStatus;
+
+ thread = (ThreadData *) mir_alloc(sizeof(ThreadData));
+ memset(thread, 0, sizeof(ThreadData));
+ thread->proto = proto;
+ proto->iface.m_iDesiredStatus = initialStatus;
+
+ oldStatus = proto->iface.m_iStatus;
+ proto->iface.m_iStatus = ID_STATUS_CONNECTING;
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, proto->iface.m_iStatus);
+ thread->hThread = (HANDLE) JabberForkThread((void (__cdecl *)(void*))JabberServerThread, 0, thread);
+ }
+}
+
+int TlenSetStatus(PROTO_INTERFACE *ptr, int iNewStatus)
+{
+ int oldStatus;
+ HANDLE s;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ proto->iface.m_iDesiredStatus = iNewStatus;
+
+ if (iNewStatus == ID_STATUS_OFFLINE) {
+ if (proto->threadData) {
+ if (proto->isConnected) {
+ JabberSendPresence(proto, ID_STATUS_OFFLINE);
+ }
+ s = proto;
+ proto->threadData = NULL;
+ if (proto->isConnected) {
+ Sleep(200);
+// JabberSend(s, "</s>");
+ // Force closing connection
+ proto->isConnected = FALSE;
+ proto->isOnline = FALSE;
+ Netlib_CloseHandle(s);
+ }
+ }
+ else {
+ if (proto->iface.m_iStatus != ID_STATUS_OFFLINE) {
+ oldStatus = proto->iface.m_iStatus;
+ proto->iface.m_iStatus = ID_STATUS_OFFLINE;
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, proto->iface.m_iStatus);
+ }
+ }
+ }
+ else if (iNewStatus != proto->iface.m_iStatus) {
+ if (!proto->isConnected)
+ TlenConnect(proto, iNewStatus);
+ else {
+ // change status
+ oldStatus = proto->iface.m_iStatus;
+ // send presence update
+ JabberSendPresence(proto, iNewStatus);
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, proto->iface.m_iStatus);
+ }
+ }
+ return 0;
+}
+
+INT_PTR TlenGetStatus(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ return proto->iface.m_iStatus;
+}
+
+
+int TlenSetAwayMsg(PROTO_INTERFACE *ptr, int iStatus, const char* msg )
+{
+ char **szMsg;
+ char *newModeMsg;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ JabberLog(proto, "SetAwayMsg called, wParam=%d lParam=%s", iStatus, msg);
+
+ newModeMsg = JabberTextEncode(msg);
+
+ EnterCriticalSection(&proto->modeMsgMutex);
+
+ switch (iStatus) {
+ case ID_STATUS_ONLINE:
+ szMsg = &proto->modeMsgs.szOnline;
+ break;
+ case ID_STATUS_AWAY:
+ case ID_STATUS_ONTHEPHONE:
+ case ID_STATUS_OUTTOLUNCH:
+ szMsg = &proto->modeMsgs.szAway;
+ break;
+ case ID_STATUS_NA:
+ szMsg = &proto->modeMsgs.szNa;
+ break;
+ case ID_STATUS_DND:
+ case ID_STATUS_OCCUPIED:
+ szMsg = &proto->modeMsgs.szDnd;
+ break;
+ case ID_STATUS_FREECHAT:
+ szMsg = &proto->modeMsgs.szFreechat;
+ break;
+ case ID_STATUS_INVISIBLE:
+ szMsg = &proto->modeMsgs.szInvisible;
+ break;
+ default:
+ LeaveCriticalSection(&proto->modeMsgMutex);
+ return 1;
+ }
+
+ if ((*szMsg==NULL && newModeMsg==NULL) ||
+ (*szMsg!=NULL && newModeMsg!=NULL && !strcmp(*szMsg, newModeMsg))) {
+ // Message is the same, no update needed
+ if (newModeMsg != NULL) mir_free(newModeMsg);
+ }
+ else {
+ // Update with the new mode message
+ if (*szMsg != NULL) mir_free(*szMsg);
+ *szMsg = newModeMsg;
+ // Send a presence update if needed
+ if (iStatus == proto->iface.m_iStatus) {
+ JabberSendPresence(proto, proto->iface.m_iStatus);
+ }
+ }
+
+ LeaveCriticalSection(&proto->modeMsgMutex);
+ return 0;
+}
+
+int JabberGetInfo(PROTO_INTERFACE *ptr, HANDLE hContact, int infoType)
+{
+ DBVARIANT dbv;
+ int iqId;
+ char *nick, *pNick;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline) return 1;
+ if (hContact==NULL) {
+ iqId = JabberSerialNext(proto);
+ JabberIqAdd(proto, iqId, IQ_PROC_NONE, TlenIqResultVcard);
+ JabberSend(proto, "<iq type='get' id='"JABBER_IQID"%d' to='tuba'><query xmlns='jabber:iq:register'></query></iq>", iqId);
+ } else {
+ if (DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) return 1;
+ if ((nick=JabberNickFromJID(dbv.pszVal)) != NULL) {
+ if ((pNick=JabberTextEncode(nick)) != NULL) {
+ iqId = JabberSerialNext(proto);
+ JabberIqAdd(proto, iqId, IQ_PROC_NONE, TlenIqResultVcard);
+ JabberSend(proto, "<iq type='get' id='"JABBER_IQID"%d' to='tuba'><query xmlns='jabber:iq:search'><i>%s</i></query></iq>", iqId, pNick);
+ mir_free(pNick);
+ }
+ mir_free(nick);
+ }
+ DBFreeVariant(&dbv);
+ }
+ return 0;
+}
+
+int TlenSetApparentMode(PROTO_INTERFACE *ptr, HANDLE hContact, int mode)
+{
+ DBVARIANT dbv;
+ int oldMode;
+ char *jid;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline) return 0;
+ if (!DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "VisibilitySupport", FALSE)) return 0;
+ if (mode!=0 && mode!=ID_STATUS_ONLINE && mode!=ID_STATUS_OFFLINE) return 1;
+ oldMode = DBGetContactSettingWord(hContact, proto->iface.m_szModuleName, "ApparentMode", 0);
+ if ((int) mode == oldMode) return 1;
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "ApparentMode", (WORD) mode);
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ jid = dbv.pszVal;
+ switch (mode) {
+ case ID_STATUS_ONLINE:
+ if (proto->iface.m_iStatus==ID_STATUS_INVISIBLE || oldMode==ID_STATUS_OFFLINE)
+ JabberSend(proto, "<presence to='%s'><show>available</show></presence>", jid);
+ break;
+ case ID_STATUS_OFFLINE:
+ if (proto->iface.m_iStatus!=ID_STATUS_INVISIBLE || oldMode==ID_STATUS_ONLINE)
+ JabberSend(proto, "<presence to='%s' type='invisible'/>", jid);
+ break;
+ case 0:
+ if (oldMode==ID_STATUS_ONLINE && proto->iface.m_iStatus==ID_STATUS_INVISIBLE)
+ JabberSend(proto, "<presence to='%s' type='invisible'/>", jid);
+ else if (oldMode==ID_STATUS_OFFLINE && proto->iface.m_iStatus!=ID_STATUS_INVISIBLE)
+ JabberSend(proto, "<presence to='%s'><show>available</show></presence>", jid);
+ break;
+ }
+ DBFreeVariant(&dbv);
+ }
+ return 0;
+}
+
+typedef struct{
+ TlenProtocol *proto;
+ HANDLE hContact;
+} SENDACKTHREADDATA;
+
+static void __cdecl JabberSendMessageAckThread(void *ptr)
+{
+ SENDACKTHREADDATA *data = (SENDACKTHREADDATA *)ptr;
+ SleepEx(10, TRUE);
+ ProtoBroadcastAck(data->proto->iface.m_szModuleName, data->hContact, ACKTYPE_MESSAGE, ACKRESULT_SUCCESS, (HANDLE) 1, 0);
+ mir_free(data);
+}
+
+static void __cdecl TlenSendMessageFailedThread(void *ptr)
+{
+ SENDACKTHREADDATA *data = (SENDACKTHREADDATA *)ptr;
+ SleepEx(10, TRUE);
+ ProtoBroadcastAck(data->proto->iface.m_szModuleName, data->hContact, ACKTYPE_MESSAGE, ACKRESULT_FAILED, (HANDLE) 2, 0);
+ mir_free(data);
+}
+
+static void __cdecl TlenGetAwayMsgThread(void *ptr)
+{
+ DBVARIANT dbv;
+ JABBER_LIST_ITEM *item;
+ SENDACKTHREADDATA *data = (SENDACKTHREADDATA *)ptr;
+ if (!DBGetContactSetting(data->hContact, data->proto->iface.m_szModuleName, "jid", &dbv)) {
+ if ((item=JabberListGetItemPtr(data->proto, LIST_ROSTER, dbv.pszVal)) != NULL) {
+ DBFreeVariant(&dbv);
+ if (item->statusMessage != NULL) {
+ ProtoBroadcastAck(data->proto->iface.m_szModuleName, data->hContact, ACKTYPE_AWAYMSG, ACKRESULT_SUCCESS, (HANDLE) 1, (LPARAM) item->statusMessage);
+ return;
+ }
+ }
+ else {
+ DBFreeVariant(&dbv);
+ }
+ }
+ ProtoBroadcastAck(data->proto->iface.m_szModuleName, data->hContact, ACKTYPE_AWAYMSG, ACKRESULT_SUCCESS, (HANDLE) 1, (LPARAM) "");
+ mir_free(data);
+}
+
+INT_PTR TlenSendAlert(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact = ( HANDLE )wParam;
+ DBVARIANT dbv;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (proto->isOnline && !DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ JabberSend(proto, "<m tp='a' to='%s'/>", dbv.pszVal);
+
+ DBFreeVariant(&dbv);
+ }
+ return 0;
+}
+
+
+int TlenSendMessage(PROTO_INTERFACE *ptr, HANDLE hContact, int flags, const char* msg)
+{
+ DBVARIANT dbv;
+ char *msgEnc;
+ JABBER_LIST_ITEM *item;
+ int id;
+ char msgType[16];
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline || DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ SENDACKTHREADDATA *tdata = (SENDACKTHREADDATA*) mir_alloc(sizeof(SENDACKTHREADDATA));
+ tdata->proto = proto;
+ tdata->hContact = hContact;
+ JabberForkThread(TlenSendMessageFailedThread, 0, (void *) tdata);
+ return 2;
+ }
+ if (!strcmp(msg, "<alert>")) {
+ SENDACKTHREADDATA *tdata = (SENDACKTHREADDATA*) mir_alloc(sizeof(SENDACKTHREADDATA));
+ tdata->proto = proto;
+ tdata->hContact = hContact;
+ JabberSend(proto, "<m tp='a' to='%s'/>", dbv.pszVal);
+ JabberForkThread(JabberSendMessageAckThread, 0, (void *) tdata);
+ } else if (!strcmp(msg, "<image>")) {
+ SENDACKTHREADDATA *tdata = (SENDACKTHREADDATA*) mir_alloc(sizeof(SENDACKTHREADDATA));
+ tdata->proto = proto;
+ tdata->hContact = hContact;
+ id = JabberSerialNext(proto);
+ JabberSend(proto, "<message to='%s' type='%s' crc='%x' idt='%d'/>", dbv.pszVal, "pic", 0x757f044, id);
+ JabberForkThread(JabberSendMessageAckThread, 0, (void *) tdata);
+ } else {
+ if ((msgEnc=JabberTextEncode(msg)) != NULL) {
+ if (JabberListExist(proto, LIST_CHATROOM, dbv.pszVal) && strchr(dbv.pszVal, '/')==NULL) {
+ strcpy(msgType, "groupchat");
+ } else if (DBGetContactSettingByte(hContact, proto->iface.m_szModuleName, "bChat", FALSE)) {
+ strcpy(msgType, "privchat");
+ } else {
+ strcpy(msgType, "chat");
+ }
+ if (!strcmp(msgType, "groupchat") || DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "MsgAck", FALSE) == FALSE) {
+ SENDACKTHREADDATA *tdata = (SENDACKTHREADDATA*) mir_alloc(sizeof(SENDACKTHREADDATA));
+ tdata->proto = proto;
+ tdata->hContact = hContact;
+ if (!strcmp(msgType, "groupchat")) {
+ JabberSend(proto, "<message to='%s' type='%s'><body>%s</body></message>", dbv.pszVal, msgType, msgEnc);
+ } else if (!strcmp(msgType, "privchat")) {
+ JabberSend(proto, "<m to='%s'><b n='6' s='10' f='0' c='000000'>%s</b></m>", dbv.pszVal, msgEnc);
+ } else {
+ id = JabberSerialNext(proto);
+ JabberSend(proto, "<message to='%s' type='%s' id='"JABBER_IQID"%d'><body>%s</body><x xmlns='jabber:x:event'><composing/></x></message>", dbv.pszVal, msgType, id, msgEnc);
+ }
+ JabberForkThread(JabberSendMessageAckThread, 0, (void *) tdata);
+ }
+ else {
+ id = JabberSerialNext(proto);
+ if ((item=JabberListGetItemPtr(proto, LIST_ROSTER, dbv.pszVal)) != NULL)
+ item->idMsgAckPending = id;
+ JabberSend(proto, "<message to='%s' type='%s' id='"JABBER_IQID"%d'><body>%s</body><x xmlns='jabber:x:event'><offline/><delivered/><composing/></x></message>", dbv.pszVal, msgType, id, msgEnc);
+ }
+ }
+ mir_free(msgEnc);
+ }
+ DBFreeVariant(&dbv);
+ return 1;
+}
+
+/////////////////////////////////////////////////////////////////////////////////////////
+// JabberGetAvatarInfo - retrieves the avatar info
+
+static INT_PTR TlenGetAvatarInfo(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ BOOL downloadingAvatar = FALSE;
+ char *avatarHash = NULL;
+ JABBER_LIST_ITEM *item = NULL;
+ DBVARIANT dbv;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ PROTO_AVATAR_INFORMATION* AI = ( PROTO_AVATAR_INFORMATION* )lParam;
+ if (!proto->tlenOptions.enableAvatars) return GAIR_NOAVATAR;
+
+ if (AI->hContact != NULL) {
+ if (!DBGetContactSetting(AI->hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ item = JabberListGetItemPtr(proto, LIST_ROSTER, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ if (item != NULL) {
+ downloadingAvatar = item->newAvatarDownloading;
+ avatarHash = item->avatarHash;
+ }
+ }
+ } else {
+ if (proto->threadData != NULL) {
+ avatarHash = proto->threadData->avatarHash;
+ }
+ }
+ if ((avatarHash == NULL || avatarHash[0] == '\0') && !downloadingAvatar) {
+ return GAIR_NOAVATAR;
+ }
+ if (avatarHash != NULL && !downloadingAvatar) {
+ TlenGetAvatarFileName(proto, item, AI->filename, sizeof(AI->filename));
+ AI->format = ( AI->hContact == NULL ) ? proto->threadData->avatarFormat : item->avatarFormat;
+ return GAIR_SUCCESS;
+ }
+ if (( wParam & GAIF_FORCE ) != 0 && AI->hContact != NULL && proto->isOnline) {
+ /* get avatar */
+ return GAIR_WAITFOR;
+ }
+ return GAIR_NOAVATAR;
+}
+
+HANDLE TlenGetAwayMsg(PROTO_INTERFACE *ptr, HANDLE hContact)
+{
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ SENDACKTHREADDATA *tdata = (SENDACKTHREADDATA*) mir_alloc(sizeof(SENDACKTHREADDATA));
+ tdata->proto = proto;
+ tdata->hContact = hContact;
+ JabberForkThread((void (__cdecl *)(void*))TlenGetAwayMsgThread, 0, (void *) tdata);
+ return (HANDLE)1;
+}
+
+HANDLE TlenFileAllow(PROTO_INTERFACE *ptr, HANDLE hContact, HANDLE hTransfer, const char* szPath)
+{
+ TLEN_FILE_TRANSFER *ft;
+ JABBER_LIST_ITEM *item;
+ char *nick;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline) return 0;
+
+ ft = (TLEN_FILE_TRANSFER *) hTransfer;
+ ft->szSavePath = mir_strdup(szPath);
+ if ((item=JabberListAdd(proto, LIST_FILE, ft->iqId)) != NULL) {
+ item->ft = ft;
+ }
+ nick = JabberNickFromJID(ft->jid);
+ if (ft->newP2P) {
+ JabberSend(proto, "<iq to='%s'><query xmlns='p2p'><fs t='%s' e='5' i='%s' v='1'/></query></iq>", ft->jid, ft->jid, ft->iqId);
+ } else {
+ JabberSend(proto, "<f t='%s' i='%s' e='5' v='1'/>", nick, ft->iqId);
+ }
+ mir_free(nick);
+ return (HANDLE)hTransfer;
+}
+
+int TlenFileDeny(PROTO_INTERFACE *ptr, HANDLE hContact, HANDLE hTransfer, const char* szReason)
+{
+ TLEN_FILE_TRANSFER *ft;
+ char *nick;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline) return 1;
+
+ ft = (TLEN_FILE_TRANSFER *) hTransfer;
+ nick = JabberNickFromJID(ft->jid);
+ if (ft->newP2P) {
+ JabberSend(proto, "<f i='%s' e='4' t='%s'/>", ft->iqId, nick);\
+ } else {
+ JabberSend(proto, "<f i='%s' e='4' t='%s'/>", ft->iqId, nick);\
+ }
+ mir_free(nick);
+ TlenP2PFreeFileTransfer(ft);
+ return 0;
+}
+
+int TlenFileCancel(PROTO_INTERFACE *ptr, HANDLE hContact, HANDLE hTransfer)
+{
+ TLEN_FILE_TRANSFER *ft = (TLEN_FILE_TRANSFER *) hTransfer;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ JabberLog(proto, "Invoking FileCancel()");
+ if (ft->s != NULL) {
+ ft->state = FT_ERROR;
+ Netlib_CloseHandle(ft->s);
+ ft->s = NULL;
+ if (ft->hFileEvent != NULL) {
+ HANDLE hEvent = ft->hFileEvent;
+ ft->hFileEvent = NULL;
+ SetEvent(hEvent);
+ }
+ } else {
+ TlenP2PFreeFileTransfer(ft);
+ }
+ return 0;
+}
+
+HANDLE TlenSendFile(PROTO_INTERFACE *ptr, HANDLE hContact, const char* szDescription, char** ppszFiles)
+{
+ TLEN_FILE_TRANSFER *ft;
+ int i, j;
+ struct _stat statbuf;
+ DBVARIANT dbv;
+ char *nick, *p, idStr[10];
+ JABBER_LIST_ITEM *item;
+ int id;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline) return 0;
+// if (DBGetContactSettingWord(ccs->hContact, iface.m_szModuleName, "Status", ID_STATUS_OFFLINE) == ID_STATUS_OFFLINE) return 0;
+ if (DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) return 0;
+ ft = TlenFileCreateFT(proto, dbv.pszVal);
+ for(ft->fileCount=0; ppszFiles[ft->fileCount]; ft->fileCount++);
+ ft->files = (char **) mir_alloc(sizeof(char *) * ft->fileCount);
+ ft->filesSize = (long *) mir_alloc(sizeof(long) * ft->fileCount);
+ ft->allFileTotalSize = 0;
+ for(i=j=0; i<ft->fileCount; i++) {
+ if (_stat(ppszFiles[i], &statbuf))
+ JabberLog(proto, "'%s' is an invalid filename", ppszFiles[i]);
+ else {
+ ft->filesSize[j] = statbuf.st_size;
+ ft->files[j++] = mir_strdup(ppszFiles[i]);
+ ft->allFileTotalSize += statbuf.st_size;
+ }
+ }
+ ft->fileCount = j;
+ ft->szDescription = mir_strdup(szDescription);
+ ft->hContact = hContact;
+ ft->currentFile = 0;
+ DBFreeVariant(&dbv);
+
+ id = JabberSerialNext(proto);
+ _snprintf(idStr, sizeof(idStr), "%d", id);
+ if ((item=JabberListAdd(proto, LIST_FILE, idStr)) != NULL) {
+ ft->iqId = mir_strdup(idStr);
+ nick = JabberNickFromJID(ft->jid);
+ item->ft = ft;
+ if (proto->tlenOptions.useNewP2P) {
+ JabberSend(proto, "<iq to='%s'><query xmlns='p2p'><fs t='%s' e='1' i='%s' c='%d' s='%d' v='%d'/></query></iq>",
+ ft->jid, ft->jid, idStr, ft->fileCount, ft->allFileTotalSize, ft->fileCount);
+
+ ft->newP2P = TRUE;
+ } else {
+ if (ft->fileCount == 1) {
+ if ((p=strrchr(ppszFiles[0], '\\')) != NULL)
+ p++;
+ else
+ p = ppszFiles[0];
+ p = JabberTextEncode(p);
+ JabberSend(proto, "<f t='%s' n='%s' e='1' i='%s' c='1' s='%d' v='1'/>", nick, p, idStr, ft->allFileTotalSize);
+ mir_free(p);
+ }
+ else
+ JabberSend(proto, "<f t='%s' e='1' i='%s' c='%d' s='%d' v='1'/>", nick, idStr, ft->fileCount, ft->allFileTotalSize);
+ }
+ mir_free(nick);
+ }
+
+ return (HANDLE) ft;
+}
+
+int TlenRecvMessage(PROTO_INTERFACE *ptr, HANDLE hContact, PROTORECVEVENT* evt)
+{
+ CCSDATA ccs = { hContact, PSR_MESSAGE, 0, ( LPARAM )evt };
+ return CallService( MS_PROTO_RECVMSG, 0, ( LPARAM )&ccs );
+}
+
+int TlenRecvFile(PROTO_INTERFACE *ptr, HANDLE hContact, PROTORECVFILE* evt)
+{
+ CCSDATA ccs = { hContact, PSR_FILE, 0, ( LPARAM )evt };
+ return CallService( MS_PROTO_RECVFILE, 0, ( LPARAM )&ccs );
+}
+
+
+static char* settingToChar( DBCONTACTWRITESETTING* cws )
+{
+ switch( cws->value.type ) {
+ case DBVT_ASCIIZ:
+ return mir_strdup( cws->value.pszVal );
+ case DBVT_UTF8:
+ return mir_utf8decode(mir_strdup(cws->value.pszVal), NULL);
+ }
+ return NULL;
+}
+
+int JabberDbSettingChanged(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ DBCONTACTWRITESETTING *cws = (DBCONTACTWRITESETTING *) lParam;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ // no action for hContact == NULL or when offline
+ if ((HANDLE) wParam == NULL) return 0;
+ if (!proto->isConnected) return 0;
+
+ if (!strcmp(cws->szModule, "CList")) {
+ HANDLE hContact;
+ DBVARIANT dbv;
+ JABBER_LIST_ITEM *item;
+ char *szProto, *nick, *jid, *group;
+
+ hContact = (HANDLE) wParam;
+ szProto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if (szProto==NULL || strcmp(szProto, proto->iface.m_szModuleName)) return 0;
+// if (DBGetContactSettingByte(hContact, iface.m_szModuleName, "ChatRoom", 0) != 0) return 0;
+ // A contact's group is changed
+ if (!strcmp(cws->szSetting, "Group")) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ if ((item=JabberListGetItemPtr(proto, LIST_ROSTER, dbv.pszVal)) != NULL) {
+ DBFreeVariant(&dbv);
+ if (!DBGetContactSetting(hContact, "CList", "MyHandle", &dbv)) {
+ nick = JabberTextEncode(dbv.pszVal);
+ DBFreeVariant(&dbv);
+ } else if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "Nick", &dbv)) {
+ nick = JabberTextEncode(dbv.pszVal);
+ DBFreeVariant(&dbv);
+ } else {
+ nick = JabberNickFromJID(item->jid);
+ }
+ if (nick != NULL) {
+ // Note: we need to compare with item->group to prevent infinite loop
+ if (cws->value.type==DBVT_DELETED && item->group!=NULL) {
+ JabberLog(proto, "Group set to nothing");
+ JabberSend(proto, "<iq type='set'><query xmlns='jabber:iq:roster'><item name='%s' jid='%s'></item></query></iq>", nick, item->jid);
+ } else if (cws->value.pszVal != NULL) {
+ char *newGroup = settingToChar(cws);
+ if (item->group==NULL || strcmp(newGroup, item->group)) {
+ JabberLog(proto, "Group set to %s", newGroup);
+ if ((group=TlenGroupEncode(newGroup)) != NULL) {
+ JabberSend(proto, "<iq type='set'><query xmlns='jabber:iq:roster'><item name='%s' jid='%s'><group>%s</group></item></query></iq>", nick, item->jid, group);
+ mir_free(group);
+ }
+ }
+ mir_free(newGroup);
+ }
+ mir_free(nick);
+ }
+ }
+ else {
+ DBFreeVariant(&dbv);
+ }
+ }
+ }
+ // A contact is renamed
+ else if (!strcmp(cws->szSetting, "MyHandle")) {
+ char *newNick;
+
+// hContact = (HANDLE) wParam;
+// szProto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+// if (szProto==NULL || strcmp(szProto, iface.m_szModuleName)) return 0;
+
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ jid = dbv.pszVal;
+ if ((item=JabberListGetItemPtr(proto, LIST_ROSTER, dbv.pszVal)) != NULL) {
+ if (cws->value.type == DBVT_DELETED) {
+ newNick = mir_strdup((char *) CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM) hContact, GCDNF_NOMYHANDLE));
+ } else if (cws->value.pszVal!=NULL) {
+ newNick = settingToChar(cws);
+ } else {
+ newNick = NULL;
+ }
+ // Note: we need to compare with item->nick to prevent infinite loop
+ if (newNick!=NULL && (item->nick==NULL || (item->nick!=NULL && strcmp(item->nick, newNick)))) {
+ if ((nick=JabberTextEncode(newNick)) != NULL) {
+ JabberLog(proto, "Nick set to %s", newNick);
+ if (item->group!=NULL && (group=TlenGroupEncode(item->group))!=NULL) {
+ JabberSend(proto, "<iq type='set'><query xmlns='jabber:iq:roster'><item name='%s' jid='%s'><group>%s</group></item></query></iq>", nick, jid, group);
+ mir_free(group);
+ } else {
+ JabberSend(proto, "<iq type='set'><query xmlns='jabber:iq:roster'><item name='%s' jid='%s'></item></query></iq>", nick, jid);
+ }
+ mir_free(nick);
+ }
+ }
+ if (newNick != NULL) mir_free(newNick);
+ }
+ DBFreeVariant(&dbv);
+ }
+ }
+ // A temporary contact has been added permanently
+ else if (!strcmp(cws->szSetting, "NotOnList")) {
+ char *jid, *nick, *pGroup;
+
+ if (cws->value.type==DBVT_DELETED || (cws->value.type==DBVT_BYTE && cws->value.bVal==0)) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ jid = mir_strdup(dbv.pszVal);
+ DBFreeVariant(&dbv);
+ JabberLog(proto, "Add %s permanently to list", jid);
+ if (!DBGetContactSetting(hContact, "CList", "MyHandle", &dbv)) {
+ nick = JabberTextEncode(dbv.pszVal); //Utf8Encode
+ DBFreeVariant(&dbv);
+ }
+ else {
+ nick = JabberNickFromJID(jid);
+ }
+ if (nick != NULL) {
+ JabberLog(proto, "jid=%s nick=%s", jid, nick);
+ if (!DBGetContactSetting(hContact, "CList", "Group", &dbv)) {
+ if ((pGroup=TlenGroupEncode(dbv.pszVal)) != NULL) {
+ JabberSend(proto, "<iq type='set'><query xmlns='jabber:iq:roster'><item name='%s' jid='%s'><group>%s</group></item></query></iq>", nick, jid, pGroup);
+ JabberSend(proto, "<presence to='%s' type='subscribe'/>", jid);
+ mir_free(pGroup);
+ }
+ DBFreeVariant(&dbv);
+ }
+ else {
+ JabberSend(proto, "<iq type='set'><query xmlns='jabber:iq:roster'><item name='%s' jid='%s'/></query></iq>", nick, jid);
+ JabberSend(proto, "<presence to='%s' type='subscribe'/>", jid);
+ }
+ mir_free(nick);
+ DBDeleteContactSetting(hContact, "CList", "Hidden");
+ }
+ mir_free(jid);
+ }
+ }
+ }
+ }
+
+ return 0;
+}
+
+int JabberContactDeleted(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ char *szProto;
+ DBVARIANT dbv;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if(!proto->isOnline) // should never happen
+ return 0;
+ szProto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, wParam, 0);
+ if (szProto==NULL || strcmp(szProto, proto->iface.m_szModuleName))
+ return 0;
+ if (!DBGetContactSetting((HANDLE) wParam, proto->iface.m_szModuleName, "jid", &dbv)) {
+ char *jid, *p, *q;
+
+ jid = dbv.pszVal;
+ if ((p=strchr(jid, '@')) != NULL) {
+ if ((q=strchr(p, '/')) != NULL)
+ *q = '\0';
+ }
+ if (JabberListExist(proto, LIST_ROSTER, jid)) {
+ // Remove from roster, server also handles the presence unsubscription process.
+ JabberSend(proto, "<iq type='set'><query xmlns='jabber:iq:roster'><item jid='%s' subscription='remove'/></query></iq>", jid);
+ }
+
+ DBFreeVariant(&dbv);
+ }
+ return 0;
+}
+
+int TlenUserIsTyping(PROTO_INTERFACE *ptr, HANDLE hContact, int type)
+{
+ DBVARIANT dbv;
+ JABBER_LIST_ITEM *item;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!proto->isOnline) return 0;
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ if ((item=JabberListGetItemPtr(proto, LIST_ROSTER, dbv.pszVal))!=NULL /*&& item->wantComposingEvent==TRUE*/) {
+ switch (type) {
+ case PROTOTYPE_SELFTYPING_OFF:
+ JabberSend(proto, "<m tp='u' to='%s'/>", dbv.pszVal);
+ break;
+ case PROTOTYPE_SELFTYPING_ON:
+ JabberSend(proto, "<m tp='t' to='%s'/>", dbv.pszVal);
+ break;
+ }
+ }
+ DBFreeVariant(&dbv);
+ }
+ return 0;
+}
+
+INT_PTR TlenGetMyAvatar(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ char* buf = ( char* )wParam;
+ int size = ( int )lParam;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if ( buf == NULL || size <= 0 )
+ return -1;
+
+ TlenGetAvatarFileName( proto, NULL, buf, size );
+ return 0;
+}
+
+static INT_PTR CALLBACK TlenChangeAvatarDlgProc( HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam )
+{
+ switch ( msg ) {
+ case WM_INITDIALOG:
+ TranslateDialogDefault( hwndDlg );
+ {
+ HICON hIcon = GetIcolibIcon(IDI_TLEN);
+ SendMessage(hwndDlg, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) hIcon);
+ ReleaseIcolibIcon(hIcon);
+ }
+ CheckDlgButton(hwndDlg, IDC_PUBLICAVATAR, TRUE);
+ return TRUE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDOK:
+ {
+ int result = LOWORD(wParam);
+ if (IsDlgButtonChecked(hwndDlg, IDC_PUBLICAVATAR)) {
+ result |= 0x10000;
+ }
+ EndDialog(hwndDlg, result);
+ }
+ return TRUE;
+ }
+ break;
+ }
+ return 0;
+}
+
+INT_PTR TlenSetMyAvatar(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ char* szFileName = ( char* )lParam;
+ char tFileName[ MAX_PATH ];
+ int fileIn;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if(!proto->isOnline) return 1;
+ if (szFileName != NULL) {
+ int result = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_USER_CHANGEAVATAR), NULL, TlenChangeAvatarDlgProc, (LPARAM) NULL);
+ TlenGetAvatarFileName( proto, NULL, tFileName, MAX_PATH);
+ if ( CopyFileA( szFileName, tFileName, FALSE ) == FALSE ) {
+ return 1;
+ }
+ fileIn = open( tFileName, O_RDWR | O_BINARY, S_IREAD | S_IWRITE );
+ if ( fileIn != -1 ) {
+ long dwPngSize = filelength(fileIn);
+ BYTE* pResult = (BYTE *)mir_alloc(dwPngSize);
+ if (pResult != NULL) {
+ read( fileIn, pResult, dwPngSize );
+ close( fileIn );
+ TlenUploadAvatar(proto, pResult, dwPngSize, (result & 0x10000) != 0);
+ mir_free(pResult);
+ }
+ }
+ } else {
+ TlenRemoveAvatar(proto);
+ }
+ return 0;
+}
+
+INT_PTR TlenGetAvatarCaps(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ switch (wParam) {
+ case AF_MAXSIZE:
+ {
+ POINT* size = (POINT*)lParam;
+ if ( size )
+ size->x = size->y = 64;
+ }
+ return 0;
+ case AF_PROPORTION:
+ return PIP_SQUARE;
+ case AF_FORMATSUPPORTED:
+ return (lParam == PA_FORMAT_PNG) ? 1 : 0;
+ case AF_ENABLED:
+ return (proto->tlenOptions.enableAvatars && proto->isOnline) ? 1 : 0;
+ case AF_DONTNEEDDELAYS:
+ return 1;
+ case AF_MAXFILESIZE:
+ return 10 * 1024;
+ case AF_DELAYAFTERFAIL:
+ return 0;
+ }
+ return 0;
+}
+
+
+int TlenOnEvent( PROTO_INTERFACE *ptr, PROTOEVENTTYPE eventType, WPARAM wParam, LPARAM lParam )
+{
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ switch( eventType ) {
+ case EV_PROTO_ONLOAD: return TlenOnModulesLoaded(proto, 0, 0 );
+ case EV_PROTO_ONOPTIONS: return TlenOptionsInit(proto, wParam, lParam );
+ case EV_PROTO_ONEXIT: return TlenPreShutdown(proto, 0, 0 );
+ case EV_PROTO_ONRENAME:
+ {
+ CLISTMENUITEM clmi = { 0 };
+ clmi.cbSize = sizeof( CLISTMENUITEM );
+ clmi.flags = CMIM_NAME | CMIF_TCHAR;
+ clmi.ptszName = proto->iface.m_tszUserName;
+ CallService( MS_CLIST_MODIFYMENUITEM, ( WPARAM )proto->hMenuRoot, ( LPARAM )&clmi );
+ /* FIXME: Rename network user as well */
+ }
+ }
+ return 1;
+}
+
+// PSS_ADDED
+int TlenAuthRecv(PROTO_INTERFACE *ptr, HANDLE hContact, PROTORECVEVENT* evt )
+{
+ return 1;
+}
+
+// PSS_AUTHREQUEST
+int TlenAuthRequest(PROTO_INTERFACE *ptr, HANDLE hContact, const TCHAR* szMessage )
+{
+ return 1;
+}
+
+HANDLE TlenChangeInfo(PROTO_INTERFACE *ptr, int iInfoType, void* pInfoData )
+{
+ return NULL;
+}
+
+int TlenRecvContacts(PROTO_INTERFACE *ptr, HANDLE hContact, PROTORECVEVENT* evt)
+{
+ return 1;
+}
+
+
+extern INT_PTR CALLBACK TlenAccMgrUIDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+INT_PTR TlenAccMgrUI(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ return (INT_PTR) CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_ACCMGRUI), (HWND)lParam, TlenAccMgrUIDlgProc, (LPARAM) ptr);
+}
+
+void TlenInitServicesVTbl(TlenProtocol *proto) {
+ char s[128];
+ proto->iface.vtbl = (PROTO_INTERFACE_VTBL*) mir_alloc(sizeof(PROTO_INTERFACE_VTBL));
+ proto->iface.vtbl->AddToList = TlenAddToList;
+ proto->iface.vtbl->AddToListByEvent = TlenAddToListByEvent;
+ proto->iface.vtbl->AuthDeny = TlenAuthDeny;
+ proto->iface.vtbl->AuthRecv = TlenAuthRecv;
+ proto->iface.vtbl->AuthRequest = TlenAuthRequest;
+ proto->iface.vtbl->Authorize = TlenAuthAllow;
+ proto->iface.vtbl->ChangeInfo = TlenChangeInfo;
+ proto->iface.vtbl->FileAllow = TlenFileAllow;
+ proto->iface.vtbl->FileCancel = TlenFileCancel;
+ proto->iface.vtbl->FileDeny = TlenFileDeny;
+ proto->iface.vtbl->FileResume = NULL;
+ proto->iface.vtbl->SearchBasic = TlenBasicSearch;
+ proto->iface.vtbl->SearchByEmail = TlenSearchByEmail;
+ proto->iface.vtbl->SearchByName = TlenSearchByName;
+ proto->iface.vtbl->SearchAdvanced = TlenSearchAdvanced;
+ proto->iface.vtbl->CreateExtendedSearchUI = TlenCreateAdvSearchUI;
+
+ proto->iface.vtbl->RecvContacts = TlenRecvContacts;
+ proto->iface.vtbl->RecvFile = TlenRecvFile;
+ proto->iface.vtbl->RecvMsg = TlenRecvMessage;
+ proto->iface.vtbl->RecvUrl = NULL;
+
+ proto->iface.vtbl->SendContacts = NULL;
+ proto->iface.vtbl->SendFile = TlenSendFile;
+ proto->iface.vtbl->SendMsg = TlenSendMessage;
+ proto->iface.vtbl->SendUrl = NULL;
+
+ proto->iface.vtbl->GetCaps = TlenGetCaps;
+ proto->iface.vtbl->GetIcon = TlenGetIcon;
+ proto->iface.vtbl->GetInfo = JabberGetInfo;
+ proto->iface.vtbl->SetApparentMode = TlenSetApparentMode;
+ proto->iface.vtbl->SetStatus = TlenSetStatus;
+
+
+ proto->iface.vtbl->GetAwayMsg = TlenGetAwayMsg;
+ proto->iface.vtbl->RecvAwayMsg = NULL;
+ proto->iface.vtbl->SendAwayMsg = NULL;
+ proto->iface.vtbl->SetAwayMsg = TlenSetAwayMsg;
+
+ proto->iface.vtbl->UserIsTyping = TlenUserIsTyping;
+
+ proto->iface.vtbl->OnEvent = TlenOnEvent;
+
+ sprintf(s, "%s%s", proto->iface.m_szModuleName, PS_GETNAME);
+ CreateServiceFunction_Ex(s, proto, TlenGetName);
+
+ sprintf(s, "%s%s", proto->iface.m_szModuleName, PS_GETAVATARINFO);
+ CreateServiceFunction_Ex(s, proto, TlenGetAvatarInfo);
+
+ sprintf(s, "%s%s", proto->iface.m_szModuleName, "/SendNudge");
+ CreateServiceFunction_Ex(s, proto, TlenSendAlert);
+
+ sprintf(s, "%s%s", proto->iface.m_szModuleName, PS_GETAVATARCAPS);
+ CreateServiceFunction_Ex(s, proto, TlenGetAvatarCaps);
+
+ sprintf(s, "%s%s", proto->iface.m_szModuleName, PS_SETMYAVATAR);
+ CreateServiceFunction_Ex(s, proto, TlenSetMyAvatar);
+
+ sprintf(s, "%s%s", proto->iface.m_szModuleName, PS_GETMYAVATAR);
+ CreateServiceFunction_Ex(s, proto, TlenGetMyAvatar);
+
+ sprintf(s, "%s%s", proto->iface.m_szModuleName, PS_GETSTATUS);
+ CreateServiceFunction_Ex(s, proto, TlenGetStatus);
+
+ sprintf(s, "%s%s", proto->iface.m_szModuleName, PS_CREATEACCMGRUI);
+ CreateServiceFunction_Ex(s, proto, TlenAccMgrUI);
+
+}
+
diff --git a/protocols/Tlen/jabber_thread.c b/protocols/Tlen/jabber_thread.c
new file mode 100644
index 0000000000..b78cb1e9b5
--- /dev/null
+++ b/protocols/Tlen/jabber_thread.c
@@ -0,0 +1,1465 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+
+#include "commons.h"
+#include "jabber_list.h"
+#include "jabber_iq.h"
+#include "resource.h"
+#include "tlen_p2p_old.h"
+#include "tlen_file.h"
+#include "tlen_muc.h"
+#include "tlen_voice.h"
+#include "tlen_avatar.h"
+#include "tlen_presence.h"
+#include "tlen_picture.h"
+#include <io.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+extern void TlenProcessP2P(XmlNode *node, void *userdata);
+
+//static void __cdecl TlenProcessInvitation(struct ThreadData *info);
+static void __cdecl JabberKeepAliveThread(void *ptr);
+static void JabberProcessStreamOpening(XmlNode *node, ThreadData *info);
+static void JabberProcessStreamClosing(XmlNode *node, ThreadData *info);
+static void JabberProcessProtocol(XmlNode *node, ThreadData *info);
+static void JabberProcessMessage(XmlNode *node, ThreadData *info);
+static void JabberProcessIq(XmlNode *node, ThreadData *info);
+static void TlenProcessW(XmlNode *node, ThreadData *info);
+static void TlenProcessM(XmlNode *node, ThreadData *info);
+static void TlenProcessN(XmlNode *node, ThreadData *info);
+static void TlenProcessP(XmlNode *node, ThreadData *info);
+static void TlenProcessV(XmlNode *node, ThreadData *info);
+static void TlenProcessAvatar(XmlNode* node, ThreadData *info);
+static void TlenProcessCipher(XmlNode *node, ThreadData *info);
+
+static VOID NTAPI JabberDummyApcFunc(ULONG_PTR param)
+{
+ return;
+}
+
+static char onlinePassword[128];
+static HANDLE hEventPasswdDlg;
+
+static INT_PTR CALLBACK JabberPasswordDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char text[128];
+
+ switch (msg) {
+ case WM_INITDIALOG:
+ TranslateDialogDefault(hwndDlg);
+ sprintf(text, "%s %s", Translate("Enter password for"), (char *) lParam);
+ SetDlgItemTextA(hwndDlg, IDC_JID, text);
+ return TRUE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDOK:
+ GetDlgItemTextA(hwndDlg, IDC_PASSWORD, onlinePassword, sizeof(onlinePassword));
+ //EndDialog(hwndDlg, (int) onlinePassword);
+ //return TRUE;
+ // Fall through
+ case IDCANCEL:
+ //EndDialog(hwndDlg, 0);
+ SetEvent(hEventPasswdDlg);
+ DestroyWindow(hwndDlg);
+ return TRUE;
+ }
+ break;
+ }
+
+ return FALSE;
+}
+
+static VOID NTAPI JabberPasswordCreateDialogApcProc(ULONG_PTR param)
+{
+ CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_PASSWORD), NULL, JabberPasswordDlgProc, (LPARAM) param);
+}
+
+void __cdecl JabberServerThread(ThreadData *info)
+{
+ DBVARIANT dbv;
+ char jidStr[128];
+ char *connectHost;
+ char *buffer;
+ int datalen;
+ XmlState xmlState;
+ HANDLE hContact;
+ int jabberNetworkBufferSize;
+ int oldStatus = ID_STATUS_OFFLINE;
+ int reconnectMaxTime;
+ int numRetry;
+ int reconnectTime;
+ char *str;
+ CLISTMENUITEM clmi;
+ int loginErr = 0;
+ JabberLog(info->proto, "Thread started");
+
+
+ // Normal server connection, we will fetch all connection parameters
+ // e.g. username, password, etc. from the database.
+
+ if (info->proto->threadData != NULL) {
+ // Will not start another connection thread if a thread is already running.
+ // Make APC call to the main thread. This will immediately wake the thread up
+ // in case it is asleep in the reconnect loop so that it will immediately
+ // reconnect.
+ QueueUserAPC(JabberDummyApcFunc, info->proto->threadData->hThread, 0);
+ JabberLog(info->proto, "Thread ended, another normal thread is running");
+ mir_free(info);
+ return;
+ }
+
+ info->proto->threadData = info;
+
+ if (!DBGetContactSetting(NULL, info->proto->iface.m_szModuleName, "LoginName", &dbv)) {
+ strncpy(info->username, dbv.pszVal, sizeof(info->username));
+ info->username[sizeof(info->username)-1] = '\0';
+ _strlwr(info->username);
+ DBWriteContactSettingString(NULL, info->proto->iface.m_szModuleName, "LoginName", info->username);
+ DBFreeVariant(&dbv);
+
+ } else {
+ JabberLog(info->proto, "Thread ended, login name is not configured");
+ loginErr = LOGINERR_BADUSERID;
+ }
+
+ if (loginErr == 0) {
+ if (!DBGetContactSetting(NULL, info->proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ strncpy(info->server, dbv.pszVal, sizeof(info->server));
+ info->server[sizeof(info->server)-1] = '\0';
+ _strlwr(info->server);
+ DBWriteContactSettingString(NULL, info->proto->iface.m_szModuleName, "LoginServer", info->server);
+ DBFreeVariant(&dbv);
+ } else {
+ JabberLog(info->proto, "Thread ended, login server is not configured");
+ loginErr = LOGINERR_NONETWORK;
+ }
+ }
+
+ if (loginErr == 0) {
+ if (!info->proto->tlenOptions.savePassword) {
+ // Ugly hack: continue logging on only the return value is &(onlinePassword[0])
+ // because if WM_QUIT while dialog box is still visible, p is returned with some
+ // exit code which may not be NULL.
+ // Should be better with modeless.
+ onlinePassword[0] = (char) -1;
+ hEventPasswdDlg = CreateEvent(NULL, FALSE, FALSE, NULL);
+ QueueUserAPC(JabberPasswordCreateDialogApcProc, hMainThread, (DWORD) jidStr);
+ WaitForSingleObject(hEventPasswdDlg, INFINITE);
+ CloseHandle(hEventPasswdDlg);
+ //if ((p=(char *)DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_PASSWORD), NULL, JabberPasswordDlgProc, (LPARAM) jidStr)) != onlinePassword) {
+ if (onlinePassword[0] != (char) -1) {
+ strncpy(info->password, onlinePassword, sizeof(info->password));
+ info->password[sizeof(info->password)-1] = '\0';
+ } else {
+ JabberLog(info->proto, "Thread ended, password request dialog was canceled");
+ loginErr = LOGINERR_BADUSERID;
+ }
+ } else {
+ if (!DBGetContactSetting(NULL, info->proto->iface.m_szModuleName, "Password", &dbv)) {
+ CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1, (LPARAM) dbv.pszVal);
+ strncpy(info->password, dbv.pszVal, sizeof(info->password));
+ info->password[sizeof(info->password)-1] = '\0';
+ DBFreeVariant(&dbv);
+ } else {
+ JabberLog(info->proto, "Thread ended, password is not configured");
+ loginErr = LOGINERR_BADUSERID;
+ }
+ }
+ }
+
+ jabberNetworkBufferSize = 2048;
+ if ((buffer=(char *) mir_alloc(jabberNetworkBufferSize+1)) == NULL) { // +1 is for '\0' when debug logging this buffer
+ JabberLog(info->proto, "Thread ended, network buffer cannot be allocated");
+ loginErr = LOGINERR_NONETWORK;
+ }
+
+ if (loginErr != 0) {
+ info->proto->threadData = NULL;
+ oldStatus = info->proto->iface.m_iStatus;
+ info->proto->iface.m_iStatus = ID_STATUS_OFFLINE;
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, info->proto->iface.m_iStatus);
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, NULL, ACKTYPE_LOGIN, ACKRESULT_FAILED, NULL, loginErr);
+ mir_free(info);
+ return;
+ }
+
+ _snprintf(jidStr, sizeof(jidStr), "%s@%s", info->username, info->server);
+ DBWriteContactSettingString(NULL, info->proto->iface.m_szModuleName, "jid", jidStr);
+
+ if (!DBGetContactSetting(NULL, info->proto->iface.m_szModuleName, "ManualHost", &dbv)) {
+ strncpy(info->manualHost, dbv.pszVal, sizeof(info->manualHost));
+ info->manualHost[sizeof(info->manualHost)-1] = '\0';
+ DBFreeVariant(&dbv);
+ }
+ info->port = DBGetContactSettingWord(NULL, info->proto->iface.m_szModuleName, "ManualPort", TLEN_DEFAULT_PORT);
+ info->useEncryption = info->proto->tlenOptions.useEncryption;
+
+ if (info->manualHost[0])
+ connectHost = info->manualHost;
+ else
+ connectHost = info->server;
+
+ JabberLog(info->proto, "Thread server='%s' port='%d'", connectHost, info->port);
+
+
+ if (!DBGetContactSetting(NULL, info->proto->iface.m_szModuleName, "AvatarHash", &dbv)) {
+ strcpy(info->proto->threadData->avatarHash, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ info->avatarFormat = DBGetContactSettingDword(NULL, info->proto->iface.m_szModuleName, "AvatarFormat", PA_FORMAT_UNKNOWN);
+
+
+ reconnectMaxTime = 10;
+ numRetry = 0;
+
+ for (;;) { // Reconnect loop
+
+ info->s = JabberWsConnect(info->proto, connectHost, info->port);
+ if (info->s == NULL) {
+ JabberLog(info->proto, "Connection failed (%d)", WSAGetLastError());
+ if (info->proto->threadData == info) {
+ oldStatus = info->proto->iface.m_iStatus;
+ info->proto->iface.m_iStatus = ID_STATUS_OFFLINE;
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, NULL, ACKTYPE_LOGIN, ACKRESULT_FAILED, NULL, LOGINERR_NONETWORK);
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, info->proto->iface.m_iStatus);
+ if (info->proto->tlenOptions.reconnect == TRUE) {
+ reconnectTime = rand() % reconnectMaxTime;
+ JabberLog(info->proto, "Sleeping %d seconds before automatic reconnecting...", reconnectTime);
+ SleepEx(reconnectTime * 1000, TRUE);
+ if (reconnectMaxTime < 10*60) // Maximum is 10 minutes
+ reconnectMaxTime *= 2;
+ if (info->proto->threadData == info) { // Make sure this is still the active thread for the main Jabber connection
+ JabberLog(info->proto, "Reconnecting to the network...");
+ if (numRetry < MAX_CONNECT_RETRIES)
+ numRetry++;
+ oldStatus = info->proto->iface.m_iStatus;
+ info->proto->iface.m_iStatus = ID_STATUS_CONNECTING + numRetry;
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, info->proto->iface.m_iStatus);
+ continue;
+ }
+ else {
+ JabberLog(info->proto, "Thread ended, connection failed");
+ mir_free(buffer);
+ mir_free(info);
+ return;
+ }
+ }
+ info->proto->threadData = NULL;
+ }
+ JabberLog(info->proto, "Thread ended, connection failed");
+ mir_free(buffer);
+ mir_free(info);
+ return;
+ }
+
+ // Determine local IP
+ /*
+ socket = CallService(MS_NETLIB_GETSOCKET, (WPARAM) proto, 0);
+ struct sockaddr_in saddr;
+ int len;
+
+ len = sizeof(saddr);
+ getsockname(socket, (struct sockaddr *) &saddr, &len);
+ jabberLocalIP = saddr.sin_addr.S_un.S_addr;
+ JabberLog("Local IP = %s", inet_ntoa(saddr.sin_addr));
+ */
+
+ // User may change status to OFFLINE while we are connecting above
+ if (info->proto->iface.m_iDesiredStatus!=ID_STATUS_OFFLINE) {
+
+ info->proto->isConnected = TRUE;
+ JabberForkThread(JabberKeepAliveThread, 0, info->proto);
+
+ JabberXmlInitState(&xmlState);
+ JabberXmlSetCallback(&xmlState, 1, ELEM_OPEN, JabberProcessStreamOpening, info);
+ JabberXmlSetCallback(&xmlState, 1, ELEM_CLOSE, JabberProcessStreamClosing, info);
+ JabberXmlSetCallback(&xmlState, 2, ELEM_CLOSE, JabberProcessProtocol, info);
+
+ info->useAES = FALSE;
+
+ if (info->useEncryption) {
+ JabberSend(info->proto, "<s s='1' v='9' t='06000106'>");
+
+ } else {
+ JabberSend(info->proto, "<s v='3'>");
+ }
+
+ JabberLog(info->proto, "Entering main recv loop");
+ datalen = 0;
+
+ for (;;) {
+ int recvResult, bytesParsed;
+
+ if (info->useAES) {
+ recvResult = JabberWsRecvAES(info->proto, buffer+datalen, jabberNetworkBufferSize-datalen, &info->aes_in_context, info->aes_in_iv);
+ } else {
+ recvResult = JabberWsRecv(info->proto, info->s, buffer+datalen, jabberNetworkBufferSize-datalen);
+ }
+
+ if (recvResult <= 0)
+ break;
+ datalen += recvResult;
+
+ buffer[datalen] = '\0';
+ JabberLog(info->proto, "RECV:%s", buffer);
+
+ bytesParsed = JabberXmlParse(&xmlState, buffer, datalen);
+ JabberLog(info->proto, "bytesParsed = %d", bytesParsed);
+ if (bytesParsed > 0) {
+ if (bytesParsed < datalen)
+ memmove(buffer, buffer+bytesParsed, datalen-bytesParsed);
+ datalen -= bytesParsed;
+ }
+ else if (datalen == jabberNetworkBufferSize) {
+ jabberNetworkBufferSize += 2048;
+ JabberLog(info->proto, "Increasing network buffer size to %d", jabberNetworkBufferSize);
+ if ((buffer=(char *) mir_realloc(buffer, jabberNetworkBufferSize+1)) == NULL) {
+ JabberLog(info->proto, "Cannot reallocate more network buffer, go offline now");
+ break;
+ }
+ }
+ else {
+ JabberLog(info->proto, "Unknown state: bytesParsed=%d, datalen=%d, jabberNetworkBufferSize=%d", bytesParsed, datalen, jabberNetworkBufferSize);
+ }
+ }
+
+ JabberXmlDestroyState(&xmlState);
+
+ info->proto->isOnline = FALSE;
+ info->proto->isConnected = FALSE;
+
+ memset(&clmi, 0, sizeof(CLISTMENUITEM));
+ clmi.cbSize = sizeof(CLISTMENUITEM);
+ clmi.flags = CMIM_FLAGS | CMIF_GRAYED;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) info->proto->hMenuMUC, (LPARAM) &clmi);
+ if (info->proto->hMenuChats != NULL){
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) info->proto->hMenuChats, (LPARAM) &clmi);
+ }
+
+ // Set status to offline
+ oldStatus = info->proto->iface.m_iStatus;
+ info->proto->iface.m_iStatus = ID_STATUS_OFFLINE;
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, info->proto->iface.m_iStatus);
+
+ // Set all contacts to offline
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ while (hContact != NULL) {
+ str = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if(str!=NULL && !strcmp(str, info->proto->iface.m_szModuleName)) {
+ if (DBGetContactSettingWord(hContact, info->proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE) != ID_STATUS_OFFLINE) {
+ DBWriteContactSettingWord(hContact, info->proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE);
+ }
+ }
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM) hContact, 0);
+ }
+
+ JabberListWipeSpecial(info->proto);
+ }
+ else {
+ oldStatus = info->proto->iface.m_iStatus;
+ info->proto->iface.m_iStatus = ID_STATUS_OFFLINE;
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, info->proto->iface.m_iStatus);
+ }
+
+ Netlib_CloseHandle(info->s);
+
+ if (info->proto->tlenOptions.reconnect==FALSE)
+ break;
+
+ if (info->proto->threadData != info) // Make sure this is still the main Jabber connection thread
+ break;
+ reconnectTime = rand() % 10;
+ JabberLog(info->proto, "Sleeping %d seconds before automatic reconnecting...", reconnectTime);
+ SleepEx(reconnectTime * 1000, TRUE);
+ reconnectMaxTime = 20;
+ if (info->proto->threadData != info) // Make sure this is still the main Jabber connection thread
+ break;
+ JabberLog(info->proto, "Reconnecting to the network...");
+ info->proto->iface.m_iDesiredStatus = oldStatus; // Reconnect to my last status
+ oldStatus = info->proto->iface.m_iStatus;
+ info->proto->iface.m_iStatus = ID_STATUS_CONNECTING;
+ numRetry = 1;
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE) oldStatus, info->proto->iface.m_iStatus);
+ }
+
+ JabberLog(info->proto, "Thread ended: server='%s'", info->server);
+
+ if (info->proto->threadData==info) {
+ info->proto->threadData = NULL;
+ }
+
+ mir_free(buffer);
+ if (info->streamId) mir_free(info->streamId);
+ JabberLog(info->proto, "Exiting ServerThread");
+ mir_free(info);
+}
+
+static void TlenSendAuth(TlenProtocol *proto) {
+ int iqId;
+ char *p;
+ char *str;
+ char text[128];
+ str = TlenPasswordHash(proto->threadData->password);
+ sprintf(text, "%s%s", proto->threadData->streamId, str);
+ mir_free(str);
+ str = JabberSha1(text);
+ if ((p=JabberTextEncode(proto->threadData->username)) != NULL) {
+ iqId = JabberSerialNext(proto->threadData->proto);
+ JabberIqAdd(proto, iqId, IQ_PROC_NONE, JabberIqResultAuth);
+ JabberSend(proto, "<iq type='set' id='"JABBER_IQID"%d'><query xmlns='jabber:iq:auth'><username>%s</username><digest>%s</digest><resource>t</resource><host>tlen.pl</host></query></iq>", iqId, p /*info->username*/, str);
+ mir_free(p);
+ }
+ mir_free(str);
+}
+
+static void JabberProcessStreamOpening(XmlNode *node, ThreadData *info)
+{
+ char *sid, *s;
+
+ if (node->name==NULL || strcmp(node->name, "s"))
+ return;
+
+ if ((sid=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if (info->streamId) mir_free(info->streamId);
+ info->streamId = mir_strdup(sid);
+ }
+ if ((s=JabberXmlGetAttrValue(node, "s")) != NULL && !strcmp(s, "1")) {
+ int i;
+ char *k1, *k2, *k3;
+ unsigned char aes_key[32];
+ char aes_key_str[140], aes_iv_str[40];
+ mpi k1_mpi, k2_mpi, aes_mpi;
+ size_t slen;
+
+ k1=JabberXmlGetAttrValue(node, "k1");
+ k2=JabberXmlGetAttrValue(node, "k2");
+ k3=JabberXmlGetAttrValue(node, "k3");
+
+ memset(&info->aes_in_context, 0, sizeof (aes_context));
+ memset(&info->aes_out_context, 0, sizeof (aes_context));
+ memset(&aes_mpi, 0, sizeof (mpi));
+ mpi_read_string(&aes_mpi, 16, k3);
+ mpi_write_binary(&aes_mpi, info->aes_in_iv, 16);
+ for (i = 0; i < 16; i++) {
+ info->aes_out_iv[i] = rand();
+ aes_key[i] = rand();
+ }
+ memset(&aes_mpi, 0, sizeof (mpi));
+ mpi_read_binary(&aes_mpi, info->aes_out_iv, 16);
+ slen = 40;
+ mpi_write_string(&aes_mpi, 16, aes_iv_str, &slen);
+ aes_setkey_dec(&info->aes_in_context, aes_key, 128);
+ aes_setkey_enc(&info->aes_out_context, aes_key, 128);
+ memset(&aes_mpi, 0, sizeof (mpi));
+ mpi_read_binary(&aes_mpi, aes_key, 16);
+ memset(&k1_mpi, 0, sizeof (mpi));
+ mpi_read_string( &k1_mpi, 16, k1 );
+ memset(&k2_mpi, 0, sizeof (mpi));
+ mpi_read_string( &k2_mpi, 16, k2 );
+ memset(&aes_mpi, 0, sizeof (mpi));
+ mpi_read_binary(&aes_mpi, (unsigned char *)aes_key, 16);
+ mpi_exp_mod( &aes_mpi, &aes_mpi, &k1_mpi, &k2_mpi, NULL );
+ slen = 140;
+ mpi_write_string(&aes_mpi, 16, aes_key_str, &slen);
+ JabberSend(info->proto, "<cipher k1='%s' k2='%s'/>", aes_key_str, aes_iv_str);
+ } else {
+ TlenSendAuth(info->proto);
+ }
+}
+
+static void JabberProcessStreamClosing(XmlNode *node, ThreadData *info)
+{
+ Netlib_CloseHandle(info->proto);
+ if (node->name && !strcmp(node->name, "stream:error") && node->text)
+ MessageBoxA(NULL, Translate(node->text), Translate("Jabber Connection Error"), MB_OK|MB_ICONERROR|MB_SETFOREGROUND);
+}
+
+static void JabberProcessProtocol(XmlNode *node, ThreadData *info)
+{
+ if (!strcmp(node->name, "message"))
+ JabberProcessMessage(node, info);
+ else if (!strcmp(node->name, "presence"))
+ TlenProcessPresence(node, info->proto);
+ else if (!strcmp(node->name, "iq"))
+ JabberProcessIq(node, info);
+ else if (!strcmp(node->name, "f"))
+ TlenProcessF(node, info);
+ else if (!strcmp(node->name, "w"))
+ TlenProcessW(node, info);
+ else if (!strcmp(node->name, "m"))
+ TlenProcessM(node, info);
+ else if (!strcmp(node->name, "n"))
+ TlenProcessN(node, info);
+ else if (!strcmp(node->name, "p"))
+ TlenProcessP(node, info);
+ else if (!strcmp(node->name, "v"))
+ TlenProcessV(node, info);
+ else if (!strcmp(node->name, "avatar"))
+ TlenProcessAvatar(node, info);
+ else if (!strcmp(node->name, "cipher"))
+ TlenProcessCipher(node, info);
+ else
+ JabberLog(info->proto, "Invalid top-level tag (only <message/> <presence/> <iq/> <f/> <w/> <m/> <n/> <p/> <v/> <cipher/> and <avatar/> allowed)");
+
+}
+
+static void TlenProcessCipher(XmlNode *node, ThreadData *info)
+{
+ char *type;
+ type=JabberXmlGetAttrValue(node, "type");
+ info->useAES = TRUE;
+ JabberSend(info->proto, "<cipher type='ok'/>");
+ TlenSendAuth(info->proto);
+}
+
+static void TlenProcessIqGetVersion(TlenProtocol *proto, XmlNode* node)
+{
+ OSVERSIONINFO osvi = { 0 };
+ char mversion[256];
+ char* from, *version, *mver;
+ char* os = NULL;
+ JABBER_LIST_ITEM *item;
+
+ if (proto->iface.m_iStatus == ID_STATUS_INVISIBLE) return;
+ if (!proto->tlenOptions.enableVersion) return;
+ if (( from=JabberXmlGetAttrValue( node, "from" )) == NULL ) return;
+ if (( item=JabberListGetItemPtr( proto, LIST_ROSTER, from )) ==NULL) return;
+ version = JabberTextEncode( TLEN_VERSION_STRING );
+ osvi.dwOSVersionInfoSize = sizeof( OSVERSIONINFO );
+ if ( GetVersionEx( &osvi )) {
+ switch ( osvi.dwPlatformId ) {
+ case VER_PLATFORM_WIN32_NT:
+ if ( osvi.dwMajorVersion == 5 ) {
+ if ( osvi.dwMinorVersion == 2 ) os = JabberTextEncode( Translate( "Windows Server 2003" ));
+ else if ( osvi.dwMinorVersion == 1 ) os = JabberTextEncode( Translate( "Windows XP" ));
+ else if ( osvi.dwMinorVersion == 0 ) os = JabberTextEncode( Translate( "Windows 2000" ));
+ }
+ else if ( osvi.dwMajorVersion <= 4 ) {
+ os = JabberTextEncode( Translate( "Windows NT" ));
+ }
+ break;
+ case VER_PLATFORM_WIN32_WINDOWS:
+ if ( osvi.dwMajorVersion == 4 ) {
+ if ( osvi.dwMinorVersion == 0 ) os = JabberTextEncode( Translate( "Windows 95" ));
+ if ( osvi.dwMinorVersion == 10 ) os = JabberTextEncode( Translate( "Windows 98" ));
+ if ( osvi.dwMinorVersion == 90 ) os = JabberTextEncode( Translate( "Windows ME" ));
+ }
+ break;
+ } }
+
+ if ( os == NULL ) os = JabberTextEncode( Translate( "Windows" ));
+
+ strcpy(mversion, "Miranda IM ");
+ CallService( MS_SYSTEM_GETVERSIONTEXT, sizeof( mversion ) - 11, ( LPARAM )mversion + 11 );
+ strcat(mversion, " (Tlen v.");
+ strcat(mversion, TLEN_VERSION_STRING);
+ strcat(mversion, ")");
+ mver = JabberTextEncode( mversion );
+ JabberSend( proto, "<message to='%s' type='iq'><iq type='result'><query xmlns='jabber:iq:version'><name>%s</name><version>%s</version><os>%s</os></query></iq></message>", from, mver?mver:"", version?version:"", os?os:"" );
+ if (!item->versionRequested) {
+ item->versionRequested = TRUE;
+ JabberSend(proto, "<message to='%s' type='iq'><iq type='get'><query xmlns='jabber:iq:version'/></iq></message>", from);
+ }
+
+ if ( mver ) mir_free( mver );
+ if ( version ) mir_free( version );
+ if ( os ) mir_free( os );
+}
+
+// Support for Tlen avatars - avatar token used to access web interface
+static void TlenProcessAvatar(XmlNode* node, ThreadData *info)
+{
+ XmlNode *tokenNode, *aNode;
+ tokenNode = JabberXmlGetChild(node, "token");
+ aNode = JabberXmlGetChild(node, "a");
+ if (tokenNode != NULL) {
+ char *token = tokenNode->text;
+ strcpy(info->avatarToken, token);
+ }
+ if (aNode != NULL) {
+ if (TlenProcessAvatarNode(info->proto, node, NULL)) {
+ }
+ }
+}
+
+static void JabberProcessMessage(XmlNode *node, ThreadData *info)
+{
+ HANDLE hContact;
+ CCSDATA ccs;
+ PROTORECVEVENT recv;
+ XmlNode *bodyNode, *subjectNode, *xNode, *n;
+ char *from, *type, *nick, *p, *localMessage, *idStr;
+ DWORD msgTime;
+ BOOL delivered, composing;
+ int i;
+ JABBER_LIST_ITEM *item;
+ BOOL isChatRoomJid;
+
+ if (!node->name || strcmp(node->name, "message")) return;
+
+ if ((type=JabberXmlGetAttrValue(node, "type"))!=NULL && !strcmp(type, "error")) {
+ }
+ else {
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ char *fromJid = JabberLoginFromJID(from);
+ if (info->proto->tlenOptions.ignoreAdvertisements && strstr(from, "b73@tlen.pl") == from) {
+ return;
+ }
+ // If message is from a stranger (not in roster), item is NULL
+ item = JabberListGetItemPtr(info->proto, LIST_ROSTER, fromJid);
+ isChatRoomJid = JabberListExist(info->proto, LIST_CHATROOM, from);
+
+ if (isChatRoomJid && type!=NULL && !strcmp(type, "groupchat")) {
+ //JabberGroupchatProcessMessage(node, userdata);
+ } else if (type!=NULL && !strcmp(type, "pic")) {
+ TlenProcessPic(node, info->proto);
+ } else if (type!=NULL && !strcmp(type, "iq")) {
+ XmlNode *iqNode;
+ // Jabber-compatible iq
+ if ((iqNode=JabberXmlGetChild(node, "iq")) != NULL) {
+ JabberXmlAddAttr(iqNode, "from", from);
+ JabberProcessIq(iqNode, info);
+ }
+ } else {
+ if ((bodyNode=JabberXmlGetChild(node, "body")) != NULL) {
+ if (bodyNode->text != NULL) {
+ if ((subjectNode=JabberXmlGetChild(node, "subject"))!=NULL && subjectNode->text!=NULL && subjectNode->text[0]!='\0') {
+ p = (char *) mir_alloc(strlen(subjectNode->text)+strlen(bodyNode->text)+5);
+ sprintf(p, "%s\r\n%s", subjectNode->text, bodyNode->text);
+ localMessage = JabberTextDecode(p);
+ mir_free(p);
+ } else {
+ localMessage = JabberTextDecode(bodyNode->text);
+ }
+
+ msgTime = 0;
+ delivered = composing = FALSE;
+ i = 1;
+ while ((xNode=JabberXmlGetNthChild(node, "x", i)) != NULL) {
+ if ((p=JabberXmlGetAttrValue(xNode, "xmlns")) != NULL) {
+ if (!strcmp(p, "jabber:x:delay") && msgTime==0) {
+ if ((p=JabberXmlGetAttrValue(xNode, "stamp")) != NULL) {
+ msgTime = JabberIsoToUnixTime(p);
+ }
+ }
+ else if (!strcmp(p, "jabber:x:event")) {
+ // Check whether any event is requested
+ if (!delivered && (n=JabberXmlGetChild(xNode, "delivered"))!=NULL) {
+ delivered = TRUE;
+ idStr = JabberXmlGetAttrValue(node, "id");
+ JabberSend(info->proto, "<message to='%s'><x xmlns='jabber:x:event'><delivered/><id>%s</id></x></message>", from, (idStr!=NULL)?idStr:"");
+ }
+ if (item!=NULL && JabberXmlGetChild(xNode, "composing")!=NULL) {
+ composing = TRUE;
+ if (item->messageEventIdStr)
+ mir_free(item->messageEventIdStr);
+ idStr = JabberXmlGetAttrValue(node, "id");
+ item->messageEventIdStr = (idStr==NULL)?NULL:mir_strdup(idStr);
+ }
+ }
+ }
+ i++;
+ }
+
+ if (item != NULL) {
+ item->wantComposingEvent = composing;
+ if (item->isTyping) {
+ item->isTyping = FALSE;
+ if ((hContact=JabberHContactFromJID(info->proto, fromJid)) != NULL)
+ CallService(MS_PROTO_CONTACTISTYPING, (WPARAM) hContact, PROTOTYPE_CONTACTTYPING_OFF);
+ }
+ }
+
+ if ((hContact=JabberHContactFromJID(info->proto, fromJid)) == NULL) {
+ // Create a temporary contact
+ if (isChatRoomJid) {
+ if ((p=strchr(from, '/'))!=NULL && p[1]!='\0')
+ p++;
+ else
+ p = from;
+ nick = JabberTextEncode(p);
+ hContact = JabberDBCreateContact(info->proto, from, nick, TRUE);
+ }
+ else {
+ nick = JabberLocalNickFromJID(from);
+ hContact = JabberDBCreateContact(info->proto, from, nick, TRUE);
+ }
+ mir_free(nick);
+ }
+
+ if (msgTime == 0) {
+ msgTime = time(NULL);
+ } else {
+ HANDLE hDbEvent = (HANDLE) CallService(MS_DB_EVENT_FINDLAST, (WPARAM) hContact, 0);
+ if (hDbEvent != NULL) {
+ DBEVENTINFO dbei = { 0 };
+ dbei.cbSize = sizeof(dbei);
+ CallService(MS_DB_EVENT_GET, (WPARAM) hDbEvent, (LPARAM) &dbei);
+ if (msgTime < dbei.timestamp) {
+ msgTime = dbei.timestamp + 1;
+ }
+ }
+ if (msgTime > (DWORD)time(NULL)) {
+ msgTime = time(NULL);
+ }
+ }
+ recv.flags = 0;
+ recv.timestamp = (DWORD) msgTime;
+ recv.szMessage = localMessage;
+ recv.lParam = 0;
+ ccs.hContact = hContact;
+ ccs.wParam = 0;
+ ccs.szProtoService = PSR_MESSAGE;
+ ccs.lParam = (LPARAM) &recv;
+ CallService(MS_PROTO_CHAINRECV, 0, (LPARAM) &ccs);
+
+ mir_free(localMessage);
+ }
+ }
+ }
+ mir_free(fromJid);
+ }
+ }
+}
+
+static void JabberProcessIq(XmlNode *node, ThreadData *info)
+{
+ HANDLE hContact;
+ XmlNode *queryNode = NULL;
+ char *type, *jid, *nick;
+ char *xmlns = NULL;
+ char *idStr, *str;
+ int id;
+ int i;
+ JABBER_IQ_PFUNC pfunc;
+
+ if (!node->name || strcmp(node->name, "iq")) return;
+ type=JabberXmlGetAttrValue(node, "type");
+// if ((type=JabberXmlGetAttrValue(node, "type")) == NULL) return;
+
+ id = -1;
+ if ((idStr=JabberXmlGetAttrValue(node, "id")) != NULL) {
+ if (!strncmp(idStr, JABBER_IQID, strlen(JABBER_IQID)))
+ id = atoi(idStr+strlen(JABBER_IQID));
+ }
+
+ queryNode = JabberXmlGetChild(node, "query");
+ if (queryNode != NULL) {
+ xmlns = JabberXmlGetAttrValue(queryNode, "xmlns");
+ }
+
+
+ /////////////////////////////////////////////////////////////////////////
+ // MATCH BY ID
+ /////////////////////////////////////////////////////////////////////////
+ if ((pfunc=JabberIqFetchFunc(info->proto, id)) != NULL) {
+ JabberLog(info->proto, "Handling iq request for id=%d", id);
+ pfunc(info->proto, node);
+ /////////////////////////////////////////////////////////////////////////
+ // MORE GENERAL ROUTINES, WHEN ID DOES NOT MATCH
+ /////////////////////////////////////////////////////////////////////////
+ // new p2p connections
+ } else if (xmlns != NULL && !strcmp(xmlns, "p2p")) {
+ if (info->proto->tlenOptions.useNewP2P) {
+ TlenProcessP2P(node, info);
+ }
+ }
+ // RECVED: <iq type='set'><query ...
+ else if (!strcmp(type, "set") && queryNode!=NULL && xmlns!=NULL) {
+
+ // RECVED: roster push
+ // ACTION: similar to iqIdGetRoster above
+ if (!strcmp(xmlns, "jabber:iq:roster")) {
+ XmlNode *itemNode, *groupNode;
+ JABBER_LIST_ITEM *item;
+ char *name;
+
+ JabberLog(info->proto, "<iq/> Got roster push, query has %d children", queryNode->numChild);
+ for (i=0; i<queryNode->numChild; i++) {
+ itemNode = queryNode->child[i];
+ if (!strcmp(itemNode->name, "item")) {
+ if ((jid=JabberXmlGetAttrValue(itemNode, "jid")) != NULL) {
+ if ((str=JabberXmlGetAttrValue(itemNode, "subscription")) != NULL) {
+ // we will not add new account when subscription=remove
+ if (!strcmp(str, "to") || !strcmp(str, "both") || !strcmp(str, "from") || !strcmp(str, "none")) {
+ if ((name=JabberXmlGetAttrValue(itemNode, "name")) != NULL) {
+ nick = JabberTextDecode(name);
+ } else {
+ nick = JabberLocalNickFromJID(jid);
+ }
+ if (nick != NULL) {
+ if ((item=JabberListAdd(info->proto, LIST_ROSTER, jid)) != NULL) {
+ if (item->nick) mir_free(item->nick);
+ item->nick = nick;
+ if ((hContact=JabberHContactFromJID(info->proto, jid)) == NULL) {
+ // Received roster has a new JID.
+ // Add the jid (with empty resource) to Miranda contact list.
+ hContact = JabberDBCreateContact(info->proto, jid, nick, FALSE);
+ }
+ DBWriteContactSettingString(hContact, "CList", "MyHandle", nick);
+ if (item->group) mir_free(item->group);
+ if ((groupNode=JabberXmlGetChild(itemNode, "group"))!=NULL && groupNode->text!=NULL) {
+ item->group = TlenGroupDecode(groupNode->text);
+ JabberContactListCreateGroup(item->group);
+ DBWriteContactSettingString(hContact, "CList", "Group", item->group);
+ }
+ else {
+ item->group = NULL;
+ DBDeleteContactSetting(hContact, "CList", "Group");
+ }
+ if (!strcmp(str, "none") || (!strcmp(str, "from") && strchr(jid, '@')!=NULL)) {
+ if (DBGetContactSettingWord(hContact, info->proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE) != ID_STATUS_OFFLINE)
+ DBWriteContactSettingWord(hContact, info->proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE);
+ }
+ }
+ else {
+ mir_free(nick);
+ }
+ }
+ }
+ if ((item=JabberListGetItemPtr(info->proto, LIST_ROSTER, jid)) != NULL) {
+ if (!strcmp(str, "both")) item->subscription = SUB_BOTH;
+ else if (!strcmp(str, "to")) item->subscription = SUB_TO;
+ else if (!strcmp(str, "from")) item->subscription = SUB_FROM;
+ else item->subscription = SUB_NONE;
+ JabberLog(info->proto, "Roster push for jid=%s, set subscription to %s", jid, str);
+ // subscription = remove is to remove from roster list
+ // but we will just set the contact to offline and not actually
+ // remove, so that history will be retained.
+ if (!strcmp(str, "remove")) {
+ if ((hContact=JabberHContactFromJID(info->proto, jid)) != NULL) {
+ if (DBGetContactSettingWord(hContact, info->proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE) != ID_STATUS_OFFLINE)
+ DBWriteContactSettingWord(hContact, info->proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE);
+ JabberListRemove(info->proto, LIST_ROSTER, jid);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ }
+ // RECVED: <iq type='get'><query ...
+ else if ( !strcmp( type, "get" ) && queryNode!=NULL && xmlns!=NULL ) {
+ // RECVED: software version query
+ // ACTION: return my software version
+ if ( !strcmp( xmlns, "jabber:iq:version" )) TlenProcessIqGetVersion(info->proto, node);
+ }
+ // RECVED: <iq type='result'><query ...
+ else if ( !strcmp( type, "result") && queryNode!=NULL) {
+ if (xmlns!=NULL ) {
+ if ( !strcmp(xmlns, "jabber:iq:roster" )) {
+ JabberIqResultRoster(info->proto, node);
+ } else if ( !strcmp( xmlns, "jabber:iq:version" )) {
+ TlenIqResultVersion(info->proto, node);
+ } else if ( !strcmp( xmlns, "jabber:iq:info" )) {
+ TlenIqResultInfo(info->proto, node);
+ }
+ } else {
+ char *from;
+ if (( from=JabberXmlGetAttrValue( node, "from" )) != NULL ) {
+ if ( !strcmp(from, "tcfg" )) {
+ TlenIqResultTcfg(info->proto, node);
+ }
+ }
+ }
+ }
+ // RECVED: <iq type='error'> ...
+ else if (!strcmp(type, "error")) {
+ JABBER_LIST_ITEM *item;
+ // Check for multi-user chat errors
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strstr(from, "@c")!=NULL || !strcmp(from, "c")) {
+ TlenMUCRecvError(info->proto, from, node);
+ return;
+ }
+ }
+
+ // Check for file transfer deny by comparing idStr with ft->iqId
+ i = 0;
+ while ((i=JabberListFindNext(info->proto, LIST_FILE, i)) >= 0) {
+ item = JabberListGetItemPtrFromIndex(info->proto,i);
+ if (item->ft->state==FT_CONNECTING && !strcmp(idStr, item->ft->iqId)) {
+ item->ft->state = FT_DENIED;
+ if (item->ft->hFileEvent != NULL)
+ SetEvent(item->ft->hFileEvent); // Simulate the termination of file server connection
+ }
+ i++;
+ }
+ }
+ // RECVED: <iq type='1'>...
+ else if (!strcmp(type, "1")) { // Chat groups list result
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strcmp(from, "c")==0) {
+ TlenIqResultChatGroups(info->proto, node);
+ }
+ }
+ }
+ else if (!strcmp(type, "2")) { // Chat rooms list result
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strcmp(from, "c")==0) {
+ TlenIqResultChatRooms(info->proto, node);
+ }
+ }
+ } else if (!strcmp(type, "3")) { // room search result - result to iq type 3 query
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strcmp(from, "c")==0) {
+ TlenIqResultRoomSearch(info->proto, node);
+ }
+ }
+ } else if (!strcmp(type, "4")) { // chat room users list
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strstr(from, "@c")!=NULL) {
+ TlenIqResultChatRoomUsers(info->proto, node);
+ }
+ }
+ } else if (!strcmp(type, "5")) { // room name & group & flags info - sent on joining the room
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strstr(from, "@c")!=NULL) {
+ TlenIqResultRoomInfo(info->proto, node);
+ }
+ }
+ } else if (!strcmp(type, "6")) { // new nick registered
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strcmp(from, "c")==0) {
+ TlenIqResultUserNicks(info->proto, node);
+ }
+ }
+ } else if (!strcmp(type, "7")) { // user nicknames list
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strcmp(from, "c")==0) {
+ TlenIqResultUserNicks(info->proto, node);
+ }
+ }
+ } else if (!strcmp(type, "8")) { // user chat rooms list
+ char *from;
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (strcmp(from, "c")==0) {
+ TlenIqResultUserRooms(info->proto, node);
+ }
+ }
+ }
+}
+
+/*
+ * Web messages
+ */
+static void TlenProcessW(XmlNode *node, ThreadData *info)
+{
+ HANDLE hContact;
+ CCSDATA ccs;
+ PROTORECVEVENT recv;
+ char *f, *e, *s, *body;
+ char *str, *localMessage;
+ int strSize;
+
+ if (!node->name || strcmp(node->name, "w")) return;
+ if ((body=node->text) == NULL) return;
+
+ if ((f=JabberXmlGetAttrValue(node, "f")) != NULL) {
+
+ char webContactName[128];
+ sprintf(webContactName, Translate("%s Web Messages"), info->proto->iface.m_szProtoName);
+ if ((hContact=JabberHContactFromJID(info->proto, webContactName)) == NULL) {
+ hContact = JabberDBCreateContact(info->proto, webContactName, webContactName, TRUE);
+ }
+
+ s = JabberXmlGetAttrValue(node, "s");
+ e = JabberXmlGetAttrValue(node, "e");
+
+ str = NULL;
+ strSize = 0;
+ JabberStringAppend(&str, &strSize, "%s\r\n%s: ", Translate("Web message"), Translate("From"));
+
+ if (f != NULL)
+ JabberStringAppend(&str, &strSize, "%s", f);
+ JabberStringAppend(&str, &strSize, "\r\n%s: ", Translate("E-mail"));
+ if (e != NULL)
+ JabberStringAppend(&str, &strSize, "%s", e);
+ JabberStringAppend(&str, &strSize, "\r\n\r\n%s", body);
+
+ localMessage = JabberTextDecode(str);
+
+ recv.flags = 0;
+ recv.timestamp = (DWORD) time(NULL);
+ recv.szMessage = localMessage;
+ recv.lParam = 0;
+ ccs.hContact = hContact;
+ ccs.wParam = 0;
+ ccs.szProtoService = PSR_MESSAGE;
+ ccs.lParam = (LPARAM) &recv;
+ CallService(MS_PROTO_CHAINRECV, 0, (LPARAM) &ccs);
+
+ mir_free(localMessage);
+ mir_free(str);
+ }
+}
+
+/*
+ * Typing notification, multi-user conference messages and invitations
+ */
+static void TlenProcessM(XmlNode *node, ThreadData *info)
+{
+ HANDLE hContact;
+ CCSDATA ccs;
+ PROTORECVEVENT recv;
+ char *f;//, *from;//username
+ char *tp;//typing start/stop
+ char *p, *n, *r, *s, *str, *localMessage;
+ int i;
+ XmlNode *xNode, *invNode, *bNode, *subjectNode;
+
+ if (!node->name || strcmp(node->name, "m")) return;
+
+ if ((f=JabberXmlGetAttrValue(node, "f")) != NULL) {
+ char *fLogin = JabberLoginFromJID(f);
+ if ((hContact=JabberHContactFromJID(info->proto, fLogin)) != NULL) {
+ if ((tp=JabberXmlGetAttrValue(node, "tp")) != NULL) {
+ JABBER_LIST_ITEM *item = JabberListGetItemPtr(info->proto, LIST_ROSTER, fLogin);
+ if(!strcmp(tp, "t")) { //contact is writing
+ if (item!=NULL ) {
+ item->isTyping = TRUE;
+ CallService(MS_PROTO_CONTACTISTYPING, (WPARAM)hContact, (LPARAM)PROTOTYPE_CONTACTTYPING_INFINITE);
+ }
+ }
+ else if(!strcmp(tp, "u")) {//contact stopped writing
+ if (item!=NULL) {
+ item->isTyping = FALSE;
+ CallService(MS_PROTO_CONTACTISTYPING, (WPARAM)hContact, (LPARAM)PROTOTYPE_CONTACTTYPING_OFF);
+ }
+ }
+ else if(!strcmp(tp, "a")) {//alert was received
+ int bAlert = TRUE;
+ if (info->proto->tlenOptions.alertPolicy == TLEN_ALERTS_IGNORE_ALL) {
+ bAlert = FALSE;
+ } else if (info->proto->tlenOptions.alertPolicy == TLEN_ALERTS_IGNORE_NIR) {
+ bAlert = IsAuthorized(info->proto, fLogin);
+ }
+ if (bAlert) {
+ if (info->proto->tlenOptions.useNudge) {
+ NotifyEventHooks(info->proto->hTlenNudge,(WPARAM) hContact,0);
+ } else {
+ if (info->proto->tlenOptions.logAlerts) {
+ TlenLogMessage(info->proto, hContact, 0, Translate("An alert has been received."));
+ }
+ SkinPlaySound("TlenAlertNotify");
+ }
+ }
+ }
+ }
+ }
+ mir_free(fLogin);
+ if ((p=strchr(f, '@')) != NULL) {
+ if ((p=strchr(p, '/'))!=NULL && p[1]!='\0') { // message from user
+ time_t timestamp;
+ s = JabberXmlGetAttrValue(node, "s");
+ if (s != NULL) {
+ timestamp = TlenTimeToUTC(atol(s));
+ if (timestamp > time(NULL)) {
+ timestamp = time(NULL);
+ }
+ } else {
+ timestamp = time(NULL);
+ }
+ tp=JabberXmlGetAttrValue(node, "tp");
+ bNode = JabberXmlGetChild(node, "b");
+ f = JabberTextDecode(f);
+ if (bNode != NULL && bNode->text != NULL) {
+ if (tp != NULL && !strcmp(tp, "p")) {
+ /* MUC private message */
+ str = JabberResourceFromJID(f);
+ hContact = JabberDBCreateContact(info->proto, f, str, TRUE);
+ DBWriteContactSettingByte(hContact, info->proto->iface.m_szModuleName, "bChat", TRUE);
+ mir_free(str);
+ localMessage = JabberTextDecode(bNode->text);
+ recv.flags = 0;
+ recv.timestamp = (DWORD) timestamp;
+ recv.szMessage = localMessage;
+ recv.lParam = 0;
+ ccs.hContact = hContact;
+ ccs.wParam = 0;
+ ccs.szProtoService = PSR_MESSAGE;
+ ccs.lParam = (LPARAM) &recv;
+ CallService(MS_PROTO_CHAINRECV, 0, (LPARAM) &ccs);
+ mir_free(localMessage);
+ } else {
+ /* MUC message */
+ TlenMUCRecvMessage(info->proto, f, timestamp, bNode);
+ }
+ }
+ mir_free(f);
+ } else { // message from chat room (system)
+ subjectNode = JabberXmlGetChild(node, "subject");
+ if (subjectNode != NULL) {
+ f = JabberTextDecode(f);
+ localMessage = "";
+ if (subjectNode->text!=NULL) {
+ localMessage = subjectNode->text;
+ }
+ localMessage = JabberTextDecode(localMessage);
+ TlenMUCRecvTopic(info->proto, f, localMessage);
+ mir_free(localMessage);
+ mir_free(f);
+ }
+ }
+ }
+ i=1;
+ while ((xNode=JabberXmlGetNthChild(node, "x", i)) != NULL) {
+ invNode=JabberXmlGetChild(xNode, "inv");
+ if (invNode != NULL) {
+ r = JabberTextDecode(f);
+ f = JabberXmlGetAttrValue(invNode, "f");
+ f = JabberTextDecode(f);
+ n = JabberXmlGetAttrValue(invNode, "n");
+ if (n!=NULL && strstr(r, n)!=r) {
+ n = JabberTextDecode(n);
+ } else {
+ n = mir_strdup(Translate("Private conference"));
+ //n = JabberNickFromJID(r);
+ }
+ TlenMUCRecvInvitation(info->proto, r, n, f, "");
+ mir_free(n);
+ mir_free(r);
+ mir_free(f);
+ break;
+ }
+ i++;
+ }
+ }
+}
+
+static void TlenMailPopup(TlenProtocol *proto, char *title, char *emailInfo)
+{
+ POPUPDATAEX ppd;
+ char * lpzContactName;
+ char * lpzText;
+
+ if (!DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "MailPopupEnabled", TRUE)) {
+ return;
+ }
+ lpzContactName = title;
+ lpzText = emailInfo;
+ ZeroMemory(&ppd, sizeof(ppd));
+ ppd.lchContact = NULL;
+ ppd.lchIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_MAIL));
+ strcpy(ppd.lpzContactName, lpzContactName);
+ strcpy(ppd.lpzText, lpzText);
+ ppd.colorBack = DBGetContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupBack", 0);
+ ppd.colorText = DBGetContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupText", 0);
+ ppd.PluginWindowProc = NULL;
+ ppd.PluginData=NULL;
+ if ( ServiceExists( MS_POPUP_ADDPOPUPEX )) {
+ BYTE delayMode;
+ int delay;
+ delayMode = DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "MailPopupDelayMode", 0);
+ delay = 0;
+ if (delayMode==1) {
+ delay = DBGetContactSettingDword(NULL, proto->iface.m_szModuleName, "MailPopupDelay", 4);
+ } else if (delayMode==2) {
+ delay = -1;
+ }
+ ppd.iSeconds = delay;
+ CallService(MS_POPUP_ADDPOPUPEX, (WPARAM)&ppd, 0);
+
+ }
+ else if ( ServiceExists( MS_POPUP_ADDPOPUP )) {
+ CallService(MS_POPUP_ADDPOPUP, (WPARAM)&ppd, 0);
+ }
+}
+/*
+ * Incoming e-mail notification
+ */
+static void TlenProcessN(XmlNode *node, ThreadData *info)
+{
+ char *f, *s;
+ char *str, *popupTitle, *popupText;
+ int strSize;
+
+ if (!node->name || strcmp(node->name, "n")) return;
+
+ s = JabberXmlGetAttrValue(node, "s");
+ f = JabberXmlGetAttrValue(node, "f");
+ if (s != NULL && f!=NULL) {
+ str = NULL;
+ strSize = 0;
+
+ JabberStringAppend(&str, &strSize, Translate("%s mail"), info->proto->iface.m_szProtoName);
+ popupTitle = JabberTextDecode(str);
+ mir_free(str);
+
+ str = NULL;
+ strSize = 0;
+
+ JabberStringAppend(&str, &strSize, "%s: %s\n", Translate("From"), f);
+ JabberStringAppend(&str, &strSize, "%s: %s", Translate("Subject"), s);
+ popupText = JabberTextDecode(str);
+ TlenMailPopup(info->proto, popupTitle, popupText);
+ SkinPlaySound("TlenMailNotify");
+
+ mir_free(popupTitle);
+ mir_free(popupText);
+ mir_free(str);
+ }
+}
+
+/*
+ * Presence is chat rooms
+ */
+static void TlenProcessP(XmlNode *node, ThreadData *info)
+{
+ char jid[512];
+ char *f, *id, *tp, *a, *n, *k;
+ XmlNode *sNode, *xNode, *iNode, *kNode;
+ int status, flags;
+
+ if (!node->name || strcmp(node->name, "p")) return;
+
+ // presence from users in chat room
+ flags = 0;
+ status = ID_STATUS_ONLINE;
+ f = JabberXmlGetAttrValue(node, "f");
+ xNode = JabberXmlGetChild(node, "x");
+ if (xNode != NULL) { // x subtag present (message from chat room) - change user rights only
+ char *temp, *iStr;
+ iNode = JabberXmlGetChild(xNode, "i");
+ if (iNode != NULL) {
+ iStr = JabberXmlGetAttrValue(iNode, "i");
+ temp = mir_alloc(strlen(f)+strlen(iStr)+2);
+ strcpy(temp, f);
+ strcat(temp, "/");
+ strcat(temp, iStr);
+ f = JabberTextDecode(temp);
+ mir_free(temp);
+ node = iNode;
+ status = 0;
+ } else {
+ f = JabberTextDecode(f);
+ }
+ } else {
+ f = JabberTextDecode(f);
+ }
+ a = JabberXmlGetAttrValue(node, "z");
+ if (a!=NULL) {
+ if (atoi(a) &1 ) {
+ flags |= USER_FLAGS_REGISTERED;
+ }
+ }
+ a = JabberXmlGetAttrValue(node, "a");
+ if (a!=NULL) {
+ if (atoi(a) == 2) {
+ flags |= USER_FLAGS_ADMIN;
+ }
+ if (atoi(a) == 1) {
+ flags |= USER_FLAGS_OWNER;
+ }
+ if (atoi(a) == 3) {
+ //flags |= USER_FLAGS_MEMBER;
+ }
+ if (atoi(a) == 5) {
+ flags |= USER_FLAGS_GLOBALOWNER;
+ }
+ }
+ sNode = JabberXmlGetChild(node, "s");
+ if (sNode != NULL) {
+ if (!strcmp(sNode->text, "unavailable")) {
+ status = ID_STATUS_OFFLINE;
+ }
+ }
+ kNode = JabberXmlGetChild(node, "kick");
+ k = NULL;
+ if (kNode != NULL) {
+ k = JabberXmlGetAttrValue(kNode, "r");
+ if (k==NULL) {
+ k = "";
+ }
+ k = JabberTextDecode(k);
+ }
+ tp = JabberXmlGetAttrValue(node, "tp");
+ if (tp!=NULL && !strcmp(tp, "c")) { // new chat room has just been created
+ id = JabberXmlGetAttrValue(node, "id");
+ if (id != NULL) {
+ n = JabberXmlGetAttrValue(node, "n");
+ if (n!=NULL) {
+ n = JabberTextDecode(n);
+ } else {
+ n = mir_strdup(Translate("Private conference"));// JabberNickFromJID(f);
+ }
+ sprintf(jid, "%s/%s", f, info->username);
+// if (!DBGetContactSetting(NULL, iface.m_szModuleName, "LoginName", &dbv)) {
+ // always real username
+// sprintf(jid, "%s/%s", f, dbv.pszVal);
+ TlenMUCCreateWindow(info->proto, f, n, 0, NULL, id);
+ TlenMUCRecvPresence(info->proto, jid, ID_STATUS_ONLINE, flags, k);
+// DBFreeVariant(&dbv);
+// }
+ mir_free(n);
+ }
+ } else {
+ TlenMUCRecvPresence(info->proto, f, status, flags, k); // user presence
+ }
+ if (k!=NULL) {
+ mir_free(k);
+ }
+ mir_free(f);
+}
+/*
+ * Voice chat
+ */
+static void TlenProcessV(XmlNode *node, ThreadData *info)
+{
+ char jid[128];
+ JABBER_LIST_ITEM *item;
+ char *from, *id, *e, *p;
+// if (!node->name || strcmp(node->name, "v")) return;
+
+ if ((from=JabberXmlGetAttrValue(node, "f")) != NULL) {
+ if (strchr(from, '@') == NULL) {
+ _snprintf(jid, sizeof(jid), "%s@%s", from, info->server);
+ } else {
+ _snprintf(jid, sizeof(jid), "%s", from);
+ }
+ if ((e=JabberXmlGetAttrValue(node, "e")) != NULL) {
+ if (!strcmp(e, "1")) {
+ if ((id=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ SkinPlaySound("TlenVoiceNotify");
+ TlenVoiceAccept(info->proto, id, from);
+ }
+ } else if (!strcmp(e, "3")) {
+ // FILE_RECV : e='3' : invalid transfer error
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_VOICE, p)) != NULL) {
+ if (item->ft != NULL) {
+ HANDLE hEvent = item->ft->hFileEvent;
+ item->ft->hFileEvent = NULL;
+ item->ft->state = FT_ERROR;
+ if (item->ft->s != NULL) {
+ Netlib_CloseHandle(item->ft->s);
+ item->ft->s = NULL;
+ if (hEvent != NULL) {
+ SetEvent(hEvent);
+ }
+ } else {
+ TlenP2PFreeFileTransfer(item->ft);
+ }
+ } else {
+ JabberListRemove(info->proto, LIST_VOICE, p);
+ }
+ }
+ }
+ } else if (!strcmp(e, "4")) {
+ // FILE_SEND : e='4' : File sending request was denied by the remote client
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_VOICE, p)) != NULL) {
+ if (!strcmp(item->ft->jid, jid)) {
+ TlenVoiceCancelAll(info->proto);
+ //JabberListRemove(info->proto, LIST_VOICE, p);
+ }
+ }
+ }
+ } else if (!strcmp(e, "5")) {
+ // FILE_SEND : e='5' : Voice request was accepted
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_VOICE, p)) != NULL) {
+ JabberLog(info->proto, "should start voice 1 ? %s ?? %s", jid, item->ft->jid);
+ if (!strcmp(item->ft->jid, jid)) {
+ JabberLog(info->proto, "starting voice 1");
+ TlenVoiceStart(item->ft, 1);
+ }
+ }
+ }
+ } else if (!strcmp(e, "6")) {
+ // FILE_RECV : e='6' : IP and port information to connect to get file
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_VOICE, p)) != NULL) {
+ if ((p=JabberXmlGetAttrValue(node, "a")) != NULL) {
+ item->ft->hostName = mir_strdup(p);
+ if ((p=JabberXmlGetAttrValue(node, "p")) != NULL) {
+ item->ft->wPort = atoi(p);
+ TlenVoiceStart(item->ft, 0);
+ //JabberForkThread((void (__cdecl *)(void*))TlenVoiceReceiveThread, 0, item->ft);
+ }
+ }
+ }
+ }
+ }
+ else if (!strcmp(e, "7")) {
+ // FILE_RECV : e='7' : IP and port information to connect to send file
+ // in case the conection to the given server was not successful
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_VOICE, p)) != NULL) {
+ if ((p=JabberXmlGetAttrValue(node, "a")) != NULL) {
+ if (item->ft->hostName!=NULL) mir_free(item->ft->hostName);
+ item->ft->hostName = mir_strdup(p);
+ if ((p=JabberXmlGetAttrValue(node, "p")) != NULL) {
+ item->ft->wPort = atoi(p);
+ item->ft->state = FT_SWITCH;
+ SetEvent(item->ft->hFileEvent);
+ }
+ }
+ }
+ }
+ }
+ else if (!strcmp(e, "8")) {
+ // FILE_RECV : e='8' : transfer error
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_VOICE, p)) != NULL) {
+ item->ft->state = FT_ERROR;
+ SetEvent(item->ft->hFileEvent);
+ }
+ }
+ }
+
+ }
+ }
+}
+
+static void __cdecl JabberKeepAliveThread(void *ptr)
+{
+ NETLIBSELECT nls = {0};
+
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ nls.cbSize = sizeof(NETLIBSELECT);
+ nls.dwTimeout = 60000; // 60000 millisecond (1 minute)
+ nls.hExceptConns[0] = proto->threadData->s;
+ for (;;) {
+ if (CallService(MS_NETLIB_SELECT, 0, (LPARAM) &nls) != 0)
+ break;
+ if (proto->tlenOptions.sendKeepAlive)
+ JabberSend(proto, " \t ");
+ }
+ JabberLog(proto, "Exiting KeepAliveThread");
+}
+
diff --git a/protocols/Tlen/jabber_util.c b/protocols/Tlen/jabber_util.c
new file mode 100644
index 0000000000..1caa390f10
--- /dev/null
+++ b/protocols/Tlen/jabber_util.c
@@ -0,0 +1,635 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "jabber_list.h"
+#include <ctype.h>
+#include <win2k.h>
+
+HANDLE HookEventObj_Ex(const char *name, TlenProtocol *proto, MIRANDAHOOKOBJ hook) {
+ proto->hookNum ++;
+ proto->hHooks = (HANDLE *) mir_realloc(proto->hHooks, sizeof(HANDLE) * (proto->hookNum));
+ proto->hHooks[proto->hookNum - 1] = HookEventObj(name, hook, proto);
+ return proto->hHooks[proto->hookNum - 1] ;
+}
+
+HANDLE CreateServiceFunction_Ex(const char *name, TlenProtocol *proto, MIRANDASERVICEOBJ service) {
+ proto->serviceNum++;
+ proto->hServices = (HANDLE *) mir_realloc(proto->hServices, sizeof(HANDLE) * (proto->serviceNum));
+ proto->hServices[proto->serviceNum - 1] = CreateServiceFunctionObj(name, service, proto);
+ return proto->hServices[proto->serviceNum - 1] ;
+}
+
+void UnhookEvents_Ex(TlenProtocol *proto) {
+ unsigned int i;
+ for (i=0; i<proto->hookNum; ++i) {
+ if (proto->hHooks[i] != NULL) {
+ UnhookEvent(proto->hHooks[i]);
+ }
+ }
+ mir_free(proto->hHooks);
+ proto->hookNum = 0;
+ proto->hHooks = NULL;
+}
+
+void DestroyServices_Ex(TlenProtocol *proto) {
+ unsigned int i;
+ for (i=0; i<proto->serviceNum; ++i) {
+ if (proto->hServices[i] != NULL) {
+ DestroyServiceFunction(proto->hServices[i]);
+ }
+ }
+ mir_free(proto->hServices);
+ proto->serviceNum = 0;
+ proto->hServices = NULL;
+}
+
+void JabberSerialInit(TlenProtocol *proto)
+{
+ InitializeCriticalSection(&proto->csSerial);
+ proto->serial = 0;
+}
+
+void JabberSerialUninit(TlenProtocol *proto)
+{
+ DeleteCriticalSection(&proto->csSerial);
+}
+
+unsigned int JabberSerialNext(TlenProtocol *proto)
+{
+ unsigned int ret;
+
+ EnterCriticalSection(&proto->csSerial);
+ ret = proto->serial;
+ proto->serial++;
+ LeaveCriticalSection(&proto->csSerial);
+ return ret;
+}
+
+void JabberLog(TlenProtocol *proto, const char *fmt, ...)
+{
+#ifdef ENABLE_LOGGING
+ char *str;
+ va_list vararg;
+ int strsize;
+ char *text;
+ char *p, *q;
+ int extra;
+
+ va_start(vararg, fmt);
+ str = (char *) mir_alloc(strsize=2048);
+ while (_vsnprintf(str, strsize, fmt, vararg) == -1)
+ str = (char *) mir_realloc(str, strsize+=2048);
+ va_end(vararg);
+
+ extra = 0;
+ for (p=str; *p!='\0'; p++)
+ if (*p=='\n' || *p=='\r')
+ extra++;
+ text = (char *) mir_alloc(strlen("TLEN")+2+strlen(str)+2+extra);
+ sprintf(text, "[%s]", "TLEN");
+ for (p=str,q=text+strlen(text); *p!='\0'; p++,q++) {
+ if (*p == '\r') {
+ *q = '\\';
+ *(q+1) = 'r';
+ q++;
+ }
+ else if (*p == '\n') {
+ *q = '\\';
+ *(q+1) = 'n';
+ q++;
+ }
+ else
+ *q = *p;
+ }
+ *q = '\n';
+ *(q+1) = '\0';
+ if (proto->hNetlibUser!=NULL) {
+ CallService(MS_NETLIB_LOG, (WPARAM) proto->hNetlibUser, (LPARAM) text);
+ }
+ //OutputDebugString(text);
+ mir_free(text);
+ mir_free(str);
+#endif
+}
+
+// Caution: DO NOT use JabberSend() to send binary (non-string) data
+int JabberSend(TlenProtocol *proto, const char *fmt, ...)
+{
+ char *str;
+ int size;
+ va_list vararg;
+ int result = 0;
+
+ EnterCriticalSection(&proto->csSend);
+
+ va_start(vararg,fmt);
+ size = 512;
+ str = (char *) mir_alloc(size);
+ while (_vsnprintf(str, size, fmt, vararg) == -1) {
+ size += 512;
+ str = (char *) mir_realloc(str, size);
+ }
+ va_end(vararg);
+
+ JabberLog(proto, "SEND:%s", str);
+ size = (int)strlen(str);
+ if (proto->threadData != NULL) {
+ if (proto->threadData->useAES) {
+ result = JabberWsSendAES(proto, str, size, &proto->threadData->aes_out_context, proto->threadData->aes_out_iv);
+ } else {
+ result = JabberWsSend(proto, proto->threadData->s, str, size);
+ }
+ }
+ LeaveCriticalSection(&proto->csSend);
+
+ mir_free(str);
+ return result;
+}
+
+
+char *JabberResourceFromJID(const char *jid)
+{
+ char *p;
+ char *nick;
+
+ p=strchr(jid, '/');
+ if (p != NULL && p[1]!='\0') {
+ p++;
+ if ((nick=(char *) mir_alloc(1+strlen(jid)-(p-jid))) != NULL) {
+ strncpy(nick, p, strlen(jid)-(p-jid));
+ nick[strlen(jid)-(p-jid)] = '\0';
+ }
+ }
+ else {
+ nick = mir_strdup(jid);
+ }
+
+ return nick;
+}
+
+char *JabberNickFromJID(const char *jid)
+{
+ char *p;
+ char *nick;
+
+ if ((p=strchr(jid, '@')) == NULL)
+ p = strchr(jid, '/');
+ if (p != NULL) {
+ if ((nick=(char *) mir_alloc((p-jid)+1)) != NULL) {
+ strncpy(nick, jid, p-jid);
+ nick[p-jid] = '\0';
+ }
+ }
+ else {
+ nick = mir_strdup(jid);
+ }
+
+ return nick;
+}
+
+char *JabberLoginFromJID(const char *jid)
+{
+ char *p;
+ char *nick;
+
+ p = strchr(jid, '/');
+ if (p != NULL) {
+ if ((nick=(char *) mir_alloc((p-jid)+1)) != NULL) {
+ strncpy(nick, jid, p-jid);
+ nick[p-jid] = '\0';
+ }
+ }
+ else {
+ nick = mir_strdup(jid);
+ }
+ return nick;
+}
+
+char *JabberLocalNickFromJID(const char *jid)
+{
+ char *p;
+ char *localNick;
+
+ p = JabberNickFromJID(jid);
+ localNick = JabberTextDecode(p);
+ mir_free(p);
+ return localNick;
+}
+
+char *JabberSha1(char *str)
+{
+ mir_sha1_ctx sha;
+ DWORD digest[5];
+ char* result;
+
+ if ( str == NULL )
+ return NULL;
+
+ mir_sha1_init( &sha );
+ mir_sha1_append( &sha, (mir_sha1_byte_t* )str, (int)strlen( str ));
+ mir_sha1_finish( &sha, (mir_sha1_byte_t* )digest );
+ if ((result=(char *)mir_alloc(41)) == NULL)
+ return NULL;
+ sprintf(result, "%08x%08x%08x%08x%08x", (int)htonl(digest[0]), (int)htonl(digest[1]), (int)htonl(digest[2]), (int)htonl(digest[3]), (int)htonl(digest[4]));
+ return result;
+}
+
+char *TlenSha1(char *str, int len)
+{
+ mir_sha1_ctx sha;
+ mir_sha1_byte_t digest[20];
+ char* result;
+ int i;
+
+ if ( str == NULL )
+ return NULL;
+
+ mir_sha1_init( &sha );
+ mir_sha1_append( &sha, (mir_sha1_byte_t* )str, len);
+ mir_sha1_finish( &sha, digest );
+ if (( result=( char* )mir_alloc( 20 )) == NULL )
+ return NULL;
+ for (i=0; i<20; i++)
+ result[i]=digest[4*(i>>2)+(3-(i&0x3))];
+ return result;
+}
+
+char *TlenPasswordHash(const char *str)
+{
+ int magic1 = 0x50305735, magic2 = 0x12345671, sum = 7;
+ char *p, *res;
+
+ if (str == NULL) return NULL;
+ for (p=(char *)str; *p!='\0'; p++) {
+ if (*p!=' ' && *p!='\t') {
+ magic1 ^= (((magic1 & 0x3f) + sum) * ((char) *p)) + (magic1 << 8);
+ magic2 += (magic2 << 8) ^ magic1;
+ sum += ((char) *p);
+ }
+ }
+ magic1 &= 0x7fffffff;
+ magic2 &= 0x7fffffff;
+ res = (char *) mir_alloc(17);
+ sprintf(res, "%08x%08x", magic1, magic2);
+ return res;
+}
+
+char *TlenUrlEncode(const char *str)
+{
+ char *p, *q, *res;
+ unsigned char c;
+
+ if (str == NULL) return NULL;
+ res = (char *) mir_alloc(3*strlen(str) + 1);
+ for (p=(char *)str,q=res; *p!='\0'; p++,q++) {
+ if (*p == ' ') {
+ *q = '+';
+ }
+ else if (*p<0x20 || *p>=0x7f || strchr("%&+:'<>\"", *p)!=NULL) {
+ // Convert first from CP1252 to ISO8859-2
+ switch ((unsigned char) *p) {
+ case 0xa5: c = (unsigned char) 0xa1; break;
+ case 0x8c: c = (unsigned char) 0xa6; break;
+ case 0x8f: c = (unsigned char) 0xac; break;
+ case 0xb9: c = (unsigned char) 0xb1; break;
+ case 0x9c: c = (unsigned char) 0xb6; break;
+ case 0x9f: c = (unsigned char) 0xbc; break;
+ default: c = (unsigned char) *p; break;
+ }
+ sprintf(q, "%%%02X", c);
+ q += 2;
+ }
+ else {
+ *q = *p;
+ }
+ }
+ *q = '\0';
+ return res;
+}
+
+void TlenUrlDecode(char *str)
+{
+ char *p, *q;
+ unsigned int code;
+
+ if (str == NULL) return;
+ for (p=q=str; *p!='\0'; p++,q++) {
+ if (*p == '+') {
+ *q = ' ';
+ }
+ else if (*p=='%' && *(p+1)!='\0' && isxdigit(*(p+1)) && *(p+2)!='\0' && isxdigit(*(p+2))) {
+ sscanf(p+1, "%2x", &code);
+ *q = (char) code;
+ // Convert from ISO8859-2 to CP1252
+ switch ((unsigned char) *q) {
+ case 0xa1: *q = (char) 0xa5; break;
+ case 0xa6: *q = (char) 0x8c; break;
+ case 0xac: *q = (char) 0x8f; break;
+ case 0xb1: *q = (char) 0xb9; break;
+ case 0xb6: *q = (char) 0x9c; break;
+ case 0xbc: *q = (char) 0x9f; break;
+ }
+ p += 2;
+ }
+ else {
+ *q = *p;
+ }
+ }
+ *q = '\0';
+}
+
+char * TlenGroupDecode(const char *str)
+{
+ char *p, *q;
+ if (str == NULL) return NULL;
+ p = q = JabberTextDecode(str);
+ for (; *p!='\0'; p++) {
+ if (*p == '/') {
+ *p = '\\';
+ }
+ }
+ return q;
+}
+
+char * TlenGroupEncode(const char *str)
+{
+ char *p, *q;
+ if (str == NULL) return NULL;
+ p = q = mir_strdup(str);
+ for (; *p!='\0'; p++) {
+ if (*p == '\\') {
+ *p = '/';
+ }
+ }
+ p = JabberTextEncode(q);
+ mir_free(q);
+ return p;
+}
+
+char *JabberTextEncode(const char *str)
+{
+ char *s1;
+
+ if (str == NULL) return NULL;
+ if ((s1=TlenUrlEncode(str)) == NULL)
+ return NULL;
+ return s1;
+}
+
+char *JabberTextDecode(const char *str)
+{
+ char *s1;
+
+ if (str == NULL) return NULL;
+ s1 = mir_strdup(str);
+ TlenUrlDecode(s1);
+ return s1;
+}
+
+static char b64table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+char *JabberBase64Encode(const char *buffer, int bufferLen)
+{
+ int n;
+ unsigned char igroup[3];
+ char *p, *peob;
+ char *res, *r;
+
+ if (buffer==NULL || bufferLen<=0) return NULL;
+ if ((res=(char *) mir_alloc((((bufferLen+2)/3)*4) + 1)) == NULL) return NULL;
+
+ for (p=(char*)buffer,peob=p+bufferLen,r=res; p<peob;) {
+ igroup[0] = igroup[1] = igroup[2] = 0;
+ for (n=0; n<3; n++) {
+ if (p >= peob) break;
+ igroup[n] = (unsigned char) *p;
+ p++;
+ }
+ if (n > 0) {
+ r[0] = b64table[ igroup[0]>>2 ];
+ r[1] = b64table[ ((igroup[0]&3)<<4) | (igroup[1]>>4) ];
+ r[2] = b64table[ ((igroup[1]&0xf)<<2) | (igroup[2]>>6) ];
+ r[3] = b64table[ igroup[2]&0x3f ];
+ if (n < 3) {
+ r[3] = '=';
+ if (n < 2)
+ r[2] = '=';
+ }
+ r += 4;
+ }
+ }
+ *r = '\0';
+
+ return res;
+}
+
+static unsigned char b64rtable[256];
+
+char *JabberBase64Decode(const char *str, int *resultLen)
+{
+ char *res;
+ unsigned char *p, *r, igroup[4], a[4];
+ int n, num, count;
+
+ if (str==NULL || resultLen==NULL) return NULL;
+ if ((res=(char *) mir_alloc(((strlen(str)+3)/4)*3)) == NULL) return NULL;
+
+ for (n=0; n<256; n++)
+ b64rtable[n] = (unsigned char) 0x80;
+ for (n=0; n<26; n++)
+ b64rtable['A'+n] = n;
+ for (n=0; n<26; n++)
+ b64rtable['a'+n] = n + 26;
+ for (n=0; n<10; n++)
+ b64rtable['0'+n] = n + 52;
+ b64rtable['+'] = 62;
+ b64rtable['/'] = 63;
+ b64rtable['='] = 0;
+ count = 0;
+ for (p=(unsigned char *)str,r=(unsigned char *)res; *p!='\0';) {
+ for (n=0; n<4; n++) {
+ if ( *p == '\r' || *p == '\n' ) {
+ n--; p++;
+ continue;
+ }
+
+ if ( *p=='\0' ) {
+ if ( n == 0 )
+ goto LBL_Exit;
+ mir_free( res );
+ return NULL;
+ }
+
+ if ( b64rtable[*p]==0x80 ) {
+ mir_free( res );
+ return NULL;
+ }
+
+ a[n] = *p;
+ igroup[n] = b64rtable[*p];
+ p++;
+ }
+ r[0] = igroup[0]<<2 | igroup[1]>>4;
+ r[1] = igroup[1]<<4 | igroup[2]>>2;
+ r[2] = igroup[2]<<6 | igroup[3];
+ r += 3;
+ num = ( a[2]=='='?1:( a[3]=='='?2:3 ));
+ count += num;
+ if ( num < 3 ) break;
+ }
+LBL_Exit:
+ *resultLen = count;
+ return res;
+}
+
+/*
+ * Apply Polish Daylight Saving Time rules to get "DST-unbiased" timestamp
+ */
+
+time_t TlenTimeToUTC(time_t time) {
+ struct tm *timestamp;
+ timestamp = gmtime(&time);
+ if ( (timestamp->tm_mon > 2 && timestamp->tm_mon < 9) ||
+ (timestamp->tm_mon == 2 && timestamp->tm_mday - timestamp->tm_wday >= 25) ||
+ (timestamp->tm_mon == 9 && timestamp->tm_mday - timestamp->tm_wday < 25)) {
+ //time -= 3600;
+ } else {
+ //time += 3600;
+ }
+ return time;
+}
+
+time_t JabberIsoToUnixTime(char *stamp)
+{
+ struct tm timestamp;
+ char date[9];
+ char *p;
+ int i, y;
+ time_t t;
+
+ if (stamp == NULL) return (time_t) 0;
+
+ p = stamp;
+
+ // Get the date part
+ for (i=0; *p!='\0' && i<8 && isdigit(*p); p++,i++)
+ date[i] = *p;
+
+ // Parse year
+ if (i == 6) {
+ // 2-digit year (1970-2069)
+ y = (date[0]-'0')*10 + (date[1]-'0');
+ if (y < 70) y += 100;
+ }
+ else if (i == 8) {
+ // 4-digit year
+ y = (date[0]-'0')*1000 + (date[1]-'0')*100 + (date[2]-'0')*10 + date[3]-'0';
+ y -= 1900;
+ }
+ else
+ return (time_t) 0;
+ timestamp.tm_year = y;
+ // Parse month
+ timestamp.tm_mon = (date[i-4]-'0')*10 + date[i-3]-'0' - 1;
+ // Parse date
+ timestamp.tm_mday = (date[i-2]-'0')*10 + date[i-1]-'0';
+
+ // Skip any date/time delimiter
+ for (; *p!='\0' && !isdigit(*p); p++);
+
+ // Parse time
+ if (sscanf(p, "%d:%d:%d", &(timestamp.tm_hour), &(timestamp.tm_min), &(timestamp.tm_sec)) != 3)
+ return (time_t) 0;
+
+ timestamp.tm_isdst = 0; // DST is already present in _timezone below
+ _tzset();
+ t = mktime(&timestamp);
+ t -= _timezone;
+ t = TlenTimeToUTC(t);
+
+ if (t >= 0)
+ return t;
+ else
+ return (time_t) 0;
+}
+
+void JabberStringAppend(char **str, int *sizeAlloced, const char *fmt, ...)
+{
+ va_list vararg;
+ char *p;
+ int size, len;
+
+ if (str == NULL) return;
+
+ if (*str==NULL || *sizeAlloced<=0) {
+ *sizeAlloced = size = 2048;
+ *str = (char *) mir_alloc(size);
+ len = 0;
+ }
+ else {
+ len = (int)strlen(*str);
+ size = *sizeAlloced - (int)strlen(*str);
+ }
+
+ p = *str + len;
+ va_start(vararg, fmt);
+ while (_vsnprintf(p, size, fmt, vararg) == -1) {
+ size += 2048;
+ (*sizeAlloced) += 2048;
+ *str = (char *) mir_realloc(*str, *sizeAlloced);
+ p = *str + len;
+ }
+ va_end(vararg);
+}
+
+int JabberGetPictureType( const char* buf )
+{
+ if ( buf != NULL ) {
+ if ( memcmp( buf, "GIF89", 5 ) == 0 ) return PA_FORMAT_GIF;
+ if ( memcmp( buf, "\x89PNG", 4 ) == 0 ) return PA_FORMAT_PNG;
+ if ( memcmp( buf, "BM", 2 ) == 0 ) return PA_FORMAT_BMP;
+ if ( memcmp( buf, "\xFF\xD8", 2 ) == 0 ) return PA_FORMAT_JPEG;
+ }
+ return PA_FORMAT_UNKNOWN;
+}
+
+BOOL IsAuthorized(TlenProtocol *proto, const char *jid)
+{
+ JABBER_LIST_ITEM *item = JabberListGetItemPtr(proto, LIST_ROSTER, jid);
+ if (item != NULL) {
+ return item->subscription == SUB_BOTH || item->subscription == SUB_FROM;
+ }
+ return FALSE;
+}
+
+
+void TlenLogMessage(TlenProtocol *proto, HANDLE hContact, DWORD flags, const char *message)
+{
+ int size = (int)strlen(message) + 2;
+ char *localMessage = (char *)mir_alloc(size);
+ strcpy(localMessage, message);
+ localMessage[size - 1] = '\0';
+ JabberDBAddEvent(proto, hContact, EVENTTYPE_MESSAGE, flags, (PBYTE)message, (DWORD)size);
+ mir_free(localMessage);
+}
diff --git a/protocols/Tlen/jabber_ws.c b/protocols/Tlen/jabber_ws.c
new file mode 100644
index 0000000000..49599fa0e3
--- /dev/null
+++ b/protocols/Tlen/jabber_ws.c
@@ -0,0 +1,159 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+
+BOOL JabberWsInit(TlenProtocol *proto)
+{
+ NETLIBUSER nlu = {0};
+ NETLIBUSERSETTINGS nlus = {0};
+ TCHAR name[128];
+
+
+ nlu.cbSize = sizeof(nlu);
+ nlu.flags = NUF_OUTGOING | NUF_INCOMING | NUF_HTTPCONNS | NUF_TCHAR; // | NUF_HTTPGATEWAY;
+ mir_sntprintf( name, SIZEOF(name), TranslateT("%s connection"), proto->iface.m_tszUserName);
+ nlu.ptszDescriptiveName = name;
+ nlu.szSettingsModule = proto->iface.m_szModuleName;
+ proto->hNetlibUser = (HANDLE) CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM) &nlu);
+
+ nlu.flags = NUF_OUTGOING | NUF_INCOMING | NUF_NOOPTIONS | NUF_TCHAR;
+ mir_sntprintf( name, SIZEOF(name), TranslateT("%s SOCKS connection"), proto->iface.m_tszUserName);
+ nlu.ptszDescriptiveName = name;
+ proto->hFileNetlibUser = (HANDLE) CallService(MS_NETLIB_REGISTERUSER, 0, (LPARAM) &nlu);
+ nlus.cbSize = sizeof(nlus);
+ nlus.useProxy = 0;
+ CallService(MS_NETLIB_SETUSERSETTINGS, (WPARAM) proto->hFileNetlibUser, (LPARAM) &nlus);
+
+ return (proto->hNetlibUser!=NULL)?TRUE:FALSE;
+}
+
+void JabberWsUninit(TlenProtocol *proto)
+{
+ if (proto->hNetlibUser!=NULL) Netlib_CloseHandle(proto->hNetlibUser);
+ if (proto->hFileNetlibUser!=NULL) Netlib_CloseHandle(proto->hFileNetlibUser);
+ proto->hNetlibUser = NULL;
+ proto->hFileNetlibUser = NULL;
+}
+
+JABBER_SOCKET JabberWsConnect(TlenProtocol *proto, char *host, WORD port)
+{
+ NETLIBOPENCONNECTION nloc = {0};
+
+ nloc.cbSize = sizeof(NETLIBOPENCONNECTION); //NETLIBOPENCONNECTION_V1_SIZE;
+ nloc.szHost = host;
+ nloc.wPort = port;
+ nloc.flags = 0;
+ nloc.timeout = 6;
+ return (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) proto->hNetlibUser, (LPARAM) &nloc);
+}
+
+int JabberWsSend(TlenProtocol *proto, JABBER_SOCKET s, char *data, int datalen)
+{
+ int len;
+ if ((len=Netlib_Send(s, data, datalen, /*MSG_NODUMP|*/MSG_DUMPASTEXT))==SOCKET_ERROR || len!=datalen) {
+ JabberLog(proto, "Netlib_Send() failed, error=%d", WSAGetLastError());
+ return FALSE;
+ }
+ return TRUE;
+}
+
+int JabberWsRecv(TlenProtocol *proto, JABBER_SOCKET s, char *data, long datalen)
+{
+ int ret;
+ ret = Netlib_Recv(s, data, datalen, /*MSG_NODUMP|*/MSG_DUMPASTEXT);
+ if(ret == SOCKET_ERROR) {
+ JabberLog(proto, "Netlib_Recv() failed, error=%d", WSAGetLastError());
+ return 0;
+ }
+ if(ret == 0) {
+ JabberLog(proto, "Connection closed gracefully");
+ return 0;
+ }
+ return ret;
+}
+
+
+int JabberWsSendAES(TlenProtocol *proto, char *data, int datalen, aes_context *aes_ctx, unsigned char *aes_iv)
+{
+ int len, sendlen;
+ unsigned char aes_input[16];
+ unsigned char aes_output[256];
+ if (proto->threadData == NULL) {
+ return FALSE;
+ }
+ while (datalen > 0) {
+ len = 0;
+ while (datalen > 0 && len < 256) {
+ int pad = datalen < 16 ? 16 - datalen : 0;
+ memcpy(aes_input, data, datalen < 16 ? datalen : 16);
+ memset(aes_input + 16 - pad, ' ', pad);
+ aes_crypt_cbc(aes_ctx, AES_ENCRYPT, 16, aes_iv, aes_input, aes_output + len);
+ datalen -= 16;
+ data += 16;
+ len += 16;
+ }
+ if (len > 0) {
+ JabberLog(proto, "Sending %d bytes", len);
+ if ((sendlen=Netlib_Send(proto->threadData->s, (char *)aes_output, len, MSG_NODUMP))==SOCKET_ERROR || len!=sendlen) {
+ JabberLog(proto, "Netlib_Send() failed, error=%d", WSAGetLastError());
+ return FALSE;
+ }
+ }
+ }
+ return TRUE;
+}
+
+int JabberWsRecvAES(TlenProtocol *proto, char *data, long datalen, aes_context *aes_ctx, unsigned char *aes_iv)
+{
+ int ret, len = 0, maxlen = datalen;
+ unsigned char aes_input[16];
+ unsigned char *aes_output = (unsigned char *)data;
+ if (proto->threadData == NULL) {
+ return 0;
+ }
+ for (maxlen = maxlen & ~0xF; maxlen != 0; maxlen = maxlen & 0xF) {
+ ret = Netlib_Recv(proto->threadData->s, data, maxlen, MSG_NODUMP);
+ if(ret == SOCKET_ERROR) {
+ JabberLog(proto, "Netlib_Recv() failed, error=%d", WSAGetLastError());
+ return 0;
+ }
+ if(ret == 0) {
+ JabberLog(proto, "Connection closed gracefully");
+ return 0;
+ }
+ data += ret;
+ len += ret;
+ maxlen -= ret;
+ }
+
+ ret = len;
+ while (len > 15) {
+ memcpy(aes_input, aes_output, 16);
+ aes_crypt_cbc(aes_ctx, AES_DECRYPT, 16, aes_iv, aes_input, aes_output);
+ aes_output += 16;
+ len -= 16;
+ }
+ return ret;
+}
+
diff --git a/protocols/Tlen/jabber_xml.c b/protocols/Tlen/jabber_xml.c
new file mode 100644
index 0000000000..6925e60eb1
--- /dev/null
+++ b/protocols/Tlen/jabber_xml.c
@@ -0,0 +1,568 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include <ctype.h>
+
+static BOOL JabberXmlProcessElem(XmlState *xmlState, XmlElemType elemType, char *elemText, char *elemAttr);
+static void JabberXmlRemoveChild(XmlNode *node, XmlNode *child);
+
+void JabberXmlInitState(XmlState *xmlState)
+{
+ if (xmlState == NULL) return;
+ xmlState->root.name = NULL;
+ xmlState->root.depth = 0;
+ xmlState->root.numAttr = 0;
+ xmlState->root.maxNumAttr = 0;
+ xmlState->root.attr = NULL;
+ xmlState->root.numChild = 0;
+ xmlState->root.maxNumChild = 0;
+ xmlState->root.child = NULL;
+ xmlState->root.text = NULL;
+ xmlState->root.state = NODE_OPEN;
+ xmlState->callback1_open = NULL;
+ xmlState->callback1_close = NULL;
+ xmlState->callback2_open = NULL;
+ xmlState->callback2_close = NULL;
+ xmlState->userdata1_open = NULL;
+ xmlState->userdata1_close = NULL;
+ xmlState->userdata2_open = NULL;
+ xmlState->userdata2_close = NULL;
+}
+
+void JabberXmlDestroyState(XmlState *xmlState)
+{
+ int i;
+ XmlNode *node;
+
+ if (xmlState == NULL) return;
+ // Note: cannot use JabberXmlFreeNode() to free xmlState->root
+ // because it will do mir_free(xmlState->root) which is not freeable.
+ node = &(xmlState->root);
+ // Free all children first
+ for (i=0; i<node->numChild; i++)
+ JabberXmlFreeNode(node->child[i]);
+ if (node->child) mir_free(node->child);
+ // Free all attributes
+ for (i=0; i<node->numAttr; i++) {
+ if (node->attr[i]->name) mir_free(node->attr[i]->name);
+ if (node->attr[i]->value) mir_free(node->attr[i]->value);
+ mir_free(node->attr[i]);
+ }
+ if (node->attr) mir_free(node->attr);
+ // Free string field
+ if (node->text) mir_free(node->text);
+ if (node->name) mir_free(node->name);
+}
+
+BOOL JabberXmlSetCallback(XmlState *xmlState, int depth, XmlElemType type, void (*callback)(), void *userdata)
+{
+ if (depth==1 && type==ELEM_OPEN) {
+ xmlState->callback1_open = callback;
+ xmlState->userdata1_open = userdata;
+ }
+ else if (depth==1 && type==ELEM_CLOSE) {
+ xmlState->callback1_close = callback;
+ xmlState->userdata1_close = userdata;
+ }
+ else if (depth==2 && type==ELEM_OPEN) {
+ xmlState->callback2_open = callback;
+ xmlState->userdata2_open = userdata;
+ }
+ else if (depth==2 && type==ELEM_CLOSE) {
+ xmlState->callback2_close = callback;
+ xmlState->userdata2_close = userdata;
+ }
+ else
+ return FALSE;
+
+ return TRUE;
+}
+
+#define TAG_MAX_LEN 50
+#define ATTR_MAX_LEN 1024
+int JabberXmlParse(XmlState *xmlState, char *buffer, int datalen)
+{
+ char *p, *q, *r, *eob;
+ char *str;
+ int num;
+ char tag[TAG_MAX_LEN];
+ char attr[ATTR_MAX_LEN];
+ XmlElemType elemType = 0;
+
+ eob = buffer + datalen;
+ num = 0;
+ // Skip leading whitespaces
+ for (p=buffer; p<eob && isspace(*p); p++,num++);
+ while (num < datalen) {
+ if (*p == '<') { // found starting bracket
+ for (q=p+1; q<eob && *q!='>'; q++);
+ if (q < eob) { // found closing bracket
+ for (r=p+1; *r!='>' && *r!=' ' && *r!='\t'; r++);
+ if (r-(p+1) > TAG_MAX_LEN) {
+// JabberLog("TAG_MAX_LEN too small, ignore current tag");
+ }
+ else {
+ if (*(p+1) == '/') { // closing tag
+ strncpy(tag, p+2, r-(p+2));
+ tag[r-(p+2)] = '\0';
+ elemType = ELEM_CLOSE;
+ }
+ else {
+ if (*(r-1) == '/') { // single open/close tag
+ strncpy(tag, p+1, r-(p+1)-1);
+ tag[r-(p+1)-1] = '\0';
+ elemType = ELEM_OPENCLOSE;
+ }
+ else {
+ strncpy(tag, p+1, r-(p+1));
+ tag[r-(p+1)] = '\0';
+ elemType = ELEM_OPEN;
+ }
+ }
+ for (;r<q && (*r==' ' || *r=='\t'); r++);
+ if (q-r > ATTR_MAX_LEN) {
+// JabberLog("ATTR_MAX_LEN too small, ignore current tag");
+ }
+ else {
+ strncpy(attr, r, q-r);
+ if ((q-r)>0 && attr[q-r-1]=='/') {
+ attr[q-r-1] = '\0';
+ elemType = ELEM_OPENCLOSE;
+ }
+ else
+ attr[q-r] = '\0';
+ JabberXmlProcessElem(xmlState, elemType, tag, attr);
+ }
+ }
+ num += (q-p+1);
+ p = q + 1;
+ if (elemType==ELEM_CLOSE || elemType==ELEM_OPENCLOSE) {
+ // Skip whitespaces after end tags
+ for (; p<eob && isspace(*p); p++,num++);
+ }
+ }
+ else
+ break;
+ }
+ else { // found inner text
+ for (q=p+1; q<eob && *q!='<'; q++);
+ if (q < eob) { // found starting bracket of the next element
+ str = (char *) mir_alloc(q-p+1);
+ strncpy(str, p, q-p);
+ str[q-p] = '\0';
+ JabberXmlProcessElem(xmlState, ELEM_TEXT, str, NULL);
+ mir_free(str);
+ num += (q-p);
+ p = q;
+ }
+ else
+ break;
+ }
+ }
+
+ return num;
+}
+
+static void JabberXmlParseAttr(XmlNode *node, char *text)
+{
+ char *kstart, *vstart;
+ int klen, vlen;
+ char *p;
+ XmlAttr *a;
+
+ if (node==NULL || text==NULL || strlen(text)<=0)
+ return;
+
+ for (p=text;;) {
+
+ // Skip leading whitespaces
+ for (;*p!='\0' && (*p==' ' || *p=='\t'); p++);
+ if (*p == '\0')
+ break;
+
+ // Fetch key
+ kstart = p;
+ for (;*p!='\0' && *p!='=' && *p!=' ' && *p!='\t'; p++);
+ klen = p-kstart;
+
+ if (node->numAttr >= node->maxNumAttr) {
+ node->maxNumAttr = node->numAttr + 20;
+ node->attr = (XmlAttr **) mir_realloc(node->attr, node->maxNumAttr*sizeof(XmlAttr *));
+ }
+ a = node->attr[node->numAttr] = (XmlAttr *) mir_alloc(sizeof(XmlAttr));
+ node->numAttr++;
+
+ // Skip possible whitespaces between key and '='
+ for (;*p!='\0' && (*p==' ' || *p=='\t'); p++);
+
+ if (*p == '\0') {
+ a->name = (char *) mir_alloc(klen+1);
+ strncpy(a->name, kstart, klen);
+ a->name[klen] = '\0';
+ a->value = mir_strdup("");
+ break;
+ }
+
+ if (*p != '=') {
+ a->name = (char *) mir_alloc(klen+1);
+ strncpy(a->name, kstart, klen);
+ a->name[klen] = '\0';
+ a->value = mir_strdup("");
+ continue;
+ }
+
+ // Found '='
+ p++;
+
+ // Skip possible whitespaces between '=' and value
+ for (;*p!='\0' && (*p==' ' || *p=='\t'); p++);
+
+ if (*p == '\0') {
+ a->name = (char *) mir_alloc(klen+1);
+ strncpy(a->name, kstart, klen);
+ a->name[klen] = '\0';
+ a->value = mir_strdup("");
+ break;
+ }
+
+ // Fetch value
+ if (*p=='\'' || *p=='"') {
+ p++;
+ vstart = p;
+ for (;*p!='\0' && *p!=*(vstart-1); p++);
+ vlen = p-vstart;
+ if (*p != '\0') p++;
+ }
+ else {
+ vstart = p;
+ for (;*p!='\0' && *p!=' ' && *p!='\t'; p++);
+ vlen = p-vstart;
+ }
+
+ a->name = (char *) mir_alloc(klen+1);
+ strncpy(a->name, kstart, klen);
+ a->name[klen] = '\0';
+ a->value = (char *) mir_alloc(vlen+1);
+ strncpy(a->value, vstart, vlen);
+ a->value[vlen] = '\0';
+ }
+}
+
+static BOOL JabberXmlProcessElem(XmlState *xmlState, XmlElemType elemType, char *elemText, char *elemAttr)
+{
+ XmlNode *node, *parentNode, *n;
+ //BOOL activateCallback = FALSE;
+ char *text, *attr;
+
+ if (elemText == NULL) return FALSE;
+
+ if (elemType==ELEM_OPEN && !strcmp(elemText, "?xml")) {
+// JabberLog("XML: skip <?xml> tag");
+ return TRUE;
+ }
+
+ // Find active node
+ node = &(xmlState->root);
+ parentNode = NULL;
+ while (node->numChild>0 && node->child[node->numChild-1]->state==NODE_OPEN) {
+ parentNode = node;
+ node = node->child[node->numChild-1];
+ }
+
+ if (node->state != NODE_OPEN) return FALSE;
+
+ text = mir_strdup(elemText);
+
+ if (elemAttr)
+ attr = mir_strdup(elemAttr);
+ else
+ attr = NULL;
+
+ switch (elemType) {
+ case ELEM_OPEN:
+ if (node->numChild >= node->maxNumChild) {
+ node->maxNumChild = node->numChild + 20;
+ node->child = (XmlNode **) mir_realloc(node->child, node->maxNumChild*sizeof(XmlNode *));
+ }
+ n = node->child[node->numChild] = (XmlNode *) mir_alloc(sizeof(XmlNode));
+ node->numChild++;
+ n->name = text;
+ n->depth = node->depth + 1;
+ n->state = NODE_OPEN;
+ n->numChild = n->maxNumChild = 0;
+ n->child = NULL;
+ n->numAttr = n->maxNumAttr = 0;
+ n->attr = NULL;
+ JabberXmlParseAttr(n, attr);
+ n->text = NULL;
+ if (n->depth==1 && xmlState->callback1_open!=NULL)
+ (*(xmlState->callback1_open))(n, xmlState->userdata1_open);
+ if (n->depth==2 && xmlState->callback2_open!=NULL)
+ (*xmlState->callback2_open)(n, xmlState->userdata2_open);
+ break;
+ case ELEM_OPENCLOSE:
+ if (node->numChild >= node->maxNumChild) {
+ node->maxNumChild = node->numChild + 20;
+ node->child = (XmlNode **) mir_realloc(node->child, node->maxNumChild*sizeof(XmlNode *));
+ }
+ n = node->child[node->numChild] = (XmlNode *) mir_alloc(sizeof(XmlNode));
+ node->numChild++;
+ n->name = text;
+ n->depth = node->depth + 1;
+ n->state = NODE_CLOSE;
+ n->numChild = n->maxNumAttr = 0;
+ n->child = NULL;
+ n->numAttr = n->maxNumAttr = 0;
+ n->attr = NULL;
+ JabberXmlParseAttr(n, attr);
+ n->text = NULL;
+ if (n->depth==1 && xmlState->callback1_close!=NULL) {
+ (*(xmlState->callback1_close))(n, xmlState->userdata1_close);
+ JabberXmlRemoveChild(node, n);
+ }
+ if (n->depth==2 && xmlState->callback2_close!=NULL) {
+ (*xmlState->callback2_close)(n, xmlState->userdata2_close);
+ JabberXmlRemoveChild(node, n);
+ }
+ break;
+ case ELEM_CLOSE:
+ if (node->name!=NULL && !strcmp(node->name, text)) {
+ node->state = NODE_CLOSE;
+ if (node->depth==1 && xmlState->callback1_close!=NULL) {
+ (*(xmlState->callback1_close))(node, xmlState->userdata1_close);
+ JabberXmlRemoveChild(parentNode, node);
+ }
+ if (node->depth==2 && xmlState->callback2_close!=NULL) {
+ (*xmlState->callback2_close)(node, xmlState->userdata2_close);
+ JabberXmlRemoveChild(parentNode, node);
+ }
+ mir_free(text);
+ }
+ else {
+// JabberLog("XML: Closing </%s> without opening tag", text);
+ mir_free(text);
+ if (attr) mir_free(attr);
+ return FALSE;
+ }
+ break;
+ case ELEM_TEXT:
+ node->text = text;
+ break;
+ default:
+ mir_free(text);
+ if (attr) mir_free(attr);
+ return FALSE;
+ }
+
+ if (attr) mir_free(attr);
+
+ return TRUE;
+}
+
+char *JabberXmlGetAttrValue(XmlNode *node, char *key)
+{
+ int i;
+
+ if (node==NULL || node->numAttr<=0 || key==NULL || strlen(key)<=0)
+ return NULL;
+ for (i=0; i<node->numAttr; i++) {
+ if (node->attr[i]->name && !strcmp(key, node->attr[i]->name))
+ return node->attr[i]->value;
+ }
+ return NULL;
+}
+
+XmlNode *JabberXmlGetChild(XmlNode *node, char *tag)
+{
+ return JabberXmlGetNthChild(node, tag, 1);
+}
+
+XmlNode *JabberXmlGetNthChild(XmlNode *node, char *tag, int nth)
+{
+ int i, num;
+
+ if (node==NULL || node->numChild<=0 || tag==NULL || strlen(tag)<=0 || nth<1)
+ return NULL;
+ num = 1;
+ for (i=0; i<node->numChild; i++) {
+ if (node->child[i]->name && !strcmp(tag, node->child[i]->name)) {
+ if (num == nth) {
+ return node->child[i];
+ }
+ num++;
+ }
+ }
+ return NULL;
+}
+
+XmlNode *JabberXmlGetChildWithGivenAttrValue(XmlNode *node, char *tag, char *attrKey, char *attrValue)
+{
+ int i;
+ char *str;
+
+ if (node==NULL || node->numChild<=0 || tag==NULL || strlen(tag)<=0 || attrKey==NULL || strlen(attrKey)<=0 || attrValue==NULL || strlen(attrValue)<=0)
+ return NULL;
+ for (i=0; i<node->numChild; i++) {
+ if (node->child[i]->name && !strcmp(tag, node->child[i]->name)) {
+ if ((str=JabberXmlGetAttrValue(node->child[i], attrKey)) != NULL)
+ if (!strcmp(str, attrValue))
+ return node->child[i];
+ }
+ }
+ return NULL;
+}
+
+static void JabberXmlRemoveChild(XmlNode *node, XmlNode *child)
+{
+ int i;
+
+ if (node==NULL || child==NULL || node->numChild<=0) return;
+ for (i=0; i<node->numChild; i++) {
+ if (node->child[i] == child)
+ break;
+ }
+ if (i < node->numChild) {
+ for (++i; i<node->numChild; i++)
+ node->child[i-1] = node->child[i];
+ node->numChild--;
+ JabberXmlFreeNode(child);
+ }
+}
+
+void JabberXmlFreeNode(XmlNode *node)
+{
+ int i;
+
+ if (node == NULL) return;
+ // Free all children first
+ for (i=0; i<node->numChild; i++)
+ JabberXmlFreeNode(node->child[i]);
+ if (node->child) mir_free(node->child);
+ // Free all attributes
+ for (i=0; i<node->numAttr; i++) {
+ if (node->attr[i]->name) mir_free(node->attr[i]->name);
+ if (node->attr[i]->value) mir_free(node->attr[i]->value);
+ mir_free(node->attr[i]);
+ }
+ if (node->attr) mir_free(node->attr);
+ // Free string field
+ if (node->text) mir_free(node->text);
+ if (node->name) mir_free(node->name);
+ // Free the node itself
+ mir_free(node);
+}
+
+XmlNode *JabberXmlCopyNode(XmlNode *node)
+{
+ XmlNode *n;
+ int i;
+
+ if (node == NULL) return NULL;
+ n = (XmlNode *) mir_alloc(sizeof(XmlNode));
+ // Copy attributes
+ if (node->numAttr > 0) {
+ n->attr = (XmlAttr **) mir_alloc(node->numAttr*sizeof(XmlAttr *));
+ for (i=0; i<node->numAttr; i++) {
+ n->attr[i] = (XmlAttr *) mir_alloc(sizeof(XmlAttr));
+ if (node->attr[i]->name) n->attr[i]->name = mir_strdup(node->attr[i]->name);
+ else n->attr[i]->name = NULL;
+ if (node->attr[i]->value) n->attr[i]->value = mir_strdup(node->attr[i]->value);
+ else n->attr[i]->value = NULL;
+ }
+ }
+ else
+ n->attr = NULL;
+ // Recursively copy children
+ if (node->numChild > 0) {
+ n->child = (XmlNode **) mir_alloc(node->numChild*sizeof(XmlNode *));
+ for (i=0; i<node->numChild; i++)
+ n->child[i] = JabberXmlCopyNode(node->child[i]);
+ }
+ else
+ n->child = NULL;
+ // Copy other fields
+ n->numAttr = node->numAttr;
+ n->maxNumAttr = node->numAttr;
+ n->numChild = node->numChild;
+ n->maxNumChild = node->numChild;
+ n->depth = node->depth;
+ n->state = node->state;
+ n->name = (node->name)?mir_strdup(node->name):NULL;
+ n->text = (node->text)?mir_strdup(node->text):NULL;
+
+ return n;
+}
+
+XmlNode *JabberXmlCreateNode(char *name)
+{
+ XmlNode *n;
+
+ if (name == NULL)
+ return NULL;
+
+ n = (XmlNode *) mir_alloc(sizeof(XmlNode));
+ memset(n, 0, sizeof(XmlNode));
+ n->name = mir_strdup(name);
+ return n;
+}
+
+void JabberXmlAddAttr(XmlNode *n, char *name, char *value)
+{
+ int i;
+
+ if (n==NULL || name==NULL || value==NULL)
+ return;
+
+ i = n->numAttr;
+ (n->numAttr)++;
+ n->attr = (XmlAttr **) mir_realloc(n->attr, sizeof(XmlAttr *) * n->numAttr);
+ n->attr[i] = (XmlAttr *) mir_alloc(sizeof(XmlAttr));
+ n->attr[i]->name = mir_strdup(name);
+ n->attr[i]->value = mir_strdup(value);
+}
+
+XmlNode *JabberXmlAddChild(XmlNode *n, char *name)
+{
+ int i;
+
+ if (n==NULL || name==NULL)
+ return NULL;
+
+ i = n->numChild;
+ n->numChild++;
+ n->child = (XmlNode **) mir_realloc(n->child, sizeof(XmlNode *) * n->numChild);
+ n->child[i] = (XmlNode *) mir_alloc(sizeof(XmlNode));
+ memset(n->child[i], 0, sizeof(XmlNode));
+ n->child[i]->name = mir_strdup(name);
+ return n->child[i];
+}
+
+void JabberXmlAddText(XmlNode *n, char *text)
+{
+ if (n!=NULL && text!=NULL) {
+ if (n->text) mir_free(n->text);
+ n->text = mir_strdup(text);
+ }
+}
+
diff --git a/protocols/Tlen/jabber_xml.h b/protocols/Tlen/jabber_xml.h
new file mode 100644
index 0000000000..98949b92f6
--- /dev/null
+++ b/protocols/Tlen/jabber_xml.h
@@ -0,0 +1,78 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#ifndef _JABBER_XML_H_
+#define _JABBER_XML_H_
+
+typedef enum { ELEM_OPEN, ELEM_CLOSE, ELEM_OPENCLOSE, ELEM_TEXT } XmlElemType;
+typedef enum { NODE_OPEN, NODE_CLOSE } XmlNodeType;
+
+typedef struct tagXmlAttr {
+ char *name;
+ char *value;
+} XmlAttr;
+
+typedef struct tagXmlNode {
+ int depth; // depth of the current node (1=root)
+ char *name; // tag name of the current node
+ int numAttr; // number of attributes
+ int maxNumAttr; // internal use (num of slots currently allocated to attr)
+ XmlAttr **attr; // attribute list
+ int numChild; // number of direct child nodes
+ int maxNumChild; // internal use (num of slots currently allocated to child)
+ struct tagXmlNode **child; // child node list
+ char *text;
+ XmlNodeType state; // internal use by parser
+} XmlNode;
+
+typedef struct tagXmlState {
+ XmlNode root; // root is the document (depth = 0);
+ // callback for depth=n element on opening/closing
+ void (*callback1_open)();
+ void (*callback1_close)();
+ void (*callback2_open)();
+ void (*callback2_close)();
+ void *userdata1_open;
+ void *userdata1_close;
+ void *userdata2_open;
+ void *userdata2_close;
+} XmlState;
+
+void JabberXmlInitState(XmlState *xmlState);
+void JabberXmlDestroyState(XmlState *xmlState);
+BOOL JabberXmlSetCallback(XmlState *xmlState, int depth, XmlElemType type, void (*callback)(), void *userdata);
+int JabberXmlParse(XmlState *xmlState, char *buffer, int datalen);
+char *JabberXmlGetAttrValue(XmlNode *node, char *key);
+XmlNode *JabberXmlGetChild(XmlNode *node, char *tag);
+XmlNode *JabberXmlGetNthChild(XmlNode *node, char *tag, int nth);
+XmlNode *JabberXmlGetChildWithGivenAttrValue(XmlNode *node, char *tag, char *attrKey, char *attrValue);
+void JabberXmlFreeNode(XmlNode *node);
+XmlNode *JabberXmlCopyNode(XmlNode *node);
+
+XmlNode *JabberXmlCreateNode(char *name);
+void JabberXmlAddAttr(XmlNode *n, char *name, char *value);
+XmlNode *JabberXmlAddChild(XmlNode *n, char *name);
+void JabberXmlAddText(XmlNode *n, char *text);
+
+#endif
+
diff --git a/protocols/Tlen/resource.h b/protocols/Tlen/resource.h
new file mode 100644
index 0000000000..f3a350630e
--- /dev/null
+++ b/protocols/Tlen/resource.h
@@ -0,0 +1,147 @@
+//{{NO_DEPENDENCIES}}
+// Microsoft Developer Studio generated include file.
+// Used by Tlen.rc
+//
+
+#define IDI_TLEN 100
+#define IDI_MAIL 101
+#define IDI_MUC 102
+#define IDI_CHATS 103
+#define IDI_GRANT 104
+#define IDI_REQUEST 105
+#define IDI_VOICE 106
+#define IDI_MICROPHONE 107
+#define IDI_SPEAKER 108
+#define IDI_IMAGE 109
+
+#define IDD_OPTIONS_BASIC 151
+#define IDD_OPTIONS_VOICE 152
+#define IDD_OPTIONS_POPUPS 153
+#define IDD_OPTIONS_ADVANCED 154
+#define IDD_USER_INFO 155
+#define IDD_USER_VCARD 156
+#define IDD_PASSWORD 157
+#define IDD_ADVSEARCH 158
+#define IDD_VOICE 159
+#define IDD_ACCEPT_VOICE 160
+#define IDD_USER_CHANGEAVATAR 161
+#define IDD_ACCMGRUI 162
+
+#define IDC_TABS 1000
+#define IDC_EDIT_USERNAME 1001
+#define IDC_SAVE 1002
+#define IDC_EDIT_PASSWORD 1003
+#define IDC_EDIT_LOGIN_SERVER 1004
+#define IDC_INFO_JID 1007
+#define IDC_INFO_RESOURCE 1008
+#define IDC_SHOW_OFFLINE 1012
+#define IDC_OFFLINE_MESSAGE 1013
+#define IDC_OFFLINE_MESSAGE_OPTION 1014
+#define IDC_VISIBILITY_SUPPORT 1015
+#define IDC_NUDGE_SUPPORT 1016
+#define IDC_LOG_ALERTS 1017
+
+#define IDC_SUBSCRIPTION 1039
+#define IDC_REGISTERACCOUNT 1040
+#define IDC_SIMPLE 1041
+#define IDC_KEEPALIVE 1042
+#define IDC_HOST 1043
+#define IDC_HOSTPORT 1044
+#define IDC_USE_SSL 1045
+#define IDC_SAVEPASSWORD 1048
+#define IDC_ROSTER_ALERTS 1049
+#define IDC_PASSWORD 1050
+#define IDC_RECONNECT 1050
+#define IDC_JID 1051
+#define IDC_ROSTER_SYNC 1052
+#define IDC_ALERT_POLICY 1053
+#define IDC_MUC_POLICY 1054
+#define IDC_VOICE_POLICY 1055
+#define IDC_IGNORE_ADVERTISEMENTS 1056
+#define IDC_AVATARS 1057
+#define IDC_VERSIONINFO 1058
+#define IDC_IMAGE_POLICY 1059
+#define IDC_CITY 1060
+#define IDC_FULLNAME 1061
+#define IDC_NICKNAME 1062
+#define IDC_FIRSTNAME 1063
+#define IDC_LASTNAME 1064
+#define IDC_BIRTH 1065
+#define IDC_AGE 1065
+#define IDC_OCCUPATION 1066
+#define IDC_EMAIL 1073
+#define IDC_GENDER 1096
+#define IDC_VOICECONVERSATIONS 1097
+#define IDC_PUBLICSTATUS 1098
+#define IDC_VCQUALITY 1100
+#define IDC_VUMETERIN 1101
+#define IDC_VUMETEROUT 1102
+#define IDC_BYTESIN 1103
+#define IDC_BYTESOUT 1104
+#define IDC_MICROPHONE 1105
+#define IDC_SPEAKER 1106
+#define IDC_ACCEPT 1107
+
+#define IDC_FILE_PROXY_TYPE_LABEL 1108
+#define IDC_FILE_PROXY_TYPE 1109
+#define IDC_FILE_PROXY_HOST_LABEL 1110
+#define IDC_FILE_PROXY_HOST 1111
+#define IDC_FILE_PROXY_PORT_LABEL 1112
+#define IDC_FILE_PROXY_PORT 1113
+#define IDC_FILE_PROXY_USE_AUTH 1114
+#define IDC_FILE_PROXY_USER 1115
+#define IDC_FILE_PROXY_USER_LABEL 1116
+#define IDC_FILE_PROXY_PASSWORD_LABEL 1117
+#define IDC_FILE_PROXY_PASSWORD 1118
+#define IDC_FILE_USE_PROXY 1119
+#define IDC_VOICE_DEVICE_IN 1120
+#define IDC_VOICE_DEVICE_OUT 1121
+
+#define IDC_MSG_ACK 1124
+#define IDC_SERVER 1125
+#define IDC_NICK 1129
+#define IDC_LIST 1133
+#define IDC_ENTER 1144
+#define IDC_AGEFROM 1152
+#define IDC_AGETO 1153
+#define IDC_LOOKFOR 1154
+#define IDC_SCHOOL 1155
+#define IDC_FROM 1175
+#define IDC_DELAY 1180
+#define IDC_COLORBKG 1181
+#define IDC_COLORTXT 1182
+#define IDC_PREVIEW 1183
+#define IDC_ENABLEPOPUP 1184
+#define IDC_DELAY_PERMANENT 1185
+#define IDC_DELAY_CUSTOM 1186
+#define IDC_DELAY_POPUP 1187
+#define IDC_TLEN 1190
+#define IDC_GENDER_TEXT 1195
+#define IDC_OCCUPATION_TEXT 1199
+#define IDC_LOOKFOR_TEXT 1200
+#define IDC_GROUP 1203
+#define IDC_SOFTWARE 1204
+#define IDC_VERSION 1205
+#define IDC_SYSTEM 1206
+#define IDC_AVATAR 1210
+#define IDC_SETAVATAR 1211
+#define IDC_DELETEAVATAR 1212
+#define IDC_AVATAR_LIST 1213
+#define IDC_OLD_AVATAR 1214
+#define IDC_BROWSEAVATAR 1215
+#define IDC_PUBLICAVATAR 1216
+
+#define IDC_STATUS 1414
+#define IDC_PLAN 1415
+#define IDC_PERSONALGROUP 1434
+#define IDC_EXTRAGROUP 1435
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NEXT_RESOURCE_VALUE 190
+#define _APS_NEXT_COMMAND_VALUE 40017
+#define _APS_NEXT_CONTROL_VALUE 1204
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/protocols/Tlen/tlen.c b/protocols/Tlen/tlen.c
new file mode 100644
index 0000000000..027e7add2e
--- /dev/null
+++ b/protocols/Tlen/tlen.c
@@ -0,0 +1,636 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "commons.h"
+#include "jabber.h"
+#include "tlen_muc.h"
+#include "tlen_file.h"
+#include "tlen_voice.h"
+#include "jabber_list.h"
+#include "jabber_iq.h"
+#include "resource.h"
+#include "tlen_picture.h"
+#include <m_file.h>
+#include <richedit.h>
+#include <ctype.h>
+#include <m_icolib.h>
+#include <m_genmenu.h>
+#include "m_mucc.h"
+#include "m_updater.h"
+
+
+struct MM_INTERFACE mmi;
+struct SHA1_INTERFACE sha1i;
+struct MD5_INTERFACE md5i;
+struct UTF8_INTERFACE utfi;
+HINSTANCE hInst;
+PLUGINLINK *pluginLink;
+HANDLE hMainThread;
+
+PLUGININFOEX pluginInfoEx = {
+ sizeof(PLUGININFOEX),
+#ifdef _UNICODE
+#ifdef _X64
+ "Tlen Protocol (x64, Unicode)",
+#else
+ "Tlen Protocol (Unicode)",
+#endif
+#else
+ "Tlen Protocol",
+#endif
+ PLUGIN_MAKE_VERSION(TLEN_MAJOR_VERSION,TLEN_MINOR_VERSION,TLEN_RELEASE_NUM,TLEN_BUILD_NUM),
+ "Tlen protocol plugin for Miranda IM (version: "TLEN_VERSION_STRING" ; compiled: "__DATE__" "__TIME__")",
+ "Santithorn Bunchua, Adam Strzelecki, Piotr Piastucki",
+ "the_leech@users.berlios.de",
+ "(c) 2002-2012 Santithorn Bunchua, Piotr Piastucki",
+ "http://mtlen.berlios.de",
+ 0,
+ 0,
+#if defined( _UNICODE )
+#ifdef _X64
+ {0x3ba4a3c6, 0x27b5, 0x4c78, { 0x92, 0x8c, 0x38, 0x2a, 0xe1, 0xd3, 0x2a, 0xb5 }}
+#else
+ {0x748f8934, 0x781a, 0x528d, { 0x52, 0x08, 0x00, 0x12, 0x65, 0x40, 0x4a, 0xb3 }}
+#endif
+#else
+ {0x11fc3484, 0x475c, 0x11dc, { 0x83, 0x14, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }}
+#endif
+};
+
+// Main jabber server connection thread global variables
+
+void TlenLoadOptions(TlenProtocol *proto);
+int TlenOptionsInit(void *ptr, WPARAM wParam, LPARAM lParam);
+int TlenUserInfoInit(void *ptr, WPARAM wParam, LPARAM lParam);
+int TlenSystemModulesLoaded(void *ptr, WPARAM wParam, LPARAM lParam);
+extern void TlenInitServicesVTbl(TlenProtocol *proto);
+extern int JabberContactDeleted(void *ptr, WPARAM wParam, LPARAM lParam);
+extern int JabberDbSettingChanged(void *ptr, WPARAM wParam, LPARAM lParam);
+
+BOOL WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpvReserved)
+{
+#ifdef _DEBUG
+ _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
+#endif
+
+ hInst = hModule;
+ return TRUE;
+}
+
+__declspec(dllexport) PLUGININFOEX *MirandaPluginInfoEx( DWORD mirandaVersion )
+{
+ if ( mirandaVersion < PLUGIN_MAKE_VERSION( 0,8,0,15 )) {
+ MessageBox( NULL, TranslateT("The Tlen protocol plugin cannot be loaded. It requires Miranda IM 0.8.0.15 or later."), TranslateT("Tlen Protocol Plugin"), MB_OK|MB_ICONWARNING|MB_SETFOREGROUND|MB_TOPMOST );
+ return NULL;
+ }
+
+ return &pluginInfoEx;
+}
+
+static const MUUID interfaces[] = {MIID_PROTOCOL, MIID_LAST};
+__declspec(dllexport) const MUUID* MirandaPluginInterfaces(void)
+{
+ return interfaces;
+}
+
+struct
+{
+ TCHAR* szDescr;
+ char* szName;
+ int defIconID;
+ HANDLE hIconLibItem;
+}
+static iconList[] =
+{
+ { _T("Protocol icon"), "PROTO", IDI_TLEN },
+ { _T("Tlen inbox"), "MAIL", IDI_MAIL },
+ { _T("Group chats"), "MUC", IDI_MUC },
+ { _T("Tlen chats"), "CHATS", IDI_CHATS },
+ { _T("Grant authorization"), "GRANT", IDI_GRANT },
+ { _T("Request authorization"),"REQUEST", IDI_REQUEST },
+ { _T("Voice chat"), "VOICE", IDI_VOICE },
+ { _T("Microphone"), "MICROPHONE", IDI_MICROPHONE },
+ { _T("Speaker"), "SPEAKER", IDI_SPEAKER },
+ { _T("Send image"), "IMAGE", IDI_IMAGE }
+};
+
+static HANDLE GetIconHandle(int iconId) {
+ int i;
+ for(i = 0; i < SIZEOF(iconList); i++)
+ if(iconList[i].defIconID == iconId)
+ return iconList[i].hIconLibItem;
+ return NULL;
+}
+
+HICON GetIcolibIcon(int iconId) {
+ HANDLE handle = GetIconHandle(iconId);
+ if (handle != NULL) {
+ return (HICON) CallService(MS_SKIN2_GETICONBYHANDLE, 0, (LPARAM)handle);
+ }
+ return NULL;
+}
+
+void ReleaseIcolibIcon(HICON hIcon) {
+ CallService( MS_SKIN2_RELEASEICON, (WPARAM)hIcon, 0 );
+}
+
+/*
+static int TlenIconsChanged(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ return 0;
+}
+*/
+
+static void TlenRegisterIcons()
+{
+ SKINICONDESC sid = { 0 };
+ char path[MAX_PATH];
+ TCHAR szSectionName[100];
+ int i;
+ mir_sntprintf(szSectionName, SIZEOF( szSectionName ), _T("%s/%s"), _T("Protocols"), _T("Tlen"));
+
+ GetModuleFileNameA(hInst, path, MAX_PATH);
+ sid.cbSize = sizeof(SKINICONDESC);
+ sid.cx = sid.cy = 16;
+ sid.ptszSection = szSectionName;
+ sid.pszDefaultFile = path;
+ sid.flags = SIDF_TCHAR;
+
+ for ( i = 0; i < SIZEOF(iconList); i++ ) {
+ char szSettingName[100];
+ mir_snprintf( szSettingName, sizeof( szSettingName ), "TLEN_%s", iconList[i].szName );
+ sid.pszName = szSettingName;
+ sid.pszDescription = (char*)iconList[i].szDescr;
+ sid.iDefaultIndex = -iconList[i].defIconID;
+ iconList[i].hIconLibItem = ( HANDLE )CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
+ }
+}
+
+static int TlenPrebuildContactMenu(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact;
+ DBVARIANT dbv;
+ CLISTMENUITEM clmi = {0};
+ JABBER_LIST_ITEM *item;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ clmi.cbSize = sizeof(CLISTMENUITEM);
+ if ((hContact=(HANDLE) wParam)!=NULL && proto->isOnline) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ if ((item=JabberListGetItemPtr(proto, LIST_ROSTER, dbv.pszVal)) != NULL) {
+ if (item->subscription==SUB_NONE || item->subscription==SUB_FROM)
+ clmi.flags = CMIM_FLAGS;
+ else
+ clmi.flags = CMIM_FLAGS|CMIF_HIDDEN;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuContactRequestAuth, (LPARAM) &clmi);
+
+ if (item->subscription==SUB_NONE || item->subscription==SUB_TO)
+ clmi.flags = CMIM_FLAGS;
+ else
+ clmi.flags = CMIM_FLAGS|CMIF_HIDDEN;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuContactGrantAuth, (LPARAM) &clmi);
+
+ if (item->status!=ID_STATUS_OFFLINE)
+ clmi.flags = CMIM_FLAGS;
+ else
+ clmi.flags = CMIM_FLAGS|CMIF_HIDDEN;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuContactMUC, (LPARAM) &clmi);
+
+ if (item->status!=ID_STATUS_OFFLINE && !TlenVoiceIsInUse(proto))
+ clmi.flags = CMIM_FLAGS;
+ else
+ clmi.flags = CMIM_FLAGS|CMIF_HIDDEN;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuContactVoice, (LPARAM) &clmi);
+
+ if (item->status!=ID_STATUS_OFFLINE)
+ clmi.flags = CMIM_FLAGS;
+ else
+ clmi.flags = CMIM_FLAGS|CMIF_HIDDEN;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuPicture, (LPARAM) &clmi);
+
+ DBFreeVariant(&dbv);
+ return 0;
+ }
+ DBFreeVariant(&dbv);
+ }
+ }
+ clmi.flags = CMIM_FLAGS|CMIF_HIDDEN;
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuContactMUC, (LPARAM) &clmi);
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuContactVoice, (LPARAM) &clmi);
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuContactRequestAuth, (LPARAM) &clmi);
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuContactGrantAuth, (LPARAM) &clmi);
+ return 0;
+}
+
+INT_PTR TlenContactMenuHandleRequestAuth(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact;
+ DBVARIANT dbv;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if ((hContact=(HANDLE) wParam)!=NULL && proto->isOnline) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ JabberSend(proto, "<presence to='%s' type='subscribe'/>", dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ }
+ return 0;
+}
+
+INT_PTR TlenContactMenuHandleGrantAuth(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact;
+ DBVARIANT dbv;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if ((hContact=(HANDLE) wParam)!=NULL && proto->isOnline) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ JabberSend(proto, "<presence to='%s' type='subscribed'/>", dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ }
+ return 0;
+}
+
+INT_PTR TlenContactMenuHandleSendPicture(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if ((hContact=(HANDLE) wParam)!=NULL && proto->isOnline) {
+ SendPicture(proto, hContact);
+ }
+ return 0;
+}
+
+INT_PTR TlenMenuHandleInbox(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ char szFileName[ MAX_PATH ];
+ DBVARIANT dbv;
+ NETLIBHTTPREQUEST req;
+ NETLIBHTTPHEADER headers[2];
+ NETLIBHTTPREQUEST *resp;
+ char *login = NULL, *password = NULL;
+ char form[1024];
+ char cookie[1024];
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginName", &dbv)) {
+ login = mir_strdup(dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "SavePassword", TRUE) == TRUE) {
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "Password", &dbv)) {
+ CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1, (LPARAM) dbv.pszVal);
+ password = mir_strdup(dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ } else if (proto->threadData != NULL && strlen(proto->threadData->password) > 0) {
+ password = mir_strdup(proto->threadData->password);
+ }
+
+ ZeroMemory(&cookie, sizeof(cookie));
+ if (login != NULL && password != NULL) {
+ mir_snprintf( form, SIZEOF(form), "username=%s&password=%s", login, password);
+ headers[0].szName = "Content-Type";
+ headers[0].szValue = "application/x-www-form-urlencoded";
+ ZeroMemory(&req, sizeof(req));
+ req.cbSize = sizeof(req);
+ req.requestType = REQUEST_POST;
+ req.flags = 0;
+ req.headersCount = 1;
+ req.headers = headers;
+ req.pData = form;
+ req.dataLength = (int)strlen(form);
+ req.szUrl = "http://poczta.o2.pl/login.html";
+ resp = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)proto->hNetlibUser, (LPARAM)&req);
+ if (resp != NULL) {
+ if (resp->resultCode/100==2 || resp->resultCode == 302) {
+ int i;
+ for (i=0; i<resp->headersCount; i++ ) {
+ if (strcmpi(resp->headers[i].szName, "Set-Cookie")==0) {
+ char *start = strstr(resp->headers[i].szValue, "ssid=");
+ if (start != NULL) {
+ char *end = strstr(resp->headers[i].szValue, ";");
+ start = start + 5;
+ if (end == NULL) {
+ end = resp->headers[i].szValue + strlen(resp->headers[i].szValue);
+ }
+ strncpy(cookie, start, (end - start));
+ break;
+ }
+ }
+ }
+ }
+ CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
+ }
+ }
+ mir_free(login);
+ mir_free(password);
+ _snprintf(szFileName, sizeof(szFileName), "http://poczta.o2.pl/login.html?sid=%s", cookie);
+ CallService(MS_UTILS_OPENURL, (WPARAM) 1, (LPARAM) szFileName);
+ return 0;
+}
+
+int TlenOnModulesLoaded(void *ptr, WPARAM wParam, LPARAM lParam) {
+
+ char str[128];
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ /* Set all contacts to offline */
+ HANDLE hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ while (hContact != NULL) {
+ char *szProto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if(szProto!=NULL && !strcmp(szProto, proto->iface.m_szModuleName)) {
+ if (DBGetContactSettingWord(hContact, proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE) != ID_STATUS_OFFLINE) {
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE);
+ }
+ }
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM) hContact, 0);
+ }
+ TlenMUCInit(proto);
+ sprintf(str, "%s", Translate("Incoming mail"));
+ SkinAddNewSoundEx("TlenMailNotify", proto->iface.m_szProtoName, str);
+ sprintf(str, "%s", Translate("Alert"));
+ SkinAddNewSoundEx("TlenAlertNotify", proto->iface.m_szProtoName, str);
+ sprintf(str, "%s", Translate("Voice chat"));
+ SkinAddNewSoundEx("TlenVoiceNotify", proto->iface.m_szProtoName, str);
+
+ HookEventObj_Ex(ME_USERINFO_INITIALISE, proto, TlenUserInfoInit);
+
+ return 0;
+}
+
+int TlenPreShutdown(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ JabberLog(ptr, "TLEN TlenPreShutdown");
+ //TlenProtocol *proto = (TlenProtocol *)ptr;
+ return 0;
+}
+
+
+static void initMenuItems(TlenProtocol *proto)
+{
+
+ char text[_MAX_PATH];
+ CLISTMENUITEM mi, clmi;
+ memset(&mi, 0, sizeof(CLISTMENUITEM));
+ mi.cbSize = sizeof(CLISTMENUITEM);
+ memset(&clmi, 0, sizeof(CLISTMENUITEM));
+ clmi.cbSize = sizeof(CLISTMENUITEM);
+ clmi.flags = CMIM_FLAGS | CMIF_GRAYED;
+
+ mi.pszContactOwner = proto->iface.m_szModuleName;
+ mi.popupPosition = 500090000;
+
+ strcpy(text, proto->iface.m_szModuleName);
+ mi.pszService = text;
+ mi.ptszName = proto->iface.m_tszUserName;
+ mi.position = -1999901009;
+ mi.pszPopupName = (char *)-1;
+ mi.flags = CMIF_ROOTPOPUP | CMIF_TCHAR | CMIF_ICONFROMICOLIB;
+ mi.icolibItem = GetIconHandle(IDI_TLEN);
+ proto->hMenuRoot = (HANDLE)CallService( MS_CLIST_ADDMAINMENUITEM, (WPARAM)0, (LPARAM)&mi);
+
+ mi.flags = CMIF_CHILDPOPUP | CMIF_ICONFROMICOLIB;
+ //mi.pszPopupName = (char *)proto->hMenuRoot;
+ mi.hParentMenu = (HGENMENU)proto->hMenuRoot;
+
+ proto->hMenuChats = NULL;
+ if(ServiceExists(MS_MUCC_NEW_WINDOW))
+ {
+ sprintf(text, "%s/MainMenuChats", proto->iface.m_szModuleName);
+ CreateServiceFunction_Ex(text, proto, TlenMUCMenuHandleChats);
+ mi.pszName = "Tlen Chats";
+ mi.position = 2000050001;
+ mi.icolibItem = GetIconHandle(IDI_CHATS);
+ mi.pszService = text;
+ proto->hMenuChats = (HANDLE) CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM) &mi);
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuChats, (LPARAM) &clmi);
+ }
+
+ // "Multi-User Conference"
+ sprintf(text, "%s/MainMenuMUC", proto->iface.m_szModuleName);
+ CreateServiceFunction_Ex(text, proto, TlenMUCMenuHandleMUC);
+ mi.pszName = "Multi-User Conference";
+ mi.position = 2000050002;
+ mi.icolibItem = GetIconHandle(IDI_MUC);
+ mi.pszService = text;
+ proto->hMenuMUC = (HANDLE) CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM) &mi);
+ CallService(MS_CLIST_MODIFYMENUITEM, (WPARAM) proto->hMenuMUC, (LPARAM) &clmi);
+
+ sprintf(text, "%s/MainMenuInbox", proto->iface.m_szModuleName);
+ CreateServiceFunction_Ex(text, proto, TlenMenuHandleInbox);
+ mi.pszName = "Tlen Mail";
+ mi.position = 2000050003;
+ mi.icolibItem = GetIconHandle(IDI_MAIL);
+ mi.pszService = text;
+ proto->hMenuInbox = (HANDLE) CallService(MS_CLIST_ADDMAINMENUITEM, 0, (LPARAM) &mi);
+
+ mi.hParentMenu = NULL;
+
+
+ // "Send picture"
+ sprintf(text, "%s/SendPicture", proto->iface.m_szModuleName);
+ CreateServiceFunction_Ex(text, proto, TlenContactMenuHandleSendPicture);
+ mi.flags = CMIF_ICONFROMICOLIB;
+ mi.pszName = "Send picture";
+ mi.position = -2000019030;
+ mi.icolibItem = GetIconHandle(IDI_IMAGE);
+ mi.pszService = text;
+ proto->hMenuPicture = (HANDLE) CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM) &mi);
+
+ // "Invite to MUC"
+ sprintf(text, "%s/ContactMenuMUC", proto->iface.m_szModuleName);
+ CreateServiceFunction_Ex(text, proto, TlenMUCContactMenuHandleMUC);
+ mi.pszName = "Multi-User Conference";
+ mi.position = -2000019020;
+ mi.icolibItem = GetIconHandle(IDI_MUC);
+ mi.pszService = text;
+ proto->hMenuContactMUC = (HANDLE) CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM) &mi);
+
+ // "Invite to voice chat"
+ sprintf(text, "%s/ContactMenuVoice", proto->iface.m_szModuleName);
+ CreateServiceFunction_Ex(text, proto, TlenVoiceContactMenuHandleVoice);
+ mi.pszName = "Voice Chat";
+ mi.position = -2000019010;
+ mi.icolibItem = GetIconHandle(IDI_VOICE);
+ mi.pszService = text;
+ proto->hMenuContactVoice = (HANDLE) CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM) &mi);
+
+ // "Request authorization"
+ sprintf(text, "%s/RequestAuth", proto->iface.m_szModuleName);
+ CreateServiceFunction_Ex(text, proto, TlenContactMenuHandleRequestAuth);
+ mi.pszName = "Request authorization";
+ mi.position = -2000001001;
+ mi.icolibItem = GetIconHandle(IDI_REQUEST);
+ mi.pszService = text;
+ proto->hMenuContactRequestAuth = (HANDLE) CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM) &mi);
+
+ // "Grant authorization"
+ sprintf(text, "%s/GrantAuth", proto->iface.m_szModuleName);
+ CreateServiceFunction_Ex(text, proto, TlenContactMenuHandleGrantAuth);
+ mi.pszName = "Grant authorization";
+ mi.position = -2000001000;
+ mi.icolibItem = GetIconHandle(IDI_GRANT);
+ mi.pszService = text;
+ proto->hMenuContactGrantAuth = (HANDLE) CallService(MS_CLIST_ADDCONTACTMENUITEM, 0, (LPARAM) &mi);
+}
+
+static void uninitMenuItems(TlenProtocol *proto) {
+ CallService(MS_CLIST_REMOVEMAINMENUITEM, (WPARAM)proto->hMenuChats, (LPARAM) 0);
+ CallService(MS_CLIST_REMOVEMAINMENUITEM, (WPARAM)proto->hMenuMUC, (LPARAM) 0);
+ CallService(MS_CLIST_REMOVEMAINMENUITEM, (WPARAM)proto->hMenuInbox, (LPARAM) 0);
+ CallService(MS_CLIST_REMOVEMAINMENUITEM, (WPARAM)proto->hMenuRoot, (LPARAM) 0);
+ CallService(MS_CLIST_REMOVECONTACTMENUITEM, (WPARAM)proto->hMenuContactMUC, (LPARAM) 0);
+ CallService(MS_CLIST_REMOVECONTACTMENUITEM, (WPARAM)proto->hMenuPicture, (LPARAM) 0);
+ CallService(MS_CLIST_REMOVECONTACTMENUITEM, (WPARAM)proto->hMenuContactVoice, (LPARAM) 0);
+ CallService(MS_CLIST_REMOVECONTACTMENUITEM, (WPARAM)proto->hMenuContactRequestAuth, (LPARAM) 0);
+ CallService(MS_CLIST_REMOVECONTACTMENUITEM, (WPARAM)proto->hMenuContactGrantAuth, (LPARAM) 0);
+}
+
+
+static TlenProtocol *tlenProtoInit( const char* pszProtoName, const TCHAR* tszUserName )
+{
+ DBVARIANT dbv;
+ char text[_MAX_PATH];
+ TlenProtocol *proto = (TlenProtocol *)mir_alloc(sizeof(TlenProtocol));
+ memset(proto, 0, sizeof(TlenProtocol));
+ proto->iface.m_tszUserName = mir_tstrdup( tszUserName );
+ proto->iface.m_szModuleName = mir_strdup(pszProtoName);
+ proto->iface.m_szProtoName = mir_strdup(pszProtoName);
+ _strlwr( proto->iface.m_szProtoName );
+ proto->iface.m_szProtoName[0] = toupper( proto->iface.m_szProtoName[0] );
+ proto->iface.m_iStatus = ID_STATUS_OFFLINE;
+ TlenInitServicesVTbl(proto);
+
+ InitializeCriticalSection(&proto->modeMsgMutex);
+ InitializeCriticalSection(&proto->csSend);
+
+ sprintf(text, "%s/%s", proto->iface.m_szModuleName, "Nudge");
+ proto->hTlenNudge = CreateHookableEvent(text);
+
+ HookEventObj_Ex(ME_SYSTEM_MODULESLOADED, proto, TlenSystemModulesLoaded);
+ HookEventObj_Ex(ME_OPT_INITIALISE, proto, TlenOptionsInit);
+ HookEventObj_Ex(ME_DB_CONTACT_SETTINGCHANGED, proto, JabberDbSettingChanged);
+ HookEventObj_Ex(ME_DB_CONTACT_DELETED, proto, JabberContactDeleted);
+ HookEventObj_Ex(ME_CLIST_PREBUILDCONTACTMENU, proto, TlenPrebuildContactMenu);
+// HookEventObj_Ex(ME_SKIN2_ICONSCHANGED, proto, TlenIconsChanged);
+ HookEventObj_Ex(ME_SYSTEM_PRESHUTDOWN, proto, TlenPreShutdown);
+
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ DBFreeVariant(&dbv);
+ } else {
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "LoginServer", "tlen.pl");
+ }
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "ManualHost", &dbv)) {
+ DBFreeVariant(&dbv);
+ } else {
+ DBWriteContactSettingString(NULL, proto->iface.m_szModuleName, "ManualHost", "s1.tlen.pl");
+ }
+
+ TlenLoadOptions(proto);
+
+ JabberWsInit(proto);
+ JabberSerialInit(proto);
+ JabberIqInit(proto);
+ JabberListInit(proto);
+
+ return proto;
+}
+
+int TlenSystemModulesLoaded(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ initMenuItems(proto);
+
+ // updater plugin support
+ if(ServiceExists(MS_UPDATE_REGISTERFL))
+ {
+ PLUGININFO* pluginInfoPtr = (PLUGININFO*)&pluginInfoEx;
+ #ifdef _UNICODE
+ #ifdef _X64
+ CallService(MS_UPDATE_REGISTERFL, (WPARAM)4435, (LPARAM)pluginInfoPtr); //x64 version
+ #else
+ CallService(MS_UPDATE_REGISTERFL, (WPARAM)4405, (LPARAM)pluginInfoPtr); //Unicode version
+ #endif
+ #else
+ CallService(MS_UPDATE_REGISTERFL, (WPARAM)4404, (LPARAM)pluginInfoPtr); //ANSI version
+ #endif
+ }
+
+ return 0;
+}
+
+static int tlenProtoUninit( TlenProtocol *proto )
+{
+ uninitMenuItems(proto);
+ TlenVoiceCancelAll(proto);
+ TlenFileCancelAll(proto);
+ if (proto->hTlenNudge)
+ DestroyHookableEvent(proto->hTlenNudge);
+ UnhookEvents_Ex(proto);
+ JabberListUninit(proto);
+ JabberIqUninit(proto);
+ JabberSerialUninit(proto);
+ DeleteCriticalSection(&proto->modeMsgMutex);
+ DeleteCriticalSection(&proto->csSend);
+ //DestroyServices_Ex(proto);
+ JabberWsUninit(proto);
+ mir_free(proto->modeMsgs.szOnline);
+ mir_free(proto->modeMsgs.szAway);
+ mir_free(proto->modeMsgs.szNa);
+ mir_free(proto->modeMsgs.szDnd);
+ mir_free(proto->modeMsgs.szFreechat);
+ mir_free(proto->modeMsgs.szInvisible);
+ mir_free(proto);
+ return 0;
+}
+
+int __declspec(dllexport) Load(PLUGINLINK *link)
+{
+ PROTOCOLDESCRIPTOR pd;
+
+ pluginLink = link;
+ mir_getMMI( &mmi );
+ mir_getMD5I( &md5i );
+ mir_getSHA1I( &sha1i );
+ mir_getUTFI( &utfi );
+
+ DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hMainThread, THREAD_SET_CONTEXT, FALSE, 0);
+
+ srand((unsigned) time(NULL));
+
+ TlenRegisterIcons();
+
+ // Register protocol module
+ ZeroMemory(&pd, sizeof(PROTOCOLDESCRIPTOR));
+ pd.cbSize = sizeof(PROTOCOLDESCRIPTOR);
+ pd.szName = "TLEN";
+ pd.fnInit = ( pfnInitProto )tlenProtoInit;
+ pd.fnUninit = ( pfnUninitProto )tlenProtoUninit;
+ pd.type = PROTOTYPE_PROTOCOL;
+ CallService(MS_PROTO_REGISTERMODULE, 0, (LPARAM) &pd);
+
+ return 0;
+}
+
+int __declspec(dllexport) Unload(void)
+{
+ return 0;
+}
+
diff --git a/protocols/Tlen/tlen.rc b/protocols/Tlen/tlen.rc
new file mode 100644
index 0000000000..ba930c75be
--- /dev/null
+++ b/protocols/Tlen/tlen.rc
@@ -0,0 +1,439 @@
+#include "resource.h"
+#include "commons.h"
+#ifdef __MINGW32__
+ #define WINVER 0x500
+ #define _WIN32_IE 0x500
+#endif
+#include <windows.h>
+#ifndef IDC_STATIC
+#define IDC_STATIC (-1)
+#endif
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+#ifdef _WIN32
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+#pragma code_page(1252)
+#endif
+#ifdef APSTUDIO_INVOKED
+
+1 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#include ""winres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_ACCMGRUI DIALOGEX 0, 0, 186, 134
+STYLE DS_SETFONT | DS_FIXEDSYS | WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ LTEXT "Username:",IDC_STATIC,0,14,38,12,SS_CENTERIMAGE
+ EDITTEXT IDC_EDIT_USERNAME,65,14,115,12,ES_AUTOHSCROLL
+ LTEXT "Password:",IDC_STATIC,0,30,38,12,SS_CENTERIMAGE
+ EDITTEXT IDC_EDIT_PASSWORD,65,30,115,12,ES_PASSWORD | ES_AUTOHSCROLL
+ CONTROL "Save password",IDC_SAVEPASSWORD,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,65,46,115,10
+ CONTROL "Create new account",IDC_REGISTERACCOUNT,"Hyperlink",
+ 0x0,0,62,100,8
+END
+
+
+IDD_OPTIONS_BASIC DIALOGEX 0, 0, 304, 200
+STYLE DS_FIXEDSYS | WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg"
+BEGIN
+ GROUPBOX "Tlen",IDC_TLEN,0,0,304,42
+ LTEXT "Username:",IDC_STATIC,8,12,52,8
+ EDITTEXT IDC_EDIT_USERNAME,70,10,86,12,ES_AUTOHSCROLL
+ CONTROL "Create new account",IDC_REGISTERACCOUNT,"Hyperlink",
+ 0x0,170,12,100,8
+ LTEXT "Password:",IDC_STATIC,8,26,52,8
+ EDITTEXT IDC_EDIT_PASSWORD,70,24,86,12,ES_PASSWORD |
+ ES_AUTOHSCROLL
+ CONTROL "Save password",IDC_SAVEPASSWORD,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,170,26,100,10
+ GROUPBOX "Options",IDC_SIMPLE,0,44,304,156
+ CONTROL "Automatically reconnect after unintentional disconnection",
+ IDC_RECONNECT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,8, 56,239,10
+ CONTROL "Leave status message after disconnection",
+ IDC_OFFLINE_MESSAGE,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,8,68,168,10
+ COMBOBOX IDC_OFFLINE_MESSAGE_OPTION,190,67,75,140,
+ CBS_DROPDOWNLIST | WS_TABSTOP
+ CONTROL "Ignore advertisements",
+ IDC_IGNORE_ADVERTISEMENTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,8, 80,250,10
+ CONTROL "Automatically delete contacts not in my roster",
+ IDC_ROSTER_SYNC,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,8, 92,250,10
+ CONTROL "Show offline users with status messages as invisible in contact list",
+ IDC_SHOW_OFFLINE,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, 8,104,250,10
+ CONTROL "Enable avatars",
+ IDC_AVATARS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, 8,116,250,10
+ CONTROL "Send and receive client version information",
+ IDC_VERSIONINFO,"Button",BS_AUTOCHECKBOX | WS_TABSTOP, 8,128,250,10
+ LTEXT "Alert policy",IDC_STATIC,8,140,70,8
+ COMBOBOX IDC_ALERT_POLICY,95,139,190,100,
+ CBS_DROPDOWNLIST | WS_TABSTOP
+ CONTROL "Use Nudge plugin",
+ IDC_NUDGE_SUPPORT,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 24,153,120,10
+ CONTROL "Log alerts as messages",
+ IDC_LOG_ALERTS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,
+ 150,153,130,10
+ LTEXT "Group chat policy",IDC_STATIC,8,168,70,8
+ COMBOBOX IDC_MUC_POLICY,95,166,190,100,
+ CBS_DROPDOWNLIST | WS_TABSTOP
+ LTEXT "Image transfer policy",IDC_STATIC,8,183,70,8
+ COMBOBOX IDC_IMAGE_POLICY,95,181,190,100,
+ CBS_DROPDOWNLIST | WS_TABSTOP
+END
+
+
+IDD_OPTIONS_VOICE DIALOGEX 0, 0, 304, 200
+STYLE DS_FIXEDSYS | WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg"
+BEGIN
+ GROUPBOX "Voice Chats",IDC_STATIC,0,0,304,57
+ LTEXT "Voice chat policy",IDC_STATIC,8,12,70,8
+ COMBOBOX IDC_VOICE_POLICY,95,10,190,100,
+ CBS_DROPDOWNLIST | WS_TABSTOP
+ LTEXT "Recording device:",IDC_STATIC,8,26,105,8
+ COMBOBOX IDC_VOICE_DEVICE_IN,120,24,110,100,CBS_DROPDOWNLIST |
+ WS_TABSTOP
+ LTEXT "Playback device:",IDC_STATIC,8,40,105,8
+ COMBOBOX IDC_VOICE_DEVICE_OUT,120,38,110,100,CBS_DROPDOWNLIST |
+ WS_TABSTOP
+END
+
+IDD_OPTIONS_ADVANCED DIALOGEX 0, 0, 304, 200
+STYLE DS_FIXEDSYS | WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg"
+BEGIN
+ GROUPBOX "Expert Options",IDC_STATIC,0,0,304,74
+ LTEXT "Login server:",IDC_STATIC,8,18,75,8
+ EDITTEXT IDC_EDIT_LOGIN_SERVER,90,16,90,12,ES_AUTOHSCROLL
+ LTEXT "Connection Host:",IDC_STATIC,8,32,75,8
+ EDITTEXT IDC_HOST,90,30,90,12,ES_AUTOHSCROLL | WS_DISABLED
+ LTEXT "Port:",IDC_STATIC,194,32,35,8
+ EDITTEXT IDC_HOSTPORT,230,30,26,12,ES_AUTOHSCROLL | ES_NUMBER |
+ WS_DISABLED
+ CONTROL "Keep connection alive",IDC_KEEPALIVE,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,8,47,250,10
+ CONTROL "Enable encryption",IDC_USE_SSL,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,8,60,250,10
+
+ CONTROL "Enable Always Visible and Never Visible",
+ IDC_VISIBILITY_SUPPORT,"Button",BS_AUTOCHECKBOX | NOT WS_VISIBLE |
+ WS_TABSTOP,8,60,250,10
+
+ GROUPBOX "P2P Connections",IDC_STATIC,0,100,304,98
+ CONTROL "Use proxy for incoming connections",IDC_FILE_USE_PROXY,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,8,114,271,10
+ LTEXT "Proxy type:",IDC_FILE_PROXY_TYPE_LABEL,10,130,48,8,
+ WS_DISABLED
+ COMBOBOX IDC_FILE_PROXY_TYPE,68,128,80,48,CBS_DROPDOWNLIST |
+ WS_DISABLED | WS_VSCROLL | WS_TABSTOP
+ LTEXT "Proxy server:",IDC_FILE_PROXY_HOST_LABEL,10,145,48,8,
+ WS_DISABLED
+ EDITTEXT IDC_FILE_PROXY_HOST,68,143,80,12,ES_AUTOHSCROLL |
+ WS_DISABLED | WS_GROUP
+ LTEXT "Port:",IDC_FILE_PROXY_PORT_LABEL,174,145,25,8,
+ WS_DISABLED
+ EDITTEXT IDC_FILE_PROXY_PORT,204,143,30,12,ES_AUTOHSCROLL |
+ ES_NUMBER | WS_DISABLED
+ CONTROL "Proxy requires authorization",IDC_FILE_PROXY_USE_AUTH,
+ "Button",BS_AUTOCHECKBOX | WS_DISABLED | WS_TABSTOP,8,
+ 160,271,10
+ LTEXT "Username:",IDC_FILE_PROXY_USER_LABEL,10,176,47,8,
+ WS_DISABLED
+ EDITTEXT IDC_FILE_PROXY_USER,68,175,80,12,ES_AUTOHSCROLL |
+ WS_DISABLED
+ LTEXT "Password:",IDC_FILE_PROXY_PASSWORD_LABEL,153,176,45,8,
+ WS_DISABLED
+ EDITTEXT IDC_FILE_PROXY_PASSWORD,204,175,81,12,ES_PASSWORD |
+ ES_AUTOHSCROLL | WS_DISABLED
+
+
+END
+
+IDD_OPTIONS_POPUPS DIALOG DISCARDABLE 0, 0, 304, 143
+STYLE WS_CHILD
+FONT 8, "MS Sans Serif"
+BEGIN
+
+ GROUPBOX "Mail Notification",IDC_STATIC,0,0,304,110
+ CONTROL "Enable incoming mail notification",IDC_ENABLEPOPUP,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,8,12,267,10
+ GROUPBOX "Colours",IDC_STATIC,8,26,140,55
+ LTEXT "Background",IDC_STATIC,47,43,95,8
+ LTEXT "Text",IDC_STATIC,47,62,96,8
+ CONTROL "",IDC_COLORBKG,"ColourPicker",WS_TABSTOP,17,41,24,12
+ CONTROL "",IDC_COLORTXT,"ColourPicker",WS_TABSTOP,17,59,24,12
+ GROUPBOX "Delay",IDC_STATIC,157,26,140,55
+ CONTROL "&From PopUp plugin",IDC_DELAY_POPUP,"Button",
+ BS_AUTORADIOBUTTON,164,40,125,10
+ CONTROL "&Custom",IDC_DELAY_CUSTOM,"Button",BS_AUTORADIOBUTTON,
+ 164,53,98,10
+ EDITTEXT IDC_DELAY,267,51,21,14,ES_AUTOHSCROLL | ES_NUMBER
+ CONTROL "P&ermanent",IDC_DELAY_PERMANENT,"Button",
+ BS_AUTORADIOBUTTON,164,67,123,10
+ PUSHBUTTON "Preview",IDC_PREVIEW,119,90,70,14
+END
+
+IDD_PASSWORD DIALOG DISCARDABLE 0, 0, 151, 63
+STYLE DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP |
+ WS_VISIBLE | WS_CAPTION
+CAPTION "Jabber Password"
+FONT 8, "MS Shell Dlg"
+BEGIN
+ EDITTEXT IDC_JID,7,7,137,12,ES_READONLY | NOT WS_BORDER | NOT
+ WS_TABSTOP
+ EDITTEXT IDC_PASSWORD,7,22,137,12,ES_PASSWORD | ES_AUTOHSCROLL
+ DEFPUSHBUTTON "OK",IDOK,23,42,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,77,42,50,14
+END
+
+IDD_USER_VCARD DIALOGEX 0, 0, 222, 140
+STYLE DS_FIXEDSYS | WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ LTEXT "Nick name:",IDC_STATIC,5,8,51,8
+ EDITTEXT IDC_NICKNAME,58,6,102,12,ES_AUTOHSCROLL
+ LTEXT "First name:",IDC_STATIC,5,21,51,8
+ EDITTEXT IDC_FIRSTNAME,58,19,102,12,ES_AUTOHSCROLL
+ LTEXT "Last name:",IDC_STATIC,5,34,51,8
+ EDITTEXT IDC_LASTNAME,58,32,102,12,ES_AUTOHSCROLL
+ LTEXT "E-mail:",IDC_STATIC,5,47,51,8
+ EDITTEXT IDC_EMAIL,58,45,102,12,ES_AUTOHSCROLL
+ LTEXT "Gender:",IDC_STATIC,5,61,51,8
+ COMBOBOX IDC_GENDER,58,59,55,52,CBS_DROPDOWN | WS_VSCROLL |
+ WS_TABSTOP
+ LTEXT "Year of birth:",IDC_STATIC,120,61,53,8
+ EDITTEXT IDC_AGE,176,59,27,12,ES_AUTOHSCROLL
+ LTEXT "City:",IDC_STATIC,6,75,51,8
+ EDITTEXT IDC_CITY,58,73,102,12,ES_AUTOHSCROLL
+ LTEXT "School:",IDC_STATIC,5,88,51,8
+ EDITTEXT IDC_SCHOOL,58,86,102,12,ES_AUTOHSCROLL
+ LTEXT "Occupation:",IDC_STATIC,5,102,51,8
+ COMBOBOX IDC_OCCUPATION,57,100,102,96,CBS_DROPDOWNLIST |
+ WS_VSCROLL | WS_TABSTOP
+ LTEXT "Looking for:",IDC_STATIC,5,116,51,8
+ COMBOBOX IDC_LOOKFOR,57,114,102,96,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ CONTROL "Voice chats",IDC_VOICECONVERSATIONS,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,5,130,107,10
+ CONTROL "Publicly visible status",IDC_PUBLICSTATUS,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,112,130,107,10
+ PUSHBUTTON "Save changes",IDC_SAVE,164,111,53,16
+END
+
+IDD_USER_CHANGEAVATAR DIALOGEX 0, 0, 180, 80
+STYLE DS_SETFONT | DS_3DLOOK | DS_MODALFRAME | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+CAPTION "Avatar"
+BEGIN
+ GROUPBOX "Avatar Options",IDC_STATIC,5,2,170,55
+ CONTROL "Public avatar",IDC_PUBLICAVATAR,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,15,15,150,13
+ PUSHBUTTON "OK",IDOK,115,62,60,13
+END
+
+
+IDD_USER_INFO DIALOG DISCARDABLE 0, 0, 222, 146
+STYLE DS_FIXEDSYS | WS_CHILD
+FONT 8, "MS Shell Dlg"
+BEGIN
+ LTEXT "Tlen login:",IDC_STATIC,5,2,48,8
+ EDITTEXT IDC_INFO_JID,53,2,73,12,ES_AUTOHSCROLL | ES_READONLY |
+ NOT WS_BORDER
+ LTEXT "Subscription:",IDC_STATIC,5,14,48,8,NOT WS_GROUP
+ EDITTEXT IDC_SUBSCRIPTION,53,14,131,12,ES_READONLY | NOT WS_BORDER |
+ NOT WS_TABSTOP
+ LTEXT "School:",IDC_STATIC,5,44,48,8
+ EDITTEXT IDC_SCHOOL,53,44,131,12,ES_AUTOHSCROLL | ES_READONLY |
+ NOT WS_BORDER
+ LTEXT "Occupation:",IDC_STATIC,5,56,48,8
+ EDITTEXT IDC_OCCUPATION_TEXT,53,56,135,12,ES_AUTOHSCROLL |
+ ES_READONLY | NOT WS_BORDER
+ LTEXT "Looking for:",IDC_STATIC,5,68,48,8
+ EDITTEXT IDC_LOOKFOR_TEXT,53,68,136,12,ES_AUTOHSCROLL |
+ ES_READONLY | NOT WS_BORDER
+ LTEXT "Software:",IDC_STATIC,5,100,48,8
+ EDITTEXT IDC_SOFTWARE,54,100,140,12,ES_AUTOHSCROLL | ES_READONLY |
+ NOT WS_BORDER | NOT WS_TABSTOP
+ LTEXT "Version:",IDC_STATIC,5,112,48,8
+ EDITTEXT IDC_VERSION,54,112,140,12,ES_AUTOHSCROLL | ES_READONLY |
+ NOT WS_BORDER | NOT WS_TABSTOP
+ LTEXT "System:",IDC_STATIC,5,124,48,8
+ EDITTEXT IDC_SYSTEM,54,124,140,12,ES_AUTOHSCROLL | ES_READONLY |
+ NOT WS_BORDER | NOT WS_TABSTOP
+END
+
+IDD_ADVSEARCH DIALOGEX 0, 0, 334, 178
+STYLE DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_BORDER
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ GROUPBOX "Personal Information",IDC_PERSONALGROUP,7,7,156,164
+ LTEXT "First name:",IDC_STATIC,15,22,50,8
+ EDITTEXT IDC_FIRSTNAME,65,20,91,12,ES_AUTOHSCROLL
+ LTEXT "Last name:",IDC_STATIC,15,37,50,8
+ EDITTEXT IDC_LASTNAME,65,35,91,12,ES_AUTOHSCROLL
+ LTEXT "Nickname:",IDC_STATIC,15,52,50,8
+ EDITTEXT IDC_NICK,65,50,91,12,ES_AUTOHSCROLL
+ LTEXT "E-mail:",IDC_STATIC,15,67,50,8
+ EDITTEXT IDC_EMAIL,65,65,91,12,ES_AUTOHSCROLL
+ LTEXT "Gender:",IDC_STATIC,15,85,50,8
+ COMBOBOX IDC_GENDER,65,83,91,51,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ LTEXT "Age:",IDC_STATIC,15,100,50,8
+ EDITTEXT IDC_AGEFROM,65,98,27,12,ES_AUTOHSCROLL | ES_NUMBER
+ LTEXT "to",IDC_STATIC,98,100,21,8
+ EDITTEXT IDC_AGETO,123,98,27,12,ES_AUTOHSCROLL | ES_NUMBER
+ LTEXT "City:",IDC_STATIC,15,118,50,8
+ EDITTEXT IDC_CITY,65,116,91,12,ES_AUTOHSCROLL
+ LTEXT "Occupation:",IDC_STATIC,15,135,50,8
+ COMBOBOX IDC_OCCUPATION,65,133,91,93,CBS_DROPDOWNLIST |
+ WS_VSCROLL | WS_TABSTOP
+ LTEXT "School:",IDC_STATIC,15,150,50,8
+ EDITTEXT IDC_SCHOOL,65,148,91,12,ES_AUTOHSCROLL
+ GROUPBOX "Extra Search Criterias",IDC_EXTRAGROUP,171,7,156,67
+ LTEXT "Status:",IDC_STATIC,177,22,50,8
+ COMBOBOX IDC_STATUS,227,20,91,113,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ LTEXT "Looking for:",IDC_STATIC,177,37,50,8
+ COMBOBOX IDC_LOOKFOR,227,35,91,172,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ LTEXT "Plan:",IDC_STATIC,177,52,50,8,WS_DISABLED
+ COMBOBOX IDC_PLAN,227,50,91,113,CBS_DROPDOWNLIST | WS_DISABLED |
+ WS_VSCROLL | WS_TABSTOP
+END
+
+IDD_VOICE DIALOG DISCARDABLE 0, 0, 151, 122
+STYLE DS_MODALFRAME | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER |
+ WS_POPUP | WS_VISIBLE | WS_CAPTION
+CAPTION "Tlen Voice Chat"
+FONT 8, "MS Shell Dlg"
+BEGIN
+ CONTROL "",IDC_MICROPHONE,"MButtonClass",0x0,12,7,16,16,
+ 0x18000000L
+ CONTROL "",IDC_VUMETERIN,"Static",SS_OWNERDRAW,47,10,120,8
+ CONTROL "",IDC_SPEAKER,"MButtonClass",0x0,12,29,16,16,
+ 0x18000000L
+ CONTROL "",IDC_VUMETEROUT,"Static",SS_OWNERDRAW,47,31,120,8
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,7,53,140,4
+ LTEXT "Quality",IDC_STATIC,10,64,45,8
+ COMBOBOX IDC_VCQUALITY,55,62,88,100,CBS_DROPDOWNLIST | WS_VSCROLL
+ LTEXT "In",IDC_STATIC,10,80,25,8
+ LTEXT "",IDC_BYTESIN,35,80,30,8
+ LTEXT "Out",IDC_STATIC,90,80,25,8
+ LTEXT "",IDC_BYTESOUT,115,80,30,8
+ EDITTEXT IDC_STATUS,10,91,131,8,ES_CENTER | ES_AUTOHSCROLL |
+ WS_DISABLED | NOT WS_BORDER
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,7,100,140,4
+ PUSHBUTTON "Finish",IDCANCEL,50,106,50,14
+END
+
+IDD_ACCEPT_VOICE DIALOG DISCARDABLE 0, 0, 210, 70
+STYLE DS_MODALFRAME | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP |
+ WS_VISIBLE | WS_CAPTION | WS_SYSMENU
+CAPTION "Tlen Voice Chat Invitation"
+FONT 8, "MS Shell Dlg"
+BEGIN
+ DEFPUSHBUTTON "&Accept",IDC_ACCEPT,98,50,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,155,50,50,14
+ LTEXT "From:",IDC_STATIC,25,24,60,8
+ LTEXT "The following invitation to join a voice chat is received.",
+ IDC_STATIC,3,4,204,8
+ EDITTEXT IDC_FROM,85,20,100,12,ES_AUTOHSCROLL | ES_READONLY
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,3,40,203,4
+END
+
+
+#ifndef _MAC
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION TLEN_FILEVERSION_STRING
+ PRODUCTVERSION TLEN_FILEVERSION_STRING
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE 0x2L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "041504e3"
+ BEGIN
+ VALUE "Comments", "\0"
+ VALUE "CompanyName", "http://mtlen.berlios.de\0"
+ VALUE "FileDescription", "Tlen Protocol Plugin for Miranda IM\0"
+ VALUE "FileVersion", TLEN_VERSION_STRING
+ VALUE "InternalName", "tlen\0"
+ VALUE "LegalCopyright", "Copyright (c) 2002-2011 Santithorn Bunchua, Piotr Piastucki\0"
+ VALUE "LegalTrademarks", "\0"
+ VALUE "OriginalFilename", "tlen.dll\0"
+ VALUE "PrivateBuild", "\0"
+ VALUE "ProductName", "Tlen Protocol Plugin\0"
+ VALUE "ProductVersion", TLEN_VERSION_STRING
+ VALUE "SpecialBuild", "\0"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x415, 1251
+ END
+END
+
+#endif // !_MAC
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_TLEN ICON DISCARDABLE "icos/tlen.ico"
+IDI_MAIL ICON DISCARDABLE "icos/mail.ico"
+IDI_MUC ICON DISCARDABLE "icos/groupchats.ico"
+IDI_CHATS ICON DISCARDABLE "icos/tlenchats.ico"
+IDI_GRANT ICON DISCARDABLE "icos/auth_grant.ico"
+IDI_REQUEST ICON DISCARDABLE "icos/auth_request.ico"
+IDI_VOICE ICON DISCARDABLE "icos/voicechat.ico"
+IDI_MICROPHONE ICON DISCARDABLE "icos/microphone.ico"
+IDI_SPEAKER ICON DISCARDABLE "icos/speaker.ico"
+IDI_IMAGE ICON DISCARDABLE "icos/image.ico"
+#endif // English (U.S.) resources
+
+
+
diff --git a/protocols/Tlen/tlen_10.sln b/protocols/Tlen/tlen_10.sln
new file mode 100644
index 0000000000..cc8b9df98f
--- /dev/null
+++ b/protocols/Tlen/tlen_10.sln
@@ -0,0 +1,44 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual C++ Express 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tlen", "tlen_10.vcxproj", "{33276462-8313-4192-8306-13717ECCA60A}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug Ansi|Win32 = Debug Ansi|Win32
+ Debug Ansi|x64 = Debug Ansi|x64
+ Debug Unicode|Win32 = Debug Unicode|Win32
+ Debug Unicode|x64 = Debug Unicode|x64
+ Debug x64|Win32 = Debug x64|Win32
+ Debug x64|x64 = Debug x64|x64
+ Release Ansi|Win32 = Release Ansi|Win32
+ Release Ansi|x64 = Release Ansi|x64
+ Release Unicode|Win32 = Release Unicode|Win32
+ Release Unicode|x64 = Release Unicode|x64
+ Release x64|Win32 = Release x64|Win32
+ Release x64|x64 = Release x64|x64
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug Ansi|Win32.ActiveCfg = Debug Ansi|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug Ansi|Win32.Build.0 = Debug Ansi|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug Ansi|x64.ActiveCfg = Debug Ansi|x64
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug Unicode|Win32.ActiveCfg = Debug Unicode|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug Unicode|Win32.Build.0 = Debug Unicode|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug Unicode|x64.ActiveCfg = Debug Unicode|x64
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug x64|Win32.ActiveCfg = Debug x64|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug x64|x64.ActiveCfg = Debug x64|x64
+ {33276462-8313-4192-8306-13717ECCA60A}.Debug x64|x64.Build.0 = Debug x64|x64
+ {33276462-8313-4192-8306-13717ECCA60A}.Release Ansi|Win32.ActiveCfg = Release Ansi|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Release Ansi|Win32.Build.0 = Release Ansi|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Release Ansi|x64.ActiveCfg = Release Ansi|x64
+ {33276462-8313-4192-8306-13717ECCA60A}.Release Unicode|Win32.ActiveCfg = Release Unicode|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Release Unicode|Win32.Build.0 = Release Unicode|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Release Unicode|x64.ActiveCfg = Release Unicode|x64
+ {33276462-8313-4192-8306-13717ECCA60A}.Release x64|Win32.ActiveCfg = Release x64|Win32
+ {33276462-8313-4192-8306-13717ECCA60A}.Release x64|x64.ActiveCfg = Release x64|x64
+ {33276462-8313-4192-8306-13717ECCA60A}.Release x64|x64.Build.0 = Release x64|x64
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/protocols/Tlen/tlen_10.vcxproj b/protocols/Tlen/tlen_10.vcxproj
new file mode 100644
index 0000000000..606d56b8d8
--- /dev/null
+++ b/protocols/Tlen/tlen_10.vcxproj
@@ -0,0 +1,928 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug Ansi|x64">
+ <Configuration>Debug Ansi</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug Unicode|Win32">
+ <Configuration>Debug Unicode</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug Unicode|x64">
+ <Configuration>Debug Unicode</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug x64|Win32">
+ <Configuration>Debug x64</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug Ansi|Win32">
+ <Configuration>Debug Ansi</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug x64|x64">
+ <Configuration>Debug x64</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Ansi|x64">
+ <Configuration>Release Ansi</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Unicode|Win32">
+ <Configuration>Release Unicode</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Unicode|x64">
+ <Configuration>Release Unicode</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release x64|Win32">
+ <Configuration>Release x64</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Ansi|Win32">
+ <Configuration>Release Ansi</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release x64|x64">
+ <Configuration>Release x64</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectName>tlen</ProjectName>
+ <ProjectGuid>{33276462-8313-4192-8306-13717ECCA60A}</ProjectGuid>
+ <RootNamespace>jabber</RootNamespace>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup>
+ <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">true</IgnoreImportLibrary>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">true</IgnoreImportLibrary>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">true</IgnoreImportLibrary>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">$(SolutionDir)$(Configuration)/Plugins\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">$(SolutionDir)$(Configuration)/Obj/$(ProjectName)\</IntDir>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">true</IgnoreImportLibrary>
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Debug/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <GenerateMapFile>false</GenerateMapFile>
+ <MapFileName>
+ </MapFileName>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Debug/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <GenerateMapFile>false</GenerateMapFile>
+ <MapFileName>
+ </MapFileName>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Release/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalOptions>/ALIGN:4096 /ignore:4108 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <GenerateMapFile>false</GenerateMapFile>
+ <MapFileName>
+ </MapFileName>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Release/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalOptions>/ALIGN:4096 /ignore:4108 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <GenerateMapFile>false</GenerateMapFile>
+ <MapFileName>
+ </MapFileName>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Release/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerOutput>AssemblyAndSourceCode</AssemblerOutput>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalOptions>/ALIGN:4096 /ignore:4108 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalManifestDependencies>type=%27Win32%27 name=%27Microsoft.Windows.Common-Controls%27 version=%276.0.0.0%27 processorArchitecture=%27X86%27 publicKeyToken=%276595b64144ccf1df%27 language=%27*%27;%(AdditionalManifestDependencies)</AdditionalManifestDependencies>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Release/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerOutput>AssemblyAndSourceCode</AssemblerOutput>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalOptions>/ALIGN:4096 /ignore:4108 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalManifestDependencies>type=%27Win32%27 name=%27Microsoft.Windows.Common-Controls%27 version=%276.0.0.0%27 processorArchitecture=%27X86%27 publicKeyToken=%276595b64144ccf1df%27 language=%27*%27;%(AdditionalManifestDependencies)</AdditionalManifestDependencies>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Release/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_X64;X64;NDEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerOutput>AssemblyAndSourceCode</AssemblerOutput>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalOptions>/ALIGN:4096 /ignore:4108 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalManifestDependencies>type=%27Win32%27 name=%27Microsoft.Windows.Common-Controls%27 version=%276.0.0.0%27 processorArchitecture=%27X86%27 publicKeyToken=%276595b64144ccf1df%27 language=%27*%27;%(AdditionalManifestDependencies)</AdditionalManifestDependencies>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX64</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Release/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Full</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_X64;X64;NDEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerOutput>AssemblyAndSourceCode</AssemblerOutput>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalOptions>/ALIGN:4096 /ignore:4108 %(AdditionalOptions)</AdditionalOptions>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <AdditionalManifestDependencies>type=%27Win32%27 name=%27Microsoft.Windows.Common-Controls%27 version=%276.0.0.0%27 processorArchitecture=%27X86%27 publicKeyToken=%276595b64144ccf1df%27 language=%27*%27;%(AdditionalManifestDependencies)</AdditionalManifestDependencies>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <OptimizeReferences>true</OptimizeReferences>
+ <EnableCOMDATFolding>true</EnableCOMDATFolding>
+ <LinkTimeCodeGeneration>UseLinkTimeCodeGeneration</LinkTimeCodeGeneration>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Debug/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>false</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <FloatingPointModel>Precise</FloatingPointModel>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)$(TargetName).pdb</ProgramDatabaseFile>
+ <GenerateMapFile>false</GenerateMapFile>
+ <MapFileName>
+ </MapFileName>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Debug/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>false</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <FloatingPointModel>Precise</FloatingPointModel>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)$(TargetName).pdb</ProgramDatabaseFile>
+ <GenerateMapFile>false</GenerateMapFile>
+ <MapFileName>
+ </MapFileName>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Debug/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_X64;X64;_DEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>false</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <FloatingPointModel>Precise</FloatingPointModel>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)$(TargetName).pdb</ProgramDatabaseFile>
+ <GenerateMapFile>false</GenerateMapFile>
+ <MapFileName>
+ </MapFileName>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX64</TargetMachine>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Debug/jabber.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../include;./ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_X64;X64;_DEBUG;_WINDOWS;_USRDLL;JABBER_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>false</StringPooling>
+ <ExceptionHandling>
+ </ExceptionHandling>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <FloatingPointModel>Precise</FloatingPointModel>
+ <PrecompiledHeader>
+ </PrecompiledHeader>
+ <PrecompiledHeaderFile>jabber.h</PrecompiledHeaderFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <BrowseInformationFile>
+ </BrowseInformationFile>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <CompileAs>Default</CompileAs>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0409</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>wsock32.lib;version.lib;comctl32.lib;winmm.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)$(TargetName).pdb</ProgramDatabaseFile>
+ <GenerateMapFile>false</GenerateMapFile>
+ <MapFileName>
+ </MapFileName>
+ <BaseAddress>0x32500000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="crypto\aes.c" />
+ <ClCompile Include="crypto\bignum.c" />
+ <ClCompile Include="codec\gsm_codec.c" />
+ <ClCompile Include="codec\gsm_long.c" />
+ <ClCompile Include="codec\gsm_lpc.c" />
+ <ClCompile Include="codec\gsm_preprocess.c" />
+ <ClCompile Include="codec\gsm_rpe.c" />
+ <ClCompile Include="codec\gsm_short.c" />
+ <ClCompile Include="jabber_iq.c" />
+ <ClCompile Include="jabber_iqid.c" />
+ <ClCompile Include="jabber_list.c" />
+ <ClCompile Include="jabber_misc.c" />
+ <ClCompile Include="jabber_opt.c" />
+ <ClCompile Include="jabber_svc.c" />
+ <ClCompile Include="jabber_thread.c" />
+ <ClCompile Include="jabber_util.c" />
+ <ClCompile Include="jabber_ws.c" />
+ <ClCompile Include="jabber_xml.c" />
+ <ClCompile Include="crypto\padlock.c" />
+ <ClCompile Include="tlen.c" />
+ <ClCompile Include="tlen_advsearch.c" />
+ <ClCompile Include="tlen_avatar.c" />
+ <ClCompile Include="tlen_file.c" />
+ <ClCompile Include="tlen_muc.c" />
+ <ClCompile Include="tlen_p2p_new.c" />
+ <ClCompile Include="tlen_p2p_old.c" />
+ <ClCompile Include="tlen_picture.c" />
+ <ClCompile Include="tlen_presence.c" />
+ <ClCompile Include="tlen_userinfo.c" />
+ <ClCompile Include="tlen_voice.c" />
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="tlen.rc" />
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="commons.h" />
+ <ClInclude Include="crypto\polarssl\aes.h" />
+ <ClInclude Include="crypto\polarssl\bignum.h" />
+ <ClInclude Include="crypto\polarssl\bn_mul.h" />
+ <ClInclude Include="crypto\polarssl\config.h" />
+ <ClInclude Include="codec\gsm.h" />
+ <ClInclude Include="jabber.h" />
+ <ClInclude Include="jabber_iq.h" />
+ <ClInclude Include="jabber_list.h" />
+ <ClInclude Include="jabber_xml.h" />
+ <ClInclude Include="crypto\polarssl\padlock.h" />
+ <ClInclude Include="resource.h" />
+ <ClInclude Include="tlen_avatar.h" />
+ <ClInclude Include="tlen_file.h" />
+ <ClInclude Include="tlen_muc.h" />
+ <ClInclude Include="tlen_p2p_new.h" />
+ <ClInclude Include="tlen_p2p_old.h" />
+ <ClInclude Include="tlen_picture.h" />
+ <ClInclude Include="tlen_presence.h" />
+ <ClInclude Include="tlen_voice.h" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="icos\auth_grant.ico" />
+ <None Include="icos\auth_request.ico" />
+ <None Include="icos\groupchats.ico" />
+ <None Include="icos\image.ico" />
+ <None Include="icos\mail.ico" />
+ <None Include="icos\microphone.ico" />
+ <None Include="icos\speaker.ico" />
+ <None Include="icos\tlen.ico" />
+ <None Include="icos\tlenbig.ico" />
+ <None Include="icos\tlenchats.ico" />
+ <None Include="icos\tlensmall.ico" />
+ <None Include="icos\voicechat.ico" />
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project> \ No newline at end of file
diff --git a/protocols/Tlen/tlen_advsearch.c b/protocols/Tlen/tlen_advsearch.c
new file mode 100644
index 0000000000..5e3d5465b8
--- /dev/null
+++ b/protocols/Tlen/tlen_advsearch.c
@@ -0,0 +1,113 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "resource.h"
+
+static void InitComboBox(HWND hwndCombo, JABBER_FIELD_MAP *fieldMap)
+{
+ int i, n;
+
+ n = SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM)_T(""));
+ SendMessage(hwndCombo, CB_SETITEMDATA, n, 0);
+ SendMessage(hwndCombo, CB_SETCURSEL, n, 0);
+ for(i=0;;i++) {
+ if (fieldMap[i].name == NULL)
+ break;
+ n = SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM) TranslateTS(fieldMap[i].name));
+ SendMessage(hwndCombo, CB_SETITEMDATA, n, fieldMap[i].id);
+ }
+}
+
+INT_PTR CALLBACK TlenAdvSearchDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ switch(msg) {
+ case WM_INITDIALOG:
+ TranslateDialogDefault(hwndDlg);
+ InitComboBox(GetDlgItem(hwndDlg, IDC_GENDER), tlenFieldGender);
+ InitComboBox(GetDlgItem(hwndDlg, IDC_LOOKFOR), tlenFieldLookfor);
+ InitComboBox(GetDlgItem(hwndDlg, IDC_STATUS), tlenFieldStatus);
+ InitComboBox(GetDlgItem(hwndDlg, IDC_OCCUPATION), tlenFieldOccupation);
+ InitComboBox(GetDlgItem(hwndDlg, IDC_PLAN), tlenFieldPlan);
+ return TRUE;
+ }
+ return FALSE;
+}
+
+static void FetchField(HWND hwndDlg, UINT idCtrl, char *fieldName, char **str, int *strSize)
+{
+ char text[512];
+ char *localFieldName, *localText;
+
+ if (hwndDlg==NULL || fieldName==NULL || str==NULL || strSize==NULL)
+ return;
+ GetDlgItemTextA(hwndDlg, idCtrl, text, sizeof(text));
+ if (text[0]) {
+ if ((localFieldName=JabberTextEncode(fieldName)) != NULL) {
+ if ((localText=JabberTextEncode(text)) != NULL) {
+ JabberStringAppend(str, strSize, "<%s>%s</%s>", localFieldName, localText, localFieldName);
+ mir_free(localText);
+ }
+ mir_free(localFieldName);
+ }
+ }
+}
+
+static void FetchCombo(HWND hwndDlg, UINT idCtrl, char *fieldName, char **str, int *strSize)
+{
+ int value;
+ char *localFieldName;
+
+ if (hwndDlg==NULL || fieldName==NULL || str==NULL || strSize==NULL)
+ return;
+ value = (int) SendDlgItemMessage(hwndDlg, idCtrl, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, idCtrl, CB_GETCURSEL, 0, 0), 0);
+ if (value > 0) {
+ if ((localFieldName=JabberTextEncode(fieldName)) != NULL) {
+ JabberStringAppend(str, strSize, "<%s>%d</%s>", localFieldName, value, localFieldName);
+ mir_free(localFieldName);
+ }
+ }
+}
+
+char *TlenAdvSearchCreateQuery(HWND hwndDlg, int iqId)
+{
+ char *str;
+ int strSize;
+
+ if (hwndDlg == NULL) return NULL;
+ str = NULL;
+ FetchField(hwndDlg, IDC_FIRSTNAME, "first", &str, &strSize);
+ FetchField(hwndDlg, IDC_LASTNAME, "last", &str, &strSize);
+ FetchField(hwndDlg, IDC_NICK, "nick", &str, &strSize);
+ FetchField(hwndDlg, IDC_EMAIL, "email", &str, &strSize);
+ FetchCombo(hwndDlg, IDC_GENDER, "s", &str, &strSize);
+ FetchField(hwndDlg, IDC_AGEFROM, "d", &str, &strSize);
+ FetchField(hwndDlg, IDC_AGETO, "u", &str, &strSize);
+ FetchField(hwndDlg, IDC_CITY, "c", &str, &strSize);
+ FetchCombo(hwndDlg, IDC_OCCUPATION, "j", &str, &strSize);
+ FetchField(hwndDlg, IDC_SCHOOL, "e", &str, &strSize);
+ FetchCombo(hwndDlg, IDC_STATUS, "m", &str, &strSize);
+ FetchCombo(hwndDlg, IDC_LOOKFOR, "r", &str, &strSize);
+ FetchCombo(hwndDlg, IDC_PLAN, "p", &str, &strSize);
+ return str;
+}
diff --git a/protocols/Tlen/tlen_avatar.c b/protocols/Tlen/tlen_avatar.c
new file mode 100644
index 0000000000..e06c793344
--- /dev/null
+++ b/protocols/Tlen/tlen_avatar.c
@@ -0,0 +1,422 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include <stdio.h>
+#include "jabber.h"
+#include "jabber_list.h"
+#include "tlen_avatar.h"
+#include <io.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+/* TlenGetAvatarFileName() - gets a file name for the avatar image */
+
+void TlenGetAvatarFileName(TlenProtocol *proto, JABBER_LIST_ITEM *item, char* pszDest, int cbLen)
+{
+ DWORD dwAttributes;
+ int tPathLen;
+ int format = PA_FORMAT_PNG;
+ char* szFileType;
+ char *tmpPath = Utils_ReplaceVars( "%miranda_avatarcache%" );
+ tPathLen = mir_snprintf( pszDest, cbLen, "%s\\Tlen", tmpPath );
+ mir_free(tmpPath);
+ dwAttributes = GetFileAttributesA( pszDest );
+ if ( dwAttributes == 0xffffffff || ( dwAttributes & FILE_ATTRIBUTE_DIRECTORY ) == 0 ) {
+ CallService( MS_UTILS_CREATEDIRTREE, 0, ( LPARAM )pszDest );
+ }
+ pszDest[ tPathLen++ ] = '\\';
+ if (item != NULL) {
+ format = item->avatarFormat;
+ } else if (proto->threadData != NULL) {
+ format = proto->threadData->avatarFormat;
+ } else {
+ format = DBGetContactSettingDword(NULL, proto->iface.m_szModuleName, "AvatarFormat", PA_FORMAT_UNKNOWN);
+ }
+ szFileType = "png";
+ switch(format) {
+ case PA_FORMAT_JPEG: szFileType = "jpg"; break;
+ case PA_FORMAT_ICON: szFileType = "ico"; break;
+ case PA_FORMAT_PNG: szFileType = "png"; break;
+ case PA_FORMAT_GIF: szFileType = "gif"; break;
+ case PA_FORMAT_BMP: szFileType = "bmp"; break;
+ }
+ if ( item != NULL ) {
+ char* hash;
+ hash = JabberSha1(item->jid);
+ mir_snprintf( pszDest + tPathLen, MAX_PATH - tPathLen, "%s.%s", hash, szFileType );
+ mir_free( hash );
+ } else {
+ mir_snprintf( pszDest + tPathLen, MAX_PATH - tPathLen, "%s_avatar.%s", proto->iface.m_szModuleName, szFileType );
+ }
+}
+
+static void RemoveAvatar(TlenProtocol *proto, HANDLE hContact) {
+ char tFileName[ MAX_PATH ];
+ if (hContact == NULL) {
+ proto->threadData->avatarHash[0] = '\0';
+ }
+ TlenGetAvatarFileName( proto, NULL, tFileName, sizeof tFileName );
+ DeleteFileA(tFileName);
+ DBDeleteContactSetting(hContact, "ContactPhoto", "File");
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "AvatarHash");
+ DBDeleteContactSetting(hContact, proto->iface.m_szModuleName, "AvatarFormat");
+ ProtoBroadcastAck(proto->iface.m_szModuleName, NULL, ACKTYPE_AVATAR, ACKRESULT_STATUS, NULL, 0);
+}
+
+static void SetAvatar(TlenProtocol *proto, HANDLE hContact, JABBER_LIST_ITEM *item, char *data, int len, DWORD format) {
+ FILE* out;
+ char filename[MAX_PATH];
+ char md5[33];
+ mir_md5_state_t ctx;
+ DWORD digest[4];
+
+ if (format == PA_FORMAT_UNKNOWN && len > 4) {
+ format = JabberGetPictureType(data);
+ }
+
+ mir_md5_init( &ctx );
+ mir_md5_append( &ctx, ( BYTE* )data, len);
+ mir_md5_finish( &ctx, ( BYTE* )digest );
+
+ sprintf( md5, "%08x%08x%08x%08x", (int)htonl(digest[0]), (int)htonl(digest[1]), (int)htonl(digest[2]), (int)htonl(digest[3]));
+ if (item != NULL) {
+ char *hash = item->avatarHash;
+ item->avatarFormat = format;
+ item->avatarHash = mir_strdup(md5);
+ mir_free(hash);
+ } else {
+ proto->threadData->avatarFormat = format;
+ strcpy(proto->threadData->avatarHash, md5);
+ }
+ TlenGetAvatarFileName(proto, item, filename, sizeof filename );
+ DeleteFileA(filename);
+ out = fopen( filename, "wb" );
+ if ( out != NULL ) {
+ fwrite( data, len, 1, out );
+ fclose( out );
+ DBWriteContactSettingString(hContact, "ContactPhoto", "File", filename );
+ DBWriteContactSettingString(hContact, proto->iface.m_szModuleName, "AvatarHash", md5);
+ DBWriteContactSettingDword(hContact, proto->iface.m_szModuleName, "AvatarFormat", format);
+ }
+ ProtoBroadcastAck( proto->iface.m_szModuleName, hContact, ACKTYPE_AVATAR, ACKRESULT_STATUS, NULL , 0);
+}
+
+int TlenProcessAvatarNode(TlenProtocol *proto, XmlNode *avatarNode, JABBER_LIST_ITEM *item) {
+ XmlNode *aNode;
+ char *oldHash = NULL;
+ char *md5 = NULL, *type = NULL;
+ HANDLE hContact;
+ hContact = NULL;
+ if (item != NULL) {
+ if ((hContact=JabberHContactFromJID(proto, item->jid)) == NULL) return 0;
+ }
+ if (item == NULL) {
+ oldHash = proto->threadData->avatarHash;
+ } else {
+ oldHash = item->avatarHash;
+ }
+ if (avatarNode != NULL) {
+ aNode = JabberXmlGetChild(avatarNode, "a");
+ if (aNode != NULL) {
+ type = JabberXmlGetAttrValue(aNode, "type");
+ md5 = JabberXmlGetAttrValue(aNode, "md5");
+ }
+ }
+ if (md5 != NULL) {
+ /* check contact's avatar hash - md5 */
+ if (oldHash == NULL || strcmp(oldHash, md5)) {
+ if (item != NULL) {
+ item->newAvatarDownloading = TRUE;
+ }
+ TlenGetAvatar(proto, hContact);
+ return 1;
+ }
+ } else {
+ /* remove avatar */
+ if (oldHash != NULL) {
+ if (item != NULL) {
+ item->avatarHash = NULL;
+ mir_free(oldHash);
+ item->newAvatarDownloading = FALSE;
+ }
+ RemoveAvatar(proto, hContact);
+ return 1;
+ }
+ }
+ return 0;
+}
+
+void TlenProcessPresenceAvatar(TlenProtocol *proto, XmlNode *node, JABBER_LIST_ITEM *item) {
+ HANDLE hContact;
+ if ((hContact=JabberHContactFromJID(proto, item->jid)) == NULL) return;
+ TlenProcessAvatarNode(proto, JabberXmlGetChild(node, "avatar"), item);
+}
+
+
+static char *replaceTokens(const char *base, const char *uri, const char *login, const char* token, int type, int access) {
+ char *result;
+ int i, l, size;
+ l = (int)strlen(uri);
+ size = (int)strlen(base);
+ for (i = 0; i < l; ) {
+ if (!strncmp(uri + i, "^login^", 7)) {
+ size += (int)strlen(login);
+ i += 7;
+ } else if (!strncmp(uri + i, "^type^", 6)) {
+ size++;
+ i += 6;
+ } else if (!strncmp(uri + i, "^token^", 7)) {
+ size += (int)strlen(token);
+ i += 7;
+ } else if (!strncmp(uri + i, "^access^", 8)) {
+ size++;
+ i += 8;
+ } else {
+ size++;
+ i++;
+ }
+ }
+ result = (char *)mir_alloc(size +1);
+ strcpy(result, base);
+ size = (int)strlen(base);
+ for (i = 0; i < l; ) {
+ if (!strncmp(uri + i, "^login^", 7)) {
+ strcpy(result + size, login);
+ size += (int)strlen(login);
+ i += 7;
+ } else if (!strncmp(uri + i, "^type^", 6)) {
+ result[size++] = '0' + type;
+ i += 6;
+ } else if (!strncmp(uri + i, "^token^", 7)) {
+ strcpy(result + size, token);
+ size += (int)strlen(token);
+ i += 7;
+ } else if (!strncmp(uri + i, "^access^", 8)) {
+ result[size++] = '0' + access;
+ i += 8;
+ } else {
+ result[size++] = uri[i++];
+ }
+ }
+ result[size] = '\0';
+ return result;
+}
+
+
+static int getAvatarMutex = 0;
+
+typedef struct {
+ TlenProtocol *proto;
+ HANDLE hContact;
+} TLENGETAVATARTHREADDATA;
+
+static void TlenGetAvatarThread(void *ptr) {
+
+ JABBER_LIST_ITEM *item = NULL;
+ NETLIBHTTPREQUEST req;
+ NETLIBHTTPREQUEST *resp;
+ TLENGETAVATARTHREADDATA *data = (TLENGETAVATARTHREADDATA *)ptr;
+ HANDLE hContact = data->hContact;
+ char *request;
+ char *login = NULL;
+ if (hContact != NULL) {
+ char *jid = JabberJIDFromHContact(data->proto, hContact);
+ login = JabberNickFromJID(jid);
+ item = JabberListGetItemPtr(data->proto, LIST_ROSTER, jid);
+ mir_free(jid);
+ } else {
+ login = mir_strdup(data->proto->threadData->username);
+ }
+ if ((data->proto->threadData != NULL && hContact == NULL) || item != NULL) {
+ DWORD format = PA_FORMAT_UNKNOWN;
+ if (item!= NULL) {
+ item->newAvatarDownloading = TRUE;
+ }
+ request = replaceTokens(data->proto->threadData->tlenConfig.mailBase, data->proto->threadData->tlenConfig.avatarGet, login, data->proto->threadData->avatarToken, 0, 0);
+ ZeroMemory(&req, sizeof(req));
+ req.cbSize = sizeof(req);
+ req.requestType = data->proto->threadData->tlenConfig.avatarGetMthd;
+ req.flags = 0;
+ req.headersCount = 0;
+ req.headers = NULL;
+ req.dataLength = 0;
+ req.szUrl = request;
+ resp = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)data->proto->hNetlibUser, (LPARAM)&req);
+ if (item!= NULL) {
+ item->newAvatarDownloading = FALSE;
+ }
+ if (resp != NULL) {
+ if (resp->resultCode/100==2) {
+ if (resp->dataLength > 0) {
+ int i;
+ for (i=0; i<resp->headersCount; i++ ) {
+ if (strcmpi(resp->headers[i].szName, "Content-Type")==0) {
+ if (strcmpi(resp->headers[i].szValue, "image/png")==0) {
+ format = PA_FORMAT_PNG;
+ } else if (strcmpi(resp->headers[i].szValue, "image/x-png")==0) {
+ format = PA_FORMAT_PNG;
+ } else if (strcmpi(resp->headers[i].szValue, "image/jpeg")==0) {
+ format = PA_FORMAT_JPEG;
+ } else if (strcmpi(resp->headers[i].szValue, "image/jpg")==0) {
+ format = PA_FORMAT_JPEG;
+ } else if (strcmpi(resp->headers[i].szValue, "image/gif")==0) {
+ format = PA_FORMAT_GIF;
+ } else if (strcmpi(resp->headers[i].szValue, "image/bmp")==0) {
+ format = PA_FORMAT_BMP;
+ }
+ break;
+ }
+ }
+ SetAvatar(data->proto, hContact, item, resp->pData, resp->dataLength, format);
+ } else {
+ RemoveAvatar(data->proto, hContact);
+ }
+ }
+ CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, 0, (LPARAM)resp);
+ }
+ mir_free(request);
+ mir_free(login);
+ }
+ if (hContact == NULL) {
+ getAvatarMutex = 0;
+ }
+ mir_free(data);
+}
+
+void TlenGetAvatar(TlenProtocol *proto, HANDLE hContact) {
+ if (hContact == NULL) {
+ if (getAvatarMutex != 0) {
+ return;
+ }
+ getAvatarMutex = 1;
+ }
+ {
+ TLENGETAVATARTHREADDATA *data = (TLENGETAVATARTHREADDATA *)mir_alloc(sizeof(TLENGETAVATARTHREADDATA));
+ data->proto = proto;
+ data->hContact = hContact;
+ JabberForkThread(TlenGetAvatarThread, 0, data);
+ }
+}
+
+typedef struct {
+ TlenProtocol *proto;
+ NETLIBHTTPREQUEST *req;
+}TLENREMOVEAVATARTHREADDATA;
+
+static void TlenRemoveAvatarRequestThread(void *ptr) {
+ NETLIBHTTPREQUEST *resp;
+ TLENREMOVEAVATARTHREADDATA *data = ptr;
+ NETLIBHTTPREQUEST *req = (NETLIBHTTPREQUEST *)data->req;
+ resp = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)data->proto->hNetlibUser, (LPARAM)req);
+ mir_free(req->szUrl);
+ mir_free(req->headers);
+ mir_free(req->pData);
+ mir_free(req);
+ if (resp != NULL) {
+ CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, (WPARAM)0, (LPARAM)resp);
+ RemoveAvatar(data->proto, NULL);
+ }
+ mir_free(data);
+
+}
+
+typedef struct {
+ TlenProtocol *proto;
+ NETLIBHTTPREQUEST *req;
+ char *data;
+ int length;
+}TLENUPLOADAVATARTHREADDATA;
+
+static void TlenUploadAvatarRequestThread(void *ptr) {
+ NETLIBHTTPREQUEST *resp;
+ TLENUPLOADAVATARTHREADDATA * data = (TLENUPLOADAVATARTHREADDATA *) ptr;
+ NETLIBHTTPREQUEST *req = data->req;
+ resp = (NETLIBHTTPREQUEST *)CallService(MS_NETLIB_HTTPTRANSACTION, (WPARAM)data->proto->hNetlibUser, (LPARAM)req);
+ if (resp != NULL) {
+ CallService(MS_NETLIB_FREEHTTPREQUESTSTRUCT, (WPARAM)0, (LPARAM)resp);
+ SetAvatar(data->proto, NULL, NULL, data->data, data->length, PA_FORMAT_PNG);
+ }
+ mir_free(req->szUrl);
+ mir_free(req->headers);
+ mir_free(req->pData);
+ mir_free(req);
+ mir_free(data->data);
+ mir_free(data);
+}
+
+void TlenRemoveAvatar(TlenProtocol *proto) {
+ NETLIBHTTPREQUEST *req;
+ char *request;
+ if (proto->threadData != NULL) {
+ TLENREMOVEAVATARTHREADDATA *data = (TLENREMOVEAVATARTHREADDATA *)mir_alloc(sizeof(TLENREMOVEAVATARTHREADDATA));
+ req = (NETLIBHTTPREQUEST *)mir_alloc(sizeof(NETLIBHTTPREQUEST));
+ data->proto =proto;
+ data->req = req;
+ request = replaceTokens(proto->threadData->tlenConfig.mailBase, proto->threadData->tlenConfig.avatarRemove, "", proto->threadData->avatarToken, 0, 0);
+ ZeroMemory(req, sizeof(NETLIBHTTPREQUEST));
+ req->cbSize = sizeof(NETLIBHTTPREQUEST);
+ req->requestType = proto->threadData->tlenConfig.avatarGetMthd;
+ req->szUrl = request;
+ JabberForkThread(TlenRemoveAvatarRequestThread, 0, data);
+ }
+}
+
+
+void TlenUploadAvatar(TlenProtocol *proto, unsigned char *data, int dataLen, int access) {
+ NETLIBHTTPREQUEST *req;
+ NETLIBHTTPHEADER *headers;
+ TLENUPLOADAVATARTHREADDATA *threadData;
+ char *request;
+ unsigned char *buffer;
+ if (proto->threadData != NULL && dataLen > 0 && data != NULL) {
+ char *mpartHead = "--AaB03x\r\nContent-Disposition: form-data; name=\"filename\"; filename=\"plik.png\"\r\nContent-Type: image/png\r\n\r\n";
+ char *mpartTail = "\r\n--AaB03x--\r\n";
+ int size, sizeHead = (int)strlen(mpartHead), sizeTail = (int)strlen(mpartTail);
+ request = replaceTokens(proto->threadData->tlenConfig.mailBase, proto->threadData->tlenConfig.avatarUpload, "", proto->threadData->avatarToken, 0, access);
+ threadData = (TLENUPLOADAVATARTHREADDATA *)mir_alloc(sizeof(TLENUPLOADAVATARTHREADDATA));
+ threadData->proto = proto;
+ req = (NETLIBHTTPREQUEST *)mir_alloc(sizeof(NETLIBHTTPREQUEST));
+ headers = (NETLIBHTTPHEADER *)mir_alloc(sizeof(NETLIBHTTPHEADER));
+ ZeroMemory(req, sizeof(NETLIBHTTPREQUEST));
+ req->cbSize = sizeof(NETLIBHTTPREQUEST);
+ req->requestType = proto->threadData->tlenConfig.avatarUploadMthd;
+ req->szUrl = request;
+ req->flags = 0;
+ headers[0].szName = "Content-Type";
+ headers[0].szValue = "multipart/form-data; boundary=AaB03x";
+ req->headersCount = 1;
+ req->headers = headers;
+ size = dataLen + sizeHead + sizeTail;
+ buffer = mir_alloc(size);
+ memcpy(buffer, mpartHead, sizeHead);
+ memcpy(buffer + sizeHead, data, dataLen);
+ memcpy(buffer + sizeHead + dataLen, mpartTail, sizeTail);
+ req->dataLength = size;
+ req->pData = buffer;
+ threadData->req = req;
+ threadData->data = (char *) mir_alloc(dataLen);
+ memcpy(threadData->data, data, dataLen);
+ threadData->length = dataLen;
+ JabberForkThread(TlenUploadAvatarRequestThread, 0, threadData);
+ }
+}
+
diff --git a/protocols/Tlen/tlen_avatar.h b/protocols/Tlen/tlen_avatar.h
new file mode 100644
index 0000000000..48a258ed38
--- /dev/null
+++ b/protocols/Tlen/tlen_avatar.h
@@ -0,0 +1,34 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#ifndef _TLEN_AVATAR_H_
+#define _TLEN_AVATAR_H_
+
+void TlenProcessPresenceAvatar(TlenProtocol *proto, XmlNode *node, JABBER_LIST_ITEM *item);
+int TlenProcessAvatarNode(TlenProtocol *proto, XmlNode *avatarNode, JABBER_LIST_ITEM *item);
+void TlenGetAvatarFileName(TlenProtocol *proto, JABBER_LIST_ITEM *item, char* pszDest, int cbLen);
+void TlenGetAvatar(TlenProtocol *proto, HANDLE hContact);
+void TlenUploadAvatar(TlenProtocol *proto, unsigned char *data, int dataLen, int access);
+void TlenRemoveAvatar(TlenProtocol *proto);
+
+#endif // TLEN_AVATAR_H_INCLUDED
diff --git a/protocols/Tlen/tlen_czaty/AdminWindow.cpp b/protocols/Tlen/tlen_czaty/AdminWindow.cpp
new file mode 100644
index 0000000000..a29c6fa2f2
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/AdminWindow.cpp
@@ -0,0 +1,490 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "AdminWindow.h"
+#include "Utils.h"
+
+
+static INT_PTR CALLBACK UserKickDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ int i;
+ const char *banOptions[]={"No ban", "1 minute", "5 minutes", "15 minutes", "30 minutes",
+ "1 hour", "6 hours", "1 day", "3 days", "1 week", "2 weeks", "4 weeks"};
+ const int banTime[] = {0, 1, 5, 15, 30, 60, 360, 1440, 4320, 10080, 20160, 40320};
+ const char *roleOptions[]={"No role", "Member", "Admin", "Moderator"};
+ const int roleMask[] = {0, MUCC_EF_USER_MEMBER, MUCC_EF_USER_ADMIN, MUCC_EF_USER_MODERATOR};
+ AdminWindow *adminWindow;
+ adminWindow = (AdminWindow *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ adminWindow = (AdminWindow *) lParam;
+ TranslateDialogDefault(hwndDlg);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) adminWindow);
+ adminWindow->setKickTabHWND(hwndDlg);
+ for (i=0;i<12;i++) {
+ SendDlgItemMessage(hwndDlg, IDC_KICK_OPTIONS, CB_ADDSTRING, 0, (LPARAM) banOptions[i]);
+ }
+ SendDlgItemMessage(hwndDlg, IDC_KICK_OPTIONS, CB_SETCURSEL, 0, 0);
+ for (i=0;i<3;i++) {
+ SendDlgItemMessage(hwndDlg, IDC_ROLE_OPTIONS, CB_ADDSTRING, 0, (LPARAM) roleOptions[i]);
+ }
+ SendDlgItemMessage(hwndDlg, IDC_ROLE_OPTIONS, CB_SETCURSEL, 0, 0);
+ SetDlgItemTextA(hwndDlg, IDC_NICK, adminWindow->getNick());
+ return FALSE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDOK:
+ {
+ char nick[256], reason[256];
+ GetDlgItemTextA(hwndDlg, IDC_NICK, nick, sizeof(nick));
+ GetDlgItemTextA(hwndDlg, IDC_REASON, reason, sizeof(reason));
+ if (strlen(nick)>0) {
+ int iSel = SendDlgItemMessage(hwndDlg, IDC_KICK_OPTIONS, CB_GETCURSEL, 0, 0);
+ if (iSel>=0 && iSel<12) {
+ adminWindow->getParent()->kickAndBan(nick, banTime[iSel] * 60, reason);
+ }
+ }
+ }
+// EndDialog(hwndDlg, 1);
+// return TRUE;
+ break;
+ case IDC_SET_ROLE:
+ {
+ char nick[256];
+ GetDlgItemTextA(hwndDlg, IDC_NICK, nick, sizeof(nick));
+ if (strlen(nick)>0) {
+ int iSel = SendDlgItemMessage(hwndDlg, IDC_ROLE_OPTIONS, CB_GETCURSEL, 0, 0);
+ if (iSel>=0 && iSel<3) {
+ adminWindow->getParent()->setRights(nick, roleMask[iSel]);
+ }
+ }
+ }
+ break;
+// EndDialog(hwndDlg, 1);
+// return TRUE;
+ case IDCANCEL:
+// EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+// EndDialog(hwndDlg, 0);
+ break;
+ }
+ return FALSE;
+}
+
+static INT_PTR CALLBACK UserBrowserDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{ int i;
+ const char *browseOptions[]={"Banned", "Owners", "Administrators", "Members", "Moderators"};
+ const int browserFlags[]={MUCC_EF_USER_BANNED, MUCC_EF_USER_OWNER, MUCC_EF_USER_ADMIN, MUCC_EF_USER_MEMBER, MUCC_EF_USER_MODERATOR};
+ LVCOLUMN lvCol;
+ HWND lv;
+ AdminWindow *adminWindow;
+ adminWindow = (AdminWindow *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ adminWindow = (AdminWindow *) lParam;
+ TranslateDialogDefault(hwndDlg);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) adminWindow);
+ adminWindow->setBrowserTabHWND(hwndDlg);
+ lv = GetDlgItem(hwndDlg, IDC_LIST);
+ ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT);
+ lvCol.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM;
+ lvCol.pszText = TranslateT("Login");
+ lvCol.cx = 80;
+ lvCol.iSubItem = 0;
+ ListView_InsertColumn(lv, 0, &lvCol);
+ lvCol.pszText = TranslateT("Nick name");
+ lvCol.cx = 80;
+ lvCol.iSubItem = 1;
+ ListView_InsertColumn(lv, 1, &lvCol);
+ lvCol.pszText = TranslateT("When");
+ lvCol.cx = 95;
+ lvCol.iSubItem = 2;
+ ListView_InsertColumn(lv, 2, &lvCol);
+ lvCol.pszText = TranslateT("Admin");
+ lvCol.cx = 80;
+ lvCol.iSubItem = 2;
+ ListView_InsertColumn(lv, 3, &lvCol);
+ lvCol.pszText = TranslateT("Reason");
+ lvCol.cx = 70;
+ lvCol.iSubItem = 2;
+ ListView_InsertColumn(lv, 5, &lvCol);
+ lvCol.pszText = TranslateT("Remaining");
+ lvCol.cx = 80;
+ lvCol.iSubItem = 2;
+ ListView_InsertColumn(lv, 4, &lvCol);
+ for (i=0;i<(adminWindow->getParent()->getRoomFlags() & MUCC_EF_ROOM_MEMBERS_ONLY ? 4 : 3);i++) {
+ SendDlgItemMessage(hwndDlg, IDC_OPTIONS, CB_ADDSTRING, 0, (LPARAM) browseOptions[i]);
+ }
+ SendDlgItemMessage(hwndDlg, IDC_OPTIONS, CB_SETCURSEL, 0, 0);
+ return FALSE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_SHOW:
+ int iSel;
+ iSel = SendDlgItemMessage(hwndDlg, IDC_OPTIONS, CB_GETCURSEL, 0, 0);
+ if (iSel< 5) {
+ adminWindow->queryUsers(browserFlags[iSel]);
+ }
+ break;
+// return TRUE;
+ case IDCANCEL:
+// EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+// EndDialog(hwndDlg, 0);
+ break;
+ case WM_MEASUREITEM:
+ if (wParam == IDC_LIST) {
+ MEASUREITEMSTRUCT *lpMis = (MEASUREITEMSTRUCT *) lParam;
+ lpMis->itemHeight = 16;//GetSystemMetrics(SM_CYSMICON);
+ return TRUE;
+ }
+ break;
+ case WM_DRAWITEM:
+ if (wParam == IDC_LIST) {
+ RECT rc;
+ int x, w;
+ TCHAR text[256];
+ DRAWITEMSTRUCT *lpDis = (DRAWITEMSTRUCT *) lParam;
+ switch (lpDis->itemAction) {
+ default:
+ case ODA_SELECT:
+ case ODA_DRAWENTIRE:
+ if (lpDis->itemState & ODS_SELECTED) {
+ HBRUSH hBrush = CreateSolidBrush(RGB(0xC2, 0xC8, 0xDA));//0xDAC8C2);
+ FillRect(lpDis->hDC, &(lpDis->rcItem), hBrush);//(HBRUSH) (COLOR_HIGHLIGHT+1));
+ DeleteObject(hBrush);
+ SetTextColor(lpDis->hDC, 0);
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ }
+ else {
+ FillRect(lpDis->hDC, &(lpDis->rcItem), (HBRUSH) (COLOR_WINDOW+1));
+ SetTextColor(lpDis->hDC, RGB(0, 0, 0));//GetSysColor(COLOR_WINDOWTEXT));
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ }
+ x = lpDis->rcItem.left + 1;
+ for (int col=0;col<6;col++) {
+ w = ListView_GetColumnWidth(GetDlgItem(hwndDlg, IDC_LIST), col);
+ rc.left = x;
+ rc.top = lpDis->rcItem.top;
+ rc.bottom = lpDis->rcItem.bottom;
+ rc.right = x+w-2;
+ ListView_GetItemText(GetDlgItem(hwndDlg, IDC_LIST), lpDis->itemID, col, text, sizeof(text)/sizeof(TCHAR));
+ if (_tcslen(text)==0) {
+ _tcscpy(text, _TEXT("-"));
+ }
+ DrawText(lpDis->hDC, text, (int)_tcslen(text), &rc, DT_LEFT|DT_NOPREFIX|DT_SINGLELINE|DT_VCENTER);
+ x+=w;
+ }
+ break;
+ }
+ }
+ break;
+ case WM_NOTIFY:
+ LPNMHDR pNmhdr;
+ pNmhdr = (LPNMHDR)lParam;
+ if (pNmhdr->idFrom == IDC_LIST && adminWindow->getBrowserMode() == MUCC_EF_USER_BANNED) {
+ switch (pNmhdr->code) {
+ case NM_RCLICK:
+ {
+ LVHITTESTINFO hti;
+ int hitItem;
+ hti.pt.x=(short)LOWORD(GetMessagePos());
+ hti.pt.y=(short)HIWORD(GetMessagePos());
+ ScreenToClient(pNmhdr->hwndFrom, &hti.pt);
+ if ((hitItem = ListView_HitTest(pNmhdr->hwndFrom,&hti)) !=-1) {
+ LVITEM lvi = {0};
+ HMENU hMenu;
+ int iSelection;
+ TCHAR nick[256];
+ lvi.mask = TVIF_TEXT;
+ lvi.iItem = hitItem;
+ lvi.iSubItem = 0;
+ lvi.pszText = nick;
+ lvi.cchTextMax = sizeof(nick)/sizeof(TCHAR);
+ ListView_GetItem(pNmhdr->hwndFrom, &lvi);
+ hMenu=GetSubMenu(LoadMenu(hInst, MAKEINTRESOURCE(IDR_CHATOPTIONS)), 3);
+ CallService(MS_LANGPACK_TRANSLATEMENU,(WPARAM)hMenu,0);
+ iSelection = TrackPopupMenu(hMenu, TPM_RETURNCMD | TPM_TOPALIGN | TPM_LEFTALIGN, (short)LOWORD(GetMessagePos()), (short)HIWORD(GetMessagePos()), 0, hwndDlg, NULL);
+ DestroyMenu(hMenu);
+ if (iSelection == ID_USERMENU_UNBAN) {
+ char* lps1 = Utils::mucc_mir_t2a(nick);
+ adminWindow->getParent()->unban(lps1);
+ Utils::mucc_mir_free(lps1);
+ }
+ }
+
+ }
+ break;
+ }
+ }
+
+ }
+ return FALSE;
+}
+
+static INT_PTR CALLBACK AdminDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ HWND hwnd;
+ TCITEM tci;
+ HWND tc;
+ AdminWindow *adminWindow;
+ adminWindow = (AdminWindow *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ adminWindow = (AdminWindow *) lParam;
+ TranslateDialogDefault(hwndDlg);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) adminWindow);
+ SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM) muccIcon[MUCC_IDI_ADMINISTRATION]);
+
+ hwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_USER_KICK), hwndDlg, UserKickDlgProc, (LPARAM) adminWindow);
+ SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
+ ShowWindow(hwnd, SW_SHOW);
+
+ hwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_USER_BROWSER), hwndDlg, UserBrowserDlgProc, (LPARAM) adminWindow);
+ SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
+ adminWindow->setCurrentTab(0);
+ adminWindow->setHWND(hwndDlg);
+
+ tc = GetDlgItem(hwndDlg, IDC_TABS);
+ tci.mask = TCIF_TEXT;
+ tci.pszText = TranslateT("Administration");
+ TabCtrl_InsertItem(tc, 0, &tci);
+ tci.pszText = TranslateT("Browser");
+ TabCtrl_InsertItem(tc, 1, &tci);
+
+ return FALSE;
+ case WM_NOTIFY:
+ switch (wParam) {
+ case IDC_TABS:
+ switch (((LPNMHDR) lParam)->code) {
+ case TCN_SELCHANGE:
+ switch (adminWindow->getCurrentTab()) {
+ case 0:
+ ShowWindow(adminWindow->getKickTabHWND(), SW_HIDE);
+ break;
+ case 1:
+ ShowWindow(adminWindow->getBrowserTabHWND(), SW_HIDE);
+ break;
+ }
+ adminWindow->setCurrentTab(TabCtrl_GetCurSel(GetDlgItem(hwndDlg, IDC_TABS)));
+ switch (adminWindow->getCurrentTab()) {
+ case 0:
+ ShowWindow(adminWindow->getKickTabHWND(), SW_SHOW);
+ break;
+ case 1:
+ ShowWindow(adminWindow->getBrowserTabHWND(), SW_SHOW);
+ break;
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDCANCEL:
+ delete adminWindow;
+ // EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+ delete adminWindow;
+ // EndDialog(hwndDlg, 0);
+ break;
+ }
+ return FALSE;
+}
+
+
+
+AdminWindow::AdminWindow(ChatWindow *parent, const char *nick, int mode) {
+ this->parent = parent;
+ hWnd = NULL;
+ browserMode = 0;
+ this->nick = NULL;
+ Utils::copyString(&this->nick, nick);
+}
+
+AdminWindow::~AdminWindow() {
+
+ if (hWnd != NULL) {
+ EndDialog(hWnd, 0);
+ }
+ if (parent != NULL) {
+ parent->setAdminWindow(NULL);
+ }
+ if (nick != NULL) {
+ delete nick;
+ }
+}
+
+void AdminWindow::start() {
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_USER_ADMIN), NULL, AdminDlgProc, (LPARAM) this);
+}
+
+void AdminWindow::setHWND(HWND hWnd) {
+ this->hWnd = hWnd;
+}
+
+void AdminWindow::setCurrentTab(int t) {
+ currentTab = t;
+}
+
+int AdminWindow::getCurrentTab() {
+ return currentTab;
+}
+
+
+void AdminWindow::setKickTabHWND(HWND hWnd) {
+ hKickTabWnd = hWnd;
+}
+
+void AdminWindow::setBrowserTabHWND(HWND hWnd) {
+ hBrowserTabWnd = hWnd;
+}
+
+HWND AdminWindow::getKickTabHWND() {
+ return hKickTabWnd;
+}
+
+HWND AdminWindow::getBrowserTabHWND() {
+ return hBrowserTabWnd;
+}
+
+void AdminWindow::queryUsers(int queryType) {
+ MUCCEVENT muce;
+ EnableWindow(GetDlgItem(getBrowserTabHWND(), IDC_SHOW), FALSE);
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_QUERY_USERS;
+ muce.pszModule = parent->getModule();
+ muce.pszID = parent->getRoomId();
+ muce.dwFlags = queryType;
+ browserMode = queryType;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+}
+
+ChatWindow * AdminWindow::getParent() {
+ return parent;
+}
+
+void AdminWindow::queryResultUsers(MUCCQUERYRESULT *queryResult) {
+ ListView_DeleteAllItems(GetDlgItem(getBrowserTabHWND(), IDC_LIST));
+ for (int i=0;i<queryResult->iItemsNum;i++) {
+
+ char timestampStr[100];
+ DBTIMETOSTRING dbtts;
+ LVITEM lvItem;
+
+ lvItem.mask = LVIF_TEXT;// | LVIF_PARAM;
+ lvItem.iSubItem = 0;
+ lvItem.iItem = ListView_GetItemCount(GetDlgItem(getBrowserTabHWND(), IDC_LIST));
+ lvItem.pszText = Utils::mucc_mir_a2t(queryResult->pItems[i].pszID);
+ if (lvItem.pszText == NULL) lvItem.pszText = _TEXT("");
+// lvItem.lParam = (LPARAM) room;
+ ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
+ Utils::mucc_mir_free(lvItem.pszText);
+
+ lvItem.iSubItem = 1;
+ lvItem.pszText = Utils::mucc_mir_a2t(queryResult->pItems[i].pszName);
+ if (lvItem.pszText == NULL) lvItem.pszText = _TEXT("");
+ ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
+ ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
+ Utils::mucc_mir_free(lvItem.pszText);
+
+ lvItem.iSubItem = 2;
+ dbtts.cbDest = 90;
+ dbtts.szDest = timestampStr;
+ dbtts.szFormat = (char *)"d t";
+ timestampStr[0]='\0';
+ if (queryResult->pItems[i].dwFlags) {
+ CallService(MS_DB_TIME_TIMESTAMPTOSTRING, (WPARAM)queryResult->pItems[i].dwFlags, (LPARAM) & dbtts);
+ }
+ lvItem.pszText = Utils::mucc_mir_a2t(timestampStr);
+ if (lvItem.pszText == NULL) lvItem.pszText = _TEXT("");
+ ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
+ ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
+ Utils::mucc_mir_free(lvItem.pszText);
+
+ lvItem.iSubItem = 3;
+ lvItem.pszText = Utils::mucc_mir_a2t(queryResult->pItems[i].pszNick);
+ if (lvItem.pszText == NULL) lvItem.pszText = _TEXT("");
+ ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
+ ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
+ Utils::mucc_mir_free(lvItem.pszText);
+
+ lvItem.iSubItem = 4;
+ timestampStr[0] = '\0';
+ if (queryResult->pItems[i].iCount > 0) {
+ int days = queryResult->pItems[i].iCount / (60*60*24);
+ int hours = (queryResult->pItems[i].iCount % (60*60*24)) / (60*60);
+ int minutes = (queryResult->pItems[i].iCount % (60*60)) / 60;
+ int seconds = queryResult->pItems[i].iCount % 60;
+ if (days != 0) {
+ sprintf(timestampStr, "%dd%dh%dm%ds", days, hours, minutes, seconds);
+ } else if (hours != 0) {
+ sprintf(timestampStr, "%dh%dm%ds", hours, minutes, seconds);
+ } else if (minutes != 0) {
+ sprintf(timestampStr, "%dm%ds", minutes, seconds);
+ } else {
+ sprintf(timestampStr, "%ds", seconds);
+ }
+ }
+ lvItem.pszText = Utils::mucc_mir_a2t(timestampStr);
+ if (lvItem.pszText == NULL) lvItem.pszText = _TEXT("");
+ ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
+ ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
+ Utils::mucc_mir_free(lvItem.pszText);
+
+ lvItem.iSubItem = 5;
+ lvItem.pszText = Utils::mucc_mir_a2t(queryResult->pItems[i].pszText);
+ if (lvItem.pszText == NULL) lvItem.pszText = _TEXT("");
+ ListView_InsertItem(GetDlgItem(getBrowserTabHWND(), IDC_LIST), &lvItem);
+ ListView_SetItemText(GetDlgItem(getBrowserTabHWND(), IDC_LIST), lvItem.iItem, lvItem.iSubItem, lvItem.pszText);
+ Utils::mucc_mir_free(lvItem.pszText);
+
+/*
+ ptr = new HelperContact(queryResult->pItems[i].pszID, queryResult->pItems[i].pszName);
+ if (lastptr !=NULL) {
+ lastptr->setNext(ptr);
+ } else {
+ contactList=ptr;
+ }
+ lastptr=ptr;
+
+ */
+ }
+ EnableWindow(GetDlgItem(getBrowserTabHWND(), IDC_SHOW), TRUE);
+}
+
+const char *AdminWindow::getNick() {
+ return nick;
+}
+
+int AdminWindow::getBrowserMode() {
+ return browserMode;
+}
diff --git a/protocols/Tlen/tlen_czaty/AdminWindow.h b/protocols/Tlen/tlen_czaty/AdminWindow.h
new file mode 100644
index 0000000000..a73cdb9285
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/AdminWindow.h
@@ -0,0 +1,63 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+class AdminWindow;
+#ifndef ADMINWINDOW_INCLUDED
+#define ADMINWINDOW_INCLUDED
+
+#include "mucc.h"
+#include "ChatWindow.h"
+
+class AdminWindow {
+private:
+ HWND hWnd;
+ HWND hKickTabWnd, hBrowserTabWnd;
+ int currentTab;
+ int browserMode;
+ ChatWindow *parent;
+ char *nick;
+public:
+ enum BROWSER_MODE {
+ BROWSE_BANNED = 1,
+ BROWSE_OWNERS = 2,
+ BROWSE_ADMINS = 3,
+ BROWSE_MEMBERS = 4,
+ BROWSE_MODERATORS = 5
+ };
+ AdminWindow (ChatWindow *parent, const char *nick, int mode);
+ ~AdminWindow();
+ void start();
+ void setHWND(HWND);
+ void setKickTabHWND(HWND);
+ void setBrowserTabHWND(HWND);
+ HWND getKickTabHWND();
+ HWND getBrowserTabHWND();
+ int getCurrentTab();
+ int getBrowserMode();
+ void setCurrentTab(int);
+ void queryUsers(int);
+ ChatWindow* getParent();
+ const char *getNick();
+ void queryResultUsers(MUCCQUERYRESULT *queryResult);
+};
+
+#endif
+
diff --git a/protocols/Tlen/tlen_czaty/ChatContainer.cpp b/protocols/Tlen/tlen_czaty/ChatContainer.cpp
new file mode 100644
index 0000000000..11e523e337
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatContainer.cpp
@@ -0,0 +1,480 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "ChatContainer.h"
+#include "Utils.h"
+#include "Options.h"
+
+#define DM_CREATECHILD (WM_USER+10)
+#define DM_ADDCHILD (WM_USER+11)
+#define DM_ACTIVATECHILD (WM_USER+12)
+#define DM_CHANGECHILDDATA (WM_USER+13)
+#define DM_REMOVECHILD (WM_USER+14)
+
+#define DM_SETUNREAD (WM_USER+15)
+#define DM_FLASHWINDOW (WM_USER+16)
+
+#define TIMERID_FLASHWND 1
+#define TIMEOUT_FLASHWND 900
+
+ChatContainer * ChatContainer::list = NULL;
+bool ChatContainer::released = false;
+CRITICAL_SECTION ChatContainer::mutex;
+
+//BOOL CALLBACK ContainerDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static void __cdecl StartThread(void *vContainer);
+
+void ChatContainer::release() {
+ released = true;
+ for (ChatContainer *ptr2, *ptr = list; ptr!=NULL; ptr=ptr2) {
+ ptr2 = ptr->getNext();
+ SendMessage(ptr->getHWND(), WM_CLOSE, 0, 0);
+ }
+ DeleteCriticalSection(&mutex);
+}
+
+void ChatContainer::init() {
+ released = false;
+ InitializeCriticalSection(&mutex);
+}
+
+int ChatContainer::getDefaultOptions() {
+ return FLAG_USE_TABS;
+}
+
+ChatContainer * ChatContainer::getWindow() {
+ ChatContainer *ptr;
+ EnterCriticalSection(&mutex);
+ if (list == NULL || !(Options::getChatContainerOptions() & ChatContainer::FLAG_USE_TABS)) {
+ ptr = new ChatContainer();
+ } else {
+ ptr = list;
+ }
+ LeaveCriticalSection(&mutex);
+ return ptr;
+}
+
+ChatContainer::ChatContainer() {
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ hWnd = NULL;
+ prev = next =NULL;
+ active = NULL;
+ childCount = 0;
+ nFlash = 0;
+ nFlashMax = 3;
+ Utils::forkThread((void (__cdecl *)(void *))StartThread, 0, (void *) this);
+ WaitForSingleObject(hEvent, INFINITE);
+ EnterCriticalSection(&mutex);
+ setNext(list);
+ if (next!=NULL) {
+ next->setPrev(this);
+ }
+ list = this;
+ LeaveCriticalSection(&mutex);
+}
+
+ChatContainer::~ChatContainer() {
+ if (!released) {
+ EnterCriticalSection(&mutex);
+ if (getPrev()!=NULL) {
+ getPrev()->setNext(next);
+ } else if (list==this) {
+ list = getNext();
+ }
+ if (getNext()!=NULL) {
+ getNext()->setPrev(prev);
+ }
+ LeaveCriticalSection(&mutex);
+ }
+ if (hEvent!=NULL) {
+ CloseHandle(hEvent);
+ }
+}
+
+void ChatContainer::setHWND(HWND hWnd) {
+ this->hWnd = hWnd;
+}
+
+HWND ChatContainer::getHWND() {
+ return hWnd;
+}
+
+HANDLE ChatContainer::getEvent() {
+ return hEvent;
+}
+
+ChatContainer * ChatContainer::getNext() {
+ return next;
+}
+
+void ChatContainer::setNext(ChatContainer * next) {
+ this->next = next;
+}
+
+ChatContainer * ChatContainer::getPrev() {
+ return prev;
+}
+
+void ChatContainer::setPrev(ChatContainer * prev) {
+ this->prev = prev;
+}
+
+void ChatContainer::show(bool bShow) {
+ ShowWindow(hWnd, bShow ? SW_SHOW : SW_HIDE);
+}
+
+ChatWindow * ChatContainer::getActive() {
+ return active;
+}
+
+int ChatContainer::getFlash() {
+ return nFlash;
+}
+
+int ChatContainer::getFlashMax() {
+ return nFlashMax;
+}
+
+int ChatContainer::getFlashTimeout() {
+ return TIMEOUT_FLASHWND;
+}
+
+void ChatContainer::setFlash(int n) {
+ nFlash = n;
+}
+
+void ChatContainer::activateChild(ChatWindow *window) {
+ RECT rcChild;
+ getChildWindowRect(&rcChild);
+ if (window!=NULL) {
+ SetWindowPos(window->getHWND(), HWND_TOP, rcChild.left, rcChild.top, rcChild.right-rcChild.left, rcChild.bottom - rcChild.top, SWP_NOSIZE);
+ }
+ if(window != active) {
+ ChatWindow *prev = active;
+ active = window;
+ SendMessage(hWnd, WM_SIZE, 0, 0);
+ ShowWindow(active->getHWND(), SW_SHOW);
+// SendMessage(active->getHWND(), DM_UPDATETITLE, 0, 0);
+ if (prev!=NULL) {
+ ShowWindow(prev->getHWND(), SW_HIDE);
+ }
+ SetWindowTextA(hWnd, window->getRoomName());
+ }
+ TCITEM tci;
+ tci.mask = TCIF_IMAGE;
+ tci.iImage = -1;
+ TabCtrl_SetItem(GetDlgItem(hWnd, IDC_TABS), getChildTab(window), &tci);
+ SendMessage(active->getHWND(), WM_ACTIVATE, WA_ACTIVE, 0);
+ SetFocus(active->getHWND());
+}
+
+
+void ChatContainer::addChild(ChatWindow *child) {
+ TCITEM tci;
+ int tabId;
+ HWND hwndTabs = GetDlgItem(hWnd, IDC_TABS);
+ childCount++;
+ tci.mask = TCIF_TEXT | TCIF_PARAM;
+ LPTSTR lps1 = Utils::mucc_mir_a2t(child->getRoomName());
+ tci.pszText = lps1;
+ tci.lParam = (LPARAM) child;
+ tabId = TabCtrl_InsertItem(hwndTabs, childCount-1, &tci);
+ TabCtrl_SetCurSel(hwndTabs, tabId);
+ Utils::mucc_mir_free(lps1);
+ activateChild(child);
+ SendMessage(hWnd, WM_SIZE, 0, 0);
+ ShowWindow(hWnd, SW_SHOWNORMAL);
+ SetForegroundWindow(hWnd);
+}
+
+void ChatContainer::changeChildData(ChatWindow *child) {
+ int tabId;
+ HWND hwndTabs = GetDlgItem(hWnd, IDC_TABS);
+ tabId = getChildTab(child);
+ if (tabId >=0) {
+ TCITEM tci;
+ tci.mask = TCIF_TEXT;
+ LPTSTR lps1 = Utils::mucc_mir_a2t(child->getRoomName());
+ tci.pszText = lps1;
+ TabCtrl_SetItem(hwndTabs, childCount-1, &tci);
+ Utils::mucc_mir_free(lps1);
+ }
+ if (child == active) {
+ SetWindowTextA(hWnd, child->getRoomName());
+ }
+}
+
+
+void ChatContainer::removeChild(ChatWindow *child) {
+ HWND hwndTabs = GetDlgItem(hWnd, IDC_TABS);
+ int iSel = getChildTab(child);
+ if (iSel >= 0) {
+ TabCtrl_DeleteItem(hwndTabs, iSel);
+ }
+ childCount--;
+ if (childCount > 0) {
+ TCITEM tci;
+ if (iSel == childCount) iSel--;
+ TabCtrl_SetCurSel(hwndTabs, iSel);
+ tci.mask = TCIF_PARAM;
+ if (TabCtrl_GetItem(hwndTabs, iSel, &tci)) {
+ child = (ChatWindow *)tci.lParam;
+ activateChild(child);
+ }
+ } else {//if (!released) {
+ SendMessage(hWnd, WM_CLOSE, 0, 0);
+ }
+}
+
+void ChatContainer::setUnread(ChatWindow *child, int unread) {
+ if (!unread || child != active) {
+ TCITEM tci;
+ tci.mask = TCIF_IMAGE;
+ if (unread) {
+ tci.iImage = 0;
+ } else {
+ tci.iImage = -1;
+ }
+ TabCtrl_SetItem(GetDlgItem(hWnd, IDC_TABS), getChildTab(child), &tci);
+ }
+}
+
+
+void ChatContainer::getChildWindowRect(RECT *rcChild)
+{
+ RECT rc, rcTabs; //rcStatus,
+ HWND hwndTabs = GetDlgItem(hWnd, IDC_TABS);
+ int l = TabCtrl_GetItemCount(hwndTabs);
+ GetClientRect(hWnd, &rc);
+ GetClientRect(hwndTabs, &rcTabs);
+ TabCtrl_AdjustRect(hwndTabs, FALSE, &rcTabs);
+// GetWindowRect(dat->hwndStatus, &rcStatus);
+ rcChild->left = 0;
+ rcChild->right = rc.right;
+ if (l > 1) {
+ rcChild->top = rcTabs.top - 1;
+ } else {
+ rcChild->top = 0;
+ }
+ rcChild->bottom = rc.bottom - rc.top;// - (rcStatus.bottom - rcStatus.top);
+}
+
+ChatWindow * ChatContainer::getChildFromTab(int tabId) {
+ TCITEM tci;
+ tci.mask = TCIF_PARAM;
+ TabCtrl_GetItem(GetDlgItem(hWnd, IDC_TABS), tabId, &tci);
+ return (ChatWindow *)tci.lParam;
+}
+
+int ChatContainer::getChildTab(ChatWindow *child) {
+ TCITEM tci;
+ int l, i;
+ HWND hwndTabs = GetDlgItem(hWnd, IDC_TABS);
+ l = TabCtrl_GetItemCount(hwndTabs);
+ for (i = 0; i < l; i++) {
+ tci.mask = TCIF_PARAM;
+ TabCtrl_GetItem(hwndTabs, i, &tci);
+ if (child == (ChatWindow *) tci.lParam) {
+ return i;
+ }
+ }
+ return -1;
+
+}
+
+HWND ChatContainer::remoteCreateChild(DLGPROC proc, ChatWindow *ptr) {
+ return (HWND) SendMessage(hWnd, DM_CREATECHILD, (WPARAM)proc, (LPARAM) ptr);
+}
+
+void ChatContainer::remoteAddChild(ChatWindow *ptr) {
+ SendMessage(hWnd, DM_ADDCHILD, (WPARAM)0, (LPARAM) ptr);
+}
+
+void ChatContainer::remoteChangeChildData(ChatWindow *ptr) {
+ SendMessage(hWnd, DM_CHANGECHILDDATA, (WPARAM)0, (LPARAM) ptr);
+}
+
+void ChatContainer::remoteRemoveChild(ChatWindow *ptr) {
+ SendMessage(hWnd, DM_REMOVECHILD, (WPARAM)0, (LPARAM) ptr);
+}
+
+void ChatContainer::remoteSetUnread(ChatWindow *ptr, int unread) {
+ SendMessage(hWnd, DM_SETUNREAD, (WPARAM)unread, (LPARAM) ptr);
+}
+
+void ChatContainer::remoteFlashWindow() {
+ SendMessage(hWnd, DM_FLASHWINDOW, 0, 0);
+}
+
+INT_PTR CALLBACK ContainerDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ ChatContainer *container;
+ container = (ChatContainer *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ if (container==NULL && msg!=WM_INITDIALOG) return FALSE;
+ switch (msg) {
+ case WM_INITDIALOG:
+ SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM) muccIcon[MUCC_IDI_CHAT]);
+ container = (ChatContainer *) lParam;
+ container->setHWND(hwndDlg);
+ TabCtrl_SetImageList(GetDlgItem(hwndDlg, IDC_TABS), hImageList);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) container);
+ ShowWindow(hwndDlg, SW_SHOW);
+ SetEvent(container->getEvent());
+ return TRUE;
+ case WM_GETMINMAXINFO:
+ MINMAXINFO *mmi;
+ RECT rcChild, rcWindow;
+ mmi = (MINMAXINFO *) lParam;
+ GetWindowRect(hwndDlg, &rcWindow);
+ container->getChildWindowRect(&rcChild);
+ mmi->ptMinTrackSize.x = 380;
+ mmi->ptMinTrackSize.y = 130 + (rcWindow.bottom - rcWindow.top) - (rcChild.bottom - rcChild.top);
+ return FALSE;
+ case WM_SIZE:
+ if (IsIconic(hwndDlg) || wParam == SIZE_MINIMIZED) break;
+ {
+ RECT rc, rcChild, rcWindow;
+ GetClientRect(hwndDlg, &rc);
+ HWND hwndTabs = GetDlgItem(hwndDlg, IDC_TABS);
+ MoveWindow(hwndTabs, 0, 0, (rc.right - rc.left), (rc.bottom - rc.top) - 0, FALSE);
+ RedrawWindow(hwndTabs, NULL, NULL, RDW_INVALIDATE | RDW_FRAME | RDW_ERASE);
+ container->getChildWindowRect(&rcChild);
+ if ((rcChild.bottom-rcChild.top) < 130 || (rcChild.right-rcChild.left) < 380) {
+ GetWindowRect(hwndDlg, &rcWindow);
+ if ((rcChild.bottom-rcChild.top) < 130) {
+ rcWindow.bottom = rcWindow.top + 130 + (rcWindow.bottom - rcWindow.top) - (rcChild.bottom - rcChild.top);
+ }
+ if ((rcChild.right-rcChild.left) < 380) {
+ rcWindow.right = rcWindow.left + 380;
+ }
+ MoveWindow(hwndDlg, rcWindow.left, rcWindow.top, rcWindow.right - rcWindow.left, rcWindow.bottom - rcWindow.top, TRUE);
+ container->getChildWindowRect(&rcChild);
+ }
+ if (container->getActive()!=NULL) {
+ MoveWindow(container->getActive()->getHWND(), rcChild.left, rcChild.top, rcChild.right-rcChild.left, rcChild.bottom - rcChild.top, TRUE);
+ }
+ }
+ return TRUE;
+ case DM_CREATECHILD:
+ SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, (LONG_PTR)CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_GROUPCHAT_LOG), hwndDlg, (DLGPROC) wParam, (LPARAM) lParam));
+ return TRUE;
+ case DM_ADDCHILD:
+ container->addChild((ChatWindow *) lParam);
+ return TRUE;
+ case DM_REMOVECHILD:
+ container->removeChild((ChatWindow *) lParam);
+ return TRUE;
+ case DM_CHANGECHILDDATA:
+ container->removeChild((ChatWindow *) lParam);
+ return TRUE;
+ case DM_SETUNREAD:
+ container->setUnread((ChatWindow *) lParam, (int)wParam);
+ return TRUE;
+ case DM_FLASHWINDOW:
+ if (GetActiveWindow() != hwndDlg && GetForegroundWindow() != hwndDlg) {
+ container->setFlash(0);
+ SetTimer(hwndDlg, TIMERID_FLASHWND, container->getFlashTimeout(), NULL);
+ }
+ return TRUE;
+ case WM_NOTIFY:
+ {
+ NMHDR* pNMHDR = (NMHDR*) lParam;
+ switch (pNMHDR->code) {
+ case TCN_SELCHANGE:
+ {
+ TCITEM tci = {0};
+ HWND hwndTabs = GetDlgItem(hwndDlg, IDC_TABS);
+ int iSel = TabCtrl_GetCurSel(hwndTabs);
+ tci.mask = TCIF_PARAM;
+ if (TabCtrl_GetItem(hwndTabs, iSel, &tci)) {
+ ChatWindow * chatWindow = (ChatWindow *) tci.lParam;
+ container->activateChild(chatWindow);
+ }
+ }
+ break;
+ case NM_CLICK:
+ {
+ FILETIME ft;
+ TCHITTESTINFO thinfo;
+ int tabId;
+ HWND hwndTabs = GetDlgItem(hwndDlg, IDC_TABS);
+ GetSystemTimeAsFileTime(&ft);
+ GetCursorPos(&thinfo.pt);
+ ScreenToClient(hwndTabs, &thinfo.pt);
+ tabId = TabCtrl_HitTest(hwndTabs, &thinfo);
+ if (tabId != -1 && tabId == container->lastClickTab &&
+ (ft.dwLowDateTime - container->lastClickTime) < (GetDoubleClickTime() * 10000)) {
+ SendMessage(container->getChildFromTab(tabId)->getHWND(), WM_CLOSE, 0, 0);
+ container->lastClickTab = -1;
+ } else {
+ container->lastClickTab = tabId;
+ }
+ container->lastClickTime = ft.dwLowDateTime;
+ }
+ break;
+ }
+
+ }
+ break;
+ case WM_ACTIVATE:
+ if (LOWORD(wParam) != WA_ACTIVE)
+ break;
+ case WM_MOUSEACTIVATE:
+ if (KillTimer(hwndDlg, TIMERID_FLASHWND)) {
+ FlashWindow(hwndDlg, FALSE);
+ }
+ /*
+ if (container->getActive()!=NULL) {
+ container->setUnread(container->getActive(), 0);
+ SendMessage(container->getActive()->getHWND(), WM_ACTIVATE, WA_ACTIVE, 0);
+ }*/
+ break;
+ case WM_CLOSE:
+ EndDialog(hwndDlg, 0);
+ return FALSE;
+ case WM_TIMER:
+ if (wParam == TIMERID_FLASHWND) {
+ if ((container->getFlash() > container->getFlashMax()) || (GetActiveWindow() == hwndDlg) || (GetForegroundWindow() == hwndDlg)) {
+ KillTimer(hwndDlg, TIMERID_FLASHWND);
+ FlashWindow(hwndDlg, FALSE);
+ } else if (container->getFlash() < container->getFlashMax()) {
+ FlashWindow(hwndDlg, TRUE);
+ container->setFlash(container->getFlash()+1);
+ }
+ }
+ break;
+ case WM_DESTROY:
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)0);
+ delete container;
+ return TRUE;
+
+ }
+ return FALSE;
+}
+
+
+static void __cdecl StartThread(void *vContainer) {
+ OleInitialize(NULL);
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_GROUPCHAT_CONTAINER), NULL, ContainerDlgProc, (LPARAM) vContainer);
+ //MessageBox(NULL, "ChatContainer dies.", "MW", MB_OK);
+ OleUninitialize();
+
+}
diff --git a/protocols/Tlen/tlen_czaty/ChatContainer.h b/protocols/Tlen/tlen_czaty/ChatContainer.h
new file mode 100644
index 0000000000..4414068033
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatContainer.h
@@ -0,0 +1,100 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+class ChatContainer;
+
+#ifndef CHATCONTAINER_INCLUDED
+#define CHATCONTAINER_INCLUDED
+#include "mucc.h"
+#include "ChatEvent.h"
+#include "ChatUser.h"
+#include "AdminWindow.h"
+
+class ChatContainerChild {
+public:
+ ChatWindow *window;
+ ChatContainerChild *next;
+ ChatContainerChild *prev;
+};
+
+class ChatContainer{
+
+private:
+ static ChatContainer * list;
+ static bool released;
+ static CRITICAL_SECTION mutex;
+ HWND hWnd;
+ HANDLE hEvent;
+ int childCount;
+ int width, height;
+ int nFlash, nFlashMax;
+ ChatContainer *next, *prev;
+ ChatWindow * active;
+ ChatContainer();
+protected:
+ friend INT_PTR CALLBACK ContainerDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+ void addChild(ChatWindow *);
+ void activateChild(ChatWindow *);
+ void changeChildData(ChatWindow *);
+ void removeChild(ChatWindow *);
+ void setUnread(ChatWindow *child, int unread);
+ void getChildWindowRect(RECT *rcChild);
+ ChatWindow * getChildFromTab(int tabId);
+ int getChildTab(ChatWindow *);
+ int getChildCount();
+ void setChildCount(int);
+ ChatWindow * getActive();
+ ChatContainerChild *getChildren();
+ ChatContainer * getNext();
+ void setNext(ChatContainer *);
+ ChatContainer * getPrev();
+ void setPrev(ChatContainer *);
+ int lastClickTime;
+ int lastClickTab;
+ HANDLE getEvent();
+ void setHWND(HWND);
+ int getFlash();
+ int getFlashMax();
+ int getFlashTimeout();
+ void setFlash(int);
+public:
+ enum FLAGS {
+ FLAG_USE_TABS = 0x00000001,
+ };
+
+ ~ChatContainer();
+ static void init();
+ static void release();
+ static ChatContainer * getWindow();
+ static int getDefaultOptions();
+ void show(bool bShow);
+ HWND getHWND();
+
+ HWND remoteCreateChild(DLGPROC proc, ChatWindow *);
+ void remoteAddChild(ChatWindow *);
+ void remoteChangeChildData(ChatWindow *);
+ void remoteRemoveChild(ChatWindow *);
+ void remoteSetUnread(ChatWindow *ptr, int unread);
+ void remoteFlashWindow();
+};
+
+
+#endif
diff --git a/protocols/Tlen/tlen_czaty/ChatEvent.cpp b/protocols/Tlen/tlen_czaty/ChatEvent.cpp
new file mode 100644
index 0000000000..246c168f22
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatEvent.cpp
@@ -0,0 +1,174 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "ChatEvent.h"
+#include "Options.h"
+#include "Utils.h"
+#include <string.h>
+
+ChatEvent::ChatEvent() {
+
+ next = prev = NULL;
+ event.cbSize = sizeof(MUCCEVENT);
+ event.iType = 0;
+ event.pszID = NULL;
+ event.pszModule = NULL;
+ event.pszName = NULL;
+ event.pszNick = NULL;
+ event.pszText = NULL;
+ event.pszUID = NULL;
+}
+
+ChatEvent::ChatEvent(const MUCCEVENT *e) {
+
+ event.cbSize = sizeof(MUCCEVENT);
+ event.iType = e->iType;
+ event.bIsMe = e->bIsMe;
+ event.color = e->color;
+ event.dwData = e->dwData;
+ event.dwFlags = e->dwFlags;
+ event.iFont = e->iFont;
+ event.iFontSize = e->iFontSize;
+ event.time = e->time;
+ event.pszID = NULL;
+ event.pszModule = NULL;
+ event.pszName = NULL;
+ event.pszNick = NULL;
+ event.pszText = NULL;
+ event.pszUID = NULL;
+// Utils::copyString((char **)&(event.pszID), e->pszID);
+// Utils::copyString((char **)&(event.pszModule), e->pszModule);
+// Utils::copyString((char **)&(event.pszName), e->pszName);
+ if (e->iType == MUCC_EVENT_STATUS || e->iType == MUCC_EVENT_MESSAGE) {
+ Utils::copyString((char **)&(event.pszNick), e->pszNick);
+ }
+ if (e->iType == MUCC_EVENT_ERROR || e->iType == MUCC_EVENT_MESSAGE || e->iType == MUCC_EVENT_TOPIC) {
+ Utils::copyString((char **)&(event.pszText), e->pszText);
+ }
+// Utils::copyString((char **)&(event.pszUID), e->pszUID);
+ next = prev = NULL;
+}
+
+ChatEvent::~ChatEvent() {
+
+ if (event.pszID != NULL) {
+ delete (char *)event.pszID;
+ }
+ if (event.pszModule != NULL) {
+ delete (char *)event.pszModule;
+ }
+ if (event.pszName != NULL) {
+ delete (char *)event.pszName;
+ }
+ if (event.pszNick != NULL) {
+ delete (char *)event.pszNick;
+ }
+ if (event.pszText != NULL) {
+ delete (char *)event.pszText;
+ }
+ if (event.pszUID != NULL) {
+ delete (char *)event.pszUID;
+ }
+ if (next != NULL) {
+ next->setPrev(prev);
+ }
+ if (prev != NULL) {
+ prev->setNext(next);
+ }
+}
+
+ChatEvent * ChatEvent::getNext() {
+ return next;
+}
+
+ChatEvent * ChatEvent::getPrev() {
+ return prev;
+}
+
+void ChatEvent::setNext(ChatEvent *next) {
+ this->next = next;
+}
+
+void ChatEvent::setPrev(ChatEvent * prev) {
+ this->prev = prev;
+}
+
+const MUCCEVENT * ChatEvent::getEvent() {
+ return &event;
+}
+
+ChatEventList::ChatEventList() {
+ eventListEnd = &eventListRoot;
+ setMaxSize(DEFAULT_MAX_SIZE);
+ currentSize = 0;
+}
+
+ChatEventList::~ChatEventList() {
+ while (eventListRoot.getNext()!=NULL) {
+ delete eventListRoot.getNext();
+ }
+}
+
+int ChatEventList::addEvent(const MUCCEVENT *muccevent) {
+ int trimmed = 0;
+ ChatEvent *event = new ChatEvent(muccevent);
+ event->setPrev(eventListEnd);
+ eventListEnd->setNext(event);
+ eventListEnd=event;
+ currentSize++;
+ if (currentSize>hiMaxSize) {
+ while (currentSize>loMaxSize && eventListRoot.getNext()!=NULL) {
+ delete eventListRoot.getNext();
+ currentSize--;
+ trimmed = 1;
+ }
+ }
+ return trimmed;
+}
+
+ChatEvent * ChatEventList::getEvents() {
+ return eventListRoot.getNext();
+}
+
+void ChatEventList::setMaxSize(int s) {
+ loMaxSize = s;
+ if (s>200) {
+ hiMaxSize = s + s/10;
+ } else {
+ hiMaxSize = s + 20;
+ }
+}
+
+void ChatEventList::clear() {
+ ChatEvent *event = eventListRoot.getNext();
+ eventListRoot.setNext(NULL);
+ eventListEnd = &eventListRoot;
+ currentSize = 0;
+ if (event!=NULL) {
+ event->setPrev(NULL);
+ while (event->getNext()!=NULL) {
+ delete event->getNext();
+ }
+ delete event;
+ }
+}
+
+
diff --git a/protocols/Tlen/tlen_czaty/ChatEvent.h b/protocols/Tlen/tlen_czaty/ChatEvent.h
new file mode 100644
index 0000000000..37e045380f
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatEvent.h
@@ -0,0 +1,60 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef CHATEVENT_INCLUDED
+#define CHATEVENT_INCLUDED
+#include "mucc.h"
+
+class ChatEvent {
+private:
+ ChatEvent * prev;
+ ChatEvent * next;
+ MUCCEVENT event;
+public:
+ ChatEvent();
+ ChatEvent(const MUCCEVENT *);
+ ~ChatEvent();
+ ChatEvent * getPrev();
+ ChatEvent * getNext();
+ void setPrev(ChatEvent *);
+ void setNext(ChatEvent *);
+ const MUCCEVENT *getEvent();
+};
+
+class ChatEventList {
+private:
+ ChatEvent eventListRoot;
+ ChatEvent * eventListEnd;
+ int loMaxSize;
+ int hiMaxSize;
+ int currentSize;
+public:
+ enum {
+ DEFAULT_MAX_SIZE = 100
+ };
+ ChatEventList();
+ ~ChatEventList();
+ ChatEvent * getEvents();
+ int addEvent(const MUCCEVENT *);
+ void clear();
+ void setMaxSize(int s);
+};
+
+#endif
diff --git a/protocols/Tlen/tlen_czaty/ChatGroup.cpp b/protocols/Tlen/tlen_czaty/ChatGroup.cpp
new file mode 100644
index 0000000000..a5c47d724f
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatGroup.cpp
@@ -0,0 +1,99 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "ChatGroup.h"
+#include "Utils.h"
+
+ChatGroup::ChatGroup() {
+ prev = next = NULL;
+ parent = child =NULL;
+ name = NULL;
+ id = 0;
+}
+
+ChatGroup::~ChatGroup() {
+ if (name!=NULL) delete name;
+ if (id!=NULL) delete id;
+}
+ChatGroup * ChatGroup::getNext() {
+ return next;
+}
+
+void ChatGroup::setNext(ChatGroup *next) {
+ this->next = next;
+}
+
+ChatGroup * ChatGroup::getPrev() {
+ return prev;
+}
+
+void ChatGroup::setPrev(ChatGroup *prev) {
+ this->prev = prev;
+}
+
+ChatGroup * ChatGroup::getChild() {
+ return child;
+}
+
+void ChatGroup::addChild(ChatGroup *child) {
+ ChatGroup *group;
+ for (group=getChild();group!=NULL && group->getNext()!=NULL;group=group->getNext()) {
+ }
+ if (group==NULL) this->child = child;
+ else {
+ group->setNext(child);
+ }
+ child->setPrev(group);
+ child->setNext(NULL);
+}
+
+ChatGroup * ChatGroup::getListNext() {
+ return listNext;
+}
+
+void ChatGroup::setListNext(ChatGroup *next) {
+ this->listNext = next;
+}
+
+const char *ChatGroup::getId() {
+ return id;
+}
+
+void ChatGroup::setId(const char *id) {
+ Utils::copyString(&this->id, id);
+}
+
+HTREEITEM ChatGroup::getTreeItem() {
+ return hItem;
+}
+
+void ChatGroup::setTreeItem(HTREEITEM hItem) {
+ this->hItem=hItem;
+}
+
+const char *ChatGroup::getName() {
+ return name;
+}
+
+void ChatGroup::setName(const char *name) {
+ Utils::copyString(&this->name, name);
+}
+
diff --git a/protocols/Tlen/tlen_czaty/ChatGroup.h b/protocols/Tlen/tlen_czaty/ChatGroup.h
new file mode 100644
index 0000000000..c04abf81ba
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatGroup.h
@@ -0,0 +1,55 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef CHATGROUP_INCLUDED
+#define CHATGROUP_INCLUDED
+#include "mucc.h"
+
+class ChatGroup {
+private:
+ HTREEITEM hItem;
+ ChatGroup * parent;
+ ChatGroup * child;
+ ChatGroup * prev;
+ ChatGroup * next;
+ ChatGroup * listNext;
+ char * name;
+ char * id;
+public:
+ ChatGroup();
+ ~ChatGroup();
+ ChatGroup * getPrev();
+ ChatGroup * getNext();
+ ChatGroup * getListNext();
+ ChatGroup * getChild();
+ ChatGroup * getParent();
+ HTREEITEM getTreeItem();
+ const char * getName();
+ const char * getId();
+ void setPrev(ChatGroup *);
+ void setNext(ChatGroup *);
+ void setListNext(ChatGroup *);
+ void addChild(ChatGroup *);
+ void setParent(ChatGroup *);
+ void setName(const char *);
+ void setTreeItem(HTREEITEM );
+ void setId(const char *);
+};
+#endif
diff --git a/protocols/Tlen/tlen_czaty/ChatRoom.cpp b/protocols/Tlen/tlen_czaty/ChatRoom.cpp
new file mode 100644
index 0000000000..2f9c1389c2
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatRoom.cpp
@@ -0,0 +1,68 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "ChatRoom.h"
+#include "Utils.h"
+
+
+ChatRoom::ChatRoom() {
+ next = prev = NULL;
+ name = NULL;
+ id = NULL;
+}
+
+ChatRoom::~ChatRoom() {
+ if (name!=NULL) delete name;
+ if (id!=NULL) delete id;
+}
+
+void ChatRoom::setId(const char *id) {
+ Utils::copyString(&this->id, id);
+}
+
+void ChatRoom::setName(const char *name) {
+ Utils::copyString(&this->name, name);
+}
+
+const char* ChatRoom::getId() {
+ return id;
+}
+
+const char* ChatRoom::getName() {
+ return name;
+}
+
+ChatRoom *ChatRoom::getNext() {
+ return next;
+}
+
+void ChatRoom::setNext(ChatRoom *next) {
+ this->next = next;
+}
+
+void ChatRoom::setFlags(int flags) {
+ this->flags = flags;
+}
+
+int ChatRoom::getFlags() {
+ return flags;
+}
+
diff --git a/protocols/Tlen/tlen_czaty/ChatRoom.h b/protocols/Tlen/tlen_czaty/ChatRoom.h
new file mode 100644
index 0000000000..51593f00c2
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatRoom.h
@@ -0,0 +1,51 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef CHATROOM_INCLUDED
+#define CHATROOM_INCLUDED
+#include "mucc.h"
+
+
+class ChatRoom {
+private:
+ HTREEITEM hItem;
+ ChatRoom * prev;
+ ChatRoom * next;
+ char * name;
+ char * id;
+ int flags;
+public:
+ ChatRoom();
+ ~ChatRoom();
+ ChatRoom * getPrev();
+ ChatRoom * getNext();
+ HTREEITEM getTreeItem();
+ const char * getName();
+ const char * getId();
+ int getFlags();
+ void setPrev(ChatRoom *);
+ void setNext(ChatRoom *);
+ void setName(const char *);
+ void setTreeItem(HTREEITEM );
+ void setId(const char *);
+ void setFlags(int);
+};
+
+#endif
diff --git a/protocols/Tlen/tlen_czaty/ChatUser.cpp b/protocols/Tlen/tlen_czaty/ChatUser.cpp
new file mode 100644
index 0000000000..cb5baea1a8
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatUser.cpp
@@ -0,0 +1,83 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "ChatUser.h"
+#include "Utils.h"
+
+ChatUser::ChatUser() {
+ id = NULL;
+ nick = NULL;
+ hTreeItem = NULL;
+ me = 0;
+}
+
+ChatUser::~ChatUser() {
+ if (id!=NULL) delete id;
+ if (nick!=NULL) delete nick;
+}
+
+void ChatUser::setNick(const char *nick) {
+ Utils::copyString(&this->nick, nick);
+}
+
+void ChatUser::setId(const char *id) {
+ Utils::copyString(&this->id, id);
+}
+
+const char *ChatUser::getNick() {
+ return nick;
+}
+
+const char *ChatUser::getId() {
+ return id;
+}
+
+void ChatUser::setNext(ChatUser *next) {
+ this->next = next;
+}
+
+ChatUser * ChatUser::getNext() {
+ return next;
+}
+
+void ChatUser::setFlags(int flags) {
+ this->flags = flags;
+}
+
+int ChatUser::getFlags() {
+ return flags;
+}
+
+void ChatUser::setMe(int me) {
+ this->me = me;
+}
+
+int ChatUser::isMe() {
+ return me;
+}
+
+void ChatUser::setHTreeItem(HTREEITEM hti) {
+ hTreeItem = hti;
+}
+
+HTREEITEM ChatUser::getHTreeItem() {
+ return hTreeItem;
+}
diff --git a/protocols/Tlen/tlen_czaty/ChatUser.h b/protocols/Tlen/tlen_czaty/ChatUser.h
new file mode 100644
index 0000000000..0084a14608
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatUser.h
@@ -0,0 +1,49 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef CHATUSER_INCLUDED
+#define CHATUSER_INCLUDED
+#include "mucc.h"
+
+class ChatUser {
+private:
+ char * nick;
+ char * id;
+ int flags;
+ int me;
+ ChatUser * next;
+ HTREEITEM hTreeItem;
+public:
+ ChatUser();
+ ~ChatUser();
+ void setNick(const char *);
+ void setId(const char *);
+ const char * getNick();
+ const char * getId();
+ void setNext(ChatUser *);
+ int getFlags();
+ void setFlags(int );
+ HTREEITEM getHTreeItem();
+ void setHTreeItem(HTREEITEM);
+ ChatUser * getNext();
+ void setMe(int);
+ int isMe();
+};
+#endif
diff --git a/protocols/Tlen/tlen_czaty/ChatWindow.cpp b/protocols/Tlen/tlen_czaty/ChatWindow.cpp
new file mode 100644
index 0000000000..97dc986381
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatWindow.cpp
@@ -0,0 +1,2108 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "ChatWindow.h"
+#include "HelperDialog.h"
+#include "Utils.h"
+#include "Options.h"
+#include "m_smileyadd.h"
+#include "m_ieview.h"
+//#include "m_chat.h"
+
+static int logPixelSY;
+static INT_PTR CALLBACK LogDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static void JabberStringAppend(char **str, int *sizeAlloced, const char *fmt, ...);
+static char *JabberRtfEscape(char *str);
+//static DWORD CALLBACK Log_StreamCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG * pcb);
+
+COLORREF ChatWindow::colorListBg, ChatWindow::colorListText, ChatWindow::colorListGroupText;
+HFONT ChatWindow::hListGroupFont=NULL;
+HFONT ChatWindow::hListFont=NULL;
+
+ChatWindow * ChatWindow::list = NULL;
+bool ChatWindow::released = false;
+CRITICAL_SECTION ChatWindow::mutex;
+
+static WNDPROC oldSplitterWndProc, oldEditWndProc;
+static HCURSOR hCurSplitNS, hCurSplitWE, hCurHyperlinkHand;
+
+void ChatWindow::release() {
+ released = true;
+ for (ChatWindow *ptr2, *ptr = list; ptr!=NULL; ptr=ptr2) {
+ ptr2 = ptr->getNext();
+ //SendMessage(ptr->getHWND(), WM_CLOSE, 0, 0);
+ }
+ DeleteCriticalSection(&mutex);
+ DestroyCursor(hCurSplitNS);
+ DestroyCursor(hCurSplitWE);
+ DestroyCursor(hCurHyperlinkHand);
+}
+
+void ChatWindow::init() {
+ hCurSplitNS = LoadCursor(NULL, IDC_SIZENS);
+ hCurSplitWE = LoadCursor(NULL, IDC_SIZEWE);
+ hCurHyperlinkHand = LoadCursor(NULL, IDC_HAND);
+ if (hCurHyperlinkHand == NULL) {
+ hCurHyperlinkHand = LoadCursor(NULL, IDC_ARROW);
+ }
+ released = false;
+ InitializeCriticalSection(&mutex);
+}
+
+/* chat.dll mod*/
+/*
+static bool gcRegistered = false;
+
+static void __stdcall StartThread(void *vChat) { //__cdecl
+ ChatWindow *chat = (ChatWindow *)vChat;
+ if (!gcRegistered) {
+ gcRegistered = true;
+ GCREGISTER gcr = {0};
+ gcr.cbSize = sizeof(GCREGISTER);
+ gcr.dwFlags = 0;
+ gcr.iMaxText = 0;
+ gcr.nColors = 0;
+ gcr.pColors = 0;
+ gcr.pszModuleDispName = chat->getModule();
+ gcr.pszModule = chat->getModule();
+ if (CallService(MS_GC_REGISTER, 0, (LPARAM)&gcr)) {
+ MessageBox(NULL, "cannot register", "CHAT", MB_OK);
+ }
+ }
+ GCWINDOW gcw = {0};
+ gcw.cbSize = sizeof(GCWINDOW);
+ gcw.iType = GCW_CHATROOM;
+ gcw.pszModule = chat->getModule();
+ gcw.pszName = chat->getRoomName();
+ gcw.pszID = chat->getRoomId();
+ gcw.pszStatusbarText = "status";
+ gcw.bDisableNickList = FALSE;
+ gcw.dwItemData = (DWORD) chat;
+ if(CallService(MS_GC_NEWCHAT, 0, (LPARAM) &gcw)) {
+ MessageBox(NULL, "cannot create", "CHAT", MB_OK);
+ }
+
+ GCDEST gcdest;
+ GCEVENT gcevent = {sizeof(GCEVENT), &gcdest};
+ const char *groupNames[] = {"Global Owners", "Owners", "Admins", "Moderators", "Users"};
+ gcdest.pszModule = (char *)chat->getModule();
+ gcdest.pszID = (char *)chat->getRoomId();
+ gcevent.bAddToLog = FALSE;
+ gcevent.time = 0;
+ gcdest.iType = GC_EVENT_ADDGROUP;
+ for (int i=0;i<5;i++) {
+ gcevent.pszStatus = Translate(groupNames[i]);
+ CallService(MS_GC_EVENT, 0, (LPARAM)&gcevent);
+ }
+
+
+ gcdest.iType = GC_EVENT_CONTROL;
+ CallService(MS_GC_EVENT, WINDOW_INITDONE, (LPARAM)&gcevent);
+ CallService(MS_GC_EVENT, WINDOW_ONLINE, (LPARAM)&gcevent);
+}
+*/
+
+ChatWindow::ChatWindow(MUCCWINDOW *mucw) {
+ prev = next = NULL;
+ adminWindow = NULL;
+ hWnd = NULL;
+ hWndLog = NULL;
+ module = roomId = roomName = topic = NULL;
+ hSplitterPos = 0;
+ vSplitterPos = 0;
+ wasFirstMessage = 0;
+ isEmpty = true;
+ isStarted = 0;
+ options = Options::getChatWindowOptions();
+ bBold = bItalic = bUnderline = 0;
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ hEditFont = NULL;
+ userMe = NULL;
+ users = NULL;
+ for (int i=0;i<5;i++) {
+ hUserGroups[i] = NULL;
+ }
+ setModule(mucw->pszModule);
+ setRoomId(mucw->pszID);
+ setRoomName(mucw->pszName);
+ EnterCriticalSection(&mutex);
+ setNext(list);
+ if (next!=NULL) {
+ next->setPrev(this);
+ }
+ list = this;
+ LeaveCriticalSection(&mutex);
+ container = ChatContainer::getWindow();
+ hWnd = container->remoteCreateChild(LogDlgProc, this);
+ container->remoteAddChild(this);
+ /* chat.dll mod*/
+/* CallFunctionAsync(StartThread, (void *)this);*/
+}
+
+ChatWindow::~ChatWindow () {
+ if (!released) {
+ EnterCriticalSection(&mutex);
+ if (getPrev()!=NULL) {
+ getPrev()->setNext(next);
+ } else if (list==this) {
+ list = getNext();
+ }
+ if (getNext()!=NULL) {
+ getNext()->setPrev(prev);
+ }
+ LeaveCriticalSection(&mutex);
+ }
+ if (adminWindow!=NULL) {
+ delete adminWindow;
+ }
+ if (hEvent!=NULL) {
+ CloseHandle(hEvent);
+ }
+ while (users!=NULL) {
+ ChatUser *user = users;
+ users = users->getNext();
+ delete user;
+ }
+ if (module!=NULL) {
+ delete module;
+ }
+ if (roomId!=NULL) {
+ delete roomId;
+ }
+ if (roomName!=NULL) {
+ delete roomName;
+ }
+ if (topic!=NULL) {
+ delete topic;
+ }
+ container->remoteRemoveChild(this);
+};
+
+
+void ChatWindow::setPrev(ChatWindow *prev) {
+ this->prev = prev;
+}
+
+ChatWindow * ChatWindow::getPrev() {
+ return prev;
+}
+
+void ChatWindow::setNext(ChatWindow *next) {
+ this->next = next;
+}
+
+ChatWindow * ChatWindow::getNext() {
+ return next;
+}
+
+void ChatWindow::setHWND(HWND hWnd) {
+ this->hWnd = hWnd;
+}
+
+HWND ChatWindow::getHWND() {
+ return hWnd;
+}
+
+void ChatWindow::setHWNDLog(HWND hWnd) {
+ this->hWndLog = hWnd;
+}
+
+HWND ChatWindow::getHWNDLog() {
+ return hWndLog;
+}
+
+HANDLE ChatWindow::getEvent() {
+ return hEvent;
+}
+
+ChatContainer * ChatWindow::getContainer() {
+ return container;
+}
+
+void ChatWindow::setAdminWindow(AdminWindow *aw) {
+ this->adminWindow = aw;
+}
+
+AdminWindow* ChatWindow::getAdminWindow() {
+ return adminWindow;
+}
+
+void ChatWindow::setModule(const char *module) {
+ Utils::copyString(&this->module, module);
+}
+
+const char * ChatWindow::getModule() {
+ return module;
+}
+
+void ChatWindow::setRoomId(const char *roomId) {
+ Utils::copyString(&this->roomId, roomId);
+}
+
+const char * ChatWindow::getRoomId() {
+ return roomId;
+}
+
+void ChatWindow::setRoomName(const char *roomName) {
+// char str[300];
+ Utils::copyString(&this->roomName, roomName);
+// sprintf(str, "%s %08X", roomName, roomFlags);
+// SetWindowText(hWnd, str);
+ SetWindowTextA(hWnd, roomName);
+}
+
+void ChatWindow::setRoomFlags(int flags) {
+// char str[300];
+ roomFlags = flags;
+// sprintf(str, "%s %08X", roomName, roomFlags);
+// SetWindowText(hWnd, str);
+}
+
+int ChatWindow::getRoomFlags() {
+ return roomFlags;
+}
+
+const char * ChatWindow::getRoomName() {
+ return roomName;
+}
+
+void ChatWindow::setOptions(int options) {
+ if (options != this->options) {
+ this->options = options;
+ rebuildLog();
+ }
+}
+
+int ChatWindow::getOptions() {
+ return options;
+}
+
+static void __cdecl StartAdminThread(void *vChat) {
+ ChatWindow *chat = (ChatWindow *)vChat;
+ chat->getAdminWindow()->start();
+}
+
+void ChatWindow::startAdminDialog(int mode) {
+ if (adminWindow==NULL) {
+ ChatUser *user = getSelectedUser();
+ if (user != NULL) {
+ adminWindow = new AdminWindow(this, user->getId(), mode);
+ } else {
+ adminWindow = new AdminWindow(this, "", mode);
+ }
+ Utils::forkThread((void (__cdecl *)(void *))StartAdminThread, 0, (void *) this);
+ }
+}
+void ChatWindow::addUser(ChatUser *user) {
+ user->setNext(users);
+ users = user;
+}
+void ChatWindow::removeUser(ChatUser *user) {
+ ChatUser *user2;
+ for (user2=users;user2!=NULL;user2=user2->getNext()) {
+ if (user2->getNext()==user) break;
+ }
+ if (user2!=NULL) {
+ user2->setNext(user->getNext());
+ } else if (users==user) {
+ users = user->getNext();
+ }
+}
+
+ChatUser * ChatWindow::getMe() {
+ return userMe;
+}
+
+ChatUser * ChatWindow::findUser(const char *userId) {
+ ChatUser *user;
+ for (user=users;user!=NULL;user=user->getNext()) {
+ if (!(strcmp(user->getId(), userId))) break;
+ }
+ return user;
+}
+
+ChatUser * ChatWindow::findUserByNick(const char *nick) {
+ ChatUser *user;
+ for (user=users;user!=NULL;user=user->getNext()) {
+ if (!(strcmp(user->getNick(), nick))) break;
+ }
+ return user;
+}
+
+ChatUser *ChatWindow::getSelectedUser() {
+ HTREEITEM hTreeItem = TreeView_GetSelection(GetDlgItem(hWnd, IDC_TREELIST));
+ if (hTreeItem!=NULL) {
+ TVITEM tvi;
+ tvi.mask = TVIF_PARAM;
+ tvi.hItem = hTreeItem;
+ TreeView_GetItem(GetDlgItem(hWnd, IDC_TREELIST), &tvi);
+ return (ChatUser *) tvi.lParam;
+ }
+ return NULL;
+}
+
+int ChatWindow::startPriv() {
+ ChatUser *user = getSelectedUser();
+ if (user!=NULL) {
+ MUCCEVENT mucce;
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_START_PRIV;
+ mucce.pszModule = getModule();
+ mucce.pszID = getRoomId();
+ mucce.pszUID = user->getId();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&mucce);
+ }
+ return 0;
+}
+
+int ChatWindow::unban(const char *id) {
+ if (id!=NULL) {
+ MUCCEVENT mucce;
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_UNBAN;
+ mucce.pszModule = getModule();
+ mucce.pszID = getRoomId();
+ mucce.pszUID = id;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&mucce);
+ }
+ return 0;
+}
+
+
+int ChatWindow::kickAndBan(const char *id, int time, const char *reason) {
+ if (id!=NULL) {
+ MUCCEVENT mucce;
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_KICK_BAN;
+ mucce.pszModule = getModule();
+ mucce.pszID = getRoomId();
+ mucce.pszUID = id;
+ mucce.dwData = time;
+ mucce.pszText = reason;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&mucce);
+ }
+ return 0;
+}
+
+int ChatWindow::kickAndBan(int time) {
+ ChatUser *user = getSelectedUser();
+ if (user!=NULL) {
+ kickAndBan(user->getId(), time, "");
+ }
+ return 0;
+}
+
+int ChatWindow::setRights(const char *id, int flags) {
+ if (id!=NULL) {
+ MUCCEVENT mucce;
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_SET_USER_ROLE;
+ mucce.pszModule = getModule();
+ mucce.pszID = getRoomId();
+ mucce.pszUID = id;
+ mucce.dwFlags = flags;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&mucce);
+ }
+ return 0;
+}
+
+int ChatWindow::setRights(int flags) {
+ ChatUser *user = getSelectedUser();
+ if (user!=NULL) {
+ setRights(user->getId(), flags);
+ }
+ return 0;
+}
+
+int ChatWindow::getUserGroup(ChatUser *user) {
+ int group = 4;
+ if (user->getFlags()&MUCC_EF_USER_GLOBALOWNER) {
+ group = 0;
+ } else if (user->getFlags()&MUCC_EF_USER_OWNER) {
+ group = 1;
+ } else if (user->getFlags()&MUCC_EF_USER_ADMIN) {
+ group = 2;
+ } else if (user->getFlags()&MUCC_EF_USER_MODERATOR) {
+ group = 3;
+ }
+ return group;
+}
+
+int ChatWindow::changePresence(const MUCCEVENT *event) {
+ int i, group, bLogEvent = FALSE;
+ const char *groupNames[] = {"Global Owners", "Owners", "Admins", "Moderators", "Users"};
+ ChatUser *user = findUser(event->pszUID);
+ if (event->dwData == ID_STATUS_ONLINE || (user!=NULL && event->dwData!=ID_STATUS_OFFLINE)) {
+ if (user == NULL) {
+ user = new ChatUser();
+ user->setId(event->pszUID);
+ user->setNick(event->pszNick);
+ user->setFlags(event->dwFlags);
+ user->setMe(event->bIsMe);
+ addUser(user);
+ if (user->isMe()) {
+ userMe = user;
+ }
+ bLogEvent = TRUE;
+ } else {
+ group = getUserGroup(user);
+ user->setFlags(event->dwFlags);
+ TreeView_DeleteItem(GetDlgItem(hWnd, IDC_TREELIST), user->getHTreeItem());
+ if (TreeView_GetChild(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group))==NULL) {
+ TreeView_DeleteItem(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group));
+ setTreeItem(group, NULL);
+ }
+ }
+ if (user->isMe()) {
+ if (user->getFlags() & MUCC_EF_USER_OWNER || user->getFlags() & MUCC_EF_USER_ADMIN) {
+ EnableWindow(GetDlgItem(hWnd, IDC_TOPIC_BUTTON), TRUE);
+ } else {
+ EnableWindow(GetDlgItem(hWnd, IDC_TOPIC_BUTTON), FALSE);
+ }
+ }
+ group = getUserGroup(user);
+ TVINSERTSTRUCT tvis;
+ if (getTreeItem(group)==NULL) {
+ for (i=group-1;i>=0;i--) {
+ if (getTreeItem(i)!=NULL) break;
+ }
+ tvis.hParent = NULL;
+ if (i>=0) {
+ tvis.hInsertAfter = getTreeItem(i);
+ } else {
+ tvis.hInsertAfter = TVI_FIRST;
+ }
+ tvis.item.mask = TVIF_TEXT | TVIF_PARAM | TVIF_CHILDREN;
+ tvis.item.lParam = (LPARAM) NULL;
+ tvis.item.cChildren = 1;
+ LPTSTR lps1 = Utils::mucc_mir_a2t(Translate(groupNames[group]));
+ tvis.item.pszText = lps1;
+ //tvis.item.state = INDEXTOSTATEIMAGEMASK(1);
+ //tvis.item.stateMask = TVIS_STATEIMAGEMASK ;
+ setTreeItem(group, TreeView_InsertItem(GetDlgItem(hWnd, IDC_TREELIST), &tvis));
+ Utils::mucc_mir_free(lps1);
+ }
+ tvis.hParent = getTreeItem(group);
+ tvis.hInsertAfter = TVI_SORT;
+ tvis.item.mask = TVIF_TEXT | TVIF_PARAM;
+ LPTSTR lps2 = Utils::mucc_mir_a2t(user->getNick());
+ tvis.item.pszText = lps2;
+ tvis.item.lParam = (LPARAM) user;
+ user->setHTreeItem(TreeView_InsertItem(GetDlgItem(hWnd, IDC_TREELIST), &tvis));
+ TreeView_Expand(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group), TVE_EXPAND);
+ Utils::mucc_mir_free(lps2);
+ }
+ else {
+ if (user != NULL) {
+ group = getUserGroup(user);
+ TreeView_DeleteItem(GetDlgItem(hWnd, IDC_TREELIST), user->getHTreeItem());
+ if (TreeView_GetChild(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group))==NULL) {
+ TreeView_DeleteItem(GetDlgItem(hWnd, IDC_TREELIST), getTreeItem(group));
+ setTreeItem(group, NULL);
+ }
+ removeUser(user);
+ delete user;
+ bLogEvent = TRUE;
+ }
+ }
+ if (bLogEvent && wasFirstMessage) {
+ logEvent(event);
+ }
+ return 1;
+}
+int ChatWindow::changeTopic(const MUCCEVENT *event) {
+
+ SetDlgItemTextA(hWnd, IDC_TOPIC, event->pszText);
+//if (wasFirstMessage) {
+ logEvent(event);
+// }
+ return 1;
+}
+
+int ChatWindow::changeRoomInfo(const MUCCEVENT *event) {
+
+ Utils::log("setting room info !");
+ setRoomName(event->pszName);
+ setRoomFlags(event->dwFlags);
+ return 1;
+}
+
+const char * ChatWindow::getFontName(int index) {
+ const char *fontNames[] = {"Arial",
+ "Comic Sans MS",
+ "Courier New",
+ "Impact",
+ "Lucida Console",
+ "MS Sans Serif",
+ "Tahoma",
+ "Times New Roman",
+ "Trebuchet MS",
+ "Verdana"};
+ if (index>9 || index<0) index = 0;
+ return fontNames[index];
+}
+int ChatWindow::getFontNameNum() {
+ return 10;
+}
+int ChatWindow::getFontSize(int index) {
+ return index+7;
+}
+int ChatWindow::getFontSizeNum() {
+ return 10;
+}
+
+void ChatWindow::refreshSettings() {
+ SendDlgItemMessage(hWnd, IDC_LOG, EM_SETBKGNDCOLOR , 0, Options::getLogBgColor());
+ SendDlgItemMessage(hWnd, IDC_TREELIST, TVM_SETBKCOLOR, 0, Options::getListBgColor());
+ eventList.setMaxSize(Options::getLogLimit());
+}
+
+void ChatWindow::refreshSettings(int force) {
+
+ if (hListFont!=NULL && !force) {
+ return;
+ }
+ EnterCriticalSection(&mutex);
+ if (hListFont!=NULL) {
+ DeleteObject(hListFont);
+ }
+ if (hListGroupFont!=NULL) {
+ DeleteObject(hListGroupFont);
+ }
+ Font * font = Options::getFont(Options::FONT_USERLIST);
+ colorListText = font->getColor();
+ hListFont = CreateFontA(font->getSize(), 0, 0, 0,
+ font->getStyle() & Font::BOLD ? FW_BOLD : FW_NORMAL,
+ font->getStyle() & Font::ITALIC ? 1 : 0,
+ font->getStyle() & Font::UNDERLINE ? 1 : 0, 0,
+ font->getCharSet(),
+ OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH | FF_ROMAN,
+ font->getFace());
+ font = Options::getFont(Options::FONT_USERLISTGROUP);
+ colorListGroupText = font->getColor();
+ hListGroupFont = CreateFontA(font->getSize(), 0, 0, 0,
+ font->getStyle() & Font::BOLD ? FW_BOLD : FW_NORMAL,
+ font->getStyle() & Font::ITALIC ? 1 : 0,
+ font->getStyle() & Font::UNDERLINE ? 1 : 0, 0,
+ font->getCharSet(),
+ OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FIXED_PITCH | FF_ROMAN,
+ font->getFace());
+
+ for (ChatWindow *ptr=list;ptr!=NULL;ptr=ptr->getNext()) {
+ ptr->refreshSettings();
+ InvalidateRect(ptr->getHWND(), NULL, FALSE);
+ }
+ LeaveCriticalSection(&mutex);
+}
+HFONT ChatWindow::getListFont() {
+ return hListFont;
+}
+
+HFONT ChatWindow::getListGroupFont() {
+ return hListGroupFont;
+}
+
+COLORREF ChatWindow::getListTextColor() {
+ return colorListText;
+}
+
+COLORREF ChatWindow::getListGroupTextColor() {
+ return colorListGroupText;
+}
+
+HTREEITEM ChatWindow::getTreeItem(int index) {
+ return hUserGroups[index];
+}
+
+void ChatWindow::setTreeItem(int index, HTREEITEM hTreeItem) {
+ hUserGroups[index]=hTreeItem;
+}
+
+int ChatWindow::getDefaultOptions() {
+ return FLAG_SHOW_NICKNAMES | FLAG_SHOW_TIMESTAMP | FLAG_FORMAT_ALL | FLAG_LOG_MESSAGES | FLAG_OPT_SENDONENTER;
+}
+
+void ChatWindow::clearLog() {
+ if (getHWNDLog()!=NULL) {
+ IEVIEWEVENT iee;
+ ZeroMemory(&iee, sizeof(iee));
+ iee.cbSize = sizeof(iee);
+ iee.iType = IEE_CLEAR_LOG;
+ iee.dwFlags = IEEF_NO_UNICODE;
+ iee.hwnd = hWndLog;
+ iee.hContact = NULL;
+ iee.codepage = CP_ACP;
+ iee.pszProto = getModule();
+ CallService(MS_IEVIEW_EVENT, 0, (LPARAM)&iee);
+ } else {
+ SetDlgItemTextA(getHWND(), IDC_LOG, "");
+ }
+ isEmpty = true;
+ eventList.clear();
+}
+
+void ChatWindow::rebuildLog() {
+ int nMin, nMax;
+ HWND hwndLog;
+ if (getHWNDLog()!=NULL) {
+ IEVIEWEVENT iee;
+ ZeroMemory(&iee, sizeof(iee));
+ iee.cbSize = sizeof(iee);
+ iee.iType = IEE_CLEAR_LOG;
+ iee.dwFlags = IEEF_NO_UNICODE;
+ iee.hwnd = hWndLog;
+ iee.hContact = NULL;
+ iee.codepage = CP_ACP;
+ iee.pszProto = getModule();
+ CallService(MS_IEVIEW_EVENT, 0, (LPARAM)&iee);
+ } else {
+ SetDlgItemTextA(getHWND(), IDC_LOG, "");
+ }
+ isEmpty = true;
+ for (ChatEvent* event=eventList.getEvents();event!=NULL;event=event->getNext()) {
+ appendMessage(event->getEvent());
+ }
+ if (getHWNDLog()==NULL) {
+ if (ServiceExists(MS_SMILEYADD_REPLACESMILEYS)) PostMessage(getHWND(), WM_TLEN_SMILEY, 0, 0);
+ hwndLog = GetDlgItem(getHWND(), IDC_LOG);
+ int len = GetWindowTextLengthA(hwndLog);
+ SendMessage(hwndLog, EM_SETSEL, len - 1, len - 1);
+ GetScrollRange(hwndLog, SB_VERT, &nMin, &nMax);
+ SetScrollPos(hwndLog, SB_VERT, nMax, TRUE);
+ PostMessage(hwndLog, WM_VSCROLL, MAKEWPARAM(SB_THUMBPOSITION, nMax), (LPARAM) NULL);
+ }
+}
+
+int ChatWindow::logEvent(const MUCCEVENT *event) {
+ /* chat.dll mod*/
+ /*
+ if (event->iType == MUCC_EVENT_MESSAGE) {
+ GCDEST gcdest;
+ GCEVENT gcevent = {sizeof(GCEVENT), &gcdest};
+ gcdest.pszModule = (char *)this->getModule();
+ gcdest.pszID = (char *)this->getRoomId();
+ gcdest.iType = GC_EVENT_MESSAGE;
+ gcevent.pszText = event->pszText;
+ gcevent.pszNick = event->pszNick;
+ gcevent.pszUID = event->pszUID;
+ gcevent.bIsMe = event->bIsMe;
+ gcevent.bAddToLog = TRUE;
+ gcevent.time = event->time;
+ CallService(MS_GC_EVENT, 0, (LPARAM)&gcevent);
+
+ }
+ if (event->iType == MUCC_EVENT_STATUS) {
+ const char *groupNames[] = {"Global Owners", "Owners", "Admins", "Moderators", "Users"};
+ GCDEST gcdest;
+ GCEVENT gcevent = {sizeof(GCEVENT), &gcdest};
+ gcdest.pszModule = (char *)this->getModule();
+ gcdest.pszID = (char *)this->getRoomId();
+ gcevent.pszText = event->pszText;
+ gcevent.pszNick = event->pszNick;
+ int group = 4;
+ if (event->dwFlags&MUCC_EF_USER_GLOBALOWNER) {
+ group = 0;
+ } else if (event->dwFlags&MUCC_EF_USER_OWNER) {
+ group = 1;
+ } else if (event->dwFlags&MUCC_EF_USER_ADMIN) {
+ group = 2;
+ } else if (event->dwFlags&MUCC_EF_USER_MODERATOR) {
+ group = 3;
+ }
+ gcevent.pszStatus = Translate(groupNames[group]);
+ gcevent.pszUID = event->pszUID;
+ gcevent.bIsMe = event->bIsMe;
+ gcevent.bAddToLog = TRUE;
+ gcevent.time = event->time;
+ if (event->dwData == ID_STATUS_ONLINE) {
+ gcdest.iType = GC_EVENT_JOIN;
+ } else {
+ gcdest.iType = GC_EVENT_PART;
+ }
+ CallService(MS_GC_EVENT, 0, (LPARAM)&gcevent);
+ }
+ */
+ /* chat.dll mod*/
+
+ int nMin, nMax;
+ HWND hwndLog;
+ if (event->iType != MUCC_EVENT_ERROR) {
+ if (eventList.addEvent(event)) {
+ rebuildLog();
+ return 1;
+ }
+ }
+ if (event->iType == MUCC_EVENT_MESSAGE) {
+ wasFirstMessage = 1;
+ appendMessage(event);
+ container->remoteSetUnread(this, 1);
+ } else {
+ appendMessage(event);
+ }
+ if (event->iType==MUCC_EVENT_MESSAGE && getOptions() & FLAG_FLASH_MESSAGES) {
+ container->remoteFlashWindow();
+ } else if (event->iType==MUCC_EVENT_STATUS && event->dwData==ID_STATUS_ONLINE && getOptions() & FLAG_FLASH_JOINED) {
+ container->remoteFlashWindow();
+ } else if (event->iType==MUCC_EVENT_STATUS && event->dwData==ID_STATUS_OFFLINE && getOptions() & FLAG_FLASH_LEFT) {
+ container->remoteFlashWindow();
+ } else if (event->iType==MUCC_EVENT_TOPIC && getOptions() & FLAG_FLASH_TOPIC) {
+ container->remoteFlashWindow();
+ }
+ if (getHWNDLog()==NULL) {
+ if (ServiceExists(MS_SMILEYADD_REPLACESMILEYS)) PostMessage(getHWND(), WM_TLEN_SMILEY, 0, 0);
+ hwndLog = GetDlgItem(getHWND(), IDC_LOG);
+ int len = GetWindowTextLengthA(hwndLog);
+ SendMessage(hwndLog, EM_SETSEL, len - 1, len - 1);
+ GetScrollRange(hwndLog, SB_VERT, &nMin, &nMax);
+ SetScrollPos(hwndLog, SB_VERT, nMax, TRUE);
+ PostMessage(hwndLog, WM_VSCROLL, MAKEWPARAM(SB_THUMBPOSITION, nMax), (LPARAM) NULL);
+ }
+ return 1;
+}
+
+void ChatWindow::createRTFHeader() {
+ char *rtf;
+ int i, msgSize;
+ //, , iFontSize, bItalic, bBold, bUnderline;
+ rtf = NULL;
+ JabberStringAppend(&rtf, &msgSize, "{\\rtf1\\ansi\\deff0{\\fonttbl");
+
+ for (i=0;i<FontList::getFontNum();i++) {
+ Font *font = FontList::getFont(i);
+ JabberStringAppend(&rtf, &msgSize, "{\\f%u\\fnil\\fcharset%u %s;}", font->getCharSet(), font->getFace());
+ }
+ JabberStringAppend(&rtf, &msgSize, "}{\\colortbl ");
+ for (i=0;i<FontList::getFontNum();i++) {
+ Font *font = FontList::getFont(i);
+ DWORD color = font->getColor();
+ JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF);
+ }
+ JabberStringAppend(&rtf, &msgSize, "}");
+}
+
+
+int ChatWindow::appendMessage(const MUCCEVENT *event) {
+ char timestampStr[100], str[512];
+ char *rtf, *escapedStr = NULL, *escapedNick = NULL;
+ Font *fontTimestamp, *fontName, *fontMessage; //*fontColon,
+ int msgSize;
+ DWORD color;
+ int iFontSize, bItalic, bBold, bUnderline;
+ HWND hwndLog;
+ DBTIMETOSTRING dbtts;
+ CHARRANGE sel;
+ SETTEXTEX stt;
+ //tm *ltime;
+
+ if (event->iType!=MUCC_EVENT_STATUS && event->iType!=MUCC_EVENT_STATUS && event->iType!=MUCC_EVENT_ERROR
+ && event->iType!=MUCC_EVENT_TOPIC && event->iType != MUCC_EVENT_MESSAGE) {
+ return 0;
+ }
+ if (event->iType==MUCC_EVENT_MESSAGE && !(getOptions() & FLAG_LOG_MESSAGES)) {
+ return 0;
+ } else if (event->iType==MUCC_EVENT_STATUS && event->dwData==ID_STATUS_ONLINE && !(getOptions() & FLAG_LOG_JOINED)) {
+ return 0;
+ } else if (event->iType==MUCC_EVENT_STATUS && event->dwData==ID_STATUS_OFFLINE && !(getOptions() & FLAG_LOG_LEFT)) {
+ return 0;
+ } else if (event->iType==MUCC_EVENT_TOPIC && !(getOptions() & FLAG_LOG_TOPIC)) {
+ return 0;
+ }
+
+ if (getHWNDLog()!=NULL) {
+ IEVIEWEVENTDATA ied;
+ IEVIEWEVENT iee;
+ IEVIEWWINDOW iew;
+ ZeroMemory(&iee, sizeof(iee));
+ iee.cbSize = sizeof(iee);
+ iee.dwFlags = IEEF_NO_UNICODE;
+ iee.hwnd = hWndLog;
+ iee.hContact = NULL;
+ iee.iType = IEE_LOG_MEM_EVENTS;
+ iee.codepage = CP_ACP;
+ iee.pszProto = getModule();
+ iee.eventData = &ied;
+ iee.count = 1;
+
+ ied.cbSize = sizeof(IEVIEWEVENTDATA);
+ if (event->iType==MUCC_EVENT_MESSAGE) {
+ ied.iType = IEED_MUCC_EVENT_MESSAGE;
+ } else if (event->iType==MUCC_EVENT_STATUS && event->dwData==ID_STATUS_ONLINE) {
+ ied.iType = IEED_MUCC_EVENT_JOINED;
+ } else if (event->iType==MUCC_EVENT_STATUS && event->dwData==ID_STATUS_OFFLINE) {
+ ied.iType = IEED_MUCC_EVENT_LEFT;
+ } else if (event->iType==MUCC_EVENT_TOPIC) {
+ ied.iType = IEED_MUCC_EVENT_TOPIC;
+ } else if (event->iType==MUCC_EVENT_ERROR) {
+ ied.iType = IEED_MUCC_EVENT_ERROR;
+ }
+ ied.dwFlags = getOptions() & FLAG_FORMAT_ALL;
+ ied.next = NULL;
+ ied.color = event->color;
+ ied.fontSize = event->iFontSize;
+ ied.fontStyle = event->dwFlags;
+ ied.fontName = getFontName(event->iFont);
+ ied.pszNick = event->pszNick;
+ ied.pszText = event->pszText;
+ ied.time = event->time;
+ ied.dwData = getOptions(); // event->dwData;
+ ied.bIsMe = event->bIsMe;
+ CallService(MS_IEVIEW_EVENT, 0, (LPARAM)&iee);
+
+ iew.cbSize = sizeof(IEVIEWWINDOW);
+ iew.iType = IEW_SCROLLBOTTOM;
+ iew.hwnd = hWndLog;
+ CallService(MS_IEVIEW_WINDOW, 0, (LPARAM)&iew);
+ return 1;
+ }
+ rtf = NULL;
+ fontTimestamp = FontList::getFont(FontList::FONT_TIMESTAMP);
+// fontColon = FontList::getFont(FontList::FONT_COLON);
+ if (event->iType == MUCC_EVENT_MESSAGE) {
+ escapedStr=JabberRtfEscape((char *)event->pszText);
+ escapedNick=JabberRtfEscape((char *)event->pszNick);
+ if (event->bIsMe) {
+ fontName = FontList::getFont(FontList::FONT_MYNAME);
+ fontMessage = FontList::getFont(FontList::FONT_OUTMESSAGE);
+ } else {
+ fontName = FontList::getFont(FontList::FONT_OTHERSNAMES);
+ fontMessage = FontList::getFont(FontList::FONT_INMESSAGE);
+ }
+ } else {
+ fontName = FontList::getFont(FontList::FONT_ERROR);
+ if (event->iType == MUCC_EVENT_ERROR) {
+ escapedStr = JabberRtfEscape((char *)event->pszText);
+ fontMessage = FontList::getFont(FontList::FONT_ERROR);
+ } else if (event->iType == MUCC_EVENT_STATUS) {
+ if (event->dwData == ID_STATUS_ONLINE) {
+ fontMessage = FontList::getFont(FontList::FONT_JOINED);
+ _snprintf(str, sizeof(str), Translate("%s has joined."), event->pszNick);
+ } else {
+ fontMessage = FontList::getFont(FontList::FONT_LEFT);
+ _snprintf(str, sizeof(str), Translate("%s has left."), event->pszNick);
+ }
+ escapedStr = JabberRtfEscape(str);
+ } else if (event->iType == MUCC_EVENT_TOPIC) {
+ fontMessage = FontList::getFont(FontList::FONT_TOPIC);
+ _snprintf(str, sizeof(str), Translate("The topic is %s."), event->pszText);
+ escapedStr = JabberRtfEscape(str);
+ }
+ }
+ //ltime = localtime(&event->time);
+ JabberStringAppend(&rtf, &msgSize, "{\\rtf1\\ansi\\deff0{\\fonttbl");
+ JabberStringAppend(&rtf, &msgSize, "{\\f0\\fnil\\fcharset%u %s;}", fontTimestamp->getCharSet(), fontTimestamp->getFace());
+ JabberStringAppend(&rtf, &msgSize, "{\\f1\\fnil\\fcharset%u %s;}", fontName->getCharSet(), fontName->getFace());
+ if (event->iType == MUCC_EVENT_MESSAGE && getOptions()&FLAG_FORMAT_FONT) {
+ JabberStringAppend(&rtf, &msgSize, "{\\f2\\fnil\\fcharset%u %s;}", fontMessage->getCharSet(), getFontName(event->iFont));
+ } else {
+ JabberStringAppend(&rtf, &msgSize, "{\\f2\\fnil\\fcharset%u %s;}", fontMessage->getCharSet(), fontMessage->getFace());
+ }
+ JabberStringAppend(&rtf, &msgSize, "}{\\colortbl ");
+ color = fontTimestamp->getColor();
+ JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF);
+ color = fontName->getColor();
+ JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF);
+ if (event->iType == MUCC_EVENT_MESSAGE && getOptions()&FLAG_FORMAT_COLOR && event->color!=0xFFFFFFFF) {
+ color = event->color;
+ } else {
+ color = fontMessage->getColor();
+ }
+ JabberStringAppend(&rtf, &msgSize, "\\red%d\\green%d\\blue%d;", color&0xFF, (color>>8)&0xFF, (color>>16)&0xFF);
+ JabberStringAppend(&rtf, &msgSize, "}\\pard");
+ if (!isEmpty) {
+ JabberStringAppend(&rtf, &msgSize, "\\par");
+ }
+ isEmpty = false;
+ if (event->iType == MUCC_EVENT_MESSAGE) {
+ if (getOptions()&FLAG_SHOW_DATE || getOptions()&FLAG_SHOW_TIMESTAMP) {
+ bBold = fontTimestamp->getStyle() & Font::BOLD ? 1 : 0;
+ bItalic = fontTimestamp->getStyle() & Font::ITALIC ? 1 : 0;
+ bUnderline = fontTimestamp->getStyle() & Font::UNDERLINE ? 1 : 0;
+ iFontSize = fontTimestamp->getSize();
+ iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY;
+ dbtts.cbDest = 90;
+ dbtts.szDest = timestampStr;
+ timestampStr[0]='\0';
+ //time_t time = time
+ if (getOptions()&FLAG_SHOW_DATE && getOptions()&FLAG_SHOW_TIMESTAMP) {
+ if (getOptions()&FLAG_LONG_DATE) {
+ dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"D s" : (char *)"D t";
+ } else {
+ dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"d s" : (char *)"d t";
+ }
+ } else if (getOptions()&FLAG_SHOW_DATE) {
+ dbtts.szFormat = getOptions()&FLAG_LONG_DATE ? (char *)"D" : (char *)"d";
+ } else if (getOptions()&FLAG_SHOW_TIMESTAMP) {
+ dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"s" : (char *)"t";
+ } else {
+ dbtts.szFormat = (char *)"";
+ }
+ CallService(MS_DB_TIME_TIMESTAMPTOSTRING, (WPARAM)event->time, (LPARAM) & dbtts);
+ JabberStringAppend(&rtf, &msgSize, "\\f0\\cf0\\fs%d\\b%d\\i%d%s %s ",
+ iFontSize,
+ bBold,
+ bItalic,
+ bUnderline?"\\ul":"",
+ timestampStr);
+ }
+ bBold = fontName->getStyle() & Font::BOLD ? 1 : 0;
+ bItalic = fontName->getStyle() & Font::ITALIC ? 1 : 0;
+ bUnderline = fontName->getStyle() & Font::UNDERLINE ? 1 : 0;
+ iFontSize = fontName->getSize();
+ iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY;
+ if (getOptions()&FLAG_SHOW_NICKNAMES) {
+ JabberStringAppend(&rtf, &msgSize, "\\f1\\cf1\\fs%d\\b%d\\i%d%s %s: ",
+ iFontSize,
+ bBold,
+ bItalic,
+ bUnderline?"\\ul":"",
+ escapedNick);
+ }
+ bBold = fontMessage->getStyle() & Font::BOLD ? 1 : 0;
+ bItalic = fontMessage->getStyle() & Font::ITALIC ? 1 : 0;
+ bUnderline = fontMessage->getStyle() & Font::UNDERLINE ? 1 : 0;
+ iFontSize = fontMessage->getSize();
+ iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY;
+ if (getOptions()&FLAG_FORMAT_STYLE) {
+ bBold = bItalic = bUnderline = 0;
+ if (event->dwFlags & MUCC_EF_FONT_BOLD) bBold = 1;
+ if (event->dwFlags & MUCC_EF_FONT_ITALIC) bItalic = 1;
+ if (event->dwFlags & MUCC_EF_FONT_UNDERLINE) bUnderline = 1;
+ }
+ if (getOptions()&FLAG_FORMAT_SIZE) {
+ if (event->iFontSize != 0) iFontSize = 2 * event->iFontSize;
+ }
+ if (getOptions()&FLAG_MSGINNEWLINE) {
+ JabberStringAppend(&rtf, &msgSize, "\\line");
+ }
+ JabberStringAppend(&rtf, &msgSize, "\\f2\\cf2\\fs%d\\b%d\\i%d%s %s",
+ iFontSize,
+ bBold,
+ bItalic,
+ bUnderline?"\\ul":"",
+ escapedStr);
+ } else {
+ if (event->iType == MUCC_EVENT_ERROR) {
+ bBold = fontName->getStyle() & Font::BOLD ? 1 : 0;
+ bItalic = fontName->getStyle() & Font::ITALIC ? 1 : 0;
+ bUnderline = fontName->getStyle() & Font::UNDERLINE ? 1 : 0;
+ iFontSize = fontName->getSize();
+ iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY;
+ JabberStringAppend(&rtf, &msgSize, "\\f1\\cf1\\fs%d\\b%d\\i%d%s %s: ",
+ iFontSize,
+ bBold,
+ bItalic,
+ bUnderline?"\\ul":"",
+ Translate("Error"));
+ } else {
+ if (getOptions()&FLAG_SHOW_DATE || getOptions()&FLAG_SHOW_TIMESTAMP) {
+ bBold = fontTimestamp->getStyle() & Font::BOLD ? 1 : 0;
+ bItalic = fontTimestamp->getStyle() & Font::ITALIC ? 1 : 0;
+ bUnderline = fontTimestamp->getStyle() & Font::UNDERLINE ? 1 : 0;
+ iFontSize = fontTimestamp->getSize();
+ iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY;
+ dbtts.cbDest = 90;
+ dbtts.szDest = timestampStr;
+ timestampStr[0]='\0';
+ //time_t time = time
+ if (getOptions()&FLAG_SHOW_DATE && getOptions()&FLAG_SHOW_TIMESTAMP) {
+ if (getOptions()&FLAG_LONG_DATE) {
+ dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"D s" : (char *)"D t";
+ } else {
+ dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"d s" : (char *)"d t";
+ }
+ } else if (getOptions()&FLAG_SHOW_DATE) {
+ dbtts.szFormat = getOptions()&FLAG_LONG_DATE ? (char *)"D" : (char *)"d";
+ } else if (getOptions()&FLAG_SHOW_TIMESTAMP) {
+ dbtts.szFormat = getOptions()&FLAG_SHOW_SECONDS ? (char *)"s" : (char *)"t";
+ } else {
+ dbtts.szFormat = (char *)"";
+ }
+ CallService(MS_DB_TIME_TIMESTAMPTOSTRING, (WPARAM)event->time, (LPARAM) & dbtts);
+ JabberStringAppend(&rtf, &msgSize, "\\f0\\cf0\\fs%d\\b%d\\i%d%s %s ",
+ iFontSize,
+ bBold,
+ bItalic,
+ bUnderline?"\\ul":"",
+ timestampStr);
+ }
+ }
+ bBold = fontMessage->getStyle() & Font::BOLD ? 1 : 0;
+ bItalic = fontMessage->getStyle() & Font::ITALIC ? 1 : 0;
+ bUnderline = fontMessage->getStyle() & Font::UNDERLINE ? 1 : 0;
+ iFontSize = fontMessage->getSize();
+ iFontSize = 2 * abs((signed char)iFontSize) * 74 / logPixelSY;
+ JabberStringAppend(&rtf, &msgSize, "\\f2\\cf2\\fs%d\\b%d\\i%d%s %s",
+ iFontSize,
+ bBold,
+ bItalic,
+ bUnderline?"\\ul":"",
+ escapedStr);
+ }
+ JabberStringAppend(&rtf, &msgSize, "}");
+ hwndLog = GetDlgItem(getHWND(), IDC_LOG);
+ sel.cpMin = sel.cpMax = GetWindowTextLength(hwndLog);
+ SendMessage(hwndLog, EM_EXSETSEL, 0, (LPARAM) &sel);
+ stt.flags = ST_SELECTION;
+ stt.codepage = CP_ACP;
+ SendMessage(hwndLog, EM_SETTEXTEX, (WPARAM) &stt, (LPARAM) rtf);
+ free(rtf);
+ if (escapedStr!=NULL) free(escapedStr);
+ if (escapedNick!=NULL) free(escapedNick);
+ return 1;
+}
+
+void ChatWindow::setFont(int font, int size, int bBold, int bItalic, int bUnderline, COLORREF color) {
+ if (hEditFont!=NULL) {
+ DeleteObject(hEditFont);
+ }
+ hEditFont = CreateFontA(MulDiv(-size, logPixelSY, 74), 0, 0, 0, bBold?FW_BOLD:FW_NORMAL,
+ bItalic, bUnderline, 0, 238, OUT_DEFAULT_PRECIS,
+ CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
+ FIXED_PITCH | FF_ROMAN,
+ getFontName(font));
+ SendDlgItemMessage(hWnd, IDC_EDIT, WM_SETFONT, (WPARAM) hEditFont, TRUE);
+ this->font = font;
+ this->fontSize = size;
+ this->bBold = bBold;
+ this->bItalic = bItalic;
+ this->bUnderline = bUnderline;
+ this->fontColor = color;
+}
+
+int ChatWindow::getFontStyle() {
+ int style = 0;
+ if (bBold) style |= MUCC_EF_FONT_BOLD;
+ if (bItalic) style |= MUCC_EF_FONT_ITALIC;
+ if (bUnderline) style |= MUCC_EF_FONT_UNDERLINE;
+ return style;
+}
+
+int ChatWindow::getFont() {
+ return font;
+}
+
+int ChatWindow::getFontSize() {
+ return fontSize;
+}
+
+COLORREF ChatWindow::getFontColor() {
+ return fontColor;
+}
+
+void ChatWindow ::queryResultContacts(MUCCQUERYRESULT *queryResult) {
+ HelperDialog::inviteDlg(this, queryResult);
+}
+
+void ChatWindow ::queryResultUsers(MUCCQUERYRESULT *queryResult) {
+ if (adminWindow!=NULL) {
+ adminWindow->queryResultUsers(queryResult);
+ }
+}
+
+ChatWindow * ChatWindow::getWindow(const char *module, const char *roomId) {
+ ChatWindow *ptr;
+ EnterCriticalSection(&mutex);
+ for (ptr=list;ptr!=NULL;ptr=ptr->getNext()) {
+ if (strcmp(ptr->getRoomId(), roomId)==0 && strcmp(ptr->getModule(), module)==0) {
+ break;
+ }
+ }
+ LeaveCriticalSection(&mutex);
+ return ptr;
+}
+
+
+static DWORD CALLBACK EditStreamCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG * pcb)
+{
+ char *szFilename = (char *)dwCookie;
+ FILE *file;
+ file = fopen(szFilename, "ab");
+ if (file != NULL) {
+ *pcb = (LONG)fwrite(pbBuff, (size_t)cb, (size_t)1, file);
+ fclose(file);
+ return 0;
+ }
+ return 1;
+}
+
+static BOOL CALLBACK EditWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ ChatWindow *chat;
+ chat = (ChatWindow *) GetWindowLongPtr(GetParent(hwnd), GWLP_USERDATA);
+ switch (msg) {
+// case WM_GETDLGCODE:
+// return DLGC_WANTALLKEYS; //DLGC_WANTARROWS|DLGC_WANTCHARS|DLGC_HASSETSEL|DLGC_WANTALLKEYS;
+ case WM_CHAR:
+ if (wParam=='\r' || wParam=='\n') {
+ if (((GetKeyState(VK_CONTROL)&0x8000)==0) == ((Options::getChatWindowOptions() & ChatWindow::FLAG_OPT_SENDONENTER) != 0)) {
+ PostMessage(GetParent(hwnd), WM_COMMAND, IDOK, 0);
+ return FALSE;
+ }
+ }
+ if (wParam == 1 && GetKeyState(VK_CONTROL) & 0x8000) { //ctrl-a
+ SendMessage(hwnd, EM_SETSEL, 0, -1);
+ return 0;
+ }
+ if (wParam == 23 && GetKeyState(VK_CONTROL) & 0x8000) { // ctrl-w
+ SendMessage(GetParent(hwnd), WM_CLOSE, 0, 0);
+ return 0;
+ }
+ break;
+ }
+ return CallWindowProc(oldEditWndProc, hwnd, msg, wParam, lParam);
+}
+
+static BOOL CALLBACK SplitterWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ ChatWindow *chat;
+ chat = (ChatWindow *) GetWindowLongPtr(GetParent(hwnd), GWLP_USERDATA);
+ switch (msg) {
+ case WM_NCHITTEST:
+ return HTCLIENT;
+ case WM_SETCURSOR:
+ RECT rc;
+ GetClientRect(hwnd, &rc);
+ SetCursor(rc.right > rc.bottom ? hCurSplitNS : hCurSplitWE);
+ return TRUE;
+ case WM_LBUTTONDOWN:
+ SetCapture(hwnd);
+ return 0;
+ case WM_MOUSEMOVE:
+ if (GetCapture() == hwnd) {
+ HWND hParent;
+ RECT rc;
+ POINT pt;
+ hParent = GetParent(hwnd);
+ GetClientRect(hwnd, &rc);
+ if (rc.right < rc.bottom) {
+ pt.x = LOWORD(GetMessagePos());
+ GetClientRect(hParent, &rc);
+ ScreenToClient(hParent, &pt);
+ if (pt.x < chat->vSplitterMinLeft)
+ pt.x = chat->vSplitterMinLeft;
+ if (rc.right-pt.x < chat->vSplitterMinRight)
+ pt.x = rc.right-chat->vSplitterMinRight;
+ if (chat->vSplitterPos != rc.right-pt.x) {
+ chat->vSplitterPos = rc.right-pt.x;
+ SendMessage(hParent, WM_SIZE, SIZE_RESTORED, (rc.bottom<<16)+rc.right);
+ }
+ } else {
+ pt.y = HIWORD(GetMessagePos());
+ GetClientRect(hParent, &rc);
+ ScreenToClient(hParent, &pt);
+ if (pt.y < chat->hSplitterMinTop)
+ pt.y = chat->hSplitterMinTop;
+ if (rc.bottom-pt.y < chat->hSplitterMinBottom)
+ pt.y = rc.bottom-chat->hSplitterMinBottom;
+ if (chat->hSplitterPos != rc.bottom-pt.y) {
+ chat->hSplitterPos = rc.bottom-pt.y;
+ SendMessage(hParent, WM_SIZE, SIZE_RESTORED, (rc.bottom<<16)+rc.right);
+ }
+ }
+ }
+ return 0;
+ case WM_LBUTTONUP:
+ ReleaseCapture();
+ return 0;
+ }
+ return CallWindowProc(oldSplitterWndProc, hwnd, msg, wParam, lParam);
+}
+
+
+
+
+static INT_PTR CALLBACK LogDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ int i;
+ ChatWindow *chatWindow;
+ chatWindow = (ChatWindow *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ if (msg!=WM_INITDIALOG && chatWindow==NULL) {
+ return FALSE;
+ }
+ switch (msg) {
+ case WM_INITDIALOG:
+ HDC hdc;
+ TranslateDialogDefault(hwndDlg);
+ hdc = GetDC(NULL);
+ logPixelSY = GetDeviceCaps(hdc, LOGPIXELSY);
+ ReleaseDC(NULL, hdc);
+ SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM) muccIcon[MUCC_IDI_CHAT]);
+
+ chatWindow = (ChatWindow *) lParam;
+ chatWindow->setHWND(hwndDlg);
+ ChatWindow::refreshSettings(0);
+ oldSplitterWndProc = (WNDPROC)SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_HSPLIT), GWLP_WNDPROC, (LONG_PTR) SplitterWndProc);
+ oldSplitterWndProc = (WNDPROC)SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_VSPLIT), GWLP_WNDPROC, (LONG_PTR) SplitterWndProc);
+ oldEditWndProc = (WNDPROC)SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT), GWLP_WNDPROC, (LONG_PTR) EditWndProc);
+ ShowWindow(GetDlgItem(hwndDlg, IDC_LIST), SW_HIDE);
+ chatWindow->hSplitterMinTop = 90;
+ chatWindow->hSplitterMinBottom = 40;
+ chatWindow->hSplitterPos=50;
+ chatWindow->vSplitterMinLeft = 100;
+ chatWindow->vSplitterMinRight = 80;
+ chatWindow->vSplitterPos=110;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) chatWindow);
+ SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT), GWLP_USERDATA, (LONG_PTR) chatWindow);
+ chatWindow->refreshSettings();
+
+ SetWindowTextA(hwndDlg, chatWindow->getRoomName());
+ SendDlgItemMessage(hwndDlg, IDC_BOLD, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_BOLD]);
+ SendDlgItemMessage(hwndDlg, IDC_ITALIC, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_ITALIC]);
+ SendDlgItemMessage(hwndDlg, IDC_UNDERLINE, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_UNDERLINE]);
+ SendDlgItemMessage(hwndDlg, IDC_SMILEYBTN, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_SMILEY]);
+
+ SendDlgItemMessage(hwndDlg, IDC_LOG, EM_SETEVENTMASK, 0, ENM_MOUSEEVENTS | ENM_LINK);
+ SendDlgItemMessage(hwndDlg, IDC_LOG, EM_SETUNDOLIMIT, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_LOG, EM_AUTOURLDETECT, (WPARAM) TRUE, 0);
+
+ // LoadImage(hInst, smadd_iconinfo.SmileyIcon, IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0));
+ SendDlgItemMessage(hwndDlg, IDC_OPTIONS, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_OPTIONS]);
+ SendDlgItemMessage(hwndDlg, IDC_INVITE, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_INVITE]);
+
+ SendDlgItemMessage(hwndDlg, IDC_TOPIC_BUTTON, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_INVITE, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BOLD, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_BOLD, BUTTONSETASPUSHBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_ITALIC, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_ITALIC, BUTTONSETASPUSHBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_UNDERLINE, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_UNDERLINE, BUTTONSETASPUSHBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_OPTIONS, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_SMILEYBTN, BUTTONSETASFLATBTN, 0, 0);
+
+ SetWindowLong(GetDlgItem(hwndDlg,IDC_TREELIST),GWL_STYLE,GetWindowLong(GetDlgItem(hwndDlg,IDC_TREELIST),GWL_STYLE)|TVS_NOHSCROLL);
+ SendDlgItemMessage(hwndDlg,IDC_TREELIST, CCM_SETVERSION,(WPARAM)5,0);
+ //TreeView_SetImageList(GetDlgItem(hwndDlg, IDC_TREELIST), hImageList, TVSIL_STATE);
+ TreeView_SetItemHeight(GetDlgItem(hwndDlg, IDC_TREELIST), 16);
+ TreeView_SetIndent(GetDlgItem(hwndDlg, IDC_TREELIST), 16);
+ for(i=0;i<chatWindow->getFontSizeNum();i++) {
+ char str[10];
+ sprintf(str, "%d", chatWindow->getFontSize(i));
+ int n = SendDlgItemMessageA(hwndDlg, IDC_FONTSIZE, CB_ADDSTRING, 0, (LPARAM) str);
+ SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_SETITEMDATA, n, chatWindow->getFontSize(i));
+ }
+ SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_SETCURSEL, Options::getChatWindowFontSize(), 0);
+ for(i=0;i<chatWindow->getFontNameNum();i++) {
+ int n = SendDlgItemMessageA(hwndDlg, IDC_FONT, CB_ADDSTRING, 0, (LPARAM) chatWindow->getFontName(i));
+ SendDlgItemMessage(hwndDlg, IDC_FONT, CB_SETITEMDATA, n, i);
+ }
+ SendDlgItemMessage(hwndDlg, IDC_FONT, CB_SETCURSEL, Options::getChatWindowFont(), 0);
+ CheckDlgButton(hwndDlg, IDC_BOLD, Options::getChatWindowFontStyle()&Font::BOLD ? TRUE : FALSE);
+ CheckDlgButton(hwndDlg, IDC_ITALIC, Options::getChatWindowFontStyle()&Font::ITALIC ? TRUE : FALSE);
+ CheckDlgButton(hwndDlg, IDC_UNDERLINE, Options::getChatWindowFontStyle()&Font::UNDERLINE ? TRUE : FALSE);
+ SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_SETCOLOUR, 0, (LPARAM)Options::getChatWindowFontColor());
+ chatWindow->setFont(Options::getChatWindowFont(),
+ chatWindow->getFontSize(Options::getChatWindowFontSize()),
+ Options::getChatWindowFontStyle()&Font::BOLD ? 1 : 0,
+ Options::getChatWindowFontStyle()&Font::ITALIC ? 1 : 0,
+ Options::getChatWindowFontStyle()&Font::UNDERLINE ? 1 : 0,
+ Options::getChatWindowFontColor());
+ if (ServiceExists(MS_IEVIEW_WINDOW) && Options::getChatWindowOptions() & ChatWindow::FLAG_OPT_ENABLEIEVIEW) {
+ IEVIEWWINDOW ieWindow;
+ ieWindow.cbSize = sizeof(IEVIEWWINDOW);
+ ieWindow.iType = IEW_CREATE;
+ ieWindow.dwFlags = 0;
+ ieWindow.dwMode = IEWM_MUCC;
+ ieWindow.parent = hwndDlg;
+ ieWindow.x = 0;
+ ieWindow.y = 0;
+ ieWindow.cx = 200;
+ ieWindow.cy = 300;
+ CallService(MS_IEVIEW_WINDOW, 0, (LPARAM)&ieWindow);
+ chatWindow->setHWNDLog(ieWindow.hwnd);
+ ShowWindow(GetDlgItem(hwndDlg, IDC_LOG), SW_HIDE);
+ }
+ SetWindowPos(hwndDlg, HWND_TOP, 0, 0, 540, 370, SWP_NOMOVE | SWP_SHOWWINDOW);
+ SetFocus(GetDlgItem(hwndDlg, IDC_EDIT));
+ chatWindow->clearLog();
+ SetEvent(chatWindow->getEvent());
+ return TRUE;
+ break;
+ case DM_CHAT_EVENT:
+ MUCCEVENT *mucEvent;
+ mucEvent = (MUCCEVENT *) lParam;
+ switch (mucEvent->iType) {
+ case MUCC_EVENT_MESSAGE:
+ chatWindow->logEvent(mucEvent);
+ break;
+ case MUCC_EVENT_TOPIC:
+ chatWindow->changeTopic(mucEvent);
+ break;
+ case MUCC_EVENT_STATUS:
+ chatWindow->changePresence(mucEvent);
+ break;
+ case MUCC_EVENT_ERROR:
+ chatWindow->logEvent(mucEvent);
+ break;
+ //case MUCC_EVENT_LEAVE:
+ // DestroyWindow(hwndDlg);
+ // break;
+ case MUCC_EVENT_ROOM_INFO:
+ chatWindow->changeRoomInfo(mucEvent);
+ break;
+ }
+ return TRUE;
+ case DM_CHAT_QUERY:
+ MUCCQUERYRESULT *queryResult;
+ queryResult = (MUCCQUERYRESULT *)lParam;
+ switch (queryResult->iType) {
+ case MUCC_EVENT_QUERY_CONTACTS:
+ chatWindow->queryResultContacts(queryResult);
+ break;
+ case MUCC_EVENT_QUERY_USERS:
+ chatWindow->queryResultUsers(queryResult);
+ break;
+
+ }
+ return TRUE;
+ case WM_SETFOCUS:
+ SetFocus(GetDlgItem(hwndDlg, IDC_EDIT));
+ return TRUE;
+ case WM_GETMINMAXINFO:
+ MINMAXINFO *mmi;
+ mmi = (MINMAXINFO *) lParam;
+ mmi->ptMinTrackSize.x = 370;
+ mmi->ptMinTrackSize.y = 130;
+ return FALSE;
+ case WM_SIZE:
+ if (wParam!=SIZE_MINIMIZED) {
+ int dlgWidth, dlgHeight;
+ RECT rc;
+ HDWP hdwp;
+ GetClientRect(hwndDlg, &rc);
+ dlgWidth = rc.right-rc.left;
+ dlgHeight = rc.bottom-rc.top;
+ if (dlgHeight-chatWindow->hSplitterPos < chatWindow->hSplitterMinTop) {
+ chatWindow->hSplitterPos = dlgHeight-chatWindow->hSplitterMinTop;
+ }
+ if (chatWindow->hSplitterPos < chatWindow->hSplitterMinBottom) {
+ chatWindow->hSplitterPos = chatWindow->hSplitterMinBottom;
+ }
+ if (dlgWidth-chatWindow->vSplitterPos < chatWindow->vSplitterMinLeft) {
+ chatWindow->vSplitterPos = dlgWidth-chatWindow->vSplitterMinLeft;
+ }
+ if (chatWindow->vSplitterPos < chatWindow->vSplitterMinRight) {
+ chatWindow->vSplitterPos = chatWindow->vSplitterMinRight;
+ }
+
+ hdwp = BeginDeferWindowPos(15);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_TOPIC), 0, 70, 7, dlgWidth-140, 18, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_LOG), 0, 0, 30, dlgWidth-(chatWindow->vSplitterPos)-2, dlgHeight-(chatWindow->hSplitterPos)-30-26-2, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_TREELIST), 0, dlgWidth-(chatWindow->vSplitterPos)+2, 30, (chatWindow->vSplitterPos)-2, dlgHeight-(chatWindow->hSplitterPos)-30-26-2, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_EDIT), 0, 0, dlgHeight-(chatWindow->hSplitterPos)+2, dlgWidth, (chatWindow->hSplitterPos)-5, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_INVITE), 0, dlgWidth-31, dlgHeight-(chatWindow->hSplitterPos)-26, 31, 24, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_BOLD), 0, 0, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER );
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_ITALIC), 0, 24, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER );
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_UNDERLINE), 0, 48, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER );
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_COLOR), 0, 73, dlgHeight-(chatWindow->hSplitterPos)-25, 22, 22, SWP_NOZORDER );
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_FONT), 0, 98, dlgHeight-(chatWindow->hSplitterPos)-24, 110, 13, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_FONTSIZE), 0, 213, dlgHeight-(chatWindow->hSplitterPos)-24, 38, 13, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_SMILEYBTN), 0, 265, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_OPTIONS), 0, dlgWidth-79, dlgHeight-(chatWindow->hSplitterPos)-26, 24, 24, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_VSPLIT), 0, dlgWidth-(chatWindow->vSplitterPos)-2, 30, 4, dlgHeight-(chatWindow->hSplitterPos)-30-26-2, SWP_NOZORDER);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_HSPLIT), 0, 0, dlgHeight-(chatWindow->hSplitterPos)-2, dlgWidth-8, 4, SWP_NOZORDER);
+ EndDeferWindowPos(hdwp);
+ if (chatWindow->getHWNDLog()!=NULL) {
+ IEVIEWWINDOW ieWindow;
+ ieWindow.cbSize = sizeof(IEVIEWWINDOW);
+ ieWindow.iType = IEW_SETPOS;
+ ieWindow.parent = hwndDlg;
+ ieWindow.hwnd = chatWindow->getHWNDLog();
+ ieWindow.x = 0;
+ ieWindow.y = 30;
+ ieWindow.cx = dlgWidth-(chatWindow->vSplitterPos)-2;
+ ieWindow.cy = dlgHeight-(chatWindow->hSplitterPos)-30-26-2;
+ CallService(MS_IEVIEW_WINDOW, 0, (LPARAM)&ieWindow);
+ }
+ }
+ break;
+ /*
+ case WM_SYSCOMMAND:
+ if (wParam == SC_CLOSE) {
+ SendMessage(hwndDlg, WM_CLOSE, 1, 0);
+// muce.iType = MUCC_EVENT_LEAVE;
+// muce.pszModule = chatWindow->getModule();
+// muce.pszID = chatWindow->getRoomId();
+// NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+// delete chatWindow;
+ return TRUE;
+ }
+ break;
+ */
+ case WM_CLOSE:
+ //if (wParam != 1) { // esc
+ //return FALSE;
+ //}
+ DestroyWindow(hwndDlg);
+ return TRUE;
+ case WM_DESTROY:
+ {
+ MUCCEVENT muce;
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_LEAVE;
+ muce.pszModule = chatWindow->getModule();
+ muce.pszID = chatWindow->getRoomId();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ if (chatWindow->getHWNDLog()!=NULL) {
+ IEVIEWWINDOW ieWindow;
+ ieWindow.cbSize = sizeof(IEVIEWWINDOW);
+ ieWindow.iType = IEW_DESTROY;
+ ieWindow.hwnd = chatWindow->getHWNDLog();
+ CallService(MS_IEVIEW_WINDOW, 0, (LPARAM)&ieWindow);
+ }
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) NULL);
+ SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_HSPLIT), GWLP_WNDPROC, (LONG_PTR) oldSplitterWndProc);
+ SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_VSPLIT), GWLP_WNDPROC, (LONG_PTR) oldSplitterWndProc);
+ SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT), GWLP_WNDPROC, (LONG_PTR) oldEditWndProc);
+ delete chatWindow;
+ break;
+ }
+ case WM_TLEN_SMILEY:
+ if (ServiceExists(MS_SMILEYADD_REPLACESMILEYS)) {
+ SMADD_RICHEDIT2 smre;
+ smre.cbSize = sizeof(SMADD_RICHEDIT2);
+ smre.hwndRichEditControl = GetDlgItem(hwndDlg, IDC_LOG);
+ smre.Protocolname = (char *)chatWindow->getModule();
+ smre.rangeToReplace = NULL;
+ smre.useSounds = FALSE;
+ smre.disableRedraw = FALSE;
+ CallService(MS_SMILEYADD_REPLACESMILEYS, 0, (LPARAM) &smre);
+ }
+ break;
+
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_OPTIONS:
+ {
+ MUCCEVENT muce;
+ HMENU hMenu;
+ RECT rc;
+ int iSelection;
+ hMenu=GetSubMenu(LoadMenu(hInst, MAKEINTRESOURCE(IDR_CHATOPTIONS)),0);
+ CallService(MS_LANGPACK_TRANSLATEMENU,(WPARAM)hMenu,0);
+ GetWindowRect(GetDlgItem(hwndDlg, IDC_OPTIONS), &rc);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_SHOWNICKNAMES, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_SHOW_NICKNAMES ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_MSGINNEWLINE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_MSGINNEWLINE ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_SHOWDATE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_SHOW_DATE ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_SHOWTIMESTAMP, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_SHOW_TIMESTAMP ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_SHOWSECONDS, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_SHOW_SECONDS ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_USELONGDATE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LONG_DATE ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_FORMATFONT, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FORMAT_FONT ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_FORMATSIZE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FORMAT_SIZE ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_FORMATCOLOR, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FORMAT_COLOR ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_FORMATSTYLE, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FORMAT_STYLE ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_LOGMESSAGES, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LOG_MESSAGES ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_LOGJOINED, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LOG_JOINED ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_LOGLEFT, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LOG_LEFT ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_LOGTOPIC, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_LOG_TOPIC ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_FLASHMESSAGES, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FLASH_MESSAGES ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_FLASHJOINED, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FLASH_JOINED ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_FLASHLEFT, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FLASH_LEFT ? MF_CHECKED : MF_UNCHECKED);
+ CheckMenuItem(hMenu, ID_OPTIONMENU_FLASHTOPIC, MF_BYCOMMAND | chatWindow->getOptions()&ChatWindow::FLAG_FLASH_TOPIC ? MF_CHECKED : MF_UNCHECKED);
+ if (chatWindow->getMe()!=NULL) {
+ if (chatWindow->getMe()->getFlags() & (MUCC_EF_USER_OWNER | MUCC_EF_USER_ADMIN)) {
+ EnableMenuItem(hMenu, ID_ADMINMENU_ADMIN, MF_BYCOMMAND | MF_ENABLED);
+ EnableMenuItem(hMenu, ID_ADMINMENU_BROWSE, MF_BYCOMMAND | MF_ENABLED);
+ }
+ if (chatWindow->getMe()->getFlags() & MUCC_EF_USER_OWNER) {
+ EnableMenuItem(hMenu, ID_ADMINMENU_DESTROY, MF_BYCOMMAND | MF_ENABLED);
+ }
+ }
+ iSelection = TrackPopupMenu(hMenu, TPM_RETURNCMD | TPM_TOPALIGN | TPM_LEFTALIGN, rc.left, rc.bottom, 0, hwndDlg, NULL);
+ DestroyMenu(hMenu);
+ switch (iSelection) {
+ case ID_OPTIONMENU_SHOWNICKNAMES:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_SHOW_NICKNAMES);
+ break;
+ case ID_OPTIONMENU_MSGINNEWLINE:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_MSGINNEWLINE);
+ break;
+ case ID_OPTIONMENU_SHOWDATE:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_SHOW_DATE);
+ break;
+ case ID_OPTIONMENU_SHOWTIMESTAMP:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_SHOW_TIMESTAMP);
+ break;
+ case ID_OPTIONMENU_SHOWSECONDS:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_SHOW_SECONDS);
+ break;
+ case ID_OPTIONMENU_USELONGDATE:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LONG_DATE);
+ break;
+ case ID_OPTIONMENU_FORMATFONT:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FORMAT_FONT);
+ break;
+ case ID_OPTIONMENU_FORMATSIZE:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FORMAT_SIZE);
+ break;
+ case ID_OPTIONMENU_FORMATCOLOR:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FORMAT_COLOR);
+ break;
+ case ID_OPTIONMENU_FORMATSTYLE:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FORMAT_STYLE);
+ break;
+ case ID_OPTIONMENU_LOGMESSAGES:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LOG_MESSAGES);
+ break;
+ case ID_OPTIONMENU_LOGJOINED:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LOG_JOINED);
+ break;
+ case ID_OPTIONMENU_LOGLEFT:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LOG_LEFT);
+ break;
+ case ID_OPTIONMENU_LOGTOPIC:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_LOG_TOPIC);
+ break;
+ case ID_OPTIONMENU_FLASHMESSAGES:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FLASH_MESSAGES);
+ break;
+ case ID_OPTIONMENU_FLASHJOINED:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FLASH_JOINED);
+ break;
+ case ID_OPTIONMENU_FLASHLEFT:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FLASH_LEFT);
+ break;
+ case ID_OPTIONMENU_FLASHTOPIC:
+ chatWindow->setOptions(chatWindow->getOptions()^ChatWindow::FLAG_FLASH_TOPIC);
+ break;
+ case ID_OPTIONMENU_SAVEDEFAULT:
+ Options::setChatWindowOptions(chatWindow->getOptions());
+ Options::setChatWindowFont((int)SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETCURSEL, 0, 0));
+ Options::setChatWindowFontSize((int)SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETCURSEL, 0, 0));
+ Options::setChatWindowFontStyle(
+ (IsDlgButtonChecked(hwndDlg, IDC_BOLD) ? Font::BOLD : 0) |
+ (IsDlgButtonChecked(hwndDlg, IDC_ITALIC) ? Font::ITALIC : 0) |
+ (IsDlgButtonChecked(hwndDlg, IDC_UNDERLINE) ? Font::UNDERLINE : 0)
+ );
+ Options::setChatWindowFontColor((COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0));
+ Options::saveSettings();
+ break;
+ case ID_ADMINMENU_DESTROY:
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_REMOVE_ROOM;
+ muce.pszModule = chatWindow->getModule();
+ muce.pszID = chatWindow->getRoomId();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ DestroyWindow(hwndDlg);
+ break;
+ case ID_ADMINMENU_ADMIN:
+ chatWindow->startAdminDialog(ChatWindow::ADMIN_MODE_KICK);
+ break;
+ case ID_ADMINMENU_BROWSE:
+ chatWindow->startAdminDialog(ChatWindow::ADMIN_MODE_ROLE);
+ break;
+ case ID_ADMINMENU_SAVELOG:
+ if (chatWindow->getHWNDLog()!=NULL) {
+ IEVIEWEVENT iee;
+ ZeroMemory(&iee, sizeof(iee));
+ iee.cbSize = sizeof(iee);
+ iee.dwFlags = 0;
+ iee.hwnd = chatWindow->getHWNDLog();
+ iee.hContact = NULL;
+ iee.iType = IEE_SAVE_DOCUMENT;
+ CallService(MS_IEVIEW_EVENT, 0, (LPARAM)&iee);
+ } else {
+ char szFilename[MAX_PATH];
+ strcpy(szFilename, "");
+ OPENFILENAMEA ofn={0};
+ ofn.lStructSize=sizeof(OPENFILENAME);
+ ofn.hwndOwner=hwndDlg;
+ ofn.lpstrFile = szFilename;
+ ofn.lpstrFilter = "Rich Text File\0*.rtf\0\0";
+ ofn.nMaxFile = MAX_PATH;
+ ofn.nMaxFileTitle = MAX_PATH;
+ ofn.Flags = OFN_HIDEREADONLY;
+ ofn.lpstrDefExt = "rtf";
+ if (GetSaveFileNameA(&ofn)) {
+ //remove(szFilename);
+ EDITSTREAM stream = { 0 };
+ stream.dwCookie = (DWORD_PTR)szFilename;
+ stream.dwError = 0;
+ stream.pfnCallback = EditStreamCallback;
+ SendDlgItemMessage(hwndDlg, IDC_LOG, EM_STREAMOUT, SF_RTF | SF_USECODEPAGE, (LPARAM) & stream);
+ }
+ }
+ break;
+ }
+ }
+ break;
+ case IDC_SMILEYBTN:
+ SMADD_SHOWSEL smaddInfo;
+ RECT rc;
+ smaddInfo.cbSize = sizeof(SMADD_SHOWSEL);
+ smaddInfo.hwndTarget = GetDlgItem(hwndDlg, IDC_EDIT);
+ smaddInfo.targetMessage = EM_REPLACESEL;
+ smaddInfo.targetWParam = TRUE;
+ smaddInfo.Protocolname = chatWindow->getModule();
+ GetWindowRect(GetDlgItem(hwndDlg, IDC_SMILEYBTN), &rc);
+ smaddInfo.Direction = 0;
+ smaddInfo.xPosition = rc.left;
+ smaddInfo.yPosition = rc.top + 24;
+ if (chatWindow->getHWNDLog() != NULL) {
+ CallService(MS_IEVIEW_SHOWSMILEYSELECTION, 0, (LPARAM) &smaddInfo);
+ } else {
+ CallService(MS_SMILEYADD_SHOWSELECTION, 0, (LPARAM) &smaddInfo);
+ }
+ break;
+ case IDC_INVITE:
+ {
+ MUCCEVENT muce;
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_QUERY_CONTACTS;
+ muce.pszModule = chatWindow->getModule();
+ muce.pszID = chatWindow->getRoomId();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ }
+ break;
+ case IDC_TOPIC_BUTTON:
+ HelperDialog::topicDlg(chatWindow);
+ break;
+ case IDCANCEL:
+ DestroyWindow(hwndDlg);
+ return TRUE;
+ case IDOK:
+ {
+ MUCCEVENT muce;
+ char text[2048];
+ GetDlgItemTextA(hwndDlg, IDC_EDIT, text, sizeof(text));
+ SetDlgItemTextA(hwndDlg, IDC_EDIT, "");
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_MESSAGE;
+ muce.pszModule = chatWindow->getModule();
+ muce.pszID = chatWindow->getRoomId();
+ muce.pszText = text;
+ muce.iFont = chatWindow->getFont();
+ muce.iFontSize = chatWindow->getFontSize();
+ muce.dwFlags = chatWindow->getFontStyle();
+ muce.color = chatWindow->getFontColor();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ }
+ break;
+ case IDC_BOLD:
+ case IDC_ITALIC:
+ case IDC_UNDERLINE:
+ if (HIWORD(wParam)==BN_CLICKED) {
+ chatWindow->setFont((int) SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETCURSEL, 0, 0), 0),
+ (int) SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETCURSEL, 0, 0), 0),
+ IsDlgButtonChecked(hwndDlg, IDC_BOLD),
+ IsDlgButtonChecked(hwndDlg, IDC_ITALIC),
+ IsDlgButtonChecked(hwndDlg, IDC_UNDERLINE),
+ (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0));
+ }
+ case IDC_FONT:
+ case IDC_FONTSIZE:
+ if (HIWORD(wParam)==CBN_SELCHANGE) {
+ chatWindow->setFont((int) SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETCURSEL, 0, 0), 0),
+ (int) SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETCURSEL, 0, 0), 0),
+ IsDlgButtonChecked(hwndDlg, IDC_BOLD),
+ IsDlgButtonChecked(hwndDlg, IDC_ITALIC),
+ IsDlgButtonChecked(hwndDlg, IDC_UNDERLINE),
+ (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0));
+ }
+ break;
+ case IDC_COLOR:
+ if (HIWORD(wParam)==CPN_COLOURCHANGED) {
+ InvalidateRect(GetDlgItem(hwndDlg, IDC_EDIT), NULL, FALSE);
+ chatWindow->setFont((int) SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONT, CB_GETCURSEL, 0, 0), 0),
+ (int) SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONTSIZE, CB_GETCURSEL, 0, 0), 0),
+ IsDlgButtonChecked(hwndDlg, IDC_BOLD),
+ IsDlgButtonChecked(hwndDlg, IDC_ITALIC),
+ IsDlgButtonChecked(hwndDlg, IDC_UNDERLINE),
+ (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0));
+ }
+ break;
+
+ }
+ break;
+ case WM_CTLCOLOREDIT:
+ if ((HWND) lParam == GetDlgItem(hwndDlg, IDC_EDIT)) {
+ SetTextColor((HDC) wParam, (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLOR, CPM_GETCOLOUR,0,0));
+ SetBkColor((HDC) wParam, Options::getInputBgColor());
+ //SelectObject((HDC) wParam, Options::getInputBgBrush());
+ return (BOOL) Options::getInputBgBrush();
+ }
+
+ break;
+ case WM_NOTIFY:
+ LPNMHDR pNmhdr;
+ pNmhdr = (LPNMHDR)lParam;
+ if (pNmhdr->idFrom == IDC_TREELIST) {
+ switch (pNmhdr->code) {
+ case TVN_ITEMEXPANDING:
+ {
+ LPNMTREEVIEW pnmtv = (LPNMTREEVIEW) lParam;
+ if (pnmtv->action==TVE_COLLAPSE) {
+ SetWindowLongPtr(hwndDlg,DWLP_MSGRESULT, TRUE);
+ return TRUE;
+ }
+ }
+ break;
+ case NM_RCLICK:
+ {
+ TVHITTESTINFO hti;
+ hti.pt.x=(short)LOWORD(GetMessagePos());
+ hti.pt.y=(short)HIWORD(GetMessagePos());
+ ScreenToClient(pNmhdr->hwndFrom,&hti.pt);
+ if(TreeView_HitTest(pNmhdr->hwndFrom, &hti) && hti.flags&TVHT_ONITEM) {
+ TVITEM tvi = {0};
+ tvi.mask = TVIF_PARAM|TVIF_HANDLE;
+ tvi.hItem = hti.hItem;
+ TreeView_GetItem(pNmhdr->hwndFrom, &tvi);
+ ChatUser *user = (ChatUser *) tvi.lParam;
+ if (user!=NULL) {
+ TreeView_Select(pNmhdr->hwndFrom, tvi.hItem, TVGN_CARET);
+ if (!user->isMe()) {
+ HMENU hMenu;
+ int iSelection;
+ hMenu = GetSubMenu(LoadMenu(hInst, MAKEINTRESOURCE(IDR_CHATOPTIONS)),1);
+ CallService(MS_LANGPACK_TRANSLATEMENU,(WPARAM)hMenu,0);
+ if (chatWindow->getMe()!=NULL) {
+ if (chatWindow->getMe()->getFlags() & MUCC_EF_USER_OWNER) {
+ EnableMenuItem(hMenu, 2, MF_BYPOSITION | MF_ENABLED);
+ EnableMenuItem(hMenu, 3, MF_BYPOSITION | MF_ENABLED);
+ EnableMenuItem(hMenu, ID_USERMENU_ADMINISTRATION, MF_BYCOMMAND | MF_ENABLED);
+
+ } else if (chatWindow->getMe()->getFlags() & MUCC_EF_USER_ADMIN) {
+ if (!(user->getFlags() & (MUCC_EF_USER_OWNER | MUCC_EF_USER_OWNER))) {
+ EnableMenuItem(hMenu, 2, MF_BYPOSITION | MF_ENABLED);
+ //EnableMenuItem(hMenu, 3, MF_BYPOSITION | MF_ENABLED);
+ EnableMenuItem(hMenu, ID_USERMENU_ADMINISTRATION, MF_BYCOMMAND | MF_ENABLED);
+ }
+ }
+ }
+ //CheckMenuItem(hMenu, ID_USERMENU_MESSAGE, MF_BYCOMMAND | MF_CHECKED : MF_UNCHECKED);
+ //EnableMenuItem(hMenu, ID_USERMENU_MESSAGE, MF_BYCOMMAND | MF_GRAYED);
+ iSelection = TrackPopupMenu(hMenu, TPM_RETURNCMD | TPM_TOPALIGN | TPM_LEFTALIGN, (short)LOWORD(GetMessagePos()), (short)HIWORD(GetMessagePos()), 0, hwndDlg, NULL);
+ DestroyMenu(hMenu);
+ if (iSelection == ID_USERMENU_MESSAGE) {
+ chatWindow->startPriv();
+ } else if (iSelection >= ID_USERMENU_KICK_NO_BAN && iSelection <= ID_USERMENU_KICK_BAN_4_W) {
+ int banTime[] = {0, 1, 5, 15, 30, 60, 360, 1440, 4320, 10080, 20160, 40320};
+ chatWindow->kickAndBan(banTime[iSelection-ID_USERMENU_KICK_NO_BAN] *60);
+ } else if (iSelection == ID_USERMENU_RIGHTS_MEMBER) {
+ chatWindow->setRights(MUCC_EF_USER_MEMBER);
+ } else if (iSelection == ID_USERMENU_RIGHTS_ADMIN) {
+ chatWindow->setRights(MUCC_EF_USER_ADMIN);
+ } else if (iSelection == ID_USERMENU_RIGHTS_NO) {
+ chatWindow->setRights(0);
+ } else if (iSelection == ID_USERMENU_ADMINISTRATION) {
+ chatWindow->startAdminDialog(ChatWindow::ADMIN_MODE_KICK);
+ }
+ }
+ }
+ }
+
+ }
+ break;
+ case NM_CUSTOMDRAW:
+ LPNMTVCUSTOMDRAW pCustomDraw = (LPNMTVCUSTOMDRAW)lParam;
+ switch (pCustomDraw->nmcd.dwDrawStage) {
+ case CDDS_PREPAINT:
+ SetWindowLongPtr(hwndDlg,DWLP_MSGRESULT,CDRF_NOTIFYITEMDRAW);
+ return TRUE;
+ case CDDS_ITEMPREPAINT:
+ {
+ TVITEM tvi;;
+ HICON hIcon;
+ TCHAR str[200];
+ RECT rc = pCustomDraw->nmcd.rc;
+ tvi.mask = TVIF_HANDLE | TVIF_STATE | TVIF_TEXT | TVIF_PARAM;
+ tvi.pszText = str;
+ tvi.cchTextMax = sizeof(str)/sizeof(TCHAR);
+ tvi.hItem = (HTREEITEM)pCustomDraw->nmcd.dwItemSpec;
+ TreeView_GetItem(pCustomDraw->nmcd.hdr.hwndFrom, &tvi);
+ ChatUser * user= (ChatUser *)pCustomDraw->nmcd.lItemlParam;
+ hIcon = NULL;
+ pCustomDraw->clrTextBk = Options::getListBgColor();
+ switch (pCustomDraw->iLevel) {
+ case 0:
+ pCustomDraw->clrText = ChatWindow::getListGroupTextColor();
+ SelectObject(pCustomDraw->nmcd.hdc, ChatWindow::getListGroupFont());
+ break;
+ case 1:
+ pCustomDraw->clrText = ChatWindow::getListTextColor();
+ if (pCustomDraw->nmcd.uItemState & CDIS_SELECTED) { // selected (CDIS_FOCUS |
+ pCustomDraw->clrTextBk = 0xDAC8C2;
+ } else {
+ pCustomDraw->clrTextBk = Options::getListBgColor();
+ }
+ if (user!=NULL) {
+ if (user->getFlags()&MUCC_EF_USER_GLOBALOWNER) {
+ hIcon = muccIcon[MUCC_IDI_U_GLOBALOWNER];
+ } else if (user->getFlags()&MUCC_EF_USER_OWNER) {
+ hIcon = muccIcon[MUCC_IDI_U_OWNER];
+ } else if (user->getFlags()&MUCC_EF_USER_ADMIN) {
+ hIcon = muccIcon[MUCC_IDI_U_ADMIN];
+ } else if (user->getFlags()&MUCC_EF_USER_REGISTERED) {
+ hIcon = muccIcon[MUCC_IDI_U_REGISTERED];
+ }
+ }
+ SelectObject(pCustomDraw->nmcd.hdc, ChatWindow::getListFont());
+ break;
+ }
+ if (rc.bottom-rc.top!=0 && rc.right-rc.left!=0) {
+ HBRUSH hBr;
+ hBr = CreateSolidBrush(pCustomDraw->clrTextBk);
+ FillRect(pCustomDraw->nmcd.hdc, &rc, hBr);
+ DeleteObject(hBr);
+ if (hIcon!=NULL) {
+ DrawIconEx(pCustomDraw->nmcd.hdc, rc.left, rc.top, hIcon, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0, NULL, DI_NORMAL);
+ }
+ SetBkMode(pCustomDraw->nmcd.hdc, TRANSPARENT);
+ SetTextColor(pCustomDraw->nmcd.hdc, pCustomDraw->clrText);
+ TextOut(pCustomDraw->nmcd.hdc,
+ rc.left+pCustomDraw->iLevel*GetSystemMetrics(SM_CXSMICON)+2,
+ rc.top, tvi.pszText, (int)_tcslen(tvi.pszText));
+ }
+ SetWindowLongPtr(hwndDlg,DWLP_MSGRESULT, CDRF_SKIPDEFAULT );
+ return TRUE;
+ }
+ }
+ break;
+ }
+ } else if (pNmhdr->idFrom == IDC_LOG) {
+ switch (((NMHDR *) lParam)->code) {
+ case EN_MSGFILTER:
+ switch (((MSGFILTER *) lParam)->msg) {
+ /*
+ case WM_LBUTTONDOWN:
+ {
+ HCURSOR hCur = GetCursor();
+ if (hCur == LoadCursor(NULL, IDC_SIZENS) || hCur == LoadCursor(NULL, IDC_SIZEWE)
+ || hCur == LoadCursor(NULL, IDC_SIZENESW) || hCur == LoadCursor(NULL, IDC_SIZENWSE)) {
+ SetWindowLong(hwndDlg, DWL_MSGRESULT, TRUE);
+ return TRUE;
+ }
+ break;
+ }
+ case WM_MOUSEMOVE:
+ {
+ HCURSOR hCur = GetCursor();
+ if (hCur == LoadCursor(NULL, IDC_SIZENS) || hCur == LoadCursor(NULL, IDC_SIZEWE)
+ || hCur == LoadCursor(NULL, IDC_SIZENESW) || hCur == LoadCursor(NULL, IDC_SIZENWSE))
+ SetCursor(LoadCursor(NULL, IDC_ARROW));
+ break;
+ }
+ */
+ case WM_RBUTTONUP:
+ {
+ HMENU hMenu, hSubMenu;
+ POINT pt;
+ CHARRANGE sel, all = { 0, -1 };
+
+ hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT));
+ hSubMenu = GetSubMenu(hMenu, 0);
+ CallService(MS_LANGPACK_TRANSLATEMENU, (WPARAM) hSubMenu, 0);
+ SendMessage(((NMHDR *) lParam)->hwndFrom, EM_EXGETSEL, 0, (LPARAM) & sel);
+ if (sel.cpMin == sel.cpMax)
+ EnableMenuItem(hSubMenu, IDM_COPY, MF_BYCOMMAND | MF_GRAYED);
+ pt.x = (short) LOWORD(((ENLINK *) lParam)->lParam);
+ pt.y = (short) HIWORD(((ENLINK *) lParam)->lParam);
+ ClientToScreen(((NMHDR *) lParam)->hwndFrom, &pt);
+ switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, pt.x, pt.y, 0, hwndDlg, NULL)) {
+ case IDM_COPY:
+ SendMessage(((NMHDR *) lParam)->hwndFrom, WM_COPY, 0, 0);
+ break;
+ case IDM_COPYALL:
+ SendMessage(((NMHDR *) lParam)->hwndFrom, EM_EXSETSEL, 0, (LPARAM) & all);
+ SendMessage(((NMHDR *) lParam)->hwndFrom, WM_COPY, 0, 0);
+ SendMessage(((NMHDR *) lParam)->hwndFrom, EM_EXSETSEL, 0, (LPARAM) & sel);
+ break;
+ case IDM_SELECTALL:
+ SendMessage(((NMHDR *) lParam)->hwndFrom, EM_EXSETSEL, 0, (LPARAM) & all);
+ break;
+ case IDM_CLEAR:
+ chatWindow->clearLog();
+ break;
+ }
+ DestroyMenu(hMenu);
+ SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, TRUE);
+ return TRUE;
+ }
+ }
+ break;
+ case EN_LINK:
+ switch (((ENLINK *) lParam)->msg) {
+ case WM_SETCURSOR:
+ SetCursor(hCurHyperlinkHand);
+ SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, TRUE);
+ return TRUE;
+ case WM_RBUTTONDOWN:
+ case WM_LBUTTONUP:
+ {
+ TEXTRANGEA tr;
+ CHARRANGE sel;
+
+ SendDlgItemMessage(hwndDlg, IDC_LOG, EM_EXGETSEL, 0, (LPARAM) & sel);
+ if (sel.cpMin != sel.cpMax)
+ break;
+ tr.chrg = ((ENLINK *) lParam)->chrg;
+ tr.lpstrText = (char *)malloc(tr.chrg.cpMax - tr.chrg.cpMin + 8);
+ SendDlgItemMessageA(hwndDlg, IDC_LOG, EM_GETTEXTRANGE, 0, (LPARAM) & tr);
+ if (strchr(tr.lpstrText, '@') != NULL && strchr(tr.lpstrText, ':') == NULL && strchr(tr.lpstrText, '/') == NULL) {
+ MoveMemory(tr.lpstrText + 7, tr.lpstrText, tr.chrg.cpMax - tr.chrg.cpMin + 1);
+ CopyMemory(tr.lpstrText, "mailto:", 7);
+ }
+ if (((ENLINK *) lParam)->msg == WM_RBUTTONDOWN) {
+ HMENU hMenu, hSubMenu;
+ POINT pt;
+
+ hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDR_CONTEXT));
+ hSubMenu = GetSubMenu(hMenu, 1);
+ CallService(MS_LANGPACK_TRANSLATEMENU, (WPARAM) hSubMenu, 0);
+ pt.x = (short) LOWORD(((ENLINK *) lParam)->lParam);
+ pt.y = (short) HIWORD(((ENLINK *) lParam)->lParam);
+ ClientToScreen(((NMHDR *) lParam)->hwndFrom, &pt);
+ switch (TrackPopupMenu(hSubMenu, TPM_RETURNCMD, pt.x, pt.y, 0, hwndDlg, NULL)) {
+ case IDM_OPENNEW:
+ CallService(MS_UTILS_OPENURL, 1, (LPARAM) tr.lpstrText);
+ break;
+ case IDM_OPENEXISTING:
+ CallService(MS_UTILS_OPENURL, 0, (LPARAM) tr.lpstrText);
+ break;
+ case IDM_COPYLINK:
+ {
+ HGLOBAL hData;
+ if (!OpenClipboard(hwndDlg))
+ break;
+ EmptyClipboard();
+ hData = GlobalAlloc(GMEM_MOVEABLE, lstrlenA(tr.lpstrText) + 1);
+ lstrcpyA((char *)GlobalLock(hData), tr.lpstrText);
+ GlobalUnlock(hData);
+ SetClipboardData(CF_TEXT, hData);
+ CloseClipboard();
+ break;
+ }
+ }
+ free(tr.lpstrText);
+ DestroyMenu(hMenu);
+ SetWindowLongPtr(hwndDlg, DWLP_MSGRESULT, TRUE);
+ return TRUE;
+ }
+ else {
+ CallService(MS_UTILS_OPENURL, 1, (LPARAM) tr.lpstrText);
+ SetFocus(GetDlgItem(hwndDlg, IDC_EDIT));
+ }
+ free(tr.lpstrText);
+ break;
+ }
+ }
+ break;
+ }
+ }
+ break;
+ }
+ return FALSE;
+}
+
+static char *JabberRtfEscape(char *str) {
+ char *escapedStr;
+ int size;
+ char *p, *q;
+
+ if (str == NULL)
+ return NULL;
+
+ for (p=str,size=0; *p!='\0'; p++) {
+ if (*p=='\\' || *p=='{' || *p=='}')
+ size += 2;
+ else if (*p=='\n' || *p=='\t')
+ size += 5;
+ else
+ size++;
+ }
+
+ if ((escapedStr=(char *)malloc(size+1)) == NULL)
+ return NULL;
+
+ for (p=str,q=escapedStr; *p!='\0'; p++) {
+ if (strchr("\\{}", *p) != NULL) {
+ *q++ = '\\';
+ *q++ = *p;
+ }
+ else if (*p == '\n') {
+ strcpy(q, "\\par ");
+ q += 5;
+ }
+ else if (*p == '\t') {
+ strcpy(q, "\\tab ");
+ q += 5;
+ }
+ else {
+ *q++ = *p;
+ }
+ }
+ *q = '\0';
+
+ return escapedStr;
+}
+
+static void JabberStringAppend(char **str, int *sizeAlloced, const char *fmt, ...) {
+ va_list vararg;
+ char *p;
+ int size, len;
+
+ if (str == NULL) return;
+
+ if (*str==NULL || *sizeAlloced<=0) {
+ *sizeAlloced = size = 2048;
+ *str = (char *) malloc(size);
+ len = 0;
+ }
+ else {
+ len = (int)strlen(*str);
+ size = *sizeAlloced - (int)strlen(*str);
+ }
+
+ p = *str + len;
+ va_start(vararg, fmt);
+ while (_vsnprintf(p, size, fmt, vararg) == -1) {
+ size += 2048;
+ (*sizeAlloced) += 2048;
+ *str = (char *) realloc(*str, *sizeAlloced);
+ p = *str + len;
+ }
+ va_end(vararg);
+}
+
+
+//static DWORD CALLBACK Log_StreamCallback(DWORD dwCookie, LPBYTE pbBuff, LONG cb, LONG * pcb)
+//{
+// StreamData *stream = (StreamData *) dwCookie;
+/*
+ if (lstrdat->buffer == NULL)
+ {
+ lstrdat->iColCount = 4;
+ lstrdat->bufferOffset = 0;
+ lstrdat->buffer = Log_CreateBody(lstrdat);
+ lstrdat->bufferLen = lstrlen(lstrdat->buffer);
+ }
+ *pcb = min(cb, lstrdat->bufferLen - lstrdat->bufferOffset);
+ CopyMemory(pbBuff, lstrdat->buffer + lstrdat->bufferOffset, *pcb);
+ lstrdat->bufferOffset += *pcb;
+ if (lstrdat->bufferOffset == lstrdat->bufferLen)
+ {
+ free(lstrdat->buffer);
+ lstrdat->buffer = NULL;
+ }
+*/
+// return 0;
+//}
diff --git a/protocols/Tlen/tlen_czaty/ChatWindow.h b/protocols/Tlen/tlen_czaty/ChatWindow.h
new file mode 100644
index 0000000000..37b0b29d6e
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ChatWindow.h
@@ -0,0 +1,196 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+class ChatWindow;
+
+#ifndef CHATWINDOW_INCLUDED
+#define CHATWINDOW_INCLUDED
+#include "mucc.h"
+#include "ChatEvent.h"
+#include "ChatUser.h"
+#include "AdminWindow.h"
+#include "ChatContainer.h"
+
+#define DM_CHAT_EVENT (WM_USER+1)
+#define DM_CHAT_QUERY (WM_USER+2)
+#define WM_TLEN_SMILEY (WM_USER+200)
+
+
+class StreamData {
+public:
+ ChatWindow *chat;
+ MUCCEVENT *event;
+};
+
+class ChatWindow{
+private:
+ static ChatWindow * list;
+ static CRITICAL_SECTION mutex;
+ static bool released;
+ static HFONT hListGroupFont, hListFont;
+ static COLORREF colorListBg, colorListText, colorListGroupText;
+ static COLORREF colorInputBg, colorLogBg;
+ ChatContainer * container;
+ HANDLE hEvent;
+ HWND hWnd;
+ HWND hWndLog;
+ HFONT hEditFont;
+ HTREEITEM hUserGroups[5];
+ char * module;
+ char * roomId;
+ char * roomName;
+ char * topic;
+ int options;
+ int roomFlags;
+ int font, fontSize;
+ int bBold, bItalic, bUnderline;
+ int wasFirstMessage;
+ bool isEmpty;
+ COLORREF fontColor;
+ int isStarted;
+ ChatWindow * prev;
+ ChatWindow * next;
+ int adminDialogMode;
+ AdminWindow * adminWindow;
+ ChatUser * users;
+ ChatUser * userMe;
+ void addUser(ChatUser *);
+ void removeUser(ChatUser *);
+ ChatUser * findUser(const char *);
+ int getUserGroup(ChatUser *);
+ ChatUser * getSelectedUser();
+ ChatEventList eventList;
+ void createRTFHeader();
+ int appendMessage(const MUCCEVENT *event);
+ int logMessage(const MUCCEVENT *event);
+public:
+ enum LOGFLAGS {
+ FLAG_SHOW_NICKNAMES = 0x00000001,
+ FLAG_MSGINNEWLINE = 0x00000002,
+ FLAG_OPT_SENDONENTER= 0x00000004,
+ FLAG_OPT_ENABLEIEVIEW=0x00000008,
+
+ FLAG_SHOW_DATE = 0x00000010,
+ FLAG_SHOW_TIMESTAMP = 0x00000020,
+ FLAG_SHOW_SECONDS = 0x00000040,
+ FLAG_LONG_DATE = 0x00000080,
+
+ FLAG_FORMAT_FONT = 0x00000100,
+ FLAG_FORMAT_SIZE = 0x00000200,
+ FLAG_FORMAT_COLOR = 0x00000400,
+ FLAG_FORMAT_STYLE = 0x00000800,
+ FLAG_FORMAT_ALL = 0x00000F00,
+
+ FLAG_LOG_MESSAGES = 0x00001000,
+ FLAG_LOG_JOINED = 0x00002000,
+ FLAG_LOG_LEFT = 0x00004000,
+ FLAG_LOG_TOPIC = 0x00008000,
+ FLAG_LOG_ALL = 0x0000F000,
+
+ FLAG_FLASH_MESSAGES = 0x00010000,
+ FLAG_FLASH_JOINED = 0x00020000,
+ FLAG_FLASH_LEFT = 0x00040000,
+ FLAG_FLASH_TOPIC = 0x00080000,
+ FLAG_FLASH_ALL = 0x000F0000,
+
+
+ };
+
+ enum ADMINMODES {
+ ADMIN_MODE_KICK = 1,
+ ADMIN_MODE_ROLE = 2,
+ ADMIN_MODE_BROWSER = 3
+ };
+ int hSplitterPos;
+ int vSplitterPos;
+ int hSplitterMinBottom;
+ int hSplitterMinTop;
+ int vSplitterMinLeft;
+ int vSplitterMinRight;
+ ChatWindow (MUCCWINDOW *);
+ ~ChatWindow ();
+ ChatWindow * getNext();
+ void setNext(ChatWindow *);
+ ChatWindow * getPrev();
+ ChatContainer* getContainer();
+ void setPrev(ChatWindow *);
+ void setHWND(HWND);
+ HWND getHWND();
+ void setHWNDLog(HWND);
+ HWND getHWNDLog();
+ HANDLE getEvent();
+ const char * getModule();
+ void setModule(const char *);
+ const char * getRoomId();
+ void setRoomId(const char *);
+ const char * getRoomName();
+ void setRoomName(const char *);
+ void setOptions(int);
+ int getOptions();
+ void setRoomFlags(int);
+ int getRoomFlags();
+ int getFontSizeNum();
+ int getFontSize(int);
+ int getFontNameNum();
+ const char * getFontName(int);
+ void setFont(int font, int size, int bBold, int bItalic, int bUnderline, COLORREF color);
+ int getFont();
+ int getFontSize();
+ int getFontStyle();
+ COLORREF getFontColor();
+ int start();
+ int startPriv();
+ void startAdminDialog(int mode);
+ int kickAndBan(int time);
+ int kickAndBan(const char *id, int time, const char *);
+ int unban(const char *id);
+ int setRights(int flags);
+ int setRights(const char *id, int flags);
+ void queryResultContacts(MUCCQUERYRESULT *queryResult);
+ void queryResultUsers(MUCCQUERYRESULT *queryResult);
+ void setTreeItem(int, HTREEITEM);
+ HTREEITEM getTreeItem(int);
+ ChatUser * findUserByNick(const char *);
+ ChatUser * getMe();
+ void refreshSettings();
+ void setAdminWindow(AdminWindow *);
+ AdminWindow * getAdminWindow();
+ void rebuildLog();
+ void clearLog();
+ int logEvent(const MUCCEVENT *event);
+ int changePresence(const MUCCEVENT *event);
+ int changeTopic(const MUCCEVENT *event);
+ int changeRoomInfo(const MUCCEVENT *event);
+ int leave();
+
+ static void refreshSettings(int force);
+ static HFONT getListGroupFont();
+ static HFONT getListFont();
+ static COLORREF getListTextColor();
+ static COLORREF getListGroupTextColor();
+ static int getDefaultOptions();
+
+ static void init();
+ static void release();
+ static ChatWindow * getWindow(const char *module, const char *roomId);
+
+};
+#endif
diff --git a/protocols/Tlen/tlen_czaty/FontList.cpp b/protocols/Tlen/tlen_czaty/FontList.cpp
new file mode 100644
index 0000000000..4d57617013
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/FontList.cpp
@@ -0,0 +1,206 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include "FontList.h"
+#include "Utils.h"
+
+#define FONTCOUNT 12
+static Font defFonts[] = {
+ Font("Timestamp","Verdana", DEFAULT_CHARSET, -9, Font::BOLD, 0x000000),
+// Font("Colon","Verdana", DEFAULT_CHARSET, -13, 0, 0x808080),
+ Font("Others names","Verdana", DEFAULT_CHARSET, -13, 0, 0x723732),
+ Font("Your name","Verdana", DEFAULT_CHARSET, -13, 0, 0x4453A4),
+ Font("Incoming message","Verdana", DEFAULT_CHARSET, -13, 0, 0x000000),
+ Font("Outgoing message","Verdana", DEFAULT_CHARSET, -13, 0, 0x505080),
+ Font("User has joined","Verdana", DEFAULT_CHARSET, -11, Font::ITALIC, 0x0F880F),
+ Font("User has left","Verdana", DEFAULT_CHARSET, -11, Font::ITALIC, 0x1313B9),
+ Font("The topic is ...","Verdana", DEFAULT_CHARSET, -13, Font::ITALIC, 0x991A53),
+ Font("Error","Verdana", DEFAULT_CHARSET, -13, Font::BOLD, 0x1010D0),
+ Font("Message typing area","Verdana", DEFAULT_CHARSET, -13, 0, 0x000000),
+ Font("User list","Tahoma", DEFAULT_CHARSET, -11, 0, 0x000000),
+ Font("User list group","Tahoma", DEFAULT_CHARSET, -11, Font::BOLD, 0x000000)
+
+};
+
+Font::Font() {
+ name = NULL;
+ face = NULL;
+ size = 0;
+ style = 0;
+ color = 0;
+ charSet = DEFAULT_CHARSET;
+}
+
+Font::Font(const char *n, const char *f, int cs, int s, int st, COLORREF c) {
+ name = NULL;
+ face = NULL;
+ size = 0;
+ style = 0;
+ color = 0;
+ setName(n);
+ setFace(f);
+ setCharSet(cs);
+ setSize(s);
+ setStyle(st);
+ setColor(c);
+}
+
+
+COLORREF Font::getColor() {
+ return color;
+}
+
+void Font::setColor(COLORREF c) {
+ color = c;
+}
+
+int Font::getSize() {
+ return size;
+}
+
+void Font::setSize(int s) {
+ size = s;
+}
+
+int Font::getStyle() {
+ return style;
+}
+
+void Font::setStyle(int s) {
+ style = s;
+}
+
+int Font::getCharSet() {
+ return charSet;
+}
+
+void Font::setCharSet(int s) {
+ charSet = s;
+}
+
+void Font::setName(const char *s) {
+ Utils::copyString(&name, s);
+}
+
+const char *Font::getName() {
+ return name;
+}
+
+void Font::setFace(const char *s) {
+ Utils::copyString(&face, s);
+}
+
+const char *Font::getFace() {
+ return face;
+}
+
+Font *FontList::fonts = NULL;
+Font *FontList::fontsSettings = NULL;
+
+Font *FontList::getFont(int index) {
+ if (index < FONTCOUNT) return &fonts[index];
+ else return NULL;
+}
+
+Font *FontList::getFontSettings(int index) {
+ if (index < FONTCOUNT) return &fontsSettings[index];
+ else return NULL;
+}
+
+void FontList::loadSettings() {
+ char fontParam[512];
+ for (int i=0;i<FONTCOUNT;i++) {
+ DBVARIANT dbv;
+ fontsSettings[i].setName(defFonts[i].getName());
+ fontsSettings[i].setFace(defFonts[i].getFace());
+ fontsSettings[i].setCharSet(defFonts[i].getCharSet());
+ fontsSettings[i].setSize(defFonts[i].getSize());
+ fontsSettings[i].setStyle(defFonts[i].getStyle());
+ fontsSettings[i].setColor(defFonts[i].getColor());
+ sprintf(fontParam, "Font%dFace", i);
+ if (!DBGetContactSetting(NULL, muccModuleName, fontParam, &dbv)) {
+ fontsSettings[i].setFace(dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ sprintf(fontParam, "Font%dSet", i);
+ if (!DBGetContactSetting(NULL, muccModuleName, fontParam, &dbv)) {
+ fontsSettings[i].setCharSet(dbv.bVal);
+ DBFreeVariant(&dbv);
+ }
+ sprintf(fontParam, "Font%dSize", i);
+ if (!DBGetContactSetting(NULL, muccModuleName, fontParam, &dbv)) {
+ fontsSettings[i].setSize(dbv.lVal);
+ DBFreeVariant(&dbv);
+ }
+ sprintf(fontParam, "Font%dCol", i);
+ if (!DBGetContactSetting(NULL, muccModuleName, fontParam, &dbv)) {
+ fontsSettings[i].setColor(dbv.lVal);
+ DBFreeVariant(&dbv);
+ }
+ sprintf(fontParam, "Font%dStyle", i);
+ if (!DBGetContactSetting(NULL, muccModuleName, fontParam, &dbv)) {
+ fontsSettings[i].setStyle(dbv.bVal);
+ DBFreeVariant(&dbv);
+ }
+ fonts[i].setName(fontsSettings[i].getName());
+ fonts[i].setFace(fontsSettings[i].getFace());
+ fonts[i].setCharSet(fontsSettings[i].getCharSet());
+ fonts[i].setSize(fontsSettings[i].getSize());
+ fonts[i].setStyle(fontsSettings[i].getStyle());
+ fonts[i].setColor(fontsSettings[i].getColor());
+ }
+}
+
+void FontList::saveSettings() {
+ char fontParam[512];
+ for (int i=0;i<FONTCOUNT;i++) {
+ sprintf(fontParam, "Font%dFace", i);
+ DBWriteContactSettingString(NULL, muccModuleName, fontParam, fontsSettings[i].getFace());
+ sprintf(fontParam, "Font%dSet", i);
+ DBWriteContactSettingByte(NULL, muccModuleName, fontParam, fontsSettings[i].getCharSet());
+ sprintf(fontParam, "Font%dSize", i);
+ DBWriteContactSettingDword(NULL, muccModuleName, fontParam, fontsSettings[i].getSize());
+ sprintf(fontParam, "Font%dCol", i);
+ DBWriteContactSettingDword(NULL, muccModuleName, fontParam, fontsSettings[i].getColor());
+ sprintf(fontParam, "Font%dStyle", i);
+ DBWriteContactSettingByte(NULL, muccModuleName, fontParam, fontsSettings[i].getStyle());
+ fonts[i].setName(fontsSettings[i].getName());
+ fonts[i].setFace(fontsSettings[i].getFace());
+ fonts[i].setCharSet(fontsSettings[i].getCharSet());
+ fonts[i].setStyle(fontsSettings[i].getStyle());
+ fonts[i].setSize(fontsSettings[i].getSize());
+ fonts[i].setColor(fontsSettings[i].getColor());
+ }
+}
+
+void FontList::init() {
+ fonts = new Font[FONTCOUNT];
+ fontsSettings = new Font[FONTCOUNT];
+ loadSettings();
+}
+
+void FontList::release() {
+ delete[] fonts;
+ delete[] fontsSettings;
+}
+
+int FontList::getFontNum() {
+ return FONTCOUNT;
+}
diff --git a/protocols/Tlen/tlen_czaty/FontList.h b/protocols/Tlen/tlen_czaty/FontList.h
new file mode 100644
index 0000000000..2e0076e765
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/FontList.h
@@ -0,0 +1,90 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef FONTLIST_INCLUDED
+#define FONTLIST_INCLUDED
+#include "mucc.h"
+
+
+class Font {
+private:
+ COLORREF color;
+ char * face;
+ char * name;
+ int size;
+ int style;
+ int charSet;
+public:
+ enum STYLES {
+ BOLD = 1,
+ ITALIC = 2,
+ UNDERLINE = 4,
+ STROKE = 8,
+ UNDERWAVE = 16
+ };
+ Font();
+ Font(const char *name, const char *face, int charSet, int size, int style, COLORREF color);
+ void setColor(COLORREF c);
+ COLORREF getColor();
+ void setSize(int s);
+ int getSize();
+ void setStyle(int s);
+ int getStyle();
+ void setFace(const char *s);
+ const char *getFace();
+ void setName(const char *s);
+ const char *getName();
+ void setCharSet(int s);
+ int getCharSet();
+};
+
+class FontList {
+private:
+ static Font *fonts;
+ static Font *fontsSettings;
+public:
+ enum FONTIDEX {
+ FONT_TIMESTAMP = 0,
+// FONT_COLON = 1,
+ FONT_OTHERSNAMES = 1,
+ FONT_MYNAME = 2,
+ FONT_INMESSAGE = 3,
+ FONT_OUTMESSAGE = 4,
+ FONT_JOINED = 5,
+ FONT_LEFT = 6,
+ FONT_TOPIC = 7,
+// FONT_NOTIFICATION = 9,
+ FONT_ERROR = 8,
+ FONT_TYPING = 9,
+ FONT_USERLIST = 10,
+ FONT_USERLISTGROUP = 11
+ };
+ static Font *getFont(int index);
+ static Font *getFontSettings(int index);
+ static void release();
+ static void init();
+ static int getFontNum();
+ static void loadSettings();
+ static void saveSettings();
+};
+
+#endif
+
+
diff --git a/protocols/Tlen/tlen_czaty/HelperDialog.cpp b/protocols/Tlen/tlen_czaty/HelperDialog.cpp
new file mode 100644
index 0000000000..343d66b89d
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/HelperDialog.cpp
@@ -0,0 +1,589 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "HelperDialog.h"
+#include "Utils.h"
+
+static INT_PTR CALLBACK InviteDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK AcceptInvitationDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK JoinDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+//static INT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK TopicDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static void __cdecl InviteDlgThread(void *vDialog);
+static void __cdecl AcceptInvitationDlgThread(void *vDialog);
+static void __cdecl JoinDlgThread(void *vDialog);
+static void __cdecl ErrorDlgThread(void *vDialog);
+static void __cdecl TopicDlgThread(void *vDialog);
+
+HelperDialog * HelperDialog::list = NULL;
+CRITICAL_SECTION HelperDialog::mutex;
+
+HelperDialog::HelperContact::HelperContact(const char *id, const char *name) {
+ this->id = NULL;
+ this->name = NULL;
+ next = NULL;
+ Utils::copyString(&this->id, id);
+ Utils::copyString(&this->name, name);
+}
+HelperDialog::HelperContact::~HelperContact() {
+ if (id != NULL) delete id;
+ if (name != NULL) delete name;
+}
+
+void HelperDialog::HelperContact::setNext(HelperContact *next) {
+ this->next = next;
+}
+
+const char *HelperDialog::HelperContact::getId() {
+ return id;
+}
+
+const char *HelperDialog::HelperContact::getName() {
+ return name;
+}
+
+HelperDialog::HelperContact* HelperDialog::HelperContact::getNext() {
+ return next;
+}
+
+void HelperDialog::init() {
+ InitializeCriticalSection(&mutex);
+}
+
+void HelperDialog::release() {
+ while (list!=NULL) {
+ delete list;
+ }
+ DeleteCriticalSection(&mutex);
+}
+
+HelperDialog::HelperDialog() {
+ module = nick = reason = roomId = roomName = NULL;
+ prev = next = NULL;
+ contactList = NULL;
+ hWnd = NULL;
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ EnterCriticalSection(&mutex);
+ setNext(list);
+ if (next!=NULL) {
+ next->setPrev(this);
+ }
+ list = this;
+ LeaveCriticalSection(&mutex);
+}
+
+HelperDialog::HelperDialog(ChatWindow *chat) {
+ module = nick = reason = roomId = roomName = NULL;
+ prev = next = NULL;
+ contactList = NULL;
+ hWnd = NULL;
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ setModule(chat->getModule());
+ setRoomId(chat->getRoomId());
+ setRoomName(chat->getRoomName());
+ setRoomFlags(chat->getRoomFlags());
+ EnterCriticalSection(&mutex);
+ setNext(list);
+ if (next!=NULL) {
+ next->setPrev(this);
+ }
+ list = this;
+ LeaveCriticalSection(&mutex);
+}
+
+HelperDialog::~HelperDialog()
+{
+ EnterCriticalSection(&mutex);
+ if (getPrev()!=NULL) {
+ getPrev()->setNext(next);
+ } else {
+ list = getNext();
+ }
+ if (getNext()!=NULL) {
+ getNext()->setPrev(prev);
+ }
+ LeaveCriticalSection(&mutex);
+ if (hEvent!=NULL) CloseHandle(hEvent);
+ if (module!=NULL) delete module;
+ if (roomId!=NULL) delete roomId;
+ if (roomName!=NULL) delete roomName;
+ if (nick!=NULL) delete nick;
+ if (reason!=NULL) delete reason;
+ for (HelperContact *ptr2, *ptr=contactList;ptr!=NULL;ptr=ptr2) {
+ ptr2 = ptr->getNext();
+ delete ptr;
+ }
+}
+void HelperDialog::setHWND(HWND hWnd) {
+ this->hWnd = hWnd;
+}
+HWND HelperDialog::getHWND() {
+ return hWnd;
+}
+void HelperDialog::setPrev(HelperDialog *prev) {
+ this->prev = prev;
+}
+void HelperDialog::setNext(HelperDialog *next) {
+ this->next = next;
+}
+HelperDialog * HelperDialog::getPrev() {
+ return prev;
+}
+HelperDialog * HelperDialog::getNext() {
+ return next;
+}
+const char *HelperDialog::getModule()
+{
+ return module;
+}
+const char *HelperDialog::getRoomId()
+{
+ return roomId;
+}
+const char *HelperDialog::getRoomName()
+{
+ return roomName;
+}
+const char *HelperDialog::getNick()
+{
+ return nick;
+}
+const char *HelperDialog::getReason()
+{
+ return reason;
+}
+void HelperDialog::setModule(const char *module)
+{
+ Utils::copyString(&this->module, module);
+}
+void HelperDialog::setRoomId(const char *roomId)
+{
+ Utils::copyString(&this->roomId, roomId);
+}
+void HelperDialog::setRoomName(const char *roomName)
+{
+ Utils::copyString(&this->roomName, roomName);
+}
+void HelperDialog::setNick(const char *nick)
+{
+ Utils::copyString(&this->nick, nick);
+}
+void HelperDialog::setReason(const char *reason)
+{
+ Utils::copyString(&this->reason, reason);
+}
+void HelperDialog::setRoomFlags(DWORD flags)
+{
+ this->roomFlags = flags;
+}
+void HelperDialog::setContactList(MUCCQUERYRESULT *queryResult) {
+ HelperContact *ptr, *lastptr;
+ for (ptr=contactList;ptr!=NULL;ptr=ptr->getNext()) {
+ delete ptr;
+ }
+ contactList = NULL;
+ lastptr = NULL;
+ for (int i=0;i<queryResult->iItemsNum;i++) {
+ ptr = new HelperContact(queryResult->pItems[i].pszID, queryResult->pItems[i].pszName);
+ if (lastptr != NULL) {
+ lastptr->setNext(ptr);
+ } else {
+ contactList = ptr;
+ }
+ lastptr = ptr;
+ }
+}
+
+HelperDialog::HelperContact * HelperDialog::getContactList() {
+ return contactList;
+}
+
+DWORD HelperDialog::getRoomFlags() {
+ return roomFlags;
+}
+
+void HelperDialog::inviteDlg(ChatWindow *chat, MUCCQUERYRESULT *queryResult) {
+ HelperDialog *dialog=new HelperDialog(chat);
+ dialog->setContactList(queryResult);
+ Utils::forkThread((void (__cdecl *)(void *))InviteDlgThread, 0, (void *) dialog);
+ //WaitForSingleObject(dialog->getEvent(), INFINITE);
+}
+
+void HelperDialog::acceptDlg(MUCCEVENT *event) {
+ HelperDialog *dialog=new HelperDialog();
+ dialog->setModule(event->pszModule);
+ dialog->setRoomId(event->pszID);
+ dialog->setRoomName(event->pszName);
+ dialog->setRoomFlags(event->dwFlags);
+ dialog->setNick(event->pszNick);
+ // dialog->setReason(event->pszText);
+ Utils::forkThread((void (__cdecl *)(void *))AcceptInvitationDlgThread, 0, (void *) dialog);
+// WaitForSingleObject(hEvent, INFINITE);
+}
+
+void HelperDialog::joinDlg(MUCCEVENT *event) {
+ HelperDialog *dialog=new HelperDialog();
+ dialog->setModule(event->pszModule);
+ dialog->setRoomId(event->pszID);
+ dialog->setRoomName(event->pszName);
+ dialog->setRoomFlags(event->dwFlags);
+ dialog->setNick(event->pszNick);
+ Utils::forkThread((void (__cdecl *)(void *))JoinDlgThread, 0, (void *) dialog);
+ //WaitForSingleObject(dialog->getEvent(), INFINITE);
+}
+
+void HelperDialog::errorDlg(MUCCEVENT *event) {
+ HelperDialog *dialog=new HelperDialog();
+ dialog->setReason(event->pszText);
+ Utils::forkThread((void (__cdecl *)(void *))ErrorDlgThread, 0, (void *) dialog);
+ //WaitForSingleObject(dialog->getEvent(), INFINITE);
+}
+
+void HelperDialog::topicDlg(ChatWindow *chat)
+{
+ HelperDialog *dialog=new HelperDialog();
+ dialog->setModule(chat->getModule());
+ dialog->setRoomId(chat->getRoomId());
+ Utils::forkThread((void (__cdecl *)(void *))TopicDlgThread, 0, (void *) dialog);
+}
+
+static void __cdecl InviteDlgThread(void *vDialog)
+{
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_HELPER_INVITE), NULL, InviteDlgProc, (LPARAM) vDialog);
+}
+
+static void __cdecl AcceptInvitationDlgThread(void *vDialog)
+{
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_HELPER_INVITE_ACCEPT), NULL, AcceptInvitationDlgProc, (LPARAM) vDialog);
+}
+
+static void __cdecl JoinDlgThread(void *vDialog)
+{
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_HELPER_JOIN), NULL, JoinDlgProc, (LPARAM) vDialog);
+}
+
+static void __cdecl TopicDlgThread(void *vDialog)
+{
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_HELPER_TOPIC), NULL, TopicDlgProc, (LPARAM) vDialog);
+}
+
+static INT_PTR CALLBACK InviteDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char str[256];
+ HelperDialog::HelperContact *contactList;
+ HelperDialog *dialog = (HelperDialog *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ dialog = (HelperDialog *) lParam;
+ TranslateDialogDefault(hwndDlg);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) dialog);
+ dialog->setHWND(hwndDlg);
+ SendDlgItemMessage(hwndDlg, IDC_REASON, EM_SETREADONLY, (WPARAM)TRUE, 0);
+ for (contactList = dialog->getContactList();contactList!=NULL;contactList=contactList->getNext()) {
+ SendDlgItemMessage(hwndDlg, IDC_USER, CB_ADDSTRING, 0, (LPARAM)contactList->getName());
+ }
+ return TRUE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_INVITE:
+ MUCCEVENT muce;
+ GetDlgItemTextA(hwndDlg, IDC_USER, str, 255);
+ if (strlen(str)>0) {
+ for (contactList = dialog->getContactList();contactList!=NULL;contactList=contactList->getNext()) {
+ if (!strcmp(str, contactList->getName())) {
+ dialog->setNick(contactList->getId());
+ break;
+ }
+ }
+ if (contactList==NULL) {
+ dialog->setNick(str);
+ }
+ }
+ muce.iType = MUCC_EVENT_INVITE;
+ muce.pszModule = dialog->getModule();
+ muce.pszID = dialog->getRoomId();
+ muce.pszNick = dialog->getNick();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ case IDCANCEL:
+ case IDCLOSE:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+ EndDialog(hwndDlg, 0);
+ break;
+ case WM_DESTROY:
+ delete dialog;
+ break;
+ }
+ return FALSE;
+}
+
+
+
+
+static INT_PTR CALLBACK AcceptInvitationDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char str[256];
+ HelperDialog *dialog;
+ dialog = (HelperDialog *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ {
+ dialog = (HelperDialog *) lParam;
+ TranslateDialogDefault(hwndDlg);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) dialog);
+ dialog->setHWND(hwndDlg);
+ if (dialog->getNick() != NULL) {
+ SetDlgItemTextA(hwndDlg, IDC_FROM, dialog->getNick());
+ }
+ if (dialog->getRoomName() != NULL) {
+ SetDlgItemTextA(hwndDlg, IDC_ROOM, dialog->getRoomName());
+ }
+ if (dialog->getReason() != NULL) {
+ SetDlgItemTextA(hwndDlg, IDC_REASON, dialog->getReason());
+ }
+
+// if (!DBGetContactSetting(NULL, jabberProtoName, "LoginName", &dbv)) {
+// SetDlgItemText(hwndDlg, IDC_NICK, dbv.pszVal);
+// DBFreeVariant(&dbv);
+// }
+
+ /*
+ SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM) LoadIcon(hInst, MAKEINTRESOURCE(IDI_GROUP)));
+*/
+ }
+ return TRUE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_ACCEPT:
+ GetDlgItemTextA(hwndDlg, IDC_NICK, str, 255);
+ dialog->setNick(str);
+ MUCCEVENT muce;
+ muce.iType = MUCC_EVENT_JOIN;
+ muce.pszModule = dialog->getModule();
+ muce.pszID = dialog->getRoomId();
+ muce.pszName = dialog->getRoomName();
+ muce.dwFlags = dialog->getRoomFlags();
+ muce.pszNick = NULL;
+ if (strlen(dialog->getNick())>0) {
+ muce.pszNick = dialog->getNick();
+ } else {
+ muce.pszNick = NULL;
+ }
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ case IDCANCEL:
+ case IDCLOSE:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+ EndDialog(hwndDlg, 0);
+ break;
+ case WM_DESTROY:
+ delete dialog;
+ break;
+ }
+
+ return FALSE;
+}
+
+
+static INT_PTR CALLBACK JoinDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char str[256];
+ HelperDialog *dialog;
+ dialog = (HelperDialog *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ dialog = (HelperDialog *) lParam;
+ TranslateDialogDefault(hwndDlg);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) dialog);
+ dialog->setHWND(hwndDlg);
+ SetFocus(GetDlgItem(hwndDlg, IDOK));
+ if (dialog->getRoomFlags() & MUCC_EF_ROOM_NAME) {
+ SetFocus(GetDlgItem(hwndDlg, IDC_ROOM));
+ } else {
+ SendDlgItemMessage(hwndDlg, IDC_ROOM, EM_SETREADONLY, (WPARAM)TRUE, 0);
+ }
+ if (dialog->getRoomFlags() & MUCC_EF_ROOM_NICKNAMES) {
+ SetFocus(GetDlgItem(hwndDlg, IDC_NICK));
+ } else {
+ SendDlgItemMessage(hwndDlg, IDC_NICK, EM_SETREADONLY, (WPARAM)TRUE, 0);
+ }
+ if (dialog->getRoomName()!=NULL) {
+ SetDlgItemTextA(hwndDlg, IDC_ROOM, dialog->getRoomName());
+ }
+ if (dialog->getNick()!=NULL) {
+ SetDlgItemTextA(hwndDlg, IDC_NICK, dialog->getNick());
+ }
+ return FALSE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDOK:
+ MUCCEVENT muce;
+ if (dialog->getRoomId()==NULL) {
+ GetDlgItemTextA(hwndDlg, IDC_ROOM, str, 255);
+ if (strlen(str)>0) {
+ //dialog->setRoomId(str);
+ dialog->setRoomName(str);
+ }
+ }
+ GetDlgItemTextA(hwndDlg, IDC_NICK, str, 255);
+ if (strlen(str)>0) {
+ dialog->setNick(str);
+ } else {
+ dialog->setNick(NULL);
+ }
+ muce.iType = MUCC_EVENT_JOIN;
+ muce.pszModule = dialog->getModule();
+ muce.pszID = dialog->getRoomId();
+ muce.pszName = dialog->getRoomName();
+ muce.pszNick = dialog->getNick();
+ muce.dwFlags = dialog->getRoomFlags();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+ EndDialog(hwndDlg, 0);
+ break;
+ case WM_DESTROY:
+ delete dialog;
+ break;
+ }
+ return FALSE;
+}
+
+static void __cdecl ErrorDlgThread(void *vDialog)
+{
+ HelperDialog *dialog=(HelperDialog *)vDialog;
+ MessageBoxA(NULL, dialog->getReason(), Translate("Error"), MB_OK | MB_ICONERROR);
+ /*
+ int result = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_GROUPCHAT_JOIN), NULL, JoinDlgProc, (LPARAM) dialog);
+ if (result!=0) {
+ MUCCEVENT muce;
+ muce.iType = MUCC_EVENT_JOIN;
+ muce.pszModule = dialog->getModule();
+ muce.pszID = dialog->getRoomId();
+ muce.pszName = dialog->getRoomName();
+ muce.pszNick = dialog->getNick();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ }
+ */
+ delete dialog;
+}
+
+/*
+static INT_PTR CALLBACK ErrorDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char str[256];
+ HelperDialog *dialog;
+ dialog = (HelperDialog *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ dialog = (HelperDialog *) lParam;
+ TranslateDialogDefault(hwndDlg);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) dialog);
+ dialog->setHWND(hwndDlg);
+ SetFocus(GetDlgItem(hwndDlg, IDOK));
+ if (dialog->getRoomName()!=NULL) {
+ SetDlgItemTextA(hwndDlg, IDC_ROOM, dialog->getRoomName());
+ }
+ if (dialog->getNick()!=NULL) {
+ SetDlgItemTextA(hwndDlg, IDC_NICK, dialog->getNick());
+ }
+ return FALSE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDOK:
+ if (dialog->getRoomId()==NULL) {
+ GetDlgItemTextA(hwndDlg, IDC_ROOM, str, 255);
+ if (strlen(str)>0) {
+ //dialog->setRoomId(str);
+ dialog->setRoomName(str);
+ }
+ }
+ GetDlgItemTextA(hwndDlg, IDC_NICK, str, 255);
+ if (strlen(str)>0) {
+ dialog->setNick(str);
+ } else {
+ dialog->setNick(NULL);
+ }
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+ EndDialog(hwndDlg, 0);
+ break;
+ case WM_DESTROY:
+ delete dialog;
+ break;
+ }
+ return FALSE;
+}
+*/
+
+static INT_PTR CALLBACK TopicDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ char str[256];
+ HelperDialog *dialog;
+ dialog = (HelperDialog *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ dialog = (HelperDialog *) lParam;
+ TranslateDialogDefault(hwndDlg);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) dialog);
+ dialog->setHWND(hwndDlg);
+ return FALSE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDOK:
+ MUCCEVENT muce;
+ GetDlgItemTextA(hwndDlg, IDC_TOPIC, str, 255);
+ dialog->setReason(str);
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_TOPIC;
+ muce.pszID = dialog->getRoomId();
+ muce.pszModule = dialog->getModule();
+ muce.pszText = dialog->getReason();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+ EndDialog(hwndDlg, 0);
+ break;
+ case WM_DESTROY:
+ delete dialog;
+ break;
+ }
+ return FALSE;
+}
+
diff --git a/protocols/Tlen/tlen_czaty/HelperDialog.h b/protocols/Tlen/tlen_czaty/HelperDialog.h
new file mode 100644
index 0000000000..08f856c3a9
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/HelperDialog.h
@@ -0,0 +1,95 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef DIALOGS_INCLUDED
+#define DIALOGS_INCLUDED
+
+#include "mucc.h"
+#include "m_mucc.h"
+#include "ChatWindow.h"
+
+
+class HelperDialog {
+public:
+ class HelperContact {
+ private:
+ char *id;
+ char *name;
+ HelperContact *next;
+ public:
+ HelperContact(const char *id, const char *name);
+ ~HelperContact();
+ void setNext(HelperContact *);
+ HelperContact* getNext();
+ const char * getId();
+ const char * getName();
+ };
+
+private:
+ static HelperDialog * list;
+ static CRITICAL_SECTION mutex;
+ char * module;
+ char * roomId;
+ char * roomName;
+ DWORD roomFlags;
+ HelperContact * contactList;
+ HelperDialog * prev;
+ HelperDialog * next;
+ char * nick;
+ char * reason;
+ HANDLE hEvent;
+ HWND hWnd;
+public:
+ HelperDialog();
+ HelperDialog(ChatWindow *);
+ ~HelperDialog();
+ void setModule(const char *);
+ void setRoomId(const char *);
+ void setRoomName(const char *);
+ void setRoomFlags(DWORD);
+ void setNick(const char *);
+ void setReason(const char *);
+ void setPrev(HelperDialog *);
+ HelperDialog* getPrev();
+ void setNext(HelperDialog *);
+ HelperDialog* getNext();
+ HWND getHWND();
+ void setHWND(HWND hWnd);
+ void setContactList(MUCCQUERYRESULT *queryResult);
+ HelperContact* getContactList();
+ const char * getModule();
+ const char * getRoomId();
+ const char * getRoomName();
+ DWORD getRoomFlags();
+ const char * getNick();
+ const char * getReason();
+ HANDLE getEvent();
+ static void init();
+ static void release();
+ static void inviteDlg(ChatWindow *chat, MUCCQUERYRESULT *queryResult);
+ static void acceptDlg(MUCCEVENT *event);
+ static void joinDlg(MUCCEVENT *event);
+ static void errorDlg(MUCCEVENT *event);
+ static void topicDlg(ChatWindow *chat);
+};
+
+
+
+#endif
diff --git a/protocols/Tlen/tlen_czaty/ManagerWindow.cpp b/protocols/Tlen/tlen_czaty/ManagerWindow.cpp
new file mode 100644
index 0000000000..a01caebc15
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ManagerWindow.cpp
@@ -0,0 +1,1067 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include "ManagerWindow.h"
+#include "Utils.h"
+#include "HelperDialog.h"
+
+static INT_PTR CALLBACK ManagerDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK ChatRoomsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+static INT_PTR CALLBACK MyRoomsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+ManagerWindow * ManagerWindow::list = NULL;
+bool ManagerWindow::released = false;
+CRITICAL_SECTION ManagerWindow::mutex;
+
+void ManagerWindow::init() {
+ released = false;
+ InitializeCriticalSection(&mutex);
+}
+
+void ManagerWindow::release() {
+ released = true;
+ for (ManagerWindow *ptr2, *ptr = list; ptr!=NULL; ptr=ptr2) {
+ ptr2 = ptr->getNext();
+ delete ptr;
+// SendMessage(ptr->getHWND(), WM_CLOSE, 0, 0);
+ }
+ DeleteCriticalSection(&mutex);
+}
+
+ManagerWindow::ManagerWindow(const char *module)
+{
+ next = prev = NULL;
+ groups = NULL;
+ rooms = NULL;
+ myRooms = NULL;
+ currentGroup = NULL;
+ isStarted = 0;
+ currentTab = 0;
+ currentRoomsPage = 0;
+ lastRoomsPage = 0;
+ userNickList = userRoomList = 0;
+ this->module = NULL;
+ this->moduleName = NULL;
+ Utils::copyString(&this->module, module);
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ EnterCriticalSection(&mutex);
+ setNext(list);
+ if (next!=NULL) {
+ next->setPrev(this);
+ }
+ list = this;
+ LeaveCriticalSection(&mutex);
+}
+
+ManagerWindow::~ManagerWindow()
+{
+ if (!released) {
+ EnterCriticalSection(&mutex);
+ if (getPrev()!=NULL) {
+ getPrev()->setNext(next);
+ } else {
+ list = getNext();
+ }
+ if (getNext()!=NULL) {
+ getNext()->setPrev(prev);
+ }
+ LeaveCriticalSection(&mutex);
+ }
+ if (hWnd!=NULL) {
+ EndDialog(hWnd, 0);
+ }
+ if (hEvent!=NULL) {
+ CloseHandle(hEvent);
+ }
+ while (groups!=NULL) {
+ ChatGroup *group = groups;
+ groups = groups->getListNext();
+ delete group;
+ }
+ while (rooms!=NULL) {
+ ChatRoom *room = rooms;
+ rooms = rooms->getNext();
+ delete room;
+ }
+ while (myRooms!=NULL) {
+ ChatRoom *room = myRooms;
+ myRooms = myRooms->getNext();
+ delete room;
+ }
+ if (module!=NULL) {
+ delete module;
+ }
+ if (moduleName!=NULL) {
+ delete moduleName;
+ }
+}
+void ManagerWindow::setPrev(ManagerWindow *prev)
+{
+ this->prev = prev;
+}
+ManagerWindow * ManagerWindow::getPrev()
+{
+ return prev;
+}
+void ManagerWindow::setNext(ManagerWindow *next)
+{
+ this->next = next;
+}
+ManagerWindow * ManagerWindow::getNext()
+{
+ return next;
+}
+void ManagerWindow::setHWND(HWND h)
+{
+ hWnd=h;
+}
+HWND ManagerWindow::getHWND()
+{
+ return hWnd;
+}
+void ManagerWindow::setChatRoomsTabHWND(HWND h)
+{
+ hChatRoomsTabWnd=h;
+}
+HWND ManagerWindow::getChatRoomsTabHWND()
+{
+ return hChatRoomsTabWnd;
+}
+void ManagerWindow::setMyRoomsTabHWND(HWND h)
+{
+ hMyRoomsTabWnd=h;
+}
+HWND ManagerWindow::getMyRoomsTabHWND()
+{
+ return hMyRoomsTabWnd;
+}
+void ManagerWindow::setMyNicksTabHWND(HWND h)
+{
+ hMyNicksTabWnd=h;
+}
+HWND ManagerWindow::getMyNicksTabHWND()
+{
+ return hMyNicksTabWnd;
+}
+const char *ManagerWindow::getModule()
+{
+ return module;
+}
+const char *ManagerWindow::getModuleName()
+{
+ return moduleName;
+}
+void ManagerWindow::setModuleName(const char *moduleName)
+{
+ Utils::copyString(&this->moduleName, moduleName);
+}
+ChatGroup *ManagerWindow::getCurrentGroup()
+{
+ return currentGroup;
+}
+void ManagerWindow::setCurrentGroup(ChatGroup *group)
+{
+ currentGroup = group;
+}
+HANDLE ManagerWindow::getEvent()
+{
+ return hEvent;
+}
+int ManagerWindow::getCurrentTab()
+{
+ return currentTab;
+}
+void ManagerWindow::setCurrentRoomsPage(int currentRoomsPage)
+{
+ this->currentRoomsPage = currentRoomsPage;
+}
+int ManagerWindow::getCurrentRoomsPage()
+{
+ return currentRoomsPage;
+}
+void ManagerWindow::setCurrentTab(int currentTab)
+{
+ this->currentTab = currentTab;
+}
+void ManagerWindow::setLastRoomsPage(int lastRoomsPage)
+{
+ this->lastRoomsPage = lastRoomsPage;
+}
+int ManagerWindow::isLastRoomsPage()
+{
+ return lastRoomsPage;
+}
+int ManagerWindow::isUserNickListReceived()
+{
+ return userNickList;
+}
+int ManagerWindow::isUserRoomListReceived()
+{
+ return userRoomList;
+}
+static void __cdecl StartThread(void *vManager)
+{
+ OleInitialize(NULL);
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_CHATMANAGER), NULL, ManagerDlgProc, (LPARAM) vManager);
+ OleUninitialize();
+}
+int ManagerWindow::start()
+{
+ if (isStarted) {
+ ShowWindow(hWnd, SW_SHOW);
+ return 0;
+ }
+ isStarted = 1;
+ Utils::forkThread((void (__cdecl *)(void *))StartThread, 0, (void *) this);
+ WaitForSingleObject(hEvent, INFINITE);
+ return 0;
+}
+void ManagerWindow::queryResultGroups(MUCCQUERYRESULT *queryResult)
+{
+ TVINSERTSTRUCT tvis;
+ ChatGroup * par = NULL;
+ ChatGroup * group;
+ if (queryResult->pszParent != NULL) {
+ par = findGroup(queryResult->pszParent);
+ if (par!=NULL) {
+ if (par->getChild()!=NULL) return;
+ }
+ }
+ for (int i=0; i<queryResult->iItemsNum; i++) {
+ group = new ChatGroup();
+ group->setId(queryResult->pItems[i].pszID);
+ group->setName(queryResult->pItems[i].pszName);
+ if (par!=NULL) {
+ par->addChild(group);
+ //group->setParent(par);
+ tvis.hParent = par->getTreeItem();
+ } else {
+ tvis.hParent = NULL;
+ }
+ tvis.hInsertAfter = TVI_SORT;
+ tvis.item.mask = TVIF_TEXT | TVIF_CHILDREN | TVIF_PARAM;
+ LPTSTR lps1 = Utils::mucc_mir_a2t(queryResult->pItems[i].pszName);
+ tvis.item.pszText = lps1;
+ tvis.item.cChildren = queryResult->pItems[i].iCount;
+ tvis.item.lParam = (LPARAM) group;
+ group->setTreeItem(TreeView_InsertItem(GetDlgItem(hWnd, IDC_GROUP), &tvis));
+ group->setListNext(groups);
+ groups = group;
+ if (par != NULL) {
+ TreeView_Expand(GetDlgItem(hWnd, IDC_GROUP), par->getTreeItem(), TVE_EXPAND);
+ }
+ Utils::mucc_mir_free(lps1);
+ }
+}
+
+void ManagerWindow::queryResultRooms(MUCCQUERYRESULT *queryResult)
+{
+ ChatRoom *room;
+ while (rooms!=NULL) {
+ room = rooms;
+ rooms = rooms->getNext();
+ delete room;
+ }
+ TCHAR str[100];
+ if (getCurrentGroup()==NULL || strcmp(getCurrentGroup()->getId(), queryResult->pszParent) || queryResult->iPage!=getCurrentRoomsPage()) return;
+ setLastRoomsPage(queryResult->iLastPage);
+ if (queryResult->iLastPage) {
+ EnableWindow(GetDlgItem(getChatRoomsTabHWND(), IDC_NEXT), FALSE);
+ } else {
+ EnableWindow(GetDlgItem(getChatRoomsTabHWND(), IDC_NEXT), TRUE);
+ }
+ if (queryResult->iPage>0) {
+ EnableWindow(GetDlgItem(getChatRoomsTabHWND(), IDC_PREV), TRUE);
+ } else {
+ EnableWindow(GetDlgItem(getChatRoomsTabHWND(), IDC_PREV), FALSE);
+ }
+ for (int i=0; i<queryResult->iItemsNum; i++) {
+ LVITEM lvItem;
+ room = new ChatRoom();
+ room->setId(queryResult->pItems[i].pszID);
+ room->setName(queryResult->pItems[i].pszName);
+ room->setFlags(queryResult->pItems[i].dwFlags);
+ room->setNext(rooms);
+ rooms=room;
+ lvItem.mask = LVIF_TEXT | LVIF_PARAM;
+ lvItem.iSubItem = 0;
+ lvItem.iItem = ListView_GetItemCount(GetDlgItem(getChatRoomsTabHWND(), IDC_ROOM));
+ LPTSTR lps1 = Utils::mucc_mir_a2t(queryResult->pItems[i].pszName);
+ lvItem.pszText = lps1;
+ lvItem.lParam = (LPARAM) room;
+ ListView_InsertItem(GetDlgItem(getChatRoomsTabHWND(), IDC_ROOM), &lvItem);
+ lvItem.iSubItem = 1;
+ ListView_InsertItem(GetDlgItem(getChatRoomsTabHWND(), IDC_ROOM), &lvItem);
+ _stprintf(str, _TEXT("%d"), queryResult->pItems[i].iCount);
+ ListView_SetItemText(GetDlgItem(getChatRoomsTabHWND(), IDC_ROOM), lvItem.iItem, 1, str);
+ Utils::mucc_mir_free(lps1);
+ }
+}
+
+void ManagerWindow::queryResultUserRooms(MUCCQUERYRESULT *queryResult)
+{
+ ChatRoom *room;
+ ListView_DeleteAllItems(GetDlgItem(getMyRoomsTabHWND(), IDC_LIST));
+ while (myRooms!=NULL) {
+ room = myRooms;
+ myRooms = myRooms->getNext();
+ delete room;
+ }
+ for (int i=0; i<queryResult->iItemsNum; i++) {
+ LVITEM lvItem;
+ room = new ChatRoom();
+ room->setId(queryResult->pItems[i].pszID);
+ room->setName(queryResult->pItems[i].pszName);
+ room->setNext(myRooms);
+ myRooms=room;
+ lvItem.mask = LVIF_TEXT | LVIF_PARAM;
+ lvItem.iSubItem = 0;
+ lvItem.iItem = ListView_GetItemCount(GetDlgItem(getMyRoomsTabHWND(), IDC_LIST));
+ LPTSTR lps1 = Utils::mucc_mir_a2t(queryResult->pItems[i].pszName);
+ lvItem.pszText = lps1;
+ lvItem.lParam = (LPARAM) room;
+ ListView_InsertItem(GetDlgItem(getMyRoomsTabHWND(), IDC_LIST), &lvItem);
+ Utils::mucc_mir_free(lps1);
+ }
+ userRoomList = 1;
+}
+
+void ManagerWindow::queryResultUserNick(MUCCQUERYRESULT *queryResult)
+{
+ ListView_DeleteAllItems(GetDlgItem(getMyNicksTabHWND(), IDC_LIST));
+ for (int i=0; i<queryResult->iItemsNum; i++) {
+ LVITEM lvItem;
+ lvItem.mask = LVIF_TEXT;
+ lvItem.iSubItem = 0;
+ lvItem.iItem = ListView_GetItemCount(GetDlgItem(getMyNicksTabHWND(), IDC_LIST));
+ LPTSTR lps1 = Utils::mucc_mir_a2t(queryResult->pItems[i].pszName);
+ lvItem.pszText = lps1;
+ ListView_InsertItem(GetDlgItem(getMyNicksTabHWND(), IDC_LIST), &lvItem);
+ Utils::mucc_mir_free(lps1);
+ }
+ userNickList = 1;
+}
+
+ChatGroup *ManagerWindow::findGroup(const char *id)
+{
+ ChatGroup *group;
+ for (group = groups;group!=NULL;group=group->getListNext()) {
+ if (!strcmp(group->getId(), id)) break;
+ }
+ return group;
+}
+
+
+static INT_PTR CALLBACK ChatRoomsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ HWND lv;
+ LVCOLUMN lvCol;
+ ManagerWindow *manager;
+ manager = (ManagerWindow *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ manager = (ManagerWindow *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) manager);
+ TranslateDialogDefault(hwndDlg);
+ manager->setChatRoomsTabHWND(hwndDlg);
+ SendDlgItemMessage(hwndDlg, IDC_PREV, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_NEXT, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_SEARCH, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_PREV, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_PREV]);
+ SendDlgItemMessage(hwndDlg, IDC_NEXT, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_NEXT]);
+ SendDlgItemMessage(hwndDlg, IDC_SEARCH, BM_SETIMAGE, IMAGE_ICON, (LPARAM) muccIcon[MUCC_IDI_SEARCH]);
+
+ lv = GetDlgItem(hwndDlg, IDC_ROOM);
+ ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT);
+ lvCol.mask = LVCF_TEXT | LVCF_WIDTH | LVCF_SUBITEM;
+ lvCol.pszText = TranslateT("Name");
+ lvCol.cx = 270;
+ lvCol.iSubItem = 0;
+ ListView_InsertColumn(lv, 0, &lvCol);
+ lvCol.pszText = TranslateT("Persons");
+ lvCol.cx = 50;
+ lvCol.iSubItem = 1;
+ ListView_InsertColumn(lv, 1, &lvCol);
+ lvCol.pszText = _TEXT("");//Translate("");
+ lvCol.cx = 46;
+ lvCol.iSubItem = 2;
+ ListView_InsertColumn(lv, 2, &lvCol);
+ return TRUE;
+ case WM_NOTIFY:
+ switch (wParam) {
+ case IDC_ROOM:
+ switch (((LPNMHDR)lParam)->code) {
+ case LVN_COLUMNCLICK:
+ {
+ LPNMLISTVIEW pnmlv = (LPNMLISTVIEW) lParam;
+ if (pnmlv->iSubItem>=0 && pnmlv->iSubItem<=1) {
+ // if (pnmlv->iSubItem == sortColumn)
+ // sortAscending = !sortAscending;
+ // else {
+ // sortAscending = TRUE;
+ // sortColumn = pnmlv->iSubItem;
+ // }
+ // ListView_SortItems(GetDlgItem(hwndDlg, IDC_ROOM), GroupchatCompare, sortColumn);
+ }
+ }
+ break;
+ case NM_DBLCLK:
+ {
+ LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) lParam;
+ LVITEM item;
+ item.iItem = lpnmitem->iItem;
+ item.iSubItem = 0;
+ item.mask = LVIF_PARAM;
+ if (ListView_GetItem(GetDlgItem(hwndDlg, IDC_ROOM), &item)) {
+ MUCCEVENT event;
+ ChatRoom *room = (ChatRoom *)item.lParam;
+ Utils::log("entering room %s ", room->getId());
+ event.cbSize = sizeof(MUCCEVENT);
+ event.iType = MUCC_EVENT_JOIN;
+ event.pszModule = manager->getModule();
+ event.pszID = room->getId();
+ event.pszName = room->getName();
+ event.dwFlags = room->getFlags();
+ event.pszNick = NULL;
+ HelperDialog::joinDlg(&event);
+ }
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_NEXT:
+ if (!manager->isLastRoomsPage()) {
+ EnableWindow(GetDlgItem(hwndDlg, IDC_PREV), FALSE);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_NEXT), FALSE);
+ manager->setCurrentRoomsPage(manager->getCurrentRoomsPage()+1);
+ SendMessage(GetParent(hwndDlg), WM_MUCC_REFRESH_ROOMS, 0, 0);
+ }
+ break;
+ case IDC_PREV:
+ if (manager->getCurrentRoomsPage()>0) {
+ EnableWindow(GetDlgItem(hwndDlg, IDC_PREV), FALSE);
+ EnableWindow(GetDlgItem(hwndDlg, IDC_NEXT), FALSE);
+ manager->setCurrentRoomsPage(manager->getCurrentRoomsPage()-1);
+ }
+ SendMessage(GetParent(hwndDlg), WM_MUCC_REFRESH_ROOMS, 0, 0);
+ break;
+ case IDC_SEARCH:
+ {
+ MUCCEVENT event;
+ event.cbSize = sizeof(MUCCEVENT);
+ event.iType = MUCC_EVENT_JOIN;
+ event.dwFlags = MUCC_EF_ROOM_NAME;
+ event.pszModule = manager->getModule();
+ event.pszID = NULL;
+ event.pszName = NULL;
+ event.pszNick = NULL;
+ HelperDialog::joinDlg(&event);
+ break;
+ }
+ }
+ break;
+ case WM_MEASUREITEM:
+ if (wParam == IDC_ROOM) {
+ MEASUREITEMSTRUCT *lpMis = (MEASUREITEMSTRUCT *) lParam;
+ lpMis->itemHeight = GetSystemMetrics(SM_CYSMICON);
+ return TRUE;
+ }
+ break;
+ case WM_DRAWITEM:
+ if (wParam == IDC_ROOM) {
+ RECT rc;
+ int w, x, col;
+ DRAWITEMSTRUCT *lpDis = (DRAWITEMSTRUCT *) lParam;
+ ChatRoom *room = NULL;
+// if (ListView_GetItem(GetDlgItem(hwndDlg, IDC_ROOM), &item)) {
+ room = (ChatRoom *)lpDis->itemData;// (ChatRoom *)item.lParam;
+// }
+ TCHAR text[256];
+ switch (lpDis->itemAction) {
+ default:
+ case ODA_SELECT:
+ case ODA_DRAWENTIRE:
+ if (lpDis->itemState & ODS_SELECTED) {
+ HBRUSH hBrush = CreateSolidBrush(RGB(0xC2, 0xC8, 0xDA));//0xDAC8C2);
+ FillRect(lpDis->hDC, &(lpDis->rcItem), hBrush);//(HBRUSH) (COLOR_HIGHLIGHT+1));
+ DeleteObject(hBrush);
+ SetTextColor(lpDis->hDC, 0);
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ }
+ else {
+// HBRUSH hBrush = CreateSolidBrush(RGB(0xC2, 0xC8, 0xDA));//0xDAC8C2);
+ FillRect(lpDis->hDC, &(lpDis->rcItem), (HBRUSH) (COLOR_WINDOW+1));
+// DeleteObject(hBrush);
+ SetTextColor(lpDis->hDC, RGB(0, 0, 0));//GetSysColor(COLOR_WINDOWTEXT));
+// SetBkColor(lpDis->hDC, GetSysColor(COLOR_WINDOW+1));
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ }
+ x = lpDis->rcItem.left;
+ for (col=0;col<3;col++) {
+ ListView_GetItemText(GetDlgItem(hwndDlg, IDC_ROOM), lpDis->itemID, col, text, sizeof(text)/sizeof(TCHAR));
+ w = ListView_GetColumnWidth(GetDlgItem(hwndDlg, IDC_ROOM), col);
+ rc.left = x;
+ rc.top = lpDis->rcItem.top;
+ rc.bottom = lpDis->rcItem.bottom;
+ rc.right = x+w;
+ if (col==0) {
+ rc.left+=2;
+ rc.right-=2;
+ DrawText(lpDis->hDC, text, (int)_tcslen(text), &rc, DT_LEFT|DT_NOPREFIX|DT_SINGLELINE|DT_VCENTER);
+ }
+ else if (col<2) {
+ DrawText(lpDis->hDC, text, (int)_tcslen(text), &rc, DT_CENTER|DT_NOPREFIX|DT_SINGLELINE|DT_VCENTER);
+ } else {
+ if (room->getFlags()&MUCC_EF_ROOM_MODERATED) {
+ DrawIconEx(lpDis->hDC, x, rc.top, muccIcon[MUCC_IDI_R_MODERATED], GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0, NULL, DI_NORMAL);
+ }
+ if (room->getFlags()&MUCC_EF_ROOM_MEMBERS_ONLY) {
+ DrawIconEx(lpDis->hDC, x+12+0*GetSystemMetrics(SM_CXSMICON), rc.top, muccIcon[MUCC_IDI_R_MEMBERS], GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0, NULL, DI_NORMAL);
+ }
+ if (!(room->getFlags()&MUCC_EF_ROOM_NICKNAMES)) {
+ DrawIconEx(lpDis->hDC, x+24+0*GetSystemMetrics(SM_CXSMICON), rc.top, muccIcon[MUCC_IDI_R_ANONYMOUS], GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0, NULL, DI_NORMAL);
+ }
+ }
+ x += w;
+ }
+ break;
+ }
+ }
+ break;
+ }
+ return FALSE;
+}
+
+static INT_PTR CALLBACK MyRoomsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ RECT rc;
+ HWND lv;
+ LVCOLUMN lvCol;
+ ManagerWindow *manager;
+ manager = (ManagerWindow *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ manager = (ManagerWindow *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) manager);
+ TranslateDialogDefault(hwndDlg);
+ manager->setMyRoomsTabHWND(hwndDlg);
+ lv = GetDlgItem(hwndDlg, IDC_LIST);
+ ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT);
+ GetClientRect(lv, &rc);
+ lvCol.mask = LVCF_WIDTH;
+ lvCol.cx = rc.right - rc.left;
+ ListView_InsertColumn(lv, 0, &lvCol);
+ return TRUE;
+ case WM_NOTIFY:
+ switch (wParam) {
+ case IDC_LIST:
+ switch (((LPNMHDR)lParam)->code) {
+ case NM_DBLCLK:
+ {
+ LVITEM item;
+ item.iItem = ListView_GetSelectionMark(GetDlgItem(hwndDlg, IDC_LIST));
+ if (item.iItem >= 0) {
+ item.iSubItem = 0;
+ item.mask = LVIF_PARAM;
+ if (ListView_GetItem(GetDlgItem(hwndDlg, IDC_LIST), &item)) {
+ ChatRoom *room = (ChatRoom *)item.lParam;
+ Utils::log("entering room %s (%s)", room->getId(), room->getId());
+ MUCCEVENT muce;
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_JOIN;
+ muce.pszModule = manager->getModule();
+ muce.pszID = room->getId();
+ muce.pszName = room->getName();
+ muce.dwFlags = MUCC_EF_ROOM_NICKNAMES;
+ muce.pszNick = NULL;
+ HelperDialog::joinDlg(&muce);
+ }
+ }
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_REFRESH:
+ SendMessage(GetParent(hwndDlg), WM_MUCC_REFRESH_USER_ROOMS, 0, 0);
+ break;
+ case IDC_REGISTER:
+ {
+ MUCCEVENT muce;
+ if (manager->getCurrentGroup()!=NULL) {
+ TCHAR name[256];
+ GetDlgItemText(hwndDlg, IDC_NAME, name, 255);
+ if (_tcslen(name)!=0) {
+ int flags = 0;
+ if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_PUBLIC)) {
+ flags |= MUCC_EF_ROOM_PUBLIC;
+ }
+ if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_PERMANENT)) {
+ flags |= MUCC_EF_ROOM_PERMANENT;
+ }
+ if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_MEMBERS)) {
+ flags |= MUCC_EF_ROOM_MEMBERS_ONLY;
+ }
+ if (IsDlgButtonChecked(hwndDlg, IDC_CHECK_NICKNAMES)) {
+ flags |= MUCC_EF_ROOM_NICKNAMES;
+ }
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_REGISTER_ROOM;
+ muce.pszModule = manager->getModule();
+ muce.pszID = manager->getCurrentGroup()->getId();
+ char* lps1 = Utils::mucc_mir_t2a(name);
+ muce.pszName = lps1;
+ muce.pszNick = NULL;
+ muce.dwFlags = flags;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ Utils::mucc_mir_free(lps1);
+ }
+ } else {
+ muce.pszText = "Please select a group first.";
+ HelperDialog::errorDlg(&muce);
+ }
+ }
+ break;
+ }
+ break;
+ case WM_MEASUREITEM:
+ if (wParam == IDC_LIST) {
+ MEASUREITEMSTRUCT *lpMis = (MEASUREITEMSTRUCT *) lParam;
+ lpMis->itemHeight = 16;//GetSystemMetrics(SM_CYSMICON);
+ return TRUE;
+ }
+ break;
+ case WM_DRAWITEM:
+ if (wParam == IDC_LIST) {
+ TCHAR text[256];
+ DRAWITEMSTRUCT *lpDis = (DRAWITEMSTRUCT *) lParam;
+ switch (lpDis->itemAction) {
+ default:
+ case ODA_SELECT:
+ case ODA_DRAWENTIRE:
+ if (lpDis->itemState & ODS_SELECTED) {
+ HBRUSH hBrush = CreateSolidBrush(RGB(0xC2, 0xC8, 0xDA));//0xDAC8C2);
+ FillRect(lpDis->hDC, &(lpDis->rcItem), hBrush);//(HBRUSH) (COLOR_HIGHLIGHT+1));
+ DeleteObject(hBrush);
+ SetTextColor(lpDis->hDC, 0);
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ }
+ else {
+ FillRect(lpDis->hDC, &(lpDis->rcItem), (HBRUSH) (COLOR_WINDOW+1));
+ SetTextColor(lpDis->hDC, RGB(0, 0, 0));//GetSysColor(COLOR_WINDOWTEXT));
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ }
+ ListView_GetItemText(GetDlgItem(hwndDlg, IDC_LIST), lpDis->itemID, 0, text, sizeof(text)/sizeof(TCHAR));
+ DrawText(lpDis->hDC, text, (int)_tcslen(text), &(lpDis->rcItem), DT_LEFT|DT_NOPREFIX|DT_SINGLELINE|DT_VCENTER);
+ break;
+ }
+ }
+ break;
+
+ }
+ return FALSE;
+}
+
+static INT_PTR CALLBACK MyNicksDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ RECT rc;
+ HWND lv;
+ LVCOLUMN lvCol;
+ ManagerWindow *manager;
+ manager = (ManagerWindow *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ manager = (ManagerWindow *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) manager);
+ TranslateDialogDefault(hwndDlg);
+ manager->setMyNicksTabHWND(hwndDlg);
+ lv = GetDlgItem(hwndDlg, IDC_LIST);
+ ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT);
+ GetClientRect(lv, &rc);
+ lvCol.mask = LVCF_WIDTH;
+ lvCol.cx = rc.right - rc.left;
+ ListView_InsertColumn(lv, 0, &lvCol);
+ return TRUE;
+ case WM_NOTIFY:
+ switch (wParam) {
+ case IDC_LIST:
+ break;
+
+ }
+ break;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_REFRESH:
+ SendMessage(GetParent(hwndDlg), WM_MUCC_REFRESH_USER_NICKS, 0, 0);
+ break;
+ case IDC_REGISTER:
+ {
+ char nick[256];
+ GetDlgItemTextA(hwndDlg, IDC_NICK, nick, 255);
+ if (strlen(nick)!=0) {
+ MUCCEVENT muce;
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_REGISTER_NICK;
+ muce.pszModule = manager->getModule();
+ muce.pszNick = nick;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ }
+ }
+ break;
+ case IDC_REMOVE:
+ {
+ LVITEM item;
+ item.iItem = ListView_GetSelectionMark(GetDlgItem(hwndDlg, IDC_LIST));
+ if (item.iItem >= 0) {
+ TCHAR text[256];
+ item.iSubItem = 0;
+ item.mask = LVIF_TEXT;
+ item.pszText = text;
+ item.cchTextMax = sizeof(text);
+ if (ListView_GetItem(GetDlgItem(hwndDlg, IDC_LIST), &item)) {
+ MUCCEVENT muce;
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_REMOVE_NICK;
+ muce.pszModule = manager->getModule();
+ char* lps2 = Utils::mucc_mir_t2a(text);
+ muce.pszNick = lps2;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ Utils::mucc_mir_free(lps2);
+ }
+ }
+ }
+ }
+ break;
+ case WM_MEASUREITEM:
+ if (wParam == IDC_LIST) {
+ MEASUREITEMSTRUCT *lpMis = (MEASUREITEMSTRUCT *) lParam;
+ lpMis->itemHeight = 16;//GetSystemMetrics(SM_CYSMICON);
+ return TRUE;
+ }
+ break;
+ case WM_DRAWITEM:
+ if (wParam == IDC_LIST) {
+ TCHAR text[256];
+ DRAWITEMSTRUCT *lpDis = (DRAWITEMSTRUCT *) lParam;
+ switch (lpDis->itemAction) {
+ default:
+ case ODA_SELECT:
+ case ODA_DRAWENTIRE:
+ if (lpDis->itemState & ODS_SELECTED) {
+ HBRUSH hBrush = CreateSolidBrush(RGB(0xC2, 0xC8, 0xDA));//0xDAC8C2);
+ FillRect(lpDis->hDC, &(lpDis->rcItem), hBrush);//(HBRUSH) (COLOR_HIGHLIGHT+1));
+ DeleteObject(hBrush);
+ SetTextColor(lpDis->hDC, 0);
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ }
+ else {
+ FillRect(lpDis->hDC, &(lpDis->rcItem), (HBRUSH) (COLOR_WINDOW+1));
+ SetTextColor(lpDis->hDC, RGB(0, 0, 0));//GetSysColor(COLOR_WINDOWTEXT));
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ }
+ ListView_GetItemText(GetDlgItem(hwndDlg, IDC_LIST), lpDis->itemID, 0, text, sizeof(text)/sizeof(TCHAR));
+ DrawText(lpDis->hDC, text, (int)_tcslen(text), &(lpDis->rcItem), DT_LEFT|DT_NOPREFIX|DT_SINGLELINE|DT_VCENTER);
+ break;
+ }
+ }
+ break;
+ }
+ return FALSE;
+}
+
+static INT_PTR CALLBACK ManagerDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ HWND hwnd, tc;
+ TCITEM tci;
+ char text[128];
+// HIMAGELIST hImageList;
+ ManagerWindow *manager;
+ MUCCEVENT muce;
+ int dlgWidth, dlgHeight, tabPos;
+ RECT rc2;
+
+ manager = (ManagerWindow *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ if (manager==NULL && msg!=WM_INITDIALOG) return FALSE;
+ switch (msg) {
+ case WM_INITDIALOG:
+ // lParam is the initial conference server (if any)
+ manager = (ManagerWindow *)lParam;
+ manager->setHWND(hwndDlg);
+ sprintf(text, "%s Chats", manager->getModuleName());
+ SetWindowTextA(hwndDlg, text);
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) manager);
+ SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM) muccIcon[MUCC_IDI_CHAT]);
+
+ TranslateDialogDefault(hwndDlg);
+// sortColumn = -1;
+ manager->setCurrentTab(0);
+ tc = GetDlgItem(hwndDlg, IDC_TABS);
+ tci.mask = TCIF_TEXT;
+ // Public rooms tab
+ tci.pszText = TranslateT("Chat rooms");
+ TabCtrl_InsertItem(tc, 0, &tci);
+ // Create room tab
+ tci.pszText = TranslateT("My rooms");
+ TabCtrl_InsertItem(tc, 1, &tci);
+ tci.pszText = TranslateT("My nicknames");
+ TabCtrl_InsertItem(tc, 2, &tci);
+ hwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_TAB_CHATROOMS), hwndDlg, ChatRoomsDlgProc, (LPARAM) manager);
+ SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
+ ShowWindow(hwnd, SW_SHOW);
+ hwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_TAB_MYROOMS), hwndDlg, MyRoomsDlgProc, (LPARAM) manager);
+ SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
+ hwnd = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_TAB_MYNICKNAMES), hwndDlg, MyNicksDlgProc, (LPARAM) manager);
+ SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
+ EnableWindow(GetDlgItem(manager->getChatRoomsTabHWND(), IDC_PREV), FALSE);
+ EnableWindow(GetDlgItem(manager->getChatRoomsTabHWND(), IDC_NEXT), FALSE);
+
+ GetWindowRect(manager->getMyRoomsTabHWND(), &rc2);
+ rc2.right-=rc2.left;
+ rc2.bottom-=rc2.top;
+ SetWindowPos(hwndDlg, NULL, 0, 0, rc2.right+300, 118+rc2.bottom, SWP_NOMOVE | SWP_NOZORDER);
+ TreeView_SetItemHeight(GetDlgItem(hwndDlg, IDC_GROUP), 16);
+// hImageList=ImageList_Create(100, 100, ILC_COLOR32, 0, 10);
+// ListView_SetImageList(GetDlgItem(hwndDlg, IDC_ROOM), hImageList, LVSIL_SMALL);
+ SetEvent(manager->getEvent());
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_QUERY_GROUPS;
+ muce.pszModule = manager->getModule();
+ muce.pszID = NULL;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ return TRUE;
+ case WM_SIZING:
+ RECT *rc, rc2;
+ rc = (RECT *)lParam;
+ GetWindowRect(manager->getMyRoomsTabHWND(), &rc2);
+ rc2.right-=rc2.left;
+ rc2.bottom-=rc2.top;
+ if (rc->right-rc->left<(rc2.right+80)) {
+ if (wParam == WMSZ_RIGHT || wParam == WMSZ_BOTTOMRIGHT || wParam == WMSZ_TOPRIGHT) {
+ rc->right=rc->left+rc2.right+80;
+ } else {
+ rc->left=rc->right-rc2.right-80;
+ }
+ }
+ if (rc->bottom-rc->top<118+rc2.bottom || rc->bottom-rc->top>118+rc2.bottom) {
+ if (wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT) {
+ rc->bottom=rc->top+118+rc2.bottom;
+ } else {
+ rc->top=rc->bottom-118-rc2.bottom;
+ }
+ }
+ return TRUE;
+ case WM_SIZE:
+ if (wParam==SIZE_RESTORED || wParam==SIZE_MAXIMIZED) {
+ HDWP hdwp;
+ dlgWidth = LOWORD(lParam);
+ dlgHeight = HIWORD(lParam);
+ GetWindowRect(manager->getMyRoomsTabHWND(), &rc2);
+ rc2.right-=rc2.left;
+ rc2.bottom-=rc2.top;
+ tabPos = dlgWidth - rc2.right - 15;
+ hdwp = BeginDeferWindowPos(6);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_TABS), 0, tabPos, 10, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
+ hdwp = DeferWindowPos(hdwp, manager->getChatRoomsTabHWND(), 0, tabPos+3, 45, 371, 292, SWP_NOZORDER | SWP_NOSIZE);
+ hdwp = DeferWindowPos(hdwp, manager->getMyRoomsTabHWND() , 0, tabPos+3, 45, 371, 292, SWP_NOZORDER | SWP_NOSIZE);
+ hdwp = DeferWindowPos(hdwp, manager->getMyNicksTabHWND() , 0, tabPos+3, 45, 371, 292, SWP_NOZORDER | SWP_NOSIZE);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDC_GROUP), 0, 0, 0, tabPos-16, dlgHeight-40, SWP_NOZORDER | SWP_NOMOVE);
+ hdwp = DeferWindowPos(hdwp, GetDlgItem(hwndDlg, IDCLOSE), 0, dlgWidth-88, dlgHeight-34, 0, 0 , SWP_NOZORDER | SWP_NOSIZE);
+ EndDeferWindowPos(hdwp);
+ }
+ break;
+ case WM_NOTIFY:
+ switch (wParam) {
+ case IDC_GROUP:
+ switch (((LPNMHDR)lParam)->code) {
+ case TVN_ITEMEXPANDING:
+ {
+ LPNMTREEVIEW pnmtv = (LPNMTREEVIEW) lParam;
+ if (pnmtv->action==TVE_EXPAND) {
+ TVITEM item = (TVITEM) pnmtv->itemNew;
+ ChatGroup *group = (ChatGroup *) item.lParam;// manager->findGroup(item.hItem);
+ if (group!=NULL) {
+ if (group->getChild()==NULL) {
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_QUERY_GROUPS;
+ muce.pszModule = manager->getModule();
+ muce.pszID = group->getId();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ }
+ }
+ }
+ }
+ break;
+ case TVN_SELCHANGED:
+ {
+ LPNMTREEVIEW pnmtv = (LPNMTREEVIEW) lParam;
+ TVITEM item = (TVITEM) pnmtv->itemNew;
+ ChatGroup *group = (ChatGroup *) item.lParam;// manager->findGroup(item.hItem);
+ if (group!=NULL) {
+ EnableWindow(GetDlgItem(manager->getChatRoomsTabHWND(), IDC_PREV), FALSE);
+ EnableWindow(GetDlgItem(manager->getChatRoomsTabHWND(), IDC_NEXT), FALSE);
+ ListView_DeleteAllItems(GetDlgItem(manager->getChatRoomsTabHWND(), IDC_ROOM));
+ manager->setCurrentGroup(group);
+ manager->setCurrentRoomsPage(0);
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_QUERY_ROOMS;
+ muce.pszModule = manager->getModule();
+ muce.pszID = (char *)group->getId();
+ muce.dwData = 0;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ }
+ }
+ break;
+ case NM_CUSTOMDRAW:
+ {
+ if (((LPNMHDR)lParam)->idFrom == IDC_GROUP) {
+ LPNMTVCUSTOMDRAW pCustomDraw = (LPNMTVCUSTOMDRAW)lParam;
+ switch (pCustomDraw->nmcd.dwDrawStage) {
+ case CDDS_PREPAINT:
+ SetWindowLongPtr(hwndDlg,DWLP_MSGRESULT,CDRF_NOTIFYITEMDRAW);
+ return TRUE;
+ case CDDS_ITEMPREPAINT:
+ {
+ if (pCustomDraw->nmcd.uItemState & CDIS_FOCUS) { // selected (CDIS_FOCUS | CDIS_SELECTED
+ pCustomDraw->clrText = 0;
+ pCustomDraw->clrTextBk = 0xDAC8C2;
+ }
+ else {
+ pCustomDraw->clrText = 0;
+ }
+ // HBRUSH hBr;
+ // hBr = CreateSolidBrush(pCustomDraw->clrTextBk);//g_LogOptions.crUserListBGColor ) ;
+ // FillRect(pCustomDraw->nmcd.hdc, &rc, hBr);
+ // DeleteObject(hBr);
+ SetWindowLongPtr(hwndDlg,DWLP_MSGRESULT, CDRF_NEWFONT);
+ return TRUE;
+ }
+ }
+ }
+ }
+ break;
+ }
+ break;
+ case IDC_TABS:
+ switch (((LPNMHDR) lParam)->code) {
+ case TCN_SELCHANGE:
+ switch (manager->getCurrentTab()) {
+ case 0:
+ ShowWindow(manager->getChatRoomsTabHWND(), SW_HIDE);
+ break;
+ case 1:
+ ShowWindow(manager->getMyRoomsTabHWND(), SW_HIDE);
+ break;
+ case 2:
+ ShowWindow(manager->getMyNicksTabHWND(), SW_HIDE);
+ break;
+ }
+ manager->setCurrentTab(TabCtrl_GetCurSel(GetDlgItem(hwndDlg, IDC_TABS)));
+ switch (manager->getCurrentTab()) {
+ case 0:
+ ShowWindow(manager->getChatRoomsTabHWND(), SW_SHOW);
+ break;
+ case 1:
+ ShowWindow(manager->getMyRoomsTabHWND(), SW_SHOW);
+ if (!manager->isUserRoomListReceived()) {
+ SendMessage(hwndDlg, WM_MUCC_REFRESH_USER_ROOMS, 0, 0);
+ }
+ break;
+ case 2:
+ ShowWindow(manager->getMyNicksTabHWND(), SW_SHOW);
+ if (!manager->isUserNickListReceived()) {
+ SendMessage(hwndDlg, WM_MUCC_REFRESH_USER_NICKS, 0, 0);
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ }
+ break;
+ case WM_MUCC_REFRESH_USER_ROOMS:
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_QUERY_USER_ROOMS;
+ muce.pszModule = manager->getModule();
+ muce.pszID = NULL;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ break;
+ case WM_MUCC_REFRESH_USER_NICKS:
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_QUERY_USER_NICKS;
+ muce.pszModule = manager->getModule();
+ muce.pszID = NULL;
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ break;
+ case WM_MUCC_REFRESH_ROOMS:
+ {
+ ChatGroup *group = manager->getCurrentGroup();
+ if (manager->getCurrentGroup()!=NULL) {
+ EnableWindow(GetDlgItem(manager->getChatRoomsTabHWND(), IDC_PREV), FALSE);
+ EnableWindow(GetDlgItem(manager->getChatRoomsTabHWND(), IDC_NEXT), FALSE);
+ ListView_DeleteAllItems(GetDlgItem(manager->getChatRoomsTabHWND(), IDC_ROOM));
+ /*
+ * TODO: delete rooms here !!!
+ */
+ muce.cbSize = sizeof(MUCCEVENT);
+ muce.iType = MUCC_EVENT_QUERY_ROOMS;
+ muce.pszModule = manager->getModule();
+ muce.pszID = (char *)group->getId();
+ muce.dwData = manager->getCurrentRoomsPage();
+ NotifyEventHooks(hHookEvent, 0,(WPARAM)&muce);
+ }
+ }
+ break;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDCLOSE:
+ ShowWindow(hwndDlg, SW_HIDE);
+ break;
+ }
+ break;
+ case WM_CLOSE:
+ ShowWindow(hwndDlg, SW_HIDE);
+ break;
+
+ }
+ return FALSE;
+}
+
+ManagerWindow* ManagerWindow::getWindow(const char *module) {
+ ManagerWindow *ptr;
+ EnterCriticalSection(&mutex);
+ for (ptr=list;ptr!=NULL;ptr=ptr->getNext()) {
+ if (strcmp(ptr->getModule(), module)==0) {
+ break;
+ }
+ }
+ LeaveCriticalSection(&mutex);
+ if (ptr==NULL) {
+ ptr = new ManagerWindow(module);
+ }
+ return ptr;
+}
+
diff --git a/protocols/Tlen/tlen_czaty/ManagerWindow.h b/protocols/Tlen/tlen_czaty/ManagerWindow.h
new file mode 100644
index 0000000000..f57d1c1057
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/ManagerWindow.h
@@ -0,0 +1,93 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef MANAGERWINDOW_INCLUDED
+#define MANAGERWINDOW_INCLUDED
+#include "mucc.h"
+#include "ChatGroup.h"
+#include "ChatRoom.h"
+
+class ManagerWindow{
+
+private:
+ static CRITICAL_SECTION mutex;
+ static bool released;
+ static ManagerWindow * list;
+ HWND hWnd;
+ HWND hChatRoomsTabWnd;
+ HWND hMyRoomsTabWnd;
+ HWND hMyNicksTabWnd;
+ HANDLE hEvent;
+ ManagerWindow * prev;
+ ManagerWindow * next;
+ ChatGroup * groups;
+ ChatRoom * rooms;
+ ChatRoom * myRooms;
+ char * module;
+ char * moduleName;
+ ChatGroup * currentGroup;
+ int isStarted;
+ int userNickList, userRoomList;
+ int currentTab;
+ int currentRoomsPage;
+ int lastRoomsPage;
+public:
+ ManagerWindow (const char *module);
+ ~ManagerWindow ();
+ int start();
+ ChatGroup * findGroup(const char *id);
+ void queryResultGroups(MUCCQUERYRESULT *queryResult);
+ void queryResultRooms(MUCCQUERYRESULT *queryResult);
+ void queryResultUserRooms(MUCCQUERYRESULT *queryResult);
+ void queryResultUserNick(MUCCQUERYRESULT *queryResult);
+ ManagerWindow * getNext();
+ void setNext(ManagerWindow *);
+ ManagerWindow * getPrev();
+ void setPrev(ManagerWindow *);
+ void setHWND(HWND);
+ HWND getHWND();
+ HANDLE getEvent();
+ void setChatRoomsTabHWND(HWND);
+ HWND getChatRoomsTabHWND();
+ void setMyNicksTabHWND(HWND);
+ HWND getMyNicksTabHWND();
+ void setMyRoomsTabHWND(HWND);
+ HWND getMyRoomsTabHWND();
+ void setModuleName(const char *moduleName);
+ void setCurrentTab(int);
+ int getCurrentTab();
+ const char * getModule();
+ const char * getModuleName();
+ void setCurrentGroup(ChatGroup *);
+ ChatGroup * getCurrentGroup();
+ void setCurrentRoomsPage(int);
+ int getCurrentRoomsPage();
+ void setLastRoomsPage(int);
+ int isLastRoomsPage();
+ int isUserRoomListReceived();
+ int isUserNickListReceived();
+
+ static ManagerWindow* getWindow(const char *module);
+ static void release();
+ static void init();
+
+};
+#endif
+
diff --git a/protocols/Tlen/tlen_czaty/Options.cpp b/protocols/Tlen/tlen_czaty/Options.cpp
new file mode 100644
index 0000000000..8e0f093ddd
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/Options.cpp
@@ -0,0 +1,789 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "mucc.h"
+#include "Options.h"
+#include "ChatWindow.h"
+#include "Utils.h"
+#include "resource.h"
+#include <commctrl.h>
+#include "m_ieview.h"
+
+static INT_PTR CALLBACK MUCCOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+//static INT_PTR CALLBACK MUCCLogOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+//static INT_PTR CALLBACK MUCCPopupsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+
+COLORREF Options::colorListBg, Options::colorInputBg, Options::colorLogBg, Options::chatWindowFontColor;
+HBRUSH Options::brushListBg=NULL, Options::brushInputBg=NULL, Options::brushLogBg=NULL;
+int Options::logLimit, Options::chatWindowOptions, Options::chatContainerOptions;
+int Options::chatWindowFont, Options::chatWindowFontSize, Options::chatWindowFontStyle;
+
+void Options::setListBgColor(COLORREF c) {
+ colorListBg = c;
+ if (brushListBg != NULL) {
+ DeleteObject(brushListBg);
+ }
+ brushListBg = CreateSolidBrush(colorListBg);
+}
+
+void Options::setInputBgColor(COLORREF c) {
+ colorInputBg = c;
+ if (brushInputBg!= NULL) {
+ DeleteObject(brushInputBg);
+ }
+ brushInputBg = CreateSolidBrush(colorInputBg);
+}
+
+void Options::setLogBgColor(COLORREF c) {
+ colorLogBg = c;
+ if (brushLogBg!= NULL) {
+ DeleteObject(brushLogBg);
+ }
+ brushLogBg = CreateSolidBrush(colorLogBg);
+}
+
+COLORREF Options::getListBgColor() {
+ return colorListBg;
+}
+
+COLORREF Options::getInputBgColor() {
+ return colorInputBg;
+}
+
+COLORREF Options::getLogBgColor() {
+ return colorLogBg;
+}
+
+HBRUSH Options::getListBgBrush() {
+ return brushListBg;
+}
+
+HBRUSH Options::getInputBgBrush() {
+ return brushInputBg;
+}
+
+HBRUSH Options::getLogBgBrush() {
+ return brushLogBg;
+}
+
+void Options::setLogLimit(int l) {
+ logLimit = l;
+}
+
+int Options::getLogLimit() {
+ return logLimit;
+}
+
+void Options::setChatWindowFont(int o) {
+ chatWindowFont = o;
+}
+
+int Options::getChatWindowFont() {
+ return chatWindowFont;
+}
+
+void Options::setChatWindowFontSize(int o) {
+ chatWindowFontSize = o;
+}
+
+int Options::getChatWindowFontSize() {
+ return chatWindowFontSize;
+}
+
+void Options::setChatWindowFontStyle(int o) {
+ chatWindowFontStyle = o;
+}
+
+int Options::getChatWindowFontStyle() {
+ return chatWindowFontStyle;
+}
+
+void Options::setChatWindowFontColor(COLORREF o) {
+ chatWindowFontColor = o;
+}
+
+COLORREF Options::getChatWindowFontColor() {
+ return chatWindowFontColor;
+}
+
+void Options::setChatWindowOptions(int o) {
+ chatWindowOptions = o;
+}
+
+int Options::getChatWindowOptions() {
+ return chatWindowOptions;
+}
+
+void Options::setChatContainerOptions(int o) {
+ chatContainerOptions = o;
+}
+
+int Options::getChatContainerOptions() {
+ return chatContainerOptions;
+}
+
+void Options::setExpandFlags(int o) {
+ DBWriteContactSettingDword(NULL, muccModuleName, "ExpandFlags", o);
+}
+
+int Options::getExpandFlags() {
+ return DBGetContactSettingDword(NULL, muccModuleName, "ExpandFlags", 0xFFFFFFFF);
+}
+
+void Options::loadSettings() {
+ FontList::loadSettings();
+ setLogBgColor((COLORREF)DBGetContactSettingDword(NULL, muccModuleName, "BackgroundLog", 0xFFFFFF));
+ setListBgColor((COLORREF)DBGetContactSettingDword(NULL, muccModuleName, "BackgroundList", 0xFFFFFF));
+ setInputBgColor((COLORREF)DBGetContactSettingDword(NULL, muccModuleName, "BackgroundTyping", 0xFFFFFF));
+ setLogLimit(DBGetContactSettingDword(NULL, muccModuleName, "LogSizeLimit", 100));
+ setChatContainerOptions(DBGetContactSettingDword(NULL, muccModuleName, "ChatContainerOptions", ChatContainer::getDefaultOptions()));
+ setChatWindowOptions(DBGetContactSettingDword(NULL, muccModuleName, "ChatWindowOptions", ChatWindow::getDefaultOptions()));
+ setChatWindowFont(DBGetContactSettingDword(NULL, muccModuleName, "ChatWindowFont", 0));
+ setChatWindowFontSize(DBGetContactSettingDword(NULL, muccModuleName, "ChatWindowFontSize", 5));
+ setChatWindowFontStyle(DBGetContactSettingDword(NULL, muccModuleName, "ChatWindowFontStyle", 0));
+ setChatWindowFontColor(DBGetContactSettingDword(NULL, muccModuleName, "ChatWindowFontColor", 0));
+}
+
+void Options::saveSettings() {
+ FontList::saveSettings();
+ DBWriteContactSettingDword(NULL, muccModuleName, "BackgroundLog", colorLogBg);
+ DBWriteContactSettingDword(NULL, muccModuleName, "BackgroundList", colorListBg);
+ DBWriteContactSettingDword(NULL, muccModuleName, "BackgroundTyping", colorInputBg);
+ DBWriteContactSettingDword(NULL, muccModuleName, "LogSizeLimit", logLimit);
+ DBWriteContactSettingDword(NULL, muccModuleName, "ChatContainerOptions", chatContainerOptions);
+ DBWriteContactSettingDword(NULL, muccModuleName, "ChatWindowOptions", chatWindowOptions);
+ DBWriteContactSettingDword(NULL, muccModuleName, "ChatWindowFont", chatWindowFont);
+ DBWriteContactSettingDword(NULL, muccModuleName, "ChatWindowFontSize", chatWindowFontSize);
+ DBWriteContactSettingDword(NULL, muccModuleName, "ChatWindowFontStyle", chatWindowFontStyle);
+ DBWriteContactSettingDword(NULL, muccModuleName, "ChatWindowFontColor", chatWindowFontColor);
+}
+
+void Options::init()
+{
+ FontList::init();
+ loadSettings();
+}
+
+int MUCCOptInit(WPARAM wParam, LPARAM lParam)
+{
+ OPTIONSDIALOGPAGE odp;
+
+ ZeroMemory(&odp, sizeof(odp));
+ odp.cbSize = sizeof(odp);
+ odp.position = 0;
+ odp.hInstance = hInst;
+ odp.pszGroup = Translate("Network");
+ odp.pszTemplate = MAKEINTRESOURCEA(IDD_OPTIONS);
+// odp.pszTitle = muccModuleName;
+ odp.pszTitle = "Tlen czaty";
+ odp.flags = ODPF_BOLDGROUPS;
+ odp.pfnDlgProc = MUCCOptDlgProc;
+ odp.nIDBottomSimpleControl = 0;
+ CallService(MS_OPT_ADDPAGE, wParam, (LPARAM) &odp);
+
+ /*
+ odp.pszTemplate = MAKEINTRESOURCE(IDD_OPTIONS_LOG);
+ _snprintf(str, sizeof(str), "%s %s", muccModuleName, Translate("Log"));
+ str[sizeof(str)-1] = '\0';
+ odp.pszTitle = str;
+ odp.pfnDlgProc = MUCCLLogOptDlgProc;
+ odp.flags = ODPF_BOLDGROUPS|ODPF_EXPERTONLY;
+ odp.nIDBottomSimpleControl = 0;
+ CallService(MS_OPT_ADDPAGE, wParam, (LPARAM) &odp);
+ if (ServiceExists(MS_POPUP_ADDPOPUP)) {
+ ZeroMemory(&odp,sizeof(odp));
+ odp.cbSize = sizeof(odp);
+ odp.position = 100000000;
+ odp.hInstance = hInst;
+ odp.pszGroup = Translate("PopUps");
+ odp.pszTemplate = MAKEINTRESOURCE(IDD_OPTIONS_POPUPS);
+ odp.pszTitle = jabberModuleName;
+ odp.flags=ODPF_BOLDGROUPS;
+ odp.pfnDlgProc = TlenPopupsDlgProc;
+ odp.nIDBottomSimpleControl = 0;
+ CallService(MS_OPT_ADDPAGE,wParam,(LPARAM)&odp);
+ }
+
+*/
+ return 0;
+}
+
+
+static int getOptions(HWND hTreeControl, HTREEITEM hItem, int flags) {
+ TVITEM tvi = {0};
+ tvi.mask = TVIF_HANDLE | TVIF_STATE | TVIF_PARAM;
+ tvi.stateMask = TVIS_STATEIMAGEMASK;
+ tvi.hItem = hItem;
+ TreeView_GetItem(hTreeControl, &tvi);
+ if ((tvi.state>>12) == 2) {
+ flags |= tvi.lParam;
+ } else {
+ flags &= ~tvi.lParam;
+ }
+ tvi.hItem = TreeView_GetChild(hTreeControl, hItem);
+ if (tvi.hItem != NULL) {
+ flags = getOptions(hTreeControl, tvi.hItem, flags);
+ }
+ tvi.hItem=TreeView_GetNextSibling(hTreeControl, hItem);
+ if (tvi.hItem != NULL) {
+ flags = getOptions(hTreeControl, tvi.hItem, flags);
+ }
+ return flags;
+
+}
+
+static int getExpandFlags(HWND hTreeControl) {
+ TVITEM tvi = {0};
+ int flags =0, mask = 1;
+ tvi.mask = TVIF_HANDLE | TVIF_STATE;
+ tvi.stateMask = TVIS_EXPANDED;
+ tvi.hItem = TreeView_GetRoot(hTreeControl);
+ while (tvi.hItem != NULL) {
+ TreeView_GetItem(hTreeControl, &tvi);
+ if (tvi.state & TVIS_EXPANDED) {
+ flags |= mask;
+ }
+ mask <<= 1;
+ tvi.hItem=TreeView_GetNextSibling(hTreeControl, tvi.hItem);
+ }
+ return flags;
+}
+
+
+static int addOption(HWND hTreeControl, HTREEITEM hParent, const char *text, int flag) {
+ TVINSERTSTRUCT tvis;
+ tvis.hInsertAfter = TVI_LAST;
+ tvis.hParent = hParent;
+ tvis.item.mask = TVIF_TEXT | TVIF_STATE | TVIF_PARAM;
+ char* textA = Translate(text);
+ LPTSTR textT = Utils::mucc_mir_a2t(textA);
+ tvis.item.pszText = textT;
+ tvis.item.lParam = flag;
+ tvis.item.stateMask = TVIS_STATEIMAGEMASK;
+ tvis.item.state = Options::getChatWindowOptions() & flag ? INDEXTOSTATEIMAGEMASK(2) : INDEXTOSTATEIMAGEMASK(1);
+ TreeView_InsertItem(hTreeControl, &tvis);
+ Utils::mucc_mir_free(textT);
+ return (Options::getChatWindowOptions() & flag) != 0;
+
+}
+
+static INT_PTR CALLBACK MUCCOptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ int i;
+ char *pszText;
+ switch (msg) {
+ case WM_INITDIALOG:
+ {
+ TVINSERTSTRUCT tvis;
+ TVITEM tvi;
+ HWND hTreeControl;
+ HTREEITEM hItem;
+ int bCheckParent, expandFlags;
+
+ TranslateDialogDefault(hwndDlg);
+ Options::loadSettings();
+ for (i=0;i<Options::getFontNum();i++) {
+ SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_ADDSTRING, 0, i + 1);
+ }
+
+ SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_SETSEL, TRUE, 0);
+ SendDlgItemMessage(hwndDlg, IDC_COLORTXT, CPM_SETCOLOUR, 0, Options::getFontSettings(0)->getColor());
+ SendDlgItemMessage(hwndDlg, IDC_COLORBKG, CPM_SETCOLOUR, 0, Options::getLogBgColor());
+ SendDlgItemMessage(hwndDlg, IDC_COLORLIST, CPM_SETCOLOUR, 0, Options::getListBgColor());
+ SendDlgItemMessage(hwndDlg, IDC_COLORINPUT, CPM_SETCOLOUR, 0, Options::getInputBgColor());
+ SendDlgItemMessage(hwndDlg, IDC_LOGLIMITSPIN, UDM_SETRANGE, 0, MAKELONG(1000,20));
+ SendDlgItemMessage(hwndDlg, IDC_LOGLIMITSPIN, UDM_SETPOS, 0, MAKELONG(Options::getLogLimit(), 0));
+
+ SetWindowLong(GetDlgItem(hwndDlg,IDC_TREELIST),GWL_STYLE,GetWindowLong(GetDlgItem(hwndDlg,IDC_TREELIST),GWL_STYLE)|TVS_NOHSCROLL|TVS_CHECKBOXES);
+
+
+ hTreeControl = GetDlgItem(hwndDlg, IDC_TREELIST);
+ expandFlags = Options::getExpandFlags();
+ tvis.hInsertAfter = TVI_LAST;
+ tvis.item.mask = TVIF_TEXT | TVIF_PARAM;
+ tvis.hParent = NULL;
+ tvis.item.lParam = 0;
+
+ tvi.mask = TVIF_HANDLE | TVIF_STATE;
+ tvi.stateMask = TVIS_STATEIMAGEMASK;
+
+ tvis.item.pszText = TranslateT("Default Log Appearence");
+ hItem = TreeView_InsertItem(hTreeControl, &tvis);
+ bCheckParent = 1;
+ bCheckParent &= addOption(hTreeControl, hItem, "Show nicknames", ChatWindow::FLAG_SHOW_NICKNAMES);
+ bCheckParent &= addOption(hTreeControl, hItem, "Show message on a new line", ChatWindow::FLAG_MSGINNEWLINE);
+ tvi.state = (bCheckParent ? INDEXTOSTATEIMAGEMASK(2) : INDEXTOSTATEIMAGEMASK(1));
+ tvi.hItem = hItem;
+ TreeView_SetItem(hTreeControl, &tvi);
+ if (expandFlags & 1) {
+ TreeView_Expand(hTreeControl, hItem, TVE_EXPAND);
+ }
+
+ tvis.item.pszText = TranslateT("Default Timestamp Settings");
+ hItem = TreeView_InsertItem(hTreeControl, &tvis);
+ bCheckParent = 1;
+ bCheckParent &= addOption(hTreeControl, hItem, "Show date", ChatWindow::FLAG_SHOW_DATE);
+ bCheckParent &= addOption(hTreeControl, hItem, "Show timestamp", ChatWindow::FLAG_SHOW_TIMESTAMP);
+ bCheckParent &= addOption(hTreeControl, hItem, "Show seconds", ChatWindow::FLAG_SHOW_SECONDS);
+ bCheckParent &= addOption(hTreeControl, hItem, "Use long date format", ChatWindow::FLAG_LONG_DATE);
+ tvi.state = (bCheckParent ? INDEXTOSTATEIMAGEMASK(2) : INDEXTOSTATEIMAGEMASK(1));
+ tvi.hItem = hItem;
+ TreeView_SetItem(hTreeControl, &tvi);
+ if (expandFlags & 2) {
+ TreeView_Expand(hTreeControl, hItem, TVE_EXPAND);
+ }
+
+ tvis.item.pszText = TranslateT("Default Text Formatting Filter");
+ hItem = TreeView_InsertItem(hTreeControl, &tvis);
+ bCheckParent = 1;
+ bCheckParent &= addOption(hTreeControl, hItem, "Font name", ChatWindow::FLAG_FORMAT_FONT);
+ bCheckParent &= addOption(hTreeControl, hItem, "Font size", ChatWindow::FLAG_FORMAT_SIZE);
+ bCheckParent &= addOption(hTreeControl, hItem, "Font style", ChatWindow::FLAG_FORMAT_STYLE);
+ bCheckParent &= addOption(hTreeControl, hItem, "Font color", ChatWindow::FLAG_FORMAT_COLOR);
+ tvi.state = (bCheckParent ? INDEXTOSTATEIMAGEMASK(2) : INDEXTOSTATEIMAGEMASK(1));
+ tvi.hItem = hItem;
+ TreeView_SetItem(hTreeControl, &tvi);
+ if (expandFlags & 4) {
+ TreeView_Expand(hTreeControl, hItem, TVE_EXPAND);
+ }
+
+ tvis.item.pszText = TranslateT("Default Event Filter");
+ hItem = TreeView_InsertItem(hTreeControl, &tvis);
+ bCheckParent = 1;
+ bCheckParent &= addOption(hTreeControl, hItem, "Messages", ChatWindow::FLAG_LOG_MESSAGES);
+ bCheckParent &= addOption(hTreeControl, hItem, "User has joined", ChatWindow::FLAG_LOG_JOINED);
+ bCheckParent &= addOption(hTreeControl, hItem, "User has left", ChatWindow::FLAG_LOG_LEFT);
+ bCheckParent &= addOption(hTreeControl, hItem, "Topic changes", ChatWindow::FLAG_LOG_TOPIC);
+ tvi.state = (bCheckParent ? INDEXTOSTATEIMAGEMASK(2) : INDEXTOSTATEIMAGEMASK(1));
+ tvi.hItem = hItem;
+ TreeView_SetItem(hTreeControl, &tvi);
+ if (expandFlags & 8) {
+ TreeView_Expand(hTreeControl, hItem, TVE_EXPAND);
+ }
+
+ tvis.item.pszText = TranslateT("Default Window Flashing");
+ hItem = TreeView_InsertItem(hTreeControl, &tvis);
+ bCheckParent = 1;
+ bCheckParent &= addOption(hTreeControl, hItem, "Messages", ChatWindow::FLAG_FLASH_MESSAGES);
+ bCheckParent &= addOption(hTreeControl, hItem, "User has joined", ChatWindow::FLAG_FLASH_JOINED);
+ bCheckParent &= addOption(hTreeControl, hItem, "User has left", ChatWindow::FLAG_FLASH_LEFT);
+ bCheckParent &= addOption(hTreeControl, hItem, "Topic changes", ChatWindow::FLAG_FLASH_TOPIC);
+ tvi.state = (bCheckParent ? INDEXTOSTATEIMAGEMASK(2) : INDEXTOSTATEIMAGEMASK(1));
+ tvi.hItem = hItem;
+ TreeView_SetItem(hTreeControl, &tvi);
+ if (expandFlags & 16) {
+ TreeView_Expand(hTreeControl, hItem, TVE_EXPAND);
+ }
+
+ CheckDlgButton(hwndDlg, IDC_SENDONENTER, Options::getChatWindowOptions() & ChatWindow::FLAG_OPT_SENDONENTER);
+ CheckDlgButton(hwndDlg, IDC_ENABLEIEVIEW, Options::getChatWindowOptions() & ChatWindow::FLAG_OPT_ENABLEIEVIEW);
+ if (!ServiceExists(MS_IEVIEW_WINDOW)) {
+ EnableWindow(GetDlgItem(hwndDlg, IDC_ENABLEIEVIEW), FALSE);
+ }
+ CheckDlgButton(hwndDlg, IDC_USETABS, Options::getChatContainerOptions() & ChatContainer::FLAG_USE_TABS);
+
+ }
+ case WM_MEASUREITEM:
+ if (wParam == IDC_FONTLIST) {
+ MEASUREITEMSTRUCT *lpMis = (MEASUREITEMSTRUCT *) lParam;
+ HFONT hFont, hoFont;
+ HDC hDC;
+ SIZE fontSize;
+ int iItem = lpMis->itemData - 1;
+ Font *font = Options::getFontSettings(iItem);
+ if (font != NULL) {
+
+ LPTSTR lps1 = Utils::mucc_mir_a2t(font->getFace());
+ hFont = CreateFont(font->getSize(), 0, 0, 0,
+ font->getStyle() & Font::BOLD ? FW_BOLD : FW_NORMAL,
+ font->getStyle() & Font::ITALIC ? 1 : 0, 0, 0,
+ font->getCharSet(),
+ OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, lps1);
+ Utils::mucc_mir_free(lps1);
+
+ hDC = GetDC(GetDlgItem(hwndDlg, lpMis->CtlID));
+ hoFont = (HFONT) SelectObject(hDC, hFont);
+ pszText = Translate(Options::getFontSettings(iItem)->getName());
+ LPTSTR pszTextT1 = Utils::mucc_mir_a2t(pszText);
+ GetTextExtentPoint32(hDC, pszTextT1, lstrlen(pszTextT1), &fontSize);
+ Utils::mucc_mir_free(pszTextT1);
+ SelectObject(hDC, hoFont);
+ ReleaseDC(GetDlgItem(hwndDlg, lpMis->CtlID), hDC);
+ DeleteObject(hFont);
+ lpMis->itemWidth = fontSize.cx;
+ lpMis->itemHeight = fontSize.cy;
+ return TRUE;
+ }
+ break;
+ }
+ case WM_DRAWITEM:
+ if (wParam == IDC_FONTLIST) {
+ DRAWITEMSTRUCT *lpDis = (DRAWITEMSTRUCT *) lParam;
+ HFONT hFont;
+ HBRUSH hBrush;
+ int iItem = lpDis->itemData - 1;
+ Font *font = Options::getFontSettings(iItem);
+ if (font != NULL) {
+ COLORREF color = (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLORBKG, CPM_GETCOLOUR, 0, 0);
+ if (iItem == Options::FONT_USERLIST || iItem == Options::FONT_USERLISTGROUP) {
+ color = (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLORLIST, CPM_GETCOLOUR, 0, 0);
+ } else if (iItem == Options::FONT_TYPING) {
+ color = (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLORINPUT, CPM_GETCOLOUR, 0, 0);
+ }
+ hBrush = CreateSolidBrush(color);
+
+ LPTSTR lps2 = Utils::mucc_mir_a2t(font->getFace());
+ hFont = CreateFont(font->getSize(), 0, 0, 0,
+ font->getStyle() & Font::BOLD ? FW_BOLD : FW_NORMAL,
+ font->getStyle() & Font::ITALIC ? 1 : 0,
+ font->getStyle() & Font::UNDERLINE ? 1 : 0, 0,
+ font->getCharSet(),
+ OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE,
+ lps2);
+ Utils::mucc_mir_free(lps2);
+
+ hFont = (HFONT) SelectObject(lpDis->hDC, hFont);
+ SetBkMode(lpDis->hDC, TRANSPARENT);
+ FillRect(lpDis->hDC, &lpDis->rcItem, hBrush);
+ if (lpDis->itemState & ODS_SELECTED) {
+ FrameRect(lpDis->hDC, &lpDis->rcItem, GetSysColorBrush(COLOR_HIGHLIGHT));
+ }
+ SetTextColor(lpDis->hDC, font->getColor());
+ pszText = Translate(font->getName());
+ LPTSTR pszTextT2 = Utils::mucc_mir_a2t(pszText);
+ TextOut(lpDis->hDC, lpDis->rcItem.left, lpDis->rcItem.top, pszTextT2, lstrlen(pszTextT2));
+ Utils::mucc_mir_free(pszTextT2);
+ hFont = (HFONT) SelectObject(lpDis->hDC, hFont);
+ DeleteObject(hBrush);
+ DeleteObject(hFont);
+ }
+ return TRUE;
+ }
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_COLORTXT:
+ {
+ int totalCount = SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETCOUNT, 0, 0);
+ int *selItems= new int[totalCount];
+ int selCount = SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETSELITEMS, totalCount, (LPARAM) selItems);
+ COLORREF color = (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLORTXT, CPM_GETCOLOUR, 0, 0);
+ for (int i=0; i<selCount; i++) {
+ int iItem = SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETITEMDATA, selItems[i], 0) - 1;
+ Font *font = Options::getFontSettings(iItem);
+ if (font != NULL) {
+ font->setColor(color);
+ }
+ }
+ delete selItems;
+ InvalidateRect(GetDlgItem(hwndDlg, IDC_FONTLIST), NULL, FALSE);
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ break;
+ }
+ break;
+ case IDC_LOGLIMIT:
+ if (HIWORD(wParam) == EN_CHANGE && (HWND)lParam==GetFocus()) {
+ i = GetDlgItemInt(hwndDlg, IDC_LOGLIMIT, NULL, FALSE);
+ // if (i>1000) {
+ // i = 1000;
+ // SetDlgItemInt(hwndDlg, IDC_LOGLIMIT, i, FALSE);
+ // }
+ if (i!=Options::getLogLimit()) {
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ }
+ }
+ break;
+ case IDC_COLORBKG:
+ case IDC_COLORLIST:
+ case IDC_COLORINPUT:
+ InvalidateRect(GetDlgItem(hwndDlg, IDC_FONTLIST), NULL, FALSE);
+ case IDC_SENDONENTER:
+ case IDC_USETABS:
+ case IDC_ENABLEIEVIEW:
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ break;
+ case IDC_FONTLIST:
+ if (HIWORD(wParam) == LBN_SELCHANGE) {
+ if (SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETSELCOUNT, 0, 0) > 1) {
+ SendDlgItemMessage(hwndDlg, IDC_COLORTXT, CPM_SETCOLOUR, 0, GetSysColor(COLOR_3DFACE));
+ SendDlgItemMessage(hwndDlg, IDC_COLORTXT, CPM_SETDEFAULTCOLOUR, 0, GetSysColor(COLOR_WINDOWTEXT));
+ }
+ else {
+ int iItem = SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETITEMDATA,
+ SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETCURSEL, 0, 0), 0) - 1;
+ Font *font = Options::getFontSettings(iItem);
+ if (font != NULL) {
+ SendDlgItemMessage(hwndDlg, IDC_COLORTXT, CPM_SETCOLOUR, 0, font->getColor());
+ SendDlgItemMessage(hwndDlg, IDC_COLORTXT, CPM_SETDEFAULTCOLOUR, 0, font->getColor());
+ }
+ }
+ }
+ if (HIWORD(wParam) != LBN_DBLCLK) {
+ return TRUE;
+ }
+ case IDC_CHOOSEFONT:
+ {
+ CHOOSEFONT cf;
+ LOGFONT lf;
+ int iItem = SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETITEMDATA, SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETCURSEL, 0, 0), 0) - 1;
+ ZeroMemory(&cf, sizeof(cf));
+ ZeroMemory(&lf, sizeof(lf));
+ Font *font = Options::getFontSettings(iItem);
+ if (font != NULL) {
+ lf.lfHeight = font->getSize();
+ lf.lfWeight = font->getStyle() & Font::BOLD ? FW_BOLD : FW_NORMAL;
+ lf.lfItalic = font->getStyle() & Font::ITALIC ? 1 : 0;
+ lf.lfCharSet = DEFAULT_CHARSET;
+ lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
+ lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
+ lf.lfQuality = DEFAULT_QUALITY;
+ lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
+ LPTSTR lps3 = Utils::mucc_mir_a2t(font->getFace());
+ lstrcpy(lf.lfFaceName, lps3);
+ Utils::mucc_mir_free(lps3);
+ cf.lStructSize = sizeof(cf);
+ cf.hwndOwner = hwndDlg;
+ cf.lpLogFont = &lf;
+ cf.Flags = CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS;
+ if (ChooseFont(&cf)) {
+ int totalCount = SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETCOUNT, 0, 0);
+ int *selItems= new int[totalCount];
+ int selCount = SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETSELITEMS, totalCount, (LPARAM) selItems);
+ for (int i=0; i<selCount; i++) {
+ int iItem = SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_GETITEMDATA, selItems[i], 0) - 1;
+ Font *font2 = Options::getFontSettings(iItem);
+ if (font2 != NULL) {
+ font2->setStyle((lf.lfWeight >= FW_BOLD ? Font::BOLD : 0) | (lf.lfItalic ? Font::ITALIC : 0));
+ font2->setCharSet(lf.lfCharSet);
+ font2->setSize(lf.lfHeight);
+ char* lps4 = Utils::mucc_mir_t2a(lf.lfFaceName);
+ font2->setFace(lps4);
+ Utils::mucc_mir_free(lps4);
+ MEASUREITEMSTRUCT mis;
+ ZeroMemory(&mis, sizeof(mis));
+ mis.CtlID = IDC_FONTLIST;
+ mis.itemData = iItem + 1;
+ SendMessage(hwndDlg, WM_MEASUREITEM, (WPARAM)IDC_FONTLIST, (LPARAM) & mis);
+ SendDlgItemMessage(hwndDlg, IDC_FONTLIST, LB_SETITEMHEIGHT, selItems[i], mis.itemHeight);
+ }
+ }
+ delete selItems;
+ InvalidateRect(GetDlgItem(hwndDlg, IDC_FONTLIST), NULL, TRUE);
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ break;
+ }
+ }
+ return TRUE;
+ }
+ break;
+ }
+ break;
+ case WM_DESTROY:
+ Options::setExpandFlags(getExpandFlags(GetDlgItem(hwndDlg, IDC_TREELIST)));
+ break;
+ case WM_NOTIFY:
+ {
+ switch (((LPNMHDR) lParam)->code) {
+ case PSN_APPLY:
+ COLORREF color;
+ color = (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLORLIST, CPM_GETCOLOUR, 0, 0);
+ Options::setListBgColor(color);
+ color = (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLORINPUT, CPM_GETCOLOUR, 0, 0);
+ Options::setInputBgColor(color);
+ color = (COLORREF) SendDlgItemMessage(hwndDlg, IDC_COLORBKG, CPM_GETCOLOUR, 0, 0);
+ Options::setLogBgColor(color);
+ Options::setLogLimit(SendDlgItemMessage(hwndDlg, IDC_LOGLIMITSPIN, UDM_GETPOS, 0, 0));
+ Options::setChatWindowOptions(getOptions(GetDlgItem(hwndDlg, IDC_TREELIST), TreeView_GetRoot(GetDlgItem(hwndDlg, IDC_TREELIST)), 0));
+ Options::setChatWindowOptions(Options::getChatWindowOptions() | (IsDlgButtonChecked(hwndDlg, IDC_SENDONENTER) ? ChatWindow::FLAG_OPT_SENDONENTER : 0));
+ Options::setChatWindowOptions(Options::getChatWindowOptions() | (IsDlgButtonChecked(hwndDlg, IDC_ENABLEIEVIEW) ? ChatWindow::FLAG_OPT_ENABLEIEVIEW : 0));
+ Options::setChatContainerOptions(IsDlgButtonChecked(hwndDlg, IDC_USETABS) ? ChatContainer::FLAG_USE_TABS : 0);
+ Options::saveSettings();
+ ChatWindow::refreshSettings(1);
+ break;
+ case NM_CLICK:
+ /* Handle checking/unchecking options here - update children and parent appropriately */
+ if(((LPNMHDR)lParam)->idFrom == IDC_TREELIST) {
+ TVHITTESTINFO hti;
+ hti.pt.x = (short)LOWORD(GetMessagePos());
+ hti.pt.y = (short)HIWORD(GetMessagePos());
+ ScreenToClient(((LPNMHDR)lParam)->hwndFrom, &hti.pt);
+ if(TreeView_HitTest(((LPNMHDR)lParam)->hwndFrom, &hti)) {
+ if(hti.flags&TVHT_ONITEMSTATEICON) {
+ TVITEM tvi = {0};
+ tvi.mask = TVIF_HANDLE | TVIF_STATE;
+ tvi.stateMask = TVIS_STATEIMAGEMASK;
+ tvi.hItem = hti.hItem;
+ TreeView_GetItem(((LPNMHDR)lParam)->hwndFrom, &tvi);
+ tvi.state ^= INDEXTOSTATEIMAGEMASK(3);
+ tvi.hItem = TreeView_GetChild(((LPNMHDR)lParam)->hwndFrom, hti.hItem);
+ if (tvi.hItem!=NULL) {
+ while(tvi.hItem != NULL) {
+ TreeView_SetItem(((LPNMHDR)lParam)->hwndFrom, &tvi);
+ tvi.hItem=TreeView_GetNextSibling(((LPNMHDR)lParam)->hwndFrom, tvi.hItem);
+ }
+ } else {
+ HTREEITEM hParent = TreeView_GetParent(((LPNMHDR)lParam)->hwndFrom, hti.hItem);
+ if (hParent != NULL) {
+ if ((tvi.state>>12) == 2) {
+ tvi.hItem = TreeView_GetNextSibling(((LPNMHDR)lParam)->hwndFrom, hti.hItem);
+ while(tvi.hItem != NULL) {
+ TreeView_GetItem(((LPNMHDR)lParam)->hwndFrom, &tvi);
+ if ((tvi.state>>12) != 2) {
+ break;
+ }
+ tvi.hItem = TreeView_GetNextSibling(((LPNMHDR)lParam)->hwndFrom, tvi.hItem);
+ }
+ if ((tvi.state>>12) == 2) {
+ tvi.hItem = TreeView_GetPrevSibling(((LPNMHDR)lParam)->hwndFrom, hti.hItem);
+ while(tvi.hItem != NULL) {
+ TreeView_GetItem(((LPNMHDR)lParam)->hwndFrom, &tvi);
+ if ((tvi.state>>12) != 2) {
+ break;
+ }
+ tvi.hItem = TreeView_GetPrevSibling(((LPNMHDR)lParam)->hwndFrom, tvi.hItem);
+ }
+ }
+ }
+ tvi.hItem = hParent;
+ TreeView_SetItem(((LPNMHDR)lParam)->hwndFrom, &tvi);
+ }
+ }
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ }
+ }
+ }
+ break;
+ }
+ }
+ break;
+ }
+ return FALSE;
+}
+
+/*
+#define POPUP_DEFAULT_COLORBKG 0xDCBDA5
+#define POPUP_DEFAULT_COLORTXT 0x000000
+static void MailPopupPreview(DWORD colorBack, DWORD colorText, char *title, char *emailInfo, int delay)
+{
+ POPUPDATAEX ppd;
+ char * lpzContactName;
+ char * lpzText;
+
+ lpzContactName = title;
+ lpzText = emailInfo;
+ ZeroMemory(&ppd, sizeof(ppd));
+ ppd.lchContact = NULL;
+ ppd.lchIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_MAIL));
+ lstrcpy(ppd.lpzContactName, lpzContactName);
+ lstrcpy(ppd.lpzText, lpzText);
+ ppd.colorBack = colorBack;
+ ppd.colorText = colorText;
+ ppd.PluginWindowProc = NULL;
+ ppd.PluginData=NULL;
+ if ( ServiceExists( MS_POPUP_ADDPOPUPEX )) {
+ ppd.iSeconds = delay;
+ CallService(MS_POPUP_ADDPOPUPEX, (WPARAM)&ppd, 0);
+
+ }
+ else if ( ServiceExists( MS_POPUP_ADDPOPUP )) {
+ CallService(MS_POPUP_ADDPOPUP, (WPARAM)&ppd, 0);
+ }
+}
+*/
+//static INT_PTR CALLBACK MUCCPopupsDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+//{
+ /*
+ switch (msg) {
+ case WM_INITDIALOG:
+ {
+ BYTE delayMode;
+ CheckDlgButton(hwndDlg, IDC_ENABLEPOPUP, DBGetContactSettingByte(NULL, jabberProtoName, "MailPopupEnabled", TRUE));
+ SendDlgItemMessage(hwndDlg, IDC_COLORBKG, CPM_SETCOLOUR, 0, DBGetContactSettingDword(NULL, jabberProtoName, "MailPopupBack", POPUP_DEFAULT_COLORBKG));
+ SendDlgItemMessage(hwndDlg, IDC_COLORTXT, CPM_SETCOLOUR, 0, DBGetContactSettingDword(NULL, jabberProtoName, "MailPopupText", POPUP_DEFAULT_COLORTXT));
+ SetDlgItemInt(hwndDlg, IDC_DELAY, DBGetContactSettingDword(NULL, jabberProtoName, "MailPopupDelay", 4), FALSE);
+ delayMode = DBGetContactSettingByte(NULL, jabberProtoName, "MailPopupDelayMode", 0);
+ if (delayMode==1) {
+ CheckDlgButton(hwndDlg, IDC_DELAY_CUSTOM, TRUE);
+ } else if (delayMode==2) {
+ CheckDlgButton(hwndDlg, IDC_DELAY_PERMANENT, TRUE);
+ } else {
+ CheckDlgButton(hwndDlg, IDC_DELAY_POPUP, TRUE);
+ }
+ return TRUE;
+ }
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_COLORTXT:
+ case IDC_COLORBKG:
+ case IDC_ENABLEPOPUP:
+ case IDC_DELAY:
+ case IDC_DELAY_POPUP:
+ case IDC_DELAY_CUSTOM:
+ case IDC_DELAY_PERMANENT:
+ SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0);
+ break;
+ case IDC_PREVIEW:
+ {
+ int delay;
+ if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_POPUP)) {
+ delay=0;
+ } else if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_PERMANENT)) {
+ delay=-1;
+ } else {
+ delay=GetDlgItemInt(hwndDlg, IDC_DELAY, NULL, FALSE);
+ }
+ MailPopupPreview((DWORD) SendDlgItemMessage(hwndDlg,IDC_COLORBKG,CPM_GETCOLOUR,0,0),
+ (DWORD) SendDlgItemMessage(hwndDlg,IDC_COLORTXT,CPM_GETCOLOUR,0,0),
+ "New mail",
+ "From: test@test.test\nSubject: test",
+ delay);
+ }
+
+ }
+ break;
+
+
+ case WM_NOTIFY:
+ switch (((LPNMHDR) lParam)->code) {
+ case PSN_APPLY:
+ {
+ BYTE delayMode;
+ DBWriteContactSettingByte(NULL, jabberProtoName, "MailPopupEnabled", (BYTE) IsDlgButtonChecked(hwndDlg, IDC_ENABLEPOPUP));
+ DBWriteContactSettingDword(NULL, jabberProtoName, "MailPopupBack", (DWORD) SendDlgItemMessage(hwndDlg,IDC_COLORBKG,CPM_GETCOLOUR,0,0));
+ DBWriteContactSettingDword(NULL, jabberProtoName, "MailPopupText", (DWORD) SendDlgItemMessage(hwndDlg,IDC_COLORTXT,CPM_GETCOLOUR,0,0));
+ DBWriteContactSettingDword(NULL, jabberProtoName, "MailPopupDelay", (DWORD) GetDlgItemInt(hwndDlg,IDC_DELAY, NULL, FALSE));
+ delayMode=0;
+ if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_CUSTOM)) {
+ delayMode=1;
+ } else if (IsDlgButtonChecked(hwndDlg, IDC_DELAY_PERMANENT)) {
+ delayMode=2;
+
+ }
+ DBWriteContactSettingByte(NULL, jabberProtoName, "MailPopupDelayMode", delayMode);
+ return TRUE;
+ }
+ }
+ break;
+
+ }*/
+// return FALSE;
+//}
+
diff --git a/protocols/Tlen/tlen_czaty/Options.h b/protocols/Tlen/tlen_czaty/Options.h
new file mode 100644
index 0000000000..90c57099d0
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/Options.h
@@ -0,0 +1,75 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef OPTIONS_INCLUDED
+#define OPTIONS_INCLUDED
+#include "FontList.h"
+#include "mucc.h"
+
+extern int MUCCOptInit(WPARAM wParam, LPARAM lParam);
+
+class Options:public FontList {
+private:
+ static COLORREF colorInputBg;
+ static COLORREF colorLogBg;
+ static COLORREF colorListBg;
+ static HBRUSH brushInputBg;
+ static HBRUSH brushLogBg;
+ static HBRUSH brushListBg;
+ static int logLimit;
+ static int chatContainerOptions;
+ static int chatWindowOptions;
+ static COLORREF chatWindowFontColor;
+ static int chatWindowFont;
+ static int chatWindowFontSize;
+ static int chatWindowFontStyle;
+public:
+ static void setListBgColor(COLORREF c);
+ static void setLogBgColor(COLORREF c);
+ static void setInputBgColor(COLORREF c);
+ static COLORREF getListBgColor();
+ static COLORREF getLogBgColor();
+ static COLORREF getInputBgColor();
+ static HBRUSH getListBgBrush();
+ static HBRUSH getInputBgBrush();
+ static HBRUSH getLogBgBrush();
+ static void setLogLimit(int l);
+ static int getLogLimit();
+ static void setChatContainerOptions(int o);
+ static int getChatContainerOptions();
+ static void setChatWindowOptions(int o);
+ static int getChatWindowOptions();
+ static void setChatWindowFontColor(COLORREF o);
+ static COLORREF getChatWindowFontColor();
+ static void setChatWindowFont(int o);
+ static int getChatWindowFont();
+ static void setChatWindowFontSize(int o);
+ static int getChatWindowFontSize();
+ static void setChatWindowFontStyle(int o);
+ static int getChatWindowFontStyle();
+ static void setExpandFlags(int l);
+ static int getExpandFlags();
+ static void init();
+ static void loadSettings();
+ static void saveSettings();
+
+};
+
+#endif
diff --git a/protocols/Tlen/tlen_czaty/Utils.cpp b/protocols/Tlen/tlen_czaty/Utils.cpp
new file mode 100644
index 0000000000..53bddf4488
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/Utils.cpp
@@ -0,0 +1,138 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include "Utils.h"
+
+struct FORK_ARG {
+ HANDLE hEvent;
+ void (__cdecl *threadcode)(void*);
+ void *arg;
+};
+
+static void __cdecl forkthread_r(struct FORK_ARG *fa)
+{
+ void (*callercode)(void*) = fa->threadcode;
+ void *arg = fa->arg;
+ CallService(MS_SYSTEM_THREAD_PUSH, 0, 0);
+ SetEvent(fa->hEvent);
+ callercode(arg);
+ CallService(MS_SYSTEM_THREAD_POP, 0, 0);
+ return;
+}
+
+unsigned long Utils::forkThread(void (__cdecl *threadcode)(void*), unsigned long stacksize, void *arg) {
+
+ unsigned long rc;
+ struct FORK_ARG fa;
+
+ fa.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ fa.threadcode = threadcode;
+ fa.arg = arg;
+ rc = _beginthread((void (__cdecl *)(void*))forkthread_r, stacksize, &fa);
+ if ((unsigned long) -1L != rc) {
+ WaitForSingleObject(fa.hEvent, INFINITE);
+ }
+ CloseHandle(fa.hEvent);
+ return rc;
+}
+
+void Utils::copyString(char **a, const char *b) {
+ char *oldA;
+ char *newA;
+ oldA = *a;
+ if (b!=NULL) {
+ newA = new char[strlen(b)+1];
+ strcpy(newA, b);
+ } else {
+ newA = NULL;
+ }
+ *a = newA;
+ if (oldA!=NULL) {
+ delete oldA;
+ }
+
+}
+
+
+
+MM_INTERFACE Utils::mmi;
+
+void Utils::mucc_mir_free(void* ptr)
+{
+ mir_free(ptr);
+}
+
+char* Utils::mucc_mir_t2a(LPCTSTR src)
+{
+ return mir_t2a(src);
+}
+
+LPTSTR Utils::mucc_mir_a2t(const char* src)
+{
+ return mir_a2t(src);
+}
+
+
+
+void Utils::log(const char *fmt, ...)
+{
+#ifdef ENABLE_LOGGING
+ char *str;
+ va_list vararg;
+ int strsize;
+ char *text;
+ char *p, *q;
+ int extra;
+
+ va_start(vararg, fmt);
+ str = (char *) malloc(strsize=2048);
+ while (_vsnprintf(str, strsize, fmt, vararg) == -1)
+ str = (char *) realloc(str, strsize+=2048);
+ va_end(vararg);
+
+ extra = 0;
+ for (p=str; *p!='\0'; p++)
+ if (*p=='\n' || *p=='\r')
+ extra++;
+ text = (char *) malloc(strlen(muccModuleName)+2+strlen(str)+2+extra);
+ wsprintf(text, "[%s]", muccModuleName);
+ for (p=str,q=text+strlen(text); *p!='\0'; p++,q++) {
+ if (*p == '\r') {
+ *q = '\\';
+ *(q+1) = 'r';
+ q++;
+ }
+ else if (*p == '\n') {
+ *q = '\\';
+ *(q+1) = 'n';
+ q++;
+ }
+ else
+ *q = *p;
+ }
+ *q = '\n';
+ *(q+1) = '\0';
+// CallService(MS_NETLIB_LOG, (WPARAM) NULL, (LPARAM) text);
+ //OutputDebugString(text);
+ free(text);
+ free(str);
+#endif
+}
+
diff --git a/protocols/Tlen/tlen_czaty/Utils.h b/protocols/Tlen/tlen_czaty/Utils.h
new file mode 100644
index 0000000000..6ae4e2a44c
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/Utils.h
@@ -0,0 +1,38 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef UTILS_INCLUDED
+#define UTILS_INCLUDED
+#include "mucc.h"
+
+class Utils {
+public:
+ static unsigned long forkThread(void (__cdecl *threadcode)(void*),unsigned long stacksize,void *arg);
+ static void copyString(char **, const char *b);
+ static void log(const char *fmt, ...);
+
+ static MM_INTERFACE mmi;
+ static void mucc_mir_free(void*);
+ static char* mucc_mir_t2a(LPCTSTR);
+ static LPTSTR mucc_mir_a2t(const char* );
+
+};
+
+#endif
diff --git a/protocols/Tlen/tlen_czaty/icos/admin.ico b/protocols/Tlen/tlen_czaty/icos/admin.ico
new file mode 100644
index 0000000000..9699f55d6f
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/admin.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/administration.ico b/protocols/Tlen/tlen_czaty/icos/administration.ico
new file mode 100644
index 0000000000..e57884857e
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/administration.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/blank.ico b/protocols/Tlen/tlen_czaty/icos/blank.ico
new file mode 100644
index 0000000000..7845f62fed
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/blank.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/bold.ico b/protocols/Tlen/tlen_czaty/icos/bold.ico
new file mode 100644
index 0000000000..01d5adda1d
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/bold.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/chat.ico b/protocols/Tlen/tlen_czaty/icos/chat.ico
new file mode 100644
index 0000000000..0b388d8f9d
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/chat.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/delete.ico b/protocols/Tlen/tlen_czaty/icos/delete.ico
new file mode 100644
index 0000000000..59408c5337
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/delete.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/glowner.ico b/protocols/Tlen/tlen_czaty/icos/glowner.ico
new file mode 100644
index 0000000000..86fdf534e9
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/glowner.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/invite.ico b/protocols/Tlen/tlen_czaty/icos/invite.ico
new file mode 100644
index 0000000000..bf7dbc4d7a
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/invite.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/italic.ico b/protocols/Tlen/tlen_czaty/icos/italic.ico
new file mode 100644
index 0000000000..d34418be24
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/italic.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/message.ico b/protocols/Tlen/tlen_czaty/icos/message.ico
new file mode 100644
index 0000000000..40d183b7b3
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/message.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/next.ico b/protocols/Tlen/tlen_czaty/icos/next.ico
new file mode 100644
index 0000000000..d817b06cc6
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/next.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/options.ico b/protocols/Tlen/tlen_czaty/icos/options.ico
new file mode 100644
index 0000000000..2fd2d902d9
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/options.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/owner.ico b/protocols/Tlen/tlen_czaty/icos/owner.ico
new file mode 100644
index 0000000000..27bea391f0
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/owner.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/prev.ico b/protocols/Tlen/tlen_czaty/icos/prev.ico
new file mode 100644
index 0000000000..2f171e5783
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/prev.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/r_anon.ico b/protocols/Tlen/tlen_czaty/icos/r_anon.ico
new file mode 100644
index 0000000000..b5ebd0289e
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/r_anon.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/r_memb.ico b/protocols/Tlen/tlen_czaty/icos/r_memb.ico
new file mode 100644
index 0000000000..418fd9abf5
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/r_memb.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/r_mod.ico b/protocols/Tlen/tlen_czaty/icos/r_mod.ico
new file mode 100644
index 0000000000..3b9fa47f60
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/r_mod.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/registered.ico b/protocols/Tlen/tlen_czaty/icos/registered.ico
new file mode 100644
index 0000000000..3a5182b5d6
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/registered.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/save.ico b/protocols/Tlen/tlen_czaty/icos/save.ico
new file mode 100644
index 0000000000..48b0581fd5
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/save.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/search.ico b/protocols/Tlen/tlen_czaty/icos/search.ico
new file mode 100644
index 0000000000..065468e272
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/search.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/sendmail.ico b/protocols/Tlen/tlen_czaty/icos/sendmail.ico
new file mode 100644
index 0000000000..0b60bf950e
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/sendmail.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/smile.ico b/protocols/Tlen/tlen_czaty/icos/smile.ico
new file mode 100644
index 0000000000..d4aea87249
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/smile.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/tlenbig.ico b/protocols/Tlen/tlen_czaty/icos/tlenbig.ico
new file mode 100644
index 0000000000..4d09293560
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/tlenbig.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/tlensmall.ico b/protocols/Tlen/tlen_czaty/icos/tlensmall.ico
new file mode 100644
index 0000000000..5204d39d21
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/tlensmall.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/icos/underline.ico b/protocols/Tlen/tlen_czaty/icos/underline.ico
new file mode 100644
index 0000000000..7709f5f7f4
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/icos/underline.ico
Binary files differ
diff --git a/protocols/Tlen/tlen_czaty/mucc.cpp b/protocols/Tlen/tlen_czaty/mucc.cpp
new file mode 100644
index 0000000000..46b0155d70
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/mucc.cpp
@@ -0,0 +1,188 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "../commons.h"
+#include "mucc.h"
+#include "mucc_services.h"
+#include "HelperDialog.h"
+#include "Options.h"
+#include "Utils.h"
+
+char *muccModuleName;
+HINSTANCE hInst;
+PLUGINLINK *pluginLink;
+HANDLE hHookEvent = NULL;
+HIMAGELIST hImageList = NULL;
+HICON muccIcon[MUCC_ICON_TOTAL];
+static int ModulesLoaded(WPARAM wParam, LPARAM lParam);
+static int PreShutdown(WPARAM wParam, LPARAM lParam);
+
+PLUGININFOEX pluginInfoEx = {
+ sizeof(PLUGININFOEX),
+#ifdef _UNICODE
+#ifdef _X64
+ "Tlen Czaty (x64, Unicode)",
+#else
+ "Tlen Czaty (Unicode)",
+#endif
+#else
+ "Tlen Czaty",
+#endif
+ PLUGIN_MAKE_VERSION(MUCC_MAJOR_VERSION,MUCC_MINOR_VERSION,MUCC_RELEASE_NUM,MUCC_BUILD_NUM),
+ "Group chats GUI plugin for Miranda IM (formerly known as mucc.dll) (version: "MUCC_VERSION_STRING" ; compiled: "__DATE__" "__TIME__")",
+ "Piotr Piastucki",
+ "the_leech@users.berlios.de",
+ "(c) 2004-2012 Piotr Piastucki",
+ "http://mtlen.berlios.de",
+ 0,
+ 0,
+#if defined( _UNICODE )
+#ifdef _X64
+ {0x9061ae31, 0x3d33, 0x49ce, { 0xaf, 0x00, 0x78, 0x9c, 0xbc, 0x25, 0xd9, 0xba }}
+#else
+ {0xadd9390c, 0x1dd4, 0x4c0d, { 0x9b, 0xa9, 0xcc, 0x76, 0x5d, 0x3d, 0xe5, 0x97 }}
+#endif
+#else
+ {0x5cf4792c, 0xa050, 0x46b6, { 0xaf, 0xd0, 0x03, 0x2d, 0x6e, 0xfc, 0xd3, 0x9c }}
+#endif
+};
+
+extern "C" BOOL WINAPI DllMain(HINSTANCE hModule, DWORD dwReason, LPVOID lpvReserved)
+{
+ hInst = hModule;
+ return TRUE;
+}
+
+extern "C" __declspec(dllexport) PLUGININFOEX *MirandaPluginInfoEx(DWORD mirandaVersion)
+{
+ if (mirandaVersion < PLUGIN_MAKE_VERSION(0,8,0,15)) {
+ MessageBox(NULL, _TEXT("The Tlen Czaty plugin cannot be loaded. It requires Miranda IM 0.8.15 or later."), _TEXT("Tlen Czaty plugin (MUCC)"), MB_OK|MB_ICONWARNING|MB_SETFOREGROUND|MB_TOPMOST);
+ return NULL;
+ }
+ return &pluginInfoEx;
+}
+
+#ifndef MIID_TLEN_MUCC
+#define MIID_TLEN_MUCC { 0xba658997, 0x0bce, 0x4f96, { 0xba, 0x48, 0x54, 0x55, 0x34, 0x16, 0x73, 0xea } }
+#endif
+
+static const MUUID interfaces[] = {
+ MIID_TLEN_MUCC,
+ MIID_LAST
+ };
+
+extern "C" __declspec(dllexport) const MUUID* MirandaPluginInterfaces(void)
+{
+ return interfaces;
+}
+
+
+static void LoadIcons() {
+ int i;
+ static int iconList[] = {
+ IDI_CHAT,
+ IDI_GLOBALOWNER,
+ IDI_OWNER,
+ IDI_ADMIN,
+ IDI_REGISTERED,
+ IDI_R_MODERATED,
+ IDI_R_MEMBERS,
+ IDI_R_ANONYMOUS,
+ IDI_PREV,
+ IDI_NEXT,
+ IDI_SEARCH,
+ IDI_BOLD,
+ IDI_ITALIC,
+ IDI_UNDERLINE,
+ IDI_OPTIONS,
+ IDI_INVITE,
+ IDI_ADMINISTRATION,
+ IDI_SMILEY,
+ IDI_MESSAGE
+
+ };
+ for (i=0; i<MUCC_ICON_TOTAL; i++) {
+ muccIcon[i] = (HICON) LoadImage(hInst, MAKEINTRESOURCE(iconList[i]), IMAGE_ICON, 0, 0, 0);
+ }
+ if (hImageList != NULL) {
+ ImageList_Destroy(hImageList);
+ }
+ hImageList = ImageList_Create(GetSystemMetrics(SM_CXSMICON),GetSystemMetrics(SM_CYSMICON),ILC_COLOR32|ILC_MASK,0,3);
+// ImageList_AddIcon(hImageList, LoadIcon(hInst, MAKEINTRESOURCE(IDI_BLANK)));
+// ImageList_AddIcon(hImageList, LoadIcon(hInst, MAKEINTRESOURCE(IDI_BLANK)));
+ ImageList_AddIcon(hImageList, muccIcon[MUCC_IDI_MESSAGE]);
+
+}
+
+extern "C" int __declspec(dllexport) Load(PLUGINLINK *link)
+{
+// char text[_MAX_PATH];
+// char *p, *q;
+// GetModuleFileNameA(hInst, text, sizeof(text));
+// p = strrchr(text, '\\');
+// p++;
+// q = strrchr(p, '.');
+// *q = '\0';
+// muccModuleName = _strdup(p);
+// _strupr(muccModuleName);
+
+ muccModuleName = "MUCC";
+
+ pluginLink = link;
+ HookEvent(ME_OPT_INITIALISE, MUCCOptInit);
+ HookEvent(ME_SYSTEM_MODULESLOADED, ModulesLoaded);
+ HookEvent(ME_SYSTEM_PRESHUTDOWN, PreShutdown);
+
+ CreateServiceFunction(MS_MUCC_QUERY_RESULT, MUCCQueryResult);
+ CreateServiceFunction(MS_MUCC_NEW_WINDOW, MUCCNewWindow);
+ CreateServiceFunction(MS_MUCC_EVENT, MUCCEvent);
+ hHookEvent = CreateHookableEvent(ME_MUCC_EVENT);
+
+ mir_getMMI(&(Utils::mmi));
+
+ LoadIcons();
+ return 0;
+}
+
+static int ModulesLoaded(WPARAM wParam, LPARAM lParam)
+{
+ Options::init();
+ HelperDialog::init();
+ ManagerWindow::init();
+ ChatWindow::init();
+ ChatContainer::init();
+ return 0;
+}
+
+static int PreShutdown(WPARAM wParam, LPARAM lParam)
+{
+ ChatContainer::release();
+ ChatWindow::release();
+ ManagerWindow::release();
+ HelperDialog::release();
+ return 0;
+}
+
+extern "C" int __declspec(dllexport) Unload(void)
+{
+ return 0;
+}
+
diff --git a/protocols/Tlen/tlen_czaty/mucc.h b/protocols/Tlen/tlen_czaty/mucc.h
new file mode 100644
index 0000000000..8dc845aa92
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/mucc.h
@@ -0,0 +1,106 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef MUCC_INCLUDED
+#define MUCC_INCLUDED
+
+//#define ENABLE_LOGGING
+
+#define _WIN32_WINNT 0x0501
+#define _WIN32_IE 0x0500
+
+#include <windows.h>
+#include <commctrl.h>
+#include <richedit.h>
+#include <process.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <time.h>
+#include <limits.h>
+
+#ifdef __MINGW32__
+#define EM_SETTEXTEX (WM_USER + 97)
+#define ST_DEFAULT 0
+#define ST_KEEPUNDO 1
+#define ST_SELECTION 2
+#define ST_NEWCHARS 4
+#else
+#include <win2k.h>
+#endif
+
+#define MIRANDA_VER 0x0700
+
+#include <newpluginapi.h>
+#include <m_system.h>
+#include <m_protomod.h>
+#include <m_protosvc.h>
+#include <m_clist.h>
+#include <m_clui.h>
+#include <m_options.h>
+#include <m_userinfo.h>
+#include <m_database.h>
+#include <m_langpack.h>
+#include <m_utils.h>
+#include <m_message.h>
+#include <m_skin.h>
+#include <m_popup.h>
+#include <m_button.h>
+
+#include "resource.h"
+
+enum {
+ MUCC_IDI_CHAT = 0,
+ MUCC_IDI_U_GLOBALOWNER,
+ MUCC_IDI_U_OWNER,
+ MUCC_IDI_U_ADMIN,
+ MUCC_IDI_U_REGISTERED,
+ MUCC_IDI_R_MODERATED,
+ MUCC_IDI_R_MEMBERS,
+ MUCC_IDI_R_ANONYMOUS,
+ MUCC_IDI_PREV,
+ MUCC_IDI_NEXT,
+ MUCC_IDI_SEARCH,
+ MUCC_IDI_BOLD,
+ MUCC_IDI_ITALIC,
+ MUCC_IDI_UNDERLINE,
+ MUCC_IDI_OPTIONS,
+ MUCC_IDI_INVITE,
+ MUCC_IDI_ADMINISTRATION,
+ MUCC_IDI_SMILEY,
+ MUCC_IDI_MESSAGE,
+ MUCC_ICON_TOTAL
+
+};
+
+extern PLUGINLINK * pluginLink;
+extern char *muccModuleName;
+extern HINSTANCE hInst;
+extern HANDLE hHookEvent;
+extern HIMAGELIST hImageList;
+extern HICON muccIcon[MUCC_ICON_TOTAL];
+
+#include "m_mucc.h"
+
+#define WM_MUCC_REFRESH_ROOMS (WM_USER+101)
+#define WM_MUCC_REFRESH_USER_ROOMS (WM_USER+102)
+#define WM_MUCC_REFRESH_USER_NICKS (WM_USER+103)
+
+#endif
+
diff --git a/protocols/Tlen/tlen_czaty/mucc.rc b/protocols/Tlen/tlen_czaty/mucc.rc
new file mode 100644
index 0000000000..d50a834649
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/mucc.rc
@@ -0,0 +1,579 @@
+#include "resource.h"
+#include "../commons.h"
+#ifdef __MINGW32__
+ #define WINVER 0x500
+ #define _WIN32_IE 0x500
+ #include <windows.h>
+ #ifndef IDC_STATIC
+ #define IDC_STATIC (-1)
+#endif
+#else
+// #define APSTUDIO_READONLY_SYMBOLS
+// #include "winres.h"
+// #undef APSTUDIO_READONLY_SYMBOLS
+ #include <windows.h>
+ #ifndef IDC_STATIC
+ #define IDC_STATIC (-1)
+ #endif
+#endif
+#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
+#ifdef _WIN32
+LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
+#pragma code_page(1252)
+#endif
+#ifdef APSTUDIO_INVOKED
+
+1 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "resource.h\0"
+END
+
+2 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "#include ""winres.h""\r\n"
+ "\0"
+END
+
+3 TEXTINCLUDE DISCARDABLE
+BEGIN
+ "\r\n"
+ "\0"
+END
+
+#endif // APSTUDIO_INVOKED
+
+IDR_CHATOPTIONS MENU DISCARDABLE
+BEGIN
+ POPUP "", MENUBREAK
+ BEGIN
+ POPUP "Log Appearance"
+ BEGIN
+ MENUITEM "Show Nicknames", ID_OPTIONMENU_SHOWNICKNAMES
+ MENUITEM "Show Message On A New Line", ID_OPTIONMENU_MSGINNEWLINE
+ END
+ POPUP "Timestamp Settings"
+ BEGIN
+ MENUITEM "Show Date", ID_OPTIONMENU_SHOWDATE
+ MENUITEM "Show Timestamp", ID_OPTIONMENU_SHOWTIMESTAMP
+ MENUITEM "Show Seconds", ID_OPTIONMENU_SHOWSECONDS
+ MENUITEM "Use Long Date Format", ID_OPTIONMENU_USELONGDATE
+
+ END
+ POPUP "Text Formatting Filter"
+ BEGIN
+ MENUITEM "Font Name", ID_OPTIONMENU_FORMATFONT
+ MENUITEM "Font Size", ID_OPTIONMENU_FORMATSIZE
+ MENUITEM "Font Style", ID_OPTIONMENU_FORMATSTYLE
+ MENUITEM "Font Color", ID_OPTIONMENU_FORMATCOLOR
+ END
+ POPUP "Event Filter"
+ BEGIN
+ MENUITEM "Messages", ID_OPTIONMENU_LOGMESSAGES
+ MENUITEM "User Has Joined", ID_OPTIONMENU_LOGJOINED
+ MENUITEM "User Has Left", ID_OPTIONMENU_LOGLEFT
+ MENUITEM "Topic Changes", ID_OPTIONMENU_LOGTOPIC
+ END
+ POPUP "Window Flashing"
+ BEGIN
+ MENUITEM "Messages", ID_OPTIONMENU_FLASHMESSAGES
+ MENUITEM "User Has Joined", ID_OPTIONMENU_FLASHJOINED
+ MENUITEM "User Has Left", ID_OPTIONMENU_FLASHLEFT
+ MENUITEM "Topic Changes", ID_OPTIONMENU_FLASHTOPIC
+ END
+ MENUITEM SEPARATOR
+ MENUITEM "Save Settings As Default", ID_OPTIONMENU_SAVEDEFAULT
+ MENUITEM SEPARATOR
+ MENUITEM "User Administration", ID_ADMINMENU_ADMIN, GRAYED
+ MENUITEM "Destroy Chat Room", ID_ADMINMENU_DESTROY, GRAYED
+ MENUITEM SEPARATOR
+ MENUITEM "Save Log", ID_ADMINMENU_SAVELOG
+ END
+ POPUP "", MENUBREAK
+ BEGIN
+ MENUITEM "Message", ID_USERMENU_MESSAGE
+ MENUITEM SEPARATOR
+ POPUP "Kick && Ban", GRAYED
+ BEGIN
+ MENUITEM "No Ban", ID_USERMENU_KICK_NO_BAN
+ MENUITEM "Ban For 1 Minute", ID_USERMENU_KICK_BAN_1_MIN
+ MENUITEM "Ban For 5 Minutes", ID_USERMENU_KICK_BAN_5_MIN
+ MENUITEM "Ban For 15 Minutes", ID_USERMENU_KICK_BAN_15_MIN
+ MENUITEM "Ban For 30 Minutes", ID_USERMENU_KICK_BAN_15_MIN
+ MENUITEM "Ban For 1 Hour", ID_USERMENU_KICK_BAN_1_H
+ MENUITEM "Ban For 6 Hours", ID_USERMENU_KICK_BAN_6_H
+ MENUITEM "Ban For 1 Day", ID_USERMENU_KICK_BAN_1_D
+ MENUITEM "Ban For 3 Days", ID_USERMENU_KICK_BAN_3_D
+ MENUITEM "Ban For 1 Week", ID_USERMENU_KICK_BAN_1_W
+ MENUITEM "Ban For 2 Weeks", ID_USERMENU_KICK_BAN_2_W
+ MENUITEM "Ban For 4 Weeks", ID_USERMENU_KICK_BAN_4_W
+ END
+ POPUP "Change User Role", GRAYED
+ BEGIN
+ MENUITEM "No Role", ID_USERMENU_RIGHTS_NO
+ MENUITEM "Member", ID_USERMENU_RIGHTS_MEMBER
+
+ MENUITEM "Admin", ID_USERMENU_RIGHTS_ADMIN
+ END
+ MENUITEM "User Administration", ID_USERMENU_ADMINISTRATION, GRAYED
+ END
+ POPUP "", MENUBREAK
+ BEGIN
+ MENUITEM "Unban", ID_USERMENU_UNBAN
+ END
+END
+
+IDR_CONTEXT MENU DISCARDABLE
+BEGIN
+ POPUP "Log"
+ BEGIN
+ MENUITEM "&Copy", IDM_COPY
+ MENUITEM "Co&py All", IDM_COPYALL
+ MENUITEM SEPARATOR
+ MENUITEM "Select &All", IDM_SELECTALL
+ MENUITEM SEPARATOR
+ MENUITEM "C&lear Log", IDM_CLEAR
+ END
+ POPUP "LogLink"
+ BEGIN
+ MENUITEM "Open in &new window", IDM_OPENNEW
+ MENUITEM "&Open in existing window", IDM_OPENEXISTING
+ MENUITEM "&Copy link", IDM_COPYLINK
+ END
+ POPUP "Message"
+ BEGIN
+ MENUITEM "Undo", IDM_UNDO
+ MENUITEM "Redo", IDM_REDO
+ MENUITEM SEPARATOR
+ MENUITEM "Cut", IDM_CUT
+ MENUITEM "Copy", IDM_COPY
+ MENUITEM "Paste", IDM_PASTE
+ MENUITEM "Delete", IDM_DELETE
+ MENUITEM SEPARATOR
+ MENUITEM "Select &All", IDM_SELECTALL
+ END
+END
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Dialog
+//
+
+IDD_OPTIONS DIALOGEX 0, 0, 320, 260
+STYLE DS_FIXEDSYS | WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ GROUPBOX "Fonts",IDC_FONTSGB,169,10,143,182
+ LTEXT "Background color",IDC_STATIC,175,23,100,8
+ CONTROL "",IDC_COLORBKG,"ColourPicker",WS_TABSTOP,277,21,29,12
+ LTEXT "Input area background",IDC_STATIC,175,38,100,8
+ CONTROL "",IDC_COLORINPUT,"ColourPicker",WS_TABSTOP,277,36,29,12
+ LTEXT "User list background",IDC_STATIC,175,53,100,8
+ CONTROL "",IDC_COLORLIST,"ColourPicker",WS_TABSTOP,277,51,29,12
+ LISTBOX IDC_FONTLIST,175,69,131,95,LBS_OWNERDRAWVARIABLE |
+ LBS_NOINTEGRALHEIGHT | LBS_EXTENDEDSEL | WS_VSCROLL |
+ WS_TABSTOP
+ CONTROL "",IDC_COLORTXT,"ColourPicker",WS_TABSTOP,175,170,55,15
+ PUSHBUTTON "Choose font",IDC_CHOOSEFONT,251,170,55,15
+ GROUPBOX "Options",IDC_OPTIONSGB,5,10,158,182
+ CONTROL "",IDC_TREELIST,"SysTreeView32",TVS_HASBUTTONS |
+ TVS_HASLINES | TVS_LINESATROOT | TVS_DISABLEDRAGDROP,11,
+ 23,146,162,WS_EX_STATICEDGE
+ GROUPBOX "Other",IDC_SIMPLE,5,193,310,57
+ CONTROL "Use tabbed mode",IDC_USETABS,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,13,206,140,10
+ CONTROL "Enable IEView",IDC_ENABLEIEVIEW,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,13,219,140,10
+ CONTROL "Send message on 'Enter'",IDC_SENDONENTER,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,13,232,140,10
+ LTEXT "Limit log history to (events):",IDC_STATIC,153,234,110,8
+ EDITTEXT IDC_LOGLIMIT,263,232,40,14,ES_RIGHT | ES_NUMBER
+ CONTROL "",IDC_LOGLIMITSPIN,"msctls_updown32",UDS_SETBUDDYINT |
+ UDS_ALIGNRIGHT | UDS_AUTOBUDDY | UDS_ARROWKEYS |
+ UDS_NOTHOUSANDS | UDS_HOTTRACK,390,218,11,14
+END
+
+IDD_CHATMANAGER DIALOGEX 0, 0, 473, 234
+STYLE DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER |
+ WS_MINIMIZEBOX | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU |
+ WS_THICKFRAME
+EXSTYLE WS_EX_CONTROLPARENT
+CAPTION "Chats"
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ CONTROL "Tab1",IDC_TABS,"SysTabControl32",TCS_BUTTONS |
+ TCS_FIXEDWIDTH | 0x8,214,7,252,20
+ PUSHBUTTON "Close",IDCLOSE,416,215,50,14
+ CONTROL "Tree1",IDC_GROUP,"SysTreeView32",TVS_HASBUTTONS |
+ TVS_HASLINES | TVS_LINESATROOT | TVS_DISABLEDRAGDROP |
+ TVS_SHOWSELALWAYS | TVS_NOTOOLTIPS,5,20,203,209,
+ WS_EX_STATICEDGE
+ LTEXT "Groups",IDC_STATIC,7,9,24,8
+END
+
+IDD_GROUPCHAT_CONTAINER DIALOGEX 0, 0, 300, 200
+STYLE DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER |
+ WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU |
+ WS_THICKFRAME
+EXSTYLE WS_EX_CONTROLPARENT
+CAPTION "Tlen Group Chat"
+FONT 8, "MS Shell Dlg"
+BEGIN
+ CONTROL "",IDC_TABS,"SysTabControl32", WS_CLIPSIBLINGS | TCS_MULTILINE | TCS_FOCUSNEVER | 0x8,0,0,300,200
+END
+
+IDD_GROUPCHAT_LOG DIALOGEX 0, 0, 294, 178
+STYLE DS_FIXEDSYS | WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN
+/*
+STYLE DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER |
+ WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_VISIBLE | WS_CAPTION | WS_SYSMENU |
+ WS_THICKFRAME
+ */
+//EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ CONTROL "",IDC_VSPLIT,"Static",SS_ENHMETAFILE,237,20,3,117
+ CONTROL "",IDC_HSPLIT,"Static",SS_ENHMETAFILE,156,285,2,0
+ CONTROL "",IDC_LOG,"RichEdit20A",WS_VSCROLL | WS_TABSTOP | WS_CLIPSIBLINGS | 0x844,
+ 3,21,233,117,WS_EX_STATICEDGE
+ CONTROL "",IDC_TREELIST,"SysTreeView32",TVS_DISABLEDRAGDROP |
+ TVS_SHOWSELALWAYS | TVS_NOTOOLTIPS | TVS_NONEVENHEIGHT,5,
+ 20,203,209,WS_EX_STATICEDGE
+ EDITTEXT IDC_EDIT,3,158,285,13,ES_MULTILINE | ES_AUTOVSCROLL |
+ NOT WS_BORDER | WS_VSCROLL | ES_WANTRETURN,WS_EX_STATICEDGE
+ CONTROL "Topic",IDC_TOPIC_BUTTON,"MButtonClass",WS_DISABLED |
+ WS_TABSTOP,3,3,34,12,0x18000000L
+ CONTROL "",IDC_BOLD,"MButtonClass",WS_TABSTOP,3,140,16,16,
+ 0x18000000L
+ CONTROL "",IDC_ITALIC,"MButtonClass",WS_TABSTOP,21,140,16,16,
+ 0x18000000L
+ CONTROL "",IDC_UNDERLINE,"MButtonClass",WS_TABSTOP,39,140,16,16,
+ 0x18000000L
+ CONTROL "",IDC_COLOR,"ColourPicker",WS_TABSTOP,57,140,16,16
+ COMBOBOX IDC_FONTSIZE,154,142,27,80,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ CONTROL "",IDC_SMILEYBTN,"MButtonClass", WS_TABSTOP,185,140,16,16,
+ 0x18000000L
+ CONTROL "Invite",IDC_INVITE,"MButtonClass",WS_TABSTOP,259,141,16,
+ 16,0x18000000L
+ EDITTEXT IDC_TOPIC,70,19,86,12,ES_AUTOHSCROLL | ES_READONLY | NOT
+ WS_BORDER
+ CONTROL "",IDC_OPTIONS,"MButtonClass",WS_TABSTOP,208,140,16,16,
+ 0x18000000L
+ COMBOBOX IDC_FONT,77,142,74,90,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ PUSHBUTTON "Close",IDCANCEL,0,0,20,20,NOT WS_VISIBLE
+ //,NOT WS_VISIBLE
+END
+
+IDD_HELPER_JOIN DIALOGEX 0, 0, 186, 79
+STYLE DS_MODALFRAME | DS_SETFOREGROUND | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER |
+ WS_POPUP | WS_VISIBLE | WS_CAPTION
+EXSTYLE WS_EX_CONTROLPARENT
+CAPTION "Join Tlen Multi-User Conference Room"
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ LTEXT "Room:",IDC_ROOM_LABEL,10,13,43,8
+ EDITTEXT IDC_ROOM,54,12,119,12,ES_AUTOHSCROLL
+ LTEXT "Nickname:",IDC_NICK_LABEL,10,30,40,8
+ EDITTEXT IDC_NICK,54,29,119,12,ES_AUTOHSCROLL
+ DEFPUSHBUTTON "&Join",IDOK,75,59,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,129,59,50,14
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,7,50,172,4
+END
+
+IDD_HELPER_INVITE DIALOG DISCARDABLE 0, 0, 186, 79
+STYLE DS_MODALFRAME | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP |
+ WS_VISIBLE | WS_CAPTION | WS_SYSMENU
+CAPTION "Invite a User"
+FONT 8, "MS Shell Dlg"
+BEGIN
+ LTEXT "User:",IDC_STATIC,10,13,43,8
+ COMBOBOX IDC_USER,54,10,119,120,CBS_DROPDOWN | CBS_AUTOHSCROLL |
+ CBS_SORT | WS_VSCROLL | WS_TABSTOP
+ LTEXT "Reason:",IDC_STATIC,10,30,40,8
+ EDITTEXT IDC_REASON,54,29,119,12,ES_AUTOHSCROLL
+ DEFPUSHBUTTON "&Invite",IDC_INVITE,75,59,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,129,59,50,14
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,7,50,172,4
+END
+
+IDD_HELPER_INVITE_ACCEPT DIALOG DISCARDABLE 0, 0, 232, 112
+STYLE DS_MODALFRAME | DS_SETFOREGROUND | DS_FIXEDSYS | DS_CENTER | WS_POPUP |
+ WS_VISIBLE | WS_CAPTION | WS_SYSMENU
+CAPTION "Multi-User Conference Invitation"
+FONT 8, "MS Shell Dlg"
+BEGIN
+ DEFPUSHBUTTON "&Accept",IDC_ACCEPT,124,93,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,178,93,50,14
+ LTEXT "From:",IDC_STATIC,33,24,63,8
+ LTEXT "Room:",IDC_STATIC,33,38,63,8
+ LTEXT "Reason:",IDC_STATIC,33,52,63,8
+ LTEXT "Nickname:",IDC_STATIC,33,76,62,8
+ LTEXT "The following invitation to join a multi-user conference is received.",
+ IDC_STATIC,3,4,225,8
+ EDITTEXT IDC_FROM,99,22,105,12,ES_AUTOHSCROLL | ES_READONLY
+ EDITTEXT IDC_ROOM,99,36,105,12,ES_AUTOHSCROLL | ES_READONLY
+ EDITTEXT IDC_REASON,99,50,105,12,ES_AUTOHSCROLL | ES_READONLY
+ EDITTEXT IDC_NICK,99,74,105,12,ES_AUTOHSCROLL
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,3,65,225,4
+END
+
+IDD_HELPER_TOPIC DIALOGEX 0, 0, 223, 44
+STYLE DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP |
+ WS_VISIBLE | WS_CAPTION
+EXSTYLE WS_EX_CONTROLPARENT
+CAPTION "Change Chat Room Topic"
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ LTEXT "New topic:",IDC_STATIC,10,8,43,8
+ EDITTEXT IDC_TOPIC,54,7,160,12,ES_AUTOHSCROLL
+ DEFPUSHBUTTON "OK",IDOK,108,26,50,14
+ PUSHBUTTON "Cancel",IDCANCEL,164,26,50,14
+END
+
+IDD_USER_ADMIN DIALOG DISCARDABLE 0, 0, 300, 180
+STYLE DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP |
+ WS_VISIBLE | WS_CAPTION | WS_SYSMENU
+EXSTYLE WS_EX_CONTROLPARENT
+CAPTION "Chat Room Administration"
+FONT 8, "MS Sans Serif"
+BEGIN
+ CONTROL "Tab1",IDC_TABS,"SysTabControl32",TCS_BUTTONS |
+ TCS_FIXEDWIDTH | 0x8,0,5,220,20
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,0,20,300,4
+ PUSHBUTTON "Close",IDCANCEL,230,162,60,16
+
+END
+
+IDD_USER_KICK DIALOGEX 0, 30, 300, 130
+STYLE WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ LTEXT "Nickname:",IDC_STATIC,30,6,70,10
+ EDITTEXT IDC_NICK,100,6,100,12,ES_AUTOHSCROLL | WS_TABSTOP
+ LTEXT "Ban for:",IDC_STATIC,30,35,70,10
+ COMBOBOX IDC_KICK_OPTIONS,100,35,90,150,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ LTEXT "Reason:",IDC_STATIC,30,51,70,10
+ EDITTEXT IDC_REASON,100,51,100,12,ES_AUTOHSCROLL | WS_TABSTOP
+ CONTROL "Kick && Ban",IDOK,"MButtonClass",WS_TABSTOP,210,65,60,16
+
+ LTEXT "User role:",IDC_STATIC,30,90,70,10
+ COMBOBOX IDC_ROLE_OPTIONS,100,90,90,60,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ CONTROL "Set Role",IDC_SET_ROLE,"MButtonClass",WS_TABSTOP,210,104,60,16
+
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,0,128,300,4
+END
+
+IDD_USER_ROLE DIALOGEX 0, 30, 300, 130
+STYLE WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ LTEXT "Nickname:",IDC_STATIC,30,25,70,10
+ EDITTEXT IDC_NICK,100,25,100,12,ES_AUTOHSCROLL | WS_TABSTOP
+ LTEXT "User role:",IDC_STATIC,30,41,70,10
+ COMBOBOX IDC_OPTIONS,100,41,90,60,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ CONTROL "Set Role",IDOK,"MButtonClass",WS_TABSTOP,120,90,60,16
+ CONTROL "",IDC_STATIC,"Static",SS_ETCHEDHORZ,0,128,300,4
+END
+
+IDD_USER_BROWSER DIALOGEX 0, 30, 300, 130
+STYLE WS_CHILD
+EXSTYLE WS_EX_CONTROLPARENT
+FONT 8, "MS Shell Dlg", 0, 0, 0x1
+BEGIN
+ COMBOBOX IDC_OPTIONS,50,0,90,60,CBS_DROPDOWNLIST | WS_VSCROLL |
+ WS_TABSTOP
+ CONTROL "Show",IDC_SHOW,"MButtonClass",WS_TABSTOP,160,0,50,14
+ CONTROL "List1",IDC_LIST,"SysListView32",LVS_REPORT |
+ LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_AUTOARRANGE |
+ LVS_OWNERDRAWFIXED | WS_TABSTOP,0,20,299,110,
+ WS_EX_CLIENTEDGE
+END
+
+IDD_OPT_POPUPS DIALOG DISCARDABLE 0, 0, 317, 141
+STYLE WS_CHILD
+FONT 8, "MS Sans Serif"
+BEGIN
+ GROUPBOX "Delay",IDC_STATIC,160,46,137,55
+ CONTROL "&From PopUp plugin",IDC_DELAY_POPUP,"Button",
+ BS_AUTORADIOBUTTON,167,60,125,10
+ CONTROL "&Custom",IDC_DELAY_CUSTOM,"Button",BS_AUTORADIOBUTTON,
+ 167,73,98,10
+ CONTROL "P&ermanent",IDC_DELAY_PERMANENT,"Button",
+ BS_AUTORADIOBUTTON,167,87,123,10
+ EDITTEXT IDC_DELAY,270,71,21,14,ES_AUTOHSCROLL | ES_NUMBER
+ GROUPBOX "Colours",IDC_STATIC,15,46,137,55
+ LTEXT "Background",IDC_STATIC,53,63,95,8
+ LTEXT "Text",IDC_STATIC,53,82,96,8
+ CONTROL "",IDC_COLORBKG,"ColourPicker",WS_TABSTOP,23,61,24,12
+ GROUPBOX "General Options",IDC_STATIC,15,15,282,26
+ CONTROL "",IDC_COLORTXT,"ColourPicker",WS_TABSTOP,23,79,24,12
+ PUSHBUTTON "Preview",IDC_PREVIEW,132,112,50,14
+ CONTROL "Enable incoming mail notification",IDC_ENABLEPOPUP,
+ "Button",BS_AUTOCHECKBOX | WS_TABSTOP,23,26,130,10
+END
+
+IDD_TAB_CHATROOMS DIALOGEX 216, 28, 247, 180
+STYLE WS_CHILD
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ CONTROL "List1",IDC_ROOM,"SysListView32",LVS_REPORT |
+ LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_AUTOARRANGE |
+ LVS_OWNERDRAWFIXED | WS_TABSTOP,0,26,247,154,
+ WS_EX_CLIENTEDGE
+ CONTROL "prev",IDC_PREV,"MButtonClass",WS_TABSTOP,5,6,20,16
+ CONTROL "next",IDC_NEXT,"MButtonClass",WS_TABSTOP,35,6,20,16
+ CONTROL "find",IDC_SEARCH,"MButtonClass",WS_TABSTOP,65,6,20,16
+END
+
+IDD_TAB_MYROOMS DIALOGEX 216, 28, 244, 180
+STYLE WS_CHILD
+FONT 8, "MS Sans Serif", 0, 0, 0x1
+BEGIN
+ CONTROL "Create",IDC_REGISTER,"MButtonClass",WS_TABSTOP,186,62,
+ 50,14,0x18000000L
+ EDITTEXT IDC_NAME,84,20,149,14,ES_AUTOHSCROLL
+ LTEXT "Room name:",IDC_STATIC,14,23,60,8
+ CONTROL "Permanent",IDC_CHECK_PERMANENT,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,111,40,89,10
+ CONTROL "Nicknames",IDC_CHECK_NICKNAMES,"Button",
+ BS_AUTOCHECKBOX | WS_TABSTOP,13,52,89,10
+ CONTROL "Public",IDC_CHECK_PUBLIC,"Button",BS_AUTOCHECKBOX |
+ WS_TABSTOP,13,40,89,10
+ CONTROL "Members only",IDC_CHECK_MEMBERS,"Button",
+ BS_AUTOCHECKBOX,111,52,89,10
+ LTEXT "Chat rooms:",IDC_STATIC,2,90,100,8
+ /*
+ CONTROL "Tree1",IDC_LIST,"SysTreeView32",TVS_DISABLEDRAGDROP |
+ TVS_SHOWSELALWAYS | TVS_NOTOOLTIPS | TVS_FULLROWSELECT |
+ TVS_NONEVENHEIGHT,0,100,177,80,WS_EX_STATICEDGE
+ */
+ CONTROL "Refresh",IDC_REFRESH,"MButtonClass",WS_TABSTOP,186,160,
+ 50,14,0x18000000L
+ GROUPBOX "New chat room",IDC_STATIC,0,5,244,78
+ CONTROL "List1",IDC_LIST,"SysListView32",LVS_REPORT |
+ LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_AUTOARRANGE |
+ LVS_NOCOLUMNHEADER | LVS_OWNERDRAWFIXED | WS_TABSTOP,0,100,177,80,
+ WS_EX_CLIENTEDGE
+END
+
+IDD_TAB_MYNICKNAMES DIALOG DISCARDABLE 216, 28, 244, 180
+STYLE WS_CHILD
+FONT 8, "MS Sans Serif"
+BEGIN
+ CONTROL "Register",IDC_REGISTER,"MButtonClass",WS_TABSTOP,186,62,
+ 50,14,0x18000000L
+ EDITTEXT IDC_NICK,84,20,149,14,ES_AUTOHSCROLL
+ LTEXT "Nickname:",IDC_STATIC,14,23,60,8
+ LTEXT "Nicknames:",IDC_STATIC,2,90,100,8
+ CONTROL "Remove",IDC_REMOVE,"MButtonClass",WS_TABSTOP,186,110,50,
+ 14,0x18000000L
+ CONTROL "Refresh",IDC_REFRESH,"MButtonClass",WS_TABSTOP,186,160,
+ 50,14,0x18000000L
+ GROUPBOX "New nickname",IDC_STATIC,0,5,244,78
+ CONTROL "List1",IDC_LIST,"SysListView32",LVS_REPORT |
+ LVS_SINGLESEL | LVS_SHOWSELALWAYS | LVS_AUTOARRANGE |
+ LVS_NOCOLUMNHEADER | LVS_OWNERDRAWFIXED | WS_TABSTOP,0,100,177,80,
+ WS_EX_CLIENTEDGE
+ /*
+ CONTROL "Tree1",IDC_LIST,"SysTreeView32",TVS_DISABLEDRAGDROP |
+ TVS_SHOWSELALWAYS | TVS_NOTOOLTIPS | TVS_FULLROWSELECT |
+ TVS_NONEVENHEIGHT,0,100,177,80,WS_EX_STATICEDGE
+ */
+END
+
+
+#ifndef _MAC
+/////////////////////////////////////////////////////////////////////////////
+//
+// Version
+//
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION MUCC_FILEVERSION_STRING
+ PRODUCTVERSION MUCC_FILEVERSION_STRING
+ FILEFLAGSMASK 0x3fL
+#ifdef _DEBUG
+ FILEFLAGS 0x1L
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS 0x40004L
+ FILETYPE 0x2L
+ FILESUBTYPE 0x0L
+BEGIN
+ BLOCK "StringFileInfo"
+ BEGIN
+ BLOCK "041504e3"
+ BEGIN
+ VALUE "Comments", "\0"
+ VALUE "CompanyName", "http://mtlen.berlios.de\0"
+ VALUE "FileDescription", "Group Chats GUI Plugin for Miranda IM\0"
+ VALUE "FileVersion", MUCC_VERSION_STRING
+ VALUE "InternalName", "tlen_chat\0"
+ VALUE "LegalCopyright", "Copyright (c) 2004-2006 Piotr Piastucki\0"
+ VALUE "LegalTrademarks", "\0"
+ VALUE "OriginalFilename", "tlen_chat.dll\0"
+ VALUE "PrivateBuild", "\0"
+ VALUE "ProductName", "Tlen Chat Plugin\0"
+ VALUE "ProductVersion", MUCC_VERSION_STRING
+ VALUE "SpecialBuild", "\0"
+ END
+ END
+ BLOCK "VarFileInfo"
+ BEGIN
+ VALUE "Translation", 0x415, 1251
+ END
+END
+
+#endif // !_MAC
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// Icon
+//
+
+// Icon with lowest ID value placed first to ensure application icon
+// remains consistent on all systems.
+IDI_CHAT ICON DISCARDABLE "icos\\chat.ico"
+IDI_BLANK ICON DISCARDABLE "icos\\blank.ico"
+IDI_ITALIC ICON DISCARDABLE "icos\\italic.ico"
+IDI_BOLD ICON DISCARDABLE "icos\\bold.ico"
+IDI_UNDERLINE ICON DISCARDABLE "icos\\underline.ico"
+IDI_OPTIONS ICON DISCARDABLE "icos\\options.ico"
+IDI_OWNER ICON DISCARDABLE "icos\\owner.ico"
+IDI_GLOBALOWNER ICON DISCARDABLE "icos\\glowner.ico"
+IDI_ADMIN ICON DISCARDABLE "icos\\admin.ico"
+IDI_REGISTERED ICON DISCARDABLE "icos\\registered.ico"
+IDI_R_MODERATED ICON DISCARDABLE "icos\\r_mod.ico"
+IDI_R_MEMBERS ICON DISCARDABLE "icos\\r_memb.ico"
+IDI_R_ANONYMOUS ICON DISCARDABLE "icos\\r_anon.ico"
+IDI_SEARCH ICON DISCARDABLE "icos\\search.ico"
+IDI_PREV ICON DISCARDABLE "icos\\prev.ico"
+IDI_NEXT ICON DISCARDABLE "icos\\next.ico"
+IDI_INVITE ICON DISCARDABLE "icos\\invite.ico"
+IDI_ADMINISTRATION ICON DISCARDABLE "icos\\administration.ico"
+IDI_SMILEY ICON DISCARDABLE "icos\\smile.ico"
+IDI_MESSAGE ICON DISCARDABLE "icos\\message.ico"
+#endif // English (U.S.) resources
+/////////////////////////////////////////////////////////////////////////////
+
+
+
+#ifndef APSTUDIO_INVOKED
+/////////////////////////////////////////////////////////////////////////////
+//
+// Generated from the TEXTINCLUDE 3 resource.
+//
+
+
+/////////////////////////////////////////////////////////////////////////////
+#endif // not APSTUDIO_INVOKED
+
diff --git a/protocols/Tlen/tlen_czaty/mucc.sln b/protocols/Tlen/tlen_czaty/mucc.sln
new file mode 100644
index 0000000000..f62ed9965d
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/mucc.sln
@@ -0,0 +1,43 @@
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual C++ Express 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mucc", "mucc.vcxproj", "{BD1D155A-7A47-4414-80A3-CCCC3C5C583B}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug Ansi|Win32 = Debug Ansi|Win32
+ Debug Ansi|x64 = Debug Ansi|x64
+ Debug Unicode|Win32 = Debug Unicode|Win32
+ Debug Unicode|x64 = Debug Unicode|x64
+ Debug x64|Win32 = Debug x64|Win32
+ Debug x64|x64 = Debug x64|x64
+ Release Ansi|Win32 = Release Ansi|Win32
+ Release Ansi|x64 = Release Ansi|x64
+ Release Unicode|Win32 = Release Unicode|Win32
+ Release Unicode|x64 = Release Unicode|x64
+ Release x64|Win32 = Release x64|Win32
+ Release x64|x64 = Release x64|x64
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug Ansi|Win32.ActiveCfg = Debug Ansi|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug Ansi|Win32.Build.0 = Debug Ansi|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug Ansi|x64.ActiveCfg = Debug Ansi|x64
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug Unicode|Win32.ActiveCfg = Debug Unicode|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug Unicode|Win32.Build.0 = Debug Unicode|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug Unicode|x64.ActiveCfg = Debug Unicode|x64
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug x64|Win32.ActiveCfg = Debug x64|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug x64|x64.ActiveCfg = Debug x64|x64
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Debug x64|x64.Build.0 = Debug x64|x64
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release Ansi|Win32.ActiveCfg = Release Ansi|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release Ansi|Win32.Build.0 = Release Ansi|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release Ansi|x64.ActiveCfg = Release Ansi|x64
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release Unicode|Win32.ActiveCfg = Release Unicode|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release Unicode|Win32.Build.0 = Release Unicode|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release Unicode|x64.ActiveCfg = Release Unicode|x64
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release x64|Win32.ActiveCfg = Release x64|Win32
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release x64|x64.ActiveCfg = Release x64|x64
+ {BD1D155A-7A47-4414-80A3-CCCC3C5C583B}.Release x64|x64.Build.0 = Release x64|x64
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/protocols/Tlen/tlen_czaty/mucc.vcxproj b/protocols/Tlen/tlen_czaty/mucc.vcxproj
new file mode 100644
index 0000000000..c2fe6e7b70
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/mucc.vcxproj
@@ -0,0 +1,1245 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <ItemGroup Label="ProjectConfigurations">
+ <ProjectConfiguration Include="Debug Ansi|Win32">
+ <Configuration>Debug Ansi</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug Ansi|x64">
+ <Configuration>Debug Ansi</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug Unicode|Win32">
+ <Configuration>Debug Unicode</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug Unicode|x64">
+ <Configuration>Debug Unicode</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug x64|Win32">
+ <Configuration>Debug x64</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Debug x64|x64">
+ <Configuration>Debug x64</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Ansi|Win32">
+ <Configuration>Release Ansi</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Ansi|x64">
+ <Configuration>Release Ansi</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Unicode|Win32">
+ <Configuration>Release Unicode</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release Unicode|x64">
+ <Configuration>Release Unicode</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release x64|Win32">
+ <Configuration>Release x64</Configuration>
+ <Platform>Win32</Platform>
+ </ProjectConfiguration>
+ <ProjectConfiguration Include="Release x64|x64">
+ <Configuration>Release x64</Configuration>
+ <Platform>x64</Platform>
+ </ProjectConfiguration>
+ </ItemGroup>
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>{BD1D155A-7A47-4414-80A3-CCCC3C5C583B}</ProjectGuid>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>Unicode</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'" Label="Configuration">
+ <ConfigurationType>DynamicLibrary</ConfigurationType>
+ <UseOfMfc>false</UseOfMfc>
+ <CharacterSet>MultiByte</CharacterSet>
+ <PlatformToolset>Windows7.1SDK</PlatformToolset>
+ <WholeProgramOptimization>true</WholeProgramOptimization>
+ </PropertyGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+ <ImportGroup Label="ExtensionSettings">
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'" Label="PropertySheets">
+ <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+ <Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC60.props" />
+ </ImportGroup>
+ <PropertyGroup Label="UserMacros" />
+ <PropertyGroup>
+ <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">$(Configuration)\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">$(Configuration)\Obj\</IntDir>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">true</IgnoreImportLibrary>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">false</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">false</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">false</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">false</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">false</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">false</LinkIncremental>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">$(Configuration)\</OutDir>
+ <OutDir Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">$(Configuration)\</OutDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">$(Configuration)\Obj\</IntDir>
+ <IntDir Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">$(Configuration)\Obj\</IntDir>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">true</IgnoreImportLibrary>
+ <IgnoreImportLibrary Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">true</IgnoreImportLibrary>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">true</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">true</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">true</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">true</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">true</LinkIncremental>
+ <LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">true</LinkIncremental>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">tlen_czaty</TargetName>
+ <TargetName Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">tlen_czaty</TargetName>
+ </PropertyGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Release/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>MaxSpeed</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;_X64;X64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <BaseAddress>0x32600000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Release/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>MaxSpeed</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;UNICODE;_UNICODE;_X64;X64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <BaseAddress>0x32600000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Release/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>MaxSpeed</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <BaseAddress>0x32600000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Release/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>MaxSpeed</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;UNICODE;_UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <BaseAddress>0x32600000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Release/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>MaxSpeed</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <BaseAddress>0x32600000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">
+ <Midl>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Release/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>MaxSpeed</Optimization>
+ <InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <StringPooling>true</StringPooling>
+ <RuntimeLibrary>MultiThreaded</RuntimeLibrary>
+ <FunctionLevelLinking>true</FunctionLevelLinking>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <BaseAddress>0x32600000</BaseAddress>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Debug/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;X64;_X64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MinimalRebuild>true</MinimalRebuild>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Debug/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;UNICODE;_UNICODE;X64;_X64;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Debug/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MinimalRebuild>true</MinimalRebuild>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Debug/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;UNICODE;_UNICODE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TargetEnvironment>Win32</TargetEnvironment>
+ <TypeLibraryName>.\Debug/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MinimalRebuild>true</MinimalRebuild>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ <TargetMachine>MachineX86</TargetMachine>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">
+ <Midl>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <MkTypLibCompatible>true</MkTypLibCompatible>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <TypeLibraryName>.\Debug/mucc.tlb</TypeLibraryName>
+ <HeaderFileName>
+ </HeaderFileName>
+ </Midl>
+ <ClCompile>
+ <Optimization>Disabled</Optimization>
+ <AdditionalIncludeDirectories>../../../include;../ExternalAPI;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;MUCC_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
+ <RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
+ <PrecompiledHeaderOutputFile>$(IntDir)$(TargetName).pch</PrecompiledHeaderOutputFile>
+ <AssemblerListingLocation>
+ </AssemblerListingLocation>
+ <ObjectFileName>$(IntDir)</ObjectFileName>
+ <ProgramDataBaseFileName>$(IntDir)vc$(PlatformToolsetVersion).pdb</ProgramDataBaseFileName>
+ <WarningLevel>Level3</WarningLevel>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
+ <DisableSpecificWarnings>4996;%(DisableSpecificWarnings)</DisableSpecificWarnings>
+ </ClCompile>
+ <ResourceCompile>
+ <PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <Culture>0x0415</Culture>
+ </ResourceCompile>
+ <Link>
+ <AdditionalDependencies>odbc32.lib;odbccp32.lib;comctl32.lib;%(AdditionalDependencies)</AdditionalDependencies>
+ <OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <GenerateDebugInformation>true</GenerateDebugInformation>
+ <ProgramDatabaseFile>$(TargetDir)tlen_czaty.pdb</ProgramDatabaseFile>
+ <RandomizedBaseAddress>false</RandomizedBaseAddress>
+ <DataExecutionPrevention>
+ </DataExecutionPrevention>
+ <ImportLibrary>$(IntDir)$(TargetName).lib</ImportLibrary>
+ </Link>
+ <Bscmake>
+ <SuppressStartupBanner>true</SuppressStartupBanner>
+ <OutputFile>$(OutDir)$(TargetName).bsc</OutputFile>
+ </Bscmake>
+ </ItemDefinitionGroup>
+ <ItemGroup>
+ <ClCompile Include="AdminWindow.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="ChatContainer.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="ChatEvent.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="ChatGroup.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="ChatRoom.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="ChatUser.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="ChatWindow.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="FontList.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="HelperDialog.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="ManagerWindow.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="mucc.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="mucc_services.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="Options.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ <ClCompile Include="Utils.cpp">
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <AdditionalIncludeDirectories Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ClCompile>
+ </ItemGroup>
+ <ItemGroup>
+ <ClInclude Include="AdminWindow.h" />
+ <ClInclude Include="ChatContainer.h" />
+ <ClInclude Include="ChatEvent.h" />
+ <ClInclude Include="ChatGroup.h" />
+ <ClInclude Include="ChatRoom.h" />
+ <ClInclude Include="ChatUser.h" />
+ <ClInclude Include="ChatWindow.h" />
+ <ClInclude Include="FontList.h" />
+ <ClInclude Include="HelperDialog.h" />
+ <ClInclude Include="ManagerWindow.h" />
+ <ClInclude Include="mucc.h" />
+ <ClInclude Include="mucc_services.h" />
+ <ClInclude Include="Options.h" />
+ <ClInclude Include="resource.h" />
+ <ClInclude Include="Utils.h" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="icos\admin.ico" />
+ <None Include="icos\administration.ico" />
+ <None Include="icos\blank.ico" />
+ <None Include="icos\bold.ico" />
+ <None Include="icos\chat.ico" />
+ <None Include="icos\glowner.ico" />
+ <None Include="icos\invite.ico" />
+ <None Include="icos\italic.ico" />
+ <None Include="icos\message.ico" />
+ <None Include="icos\moderator.ico" />
+ <None Include="icos\next.ico" />
+ <None Include="icos\options.ico" />
+ <None Include="icos\owner.ico" />
+ <None Include="icos\prev.ico" />
+ <None Include="icos\r_anon.ico" />
+ <None Include="icos\r_memb.ico" />
+ <None Include="icos\r_mod.ico" />
+ <None Include="icos\registered.ico" />
+ <None Include="icos\search.ico" />
+ <None Include="icos\smile.ico" />
+ <None Include="icos\tlensmall.ico" />
+ <None Include="icos\underline.ico" />
+ </ItemGroup>
+ <ItemGroup>
+ <ResourceCompile Include="mucc.rc">
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release x64|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Unicode|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|Win32'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release Ansi|x64'">%(PreprocessorDefinitions)</PreprocessorDefinitions>
+ </ResourceCompile>
+ </ItemGroup>
+ <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+ <ImportGroup Label="ExtensionTargets">
+ </ImportGroup>
+</Project> \ No newline at end of file
diff --git a/protocols/Tlen/tlen_czaty/mucc_services.cpp b/protocols/Tlen/tlen_czaty/mucc_services.cpp
new file mode 100644
index 0000000000..0d4571a633
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/mucc_services.cpp
@@ -0,0 +1,140 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#include "mucc_services.h"
+#include "Utils.h"
+#include "HelperDialog.h"
+
+int MUCCQueryChatGroups(MUCCQUERYRESULT *queryResult)
+{
+ ManagerWindow *managerWnd=ManagerWindow::getWindow(queryResult->pszModule);
+ if (managerWnd!=NULL) {
+ managerWnd->queryResultGroups(queryResult);
+ }
+ return 1;
+}
+
+int MUCCQueryChatRooms(MUCCQUERYRESULT *queryResult)
+{
+ ManagerWindow *managerWnd=ManagerWindow::getWindow(queryResult->pszModule);
+ if (managerWnd!=NULL) {
+ managerWnd->queryResultRooms(queryResult);
+ }
+ return 1;
+}
+
+int MUCCQueryUserRooms(MUCCQUERYRESULT *queryResult)
+{
+ ManagerWindow *managerWnd=ManagerWindow::getWindow(queryResult->pszModule);
+ if (managerWnd!=NULL) {
+ managerWnd->queryResultUserRooms(queryResult);
+ }
+ return 1;
+}
+
+int MUCCQueryUserNicks(MUCCQUERYRESULT *queryResult)
+{
+ ManagerWindow *managerWnd=ManagerWindow::getWindow(queryResult->pszModule);
+ if (managerWnd!=NULL) {
+ managerWnd->queryResultUserNick(queryResult);
+ }
+ return 1;
+}
+
+INT_PTR MUCCQueryResult(WPARAM wParam, LPARAM lParam)
+{
+ MUCCQUERYRESULT *queryResult=(MUCCQUERYRESULT *)lParam;
+ ChatWindow * chatWindow = NULL;
+ switch (queryResult->iType) {
+ case MUCC_EVENT_QUERY_GROUPS:
+ MUCCQueryChatGroups(queryResult);
+ break;
+ case MUCC_EVENT_QUERY_ROOMS:
+ MUCCQueryChatRooms(queryResult);
+ break;
+ case MUCC_EVENT_QUERY_USER_ROOMS:
+ MUCCQueryUserRooms(queryResult);
+ break;
+ case MUCC_EVENT_QUERY_USER_NICKS:
+ MUCCQueryUserNicks(queryResult);
+ break;
+ case MUCC_EVENT_QUERY_CONTACTS:
+ case MUCC_EVENT_QUERY_USERS:
+ chatWindow=ChatWindow::getWindow(queryResult->pszModule, queryResult->pszParent);
+ if (chatWindow!=NULL) {
+ SendMessage(chatWindow->getHWND(), DM_CHAT_QUERY, (WPARAM) 0, (LPARAM) queryResult);
+ }
+ break;
+ }
+ return 0;
+}
+
+INT_PTR MUCCNewWindow(WPARAM wParam, LPARAM lParam)
+{
+ MUCCWINDOW *mucWindow = (MUCCWINDOW *) lParam;
+ if (mucWindow->iType == MUCC_WINDOW_CHATROOM) {
+ ChatWindow *chat = ChatWindow::getWindow(mucWindow->pszModule, mucWindow->pszID);
+ if (chat == NULL) {
+ chat = new ChatWindow(mucWindow);
+ }
+ } else if (mucWindow->iType == MUCC_WINDOW_CHATLIST) {
+ ManagerWindow *manager = ManagerWindow::getWindow(mucWindow->pszModule);
+ if (manager == NULL) {
+
+ }
+ //Utils::log("setting name: %s", mucWindow->pszModuleName);
+ manager->setModuleName(mucWindow->pszModuleName);
+ manager->start();
+ }
+ return 0;
+}
+
+INT_PTR MUCCEvent(WPARAM wParam, LPARAM lParam)
+{
+ MUCCEVENT* mucEvent = (MUCCEVENT *) lParam;
+ ChatWindow * chatWindow = NULL;
+ switch (mucEvent->iType) {
+ case MUCC_EVENT_STATUS:
+ case MUCC_EVENT_MESSAGE:
+ case MUCC_EVENT_ROOM_INFO:
+ case MUCC_EVENT_LEAVE:
+ case MUCC_EVENT_TOPIC:
+ chatWindow = ChatWindow::getWindow(mucEvent->pszModule, mucEvent->pszID);
+ if (chatWindow!=NULL) {
+ SendMessage(chatWindow->getHWND(), DM_CHAT_EVENT, (WPARAM) 0, (LPARAM) mucEvent);
+ }
+ break;
+ case MUCC_EVENT_ERROR:
+ chatWindow = ChatWindow::getWindow(mucEvent->pszModule, mucEvent->pszID);
+ if (chatWindow!=NULL) {
+ SendMessage(chatWindow->getHWND(), DM_CHAT_EVENT, (WPARAM) 0, (LPARAM) mucEvent);
+ } else {
+ HelperDialog::errorDlg(mucEvent);
+ }
+ break;
+ case MUCC_EVENT_INVITATION:
+ HelperDialog::acceptDlg(mucEvent);
+ break;
+ case MUCC_EVENT_JOIN:
+ HelperDialog::joinDlg(mucEvent);
+ break;
+ }
+ return 0;
+}
diff --git a/protocols/Tlen/tlen_czaty/mucc_services.h b/protocols/Tlen/tlen_czaty/mucc_services.h
new file mode 100644
index 0000000000..f1db38274b
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/mucc_services.h
@@ -0,0 +1,35 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef MUCCSERVICES_INCLUDED
+#define MUCCSERVICES_INCLUDED
+
+#include "mucc.h"
+#include "ManagerWindow.h"
+#include "ChatWindow.h"
+
+extern int MUCCServicesInit(WPARAM wParam, LPARAM lParam);
+
+extern INT_PTR MUCCQueryResult(WPARAM wParam, LPARAM lParam) ;
+extern INT_PTR MUCCNewWindow(WPARAM wParam, LPARAM lParam) ;
+extern INT_PTR MUCCEvent(WPARAM wParam, LPARAM lParam) ;
+
+#endif
+
diff --git a/protocols/Tlen/tlen_czaty/resource.h b/protocols/Tlen/tlen_czaty/resource.h
new file mode 100644
index 0000000000..c4d2f1945c
--- /dev/null
+++ b/protocols/Tlen/tlen_czaty/resource.h
@@ -0,0 +1,218 @@
+/*
+
+MUCC Group Chat GUI Plugin for Miranda IM
+Copyright (C) 2004 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#define IDI_CHAT 100
+#define IDI_ITALIC 101
+#define IDI_BOLD 102
+#define IDI_UNDERLINE 103
+#define IDI_OPTIONS 104
+#define IDI_OWNER 105
+#define IDI_ADMIN 106
+#define IDI_REGISTERED 107
+#define IDI_R_MODERATED 108
+#define IDI_R_MEMBERS 109
+#define IDI_R_ANONYMOUS 110
+#define IDI_SEARCH 111
+#define IDI_PREV 112
+#define IDI_NEXT 113
+#define IDI_BLANK 114
+#define IDI_INVITE 115
+#define IDI_ADMINISTRATION 116
+#define IDI_GLOBALOWNER 117
+#define IDI_SMILEY 118
+#define IDI_MESSAGE 119
+
+#define IDD_CHATMANAGER 150
+#define IDD_GROUPCHAT_LOG 151
+#define IDD_HELPER_JOIN 152
+#define IDD_HELPER_INPUT 153
+#define IDD_HELPER_INVITE 154
+#define IDD_HELPER_INVITE_ACCEPT 155
+#define IDD_HELPER_TOPIC 156
+#define IDD_OPTIONS 157
+#define IDD_OPT_POPUPS 158
+#define IDD_TAB_CHATROOMS 159
+#define IDD_TAB_MYROOMS 160
+#define IDD_TAB_MYNICKNAMES 161
+#define IDD_USER_ADMIN 162
+#define IDD_USER_KICK 163
+#define IDD_USER_ROLE 164
+#define IDD_USER_BROWSER 165
+#define IDD_GROUPCHAT_CONTAINER 166
+
+#define IDR_CHATOPTIONS 200
+#define IDR_CONTEXT 201
+
+#define IDC_FONTLIST 1000
+#define IDC_COLORINPUT 1001
+#define IDC_COLORBKG 1002
+#define IDC_COLORLIST 1003
+#define IDC_COLORTXT 1004
+#define IDC_CHOOSEFONT 1005
+#define IDC_FONTSGB 1006
+#define IDC_OPTIONSGB 1007
+#define IDC_LOGLIMITSPIN 1008
+#define IDC_LOGLIMIT 1009
+#define IDC_SENDONENTER 1010
+#define IDC_USETABS 1011
+#define IDC_ENABLEIEVIEW 1012
+#define IDC_REGISTER 1020
+#define IDC_NAME 1021
+#define IDC_FRAME 1037
+#define IDC_SIMPLE 1041
+#define IDC_PASSWORD 1050
+#define IDC_JID 1051
+#define IDC_COUNTRY 1060
+#define IDC_NICKNAME 1062
+#define IDC_MSG 1084
+#define IDC_TITLE 1089
+#define IDC_DESC 1090
+#define IDC_DELETE 1092
+#define IDC_LOAD 1093
+#define IDC_JOIN 1123
+#define IDC_ROOM 1124
+#define IDC_ROOM_LABEL 1125
+#define IDC_BROWSE 1126
+#define IDC_VSCROLL 1128
+#define IDC_NICK 1129
+#define IDC_NICK_LABEL 1130
+#define IDC_EDIT 1131
+#define IDC_TREELIST 1132
+#define IDC_LIST 1133
+#define IDC_HSPLIT 1134
+#define IDC_LOG 1136
+#define IDC_VSPLIT 1137
+#define IDC_SET 1140
+#define IDC_TABS 1141
+#define IDC_TOPIC 1141
+#define IDC_TOPIC_BUTTON 1142
+#define IDC_FONT 1143
+#define IDC_ENTER 1144
+#define IDC_CTRLENTER 1145
+#define IDC_FLASH 1148
+#define IDC_TIME 1156
+#define IDC_DATE 1157
+#define IDC_REASON 1171
+#define IDC_USER 1172
+#define IDC_INVITE 1173
+#define IDC_ACCEPT 1174
+#define IDC_FROM 1175
+#define IDC_DELAY 1180
+#define IDC_PREVIEW 1183
+#define IDC_ENABLEPOPUP 1184
+#define IDC_DELAY_PERMANENT 1185
+#define IDC_DELAY_CUSTOM 1186
+#define IDC_DELAY_POPUP 1187
+#define IDC_GROUP 1203
+#define IDC_BOLD 1204
+#define IDC_SMILEY 1205
+#define IDC_UNDERLINE 1205
+#define IDC_ITALIC 1206
+#define IDC_COLOR 1207
+#define IDC_OPTIONS 1208
+#define IDC_SMILEYBTN 1209
+#define IDC_CHECK_PERMANENT 1210
+#define IDC_CHECK_PUBLIC 1211
+#define IDC_CHECK_NICKNAMES 1212
+#define IDC_CHECK_MEMBERS 1213
+#define IDC_NEXT 1214
+#define IDC_PREV 1215
+#define IDC_FONTSIZE 1215
+#define IDC_SEARCH 1216
+#define IDC_REFRESH 1216
+#define IDC_REMOVE 1217
+#define IDC_KICK_OPTIONS 1218
+#define IDC_ROLE_OPTIONS 1219
+#define IDC_KICK 1220
+#define IDC_SET_ROLE 1221
+#define IDC_UPDATE 1313
+#define IDC_STATUS 1414
+#define IDC_PLAN 1415
+#define IDC_SHOW 1416
+
+#define IDC_PERSONALGROUP 1434
+#define IDC_EXTRAGROUP 1436
+
+#define ID_OPTIONMENU_SHOWNICKNAMES 40001
+#define ID_OPTIONMENU_MSGINNEWLINE 40002
+#define ID_OPTIONMENU_SHOWTIMESTAMP 40011
+#define ID_OPTIONMENU_SHOWDATE 40012
+#define ID_OPTIONMENU_SHOWSECONDS 40013
+#define ID_OPTIONMENU_USELONGDATE 40014
+#define ID_OPTIONMENU_FORMATFONT 40021
+#define ID_OPTIONMENU_FORMATSIZE 40022
+#define ID_OPTIONMENU_FORMATCOLOR 40023
+#define ID_OPTIONMENU_FORMATSTYLE 40024
+#define ID_OPTIONMENU_LOGMESSAGES 40031
+#define ID_OPTIONMENU_LOGJOINED 40032
+#define ID_OPTIONMENU_LOGLEFT 40033
+#define ID_OPTIONMENU_LOGTOPIC 40034
+#define ID_OPTIONMENU_FLASHMESSAGES 40035
+#define ID_OPTIONMENU_FLASHJOINED 40036
+#define ID_OPTIONMENU_FLASHLEFT 40037
+#define ID_OPTIONMENU_FLASHTOPIC 40038
+#define ID_OPTIONMENU_SAVEDEFAULT 40040
+#define ID_USERMENU_MESSAGE 40050
+#define ID_USERMENU_KICK_POPUP 40051
+#define ID_USERMENU_KICK_NO_BAN 40052
+#define ID_USERMENU_KICK_BAN_1_MIN 40053
+#define ID_USERMENU_KICK_BAN_5_MIN 40054
+#define ID_USERMENU_KICK_BAN_15_MIN 40055
+#define ID_USERMENU_KICK_BAN_30_MIN 40056
+#define ID_USERMENU_KICK_BAN_1_H 40057
+#define ID_USERMENU_KICK_BAN_6_H 40058
+#define ID_USERMENU_KICK_BAN_1_D 40059
+#define ID_USERMENU_KICK_BAN_3_D 40060
+#define ID_USERMENU_KICK_BAN_1_W 40061
+#define ID_USERMENU_KICK_BAN_2_W 40062
+#define ID_USERMENU_KICK_BAN_4_W 40063
+#define ID_USERMENU_RIGHTS_NO 40065
+#define ID_USERMENU_RIGHTS_MEMBER 40066
+#define ID_USERMENU_RIGHTS_ADMIN 40067
+#define ID_USERMENU_ADMINISTRATION 40070
+#define ID_USERMENU_UNBAN 40071
+#define ID_ADMINMENU_DESTROY 40080
+#define ID_ADMINMENU_ADMIN 40081
+#define ID_ADMINMENU_BROWSE 40082
+#define ID_ADMINMENU_SAVELOG 40083
+
+#define IDM_CUT 40000
+#define IDM_COPY 40001
+#define IDM_PASTE 40002
+#define IDM_UNDO 40003
+#define IDM_DELETE 40004
+#define IDM_REDO 40005
+#define IDM_COPYALL 40011
+#define IDM_SELECTALL 40012
+#define IDM_CLEAR 40013
+#define IDM_OPENNEW 40014
+#define IDM_OPENEXISTING 40015
+#define IDM_COPYLINK 40016
+
+// Next default values for new objects
+//
+#ifdef APSTUDIO_INVOKED
+#ifndef APSTUDIO_READONLY_SYMBOLS
+#define _APS_NEXT_RESOURCE_VALUE 205
+#define _APS_NEXT_COMMAND_VALUE 40090
+#define _APS_NEXT_CONTROL_VALUE 1217
+#define _APS_NEXT_SYMED_VALUE 101
+#endif
+#endif
diff --git a/protocols/Tlen/tlen_file.c b/protocols/Tlen/tlen_file.c
new file mode 100644
index 0000000000..9926a09aa6
--- /dev/null
+++ b/protocols/Tlen/tlen_file.c
@@ -0,0 +1,718 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include <io.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include "jabber_list.h"
+#include "tlen_p2p_old.h"
+
+extern int TlenFileCancel(PROTO_INTERFACE *ptr, HANDLE hContact, HANDLE hTransfer);
+
+
+static void TlenFileReceiveParse(TLEN_FILE_TRANSFER *ft)
+{
+ int i;
+ char *p;
+ TLEN_FILE_PACKET *rpacket, *packet;
+
+ rpacket = NULL;
+ if (ft->state == FT_CONNECTING) {
+ rpacket = TlenP2PPacketReceive(ft->s);
+ if (rpacket != NULL) {
+ p = rpacket->packet;
+ if (rpacket->type == TLEN_FILE_PACKET_FILE_LIST) { // list of files (length & name)
+ ft->fileCount = (int)(*((DWORD*)p));
+ ft->files = (char **) mir_alloc(sizeof(char *) * ft->fileCount);
+ ft->filesSize = (long *) mir_alloc(sizeof(long) * ft->fileCount);
+ ft->currentFile = 0;
+ ft->allFileTotalSize = 0;
+ ft->allFileReceivedBytes = 0;
+ p += sizeof(DWORD);
+ for (i=0;i<ft->fileCount;i++) {
+ ft->filesSize[i] = (long)(*((DWORD*)p));
+ ft->allFileTotalSize += ft->filesSize[i];
+ p += sizeof(DWORD);
+ ft->files[i] = (char *)mir_alloc(256);
+ memcpy(ft->files[i], p, 256);
+ p += 256;
+ }
+ if ((packet=TlenP2PPacketCreate(3*sizeof(DWORD))) == NULL) {
+ ft->state = FT_ERROR;
+ }
+ else {
+ TlenP2PPacketSetType(packet, TLEN_FILE_PACKET_FILE_LIST_ACK);
+ TlenP2PPacketSend(ft->s, packet);
+ TlenP2PPacketFree(packet);
+ ft->state = FT_INITIALIZING;
+ JabberLog(ft->proto, "Change to FT_INITIALIZING");
+ }
+ }
+ TlenP2PPacketFree(rpacket);
+ }
+ else {
+ ft->state = FT_ERROR;
+ }
+ }
+ else if (ft->state == FT_INITIALIZING) {
+ char *fullFileName;
+ if ((packet=TlenP2PPacketCreate(3*sizeof(DWORD))) != NULL) {
+ TlenP2PPacketSetType(packet, TLEN_FILE_PACKET_FILE_REQUEST); // file request
+ TlenP2PPacketPackDword(packet, ft->currentFile);
+ TlenP2PPacketPackDword(packet, 0);
+ TlenP2PPacketPackDword(packet, 0);
+ TlenP2PPacketSend(ft->s, packet);
+ TlenP2PPacketFree(packet);
+
+ fullFileName = (char *) mir_alloc(strlen(ft->szSavePath) + strlen(ft->files[ft->currentFile]) + 2);
+ strcpy(fullFileName, ft->szSavePath);
+ if (fullFileName[strlen(fullFileName)-1] != '\\')
+ strcat(fullFileName, "\\");
+ strcat(fullFileName, ft->files[ft->currentFile]);
+ ft->fileId = _open(fullFileName, _O_BINARY|_O_WRONLY|_O_CREAT|_O_TRUNC, _S_IREAD|_S_IWRITE);
+ ft->fileReceivedBytes = 0;
+ ft->fileTotalSize = ft->filesSize[ft->currentFile];
+ JabberLog(ft->proto, "Saving to [%s] [%d]", fullFileName, ft->filesSize[ft->currentFile]);
+ mir_free(fullFileName);
+ ft->state = FT_RECEIVING;
+ JabberLog(ft->proto, "Change to FT_RECEIVING");
+ }
+ else {
+ ft->state = FT_ERROR;
+ }
+ }
+ else if (ft->state == FT_RECEIVING) {
+ PROTOFILETRANSFERSTATUS pfts;
+ memset(&pfts, 0, sizeof(PROTOFILETRANSFERSTATUS));
+ pfts.cbSize = sizeof(PROTOFILETRANSFERSTATUS);
+ pfts.hContact = ft->hContact;
+ pfts.sending = FALSE;
+ pfts.files = ft->files;
+ pfts.totalFiles = ft->fileCount;
+ pfts.currentFileNumber = ft->currentFile;
+ pfts.totalBytes = ft->allFileTotalSize;
+ pfts.workingDir = NULL;
+ pfts.currentFile = ft->files[ft->currentFile];
+ pfts.currentFileSize = ft->filesSize[ft->currentFile];
+ pfts.currentFileTime = 0;
+ JabberLog(ft->proto, "Receiving data...");
+ while (ft->state == FT_RECEIVING) {
+ rpacket = TlenP2PPacketReceive(ft->s);
+ if (rpacket != NULL) {
+ p = rpacket->packet;
+ if (rpacket->type == TLEN_FILE_PACKET_FILE_DATA) { // file data
+ int writeSize;
+ writeSize = rpacket->len - 2 * sizeof(DWORD) ; // skip file offset
+ if (_write(ft->fileId, p + 2 * sizeof(DWORD), writeSize) != writeSize) {
+ ft->state = FT_ERROR;
+ }
+ else {
+ ft->fileReceivedBytes += writeSize;
+ ft->allFileReceivedBytes += writeSize;
+ pfts.totalProgress = ft->allFileReceivedBytes;
+ pfts.currentFileProgress = ft->fileReceivedBytes;
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM) &pfts);
+ }
+ }
+ else if (rpacket->type == TLEN_FILE_PACKET_END_OF_FILE) { // end of file
+ _close(ft->fileId);
+ JabberLog(ft->proto, "Finishing this file...");
+ if (ft->currentFile >= ft->fileCount-1) {
+ ft->state = FT_DONE;
+ }
+ else {
+ ft->currentFile++;
+ ft->state = FT_INITIALIZING;
+ JabberLog(ft->proto, "File received, advancing to the next file...");
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
+ }
+ }
+ TlenP2PPacketFree(rpacket);
+ }
+ else {
+ ft->state = FT_ERROR;
+ }
+ }
+ }
+}
+
+static void TlenFileReceivingConnection(JABBER_SOCKET hConnection, DWORD dwRemoteIP, void * pExtra)
+{
+ JABBER_SOCKET slisten;
+ TLEN_FILE_TRANSFER *ft;
+
+ TlenProtocol *proto = (TlenProtocol *)pExtra;
+ ft = TlenP2PEstablishIncomingConnection(proto, hConnection, LIST_FILE, TRUE);
+ if (ft != NULL) {
+ slisten = ft->s;
+ ft->s = hConnection;
+ JabberLog(ft->proto, "Set ft->s to %d (saving %d)", hConnection, slisten);
+ JabberLog(ft->proto, "Entering send loop for this file connection... (ft->s is hConnection)");
+ while (ft->state!=FT_DONE && ft->state!=FT_ERROR) {
+ TlenFileReceiveParse(ft);
+ }
+ if (ft->state==FT_DONE)
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ else
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ JabberLog(ft->proto, "Closing connection for this file transfer... (ft->s is now hBind)");
+ ft->s = slisten;
+ JabberLog(ft->proto, "ft->s is restored to %d", ft->s);
+ if (ft->s != hConnection) {
+ Netlib_CloseHandle(hConnection);
+ }
+ if (ft->hFileEvent != NULL)
+ SetEvent(ft->hFileEvent);
+ } else {
+ Netlib_CloseHandle(hConnection);
+ }
+}
+
+
+static void __cdecl TlenFileReceiveThread(TLEN_FILE_TRANSFER *ft)
+{
+ NETLIBOPENCONNECTION nloc;
+ JABBER_SOCKET s;
+ JabberLog(ft->proto, "Thread started: type=file_receive server='%s' port='%d'", ft->hostName, ft->wPort);
+ ft->mode = FT_RECV;
+ nloc.cbSize = NETLIBOPENCONNECTION_V1_SIZE;//sizeof(NETLIBOPENCONNECTION);
+ nloc.szHost = ft->hostName;
+ nloc.wPort = ft->wPort;
+ nloc.flags = 0;
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, ft, 0);
+ s = (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) ft->proto->hNetlibUser, (LPARAM) &nloc);
+ if (s != NULL) {
+ ft->s = s;
+ JabberLog(ft->proto, "Entering file receive loop");
+ TlenP2PEstablishOutgoingConnection(ft, TRUE);
+ while (ft->state!=FT_DONE && ft->state!=FT_ERROR) {
+ TlenFileReceiveParse(ft);
+ }
+ if (ft->s) {
+ Netlib_CloseHandle(s);
+ }
+ ft->s = NULL;
+ } else {
+ ft->pfnNewConnectionV2 = TlenFileReceivingConnection;
+ JabberLog(ft->proto, "Connection failed - receiving as server");
+ s = TlenP2PListen(ft);
+ if (s != NULL) {
+ HANDLE hEvent;
+ char *nick;
+ ft->s = s;
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ ft->hFileEvent = hEvent;
+ ft->currentFile = 0;
+ ft->state = FT_CONNECTING;
+ nick = JabberNickFromJID(ft->jid);
+ JabberSend(ft->proto, "<f t='%s' i='%s' e='7' a='%s' p='%d'/>", nick, ft->iqId, ft->localName, ft->wLocalPort);
+ mir_free(nick);
+ JabberLog(ft->proto, "Waiting for the file to be received...");
+ WaitForSingleObject(hEvent, INFINITE);
+ ft->hFileEvent = NULL;
+ CloseHandle(hEvent);
+ JabberLog(ft->proto, "Finish all files");
+ Netlib_CloseHandle(s);
+ } else {
+ ft->state = FT_ERROR;
+ }
+ }
+ JabberListRemove(ft->proto, LIST_FILE, ft->iqId);
+ if (ft->state==FT_DONE)
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ else {
+ char *nick;
+ nick = JabberNickFromJID(ft->jid);
+ JabberSend(ft->proto, "<f t='%s' i='%s' e='8'/>", nick, ft->iqId);
+ mir_free(nick);
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ }
+
+ JabberLog(ft->proto, "Thread ended: type=file_receive server='%s'", ft->hostName);
+ TlenP2PFreeFileTransfer(ft);
+}
+
+
+
+static void TlenFileSendParse(TLEN_FILE_TRANSFER *ft)
+{
+ int i;
+ char *p, *t;
+ int currentFile, numRead;
+ char *fileBuffer;
+ TLEN_FILE_PACKET *rpacket, *packet;
+
+
+ if (ft->state == FT_CONNECTING) {
+ char filename[256]; // Must be 256 (0x100)
+ if ((packet=TlenP2PPacketCreate(sizeof(DWORD)+(ft->fileCount*(sizeof(filename)+sizeof(DWORD))))) != NULL) {
+ // Must pause a bit, sending these two packets back to back
+ // will break the session because the receiver cannot take it :)
+ SleepEx(1000, TRUE);
+ TlenP2PPacketSetLen(packet, 0); // Reuse packet
+ TlenP2PPacketSetType(packet, TLEN_FILE_PACKET_FILE_LIST);
+ TlenP2PPacketPackDword(packet, (DWORD) ft->fileCount);
+ for (i=0; i<ft->fileCount; i++) {
+// struct _stat statbuf;
+// _stat(ft->files[i], &statbuf);
+// TlenP2PPacketPackDword(packet, statbuf.st_size);
+ TlenP2PPacketPackDword(packet, ft->filesSize[i]);
+ memset(filename, 0, sizeof(filename));
+ if ((t=strrchr(ft->files[i], '\\')) != NULL)
+ t++;
+ else
+ t = ft->files[i];
+ _snprintf(filename, sizeof(filename)-1, t);
+ TlenP2PPacketPackBuffer(packet, filename, sizeof(filename));
+ }
+ TlenP2PPacketSend(ft->s, packet);
+ TlenP2PPacketFree(packet);
+
+ ft->allFileReceivedBytes = 0;
+ ft->state = FT_INITIALIZING;
+ JabberLog(ft->proto, "Change to FT_INITIALIZING");
+ }
+ else {
+ ft->state = FT_ERROR;
+ }
+ }
+ else if (ft->state == FT_INITIALIZING) { // FT_INITIALIZING
+ rpacket = TlenP2PPacketReceive(ft->s);
+ JabberLog(ft->proto, "FT_INITIALIZING: recv %d", rpacket);
+ if (rpacket == NULL) {
+ ft->state = FT_ERROR;
+ return;
+ }
+ JabberLog(ft->proto, "FT_INITIALIZING: recv type %d", rpacket->type);
+ p = rpacket->packet;
+ // TYPE: TLEN_FILE_PACKET_FILE_LIST_ACK will be ignored
+ // LEN: 0
+ if (rpacket->type == TLEN_FILE_PACKET_FILE_LIST_ACK) {
+
+ }
+ // Then the receiver will request each file
+ // TYPE: TLEN_FILE_PACKET_REQUEST
+ // LEN:
+ // (DWORD) file number
+ // (DWORD) 0
+ // (DWORD) 0
+ else if (rpacket->type == TLEN_FILE_PACKET_FILE_REQUEST) {
+ PROTOFILETRANSFERSTATUS pfts;
+ //struct _stat statbuf;
+
+ currentFile = *((DWORD*)p);
+ if (currentFile != ft->currentFile) {
+ JabberLog(ft->proto, "Requested file (#%d) is invalid (must be %d)", currentFile, ft->currentFile);
+ ft->state = FT_ERROR;
+ }
+ else {
+ // _stat(ft->files[currentFile], &statbuf); // file size in statbuf.st_size
+ JabberLog(ft->proto, "Sending [%s] [%d]", ft->files[currentFile], ft->filesSize[currentFile]);
+ if ((ft->fileId=_open(ft->files[currentFile], _O_BINARY|_O_RDONLY)) < 0) {
+ JabberLog(ft->proto, "File cannot be opened");
+ ft->state = FT_ERROR;
+ }
+ else {
+ memset(&pfts, 0, sizeof(PROTOFILETRANSFERSTATUS));
+ pfts.cbSize = sizeof(PROTOFILETRANSFERSTATUS);
+ pfts.hContact = ft->hContact;
+ pfts.sending = TRUE;
+ pfts.files = ft->files;
+ pfts.totalFiles = ft->fileCount;
+ pfts.currentFileNumber = ft->currentFile;
+ pfts.totalBytes = ft->allFileTotalSize;
+ pfts.workingDir = NULL;
+ pfts.currentFile = ft->files[ft->currentFile];
+ pfts.currentFileSize = ft->filesSize[ft->currentFile]; //statbuf.st_size;
+ pfts.currentFileTime = 0;
+ ft->fileReceivedBytes = 0;
+ if ((packet = TlenP2PPacketCreate(2*sizeof(DWORD)+2048)) == NULL) {
+ ft->state = FT_ERROR;
+ }
+ else {
+ TlenP2PPacketSetType(packet, TLEN_FILE_PACKET_FILE_DATA);
+ fileBuffer = (char *) mir_alloc(2048);
+ JabberLog(ft->proto, "Sending file data...");
+ while ((numRead=_read(ft->fileId, fileBuffer, 2048)) > 0) {
+ TlenP2PPacketSetLen(packet, 0); // Reuse packet
+ TlenP2PPacketPackDword(packet, (DWORD) ft->fileReceivedBytes);
+ TlenP2PPacketPackDword(packet, 0);
+ TlenP2PPacketPackBuffer(packet, fileBuffer, numRead);
+ if (TlenP2PPacketSend(ft->s, packet)) {
+ ft->fileReceivedBytes += numRead;
+ ft->allFileReceivedBytes += numRead;
+ pfts.totalProgress = ft->allFileReceivedBytes;
+ pfts.currentFileProgress = ft->fileReceivedBytes;
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM) &pfts);
+ }
+ else {
+ ft->state = FT_ERROR;
+ break;
+ }
+ }
+ mir_free(fileBuffer);
+ _close(ft->fileId);
+ if (ft->state != FT_ERROR) {
+ if (ft->currentFile >= ft->fileCount-1)
+ ft->state = FT_DONE;
+ else {
+ ft->currentFile++;
+ ft->state = FT_INITIALIZING;
+ JabberLog(ft->proto, "File sent, advancing to the next file...");
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
+ }
+ }
+ JabberLog(ft->proto, "Finishing this file...");
+ TlenP2PPacketSetLen(packet, 0); // Reuse packet
+ TlenP2PPacketSetType(packet, TLEN_FILE_PACKET_END_OF_FILE);
+ TlenP2PPacketPackDword(packet, currentFile);
+ TlenP2PPacketSend(ft->s, packet);
+ TlenP2PPacketFree(packet);
+ }
+ }
+ }
+ TlenP2PPacketFree(rpacket);
+ }
+ else {
+ ft->state = FT_ERROR;
+ }
+ }
+}
+
+static void TlenFileSendingConnection(JABBER_SOCKET hConnection, DWORD dwRemoteIP, void * pExtra)
+{
+ JABBER_SOCKET slisten;
+ TLEN_FILE_TRANSFER *ft;
+ TlenProtocol *proto = (TlenProtocol *)pExtra;
+
+ ft = TlenP2PEstablishIncomingConnection(proto, hConnection, LIST_FILE, TRUE);
+ if (ft != NULL) {
+ slisten = ft->s;
+ ft->s = hConnection;
+ JabberLog(ft->proto, "Set ft->s to %d (saving %d)", hConnection, slisten);
+
+ JabberLog(ft->proto, "Entering send loop for this file connection... (ft->s is hConnection)");
+ while (ft->state!=FT_DONE && ft->state!=FT_ERROR) {
+ TlenFileSendParse(ft);
+ }
+ if (ft->state==FT_DONE)
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ else
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ JabberLog(ft->proto, "Closing connection for this file transfer... (ft->s is now hBind)");
+ ft->s = slisten;
+ JabberLog(ft->proto, "ft->s is restored to %d", ft->s);
+ if (ft->s != hConnection) {
+ Netlib_CloseHandle(hConnection);
+ }
+ if (ft->hFileEvent != NULL)
+ SetEvent(ft->hFileEvent);
+ } else {
+ Netlib_CloseHandle(hConnection);
+ }
+}
+
+int TlenFileCancelAll(TlenProtocol *proto)
+{
+ JABBER_LIST_ITEM *item;
+ HANDLE hEvent;
+ int i = 0;
+
+ while ((i=JabberListFindNext(proto, LIST_FILE, 0)) >=0 ) {
+ if ((item=JabberListGetItemPtrFromIndex(proto, i)) != NULL) {
+ TLEN_FILE_TRANSFER *ft = item->ft;
+ JabberListRemoveByIndex(proto, i);
+ if (ft != NULL) {
+ if (ft->s) {
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ JabberLog(ft->proto, "Closing ft->s = %d", ft->s);
+ ft->state = FT_ERROR;
+ Netlib_CloseHandle(ft->s);
+ ft->s = NULL;
+ if (ft->hFileEvent != NULL) {
+ hEvent = ft->hFileEvent;
+ ft->hFileEvent = NULL;
+ SetEvent(hEvent);
+ }
+ } else {
+ JabberLog(ft->proto, "freeing ft struct");
+ TlenP2PFreeFileTransfer(ft);
+ }
+ }
+ }
+ }
+ return 0;
+}
+
+static void __cdecl TlenFileSendingThread(TLEN_FILE_TRANSFER *ft)
+{
+ JABBER_SOCKET s = NULL;
+ HANDLE hEvent;
+ char *nick;
+
+ JabberLog(ft->proto, "Thread started: type=tlen_file_send");
+ ft->mode = FT_SEND;
+ ft->pfnNewConnectionV2 = TlenFileSendingConnection;
+ s = TlenP2PListen(ft);
+ if (s != NULL) {
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, ft, 0);
+ ft->s = s;
+ //JabberLog("ft->s = %d", s);
+ //JabberLog("fileCount = %d", ft->fileCount);
+
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ ft->hFileEvent = hEvent;
+ ft->currentFile = 0;
+ ft->state = FT_CONNECTING;
+
+ nick = JabberNickFromJID(ft->jid);
+ JabberSend(ft->proto, "<f t='%s' i='%s' e='6' a='%s' p='%d'/>", nick, ft->iqId, ft->localName, ft->wLocalPort);
+ mir_free(nick);
+ JabberLog(ft->proto, "Waiting for the file to be sent...");
+ WaitForSingleObject(hEvent, INFINITE);
+ ft->hFileEvent = NULL;
+ CloseHandle(hEvent);
+ JabberLog(ft->proto, "Finish all files");
+ Netlib_CloseHandle(s);
+ ft->s = NULL;
+ JabberLog(ft->proto, "ft->s is NULL");
+
+ if (ft->state == FT_SWITCH) {
+ NETLIBOPENCONNECTION nloc;
+ JABBER_SOCKET s;
+ JabberLog(ft->proto, "Sending as client...");
+ ft->state = FT_CONNECTING;
+ nloc.cbSize = NETLIBOPENCONNECTION_V1_SIZE;//sizeof(NETLIBOPENCONNECTION);
+ nloc.szHost = ft->hostName;
+ nloc.wPort = ft->wPort;
+ nloc.flags = 0;
+ s = (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) ft->proto->hNetlibUser, (LPARAM) &nloc);
+ if (s != NULL) {
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, ft, 0);
+ ft->s = s;
+ TlenP2PEstablishOutgoingConnection(ft, TRUE);
+ JabberLog(ft->proto, "Entering send loop for this file connection...");
+ while (ft->state!=FT_DONE && ft->state!=FT_ERROR) {
+ TlenFileSendParse(ft);
+ }
+ if (ft->state==FT_DONE)
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ else
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ JabberLog(ft->proto, "Closing connection for this file transfer... ");
+ Netlib_CloseHandle(s);
+ } else {
+ ft->state = FT_ERROR;
+ }
+ }
+ } else {
+ JabberLog(ft->proto, "Cannot allocate port to bind for file server thread, thread ended.");
+ ft->state = FT_ERROR;
+ }
+ JabberListRemove(ft->proto, LIST_FILE, ft->iqId);
+ switch (ft->state) {
+ case FT_DONE:
+ JabberLog(ft->proto, "Finish successfully");
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ break;
+ case FT_DENIED:
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_DENIED, ft, 0);
+ break;
+ default: // FT_ERROR:
+ nick = JabberNickFromJID(ft->jid);
+ JabberSend(ft->proto, "<f t='%s' i='%s' e='8'/>", nick, ft->iqId);
+ mir_free(nick);
+ JabberLog(ft->proto, "Finish with errors");
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ break;
+ }
+ JabberLog(ft->proto, "Thread ended: type=file_send");
+ TlenP2PFreeFileTransfer(ft);
+}
+
+
+TLEN_FILE_TRANSFER *TlenFileCreateFT(TlenProtocol *proto, const char *jid) {
+ TLEN_FILE_TRANSFER *ft;
+ ft = (TLEN_FILE_TRANSFER *) mir_alloc(sizeof(TLEN_FILE_TRANSFER));
+ memset(ft, 0, sizeof(TLEN_FILE_TRANSFER));
+ ft->proto = proto;
+ ft->jid = mir_strdup(jid);
+ return ft;
+}
+
+/*
+ * File transfer
+ */
+void TlenProcessF(XmlNode *node, ThreadData *info)
+{
+ TLEN_FILE_TRANSFER *ft;
+ CCSDATA ccs;
+ PROTORECVEVENT pre;
+ char *szBlob, *from, *p, *e;
+ char jid[128], szFilename[MAX_PATH];
+ int numFiles;
+ JABBER_LIST_ITEM *item;
+
+// if (!node->name || strcmp(node->name, "f")) return;
+ if (info == NULL) return;
+
+ if ((from=JabberXmlGetAttrValue(node, "f")) != NULL) {
+
+ if (strchr(from, '@') == NULL) {
+ _snprintf(jid, sizeof(jid), "%s@%s", from, info->server);
+ } else {
+ _snprintf(jid, sizeof(jid), "%s", from);
+ }
+ if ((e=JabberXmlGetAttrValue(node, "e")) != NULL) {
+
+ if (!strcmp(e, "1")) {
+ // FILE_RECV : e='1' : File transfer request
+ ft = TlenFileCreateFT(info->proto, jid);
+ ft->hContact = JabberHContactFromJID(info->proto, jid);
+
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL)
+ ft->iqId = mir_strdup(p);
+
+ szFilename[0] = '\0';
+ if ((p=JabberXmlGetAttrValue(node, "c")) != NULL) {
+ numFiles = atoi(p);
+ if (numFiles == 1) {
+ if ((p=JabberXmlGetAttrValue(node, "n")) != NULL) {
+ p = JabberTextDecode(p);
+ strncpy(szFilename, p, sizeof(szFilename));
+ mir_free(p);
+ } else {
+ strcpy(szFilename, Translate("1 File"));
+ }
+ }
+ else if (numFiles > 1) {
+ _snprintf(szFilename, sizeof(szFilename), Translate("%d Files"), numFiles);
+ }
+ }
+
+ if (szFilename[0]!='\0' && ft->iqId!=NULL) {
+ // blob is DWORD(*ft), ASCIIZ(filenames), ASCIIZ(description)
+ szBlob = (char *) mir_alloc(sizeof(DWORD) + strlen(szFilename) + 2);
+ *((PDWORD) szBlob) = (DWORD) ft;
+ strcpy(szBlob + sizeof(DWORD), szFilename);
+ szBlob[sizeof(DWORD) + strlen(szFilename) + 1] = '\0';
+ pre.flags = 0;
+ pre.timestamp = time(NULL);
+ pre.szMessage = szBlob;
+ pre.lParam = 0;
+ ccs.szProtoService = PSR_FILE;
+ ccs.hContact = ft->hContact;
+ ccs.wParam = 0;
+ ccs.lParam = (LPARAM) &pre;
+ JabberLog(ft->proto, "sending chainrecv");
+ CallService(MS_PROTO_CHAINRECV, 0, (LPARAM) &ccs);
+ mir_free(szBlob);
+ }
+ else {
+ // malformed <f/> request, reject
+ if (ft->iqId)
+ JabberSend(ft->proto, "<f i='%s' e='4' t='%s'/>", ft->iqId, from);
+ else
+ JabberSend(ft->proto, "<f e='4' t='%s'/>", from);
+ TlenP2PFreeFileTransfer(ft);
+ }
+ }
+ else if (!strcmp(e, "3")) {
+ // FILE_RECV : e='3' : invalid transfer error
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_FILE, p)) != NULL) {
+ if (item->ft != NULL) {
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, item->ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, item->ft, 0);
+ TlenFileCancel((PROTO_INTERFACE *)info->proto, NULL, item->ft);
+ }
+ JabberListRemove(info->proto, LIST_FILE, p);
+ }
+ }
+ }
+ else if (!strcmp(e, "4")) {
+ // FILE_SEND : e='4' : File sending request was denied by the remote client
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_FILE, p)) != NULL) {
+ if (!strcmp(item->ft->jid, jid)) {
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, item->ft->hContact, ACKTYPE_FILE, ACKRESULT_DENIED, item->ft, 0);
+ JabberListRemove(info->proto, LIST_FILE, p);
+ }
+ }
+ }
+ }
+ else if (!strcmp(e, "5")) {
+ // FILE_SEND : e='5' : File sending request was accepted
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_FILE, p)) != NULL) {
+ if (!strcmp(item->ft->jid, jid))
+ JabberForkThread((void (__cdecl *)(void*))TlenFileSendingThread, 0, item->ft);
+ }
+ }
+ }
+ else if (!strcmp(e, "6")) {
+ // FILE_RECV : e='6' : IP and port information to connect to get file
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_FILE, p)) != NULL) {
+ if ((p=JabberXmlGetAttrValue(node, "a")) != NULL) {
+ item->ft->hostName = mir_strdup(p);
+ if ((p=JabberXmlGetAttrValue(node, "p")) != NULL) {
+ item->ft->wPort = atoi(p);
+ JabberForkThread((void (__cdecl *)(void*))TlenFileReceiveThread, 0, item->ft);
+ }
+ }
+ }
+ }
+ }
+ else if (!strcmp(e, "7")) {
+ // FILE_RECV : e='7' : IP and port information to connect to send file
+ // in case the conection to the given server was not successful
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_FILE, p)) != NULL) {
+ if ((p=JabberXmlGetAttrValue(node, "a")) != NULL) {
+ if (item->ft->hostName!=NULL) mir_free(item->ft->hostName);
+ item->ft->hostName = mir_strdup(p);
+ if ((p=JabberXmlGetAttrValue(node, "p")) != NULL) {
+ item->ft->wPort = atoi(p);
+ item->ft->state = FT_SWITCH;
+ SetEvent(item->ft->hFileEvent);
+ }
+ }
+ }
+ }
+ }
+ else if (!strcmp(e, "8")) {
+ // FILE_RECV : e='8' : transfer error
+ if ((p=JabberXmlGetAttrValue(node, "i")) != NULL) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_FILE, p)) != NULL) {
+ item->ft->state = FT_ERROR;
+ if (item->ft->hFileEvent != NULL) {
+ SetEvent(item->ft->hFileEvent);
+ } else {
+ ProtoBroadcastAck(info->proto->iface.m_szModuleName, item->ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, item->ft, 0);
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/protocols/Tlen/tlen_file.h b/protocols/Tlen/tlen_file.h
new file mode 100644
index 0000000000..40527a2bcb
--- /dev/null
+++ b/protocols/Tlen/tlen_file.h
@@ -0,0 +1,34 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#ifndef _TLEN_FILE_H_
+#define _TLEN_FILE_H_
+
+#include <windows.h>
+#include "jabber.h"
+
+extern int TlenFileCancelAll(TlenProtocol *proto);
+extern void TlenProcessF(XmlNode *node, ThreadData *userdata);
+extern TLEN_FILE_TRANSFER *TlenFileCreateFT(TlenProtocol *proto, const char *jid);
+#endif
+
diff --git a/protocols/Tlen/tlen_muc.c b/protocols/Tlen/tlen_muc.c
new file mode 100644
index 0000000000..0b8e7534f5
--- /dev/null
+++ b/protocols/Tlen/tlen_muc.c
@@ -0,0 +1,1071 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "jabber_list.h"
+#include "jabber_iq.h"
+#include "resource.h"
+#include "tlen_muc.h"
+
+static int TlenMUCHandleEvent(void *ptr, WPARAM wParam, LPARAM lParam);
+static int TlenMUCQueryContacts(TlenProtocol *proto, const char *roomId);
+static int TlenMUCSendInvitation(TlenProtocol *proto, const char *roomID, const char *user);
+static int TlenMUCSendPresence(TlenProtocol *proto, const char *roomID, const char *nick, int desiredStatus);
+static int TlenMUCSendMessage(TlenProtocol *proto, MUCCEVENT *event);
+static int TlenMUCSendTopic(TlenProtocol *proto, MUCCEVENT *event);
+static int TlenMUCSendQuery(TlenProtocol *proto, int type, const char *parent, int page);
+
+static int isSelf(TlenProtocol *proto, const char *roomID, const char *nick)
+{
+ JABBER_LIST_ITEM *item;
+ int result;
+ result=0;
+ item = JabberListGetItemPtr(proto, LIST_CHATROOM, roomID);
+ if (item!=NULL) {
+ if (item->nick==NULL) {
+ if (!strcmp(nick, proto->threadData->username)) result = 1;
+ } else if (nick[0]=='~') {
+ if (!strcmp(nick+1, item->nick)) {
+ result = 1;
+ }
+ }
+ }
+ return result;
+}
+
+static int stringToHex(const char *str)
+{
+ int i, val;
+ val = 0;
+ for (i=0;i<2;i++) {
+ val <<= 4;
+ if (str[i]>='A' && str[i]<='F') {
+ val += 10 + str[i]-'A';
+ } else if (str[i]>='0' && str[i]<='9') {
+ val += str[i]-'0';
+ }
+ }
+ return val;
+
+}
+static char *getDisplayName(TlenProtocol *proto, const char *id)
+{
+ CONTACTINFO ci;
+ char jid[256];
+ HANDLE hContact;
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ _snprintf(jid, sizeof(jid), "%s@%s", id, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ if (((hContact=JabberHContactFromJID(proto, jid)) != NULL) || !strcmp(id, proto->threadData->username)) {
+ ZeroMemory(&ci, sizeof(ci));
+ ci.cbSize = sizeof(ci);
+ ci.hContact = hContact;
+ ci.szProto = (char *)proto->iface.m_szModuleName;
+ ci.dwFlag = CNF_DISPLAY;
+ if (!CallService(MS_CONTACT_GETCONTACTINFO, 0, (LPARAM) & ci)) {
+ if (ci.type == CNFT_ASCIIZ) {
+ if (ci.pszVal) {
+ char * str = mir_strdup((char *)ci.pszVal);
+ miranda_sys_free(ci.pszVal);
+ return str;
+ }
+ }
+ }
+ }
+ }
+ return mir_strdup(id);
+}
+
+BOOL TlenMUCInit(TlenProtocol *proto)
+{
+ HookEventObj_Ex(ME_MUCC_EVENT, proto, TlenMUCHandleEvent);
+ return 0;
+}
+static int TlenMUCHandleEvent(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact;
+ int id;
+ MUCCEVENT *mucce=(MUCCEVENT *) lParam;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (!strcmp(mucce->pszModule, proto->iface.m_szModuleName)) {
+ switch (mucce->iType) {
+ case MUCC_EVENT_INVITE:
+ TlenMUCSendInvitation(proto, mucce->pszID, mucce->pszNick);
+ break;
+ case MUCC_EVENT_MESSAGE:
+ TlenMUCSendMessage(proto, mucce);
+ break;
+ case MUCC_EVENT_TOPIC:
+ TlenMUCSendTopic(proto, mucce);
+ break;
+ case MUCC_EVENT_LEAVE:
+ TlenMUCSendPresence(proto, mucce->pszID, NULL, ID_STATUS_OFFLINE);
+ break;
+ case MUCC_EVENT_QUERY_GROUPS:
+ TlenMUCSendQuery(proto, 1, mucce->pszID, 0);
+ break;
+ case MUCC_EVENT_QUERY_ROOMS:
+ TlenMUCSendQuery(proto, 2, mucce->pszID, mucce->dwData);
+ break;
+ case MUCC_EVENT_QUERY_SEARCH:
+ TlenMUCSendQuery(proto, 3, mucce->pszName, 0);
+ break;
+ case MUCC_EVENT_QUERY_USERS:
+ switch (mucce->dwFlags) {
+ case MUCC_EF_USER_OWNER:
+ id = 1;
+ break;
+ case MUCC_EF_USER_ADMIN:
+ id = 2;
+ break;
+ case MUCC_EF_USER_MEMBER:
+ id = 3;
+ break;
+ case MUCC_EF_USER_BANNED:
+ id = 4;
+ break;
+ case MUCC_EF_USER_MODERATOR:
+ id = 6;
+ break;
+ default:
+ id = 0;
+ }
+ TlenMUCSendQuery(proto, 4, mucce->pszID, id);
+ break;
+ case MUCC_EVENT_REGISTER_NICK:
+ TlenMUCSendQuery(proto, 6, mucce->pszNick, 0);
+ break;
+ case MUCC_EVENT_REMOVE_NICK:
+ TlenMUCSendQuery(proto, 6, mucce->pszNick, 1);
+ break;
+ case MUCC_EVENT_REGISTER_ROOM:
+ id = JabberSerialNext(proto);
+ if (proto->isOnline) {
+ if (mucce->pszNick!=NULL) {
+ JabberSend(proto, "<p to='c' tp='c' id='"JABBER_IQID"%d' x='%d' n='%s' p='%s' nick='%s'/>", id, mucce->dwFlags | 0x10, mucce->pszName, mucce->pszID);
+ } else {
+ JabberSend(proto, "<p to='c' tp='c' id='"JABBER_IQID"%d' x='%d' n='%s' p='%s'/>", id, mucce->dwFlags | 0x10, mucce->pszName, mucce->pszID);
+ }
+ }
+ break;
+ case MUCC_EVENT_REMOVE_ROOM:
+ if (proto->isOnline) {
+ JabberSend(proto, "<p to='%s' type='d'/>", mucce->pszID);
+ JabberListRemove(proto, LIST_CHATROOM, mucce->pszID);
+ // TlenMUCSendPresence(mucce->pszID, NULL, ID_STATUS_OFFLINE);
+ }
+ break;
+ case MUCC_EVENT_KICK_BAN:
+ if (proto->isOnline) {
+ char *nick;
+ nick = JabberResourceFromJID(mucce->pszUID);
+ if (!isSelf(proto, mucce->pszID, nick)) {
+ char *reason = JabberTextEncode(mucce->pszText);
+ JabberSend(proto, "<p to='%s'><x><i i='%s' a='4' ex='%d' rs='%s'/></x></p>", mucce->pszID, nick, mucce->dwData, reason);
+ mir_free(reason);
+ }
+ mir_free(nick);
+ }
+ break;
+ case MUCC_EVENT_UNBAN:
+ if (proto->isOnline) {
+ char *nick;
+ nick = JabberResourceFromJID(mucce->pszUID);
+ if (!isSelf(proto, mucce->pszID, nick)) {
+ JabberSend(proto, "<p to='%s'><x><i i='%s' a='0'/></x></p>", mucce->pszID, nick);
+ }
+ mir_free(nick);
+ }
+ break;
+ case MUCC_EVENT_SET_USER_ROLE:
+ if (proto->isOnline) {
+ char *nick;
+ nick = JabberResourceFromJID(mucce->pszUID);
+ if (!isSelf(proto, mucce->pszID, nick)) {
+ if (mucce->dwFlags == MUCC_EF_USER_ADMIN) {
+ id = 2;
+ } else if (mucce->dwFlags == MUCC_EF_USER_MEMBER) {
+ id = 3;
+ } else {
+ id = 0;
+ }
+ JabberSend(proto, "<p to='%s'><x><i i='%s' a='%d' /></x></p>", mucce->pszID, nick, id);
+ }
+ mir_free(nick);
+ }
+ break;
+ case MUCC_EVENT_QUERY_USER_NICKS:
+ TlenMUCSendQuery(proto, 7, mucce->pszID, 0);
+ break;
+ case MUCC_EVENT_QUERY_USER_ROOMS:
+ TlenMUCSendQuery(proto, 8, mucce->pszID, 0);
+ break;
+ case MUCC_EVENT_QUERY_CONTACTS:
+ TlenMUCQueryContacts(proto, mucce->pszID);
+ break;
+ case MUCC_EVENT_JOIN:
+ if (proto->isOnline) {
+ if (mucce->pszID==NULL || strlen(mucce->pszID)==0) {
+ if (mucce->pszName==NULL || strlen(mucce->pszName)==0) { // create a new chat room
+ id = JabberSerialNext(proto);
+ JabberSend(proto, "<p to='c' tp='c' id='"JABBER_IQID"%d'/>", id);
+ } else { // find a chat room by name
+ TlenMUCSendQuery(proto, 3, mucce->pszName, 0);
+ }
+ } else { // join existing chat room
+ if (!TlenMUCCreateWindow(proto, mucce->pszID, mucce->pszName, mucce->dwFlags, mucce->pszNick, NULL)) {
+ TlenMUCSendPresence(proto, mucce->pszID, mucce->pszNick, ID_STATUS_ONLINE);
+ }
+ }
+ }
+ break;
+ case MUCC_EVENT_START_PRIV:
+ if (proto->isOnline) {
+ JABBER_LIST_ITEM *item;
+ item = JabberListGetItemPtr(proto, LIST_CHATROOM, mucce->pszID);
+ if (item!=NULL) {
+ char *nick;
+ nick = JabberResourceFromJID(mucce->pszUID);
+ if (!isSelf(proto, mucce->pszID, nick)) {
+ if (nick[0]=='~' || item->nick!=NULL) {
+ char str[256];
+ sprintf(str, "%s/%s", mucce->pszID, nick);
+ hContact = JabberDBCreateContact(proto, str, nick, TRUE); //(char *)mucce->pszUID
+ DBWriteContactSettingByte(hContact, proto->iface.m_szModuleName, "bChat", TRUE);
+ CallService(MS_MSG_SENDMESSAGE, (WPARAM) hContact, (LPARAM) NULL);
+ } else {
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ char str[512];
+ _snprintf(str, sizeof(str), "%s@%s", nick, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ hContact = JabberDBCreateContact(proto, str, nick, TRUE);
+ CallService(MS_MSG_SENDMESSAGE, (WPARAM) hContact, (LPARAM) NULL);
+ }
+ }
+ }
+ mir_free(nick);
+ }
+ }
+ break;
+ }
+ }
+ return 0;
+}
+
+int TlenMUCRecvInvitation(TlenProtocol *proto, const char *roomId, const char *roomName, const char *from, const char *reason)
+{
+ char *nick;
+ int ignore, ask, groupChatPolicy;
+ if (roomId == NULL) return 1;
+ groupChatPolicy = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "GroupChatPolicy", 0);
+ ask = TRUE;
+ ignore = FALSE;
+ if (groupChatPolicy == TLEN_MUC_ASK) {
+ ignore = FALSE;
+ ask = TRUE;
+ } else if (groupChatPolicy == TLEN_MUC_IGNORE_ALL) {
+ ignore = TRUE;
+ } else if (groupChatPolicy == TLEN_MUC_IGNORE_NIR) {
+ char jid[256];
+ JABBER_LIST_ITEM *item;
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ _snprintf(jid, sizeof(jid), "%s@%s", from, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ } else {
+ strcpy(jid, from);
+ }
+ ignore = !IsAuthorized(proto, jid);
+ ask = TRUE;
+ } else if (groupChatPolicy == TLEN_MUC_ACCEPT_IR) {
+ char jid[256];
+ JABBER_LIST_ITEM *item;
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ _snprintf(jid, sizeof(jid), "%s@%s", from, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ } else {
+ strcpy(jid, from);
+ }
+ item = JabberListGetItemPtr(proto, LIST_ROSTER, jid);
+ ask = !IsAuthorized(proto, jid);
+ ignore = FALSE;
+ } else if (groupChatPolicy == TLEN_MUC_ACCEPT_ALL) {
+ ask = FALSE;
+ ignore = FALSE;
+ }
+ if (!ignore) {
+ if (ask) {
+ MUCCEVENT mucce;
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.pszModule = proto->iface.m_szModuleName;
+ mucce.pszID = roomId;
+ mucce.pszName = roomName;
+ mucce.iType = MUCC_EVENT_INVITATION;
+ mucce.pszUID = from;
+ nick = getDisplayName(proto, from);
+ mucce.pszNick = nick;
+ mucce.pszText = reason;
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+ mir_free(nick);
+ } else {
+ if (!TlenMUCCreateWindow(proto, roomId, roomName, 0, NULL, NULL)) {
+ TlenMUCSendPresence(proto, roomId, NULL, ID_STATUS_ONLINE);
+ }
+ }
+ }
+ return 0;
+}
+
+int TlenMUCRecvPresence(TlenProtocol *proto, const char *from, int status, int flags, const char *kick)
+{
+ char str[512];
+// if (JabberListExist(LIST_CHATROOM, from)) {
+ char *nick, *roomId, *userId;
+ MUCCEVENT mucce;
+ roomId = JabberLoginFromJID(from);
+ userId = JabberResourceFromJID(from);
+ nick = getDisplayName(proto, userId);
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.pszModule = proto->iface.m_szModuleName;
+ mucce.pszID = roomId;
+ mucce.iType = MUCC_EVENT_STATUS;
+ mucce.pszUID = userId;//from;
+ mucce.pszNick = nick;
+ mucce.time = time(NULL);
+ mucce.bIsMe = isSelf(proto, roomId, userId);
+ mucce.dwData = status;
+ mucce.dwFlags = 0;
+ if (flags & USER_FLAGS_GLOBALOWNER) mucce.dwFlags |= MUCC_EF_USER_GLOBALOWNER;
+ if (flags & USER_FLAGS_OWNER) mucce.dwFlags |= MUCC_EF_USER_OWNER;
+ if (flags & USER_FLAGS_ADMIN) mucce.dwFlags |= MUCC_EF_USER_ADMIN;
+ if (flags & USER_FLAGS_REGISTERED) mucce.dwFlags |= MUCC_EF_USER_REGISTERED;
+ if (status == ID_STATUS_OFFLINE && mucce.bIsMe && kick!=NULL) {
+ mucce.iType = MUCC_EVENT_ERROR;
+ sprintf(str, Translate("You have been kicked. Reason: %s "), kick);
+ mucce.pszText = str;
+ }
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+ mir_free(roomId);
+ mir_free(userId);
+ mir_free(nick);
+// }
+ return 0;
+}
+
+int TlenMUCRecvMessage(TlenProtocol *proto, const char *from, long timestamp, XmlNode *bodyNode)
+{
+// if (JabberListExist(LIST_CHATROOM, from)) {
+ char *localMessage;
+ char *nick, *style, *roomId, *userId;
+ int iStyle;
+ MUCCEVENT mucce;
+ roomId = JabberLoginFromJID(from);
+ userId = JabberResourceFromJID(from);
+ nick = getDisplayName(proto, userId);
+ localMessage = JabberTextDecode(bodyNode->text);
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_MESSAGE;
+ mucce.pszID = roomId;
+ mucce.pszModule = proto->iface.m_szModuleName;
+ mucce.pszText = localMessage;
+ mucce.pszUID = userId;//from;
+ mucce.pszNick = nick;
+ mucce.time = timestamp;
+ mucce.bIsMe = isSelf(proto, roomId, userId);
+ mucce.dwFlags = 0;
+ mucce.iFontSize = 0;
+ style = JabberXmlGetAttrValue(bodyNode, "f");
+ if (style!=NULL) {
+ iStyle = atoi(style);
+ if (iStyle & 1) mucce.dwFlags |= MUCC_EF_FONT_BOLD;
+ if (iStyle & 2) mucce.dwFlags |= MUCC_EF_FONT_ITALIC;
+ if (iStyle & 4) mucce.dwFlags |= MUCC_EF_FONT_UNDERLINE;
+ }
+ style = JabberXmlGetAttrValue(bodyNode, "c");
+ if (style!=NULL && strlen(style)>5) {
+ iStyle = (stringToHex(style)<<16) | (stringToHex(style+2)<<8) | stringToHex(style+4);
+ } else {
+ iStyle = 0xFFFFFFFF;
+ }
+ mucce.color = (COLORREF) iStyle;
+ style = JabberXmlGetAttrValue(bodyNode, "s");
+ if (style!=NULL) {
+ iStyle = atoi(style);
+ } else {
+ iStyle = 0;
+ }
+ mucce.iFontSize = iStyle;
+ style = JabberXmlGetAttrValue(bodyNode, "n");
+ if (style!=NULL) {
+ iStyle = atoi(style)-1;
+ } else {
+ iStyle = 0;
+ }
+ mucce.iFont = iStyle;
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+ mir_free(roomId);
+ mir_free(userId);
+ mir_free(nick);
+ mir_free(localMessage);
+// }
+ return 0;
+}
+int TlenMUCRecvTopic(TlenProtocol *proto, const char *from, const char *subject)
+{
+// if (JabberListExist(LIST_CHATROOM, from)) {
+ MUCCEVENT mucce;
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_TOPIC;
+ mucce.pszID = from;
+ mucce.pszModule = proto->iface.m_szModuleName;
+ mucce.pszText = subject;
+ mucce.time = time(NULL);
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+// }
+ return 0;
+}
+
+int TlenMUCRecvError(TlenProtocol *proto, const char *from, XmlNode *errorNode)
+{
+ int errCode;
+ char str[512];
+ JABBER_LIST_ITEM *item;
+ MUCCEVENT mucce;
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_ERROR;
+ mucce.pszID = from;
+ mucce.pszModule = proto->iface.m_szModuleName;
+ errCode = atoi(JabberXmlGetAttrValue(errorNode, "code"));
+ switch (errCode) {
+ case 403:
+ sprintf(str, Translate("You cannot join this chat room, because you are banned."));
+ break;
+ case 404:
+ sprintf(str, Translate("Chat room not found."));
+ break;
+ case 407:
+ sprintf(str, Translate("This is a private chat room and you are not one of the members."));
+ break;
+ case 408:
+ sprintf(str, Translate("You cannot send any message unless you join this chat room."));
+ break;
+ case 410:
+ sprintf(str, Translate("Chat room with already created."));
+ break;
+ case 411:
+ sprintf(str, Translate("Nickname '%s' is already registered."),
+ JabberXmlGetAttrValue(errorNode, "n"));
+ break;
+ case 412:
+ sprintf(str, Translate("Nickname already in use, please try another one. Hint: '%s' is free."),
+ JabberXmlGetAttrValue(errorNode, "free"));
+ break;
+ case 413:
+ sprintf(str, Translate("You cannot register more than %s nicknames."),
+ JabberXmlGetAttrValue(errorNode, "num"));
+ break;
+ case 414:
+ sprintf(str, Translate("You cannot create more than %s chat rooms."),
+ JabberXmlGetAttrValue(errorNode, "num"));
+ break;
+ case 415:
+ sprintf(str, Translate("You cannot join more than %s chat rooms."),
+ JabberXmlGetAttrValue(errorNode, "num"));
+ break;
+ case 601:
+ sprintf(str, Translate("Anonymous nicknames are not allowed in this chat room."));
+ break;
+ default:
+ sprintf(str, Translate("Unknown error code : %d"), errCode);
+ break;
+ }
+ mucce.pszText = str;
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+ if (proto->isOnline) {
+ switch (errCode) {
+ case 412:
+ item = JabberListGetItemPtr(proto, LIST_CHATROOM, from);
+ if (item!=NULL) {
+ mucce.iType = MUCC_EVENT_JOIN;
+ mucce.dwFlags = MUCC_EF_ROOM_NICKNAMES;
+ mucce.pszModule = proto->iface.m_szModuleName;
+ mucce.pszID = from;
+ mucce.pszName = item->roomName;
+ mucce.pszNick = JabberXmlGetAttrValue(errorNode, "free");
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+ }
+ break;
+ case 601:
+ item = JabberListGetItemPtr(proto, LIST_CHATROOM, from);
+ if (item!=NULL) {
+ mucce.iType = MUCC_EVENT_JOIN;
+ mucce.dwFlags = 0;
+ mucce.pszModule = proto->iface.m_szModuleName;
+ mucce.pszID = from;
+ mucce.pszName = item->roomName;
+ mucce.pszNick = NULL;
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+ }
+ break;
+ }
+ }
+ return 1;
+}
+static int TlenMUCSendInvitation(TlenProtocol *proto, const char *roomID, const char *user)
+{
+ if (!proto->isOnline) {
+ return 1;
+ }
+ JabberSend(proto, "<m to='%s'><x><inv to='%s'><r></r></inv></x></m>", roomID, user);
+ return 0;
+}
+
+static int TlenMUCSendPresence(TlenProtocol *proto, const char *roomID, const char *nick, int desiredStatus)
+{
+ char str[512];
+ char *jid;
+ JABBER_LIST_ITEM *item;
+ if (!proto->isOnline) {
+ return 1;
+ }
+ if (nick!=NULL) {
+ _snprintf(str, sizeof(str), "%s/%s", roomID, nick);
+ } else {
+ _snprintf(str, sizeof(str), "%s", roomID);
+ }
+ if ((jid = JabberTextEncode(str))!=NULL) {
+ switch (desiredStatus) {
+ case ID_STATUS_ONLINE:
+ JabberSend(proto, "<p to='%s'/>", jid);
+ item = JabberListGetItemPtr(proto, LIST_CHATROOM, roomID);
+ if (item!=NULL) {
+ if (item->nick!=NULL) mir_free(item->nick);
+ item->nick = NULL;
+ if (nick!=NULL) {
+ item->nick = mir_strdup(nick);
+ }
+ }
+ break;
+ default:
+ item = JabberListGetItemPtr(proto, LIST_CHATROOM, roomID);
+ if (item!=NULL) {
+ JabberSend(proto, "<p to='%s'><s>unavailable</s></p>", jid);
+ JabberListRemove(proto, LIST_CHATROOM, roomID);
+ }
+ break;
+ }
+ mir_free(jid);
+ }
+ return 0;
+}
+
+static int TlenMUCSendMessage(TlenProtocol *proto, MUCCEVENT *event)
+{
+ char *msg, *jid;
+ int style;
+
+ if (!proto->isOnline) {
+ return 1;
+ }
+ if ((msg = JabberTextEncode(event->pszText))!=NULL) {
+ if ((jid = JabberTextEncode(event->pszID))!=NULL) {
+ style = 0;
+ if (event->dwFlags & MUCC_EF_FONT_BOLD) style |=1;
+ if (event->dwFlags & MUCC_EF_FONT_ITALIC) style |=2;
+ if (event->dwFlags & MUCC_EF_FONT_UNDERLINE) style |=4;
+ JabberSend(proto, "<m to='%s'><b n='%d' s='%d' f='%d' c='%06X'>%s</b></m>", jid, event->iFont+1, event->iFontSize, style, event->color, msg);
+ mir_free(jid);
+ }
+ mir_free(msg);
+ }
+ return 0;
+}
+
+static int TlenMUCSendTopic(TlenProtocol *proto, MUCCEVENT *event)
+{
+ char *msg, *jid;
+ if (!proto->isOnline) {
+ return 1;
+ }
+ if ((msg = JabberTextEncode(event->pszText))!=NULL) {
+ if ((jid = JabberTextEncode(event->pszID))!=NULL) {
+ JabberSend(proto, "<m to='%s'><subject>%s</subject></m>", jid, msg);
+ mir_free(jid);
+ }
+ mir_free(msg);
+ }
+ return 0;
+}
+
+static int TlenMUCSendQuery(TlenProtocol *proto, int type, const char *parent, int page)
+{
+ if (!proto->isOnline) {
+ return 1;
+ }
+ if (type==3) { // find chat room by name
+ char serialId[32];
+ JABBER_LIST_ITEM *item;
+ sprintf(serialId, JABBER_IQID"%d", JabberSerialNext(proto));
+ item = JabberListAdd(proto, LIST_SEARCH, serialId);
+ item->roomName = mir_strdup(parent);
+ JabberSend(proto, "<iq to='c' type='3' n='%s' id='%s'/>", parent, serialId);
+ } else {
+ if (parent==NULL) {
+ JabberSend(proto, "<iq to='c' type='%d'/>", type);
+ } else { // 1 - groups, 2 - chat rooms, 7 - user nicks, 8 - user rooms
+ if (type==1 || (type==2 && page==0) || type==7 || type==8) {
+ JabberSend(proto, "<iq to='c' type='%d' p='%s'/>", type, parent);
+ } else if (type==2) {
+ JabberSend(proto, "<iq to='c' type='%d' p='%s' n='%d'/>", type, parent, page);
+ } else if (type==6) {
+ if (page) {
+ JabberSend(proto, "<iq to='c' type='%d' n='%s' k='u'/>", type, parent);
+ } else {
+ JabberSend(proto, "<iq to='c' type='%d' n='%s'/>", type, parent);
+ }
+ } else if (type==4) { // list of users, admins etc.
+ JabberSend(proto, "<iq to='%s' type='%d' k='%d'/>", parent, type, page);
+ }
+ }
+ }
+ return 0;
+}
+
+int TlenMUCCreateWindow(TlenProtocol *proto, const char *roomID, const char *roomName, int roomFlags, const char *nick, const char *iqId)
+{
+ JABBER_LIST_ITEM *item;
+ MUCCWINDOW mucw;
+ if (!proto->isOnline || roomID==NULL) {
+ return 1;
+ }
+ if (JabberListExist(proto, LIST_CHATROOM, roomID)) {
+ return 0;
+ }
+ item = JabberListAdd(proto, LIST_CHATROOM, roomID);
+ if (roomName!=NULL) {
+ item->roomName = mir_strdup(roomName);
+ }
+ if (nick!=NULL) {
+ item->nick = mir_strdup(nick);
+ }
+ mucw.cbSize = sizeof(MUCCWINDOW);
+ mucw.iType = MUCC_WINDOW_CHATROOM;
+ mucw.pszModule = proto->iface.m_szModuleName;
+ mucw.pszModuleName = proto->iface.m_szProtoName;
+ mucw.pszID = roomID;
+ mucw.pszName = roomName;
+ mucw.pszNick = nick;
+ mucw.dwFlags = roomFlags;
+ mucw.pszStatusbarText = "hello";
+ CallService(MS_MUCC_NEW_WINDOW, 0, (LPARAM) &mucw);
+ if (iqId != NULL) {
+ item = JabberListGetItemPtr(proto, LIST_INVITATIONS, iqId);
+ if (item !=NULL) {
+ TlenMUCSendInvitation(proto, roomID, item->nick);
+ }
+ JabberListRemove(proto, LIST_INVITATIONS, iqId);
+ }
+ return 0;
+}
+
+static void TlenMUCFreeQueryResult(MUCCQUERYRESULT *result)
+{ int i;
+ for (i=0; i<result->iItemsNum; i++) {
+ if (result->pItems[i].pszID != NULL) {
+ mir_free((char *) result->pItems[i].pszID);
+ }
+ if (result->pItems[i].pszName != NULL) {
+ mir_free((char *) result->pItems[i].pszName);
+ }
+ if (result->pItems[i].pszNick != NULL) {
+ mir_free((char *) result->pItems[i].pszNick);
+ }
+ if (result->pItems[i].pszText != NULL) {
+ mir_free((char *) result->pItems[i].pszText);
+ }
+ }
+ mir_free((MUCCQUERYITEM *)result->pItems);
+}
+
+void TlenIqResultChatGroups(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *lNode, *itemNode;
+ char *p, *n, *id, *f;
+ int i, j;
+ MUCCQUERYRESULT queryResult;
+
+ if ((lNode=JabberXmlGetChild(iqNode, "l")) == NULL) return;
+ p = JabberXmlGetAttrValue(iqNode, "p");
+ if (p==NULL) {
+ p="";
+ }
+ p = JabberTextDecode(p);
+ queryResult.cbSize = sizeof (MUCCQUERYRESULT);
+ queryResult.iType = MUCC_EVENT_QUERY_GROUPS;
+ queryResult.pszModule = proto->iface.m_szModuleName;
+ queryResult.pszParent = p;
+ queryResult.pItems = mir_alloc(sizeof(MUCCQUERYITEM) * lNode->numChild);
+ memset(queryResult.pItems, 0, sizeof(MUCCQUERYITEM) * lNode->numChild);
+ for (i=j=0; i<lNode->numChild; i++) {
+ itemNode = lNode->child[i];
+ if (!strcmp(itemNode->name, "i")) {
+ queryResult.pItems[j].iCount = 0;
+ if ((f = JabberXmlGetAttrValue(itemNode, "f")) != NULL) {
+ queryResult.pItems[j].iCount = !strcmp(f, "3");
+ }
+ n = JabberXmlGetAttrValue(itemNode, "n");
+ id = JabberXmlGetAttrValue(itemNode, "i");
+ if (n != NULL && id != NULL) {
+ queryResult.pItems[j].pszID = JabberTextDecode(id);
+ queryResult.pItems[j].pszName = JabberTextDecode(n);
+ j++;
+ }
+ }
+ }
+ queryResult.iItemsNum = j;
+ CallService(MS_MUCC_QUERY_RESULT, 0, (LPARAM) &queryResult);
+ TlenMUCFreeQueryResult(&queryResult);
+ mir_free(p);
+}
+
+void TlenIqResultChatRooms(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *lNode, *itemNode;
+ char *id, *c, *n, *x, *p, *px, *pn;
+ int i, j;
+ MUCCQUERYRESULT queryResult;
+
+ if ((lNode=JabberXmlGetChild(iqNode, "l")) == NULL) return;
+ if ((p = JabberXmlGetAttrValue(iqNode, "p")) == NULL) return;
+ pn = JabberXmlGetAttrValue(lNode, "n");
+ if (pn == NULL) pn = "0";
+ px = JabberXmlGetAttrValue(lNode, "x");
+ if (px == NULL) px = "0";
+ p = JabberTextDecode(p);
+ queryResult.cbSize = sizeof (MUCCQUERYRESULT);
+ queryResult.iType = MUCC_EVENT_QUERY_ROOMS;
+ queryResult.pszModule = proto->iface.m_szModuleName;
+ queryResult.pszParent = p;
+ queryResult.pItems = mir_alloc(sizeof(MUCCQUERYITEM) * lNode->numChild);
+ memset(queryResult.pItems, 0, sizeof(MUCCQUERYITEM) * lNode->numChild);
+ queryResult.iPage = atoi(pn);
+ queryResult.iLastPage = atoi(px)&2?1:0;
+ for (i=j=0; i<lNode->numChild; i++) {
+ itemNode = lNode->child[i];
+ if (!strcmp(itemNode->name, "i")) {
+ n = JabberXmlGetAttrValue(itemNode, "n");
+ c = JabberXmlGetAttrValue(itemNode, "c");
+ x = JabberXmlGetAttrValue(itemNode, "x");
+ if ((id=JabberXmlGetAttrValue(itemNode, "i")) != NULL) {
+ queryResult.pItems[j].pszID = JabberTextDecode(id);
+ queryResult.pItems[j].pszName = JabberTextDecode(n);
+ queryResult.pItems[j].iCount = atoi(c);
+ queryResult.pItems[j].dwFlags = atoi(x);
+ j++;
+ }
+ }
+ }
+ queryResult.iItemsNum = j;
+ CallService(MS_MUCC_QUERY_RESULT, 0, (LPARAM) &queryResult);
+ TlenMUCFreeQueryResult(&queryResult);
+ mir_free(p);
+}
+void TlenIqResultUserRooms(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *lNode, *itemNode;
+ char *id, *n;
+ int i, j;
+ MUCCQUERYRESULT queryResult;
+ if ((lNode=JabberXmlGetChild(iqNode, "l")) == NULL) return;
+ queryResult.cbSize = sizeof (MUCCQUERYRESULT);
+ queryResult.iType = MUCC_EVENT_QUERY_USER_ROOMS;
+ queryResult.pszModule = proto->iface.m_szModuleName;
+ queryResult.pItems = mir_alloc(sizeof(MUCCQUERYITEM) * lNode->numChild);
+ memset(queryResult.pItems, 0, sizeof(MUCCQUERYITEM) * lNode->numChild);
+ for (i=j=0; i<lNode->numChild; i++) {
+ itemNode = lNode->child[i];
+ if (!strcmp(itemNode->name, "i")) {
+ n = JabberXmlGetAttrValue(itemNode, "n");
+ id = JabberXmlGetAttrValue(itemNode, "i");
+ if (n != NULL && id != NULL) {
+ queryResult.pItems[j].pszID = JabberTextDecode(id);
+ queryResult.pItems[j].pszName = JabberTextDecode(n);
+ j++;
+ }
+ }
+ }
+ queryResult.iItemsNum = j;
+ CallService(MS_MUCC_QUERY_RESULT, 0, (LPARAM) &queryResult);
+ TlenMUCFreeQueryResult(&queryResult);
+}
+void TlenIqResultUserNicks(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *lNode, *itemNode;
+ char *n;
+ int i, j;
+ MUCCQUERYRESULT queryResult;
+ if ((lNode=JabberXmlGetChild(iqNode, "l")) == NULL) return;
+ queryResult.cbSize = sizeof (MUCCQUERYRESULT);
+ queryResult.iType = MUCC_EVENT_QUERY_USER_NICKS;
+ queryResult.pszModule = proto->iface.m_szModuleName;
+ queryResult.pItems = mir_alloc(sizeof(MUCCQUERYITEM) * lNode->numChild);
+ memset(queryResult.pItems, 0, sizeof(MUCCQUERYITEM) * lNode->numChild);
+ for (i=j=0; i<lNode->numChild; i++) {
+ itemNode = lNode->child[i];
+ if (!strcmp(itemNode->name, "i")) {
+ n = JabberXmlGetAttrValue(itemNode, "n");
+ queryResult.pItems[j].pszID = NULL;//JabberTextDecode(n);
+ queryResult.pItems[j].pszName = JabberTextDecode(n);
+ j++;
+ }
+ }
+ queryResult.iItemsNum = j;
+ CallService(MS_MUCC_QUERY_RESULT, 0, (LPARAM) &queryResult);
+ TlenMUCFreeQueryResult(&queryResult);
+}
+void TlenIqResultChatRoomUsers(TlenProtocol *proto, XmlNode *iqNode)
+{
+ XmlNode *lNode, *itemNode;
+ char *id, *n;
+ int i, j;
+ MUCCQUERYRESULT queryResult;
+ if ((lNode=JabberXmlGetChild(iqNode, "l")) == NULL) return;
+ if ((id=JabberXmlGetAttrValue(iqNode, "from")) == NULL) return;
+ queryResult.cbSize = sizeof (MUCCQUERYRESULT);
+ queryResult.iType = MUCC_EVENT_QUERY_USERS;
+ queryResult.pszModule = proto->iface.m_szModuleName;
+ queryResult.pszParent = id;
+ queryResult.pItems = mir_alloc(sizeof(MUCCQUERYITEM) * lNode->numChild);
+ memset(queryResult.pItems, 0, sizeof(MUCCQUERYITEM) * lNode->numChild);
+ for (i=j=0; i<lNode->numChild; i++) {
+ itemNode = lNode->child[i];
+ if (!strcmp(itemNode->name, "i")) {
+ id = JabberXmlGetAttrValue(itemNode, "i");
+ if (id != NULL) {
+ queryResult.pItems[j].pszID = JabberTextDecode(id);
+ n = JabberXmlGetAttrValue(itemNode, "n");
+ if (n!=NULL) {
+ queryResult.pItems[j].pszName = JabberTextDecode(n);
+ }
+ n = JabberXmlGetAttrValue(itemNode, "a");
+ if (n!=NULL) {
+ queryResult.pItems[j].pszNick = JabberTextDecode(n);
+ }
+ n = JabberXmlGetAttrValue(itemNode, "r");
+ if (n!=NULL) {
+ queryResult.pItems[j].pszText = JabberTextDecode(n);
+ }
+ n = JabberXmlGetAttrValue(itemNode, "e");
+ if (n!=NULL) {
+ queryResult.pItems[j].iCount = atoi(n);
+ }
+ n = JabberXmlGetAttrValue(itemNode, "s");
+ if (n!=NULL) {
+ queryResult.pItems[j].dwFlags = atoi(n);
+ }
+ j++;
+ }
+ }
+ }
+ queryResult.iItemsNum = j;
+ CallService(MS_MUCC_QUERY_RESULT, 0, (LPARAM) &queryResult);
+ TlenMUCFreeQueryResult(&queryResult);
+}
+
+void TlenIqResultRoomSearch(TlenProtocol *proto, XmlNode *iqNode)
+{
+ char *iqId, *id;
+ JABBER_LIST_ITEM *item;
+ iqId=JabberXmlGetAttrValue(iqNode, "id");
+ item=JabberListGetItemPtr(proto, LIST_SEARCH, iqId);
+ if ((id=JabberXmlGetAttrValue(iqNode, "i")) != NULL) {
+ MUCCEVENT mucce;
+ id = JabberTextDecode(id);
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_JOIN;
+ mucce.pszModule = proto->iface.m_szModuleName;
+ mucce.pszID = id;
+ mucce.pszName = id;
+ if (item!=NULL) {
+ mucce.pszName = item->roomName;
+ }
+ mucce.pszNick = NULL;
+ mucce.dwFlags = MUCC_EF_ROOM_NICKNAMES;
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+ mir_free(id);
+ }
+ JabberListRemove(proto, LIST_SEARCH, iqId);
+}
+
+void TlenIqResultRoomInfo(TlenProtocol *proto, XmlNode *iqNode)
+{
+ char *id, *name, *group, *flags;
+ if ((id=JabberXmlGetAttrValue(iqNode, "from")) != NULL) {
+ if ((name=JabberXmlGetAttrValue(iqNode, "n")) != NULL) {
+ MUCCEVENT mucce;
+ group = JabberXmlGetAttrValue(iqNode, "cn");
+ flags = JabberXmlGetAttrValue(iqNode, "x");
+ id = JabberTextDecode(id);
+ name = JabberTextDecode(name);
+ mucce.cbSize = sizeof(MUCCEVENT);
+ mucce.iType = MUCC_EVENT_ROOM_INFO;
+ mucce.pszModule = proto->iface.m_szModuleName;
+ mucce.pszID = id;
+ mucce.pszName = name;
+ mucce.dwFlags = atoi(flags);
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) &mucce);
+ mir_free(id);
+ mir_free(name);
+ }
+ }
+}
+
+
+typedef struct {
+ TlenProtocol *proto;
+ char *roomId;
+} MUCSENDQUERYTHREADDATA;
+
+static void __cdecl TlenMUCCSendQueryResultThread(void *ptr)
+{
+ HANDLE hContact;
+ MUCCQUERYRESULT queryResult;
+ DBVARIANT dbv;
+ MUCSENDQUERYTHREADDATA* threadData = (MUCSENDQUERYTHREADDATA*)ptr;
+ queryResult.cbSize = sizeof (MUCCQUERYRESULT);
+ queryResult.iType = MUCC_EVENT_QUERY_CONTACTS;
+ queryResult.pszModule = threadData->proto->iface.m_szModuleName;
+ queryResult.pszParent = threadData->roomId;
+ queryResult.iItemsNum = 0;
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ while (hContact != NULL) {
+ char *str = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if(str!=NULL && !strcmp(str, threadData->proto->iface.m_szModuleName)) {
+ if (!DBGetContactSettingByte(hContact, threadData->proto->iface.m_szModuleName, "bChat", FALSE)) {
+ if (!DBGetContactSetting(hContact, threadData->proto->iface.m_szModuleName, "jid", &dbv)) {
+ if (strcmp(dbv.pszVal, "b73@tlen.pl")) {
+ queryResult.iItemsNum++;
+ }
+ DBFreeVariant(&dbv);
+ }
+ }
+ }
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM) hContact, 0);
+ }
+ queryResult.pItems = mir_alloc(sizeof(MUCCQUERYITEM) * queryResult.iItemsNum);
+ memset(queryResult.pItems, 0, sizeof(MUCCQUERYITEM) * queryResult.iItemsNum);
+ queryResult.iItemsNum = 0;
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDFIRST, 0, 0);
+ while (hContact != NULL) {
+ char *baseProto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if(baseProto!=NULL && !strcmp(baseProto, threadData->proto->iface.m_szModuleName)) {
+ if (!DBGetContactSettingByte(hContact, threadData->proto->iface.m_szModuleName, "bChat", FALSE)) {
+ if (!DBGetContactSetting(hContact, threadData->proto->iface.m_szModuleName, "jid", &dbv)) {
+ if (strcmp(dbv.pszVal, "b73@tlen.pl")) {
+ queryResult.pItems[queryResult.iItemsNum].pszID = mir_strdup(dbv.pszVal);
+ queryResult.pItems[queryResult.iItemsNum].pszName = mir_strdup((char *) CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM) hContact, 0));
+ queryResult.iItemsNum++;
+ }
+ DBFreeVariant(&dbv);
+ }
+ }
+ }
+ hContact = (HANDLE) CallService(MS_DB_CONTACT_FINDNEXT, (WPARAM) hContact, 0);
+ }
+ CallService(MS_MUCC_QUERY_RESULT, 0, (LPARAM) &queryResult);
+ TlenMUCFreeQueryResult(&queryResult);
+ mir_free(threadData->roomId);
+ mir_free(threadData);
+}
+
+
+static int TlenMUCQueryContacts(TlenProtocol *proto, const char *roomId) {
+
+ MUCSENDQUERYTHREADDATA *threadData = (MUCSENDQUERYTHREADDATA *)mir_alloc(sizeof(MUCSENDQUERYTHREADDATA));
+ threadData->proto = proto;
+ threadData->roomId = mir_strdup(roomId);
+ JabberForkThread(TlenMUCCSendQueryResultThread, 0, (void *)threadData);
+ return 1;
+}
+
+
+INT_PTR TlenMUCMenuHandleMUC(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (!proto->isOnline) {
+ return 1;
+ }
+ JabberSend(proto, "<p to='c' tp='c' id='"JABBER_IQID"%d'/>", JabberSerialNext(proto));
+ /*
+ MUCCEVENT *mucce;
+ mucce = (MUCCEVENT *) mir_alloc (sizeof(MUCCEVENT));
+ mucce->cbSize = sizeof(MUCCEVENT);
+ mucce->iType = MUCC_EVENT_JOIN;
+ mucce->dwFlags = 0;
+ mucce->pszModule = iface.m_szModuleName;
+ mucce->pszID = NULL;
+ mucce->pszName = NULL;
+ mucce->pszNick = NULL;
+ CallService(MS_MUCC_EVENT, 0, (LPARAM) mucce);
+ mir_free(mucce);
+ */
+ return 0;
+}
+
+INT_PTR TlenMUCMenuHandleChats(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ MUCCWINDOW mucw;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (!proto->isOnline) {
+ return 1;
+ }
+ mucw.cbSize = sizeof(MUCCWINDOW);
+ mucw.iType = MUCC_WINDOW_CHATLIST;
+ mucw.pszModule = proto->iface.m_szModuleName;
+ mucw.pszModuleName = proto->iface.m_szProtoName;
+ CallService(MS_MUCC_NEW_WINDOW, 0, (LPARAM) &mucw);
+ return 0;
+}
+
+INT_PTR TlenMUCContactMenuHandleMUC(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact;
+ DBVARIANT dbv;
+ JABBER_LIST_ITEM *item;
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+ if (!proto->isOnline) {
+ return 1;
+ }
+ if ((hContact=(HANDLE) wParam)!=NULL && proto->isOnline) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ char serialId[32];
+ sprintf(serialId, JABBER_IQID"%d", JabberSerialNext(proto));
+ item = JabberListAdd(proto, LIST_INVITATIONS, serialId);
+ item->nick = mir_strdup(dbv.pszVal);
+ JabberSend(proto, "<p to='c' tp='c' id='%s'/>", serialId);
+ DBFreeVariant(&dbv);
+ }
+ }
+ return 0;
+}
diff --git a/protocols/Tlen/tlen_muc.h b/protocols/Tlen/tlen_muc.h
new file mode 100644
index 0000000000..fc1713a837
--- /dev/null
+++ b/protocols/Tlen/tlen_muc.h
@@ -0,0 +1,45 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#ifndef _TLEN_MUC_H_
+#define _TLEN_MUC_H_
+
+#include <windows.h>
+#include "m_mucc.h"
+
+#define USER_FLAGS_OWNER 0x01
+#define USER_FLAGS_ADMIN 0x02
+#define USER_FLAGS_REGISTERED 0x04
+#define USER_FLAGS_GLOBALOWNER 0x08
+#define USER_FLAGS_KICKED 0x80
+
+extern BOOL TlenMUCInit(TlenProtocol *proto);
+extern INT_PTR TlenMUCMenuHandleMUC(void *ptr, WPARAM wParam, LPARAM lParam);
+extern INT_PTR TlenMUCMenuHandleChats(void *ptr, WPARAM wParam, LPARAM lParam);
+extern INT_PTR TlenMUCContactMenuHandleMUC(void *ptr, WPARAM wParam, LPARAM lParam);
+extern int TlenMUCCreateWindow(TlenProtocol *proto, const char *roomID, const char *roomName, int roomFlags, const char *nick, const char *iqId);
+extern int TlenMUCRecvInvitation(TlenProtocol *proto, const char *roomJid, const char *roomName, const char *from, const char *reason);
+extern int TlenMUCRecvPresence(TlenProtocol *proto, const char *from, int status, int flags, const char *kick);
+extern int TlenMUCRecvMessage(TlenProtocol *proto, const char *from, long timestamp, XmlNode *bodyNode);
+extern int TlenMUCRecvTopic(TlenProtocol *proto, const char *from, const char *subject);
+extern int TlenMUCRecvError(TlenProtocol *proto, const char *from, XmlNode *errorNode);
+
+#endif
diff --git a/protocols/Tlen/tlen_p2p_new.c b/protocols/Tlen/tlen_p2p_new.c
new file mode 100644
index 0000000000..7d9c959a42
--- /dev/null
+++ b/protocols/Tlen/tlen_p2p_new.c
@@ -0,0 +1,361 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include <io.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include "jabber_list.h"
+#include "tlen_p2p_old.h"
+
+
+static void logInfo(const char *filename, const char *fmt, ...) {
+ SYSTEMTIME time;
+ char *str;
+ va_list vararg;
+ int strsize;
+ FILE *flog=fopen(filename,"at");
+ if (flog!=NULL) {
+ GetLocalTime(&time);
+ va_start(vararg, fmt);
+ str = (char *) mir_alloc(strsize=2048);
+ while (_vsnprintf(str, strsize, fmt, vararg) == -1)
+ str = (char *) realloc(str, strsize+=2048);
+ va_end(vararg);
+ fprintf(flog,"%04d-%02d-%02d %02d:%02d:%02d,%03d [%s]",time.wYear,time.wMonth,time.wDay,time.wHour,time.wMinute,time.wSecond,time.wMilliseconds, "INFO");
+ fprintf(flog," %s\n",str);
+ mir_free(str);
+ fclose(flog);
+ }
+}
+
+void __cdecl TlenNewFileReceiveThread(TLEN_FILE_TRANSFER *ft)
+{
+ JabberLog(ft->proto, "P2P receive thread started");
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, ft, 0);
+// ft->mode = FT_RECV;
+// ft->currentFile = 0;
+// ft->state = FT_CONNECTING;
+ {
+ FILE * fout = fopen("tlen_recv.dxx", "wt");
+ SOCKADDR_IN toad;
+ toad.sin_family = AF_INET;
+ toad.sin_addr.s_addr = inet_addr(ft->hostName);
+ toad.sin_port = htons(ft->wPort);
+ if (fout != NULL) {
+ fprintf(fout, "START:\n");
+ }
+ if (fout != NULL) {
+ fclose(fout);
+ }
+ while (ft->udps != INVALID_SOCKET) {
+ SOCKADDR_IN cad;
+ int alen;
+ int j, n;
+ unsigned char buff[1024];
+ alen = sizeof(struct sockaddr);
+ n=recvfrom(ft->udps, (char*)buff,sizeof(buff),0, (struct sockaddr *) &cad, &alen);
+ if (n<0) {
+ break;
+ }
+ logInfo("tlen_recv.dxx", "UDP");
+ fout = fopen("tlen_recv.dxx", "at");
+ if (fout != NULL) {
+ fprintf(fout, "\n|RECV %d bytes from %s:%d|",n, inet_ntoa(cad.sin_addr), cad.sin_port);
+ for (j = 0; j < n; j++) {
+ fprintf(fout, "%02X-", buff[j]);
+ }
+ }
+ if (n == 1) {
+ alen = sizeof(struct sockaddr);
+ n = sendto(ft->udps, (char*)buff, n, 0,(struct sockaddr *) &toad, alen);
+ if (fout != NULL) {
+ fprintf(fout, "\n|SEND |");
+ for (j = 0; j < n; j++) {
+ fprintf(fout, "%02X-", buff[j]);
+ }
+ }
+ }
+ if (fout != NULL) {
+ fprintf(fout, "\n");
+ fclose(fout);
+ }
+ }
+ }
+ if (ft->udps != INVALID_SOCKET) {
+ closesocket(ft->udps);
+ }
+
+ JabberListRemove(ft->proto, LIST_FILE, ft->iqId);
+ if (ft->state==FT_DONE)
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ else {
+ ProtoBroadcastAck(ft->proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ }
+ JabberLog(ft->proto, "P2P receive thread ended");
+ TlenP2PFreeFileTransfer(ft);
+}
+
+void __cdecl TlenNewFileSendThread(TLEN_FILE_TRANSFER *ft)
+{
+ JabberLog(ft->proto, "P2P send thread started");
+// ft->mode = FT_RECV;
+// ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, ft, 0);
+// ft->currentFile = 0;
+// ft->state = FT_CONNECTING;
+ {
+ FILE * fout = fopen("tlen_send.gxx", "wt");
+ int step = 0;
+ SOCKADDR_IN toad;
+ toad.sin_family = AF_INET;
+ toad.sin_addr.s_addr = inet_addr(ft->hostName);
+ toad.sin_port = htons(ft->wPort);
+
+ if (fout != NULL) {
+ fprintf(fout, "START:");
+ }
+ if (fout != NULL) {
+ fclose(fout);
+ }
+ for (step = 0; step < 10; step ++) {
+// while (ft->udps != INVALID_SOCKET) {
+ int alen;
+ int j, n;
+ unsigned char buff[1024];
+ alen = sizeof(struct sockaddr);
+ if (step < 3 || step > 5) {
+ buff[0] = 1;
+ n = 1;
+ } else {
+ buff[0] = '$';
+ buff[1] = '^';
+ buff[2] = '&';
+ buff[3] = '%';
+ n = 4;
+ }
+ n=sendto(ft->udps, (char*)buff, n, 0, (struct sockaddr *)&toad, alen);
+ logInfo("tlen_send.dxx", "UDP");
+ if (fout != NULL) {
+ fprintf(fout, "|send: %d %s %d|",n, inet_ntoa(toad.sin_addr), toad.sin_port);
+ for (j = 0; j < n; j++) {
+ fprintf(fout, "%02X-", buff[j]);
+ }
+ }
+ if (fout != NULL) {
+ fprintf(fout, "\n");
+ fclose(fout);
+ }
+ SleepEx(1000, TRUE);
+ }
+ }
+ JabberLog(ft->proto, "P2P send thread ended");
+}
+
+void TlenBindUDPSocket(TLEN_FILE_TRANSFER *ft)
+{
+ JabberLog(ft->proto, "Binding UDP socket");
+ ft->udps = socket(PF_INET, SOCK_DGRAM, 0);
+ if (ft->udps != INVALID_SOCKET) {
+ SOCKADDR_IN sin;
+ int len = sizeof(struct sockaddr);
+ memset((char *)&sin,0,sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(INADDR_ANY);;
+ sin.sin_port = 0;
+ if (bind(ft->udps, (struct sockaddr *)&sin, sizeof(sin)) >= 0) {
+ if(!getsockname((SOCKET)ft->udps,(SOCKADDR *)&sin,&len)) {
+ struct hostent *hp;
+ char host_name[256];
+ gethostname(host_name, sizeof(host_name));
+ hp = gethostbyname(host_name);
+ mir_snprintf(host_name, sizeof(host_name), "%u.%u.%u.%u", (unsigned char)hp->h_addr_list[0][0],
+ (unsigned char)hp->h_addr_list[0][1],
+ (unsigned char)hp->h_addr_list[0][2],
+ (unsigned char)hp->h_addr_list[0][3]);
+
+ ft->wLocalPort = ntohs(sin.sin_port);
+ ft->localName= mir_strdup(host_name);
+ JabberLog(ft->proto, "UDP socket bound to %s:%d", ft->localName, ft->wLocalPort);
+ }
+ }
+ }
+}
+
+
+/*
+aaa sends a file to bbb:
+
+1) aaa wants to SEND bbb a file
+A SEND: <iq to='bbb@tlen.pl'><query xmlns='p2p'><fs t="bbb@tlen.pl" e="1" i="179610858" c="1" s="308278" v="2" /></query></iq>
+B RECV: <iq from='aaa@tlen.pl'><query xmlns='p2p'><fs t="bbb@tlen.pl" e="1" i="179610858" c="1" s="308278" v="2" /></query></iq>
+
+2) bbb ACCEPTs
+B SEND: <iq to='aaa@tlen.pl'><query xmlns='p2p'><fs t="aaa@tlen.pl" e="5" i="179610858" v="2" /></query></iq>
+A RECV: <iq from='bbb@tlen.pl'><query xmlns='p2p'><fs t="aaa@tlen.pl" e="5" i="179610858" v="2" /></query></iq>
+
+3) aaa tries to establish p2p connection:
+A SEND: <iq to='bbb@tlen.pl'><query xmlns='p2p'><dcng n='file_send' k='5' v='2' s='1' i='179610858' ck='rNbjnfRSQwJyaI+oRAXmfQ==' ks='16' iv='MAfaCCrqtuU2Ngw=rNbjnfRSQwJyaI+oRAXmfQ==' mi='24835584'/></query></iq>
+B SEND: <iq from='aaa@tlen.pl'><query xmlns='p2p'><dcng n='file_send' k='5' v='2' s='1' i='179610858' ck='rNbjnfRSQwJyaI+oRAXmfQ==' ks='16' iv='MAfaCCrqtuU2Ngw=rNbjnfRSQwJyaI+oRAXmfQ==' mi='24835584'/></query></iq>
+
+3) bbb sends IP/port details
+B SEND: <iq to='bbb@tlen.pl'><query xmlns='p2p'><dcng la='xx.xx.xx.xx' lp='nnn' pa='xx.xx.xx.xx' pp='nnn' i='179610858' v='2' k='5' s='2'/></query></iq>
+
+*/
+
+void TlenProcessP2P(XmlNode *node, ThreadData *info) {
+ XmlNode *queryNode;
+ JABBER_LIST_ITEM *item;
+ char *from;
+
+ if (info == NULL) return;
+
+ queryNode = JabberXmlGetChild(node, "query");
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ XmlNode *fs , *vs, *dcng, *dc;
+ /* file send */
+ fs = JabberXmlGetChild(queryNode, "fs");
+ /* voice send */
+ vs = JabberXmlGetChild(queryNode, "vs");
+ dcng = JabberXmlGetChild(queryNode, "dcng");
+ dc = JabberXmlGetChild(queryNode, "dc");
+ if (fs != NULL) {
+ char *e, *id;
+ /* e - step in the process (starting with 1)*/
+ /* i - id of the file */
+ /* s - size of the file */
+ /* c - number of files */
+ /* v - ??? */
+ e = JabberXmlGetAttrValue(fs, "e");
+ id = JabberXmlGetAttrValue(fs, "i");
+ if (e != NULL) {
+ if (!strcmp(e, "1")) {
+ CCSDATA ccs;
+ PROTORECVEVENT pre;
+ char *c, *s;
+ TLEN_FILE_TRANSFER * ft = (TLEN_FILE_TRANSFER *) mir_alloc(sizeof(TLEN_FILE_TRANSFER));
+ memset(ft, 0, sizeof(TLEN_FILE_TRANSFER));
+ c = JabberXmlGetAttrValue(fs, "c");
+ s = JabberXmlGetAttrValue(fs, "s");
+ ft->jid = mir_strdup(from);
+ ft->proto = info->proto;
+ ft->hContact = JabberHContactFromJID(info->proto, from);
+ ft->iqId = mir_strdup(id);
+ ft->fileTotalSize = atoi(s);
+ ft->newP2P = TRUE;
+ if ((item=JabberListAdd(ft->proto, LIST_FILE, ft->iqId)) != NULL) {
+ char *szBlob;
+ char fileInfo[128];
+ item->ft = ft;
+ mir_snprintf(fileInfo, sizeof(fileInfo), "%s file(s), %s bytes", c, s);
+ // blob is DWORD(*ft), ASCIIZ(filenames), ASCIIZ(description)
+ szBlob = (char *) mir_alloc(sizeof(DWORD) + strlen(fileInfo) + 2);
+ *((PDWORD) szBlob) = (DWORD) ft;
+ strcpy(szBlob + sizeof(DWORD), fileInfo);
+ szBlob[sizeof(DWORD) + strlen(fileInfo) + 1] = '\0';
+ pre.flags = 0;
+ pre.timestamp = time(NULL);
+ pre.szMessage = szBlob;
+ pre.lParam = 0;
+ ccs.szProtoService = PSR_FILE;
+ ccs.hContact = ft->hContact;
+ ccs.wParam = 0;
+ ccs.lParam = (LPARAM) &pre;
+ JabberLog(ft->proto, "sending chainrecv");
+ CallService(MS_PROTO_CHAINRECV, 0, (LPARAM) &ccs);
+ mir_free(szBlob);
+ }
+ } else if (!strcmp(e, "3")) {
+ /* transfer error */
+ } else if (!strcmp(e, "4")) {
+ /* transfer denied */
+ } else if (!strcmp(e, "5")) {
+ /* transfer accepted */
+ if ((item=JabberListGetItemPtr(info->proto, LIST_FILE, id)) != NULL) {
+ item->id2 = mir_strdup("84273372");
+ item->ft->id2 = mir_strdup("84273372");
+ JabberSend(info->proto, "<iq to='%s'><query xmlns='p2p'><dcng n='file_send' k='5' v='2' s='1' i='%s' ck='o7a32V9n2UZYCWpBUhSbFw==' ks='16' iv='MhjWEj9WTsovrQc=o7a32V9n2UZYCWpBUhSbFw==' mi='%s'/></query></iq>", from, item->id2, id);
+ }
+ }
+ }
+ } else if (vs != NULL) {
+
+ } else if (dcng != NULL) {
+ char *s, *id, *id2;
+ JabberLog(info->proto, "DCNG");
+ s = JabberXmlGetAttrValue(dcng, "s");
+ id2 = JabberXmlGetAttrValue(dcng, "i");
+ id = JabberXmlGetAttrValue(dcng, "mi");
+ if (!strcmp(s, "1")) {
+ /* Keys */
+ /* n - name (file_send) */
+ /* k - ??? */
+ /* v - ??? */
+ /* s - step */
+ /* i - id of the file */
+ /* ck - aes key */
+ /* ks - key size (in bytes) */
+ /* iv - aes initial vector */
+ /* mi - p2p connection id */
+ char *n, *k, *v, *ck, *ks, *iv;
+ n = JabberXmlGetAttrValue(dcng, "n");
+ k = JabberXmlGetAttrValue(dcng, "k");
+ v = JabberXmlGetAttrValue(dcng, "v");
+ ck = JabberXmlGetAttrValue(dcng, "ck");
+ iv = JabberXmlGetAttrValue(dcng, "iv");
+ if (!strcmp(n, "file_send")) {
+ if ((item=JabberListGetItemPtr(info->proto, LIST_FILE, id)) != NULL) {
+ item->id2 = mir_strdup(id2);
+ item->ft->id2 = mir_strdup(id2);
+ TlenBindUDPSocket(item->ft);
+ JabberSend(info->proto, "<iq to='%s'><query xmlns='p2p'><dcng la='%s' lp='%d' pa='%s' pp='%d' i='%s' v='2' k='5' s='2'/></query></iq>",
+ item->ft->jid, item->ft->localName, item->ft->wLocalPort, item->ft->localName, item->ft->wLocalPort, item->ft->id2);
+ }
+ }
+ } else if (!strcmp(s, "2")) {
+ JabberLog(info->proto, "step = 2");
+ JabberLog(info->proto, "%s",from);
+ JabberLog(info->proto, "%s",id2);
+ /* IP and port */
+ if ((item=JabberListFindItemPtrById2(info->proto, LIST_FILE, id2)) != NULL) {
+ item->ft->hostName = mir_strdup(JabberXmlGetAttrValue(dcng, "pa"));
+ item->ft->wPort = atoi(JabberXmlGetAttrValue(dcng, "pp"));
+ TlenBindUDPSocket(item->ft);
+ JabberSend(info->proto, "<iq to='%s'><query xmlns='p2p'><dcng la='%s' lp='%d' pa='%s' pp='%d' i='%s' k='5' s='4'/></query></iq>",
+ item->ft->jid, item->ft->localName, item->ft->wLocalPort, item->ft->localName, item->ft->wLocalPort, item->ft->id2);
+ JabberForkThread((void (__cdecl *)(void*))TlenNewFileReceiveThread, 0, item->ft);
+ JabberForkThread((void (__cdecl *)(void*))TlenNewFileSendThread, 0, item->ft);
+ }
+ } else if (!strcmp(s, "4")) {
+ /* IP and port */
+ if ((item=JabberListFindItemPtrById2(info->proto, LIST_FILE, id2)) != NULL) {
+ JabberLog(info->proto, "step = 4");
+ item->ft->hostName = mir_strdup(JabberXmlGetAttrValue(dcng, "pa"));
+ item->ft->wPort = atoi(JabberXmlGetAttrValue(dcng, "pp"));
+ JabberForkThread((void (__cdecl *)(void*))TlenNewFileReceiveThread, 0, item->ft);
+ }
+ }
+
+ } else if (dc != NULL) {
+
+ }
+ }
+}
diff --git a/protocols/Tlen/tlen_p2p_old.c b/protocols/Tlen/tlen_p2p_old.c
new file mode 100644
index 0000000000..0d5c121535
--- /dev/null
+++ b/protocols/Tlen/tlen_p2p_old.c
@@ -0,0 +1,536 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include <io.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include "jabber_list.h"
+#include "tlen_p2p_old.h"
+
+void TlenP2PFreeFileTransfer(TLEN_FILE_TRANSFER *ft)
+{
+ int i;
+ if (ft->jid) mir_free(ft->jid);
+ if (ft->iqId) mir_free(ft->iqId);
+ if (ft->id2) mir_free(ft->id2);
+ if (ft->hostName) mir_free(ft->hostName);
+ if (ft->localName) mir_free(ft->localName);
+ if (ft->szSavePath) mir_free(ft->szSavePath);
+ if (ft->szDescription) mir_free(ft->szDescription);
+ if (ft->filesSize) mir_free(ft->filesSize);
+ if (ft->files) {
+ for (i=0; i<ft->fileCount; i++) {
+ if (ft->files[i]) mir_free(ft->files[i]);
+ }
+ mir_free(ft->files);
+ }
+ mir_free(ft);
+}
+
+TLEN_FILE_PACKET *TlenP2PPacketCreate(int datalen)
+{
+ TLEN_FILE_PACKET *packet;
+
+ if ((packet=(TLEN_FILE_PACKET *) mir_alloc(sizeof(TLEN_FILE_PACKET))) == NULL)
+ return NULL;
+ packet->packet = NULL;
+ if (datalen > 0) {
+ if ((packet->packet=(char *) mir_alloc(datalen)) == NULL) {
+ mir_free(packet);
+ return NULL;
+ }
+ }
+ packet->maxDataLen = datalen;
+ packet->type=0;
+ packet->len=0;
+ return packet;
+}
+
+void TlenP2PPacketFree(TLEN_FILE_PACKET *packet)
+{
+ if (packet != NULL) {
+ if (packet->packet != NULL)
+ mir_free(packet->packet);
+ mir_free(packet);
+ }
+}
+
+void TlenP2PPacketSetType(TLEN_FILE_PACKET *packet, DWORD type)
+{
+ if (packet!=NULL) {
+ packet->type = type;
+ }
+}
+
+void TlenP2PPacketSetLen(TLEN_FILE_PACKET *packet, DWORD len)
+{
+ if (packet!=NULL) {
+ packet->len = len;
+ }
+}
+
+void TlenP2PPacketPackDword(TLEN_FILE_PACKET *packet, DWORD data)
+{
+ if (packet!=NULL && packet->packet!=NULL) {
+ if (packet->len + sizeof(DWORD) <= packet->maxDataLen) {
+ (*((DWORD*)((packet->packet)+(packet->len)))) = data;
+ packet->len += sizeof(DWORD);
+ }
+ }
+}
+
+void TlenP2PPacketPackBuffer(TLEN_FILE_PACKET *packet, char *buffer, int len)
+{
+ if (packet!=NULL && packet->packet!=NULL) {
+ if (packet->len + len <= packet->maxDataLen) {
+ memcpy((packet->packet)+(packet->len), buffer, len);
+ packet->len += len;
+ }
+ }
+}
+
+void TlenP2PInit() {
+}
+
+void TlenP2PUninit() {
+}
+
+int TlenP2PPacketSend(JABBER_SOCKET s, TLEN_FILE_PACKET *packet)
+{
+ DWORD sendResult;
+ if (packet!=NULL && packet->packet!=NULL) {
+ Netlib_Send(s, (char *)&packet->type, 4, MSG_NODUMP);
+ Netlib_Send(s, (char *)&packet->len, 4, MSG_NODUMP);
+ sendResult=Netlib_Send(s, packet->packet, packet->len, MSG_NODUMP);
+ if (sendResult==SOCKET_ERROR || sendResult!=packet->len) return 0;
+ }
+ return 1;
+}
+
+TLEN_FILE_PACKET* TlenP2PPacketReceive(JABBER_SOCKET s)
+{
+ TLEN_FILE_PACKET *packet;
+ DWORD recvResult;
+ DWORD type, len, pos;
+ recvResult = Netlib_Recv(s, (char *)&type, 4, MSG_NODUMP);
+ if (recvResult==0 || recvResult==SOCKET_ERROR) return NULL;
+ recvResult = Netlib_Recv(s, (char *)&len, 4, MSG_NODUMP);
+ if (recvResult==0 || recvResult==SOCKET_ERROR) return NULL;
+ packet = TlenP2PPacketCreate(len);
+ TlenP2PPacketSetType(packet, type);
+ TlenP2PPacketSetLen(packet, len);
+ pos = 0;
+ while (len > 0) {
+ recvResult = Netlib_Recv(s, packet->packet+pos, len, MSG_NODUMP);
+ if (recvResult==0 || recvResult==SOCKET_ERROR) {
+ TlenP2PPacketFree(packet);
+ return NULL;
+ }
+ len -= recvResult;
+ pos += recvResult;
+ }
+ return packet;
+}
+
+void TlenP2PEstablishOutgoingConnection(TLEN_FILE_TRANSFER *ft, BOOL sendAck)
+{
+ char *hash;
+ char str[300];
+ TLEN_FILE_PACKET *packet;
+ TlenProtocol *proto = ft->proto;
+
+ JabberLog(proto, "Establishing outgoing connection.");
+ ft->state = FT_ERROR;
+ if ((packet = TlenP2PPacketCreate(2*sizeof(DWORD) + 20))!=NULL) {
+ TlenP2PPacketSetType(packet, TLEN_FILE_PACKET_CONNECTION_REQUEST);
+ TlenP2PPacketPackDword(packet, 1);
+ TlenP2PPacketPackDword(packet, (DWORD) atoi(ft->iqId));
+ _snprintf(str, sizeof(str), "%08X%s%d", atoi(ft->iqId), proto->threadData->username, atoi(ft->iqId));
+ hash = TlenSha1(str, (int)strlen(str));
+ TlenP2PPacketPackBuffer(packet, hash, 20);
+ mir_free(hash);
+ TlenP2PPacketSend(ft->s, packet);
+ TlenP2PPacketFree(packet);
+ packet = TlenP2PPacketReceive(ft->s);
+ if (packet != NULL) {
+ if (packet->type == TLEN_FILE_PACKET_CONNECTION_REQUEST_ACK) { // acknowledge
+ if ((int)(*((DWORD*)packet->packet)) == atoi(ft->iqId)) {
+ ft->state = FT_CONNECTING;
+ if (sendAck) {
+ ProtoBroadcastAck(proto->iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTED, ft, 0);
+ }
+ }
+ }
+ TlenP2PPacketFree(packet);
+ }
+ }
+}
+
+TLEN_FILE_TRANSFER* TlenP2PEstablishIncomingConnection(TlenProtocol *proto, JABBER_SOCKET s, int list, BOOL sendAck)
+{
+ JABBER_LIST_ITEM *item = NULL;
+ TLEN_FILE_PACKET *packet;
+ int i;
+ char str[300];
+ DWORD iqId;
+ // TYPE: 0x1
+ // LEN:
+ // (DWORD) 0x1
+ // (DWORD) id
+ // (BYTE) hash[20]
+ packet = TlenP2PPacketReceive(s);
+ if (packet == NULL || packet->type != TLEN_FILE_PACKET_CONNECTION_REQUEST || packet->len<28) {
+ if (packet!=NULL) {
+ TlenP2PPacketFree(packet);
+ }
+ return NULL;
+ }
+ iqId = *((DWORD *)(packet->packet+sizeof(DWORD)));
+ i = 0;
+ while ((i=JabberListFindNext(proto, list, i)) >= 0) {
+ if ((item=JabberListGetItemPtrFromIndex(proto, i))!=NULL) {
+ _snprintf(str, sizeof(str), "%d", iqId);
+ if (!strcmp(item->ft->iqId, str)) {
+ char *hash, *nick;
+ int j;
+ nick = JabberNickFromJID(item->ft->jid);
+ _snprintf(str, sizeof(str), "%08X%s%d", iqId, nick, iqId);
+ mir_free(nick);
+ hash = TlenSha1(str, (int)strlen(str));
+ for (j=0;j<20;j++) {
+ if (hash[j]!=packet->packet[2*sizeof(DWORD)+j]) break;
+ }
+ mir_free(hash);
+ if (j==20) break;
+ }
+ }
+ i++;
+ }
+ TlenP2PPacketFree(packet);
+ if (i >=0) {
+ if ((packet=TlenP2PPacketCreate(sizeof(DWORD))) != NULL) {
+ // Send connection establishment acknowledgement
+ TlenP2PPacketSetType(packet, TLEN_FILE_PACKET_CONNECTION_REQUEST_ACK);
+ TlenP2PPacketPackDword(packet, (DWORD) atoi(item->ft->iqId));
+ TlenP2PPacketSend(s, packet);
+ TlenP2PPacketFree(packet);
+ item->ft->state = FT_CONNECTING;
+ if (sendAck) {
+ ProtoBroadcastAck(item->ft->proto->iface.m_szModuleName, item->ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTED, item->ft, 0);
+ }
+ return item->ft;
+ }
+ }
+ return NULL;
+}
+
+static void __cdecl TlenFileBindSocks4Thread(TLEN_FILE_TRANSFER* ft)
+{
+ BYTE buf[8];
+ int status;
+
+// JabberLog("Waiting for the file to be sent via SOCKS...");
+ status = Netlib_Recv(ft->s, (char*)buf, 8, MSG_NODUMP);
+// JabberLog("accepted connection !!!");
+ if ( status == SOCKET_ERROR || status<8 || buf[1]!=90) {
+ status = 1;
+ } else {
+ status = 0;
+ }
+ if (!status) {
+ ft->pfnNewConnectionV2(ft->s, 0, NULL);
+ } else {
+ if (ft->state!=FT_SWITCH) {
+ ft->state = FT_ERROR;
+ }
+ }
+ JabberLog(ft->proto, "Closing connection for this file transfer...");
+// Netlib_CloseHandle(ft->s);
+ if (ft->hFileEvent != NULL)
+ SetEvent(ft->hFileEvent);
+
+}
+static void __cdecl TlenFileBindSocks5Thread(TLEN_FILE_TRANSFER* ft)
+{
+ BYTE buf[256];
+ int status;
+
+// JabberLog("Waiting for the file to be sent via SOCKS...");
+ status = Netlib_Recv(ft->s, (char*)buf, sizeof(buf), MSG_NODUMP);
+// JabberLog("accepted connection !!!");
+ if ( status == SOCKET_ERROR || status<7 || buf[1]!=0) {
+ status = 1;
+ } else {
+ status = 0;
+ }
+ if (!status) {
+ ft->pfnNewConnectionV2(ft->s, 0, NULL);
+ } else {
+ if (ft->state!=FT_SWITCH) {
+ ft->state = FT_ERROR;
+ }
+ }
+// JabberLog("Closing connection for this file transfer...");
+// Netlib_CloseHandle(ft->s);
+ if (ft->hFileEvent != NULL)
+ SetEvent(ft->hFileEvent);
+
+}
+
+static JABBER_SOCKET TlenP2PBindSocks4(SOCKSBIND * sb, TLEN_FILE_TRANSFER *ft)
+{ //rfc1928
+ int len;
+ BYTE buf[256];
+ int status;
+ struct in_addr in;
+ NETLIBOPENCONNECTION nloc;
+ JABBER_SOCKET s;
+
+ nloc.cbSize = NETLIBOPENCONNECTION_V1_SIZE;//sizeof(NETLIBOPENCONNECTION);
+ nloc.szHost = sb->szHost;
+ nloc.wPort = sb->wPort;
+ nloc.flags = 0;
+ s = (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) ft->proto->hFileNetlibUser, (LPARAM) &nloc);
+ if (s==NULL) {
+// JabberLog("Connection failed (%d), thread ended", WSAGetLastError());
+ return NULL;
+ }
+ buf[0] = 4; //socks4
+ buf[1] = 2; //2-bind, 1-connect
+ *(PWORD)(buf+2) = htons(0); // port
+ *(PDWORD)(buf+4) = INADDR_ANY;
+ if (sb->useAuth) {
+ strcpy((char*)buf+8, sb->szUser);
+ len = (int)strlen(sb->szUser);
+ } else {
+ buf[8] = 0;
+ len = 0;
+ }
+ len += 9;
+ status = Netlib_Send(s, (char*)buf, len, MSG_NODUMP);
+ if (status==SOCKET_ERROR || status<len) {
+// JabberLog("Send failed (%d), thread ended", WSAGetLastError());
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ status = Netlib_Recv(s, (char*)buf, 8, MSG_NODUMP);
+ if (status==SOCKET_ERROR || status<8 || buf[1]!=90) {
+// JabberLog("SOCKS4 negotiation failed");
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ status = Netlib_Recv(s, (char*)buf, sizeof(buf), MSG_NODUMP);
+ if ( status == SOCKET_ERROR || status<7 || buf[0]!=5 || buf[1]!=0) {
+// JabberLog("SOCKS5 request failed");
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ in.S_un.S_addr = *(PDWORD)(buf+4);
+ strcpy(sb->szHost, inet_ntoa(in));
+ sb->wPort = htons(*(PWORD)(buf+2));
+ ft->s = s;
+ JabberForkThread((void (__cdecl *)(void*))TlenFileBindSocks4Thread, 0, ft);
+ return s;
+}
+
+static JABBER_SOCKET TlenP2PBindSocks5(SOCKSBIND * sb, TLEN_FILE_TRANSFER *ft)
+{ //rfc1928
+ BYTE buf[512];
+ int len, status;
+ NETLIBOPENCONNECTION nloc;
+ struct in_addr in;
+ JABBER_SOCKET s;
+
+ nloc.cbSize = NETLIBOPENCONNECTION_V1_SIZE;//sizeof(NETLIBOPENCONNECTION);
+ nloc.szHost = sb->szHost;
+ nloc.wPort = sb->wPort;
+ nloc.flags = 0;
+ s = (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) ft->proto->hFileNetlibUser, (LPARAM) &nloc);
+ if (s==NULL) {
+ JabberLog(ft->proto, "Connection failed (%d), thread ended", WSAGetLastError());
+ return NULL;
+ }
+ buf[0] = 5; //yep, socks5
+ buf[1] = 1; //one auth method
+ buf[2] = sb->useAuth?2:0; // authorization
+ status = Netlib_Send(s, (char*)buf, 3, MSG_NODUMP);
+ if (status==SOCKET_ERROR || status<3) {
+ JabberLog(ft->proto, "Send failed (%d), thread ended", WSAGetLastError());
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ status = Netlib_Recv(s, (char*)buf, 2, MSG_NODUMP);
+ if (status==SOCKET_ERROR || status<2 || (buf[1]!=0 && buf[1]!=2)) {
+ JabberLog(ft->proto, "SOCKS5 negotiation failed");
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ if(buf[1]==2) { //rfc1929
+ int nUserLen, nPassLen;
+ PBYTE pAuthBuf;
+
+ nUserLen = (int)strlen(sb->szUser);
+ nPassLen = (int)strlen(sb->szPassword);
+ pAuthBuf = (PBYTE)mir_alloc(3+nUserLen+nPassLen);
+ pAuthBuf[0] = 1; //auth version
+ pAuthBuf[1] = nUserLen;
+ memcpy(pAuthBuf+2, sb->szUser, nUserLen);
+ pAuthBuf[2+nUserLen]=nPassLen;
+ memcpy(pAuthBuf+3+nUserLen,sb->szPassword,nPassLen);
+ status = Netlib_Send(s, (char*)pAuthBuf, 3+nUserLen+nPassLen, MSG_NODUMP);
+ mir_free(pAuthBuf);
+ if (status==SOCKET_ERROR || status<3+nUserLen+nPassLen) {
+ JabberLog(ft->proto, "Send failed (%d), thread ended", WSAGetLastError());
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ status = Netlib_Recv(s, (char*)buf, sizeof(buf), MSG_NODUMP);
+ if (status==SOCKET_ERROR || status<2 || buf[1]!=0) {
+ JabberLog(ft->proto, "SOCKS5 sub-negotiation failed");
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ }
+
+ { PBYTE pInit;
+ int nHostLen=4;
+ DWORD hostIP=INADDR_ANY;
+ pInit=(PBYTE)mir_alloc(6+nHostLen);
+ pInit[0]=5; //SOCKS5
+ pInit[1]=2; //bind
+ pInit[2]=0; //reserved
+ pInit[3]=1;
+ *(PDWORD)(pInit+4)=hostIP;
+ *(PWORD)(pInit+4+nHostLen)=htons(0);
+ status = Netlib_Send(s, (char*)pInit, 6+nHostLen, MSG_NODUMP);
+ mir_free(pInit);
+ if (status==SOCKET_ERROR || status<6+nHostLen) {
+// JabberLog("Send failed (%d), thread ended", WSAGetLastError());
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ }
+ status = Netlib_Recv(s, (char*)buf, sizeof(buf), MSG_NODUMP);
+ if ( status == SOCKET_ERROR || status<7 || buf[0]!=5 || buf[1]!=0) {
+// JabberLog("SOCKS5 request failed");
+ Netlib_CloseHandle(s);
+ return NULL;
+ }
+ if (buf[2]==1) { // domain
+ len = buf[4];
+ memcpy(sb->szHost, buf+5, len);
+ sb->szHost[len]=0;
+ len += 4;
+ } else { // ip address
+ in.S_un.S_addr = *(PDWORD)(buf+4);
+ strcpy(sb->szHost, inet_ntoa(in));
+ len = 8;
+ }
+ sb->wPort = htons(*(PWORD)(buf+len));
+ ft->s = s;
+
+ JabberForkThread((void (__cdecl *)(void*))TlenFileBindSocks5Thread, 0, ft);
+ return s;
+}
+
+
+JABBER_SOCKET TlenP2PListen(TLEN_FILE_TRANSFER *ft)
+{
+ NETLIBBIND nlb = {0};
+ JABBER_SOCKET s = NULL;
+ int useProxy;
+ DBVARIANT dbv;
+ SOCKSBIND sb;
+ struct in_addr in;
+ TlenProtocol *proto = ft->proto;
+ useProxy=0;
+ if (ft->localName!= NULL) mir_free(ft->localName);
+ ft->localName = NULL;
+ ft->wPort = 0;
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "UseFileProxy", FALSE)) {
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "FileProxyHost", &dbv)) {
+ strcpy(sb.szHost, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ sb.wPort = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "FileProxyPort", 0);
+ sb.useAuth = FALSE;
+ strcpy(sb.szUser, "");
+ strcpy(sb.szPassword, "");
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "FileProxyAuth", FALSE)) {
+ sb.useAuth = TRUE;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "FileProxyUsername", &dbv)) {
+ strcpy(sb.szUser, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "FileProxyPassword", &dbv)) {
+ CallService(MS_DB_CRYPT_DECODESTRING, strlen(dbv.pszVal)+1, (LPARAM) dbv.pszVal);
+ strcpy(sb.szPassword, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ }
+ }
+ switch (DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "FileProxyType", 0)) {
+ case 0: // forwarding
+ useProxy = 1;
+ break;
+ case 1: // socks4
+ s = TlenP2PBindSocks4(&sb, ft);
+ useProxy = 2;
+ break;
+ case 2: // socks5
+ s = TlenP2PBindSocks5(&sb, ft);
+ useProxy = 2;
+ break;
+ }
+ ft->localName = mir_strdup(sb.szHost);
+ ft->wPort = sb.wPort;
+ ft->wLocalPort = sb.wPort;
+ }
+ }
+ if (useProxy<2) {
+ nlb.cbSize = sizeof(NETLIBBIND);
+ nlb.pfnNewConnectionV2 = ft->pfnNewConnectionV2;
+ nlb.wPort = 0; // Use user-specified incoming port ranges, if available
+ nlb.pExtra = proto;
+ JabberLog(ft->proto, "Calling MS_NETLIB_BINDPORT");
+ s = (HANDLE) CallService(MS_NETLIB_BINDPORT, (WPARAM) ft->proto->hNetlibUser, (LPARAM) &nlb);
+ JabberLog(ft->proto, "listening on %d",s);
+ }
+ if (useProxy==0) {
+ in.S_un.S_addr = htonl(nlb.dwExternalIP);
+ ft->localName = mir_strdup(inet_ntoa(in));
+ ft->wPort = nlb.wPort;
+ ft->wLocalPort = nlb.wExPort;
+ }
+ if (s != NULL) {
+// listenCount++;
+ }
+ return s;
+}
+
+void TlenP2PStopListening(JABBER_SOCKET s) {
+ if (s != NULL) {
+// listenCount--;
+// if (listenCount <= 0) {
+// Netlib_CloseHandle(s);
+// }
+ }
+}
diff --git a/protocols/Tlen/tlen_p2p_old.h b/protocols/Tlen/tlen_p2p_old.h
new file mode 100644
index 0000000000..d6405a378e
--- /dev/null
+++ b/protocols/Tlen/tlen_p2p_old.h
@@ -0,0 +1,66 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+
+#ifndef _TLEN_P2P_OLD_H_
+#define _TLEN_P2P_OLD_H_
+
+enum {
+ TLEN_FILE_PACKET_CONNECTION_REQUEST = 0x01,
+ TLEN_FILE_PACKET_CONNECTION_REQUEST_ACK = 0x02,
+ TLEN_FILE_PACKET_FILE_LIST = 0x32,
+ TLEN_FILE_PACKET_FILE_LIST_ACK = 0x33,
+ TLEN_FILE_PACKET_FILE_REQUEST = 0x34,
+ TLEN_FILE_PACKET_FILE_DATA = 0x35,
+ TLEN_FILE_PACKET_END_OF_FILE = 0x37,
+ TLEN_VOICE_PACKET = 0x96
+};
+
+typedef struct {
+ unsigned int maxDataLen;
+ char *packet;
+ DWORD type;
+ DWORD len;
+} TLEN_FILE_PACKET;
+
+typedef struct {
+ char szHost[256];
+ int wPort;
+ int useAuth;
+ char szUser[256];
+ char szPassword[256];
+}SOCKSBIND;
+
+extern void TlenP2PFreeFileTransfer(TLEN_FILE_TRANSFER *ft);
+extern TLEN_FILE_PACKET *TlenP2PPacketCreate(int datalen);
+extern void TlenP2PPacketFree(TLEN_FILE_PACKET *packet);
+extern void TlenP2PPacketSetType(TLEN_FILE_PACKET *packet, DWORD type);
+extern void TlenP2PPacketSetLen(TLEN_FILE_PACKET *packet, DWORD len);
+extern void TlenP2PPacketPackDword(TLEN_FILE_PACKET *packet, DWORD data);
+extern void TlenP2PPacketPackBuffer(TLEN_FILE_PACKET *packet, char *buffer, int len);
+extern int TlenP2PPacketSend(JABBER_SOCKET s, TLEN_FILE_PACKET *packet);
+extern TLEN_FILE_PACKET* TlenP2PPacketReceive(JABBER_SOCKET s);
+extern void TlenP2PEstablishOutgoingConnection(TLEN_FILE_TRANSFER *ft, BOOL sendAck);
+extern TLEN_FILE_TRANSFER* TlenP2PEstablishIncomingConnection(TlenProtocol *proto, JABBER_SOCKET s, int list, BOOL sendAck);
+extern JABBER_SOCKET TlenP2PListen(TLEN_FILE_TRANSFER *ft);
+extern void TlenP2PStopListening(JABBER_SOCKET s);
+#endif
diff --git a/protocols/Tlen/tlen_picture.c b/protocols/Tlen/tlen_picture.c
new file mode 100644
index 0000000000..c8f8d6f3e2
--- /dev/null
+++ b/protocols/Tlen/tlen_picture.c
@@ -0,0 +1,320 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2009 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "jabber_list.h"
+#include "tlen_file.h"
+#include "tlen_p2p_old.h"
+
+typedef struct {
+ TlenProtocol *proto;
+ JABBER_LIST_ITEM *item;
+} TLENPSREQUESTTHREADDATA;
+
+static void LogPictureMessage(TlenProtocol *proto, const char *jid, const char *filename, BOOL isSent)
+{
+ char message[1024];
+ const char *msg = isSent ? "Image sent file://%s" : "Image received file://%s";
+ _snprintf(message, sizeof(message), Translate(msg), filename);
+ TlenLogMessage(proto, JabberHContactFromJID(proto, jid), isSent ? DBEF_SENT : 0, message);
+}
+
+static void TlenPsPostThread(void *ptr) {
+ TLENPSREQUESTTHREADDATA *data = (TLENPSREQUESTTHREADDATA *)ptr;
+ TlenProtocol *proto = data->proto;
+ JABBER_LIST_ITEM *item = data->item;
+ JABBER_SOCKET socket = JabberWsConnect(proto, "ps.tlen.pl", 443);
+ BOOL bSent = FALSE;
+ if (socket != NULL) {
+ char header[512];
+ DWORD ret;
+ item->ft->s = socket;
+ item->ft->hFileEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ _snprintf(header, sizeof(header), "<pic auth='%s' t='p' to='%s' size='%d' idt='%s'/>", proto->threadData->username, item->ft->jid, item->ft->fileTotalSize, item->jid);
+ JabberWsSend(proto, socket, header, (int)strlen(header));
+ ret = WaitForSingleObject(item->ft->hFileEvent, 1000 * 60 * 5);
+ if (ret == WAIT_OBJECT_0) {
+ FILE *fp = fopen( item->ft->files[0], "rb" );
+ if (fp) {
+ int i;
+ char header[512];
+ char fileBuffer[2048];
+ _snprintf(header, sizeof(header), "<pic st='%s' idt='%s'/>", item->ft->iqId, item->jid);
+ JabberWsSend(proto, socket, header, (int)strlen(header));
+ JabberLog(proto, "Sending picture data...");
+ for (i = item->ft->filesSize[0]; i > 0; ) {
+ int toread = min(2048, i);
+ int readcount = (int)fread(fileBuffer, (size_t)1, (size_t)toread, fp);
+ i -= readcount;
+ if (readcount > 0) {
+ JabberWsSend(proto, socket, fileBuffer, readcount);
+ }
+ if (toread != readcount) {
+ break;
+ }
+ }
+ fclose(fp);
+ SleepEx(3000, TRUE);
+ bSent = TRUE;
+ } else {
+ /* picture not found */
+ }
+ } else {
+ /* 5 minutes passed */
+ }
+ Netlib_CloseHandle(socket);
+ if (bSent) {
+ JabberSend(proto, "<message to='%s' idt='%s' rt='%s' pid='1001' type='pic' />", item->ft->jid, item->jid, item->ft->id2);
+ LogPictureMessage(proto, item->ft->jid, item->ft->files[0], TRUE);
+ }
+ TlenP2PFreeFileTransfer(item->ft);
+ JabberListRemove(proto, LIST_PICTURE, item->jid);
+ } else {
+ /* cannot connect to ps server */
+ }
+ mir_free(data);
+}
+
+static void TlenPsPost(TlenProtocol *proto, JABBER_LIST_ITEM *item) {
+ TLENPSREQUESTTHREADDATA *threadData = (TLENPSREQUESTTHREADDATA *)mir_alloc(sizeof(TLENPSREQUESTTHREADDATA));
+ threadData->proto = proto;
+ threadData->item = item;
+ JabberForkThread(TlenPsPostThread, 0, threadData);
+}
+
+static void TlenPsGetThread(void *ptr) {
+ TLENPSREQUESTTHREADDATA *data = (TLENPSREQUESTTHREADDATA *)ptr;
+ TlenProtocol *proto = data->proto;
+ JABBER_LIST_ITEM *item = data->item;
+ FILE *fp;
+ fp = fopen( item->ft->files[0], "wb" );
+ if (fp) {
+ JABBER_SOCKET socket = JabberWsConnect(proto, "ps.tlen.pl", 443);
+ if (socket != NULL) {
+ XmlState xmlState;
+ char header[512];
+ char fileBuffer[2048];
+ JabberXmlInitState(&xmlState);
+ _snprintf(header, sizeof(header), "<pic auth='%s' t='g' to='%s' pid='1001' idt='%s' rt='%s'/>", proto->threadData->username, item->ft->jid, item->jid, item->ft->id2);
+ JabberWsSend(proto, socket, header, (int)strlen(header));
+ JabberLog(proto, "Reveiving picture data...");
+ {
+ int totalcount = 0;
+ int size = item->ft->filesSize[0];
+ BOOL bHeader = TRUE;
+ while (TRUE) {
+ int readcount = JabberWsRecv(proto, socket, fileBuffer, 2048 - totalcount);
+ if (readcount == 0) {
+ break;
+ }
+ totalcount += readcount;
+ if (bHeader) {
+ char * tagend = memchr(fileBuffer, '/', totalcount);
+ tagend = memchr(tagend + 1, '>', totalcount - (tagend - fileBuffer) - 1);
+ if (tagend != NULL) {
+ int parsed = JabberXmlParse(&xmlState, fileBuffer, tagend - fileBuffer + 1);
+ if (parsed == 0) {
+ continue;
+ }
+ bHeader = FALSE;
+ totalcount -= parsed;
+ memmove(fileBuffer, fileBuffer+parsed, totalcount);
+ }
+ }
+ if (!bHeader) {
+ if (totalcount > 0) {
+ fwrite(fileBuffer, 1, totalcount, fp);
+ size -= totalcount;
+ totalcount = 0;
+ }
+ if (size == 0) {
+ break;
+ }
+ }
+ }
+ }
+ Netlib_CloseHandle(socket);
+ JabberLog(proto, "Picture received...");
+ LogPictureMessage(proto, item->ft->jid, item->ft->files[0], FALSE);
+ } else {
+ /* cannot connect to ps server */
+ }
+ fclose(fp);
+ } else {
+ /* cannot create file */
+ }
+ TlenP2PFreeFileTransfer(item->ft);
+ JabberListRemove(proto, LIST_PICTURE, item->jid);
+ mir_free(data);
+}
+
+static void TlenPsGet(TlenProtocol *proto, JABBER_LIST_ITEM *item) {
+ TLENPSREQUESTTHREADDATA *threadData = (TLENPSREQUESTTHREADDATA *)mir_alloc(sizeof(TLENPSREQUESTTHREADDATA));
+ threadData->proto = proto;
+ threadData->item = item;
+ JabberForkThread(TlenPsGetThread, 0, threadData);
+}
+
+void TlenProcessPic(XmlNode *node, TlenProtocol *proto) {
+ JABBER_LIST_ITEM *item = NULL;
+ char *crc, *crc_c, *idt, *size, *from, *fromRaw, *rt;
+ from = JabberXmlGetAttrValue(node, "from");
+ fromRaw = JabberLoginFromJID(from);
+ idt = JabberXmlGetAttrValue(node, "idt");
+ size = JabberXmlGetAttrValue(node, "size");
+ crc_c = JabberXmlGetAttrValue(node, "crc_c");
+ crc = JabberXmlGetAttrValue(node, "crc");
+ rt = JabberXmlGetAttrValue(node, "rt");
+ if (idt != NULL) {
+ item = JabberListGetItemPtr(proto, LIST_PICTURE, idt);
+ }
+ if (item != NULL) {
+ if (!strcmp(from, "ps")) {
+ char *st = JabberXmlGetAttrValue(node, "st");
+ if (st != NULL) {
+ item->ft->iqId = mir_strdup(st);
+ item->ft->id2 = mir_strdup(rt);
+ if (item->ft->hFileEvent != NULL) {
+ SetEvent(item->ft->hFileEvent);
+ item->ft->hFileEvent = NULL;
+ }
+ }
+ } else if (!strcmp(item->ft->jid, fromRaw)) {
+ if (crc_c != NULL) {
+ if (!strcmp(crc_c, "n")) {
+ /* crc_c = n, picture transfer accepted */
+ TlenPsPost(proto, item);
+ } else if (!strcmp(crc_c, "f")) {
+ /* crc_c = f, picture cached, no need to transfer again */
+ LogPictureMessage(proto, item->ft->jid, item->ft->files[0], TRUE);
+ TlenP2PFreeFileTransfer(item->ft);
+ JabberListRemove(proto, LIST_PICTURE, idt);
+ }
+ } else if (rt != NULL) {
+ item->ft->id2 = mir_strdup(rt);
+ TlenPsGet(proto, item);
+ }
+ }
+ } else if (crc != NULL) {
+ BOOL bAccept = proto->tlenOptions.imagePolicy == TLEN_IMAGES_ACCEPT_ALL || (proto->tlenOptions.imagePolicy == TLEN_IMAGES_IGNORE_NIR && IsAuthorized(proto, from));
+ if (bAccept) {
+ FILE* fp;
+ char fileName[MAX_PATH];
+ char *ext = JabberXmlGetAttrValue(node, "ext");
+ char *tmpPath = Utils_ReplaceVars( "%miranda_userdata%" );
+ int tPathLen = mir_snprintf( fileName, MAX_PATH, "%s\\Images\\Tlen", tmpPath );
+ long oldSize = 0, lSize = atol(size);
+ DWORD dwAttributes = GetFileAttributesA( fileName );
+ if ( dwAttributes == 0xffffffff || ( dwAttributes & FILE_ATTRIBUTE_DIRECTORY ) == 0 ) {
+ CallService( MS_UTILS_CREATEDIRTREE, 0, ( LPARAM )fileName );
+ }
+ mir_free(tmpPath);
+ fileName[ tPathLen++ ] = '\\';
+ mir_snprintf( fileName + tPathLen, MAX_PATH - tPathLen, "%s.%s", crc, ext );
+ fp = fopen( fileName, "rb" );
+ if (fp) {
+ fseek(fp, 0, SEEK_END);
+ oldSize = ftell(fp);
+ fclose(fp);
+ }
+ if (oldSize != lSize) {
+ item = JabberListAdd(proto, LIST_PICTURE, idt);
+ item->ft = TlenFileCreateFT(proto, from);
+ item->ft->files = (char **) mir_alloc(sizeof(char *));
+ item->ft->filesSize = (long *) mir_alloc(sizeof(long));
+ item->ft->files[0] = mir_strdup(fileName);
+ item->ft->filesSize[0] = lSize;
+ item->ft->fileTotalSize = item->ft->filesSize[0];
+ JabberSend(proto, "<message type='pic' to='%s' crc_c='n' idt='%s'/>", from, idt);
+ } else {
+ JabberSend(proto, "<message type='pic' to='%s' crc_c='f' idt='%s'/>", from, idt);
+ LogPictureMessage(proto, from, fileName, FALSE);
+ }
+ }
+ }
+ mir_free(fromRaw);
+}
+
+BOOL SendPicture(TlenProtocol *proto, HANDLE hContact) {
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ char *jid = dbv.pszVal;
+ char szFilter[512];
+ char *szFileName = (char*) mir_alloc(_MAX_PATH);
+ OPENFILENAMEA ofn = {0};
+ CallService( MS_UTILS_GETBITMAPFILTERSTRINGS, ( WPARAM ) sizeof( szFilter ), ( LPARAM )szFilter );
+ ofn.lStructSize = OPENFILENAME_SIZE_VERSION_400;
+ ofn.hwndOwner = NULL;
+ ofn.lpstrFilter = szFilter;
+ ofn.lpstrCustomFilter = NULL;
+ ofn.lpstrFile = szFileName;
+ ofn.nMaxFile = _MAX_PATH;
+ ofn.Flags = OFN_FILEMUSTEXIST;
+ szFileName[0] = '\0';
+ if ( GetOpenFileNameA( &ofn )) {
+ long size;
+ FILE* fp = fopen( szFileName, "rb" );
+ if (fp) {
+ fseek(fp, 0, SEEK_END);
+ size = ftell(fp);
+ if (size > 0 && size < 256*1024) {
+ JABBER_LIST_ITEM *item;
+ mir_sha1_ctx sha;
+ DWORD digest[5];
+ int i;
+ char idStr[10];
+ char fileBuffer[2048];
+ int id = JabberSerialNext(proto);
+ _snprintf(idStr, sizeof(idStr), "%d", id);
+ item = JabberListAdd(proto, LIST_PICTURE, idStr);
+ item->ft = TlenFileCreateFT(proto, jid);
+ item->ft->files = (char **) mir_alloc(sizeof(char *));
+ item->ft->filesSize = (long *) mir_alloc(sizeof(long));
+ item->ft->files[0] = szFileName;
+ item->ft->filesSize[0] = size;
+ item->ft->fileTotalSize = size;
+ fseek(fp, 0, SEEK_SET);
+ mir_sha1_init( &sha );
+ for (i = item->ft->filesSize[0]; i > 0; ) {
+ int toread = min(2048, i);
+ int readcount = (int)fread(fileBuffer, (size_t)1, (size_t)toread, fp);
+ i -= readcount;
+ if (readcount > 0) {
+ mir_sha1_append( &sha, (mir_sha1_byte_t* )fileBuffer, readcount);
+ }
+ if (toread != readcount) {
+ break;
+ }
+ }
+ mir_sha1_finish( &sha, (mir_sha1_byte_t* )digest );
+ JabberSend(proto, "<message type='pic' to='%s' crc='%08x%08x%08x%08x%08x' idt='%s' size='%d' ext='%s'/>", jid,
+ (int)htonl(digest[0]), (int)htonl(digest[1]), (int)htonl(digest[2]), (int)htonl(digest[3]), (int)htonl(digest[4]), idStr, item->ft->filesSize[0], "jpg");
+ } else {
+ /* file too big */
+ }
+ fclose(fp);
+ }
+ }
+ DBFreeVariant(&dbv);
+ }
+ return FALSE;
+}
diff --git a/protocols/Tlen/tlen_picture.h b/protocols/Tlen/tlen_picture.h
new file mode 100644
index 0000000000..e4836444ee
--- /dev/null
+++ b/protocols/Tlen/tlen_picture.h
@@ -0,0 +1,41 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2009 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef _TLEN_PICTURE_H
+#define _TLEN_PICTURE_H
+
+#include <windows.h>
+#include "jabber.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern void TlenProcessPic(XmlNode *node, TlenProtocol *proto);
+extern BOOL SendPicture(TlenProtocol *, HANDLE hContact);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TLEN_PICTURE_H */
+
diff --git a/protocols/Tlen/tlen_presence.c b/protocols/Tlen/tlen_presence.c
new file mode 100644
index 0000000000..ca1f14e23c
--- /dev/null
+++ b/protocols/Tlen/tlen_presence.c
@@ -0,0 +1,314 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2009 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include "jabber_list.h"
+#include "tlen_avatar.h"
+
+void TlenProcessPresence(XmlNode *node, TlenProtocol *proto)
+{
+ HANDLE hContact;
+ XmlNode *showNode, *statusNode;
+ JABBER_LIST_ITEM *item;
+ char *from, *type, *nick, *show;
+ int status, laststatus = ID_STATUS_OFFLINE;
+ char *p;
+
+ if ((from=JabberXmlGetAttrValue(node, "from")) != NULL) {
+ if (JabberListExist(proto, LIST_CHATROOM, from)); //JabberGroupchatProcessPresence(node, userdata);
+
+ else {
+ type = JabberXmlGetAttrValue(node, "type");
+ item = JabberListGetItemPtr(proto, LIST_ROSTER, from);
+ if (item != NULL) {
+ if (proto->tlenOptions.enableAvatars) {
+ TlenProcessPresenceAvatar(proto, node, item);
+ }
+ }
+ if (type==NULL || (!strcmp(type, "available"))) {
+ if ((nick=JabberLocalNickFromJID(from)) != NULL) {
+ if ((hContact=JabberHContactFromJID(proto, from)) == NULL)
+ hContact = JabberDBCreateContact(proto, from, nick, FALSE);
+ if (!JabberListExist(proto, LIST_ROSTER, from)) {
+ JabberLog(proto, "Receive presence online from %s (who is not in my roster)", from);
+ JabberListAdd(proto, LIST_ROSTER, from);
+ }
+ status = ID_STATUS_ONLINE;
+ if ((showNode=JabberXmlGetChild(node, "show")) != NULL) {
+ if ((show=showNode->text) != NULL) {
+ if (!strcmp(show, "away")) status = ID_STATUS_AWAY;
+ else if (!strcmp(show, "xa")) status = ID_STATUS_NA;
+ else if (!strcmp(show, "dnd")) status = ID_STATUS_DND;
+ else if (!strcmp(show, "chat")) status = ID_STATUS_FREECHAT;
+ else if (!strcmp(show, "unavailable")) {
+ // Always show invisible (on old Tlen client) as invisible (not offline)
+ status = ID_STATUS_OFFLINE;
+ }
+ }
+ }
+
+ statusNode = JabberXmlGetChild(node, "status");
+ if (statusNode)
+ p = JabberTextDecode(statusNode->text);
+ else
+ p = NULL;
+ JabberListAddResource(proto, LIST_ROSTER, from, status, statusNode?p:NULL);
+ if (p) {
+ DBWriteContactSettingString(hContact, "CList", "StatusMsg", p);
+ mir_free(p);
+ } else {
+ DBDeleteContactSetting(hContact, "CList", "StatusMsg");
+ }
+ // Determine status to show for the contact and request version information
+ if (item != NULL) {
+ laststatus = item->status;
+ item->status = status;
+ }
+ if (strchr(from, '@')!=NULL || DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "ShowTransport", TRUE)==TRUE) {
+ if (DBGetContactSettingWord(hContact, proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE) != status)
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "Status", (WORD) status);
+ }
+ if (item != NULL) {
+ if (!item->infoRequested) {
+ int iqId = JabberSerialNext(proto);
+ item->infoRequested = TRUE;
+ JabberSend( proto, "<iq type='get' id='"JABBER_IQID"%d'><query xmlns='jabber:iq:info' to='%s'></query></iq>", iqId, from);
+ }
+ if (proto->tlenOptions.enableVersion && !item->versionRequested) {
+ item->versionRequested = TRUE;
+ if (proto->iface.m_iStatus != ID_STATUS_INVISIBLE) {
+ JabberSend( proto, "<message to='%s' type='iq'><iq type='get'><query xmlns='jabber:iq:version'/></iq></message>", from );
+ }
+ }
+ }
+ JabberLog(proto, "%s (%s) online, set contact status to %d", nick, from, status);
+ mir_free(nick);
+ }
+ }
+ else if (!strcmp(type, "unavailable")) {
+ if (!JabberListExist(proto, LIST_ROSTER, from)) {
+ JabberLog(proto, "Receive presence offline from %s (who is not in my roster)", from);
+ JabberListAdd(proto, LIST_ROSTER, from);
+ }
+ else {
+ JabberListRemoveResource(proto, LIST_ROSTER, from);
+ }
+ status = ID_STATUS_OFFLINE;
+ statusNode = JabberXmlGetChild(node, "status");
+ if (statusNode) {
+ if (proto->tlenOptions.offlineAsInvisible) {
+ status = ID_STATUS_INVISIBLE;
+ }
+ p = JabberTextDecode(statusNode->text);
+ JabberListAddResource(proto, LIST_ROSTER, from, status, p);
+ if ((hContact=JabberHContactFromJID(proto, from)) != NULL) {
+ if (p) {
+ DBWriteContactSettingString(hContact, "CList", "StatusMsg", p);
+ } else {
+ DBDeleteContactSetting(hContact, "CList", "StatusMsg");
+ }
+ }
+ if (p) mir_free(p);
+ }
+ if ((item=JabberListGetItemPtr(proto, LIST_ROSTER, from)) != NULL) {
+ // Determine status to show for the contact based on the remaining resources
+ item->status = status;
+ item->versionRequested = FALSE;
+ item->infoRequested = FALSE;
+ }
+ if ((hContact=JabberHContactFromJID(proto, from)) != NULL) {
+ if (strchr(from, '@')!=NULL || DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "ShowTransport", TRUE)==TRUE) {
+ if (DBGetContactSettingWord(hContact, proto->iface.m_szModuleName, "Status", ID_STATUS_OFFLINE) != status)
+ DBWriteContactSettingWord(hContact, proto->iface.m_szModuleName, "Status", (WORD) status);
+ }
+ if (item != NULL && item->isTyping) {
+ item->isTyping = FALSE;
+ CallService(MS_PROTO_CONTACTISTYPING, (WPARAM) hContact, PROTOTYPE_CONTACTTYPING_OFF);
+ }
+ JabberLog(proto, "%s offline, set contact status to %d", from, status);
+ }
+ }
+ else if (!strcmp(type, "subscribe")) {
+ if (strchr(from, '@') == NULL) {
+ // automatically send authorization allowed to agent/transport
+ JabberSend(proto, "<presence to='%s' type='subscribed'/>", from);
+ }
+ else if ((nick=JabberNickFromJID(from)) != NULL) {
+ JabberLog(proto, "%s (%s) requests authorization", nick, from);
+ JabberDBAddAuthRequest(proto, from, nick);
+ mir_free(nick);
+ }
+ }
+ else if (!strcmp(type, "subscribed")) {
+ if ((item=JabberListGetItemPtr(proto, LIST_ROSTER, from)) != NULL) {
+ if (item->subscription == SUB_FROM) item->subscription = SUB_BOTH;
+ else if (item->subscription == SUB_NONE) {
+ item->subscription = SUB_TO;
+ }
+ }
+ }
+ }
+ }
+}
+
+static void JabberSendPresenceTo(TlenProtocol *proto, int status, char *to)
+{
+ char *showBody, *statusMsg, *presenceType;
+ char *ptr = NULL;
+
+ if (!proto->isOnline) return;
+
+ // Send <presence/> update for status (we won't handle ID_STATUS_OFFLINE here)
+ // Note: jabberModeMsg is already encoded using JabberTextEncode()
+ EnterCriticalSection(&proto->modeMsgMutex);
+
+ showBody = NULL;
+ statusMsg = NULL;
+ presenceType = NULL;
+ switch (status) {
+ case ID_STATUS_ONLINE:
+ showBody = "available";
+ statusMsg = proto->modeMsgs.szOnline;
+ break;
+ case ID_STATUS_AWAY:
+ case ID_STATUS_ONTHEPHONE:
+ case ID_STATUS_OUTTOLUNCH:
+ showBody = "away";
+ statusMsg = proto->modeMsgs.szAway;
+ break;
+ case ID_STATUS_NA:
+ showBody = "xa";
+ statusMsg = proto->modeMsgs.szNa;
+ break;
+ case ID_STATUS_DND:
+ case ID_STATUS_OCCUPIED:
+ showBody = "dnd";
+ statusMsg = proto->modeMsgs.szDnd;
+ break;
+ case ID_STATUS_FREECHAT:
+ showBody = "chat";
+ statusMsg = proto->modeMsgs.szFreechat;
+ break;
+ case ID_STATUS_INVISIBLE:
+ presenceType = "invisible";
+ statusMsg = proto->modeMsgs.szInvisible;
+ break;
+ case ID_STATUS_OFFLINE:
+ presenceType = "unavailable";
+ if (DBGetContactSettingByte(NULL, proto->iface.m_szModuleName, "LeaveOfflineMessage", FALSE)) {
+ int offlineMessageOption = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "OfflineMessageOption", 0);
+ if (offlineMessageOption == 0) {
+ switch (proto->iface.m_iStatus) {
+ case ID_STATUS_ONLINE:
+ ptr = mir_strdup(proto->modeMsgs.szOnline);
+ break;
+ case ID_STATUS_AWAY:
+ case ID_STATUS_ONTHEPHONE:
+ case ID_STATUS_OUTTOLUNCH:
+ ptr = mir_strdup(proto->modeMsgs.szAway);
+ break;
+ case ID_STATUS_NA:
+ ptr = mir_strdup(proto->modeMsgs.szNa);
+ break;
+ case ID_STATUS_DND:
+ case ID_STATUS_OCCUPIED:
+ ptr = mir_strdup(proto->modeMsgs.szDnd);
+ break;
+ case ID_STATUS_FREECHAT:
+ ptr = mir_strdup(proto->modeMsgs.szFreechat);
+ break;
+ case ID_STATUS_INVISIBLE:
+ ptr = mir_strdup(proto->modeMsgs.szInvisible);
+ break;
+ }
+ } else if (offlineMessageOption == 99) {
+
+ } else if (offlineMessageOption < 7) {
+ DBVARIANT dbv;
+ const char *statusNames[] = {"OnDefault", "AwayDefault", "NaDefault", "DndDefault", "FreeChatDefault", "InvDefault"};
+ if (!DBGetContactSetting(NULL, "SRAway", statusNames[offlineMessageOption-1], &dbv)) {
+ int i;
+ char substituteStr[128];
+ ptr = mir_strdup(dbv.pszVal);
+ DBFreeVariant(&dbv);
+ for(i=0;ptr[i];i++) {
+ if(ptr[i]!='%') continue;
+ if(!_strnicmp(ptr+i,"%time%",6))
+ GetTimeFormatA(LOCALE_USER_DEFAULT,TIME_NOSECONDS,NULL,NULL,substituteStr,sizeof(substituteStr));
+ else if(!_strnicmp(ptr+i,"%date%",6))
+ GetDateFormatA(LOCALE_USER_DEFAULT,DATE_SHORTDATE,NULL,NULL,substituteStr,sizeof(substituteStr));
+ else continue;
+ if(strlen(substituteStr)>6) ptr=(char*)mir_realloc(ptr,strlen(ptr)+1+strlen(substituteStr)-6);
+ MoveMemory(ptr+i+strlen(substituteStr),ptr+i+6,strlen(ptr)-i-5);
+ CopyMemory(ptr+i,substituteStr,strlen(substituteStr));
+ }
+ }
+ }
+ }
+ statusMsg = ptr;
+ break;
+ default:
+ // Should not reach here
+ break;
+ }
+ proto->iface.m_iStatus = status;
+ if (presenceType) {
+ if (statusMsg)
+ JabberSend(proto, "<presence type='%s'><status>%s</status></presence>", presenceType, statusMsg);
+ else
+ JabberSend(proto, "<presence type='%s'></presence>", presenceType);
+ } else {
+ if (statusMsg)
+ JabberSend(proto, "<presence><show>%s</show><status>%s</status></presence>", showBody, statusMsg);
+ else
+ JabberSend(proto, "<presence><show>%s</show></presence>", showBody);
+ }
+ if (ptr) {
+ mir_free(ptr);
+ }
+ LeaveCriticalSection(&proto->modeMsgMutex);
+}
+
+void JabberSendPresence(TlenProtocol *proto, int statusIn)
+{
+ int statusOut;
+ switch (statusIn) {
+ case ID_STATUS_ONLINE:
+ case ID_STATUS_OFFLINE:
+ case ID_STATUS_NA:
+ case ID_STATUS_FREECHAT:
+ case ID_STATUS_INVISIBLE:
+ statusOut = statusIn;
+ break;
+ case ID_STATUS_AWAY:
+ case ID_STATUS_ONTHEPHONE:
+ case ID_STATUS_OUTTOLUNCH:
+ default:
+ statusOut = ID_STATUS_AWAY;
+ break;
+ case ID_STATUS_DND:
+ case ID_STATUS_OCCUPIED:
+ statusOut = ID_STATUS_DND;
+ break;
+ }
+ JabberSendPresenceTo(proto, statusOut, NULL);
+}
diff --git a/protocols/Tlen/tlen_presence.h b/protocols/Tlen/tlen_presence.h
new file mode 100644
index 0000000000..fdc3ea642e
--- /dev/null
+++ b/protocols/Tlen/tlen_presence.h
@@ -0,0 +1,37 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2009 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+#ifndef _TLEN_PRESENCE_H
+#define _TLEN_PRESENCE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void TlenProcessPresence(XmlNode *node, TlenProtocol *proto);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _TLEN_PRESENCE_H */
+
diff --git a/protocols/Tlen/tlen_userinfo.c b/protocols/Tlen/tlen_userinfo.c
new file mode 100644
index 0000000000..50345282a9
--- /dev/null
+++ b/protocols/Tlen/tlen_userinfo.c
@@ -0,0 +1,335 @@
+/*
+
+Jabber Protocol Plugin for Miranda IM
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2002-2004 Santithorn Bunchua
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include <commctrl.h>
+#include <io.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include "jabber_list.h"
+#include "resource.h"
+#include "tlen_avatar.h"
+
+JABBER_FIELD_MAP tlenFieldGender[] = {
+ { 1, _T("Male") },
+ { 2, _T("Female") },
+ { 0, NULL }
+};
+JABBER_FIELD_MAP tlenFieldLookfor[] = {
+ { 1, _T("Somebody to talk") },
+ { 2, _T("Friendship") },
+ { 3, _T("Flirt/romance") },
+ { 4, _T("Love") },
+ { 5, _T("Nothing") },
+ { 0, NULL }
+};
+JABBER_FIELD_MAP tlenFieldStatus[] = {
+ { 1, _T("All") },
+ { 2, _T("Available") },
+ { 3, _T("Free for chat") },
+ { 0, NULL }
+};
+JABBER_FIELD_MAP tlenFieldOccupation[] = {
+ { 1, _T("Student") },
+ { 2, _T("College student") },
+ { 3, _T("Farmer") },
+ { 4, _T("Manager") },
+ { 5, _T("Specialist") },
+ { 6, _T("Clerk") },
+ { 7, _T("Unemployed") },
+ { 8, _T("Pensioner") },
+ { 9, _T("Housekeeper") },
+ { 10, _T("Teacher") },
+ { 11, _T("Doctor") },
+ { 12, _T("Other") },
+ { 0, NULL }
+};
+JABBER_FIELD_MAP tlenFieldPlan[] = {
+ { 1, _T("I'd like to go downtown") },
+ { 2, _T("I'd like to go to the cinema") },
+ { 3, _T("I'd like to take a walk") },
+ { 4, _T("I'd like to go to the disco") },
+ { 5, _T("I'd like to go on a blind date") },
+ { 6, _T("Waiting for suggestion") },
+ { 0, NULL }
+};
+
+static INT_PTR CALLBACK TlenUserInfoDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam);
+
+static void InitComboBox(HWND hwndCombo, JABBER_FIELD_MAP *fieldMap)
+{
+ int i, n;
+
+ n = SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM)_T(""));
+ SendMessage(hwndCombo, CB_SETITEMDATA, n, 0);
+ SendMessage(hwndCombo, CB_SETCURSEL, n, 0);
+ for(i=0;;i++) {
+ if (fieldMap[i].name == NULL)
+ break;
+ n = SendMessage(hwndCombo, CB_ADDSTRING, 0, (LPARAM) TranslateTS(fieldMap[i].name));
+ SendMessage(hwndCombo, CB_SETITEMDATA, n, fieldMap[i].id);
+ }
+}
+
+static void FetchField(HWND hwndDlg, UINT idCtrl, char *fieldName, char **str, int *strSize)
+{
+ char text[512];
+ char *localFieldName, *localText;
+
+ if (hwndDlg==NULL || fieldName==NULL || str==NULL || strSize==NULL)
+ return;
+ GetDlgItemTextA(hwndDlg, idCtrl, text, sizeof(text));
+ if (text[0]) {
+ if ((localFieldName=JabberTextEncode(fieldName)) != NULL) {
+ if ((localText=JabberTextEncode(text)) != NULL) {
+ JabberStringAppend(str, strSize, "<%s>%s</%s>", localFieldName, localText, localFieldName);
+ mir_free(localText);
+ }
+ mir_free(localFieldName);
+ }
+ }
+}
+
+static void FetchCombo(HWND hwndDlg, UINT idCtrl, char *fieldName, char **str, int *strSize)
+{
+ int value;
+ char *localFieldName;
+
+ if (hwndDlg==NULL || fieldName==NULL || str==NULL || strSize==NULL)
+ return;
+ value = (int) SendDlgItemMessage(hwndDlg, idCtrl, CB_GETITEMDATA, SendDlgItemMessage(hwndDlg, idCtrl, CB_GETCURSEL, 0, 0), 0);
+ if (value > 0) {
+ if ((localFieldName=JabberTextEncode(fieldName)) != NULL) {
+ JabberStringAppend(str, strSize, "<%s>%d</%s>", localFieldName, value, localFieldName);
+ mir_free(localFieldName);
+ }
+ }
+}
+
+
+int TlenUserInfoInit(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ char *szProto;
+ HANDLE hContact;
+ OPTIONSDIALOGPAGE odp = {0};
+ TlenProtocol *proto = (TlenProtocol *)ptr;
+
+ if (!CallService(MS_PROTO_ISPROTOCOLLOADED, 0, (LPARAM) proto->iface.m_szModuleName))
+ return 0;
+ hContact = (HANDLE) lParam;
+ szProto = (char *) CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM) hContact, 0);
+ if ((szProto!=NULL && !strcmp(szProto, proto->iface.m_szModuleName)) || !lParam) {
+ odp.cbSize = sizeof(odp);
+ odp.hInstance = hInst;
+ odp.flags = ODPF_TCHAR;
+ odp.pfnDlgProc = TlenUserInfoDlgProc;
+ odp.position = -2000000000;
+ odp.pszTemplate = ((HANDLE)lParam!=NULL) ? MAKEINTRESOURCEA(IDD_USER_INFO):MAKEINTRESOURCEA(IDD_USER_VCARD);
+ odp.ptszTitle = (hContact != NULL) ? TranslateT("Account") : proto->iface.m_tszUserName;
+ odp.dwInitParam = (LPARAM)proto;
+ CallService(MS_USERINFO_ADDPAGE, wParam, (LPARAM) &odp);
+
+ }
+ if (!lParam && proto->isOnline) {
+ CCSDATA ccs = {0};
+ JabberGetInfo(ptr, 0, (LPARAM) &ccs);
+ }
+ return 0;
+}
+
+typedef struct {
+ TlenProtocol *proto;
+ HANDLE hContact;
+}TLENUSERINFODLGDATA;
+
+
+static INT_PTR CALLBACK TlenUserInfoDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ TLENUSERINFODLGDATA *data = (TLENUSERINFODLGDATA *) GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+
+ data = (TLENUSERINFODLGDATA*)mir_alloc(sizeof(TLENUSERINFODLGDATA));
+ data->hContact = (HANDLE) lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)data);
+ // lParam is hContact
+ TranslateDialogDefault(hwndDlg);
+ InitComboBox(GetDlgItem(hwndDlg, IDC_GENDER), tlenFieldGender);
+ InitComboBox(GetDlgItem(hwndDlg, IDC_OCCUPATION), tlenFieldOccupation);
+ InitComboBox(GetDlgItem(hwndDlg, IDC_LOOKFOR), tlenFieldLookfor);
+
+ return TRUE;
+ case WM_TLEN_REFRESH:
+ {
+ DBVARIANT dbv;
+ char *jid;
+ int i;
+ JABBER_LIST_ITEM *item;
+
+ SetDlgItemText(hwndDlg, IDC_INFO_JID, _T(""));
+ SetDlgItemText(hwndDlg, IDC_SUBSCRIPTION, _T(""));
+ SetFocus(GetDlgItem(hwndDlg, IDC_STATIC));
+
+ if (!DBGetContactSettingTString(data->hContact, data->proto->iface.m_szModuleName, "FirstName", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_FIRSTNAME, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ } else SetDlgItemText(hwndDlg, IDC_FIRSTNAME, _T(""));
+ if (!DBGetContactSettingTString(data->hContact, data->proto->iface.m_szModuleName, "LastName", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_LASTNAME, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ } else SetDlgItemText(hwndDlg, IDC_LASTNAME, _T(""));
+ if (!DBGetContactSettingTString(data->hContact, data->proto->iface.m_szModuleName, "Nick", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_NICKNAME, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ } else SetDlgItemText(hwndDlg, IDC_NICKNAME, _T(""));
+ if (!DBGetContactSettingTString(data->hContact, data->proto->iface.m_szModuleName, "e-mail", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_EMAIL, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ } else SetDlgItemText(hwndDlg, IDC_EMAIL, _T(""));
+ if (!DBGetContactSetting(data->hContact, data->proto->iface.m_szModuleName, "Age", &dbv)) {
+ SetDlgItemInt(hwndDlg, IDC_AGE, dbv.wVal, FALSE);
+ DBFreeVariant(&dbv);
+ } else SetDlgItemText(hwndDlg, IDC_AGE, _T(""));
+ if (!DBGetContactSettingTString(data->hContact, data->proto->iface.m_szModuleName, "City", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_CITY, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ } else SetDlgItemText(hwndDlg, IDC_CITY, _T(""));
+ if (!DBGetContactSettingTString(data->hContact, data->proto->iface.m_szModuleName, "School", &dbv)) {
+ SetDlgItemText(hwndDlg, IDC_SCHOOL, dbv.ptszVal);
+ DBFreeVariant(&dbv);
+ } else SetDlgItemText(hwndDlg, IDC_SCHOOL, _T(""));
+ switch (DBGetContactSettingByte(data->hContact, data->proto->iface.m_szModuleName, "Gender", '?')) {
+ case 'M':
+ SendDlgItemMessage(hwndDlg, IDC_GENDER, CB_SETCURSEL, 1, 0);
+ SetDlgItemText(hwndDlg, IDC_GENDER_TEXT, TranslateTS(tlenFieldGender[0].name));
+ break;
+ case 'F':
+ SendDlgItemMessage(hwndDlg, IDC_GENDER, CB_SETCURSEL, 2, 0);
+ SetDlgItemText(hwndDlg, IDC_GENDER_TEXT, TranslateTS(tlenFieldGender[1].name));
+ break;
+ default:
+ SendDlgItemMessage(hwndDlg, IDC_GENDER, CB_SETCURSEL, 0, 0);
+ SetDlgItemText(hwndDlg, IDC_GENDER_TEXT, _T(""));
+ break;
+ }
+ i = DBGetContactSettingWord(data->hContact, data->proto->iface.m_szModuleName, "Occupation", 0);
+ if (i>0 && i<13) {
+ SetDlgItemText(hwndDlg, IDC_OCCUPATION_TEXT, TranslateTS(tlenFieldOccupation[i-1].name));
+ SendDlgItemMessage(hwndDlg, IDC_OCCUPATION, CB_SETCURSEL, i, 0);
+ } else {
+ SetDlgItemText(hwndDlg, IDC_OCCUPATION_TEXT, _T(""));
+ SendDlgItemMessage(hwndDlg, IDC_OCCUPATION, CB_SETCURSEL, 0, 0);
+ }
+ i = DBGetContactSettingWord(data->hContact, data->proto->iface.m_szModuleName, "LookingFor", 0);
+ if (i>0 && i<6) {
+ SetDlgItemText(hwndDlg, IDC_LOOKFOR_TEXT, TranslateTS(tlenFieldLookfor[i-1].name));
+ SendDlgItemMessage(hwndDlg, IDC_LOOKFOR, CB_SETCURSEL, i, 0);
+ } else {
+ SetDlgItemText(hwndDlg, IDC_LOOKFOR_TEXT, _T(""));
+ SendDlgItemMessage(hwndDlg, IDC_LOOKFOR, CB_SETCURSEL, 0, 0);
+ }
+ i = DBGetContactSettingWord(data->hContact, data->proto->iface.m_szModuleName, "VoiceChat", 0);
+ CheckDlgButton(hwndDlg, IDC_VOICECONVERSATIONS, i);
+ i = DBGetContactSettingWord(data->hContact, data->proto->iface.m_szModuleName, "PublicStatus", 0);
+ CheckDlgButton(hwndDlg, IDC_PUBLICSTATUS, i);
+ if (!DBGetContactSetting(data->hContact, data->proto->iface.m_szModuleName, "jid", &dbv)) {
+ jid = JabberTextDecode(dbv.pszVal);
+ SetDlgItemTextA(hwndDlg, IDC_INFO_JID, jid);
+ mir_free(jid);
+ jid = dbv.pszVal;
+ if (data->proto->isOnline) {
+ if ((item=JabberListGetItemPtr(data->proto, LIST_ROSTER, jid)) != NULL) {
+ switch (item->subscription) {
+ case SUB_BOTH:
+ SetDlgItemText(hwndDlg, IDC_SUBSCRIPTION, TranslateT("both"));
+ break;
+ case SUB_TO:
+ SetDlgItemText(hwndDlg, IDC_SUBSCRIPTION, TranslateT("to"));
+ break;
+ case SUB_FROM:
+ SetDlgItemText(hwndDlg, IDC_SUBSCRIPTION, TranslateT("from"));
+ break;
+ default:
+ SetDlgItemText(hwndDlg, IDC_SUBSCRIPTION, TranslateT("none"));
+ break;
+ }
+ SetDlgItemTextA(hwndDlg, IDC_SOFTWARE, item->software);
+ SetDlgItemTextA(hwndDlg, IDC_VERSION, item->version);
+ SetDlgItemTextA(hwndDlg, IDC_SYSTEM, item->system);
+ } else {
+ SetDlgItemText(hwndDlg, IDC_SUBSCRIPTION, TranslateT("not on roster"));
+ }
+ }
+ DBFreeVariant(&dbv);
+ }
+ }
+ break;
+ case WM_NOTIFY:
+ switch (((LPNMHDR)lParam)->idFrom) {
+ case 0:
+ switch (((LPNMHDR)lParam)->code) {
+ case PSN_INFOCHANGED:
+ {
+ HANDLE hContact = (HANDLE) ((LPPSHNOTIFY) lParam)->lParam;
+ SendMessage(hwndDlg, WM_TLEN_REFRESH, 0, (LPARAM) hContact);
+ }
+ break;
+ case PSN_PARAMCHANGED:
+ {
+ data->proto = ( TlenProtocol* )(( LPPSHNOTIFY )lParam )->lParam;
+ SendMessage(hwndDlg, WM_TLEN_REFRESH, 0, 0);
+ }
+ }
+ break;
+ }
+ break;
+ case WM_COMMAND:
+ if (LOWORD(wParam)==IDC_SAVE && HIWORD(wParam)==BN_CLICKED) {
+ char *str = NULL;
+ int strSize;
+ JabberStringAppend(&str, &strSize, "<iq type='set' id='"JABBER_IQID"%d' to='tuba'><query xmlns='jabber:iq:register'>", JabberSerialNext(data->proto));
+ FetchField(hwndDlg, IDC_FIRSTNAME, "first", &str, &strSize);
+ FetchField(hwndDlg, IDC_LASTNAME, "last", &str, &strSize);
+ FetchField(hwndDlg, IDC_NICKNAME, "nick", &str, &strSize);
+ FetchField(hwndDlg, IDC_EMAIL, "email", &str, &strSize);
+ FetchCombo(hwndDlg, IDC_GENDER, "s", &str, &strSize);
+ FetchField(hwndDlg, IDC_AGE, "b", &str, &strSize);
+ FetchField(hwndDlg, IDC_CITY, "c", &str, &strSize);
+ FetchCombo(hwndDlg, IDC_OCCUPATION, "j", &str, &strSize);
+ FetchField(hwndDlg, IDC_SCHOOL, "e", &str, &strSize);
+ FetchCombo(hwndDlg, IDC_LOOKFOR, "r", &str, &strSize);
+ JabberStringAppend(&str, &strSize, "<g>%d</g>", IsDlgButtonChecked(hwndDlg, IDC_VOICECONVERSATIONS) ? 1 : 0);
+ JabberStringAppend(&str, &strSize, "<v>%d</v>", IsDlgButtonChecked(hwndDlg, IDC_PUBLICSTATUS) ? 1 : 0);
+ JabberStringAppend(&str, &strSize, "</query></iq>");
+ JabberSend(data->proto, "%s", str);
+ mir_free(str);
+ JabberGetInfo((PROTO_INTERFACE *)data->proto, NULL, 0);
+ }
+ break;
+ case WM_DESTROY:
+ mir_free(data);
+ break;
+ }
+ return FALSE;
+}
diff --git a/protocols/Tlen/tlen_voice.c b/protocols/Tlen/tlen_voice.c
new file mode 100644
index 0000000000..4c4868152c
--- /dev/null
+++ b/protocols/Tlen/tlen_voice.c
@@ -0,0 +1,1122 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#include "jabber.h"
+#include <io.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <math.h>
+#include <m_button.h>
+//#include <win2k.h>
+#include "resource.h"
+#include "jabber_list.h"
+#include "tlen_voice.h"
+#include "tlen_p2p_old.h"
+#include "tlen_file.h"
+
+static int MODE_FREQUENCY[]= {0, 0, 8000, 11025, 22050, 44100};
+static int MODE_FRAME_SIZE[]= {0, 0, 5, 5, 10, 25};
+static int FRAMES_AVAILABLE_MAX_LIMIT = 2;
+static int VU_METER_HEIGHT = 64;
+static int VU_METER_WIDTH = 20;
+static int VU_METER_LEVELS = 16;
+static HBITMAP vuMeterBitmaps[100];
+
+static void TlenVoiceReceiveParse(TLEN_FILE_TRANSFER *ft);
+static void TlenVoiceSendParse(TLEN_FILE_TRANSFER *ft);
+static void TlenVoiceReceivingConnection(HANDLE hNewConnection, DWORD dwRemoteIP, void * pExtra);
+
+static void CALLBACK TlenVoicePlaybackCallback(HWAVEOUT hwo, UINT uMsg, DWORD* dwInstance, DWORD dwParam1, DWORD dwParam2)
+{
+ if (uMsg == WOM_DONE) {
+ TLEN_VOICE_CONTROL *control = (TLEN_VOICE_CONTROL *) dwInstance;
+ waveOutUnprepareHeader(hwo, (WAVEHDR *) dwParam1, sizeof(WAVEHDR));
+ if (control->proto->framesAvailableForPlayback > 0) {
+ control->proto->framesAvailableForPlayback--;
+ }
+// playbackControl->waveHeaders[playbackControl->waveHeadersPos].dwFlags = WHDR_DONE;
+// playbackControl->waveHeaders[playbackControl->waveHeadersPos].lpData = (char *) (playbackControl->waveData + playbackControl->waveHeadersPos * playbackControl->waveFrameSize);
+// playbackControl->waveHeaders[playbackControl->waveHeadersPos].dwBufferLength = playbackControl->waveFrameSize * 2;
+// waveOutPrepareHeader(playbackControl->hWaveOut, &playbackControl->waveHeaders[playbackControl->waveHeadersPos], sizeof(WAVEHDR));
+// waveOutWrite(playbackControl->hWaveOut, &playbackControl->waveHeaders[playbackControl->waveHeadersPos], sizeof(WAVEHDR));
+
+ }
+}
+
+static DWORD WINAPI TlenVoiceRecordingThreadProc(TLEN_VOICE_CONTROL *control)
+{
+ MSG msg;
+ HWAVEIN hWaveIn;
+ WAVEHDR *hWaveHdr;
+ control->isRunning = 1;
+ control->stopThread = 0;
+ while (TRUE) {
+ GetMessage(&msg,NULL,0,0);
+ if (msg.message == MM_WIM_DATA) {
+// JabberLog("recording thread running...%d", msg.message);
+ hWaveIn = (HWAVEIN) msg.wParam;
+ hWaveHdr = (WAVEHDR *) msg.lParam;
+ waveInUnprepareHeader(hWaveIn, hWaveHdr, sizeof(WAVEHDR));
+ if (hWaveHdr->dwBytesRecorded>0 && !control->bDisable) {
+ control->recordingData = (short *)hWaveHdr->lpData;
+ TlenVoiceSendParse(control->ft);
+ }
+ if (!control->stopThread) {
+ waveInPrepareHeader(hWaveIn, &control->waveHeaders[control->waveHeadersPos], sizeof(WAVEHDR));
+ waveInAddBuffer(hWaveIn, &control->waveHeaders[control->waveHeadersPos], sizeof(WAVEHDR));
+ control->waveHeadersPos = (control->waveHeadersPos +1) % control->waveHeadersNum;
+ }
+ }
+ else if (msg.message == MM_WIM_CLOSE) {
+ break;
+ }
+ }
+ control->isRunning = 0;
+ JabberLog(control->proto, "recording thread ended...");
+ return 0;
+}
+
+
+/*static void CALLBACK TlenVoiceRecordingCallback(HWAVEIN hwi, UINT uMsg, DWORD* dwInstance, DWORD dwParam1, DWORD dwParam2)
+{
+ if (uMsg == WIM_DATA) {
+ TLEN_VOICE_CONTROL *control = (TLEN_VOICE_CONTROL *) dwInstance;
+ if (control->waveHeaders[control->waveHeadersPos].dwBytesRecorded>0) {
+ control->recordingData = (short *)control->waveHeaders[control->waveHeadersPos].lpData;
+ TlenVoiceSendParse(control->ft);
+ }
+ waveInAddBuffer(control->hWaveIn, &control->waveHeaders[control->waveHeadersPos], sizeof(WAVEHDR));
+ control->waveHeadersPos = (control->waveHeadersPos +1) % control->waveHeadersNum;
+ }
+}*/
+
+static int TlenVoicePlaybackStart(TLEN_VOICE_CONTROL *control)
+{
+ WAVEFORMATEX wfm;
+ MMRESULT mmres;
+ int i, j;
+ int iNumDevs, iSelDev;
+ WAVEOUTCAPS wic;
+
+ memset(&wfm, 0, sizeof(wfm));
+ wfm.cbSize = sizeof(WAVEFORMATEX);
+ wfm.nChannels = 1;
+ wfm.wBitsPerSample = 16;
+ wfm.nSamplesPerSec = MODE_FREQUENCY[control->codec];
+ wfm.nAvgBytesPerSec = wfm.nSamplesPerSec * wfm.nChannels * wfm.wBitsPerSample/8;
+ wfm.nBlockAlign = 2 * wfm.nChannels;
+ wfm.wFormatTag = WAVE_FORMAT_PCM;
+
+ control->waveMode = 0;
+ control->waveFrameSize = MODE_FRAME_SIZE[control->codec] * 160 * wfm.nChannels;// * wfm.wBitsPerSample / 8;
+ control->waveHeadersPos = 0;
+ control->waveHeadersNum = FRAMES_AVAILABLE_MAX_LIMIT + 2;
+
+ j = DBGetContactSettingWord(NULL, control->proto->iface.m_szModuleName, "VoiceDeviceOut", 0);
+ iSelDev = WAVE_MAPPER;
+ if (j!=0) {
+ iNumDevs = waveOutGetNumDevs();
+ for (i = 0; i < iNumDevs; i++) {
+ if (!waveOutGetDevCaps(i, &wic, sizeof(WAVEOUTCAPS))) {
+ if (wic.dwFormats != 0) {
+ j--;
+ if (j == 0) {
+ iSelDev = i;
+ break;
+ }
+ }
+ }
+ }
+ }
+ if (!waveOutGetDevCaps(iSelDev, &wic, sizeof(WAVEOUTCAPS))) {
+ JabberLog(control->proto, "Playback device ID #%u: %s\r\n", iSelDev, wic.szPname);
+ }
+
+ mmres = waveOutOpen(&control->hWaveOut, iSelDev, &wfm, (DWORD) &TlenVoicePlaybackCallback, (DWORD) control, CALLBACK_FUNCTION);
+ if (mmres!=MMSYSERR_NOERROR) {
+ JabberLog(control->proto, "TlenVoiceStart FAILED!");
+ return 1;
+ }
+ control->waveData = (short *)mir_alloc(control->waveHeadersNum * control->waveFrameSize * 2);
+ memset(control->waveData, 0, control->waveHeadersNum * control->waveFrameSize * 2);
+ control->waveHeaders = (WAVEHDR *)mir_alloc(control->waveHeadersNum * sizeof(WAVEHDR));
+ JabberLog(control->proto, "TlenVoiceStart OK!");
+ return 0;
+}
+
+
+static int TlenVoiceRecordingStart(TLEN_VOICE_CONTROL *control)
+{
+ WAVEFORMATEX wfm;
+ MMRESULT mmres;
+ int i, j;
+ int iNumDevs, iSelDev;
+ WAVEINCAPS wic;
+
+ memset(&wfm, 0, sizeof(wfm));
+ wfm.cbSize = sizeof(WAVEFORMATEX);
+ wfm.nChannels = 1;
+ wfm.wBitsPerSample = 16;
+ wfm.nSamplesPerSec = MODE_FREQUENCY[control->codec];
+ wfm.nAvgBytesPerSec = wfm.nSamplesPerSec * wfm.nChannels * wfm.wBitsPerSample/8;
+ wfm.nBlockAlign = 2 * wfm.nChannels;
+ wfm.wFormatTag = WAVE_FORMAT_PCM;
+
+
+ control->waveMode = 0;
+// control->isRunning = 1;
+ control->waveFrameSize = MODE_FRAME_SIZE[control->codec] * 160 * wfm.nChannels;// * wfm.wBitsPerSample / 8;
+ control->waveHeadersPos = 0;
+ control->waveHeadersNum = 2;
+
+ control->hThread = CreateThread( NULL,
+ 0,
+ (LPTHREAD_START_ROUTINE)TlenVoiceRecordingThreadProc,
+ control,
+ 0,
+ (LPDWORD)&control->threadID);
+
+
+ SetThreadPriority(control->hThread, THREAD_PRIORITY_ABOVE_NORMAL);
+
+ j = DBGetContactSettingWord(NULL, control->proto->iface.m_szModuleName, "VoiceDeviceIn", 0);
+ iSelDev = WAVE_MAPPER;
+ if (j!=0) {
+ iNumDevs = waveInGetNumDevs();
+ for (i = 0; i < iNumDevs; i++) {
+ if (!waveInGetDevCaps(i, &wic, sizeof(WAVEINCAPS))) {
+ if (wic.dwFormats != 0) {
+ j--;
+ if (j == 0) {
+ iSelDev = i;
+ break;
+ }
+ }
+ }
+ }
+ }
+ if (!waveInGetDevCaps(iSelDev, &wic, sizeof(WAVEINCAPS))) {
+ JabberLog(control->proto, "Recording device ID #%u: %s\r\n", iSelDev, wic.szPname);
+ }
+
+ mmres = waveInOpen(&control->hWaveIn, iSelDev, &wfm, (DWORD) control->threadID, 0, CALLBACK_THREAD);
+// mmres = waveInOpen(&control->hWaveIn, 3, &wfm, (DWORD) &TlenVoiceRecordingCallback, (DWORD) control, CALLBACK_FUNCTION);
+ if (mmres!=MMSYSERR_NOERROR) {
+ PostThreadMessage(control->threadID, WIM_CLOSE, 0, 0);
+ JabberLog(control->proto, "TlenVoiceStart FAILED %d!", mmres);
+ return 1;
+ }
+ control->waveData = (short *)mir_alloc(control->waveHeadersNum * control->waveFrameSize * 2);
+ memset(control->waveData, 0, control->waveHeadersNum * control->waveFrameSize * 2);
+ control->waveHeaders = (WAVEHDR *)mir_alloc(control->waveHeadersNum * sizeof(WAVEHDR));
+ for (i=0;i<control->waveHeadersNum;i++) {
+ control->waveHeaders[i].dwFlags = 0;//WHDR_DONE;
+ control->waveHeaders[i].lpData = (char *) (control->waveData + i * control->waveFrameSize);
+ control->waveHeaders[i].dwBufferLength = control->waveFrameSize *2;
+ mmres = waveInPrepareHeader(control->hWaveIn, &control->waveHeaders[i], sizeof(WAVEHDR));
+ if (mmres!=MMSYSERR_NOERROR) {
+ waveInClose(control->hWaveIn);
+// PostThreadMessage(control->threadID, WIM_CLOSE, 0, 0);
+ JabberLog(control->proto, "TlenVoiceStart FAILED #2!");
+ return 1;
+ }
+ }
+ for (i=0;i<control->waveHeadersNum;i++) {
+ waveInAddBuffer(control->hWaveIn, &control->waveHeaders[i], sizeof(WAVEHDR));
+ }
+ waveInStart(control->hWaveIn);
+ JabberLog(control->proto, "TlenVoiceRStart OK!");
+ return 0;
+}
+
+
+static TLEN_VOICE_CONTROL *TlenVoiceCreateVC(TlenProtocol *proto, int codec)
+{
+ TLEN_VOICE_CONTROL *vc;
+ vc = (TLEN_VOICE_CONTROL *) mir_alloc(sizeof (TLEN_VOICE_CONTROL));
+ memset(vc, 0, sizeof(TLEN_VOICE_CONTROL));
+ vc->gsmstate = gsm_create();
+ vc->codec = codec;
+ vc->proto = proto;
+ return vc;
+}
+static void TlenVoiceFreeVc(TLEN_VOICE_CONTROL *vc)
+{
+ int i;
+ JabberLog(vc->proto, "-> TlenVoiceFreeVc");
+ vc->stopThread = 1;
+ PostThreadMessage(vc->threadID, MM_WIM_CLOSE, 0, 0);
+ while(vc->isRunning) {
+ Sleep(50);
+ }
+ if (vc->hThread!=NULL) CloseHandle(vc->hThread);
+ if (vc->hWaveIn) {
+ for (i=0;i<vc->waveHeadersNum;i++) {
+ while(waveInUnprepareHeader(vc->hWaveIn, &vc->waveHeaders[i], sizeof(WAVEHDR)) == WAVERR_STILLPLAYING) {
+ Sleep(50);
+ }
+ }
+ while(waveInClose(vc->hWaveIn) == WAVERR_STILLPLAYING) {
+ Sleep(50);
+ }
+ }
+ if (vc->hWaveOut) {
+ for (i=0;i<vc->waveHeadersNum;i++) {
+ while(waveOutUnprepareHeader(vc->hWaveOut, &vc->waveHeaders[i], sizeof(WAVEHDR)) == WAVERR_STILLPLAYING) {
+ Sleep(50);
+ }
+ }
+ while(waveOutClose(vc->hWaveOut) == WAVERR_STILLPLAYING) {
+ Sleep(50);
+ }
+ }
+ if (vc->waveData) mir_free(vc->waveData);
+ if (vc->waveHeaders) mir_free(vc->waveHeaders);
+ if (vc->gsmstate) gsm_release(vc->gsmstate);
+ JabberLog(vc->proto, "<- TlenVoiceFreeVc");
+ mir_free(vc);
+}
+
+static void TlenVoiceCrypt(char *buffer, int len)
+{
+ int i, j, k;
+ j = 0x71;
+ for (i=0;i<len;i++) {
+ k = j;
+ j = j << 6;
+ j += k;
+ j = k + (j << 1);
+ j += 0xBB;
+ buffer[i]^=j;
+ }
+}
+
+void __cdecl TlenVoiceReceiveThread(TLEN_FILE_TRANSFER *ft)
+{
+ NETLIBOPENCONNECTION nloc;
+ JABBER_SOCKET s;
+
+ JabberLog(ft->proto, "Thread started: type=file_receive server='%s' port='%d'", ft->hostName, ft->wPort);
+ nloc.cbSize = NETLIBOPENCONNECTION_V1_SIZE;//sizeof(NETLIBOPENCONNECTION);
+ nloc.szHost = ft->hostName;
+ nloc.wPort = ft->wPort;
+ nloc.flags = 0;
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Connecting..."));
+// ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, ft, 0);
+ s = (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) ft->proto->hNetlibUser, (LPARAM) &nloc);
+ if (s != NULL) {
+ ft->s = s;
+ JabberLog(ft->proto, "Entering file receive loop");
+ TlenP2PEstablishOutgoingConnection(ft, FALSE);
+ if (ft->state!=FT_ERROR) {
+ ft->proto->playbackControl = NULL;
+ ft->proto->recordingControl = TlenVoiceCreateVC(ft->proto, 3);
+ ft->proto->recordingControl->ft = ft;
+ TlenVoiceRecordingStart(ft->proto->recordingControl);
+ while (ft->state!=FT_DONE && ft->state!=FT_ERROR) {
+ TlenVoiceReceiveParse(ft);
+ }
+ TlenVoiceFreeVc(ft->proto->recordingControl);
+ ft->proto->playbackControl = NULL;
+ ft->proto->recordingControl = NULL;
+ }
+ if (ft->s) {
+ Netlib_CloseHandle(s);
+ }
+ ft->s = NULL;
+ } else {
+ JabberLog(ft->proto, "Connection failed - receiving as server");
+ ft->pfnNewConnectionV2 = TlenVoiceReceivingConnection;
+ s = TlenP2PListen(ft);
+ if (s != NULL) {
+ HANDLE hEvent;
+ char *nick;
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Waiting for connection..."));
+ ft->s = s;
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ ft->hFileEvent = hEvent;
+ ft->currentFile = 0;
+ ft->state = FT_CONNECTING;
+ nick = JabberNickFromJID(ft->jid);
+ JabberSend(ft->proto, "<v t='%s' i='%s' e='7' a='%s' p='%d'/>", nick, ft->iqId, ft->localName, ft->wLocalPort);
+ mir_free(nick);
+ JabberLog(ft->proto, "Waiting for the file to be received...");
+ WaitForSingleObject(hEvent, INFINITE);
+ ft->hFileEvent = NULL;
+ CloseHandle(hEvent);
+ JabberLog(ft->proto, "Finish all files");
+ Netlib_CloseHandle(s);
+ } else {
+ ft->state = FT_ERROR;
+ }
+ }
+ JabberListRemove(ft->proto, LIST_VOICE, ft->iqId);
+ if (ft->state==FT_DONE) {
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Finished..."));
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ } else {
+ char *nick;
+ nick = JabberNickFromJID(ft->jid);
+ JabberSend(ft->proto, "<f t='%s' i='%s' e='8'/>", nick, ft->iqId);
+ mir_free(nick);
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Error..."));
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ }
+ JabberLog(ft->proto, "Thread ended: type=file_receive server='%s'", ft->hostName);
+
+ TlenP2PFreeFileTransfer(ft);
+}
+
+static void TlenVoiceReceivingConnection(JABBER_SOCKET hConnection, DWORD dwRemoteIP, void * pExtra)
+{
+ JABBER_SOCKET slisten;
+ TLEN_FILE_TRANSFER *ft;
+ TlenProtocol *proto = (TlenProtocol *)pExtra;
+
+ ft = TlenP2PEstablishIncomingConnection(proto, hConnection, LIST_VOICE, FALSE);
+ if (ft != NULL) {
+ slisten = ft->s;
+ ft->s = hConnection;
+ JabberLog(ft->proto, "Set ft->s to %d (saving %d)", hConnection, slisten);
+ JabberLog(ft->proto, "Entering send loop for this file connection... (ft->s is hConnection)");
+ proto->playbackControl = NULL;
+ proto->recordingControl = TlenVoiceCreateVC(proto, 3);
+ proto->recordingControl->ft = ft;
+ TlenVoiceRecordingStart(proto->recordingControl);
+ while (ft->state!=FT_DONE && ft->state!=FT_ERROR) {
+ TlenVoiceReceiveParse(ft);
+ }
+ TlenVoiceFreeVc(proto->recordingControl);
+ proto->playbackControl = NULL;
+ proto->recordingControl = NULL;
+ if (ft->state==FT_DONE) {
+ SetDlgItemText(proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Finished..."));
+// ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ } else {
+// ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Error..."));
+ }
+ JabberLog(ft->proto, "Closing connection for this file transfer... (ft->s is now hBind)");
+ ft->s = slisten;
+ JabberLog(ft->proto, "ft->s is restored to %d", ft->s);
+ }
+ Netlib_CloseHandle(hConnection);
+ if (ft!=NULL && ft->hFileEvent != NULL)
+ SetEvent(ft->hFileEvent);
+}
+
+static void TlenVoiceReceiveParse(TLEN_FILE_TRANSFER *ft)
+{
+ char *statusTxt;
+ int i, j;
+ char *p;
+ float val;
+ TLEN_FILE_PACKET *packet;
+ packet = TlenP2PPacketReceive(ft->s);
+ if (packet != NULL) {
+ statusTxt = " Unknown packet ";
+ p = packet->packet;
+ if (packet->type == TLEN_VOICE_PACKET) {
+ short *out;
+ int codec, chunkNum;
+ statusTxt = " OK ";
+ TlenVoiceCrypt(packet->packet+4, packet->len-4);
+ codec = *((int *)packet->packet);
+ if (codec<2 || codec>5) {
+ statusTxt = " Unknown codec ";
+ } else {
+ if (ft->proto->playbackControl == NULL) {
+ ft->proto->playbackControl = TlenVoiceCreateVC(ft->proto, codec);
+ TlenVoicePlaybackStart(ft->proto->playbackControl);
+ ft->proto->framesAvailableForPlayback = 0;
+ ft->proto->availOverrunValue = 0;
+ } else if (ft->proto->playbackControl->codec != codec) {
+ TlenVoiceFreeVc(ft->proto->playbackControl);
+ ft->proto->playbackControl = TlenVoiceCreateVC(ft->proto, codec);
+ TlenVoicePlaybackStart(ft->proto->playbackControl);
+ ft->proto->framesAvailableForPlayback = 0;
+ ft->proto->availOverrunValue = 0;
+ }
+ if (!ft->proto->playbackControl->bDisable) {
+ ft->proto->playbackControl->waveHeaders[ft->proto->playbackControl->waveHeadersPos].dwFlags = WHDR_DONE;
+ ft->proto->playbackControl->waveHeaders[ft->proto->playbackControl->waveHeadersPos].lpData = (char *) (ft->proto->playbackControl->waveData + ft->proto->playbackControl->waveHeadersPos * ft->proto->playbackControl->waveFrameSize);
+ ft->proto->playbackControl->waveHeaders[ft->proto->playbackControl->waveHeadersPos].dwBufferLength = ft->proto->playbackControl->waveFrameSize * 2;
+ /*
+ if (availPlayback == 0) {
+ statusTxt = "!! Buffer is empty !!";
+ availPlayback++;
+ waveOutPrepareHeader(playbackControl->hWaveOut, &playbackControl->waveHeaders[playbackControl->waveHeadersPos], sizeof(WAVEHDR));
+ waveOutWrite(playbackControl->hWaveOut, &playbackControl->waveHeaders[playbackControl->waveHeadersPos], sizeof(WAVEHDR));
+ playbackControl->waveHeadersPos = (playbackControl->waveHeadersPos +1) % playbackControl->waveHeadersNum;
+ playbackControl->waveHeaders[playbackControl->waveHeadersPos].dwFlags = WHDR_DONE;
+ playbackControl->waveHeaders[playbackControl->waveHeadersPos].lpData = (char *) (playbackControl->waveData + playbackControl->waveHeadersPos * playbackControl->waveFrameSize);
+ playbackControl->waveHeaders[playbackControl->waveHeadersPos].dwBufferLength = playbackControl->waveFrameSize * 2;
+ }
+ */
+ chunkNum = min(MODE_FRAME_SIZE[codec], (int)(packet->len - 4) / 33);
+ out = (short *)ft->proto->playbackControl->waveHeaders[ft->proto->playbackControl->waveHeadersPos].lpData;
+ for (i=0; i<chunkNum; i++) {
+ for (j=0;j<33;j++) {
+ ft->proto->playbackControl->gsmstate->gsmFrame[j] = packet->packet[i*33 +j +4];
+ }
+ gsm_decode(ft->proto->playbackControl->gsmstate, out);
+ out += 160;
+ }
+ out = (short *)ft->proto->playbackControl->waveHeaders[ft->proto->playbackControl->waveHeadersPos].lpData;
+ val = 0;
+ for (i=0; i<MODE_FRAME_SIZE[codec] * 160; i+=MODE_FRAME_SIZE[codec]) {
+ val += out[i]*out[i];
+ }
+ j = (int)((log10(val) - 4) * 2.35);
+ if (j > VU_METER_LEVELS - 1 ) {
+ j = VU_METER_LEVELS - 1;
+ } else if (j<0) {
+ j = 0;
+ }
+ ft->proto->playbackControl->vuMeter = j;
+ ft->proto->playbackControl->bytesSum += 8 + packet->len;
+ /* Simple logic to avoid huge delays. If a delay is detected a frame is not played */
+ j = ft->proto->availOverrunValue > 0 ? -1 : 0;
+ while (ft->proto->framesAvailableForPlayback > FRAMES_AVAILABLE_MAX_LIMIT) {
+ j = 1;
+ SleepEx(5, FALSE);
+ }
+ ft->proto->availOverrunValue += j;
+ /* 40 frames - 800ms/8kHz */
+ if (ft->proto->availOverrunValue < 40) {
+ ft->proto->framesAvailableForPlayback++;
+ waveOutPrepareHeader(ft->proto->playbackControl->hWaveOut, &ft->proto->playbackControl->waveHeaders[ft->proto->playbackControl->waveHeadersPos], sizeof(WAVEHDR));
+ waveOutWrite(ft->proto->playbackControl->hWaveOut, &ft->proto->playbackControl->waveHeaders[ft->proto->playbackControl->waveHeadersPos], sizeof(WAVEHDR));
+ ft->proto->playbackControl->waveHeadersPos = (ft->proto->playbackControl->waveHeadersPos +1) % ft->proto->playbackControl->waveHeadersNum;
+ } else {
+ ft->proto->availOverrunValue -= 10;
+ statusTxt = "!! Skipping frame !!";
+ }
+ }
+ }
+ }
+ {
+ char ttt[2048];
+ sprintf(ttt, "%s %d %d ", statusTxt, ft->proto->framesAvailableForPlayback, ft->proto->availOverrunValue);
+ SetDlgItemTextA(ft->proto->voiceDlgHWND, IDC_STATUS, ttt);
+ }
+ TlenP2PPacketFree(packet);
+ }
+ else {
+ if (ft->proto->playbackControl!=NULL) {
+ TlenVoiceFreeVc(ft->proto->playbackControl);
+ ft->proto->playbackControl = NULL;
+ }
+ ft->state = FT_ERROR;
+ }
+}
+
+
+void __cdecl TlenVoiceSendingThread(TLEN_FILE_TRANSFER *ft)
+{
+ JABBER_SOCKET s = NULL;
+ HANDLE hEvent;
+ char *nick;
+
+ JabberLog(ft->proto, "Thread started: type=voice_send");
+ ft->pfnNewConnectionV2 = TlenVoiceReceivingConnection;
+ s = TlenP2PListen(ft);
+ if (s != NULL) {
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Waiting for connection..."));
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, ft, 0);
+ ft->s = s;
+ //JabberLog("ft->s = %d", s);
+ //JabberLog("fileCount = %d", ft->fileCount);
+
+ hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+ ft->hFileEvent = hEvent;
+ ft->currentFile = 0;
+ ft->state = FT_CONNECTING;
+
+ nick = JabberNickFromJID(ft->jid);
+ JabberSend(ft->proto, "<v t='%s' i='%s' e='6' a='%s' p='%d'/>", nick, ft->iqId, ft->localName, ft->wLocalPort);
+ mir_free(nick);
+ JabberLog(ft->proto, "Waiting for the voice data to be sent...");
+ WaitForSingleObject(hEvent, INFINITE);
+ ft->hFileEvent = NULL;
+ CloseHandle(hEvent);
+ JabberLog(ft->proto, "Finish voice");
+ Netlib_CloseHandle(s);
+ ft->s = NULL;
+ JabberLog(ft->proto, "ft->s is NULL");
+
+ if (ft->state == FT_SWITCH) {
+ NETLIBOPENCONNECTION nloc;
+ JABBER_SOCKET s;
+ JabberLog(ft->proto, "Sending as client...");
+ ft->state = FT_CONNECTING;
+ nloc.cbSize = NETLIBOPENCONNECTION_V1_SIZE;//sizeof(NETLIBOPENCONNECTION);
+ nloc.szHost = ft->hostName;
+ nloc.wPort = ft->wPort;
+ nloc.flags = 0;
+ s = (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) ft->proto->hNetlibUser, (LPARAM) &nloc);
+ if (s != NULL) {
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Connecting..."));
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, ft, 0);
+ ft->s = s;
+ TlenP2PEstablishOutgoingConnection(ft, FALSE);
+ if (ft->state!=FT_ERROR) {
+ JabberLog(ft->proto, "Entering send loop for this file connection...");
+ ft->proto->playbackControl = NULL;
+ ft->proto->recordingControl = TlenVoiceCreateVC(ft->proto, 3);
+ ft->proto->recordingControl->ft = ft;
+ TlenVoiceRecordingStart(ft->proto->recordingControl);
+ while (ft->state!=FT_DONE && ft->state!=FT_ERROR) {
+ TlenVoiceReceiveParse(ft);
+ }
+ }
+ JabberLog(ft->proto, "Closing connection for this file transfer... ");
+ Netlib_CloseHandle(s);
+ } else {
+ ft->state = FT_ERROR;
+ }
+ }
+ } else {
+ JabberLog(ft->proto, "Cannot allocate port to bind for file server thread, thread ended.");
+ ft->state = FT_ERROR;
+ }
+ JabberListRemove(ft->proto, LIST_VOICE, ft->iqId);
+ switch (ft->state) {
+ case FT_DONE:
+ JabberLog(ft->proto, "Finish successfully");
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Finished..."));
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
+ break;
+ case FT_DENIED:
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Denied..."));
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_DENIED, ft, 0);
+ break;
+ default: // FT_ERROR:
+ nick = JabberNickFromJID(ft->jid);
+ JabberSend(ft->proto, "<v t='%s' i='%s' e='8'/>", nick, ft->iqId);
+ mir_free(nick);
+ JabberLog(ft->proto, "Finish with errors");
+ SetDlgItemText(ft->proto->voiceDlgHWND, IDC_STATUS, TranslateT("...Error..."));
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ break;
+ }
+ JabberLog(ft->proto, "Thread ended: type=voice_send");
+ TlenP2PFreeFileTransfer(ft);
+}
+
+static void TlenVoiceSendParse(TLEN_FILE_TRANSFER *ft)
+{
+ int codec, i;
+ TLEN_FILE_PACKET *packet;
+
+ codec = ft->proto->recordingControl->codec;
+ if ((packet=TlenP2PPacketCreate(sizeof(DWORD)+MODE_FRAME_SIZE[codec]*33)) != NULL) {
+ short *in;
+ float val;
+ in = ft->proto->recordingControl->recordingData;
+ TlenP2PPacketSetType(packet, 0x96);
+ packet->packet[0] = codec;
+ TlenP2PPacketPackDword(packet, codec);
+ val = 0;
+ for (i=0; i<MODE_FRAME_SIZE[codec] * 160; i+=MODE_FRAME_SIZE[codec]) {
+ val += in[i]*in[i];
+ }
+ i = (int)((log10(val) - 4) * 2.35);
+ if (i > VU_METER_LEVELS - 1 ) {
+ i = VU_METER_LEVELS - 1;
+ } else if (i<0) {
+ i = 0;
+ }
+ ft->proto->recordingControl->vuMeter = i;
+ for (i=0; i<MODE_FRAME_SIZE[codec]; i++) {
+ gsm_encode(ft->proto->recordingControl->gsmstate, in + i * 160);
+ TlenP2PPacketPackBuffer(packet, (char*)ft->proto->recordingControl->gsmstate->gsmFrame, 33);
+ }
+ TlenVoiceCrypt(packet->packet+4, packet->len-4);
+ if (!TlenP2PPacketSend(ft->s, packet)) {
+ ft->state = FT_ERROR;
+ }
+ ft->proto->recordingControl->bytesSum += 8 + packet->len;
+ TlenP2PPacketFree(packet);
+ } else {
+ ft->state = FT_ERROR;
+ }
+}
+
+int TlenVoiceCancelAll(TlenProtocol *proto)
+{
+ JABBER_LIST_ITEM *item;
+ HANDLE hEvent;
+ int i = 0;
+
+ while ((i=JabberListFindNext(proto, LIST_VOICE, 0)) >=0 ) {
+ if ((item=JabberListGetItemPtrFromIndex(proto, i)) != NULL) {
+ TLEN_FILE_TRANSFER *ft = item->ft;
+ JabberListRemoveByIndex(proto, i);
+ if (ft != NULL) {
+ if (ft->s) {
+ //ProtoBroadcastAck(iface.m_szModuleName, ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
+ JabberLog(proto, "Closing ft->s = %d", ft->s);
+ ft->state = FT_ERROR;
+ Netlib_CloseHandle(ft->s);
+ ft->s = NULL;
+ if (ft->hFileEvent != NULL) {
+ hEvent = ft->hFileEvent;
+ ft->hFileEvent = NULL;
+ SetEvent(hEvent);
+ }
+ } else {
+ JabberLog(proto, "freeing (V) ft struct");
+ TlenP2PFreeFileTransfer(ft);
+ }
+ }
+ }
+ }
+ if (proto->voiceDlgHWND !=NULL) {
+ EndDialog(proto->voiceDlgHWND, 0);
+ }
+ return 0;
+}
+
+INT_PTR TlenVoiceContactMenuHandleVoice(void *ptr, WPARAM wParam, LPARAM lParam)
+{
+ HANDLE hContact;
+ DBVARIANT dbv;
+ JABBER_LIST_ITEM *item;
+ TLEN_FILE_TRANSFER *ft;
+ TlenProtocol *proto =(TlenProtocol *)ptr;
+ if (!proto->isOnline) {
+ return 1;
+ }
+ if ((hContact=(HANDLE) wParam)!=NULL) {
+ if (!DBGetContactSetting(hContact, proto->iface.m_szModuleName, "jid", &dbv)) {
+ char serialId[32];
+ sprintf(serialId, "%d", JabberSerialNext(proto));
+ if ((item = JabberListAdd(proto, LIST_VOICE, serialId)) != NULL) {
+ ft = TlenFileCreateFT(proto, dbv.pszVal);
+ ft->iqId = mir_strdup(serialId);
+ item->ft = ft;
+// JabberSend(ft->proto, "<iq to='%s'><query xmlns='voip'><voip k='1' s='1' v='1' i='51245604'/></query></iq>", ft->jid);
+// Sleep(5000);
+ TlenVoiceStart(ft, 2);
+ JabberSend(ft->proto, "<v t='%s' e='1' i='%s' v='1'/>", ft->jid, serialId);
+ }
+ DBFreeVariant(&dbv);
+ }
+ }
+ return 0;
+}
+
+int TlenVoiceIsInUse(TlenProtocol *proto) {
+ if (JabberListFindNext(proto, LIST_VOICE, 0) >= 0 || proto->voiceDlgHWND!=NULL) {
+ JabberLog(proto, "voice in use ? %d", proto->voiceDlgHWND);
+ return 1;
+ }
+ return 0;
+}
+
+static HBITMAP TlenVoiceMakeBitmap(int w, int h, int bpp, void *ptr)
+{
+ BITMAPINFO bmih;
+ HBITMAP hbm;
+ HDC hdc;
+ bmih.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ bmih.bmiHeader.biWidth = w&0xFFFFFFFC;
+ bmih.bmiHeader.biHeight = h;//&0xFFFFFFFC;
+ bmih.bmiHeader.biPlanes = 1; // musi byc 1
+ bmih.bmiHeader.biBitCount = bpp;
+ bmih.bmiHeader.biCompression = BI_RGB;
+ bmih.bmiHeader.biSizeImage = 0;
+ bmih.bmiHeader.biXPelsPerMeter = 0;
+ bmih.bmiHeader.biYPelsPerMeter = 0;
+ bmih.bmiHeader.biClrUsed = 0;
+ bmih.bmiHeader.biClrImportant = 0;
+ hdc = CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
+ hbm = CreateDIBitmap(hdc, (PBITMAPINFOHEADER) &bmih, CBM_INIT, ptr, &bmih, DIB_RGB_COLORS);
+ ReleaseDC(NULL,hdc);
+ return hbm;
+}
+
+static void TlenVoiceInitVUMeters()
+{
+ int i, v, y, x, x0, col, col0;
+ unsigned char *pBits;
+ int ledWidth, ledHeight;
+ ledWidth = 9;
+ ledHeight = 6;
+ VU_METER_HEIGHT = ledHeight;
+ VU_METER_WIDTH = (VU_METER_LEVELS-1) * ledWidth;
+ VU_METER_WIDTH = (VU_METER_WIDTH + 3) & (~3);
+ pBits = (unsigned char *)mir_alloc(3*VU_METER_WIDTH*VU_METER_HEIGHT);
+ memset(pBits, 0x80, 3*VU_METER_WIDTH*VU_METER_HEIGHT);
+ for (i=0;i<VU_METER_LEVELS;i++) {
+ for (v=0;v<VU_METER_LEVELS-1;v++) {
+ if (v>=i) {
+ if (v < 10) col0 = 0x104010;
+ else if (v<13) col0 = 0x404010;
+ else col0 = 0x401010;
+ } else {
+ if (v < 10) col0 = 0x00f000;
+ else if (v<13) col0 = 0xf0f000;
+ else col0 = 0xf00000;
+ }
+ x0 = v * ledWidth;
+ for (y=1;y<VU_METER_HEIGHT-1;y++) {
+ col = col0;
+ for (x=1;x<ledWidth;x++) {
+ pBits[3*(x+x0+y*VU_METER_WIDTH)] = col &0xFF;
+ pBits[3*(x+x0+y*VU_METER_WIDTH)+1] = (col>>8) &0xFF;
+ pBits[3*(x+x0+y*VU_METER_WIDTH)+2] = (col>>16) &0xFF;
+ }
+ }
+ }
+ vuMeterBitmaps[i] = TlenVoiceMakeBitmap(VU_METER_WIDTH, VU_METER_HEIGHT, 24, pBits);
+ }
+ mir_free(pBits);
+}
+
+static INT_PTR CALLBACK TlenVoiceDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ HDC hDC, hMemDC;
+ int v;
+ static int counter;
+ TlenProtocol *proto = (TlenProtocol *)GetWindowLongPtr(hwndDlg, GWLP_USERDATA);
+ switch (msg) {
+ case WM_INITDIALOG:
+ proto = (TlenProtocol *)lParam;
+ SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR)proto);
+ proto->voiceDlgHWND = hwndDlg;
+ TranslateDialogDefault(hwndDlg);
+ SendDlgItemMessage(hwndDlg, IDC_VCQUALITY, CB_ADDSTRING, 0, (LPARAM) TranslateT("8000 Hz / 13.8 kbps"));
+ SendDlgItemMessage(hwndDlg, IDC_VCQUALITY, CB_ADDSTRING, 0, (LPARAM) TranslateT("11025 Hz / 19.1 kbps"));
+ SendDlgItemMessage(hwndDlg, IDC_VCQUALITY, CB_ADDSTRING, 0, (LPARAM) TranslateT("22050 Hz / 36.8 kbps"));
+ SendDlgItemMessage(hwndDlg, IDC_VCQUALITY, CB_ADDSTRING, 0, (LPARAM) TranslateT("44100 Hz / 72 kbps"));
+ SendDlgItemMessage(hwndDlg, IDC_VCQUALITY, CB_SETCURSEL, 1, 0);
+ SendDlgItemMessage(hwndDlg, IDC_MICROPHONE, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_SPEAKER, BUTTONSETASFLATBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_MICROPHONE, BUTTONSETASPUSHBTN, 0, 0);
+ SendDlgItemMessage(hwndDlg, IDC_SPEAKER, BUTTONSETASPUSHBTN, 0, 0);
+ {
+ HICON hIcon = GetIcolibIcon(IDI_MICROPHONE);
+ SendDlgItemMessage(hwndDlg, IDC_MICROPHONE, BM_SETIMAGE, IMAGE_ICON, (LPARAM) hIcon);
+ ReleaseIcolibIcon(hIcon);
+ hIcon = GetIcolibIcon(IDI_SPEAKER);
+ SendDlgItemMessage(hwndDlg, IDC_SPEAKER, BM_SETIMAGE, IMAGE_ICON, (LPARAM) hIcon);
+ ReleaseIcolibIcon(hIcon);
+ }
+ CheckDlgButton(hwndDlg, IDC_MICROPHONE, TRUE);
+ CheckDlgButton(hwndDlg, IDC_SPEAKER, TRUE);
+ TlenVoiceInitVUMeters();
+ SetDlgItemText(hwndDlg, IDC_STATUS, TranslateT("...???..."));
+ counter = 0;
+ SetTimer(hwndDlg, 1, 100, NULL);
+ return FALSE;
+ case WM_TIMER:
+ if (proto->recordingControl != NULL && !proto->recordingControl->bDisable) {
+ v = proto->recordingControl->vuMeter % VU_METER_LEVELS;
+ if (proto->recordingControl->vuMeter >0) {
+ proto->recordingControl->vuMeter--;
+ }
+ } else {
+ v = 0;
+ }
+ hDC = GetDC(GetDlgItem(hwndDlg, IDC_VUMETERIN));
+ if (NULL != (hMemDC = CreateCompatibleDC( hDC ))) {
+ SelectObject( hMemDC, vuMeterBitmaps[v]) ;
+ BitBlt( hDC, 0, 0, VU_METER_WIDTH, VU_METER_HEIGHT, hMemDC, 0, 0, SRCCOPY ) ;
+ DeleteDC(hMemDC);
+ }
+ ReleaseDC(GetDlgItem(hwndDlg, IDC_PLAN), hDC);
+ if (proto->playbackControl != NULL && !proto->playbackControl->bDisable) {
+ v = proto->playbackControl->vuMeter % VU_METER_LEVELS;
+ if (proto->playbackControl->vuMeter >0) {
+ proto->playbackControl->vuMeter--;
+ }
+ } else {
+ v = 0;
+ }
+ hDC = GetDC(GetDlgItem(hwndDlg, IDC_VUMETEROUT));
+ if (NULL != (hMemDC = CreateCompatibleDC( hDC ))) {
+ SelectObject( hMemDC, vuMeterBitmaps[v]) ;
+ BitBlt( hDC, 0, 0, VU_METER_WIDTH, VU_METER_HEIGHT, hMemDC, 0, 0, SRCCOPY ) ;
+ DeleteDC(hMemDC);
+ }
+ ReleaseDC(GetDlgItem(hwndDlg, IDC_PLAN), hDC);
+ counter ++;
+ if (counter %10 == 0) {
+ char str[50];
+ float fv;
+ if (proto->recordingControl != NULL) {
+ fv = (float)proto->recordingControl->bytesSum;
+ proto->recordingControl->bytesSum = 0;
+ } else {
+ fv = 0;
+ }
+ sprintf(str, "%.1f kB/s", fv / 1024);
+ SetDlgItemTextA(hwndDlg, IDC_BYTESOUT, str);
+ if (proto->playbackControl != NULL) {
+ fv = (float)proto->playbackControl->bytesSum;
+ proto->playbackControl->bytesSum = 0;
+ } else {
+ fv = 0;
+ }
+ sprintf(str, "%.1f kB/s", fv / 1024);
+ SetDlgItemTextA(hwndDlg, IDC_BYTESIN, str);
+ }
+ break;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDCANCEL:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ case IDC_VCQUALITY:
+ if (HIWORD(wParam)==CBN_SELCHANGE) {
+ if (proto->recordingControl!=NULL) {
+ int codec;
+ codec = SendDlgItemMessage(hwndDlg, IDC_VCQUALITY, CB_GETCURSEL, 0, 0) + 2;
+ if (codec!=proto->recordingControl->codec && codec>1 && codec<6) {
+ TLEN_FILE_TRANSFER *ft = proto->recordingControl->ft;
+ TlenVoiceFreeVc(proto->recordingControl);
+ proto->recordingControl = TlenVoiceCreateVC(ft->proto, codec);
+ proto->recordingControl->ft = ft;
+ TlenVoiceRecordingStart(proto->recordingControl);
+ }
+ }
+ }
+ case IDC_MICROPHONE:
+ if (proto->recordingControl!=NULL) {
+ proto->recordingControl->bDisable = !IsDlgButtonChecked(hwndDlg, IDC_MICROPHONE);
+ }
+ break;
+ case IDC_SPEAKER:
+ if (proto->playbackControl!=NULL) {
+ proto->playbackControl->bDisable = !IsDlgButtonChecked(hwndDlg, IDC_SPEAKER);
+ }
+ break;
+ }
+ break;
+ case WM_CLOSE:
+ EndDialog(hwndDlg, 0);
+ break;
+ case WM_DESTROY:
+ proto->voiceDlgHWND = NULL;
+ break;
+
+ }
+ return FALSE;
+}
+
+static void __cdecl TlenVoiceDlgThread(void *ptr)
+{
+
+ TLEN_FILE_TRANSFER *ft = (TLEN_FILE_TRANSFER *)ptr;
+ TlenProtocol * proto = ft->proto;
+ DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_VOICE), NULL, TlenVoiceDlgProc, (LPARAM) proto);
+ TlenVoiceCancelAll(proto);
+}
+
+int TlenVoiceStart(TLEN_FILE_TRANSFER *ft, int mode)
+{
+
+ JabberLog(ft->proto, "starting voice %d", mode);
+ if (mode==0) {
+ JabberForkThread((void (__cdecl *)(void*))TlenVoiceReceiveThread, 0, ft);
+ } else if (mode==1) {
+ JabberForkThread((void (__cdecl *)(void*))TlenVoiceSendingThread, 0, ft);
+ } else {
+ JabberForkThread((void (__cdecl *)(void*))TlenVoiceDlgThread, 0, ft);
+ }
+ return 0;
+}
+
+static char *getDisplayName(TlenProtocol *proto, const char *id)
+{
+ char jid[256];
+ HANDLE hContact;
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ _snprintf(jid, sizeof(jid), "%s@%s", id, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ if ((hContact=JabberHContactFromJID(proto, jid)) != NULL) {
+ return mir_strdup((char *) CallService(MS_CLIST_GETCONTACTDISPLAYNAME, (WPARAM) hContact, 0));
+ }
+ }
+ return mir_strdup(id);
+}
+
+typedef struct {
+ TlenProtocol *proto;
+ JABBER_LIST_ITEM *item;
+}ACCEPTDIALOGDATA;
+
+static INT_PTR CALLBACK TlenVoiceAcceptDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+ ACCEPTDIALOGDATA * data;
+ char *str;
+ switch (msg) {
+ case WM_INITDIALOG:
+ TranslateDialogDefault(hwndDlg);
+ data = (ACCEPTDIALOGDATA *) lParam;
+ str = getDisplayName(data->proto, data->item->nick);
+ SetDlgItemTextA(hwndDlg, IDC_FROM, str);
+ mir_free(str);
+ return FALSE;
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
+ case IDC_ACCEPT:
+ EndDialog(hwndDlg, 1);
+ return TRUE;
+ case IDCANCEL:
+ case IDCLOSE:
+ EndDialog(hwndDlg, 0);
+ return TRUE;
+ }
+ break;
+ case WM_CLOSE:
+ EndDialog(hwndDlg, 0);
+ break;
+ }
+ return FALSE;
+}
+
+static void __cdecl TlenVoiceAcceptDlgThread(void *ptr)
+{
+
+ ACCEPTDIALOGDATA *data = (ACCEPTDIALOGDATA *)ptr;
+ int result = DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_ACCEPT_VOICE), NULL, TlenVoiceAcceptDlgProc, (LPARAM) data);
+ if (result && data->proto->isOnline) {
+ data->item->ft = TlenFileCreateFT(data->proto, data->item->nick);
+ data->item->ft->iqId = mir_strdup(data->item->jid);
+ TlenVoiceStart(data->item->ft, 2);
+ JabberSend(data->proto, "<v t='%s' i='%s' e='5' v='1'/>", data->item->nick, data->item->jid);
+ } else {
+ if (data->proto->isOnline) {
+ JabberSend(data->proto, "<v t='%s' i='%s' e='4' />", data->item->nick, data->item->jid);
+ }
+ JabberListRemove(data->proto, LIST_VOICE, data->item->jid);
+ }
+ mir_free(data);
+}
+
+int TlenVoiceAccept(TlenProtocol *proto, const char *id, const char *from)
+{
+ JABBER_LIST_ITEM * item;
+ if (!TlenVoiceIsInUse(proto)) {
+ if ((item = JabberListAdd(proto, LIST_VOICE, id)) != NULL) {
+ int ask, ignore, voiceChatPolicy;
+ ask = TRUE;
+ ignore = FALSE;
+ voiceChatPolicy = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "VoiceChatPolicy", 0);
+ if (voiceChatPolicy == TLEN_MUC_ASK) {
+ ignore = FALSE;
+ ask = TRUE;
+ } else if (voiceChatPolicy == TLEN_MUC_IGNORE_ALL) {
+ ignore = TRUE;
+ } else if (voiceChatPolicy == TLEN_MUC_IGNORE_NIR) {
+ char jid[256];
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ _snprintf(jid, sizeof(jid), "%s@%s", from, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ } else {
+ strcpy(jid, from);
+ }
+ ignore = !IsAuthorized(proto, jid);
+ ask = TRUE;
+ } else if (voiceChatPolicy == TLEN_MUC_ACCEPT_IR) {
+ char jid[256];
+ JABBER_LIST_ITEM *item;
+ DBVARIANT dbv;
+ if (!DBGetContactSetting(NULL, proto->iface.m_szModuleName, "LoginServer", &dbv)) {
+ _snprintf(jid, sizeof(jid), "%s@%s", from, dbv.pszVal);
+ DBFreeVariant(&dbv);
+ } else {
+ strcpy(jid, from);
+ }
+ ask = !IsAuthorized(proto, jid);
+ ignore = FALSE;
+ } else if (voiceChatPolicy == TLEN_MUC_ACCEPT_ALL) {
+ ask = FALSE;
+ ignore = FALSE;
+ }
+ if (ignore) {
+ if (proto->isOnline) {
+ JabberSend(proto, "<v t='%s' i='%s' e='4' />", from, id);
+ }
+ JabberListRemove(proto, LIST_VOICE, id);
+ } else {
+ item->nick = mir_strdup(from);
+ if (ask) {
+ ACCEPTDIALOGDATA *data = (ACCEPTDIALOGDATA *)mir_alloc(sizeof(ACCEPTDIALOGDATA));
+ data->proto = proto;
+ data->item = item;
+ JabberForkThread((void (__cdecl *)(void*))TlenVoiceAcceptDlgThread, 0, data);
+ } else if (proto->isOnline) {
+ item->ft = TlenFileCreateFT(proto, from);
+ item->ft->iqId = mir_strdup(id);
+ TlenVoiceStart(item->ft, 2);
+ JabberSend(proto, "<v t='%s' i='%s' e='5' v='1'/>", item->nick, item->jid);
+ }
+ }
+ return 1;
+ }
+ }
+ return 0;
+}
+
+int TlenVoiceBuildInDeviceList(TlenProtocol *proto, HWND hWnd)
+{ int i, j, iNumDevs;
+ WAVEINCAPS wic;
+ iNumDevs = waveInGetNumDevs();
+ SendMessage(hWnd, CB_ADDSTRING, 0, (LPARAM)TranslateT("Default"));
+ for (i = j = 0; i < iNumDevs; i++) {
+ if (!waveInGetDevCaps(i, &wic, sizeof(WAVEINCAPS))) {
+ if (wic.dwFormats != 0) {
+ SendMessage(hWnd, CB_ADDSTRING, 0, (LPARAM)wic.szPname);
+ j++;
+ }
+ }
+ }
+ i = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "VoiceDeviceIn", 0);
+ if (i>j) i = 0;
+ SendMessage(hWnd, CB_SETCURSEL, i, 0);
+ return 0;
+}
+
+int TlenVoiceBuildOutDeviceList(TlenProtocol *proto, HWND hWnd)
+{ int i, j, iNumDevs;
+ WAVEOUTCAPS woc;
+ iNumDevs = waveInGetNumDevs();
+ SendMessage(hWnd, CB_ADDSTRING, 0, (LPARAM)TranslateT("Default"));
+ for (i = j = 0; i < iNumDevs; i++) {
+ if (!waveOutGetDevCaps(i, &woc, sizeof(WAVEOUTCAPS))) {
+ if (woc.dwFormats != 0) {
+ SendMessage(hWnd, CB_ADDSTRING, 0, (LPARAM)woc.szPname);
+ j++;
+ }
+ }
+ }
+ i = DBGetContactSettingWord(NULL, proto->iface.m_szModuleName, "VoiceDeviceOut", 0);
+ if (i>j) i = 0;
+ SendMessage(hWnd, CB_SETCURSEL, i, 0);
+ return 0;
+}
diff --git a/protocols/Tlen/tlen_voice.h b/protocols/Tlen/tlen_voice.h
new file mode 100644
index 0000000000..cd38a23c1c
--- /dev/null
+++ b/protocols/Tlen/tlen_voice.h
@@ -0,0 +1,68 @@
+/*
+
+Tlen Protocol Plugin for Miranda IM
+Copyright (C) 2004-2007 Piotr Piastucki
+
+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.
+
+You should have received a copy of the GNU General Public License
+along with this program; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+
+*/
+
+#ifndef _TLEN_VOICE_H_
+#define _TLEN_VOICE_H_
+
+#include <windows.h>
+#include <mmsystem.h>
+
+#include "jabber.h"
+#include "codec/gsm.h"
+
+typedef struct TLEN_VOICE_CONTROL_STRUCT {
+ int waveMode;
+ int codec;
+ int bDisable;
+
+ short *recordingData;
+ short *waveData;
+ WAVEHDR *waveHeaders;
+ int waveFrameSize;
+ int waveHeadersPos;
+ int waveHeadersNum;
+
+// HANDLE hEvent;
+ HANDLE hThread;
+ DWORD threadID;
+ HWAVEOUT hWaveOut;
+ HWAVEIN hWaveIn;
+ int isRunning;
+ int stopThread;
+ gsm_state *gsmstate;
+ TLEN_FILE_TRANSFER *ft;
+ int vuMeter;
+ int bytesSum;
+ TlenProtocol *proto;
+} TLEN_VOICE_CONTROL;
+
+
+extern void __cdecl TlenVoiceSendingThread(TLEN_FILE_TRANSFER *ft);
+extern void __cdecl TlenVoiceReceiveThread(TLEN_FILE_TRANSFER *ft);
+extern int TlenVoiceIsInUse(TlenProtocol *proto);
+extern INT_PTR TlenVoiceContactMenuHandleVoice(void *ptr, WPARAM wParam, LPARAM lParam);
+extern int TlenVoiceCancelAll(TlenProtocol *proto);
+extern int TlenVoiceStart(TLEN_FILE_TRANSFER *ft, int mode) ;
+extern int TlenVoiceAccept(TlenProtocol *proto, const char *id, const char *from);
+extern int TlenVoiceBuildInDeviceList(TlenProtocol *proto, HWND hWnd);
+extern int TlenVoiceBuildOutDeviceList(TlenProtocol *proto, HWND hWnd);
+#endif
+