From 075bdcd93cf7882bad4cb027adf159f93674d6e5 Mon Sep 17 00:00:00 2001 From: Szymon Tomasz Stefanek Date: Mon, 27 Dec 2010 05:02:48 +0000 Subject: More renaming and cleanup git-svn-id: https://svn.kvirc.de/svn/trunk/kvirc@5237 17fca916-40b9-46aa-a4ea-0a15b648b75c --- src/kvilib/core/KviCString.h | 2 +- src/kvilib/core/kvi_hstrEqualCIN.cpp | 2 +- src/kvilib/core/kvi_hstrEqualCIN.h | 2 +- src/kvilib/irc/KviIrcServerDataBase.h | 4 +- src/kvilib/system/KviThread.h | 6 +- src/kvirc/CMakeLists.txt | 598 +-- src/kvirc/kernel/KviAction.cpp | 503 +++ src/kvirc/kernel/KviAction.h | 375 ++ src/kvirc/kernel/KviActionManager.cpp | 318 ++ src/kvirc/kernel/KviActionManager.h | 118 + src/kvirc/kernel/KviApplication.cpp | 1999 ++++++++++ src/kvirc/kernel/KviApplication.h | 383 ++ src/kvirc/kernel/KviApplication_filesystem.cpp | 603 +++ src/kvirc/kernel/KviApplication_setup.cpp | 856 +++++ src/kvirc/kernel/KviAsynchronousConnectionData.cpp | 41 + src/kvirc/kernel/KviAsynchronousConnectionData.h | 56 + src/kvirc/kernel/KviCoreActions.cpp | 1179 ++++++ src/kvirc/kernel/KviCoreActions.h | 188 + src/kvirc/kernel/KviCustomToolBarDescriptor.cpp | 220 ++ src/kvirc/kernel/KviCustomToolBarDescriptor.h | 78 + src/kvirc/kernel/KviCustomToolBarManager.cpp | 212 ++ src/kvirc/kernel/KviCustomToolBarManager.h | 68 + src/kvirc/kernel/KviDefaultScript.cpp | 489 +++ src/kvirc/kernel/KviDefaultScript.h | 239 ++ src/kvirc/kernel/KviFileTransfer.cpp | 202 + src/kvirc/kernel/KviFileTransfer.h | 114 + src/kvirc/kernel/KviHtmlGenerator.cpp | 304 ++ src/kvirc/kernel/KviHtmlGenerator.h | 49 + src/kvirc/kernel/KviIconManager.cpp | 956 +++++ src/kvirc/kernel/KviIconManager.h | 528 +++ src/kvirc/kernel/KviInternalCommand.cpp | 83 + src/kvirc/kernel/KviInternalCommand.h | 74 + src/kvirc/kernel/KviIpcSentinel.cpp | 284 ++ src/kvirc/kernel/KviIpcSentinel.h | 68 + src/kvirc/kernel/KviIrcConnection.cpp | 1745 +++++++++ src/kvirc/kernel/KviIrcConnection.h | 947 +++++ .../kernel/KviIrcConnectionAntiCtcpFloodData.cpp | 38 + .../kernel/KviIrcConnectionAntiCtcpFloodData.h | 48 + src/kvirc/kernel/KviIrcConnectionAsyncData.h | 82 + .../kernel/KviIrcConnectionAsyncWhoisData.cpp | 42 + src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.h | 68 + .../KviIrcConnectionNetsplitDetectorData.cpp | 37 + .../kernel/KviIrcConnectionNetsplitDetectorData.h | 46 + src/kvirc/kernel/KviIrcConnectionRequestQueue.cpp | 175 + src/kvirc/kernel/KviIrcConnectionRequestQueue.h | 115 + src/kvirc/kernel/KviIrcConnectionServerInfo.cpp | 488 +++ src/kvirc/kernel/KviIrcConnectionServerInfo.h | 241 ++ src/kvirc/kernel/KviIrcConnectionStateData.cpp | 91 + src/kvirc/kernel/KviIrcConnectionStateData.h | 109 + src/kvirc/kernel/KviIrcConnectionStatistics.cpp | 38 + src/kvirc/kernel/KviIrcConnectionStatistics.h | 50 + src/kvirc/kernel/KviIrcConnectionTarget.cpp | 72 + src/kvirc/kernel/KviIrcConnectionTarget.h | 100 + .../kernel/KviIrcConnectionTargetResolver.cpp | 583 +++ src/kvirc/kernel/KviIrcConnectionTargetResolver.h | 89 + src/kvirc/kernel/KviIrcConnectionUserInfo.cpp | 65 + src/kvirc/kernel/KviIrcConnectionUserInfo.h | 91 + src/kvirc/kernel/KviIrcContext.cpp | 926 +++++ src/kvirc/kernel/KviIrcContext.h | 189 + src/kvirc/kernel/KviIrcDataStreamMonitor.cpp | 41 + src/kvirc/kernel/KviIrcDataStreamMonitor.h | 49 + src/kvirc/kernel/KviIrcLink.cpp | 424 +++ src/kvirc/kernel/KviIrcLink.h | 222 ++ src/kvirc/kernel/KviIrcSocket.cpp | 2014 ++++++++++ src/kvirc/kernel/KviIrcSocket.h | 520 +++ src/kvirc/kernel/KviIrcUrl.cpp | 365 ++ src/kvirc/kernel/KviIrcUrl.h | 79 + src/kvirc/kernel/KviLagMeter.cpp | 266 ++ src/kvirc/kernel/KviLagMeter.h | 75 + src/kvirc/kernel/KviMain.cpp | 462 +++ src/kvirc/kernel/KviNotifyList.cpp | 1294 +++++++ src/kvirc/kernel/KviNotifyList.h | 160 + src/kvirc/kernel/KviOptions.cpp | 1445 ++++++++ src/kvirc/kernel/KviOptions.h | 772 ++++ src/kvirc/kernel/KviSSLMaster.cpp | 315 ++ src/kvirc/kernel/KviSSLMaster.h | 53 + src/kvirc/kernel/KviTextIconManager.cpp | 309 ++ src/kvirc/kernel/KviTextIconManager.h | 244 ++ src/kvirc/kernel/KviTheme.cpp | 295 ++ src/kvirc/kernel/KviTheme.h | 170 + src/kvirc/kernel/KviUserAction.cpp | 43 + src/kvirc/kernel/KviUserAction.h | 98 + src/kvirc/kernel/KviUserInput.cpp | 156 + src/kvirc/kernel/KviUserInput.h | 82 + src/kvirc/kernel/kvi_action.cpp | 503 --- src/kvirc/kernel/kvi_action.h | 375 -- src/kvirc/kernel/kvi_actionmanager.cpp | 318 -- src/kvirc/kernel/kvi_actionmanager.h | 118 - src/kvirc/kernel/kvi_app.cpp | 1999 ---------- src/kvirc/kernel/kvi_app.h | 383 -- src/kvirc/kernel/kvi_app_fs.cpp | 603 --- src/kvirc/kernel/kvi_app_setup.cpp | 856 ----- .../kernel/kvi_asynchronousconnectiondata.cpp | 41 - src/kvirc/kernel/kvi_asynchronousconnectiondata.h | 56 - src/kvirc/kernel/kvi_coreactions.cpp | 1179 ------ src/kvirc/kernel/kvi_coreactions.h | 188 - src/kvirc/kernel/kvi_customtoolbardescriptor.cpp | 220 -- src/kvirc/kernel/kvi_customtoolbardescriptor.h | 78 - src/kvirc/kernel/kvi_customtoolbarmanager.cpp | 212 -- src/kvirc/kernel/kvi_customtoolbarmanager.h | 68 - src/kvirc/kernel/kvi_defaultscript.cpp | 489 --- src/kvirc/kernel/kvi_defaultscript.h | 239 -- src/kvirc/kernel/kvi_filetransfer.cpp | 202 - src/kvirc/kernel/kvi_filetransfer.h | 114 - src/kvirc/kernel/kvi_htmlgenerator.cpp | 304 -- src/kvirc/kernel/kvi_htmlgenerator.h | 49 - src/kvirc/kernel/kvi_iconmanager.cpp | 956 ----- src/kvirc/kernel/kvi_iconmanager.h | 528 --- src/kvirc/kernel/kvi_internalcmd.cpp | 83 - src/kvirc/kernel/kvi_internalcmd.h | 74 - src/kvirc/kernel/kvi_ipc.cpp | 284 -- src/kvirc/kernel/kvi_ipc.h | 68 - src/kvirc/kernel/kvi_ircconnection.cpp | 1745 --------- src/kvirc/kernel/kvi_ircconnection.h | 947 ----- .../kernel/kvi_ircconnectionantictcpflooddata.cpp | 38 - .../kernel/kvi_ircconnectionantictcpflooddata.h | 48 - .../kernel/kvi_ircconnectionasynctemplatedata.h | 82 - .../kernel/kvi_ircconnectionasyncwhoisdata.cpp | 42 - src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.h | 68 - .../kvi_ircconnectionnetsplitdetectordata.cpp | 37 - .../kernel/kvi_ircconnectionnetsplitdetectordata.h | 46 - src/kvirc/kernel/kvi_ircconnectionrequestqueue.cpp | 175 - src/kvirc/kernel/kvi_ircconnectionrequestqueue.h | 115 - src/kvirc/kernel/kvi_ircconnectionserverinfo.cpp | 488 --- src/kvirc/kernel/kvi_ircconnectionserverinfo.h | 241 -- src/kvirc/kernel/kvi_ircconnectionstatedata.cpp | 91 - src/kvirc/kernel/kvi_ircconnectionstatedata.h | 109 - src/kvirc/kernel/kvi_ircconnectionstatistics.cpp | 38 - src/kvirc/kernel/kvi_ircconnectionstatistics.h | 50 - src/kvirc/kernel/kvi_ircconnectiontarget.cpp | 72 - src/kvirc/kernel/kvi_ircconnectiontarget.h | 100 - .../kernel/kvi_ircconnectiontargetresolver.cpp | 583 --- src/kvirc/kernel/kvi_ircconnectiontargetresolver.h | 89 - src/kvirc/kernel/kvi_ircconnectionuserinfo.cpp | 65 - src/kvirc/kernel/kvi_ircconnectionuserinfo.h | 91 - src/kvirc/kernel/kvi_irccontext.cpp | 926 ----- src/kvirc/kernel/kvi_irccontext.h | 189 - src/kvirc/kernel/kvi_ircdatastreammonitor.cpp | 41 - src/kvirc/kernel/kvi_ircdatastreammonitor.h | 49 - src/kvirc/kernel/kvi_irclink.cpp | 424 --- src/kvirc/kernel/kvi_irclink.h | 222 -- src/kvirc/kernel/kvi_ircsocket.cpp | 2014 ---------- src/kvirc/kernel/kvi_ircsocket.h | 520 --- src/kvirc/kernel/kvi_ircurl.cpp | 365 -- src/kvirc/kernel/kvi_ircurl.h | 79 - src/kvirc/kernel/kvi_lagmeter.cpp | 266 -- src/kvirc/kernel/kvi_lagmeter.h | 75 - src/kvirc/kernel/kvi_main.cpp | 462 --- src/kvirc/kernel/kvi_notifylist.cpp | 1294 ------- src/kvirc/kernel/kvi_notifylist.h | 160 - src/kvirc/kernel/kvi_options.cpp | 1445 -------- src/kvirc/kernel/kvi_options.h | 772 ---- src/kvirc/kernel/kvi_out.h | 2 +- src/kvirc/kernel/kvi_sslmaster.cpp | 315 -- src/kvirc/kernel/kvi_sslmaster.h | 53 - src/kvirc/kernel/kvi_texticonmanager.cpp | 309 -- src/kvirc/kernel/kvi_texticonmanager.h | 244 -- src/kvirc/kernel/kvi_theme.cpp | 295 -- src/kvirc/kernel/kvi_theme.h | 170 - src/kvirc/kernel/kvi_useraction.cpp | 43 - src/kvirc/kernel/kvi_useraction.h | 98 - src/kvirc/kernel/kvi_userinput.cpp | 156 - src/kvirc/kernel/kvi_userinput.h | 82 - src/kvirc/kvs/KviKvs.cpp | 141 + src/kvirc/kvs/KviKvs.h | 59 + src/kvirc/kvs/KviKvsAction.cpp | 50 + src/kvirc/kvs/KviKvsAction.h | 82 + src/kvirc/kvs/KviKvsAliasManager.cpp | 156 + src/kvirc/kvs/KviKvsAliasManager.h | 67 + src/kvirc/kvs/KviKvsArray.cpp | 249 ++ src/kvirc/kvs/KviKvsArray.h | 163 + src/kvirc/kvs/KviKvsArrayCast.cpp | 44 + src/kvirc/kvs/KviKvsArrayCast.h | 50 + src/kvirc/kvs/KviKvsAsyncDnsOperation.cpp | 122 + src/kvirc/kvs/KviKvsAsyncDnsOperation.h | 53 + src/kvirc/kvs/KviKvsAsyncOperation.cpp | 66 + src/kvirc/kvs/KviKvsAsyncOperation.h | 60 + src/kvirc/kvs/KviKvsCallbackObject.cpp | 108 + src/kvirc/kvs/KviKvsCallbackObject.h | 84 + src/kvirc/kvs/KviKvsCoreCallbackCommands.cpp | 1205 ++++++ src/kvirc/kvs/KviKvsCoreCallbackCommands.h | 74 + src/kvirc/kvs/KviKvsCoreFunctions.cpp | 167 + src/kvirc/kvs/KviKvsCoreFunctions.h | 156 + src/kvirc/kvs/KviKvsCoreFunctions_af.cpp | 1528 ++++++++ src/kvirc/kvs/KviKvsCoreFunctions_gl.cpp | 1050 ++++++ src/kvirc/kvs/KviKvsCoreFunctions_mr.cpp | 752 ++++ src/kvirc/kvs/KviKvsCoreFunctions_sz.cpp | 1136 ++++++ src/kvirc/kvs/KviKvsCoreSimpleCommands.cpp | 246 ++ src/kvirc/kvs/KviKvsCoreSimpleCommands.h | 140 + src/kvirc/kvs/KviKvsCoreSimpleCommands_af.cpp | 1565 ++++++++ src/kvirc/kvs/KviKvsCoreSimpleCommands_gl.cpp | 694 ++++ src/kvirc/kvs/KviKvsCoreSimpleCommands_mr.cpp | 1306 +++++++ src/kvirc/kvs/KviKvsCoreSimpleCommands_sz.cpp | 1129 ++++++ src/kvirc/kvs/KviKvsDnsManager.cpp | 179 + src/kvirc/kvs/KviKvsDnsManager.h | 87 + src/kvirc/kvs/KviKvsEvent.cpp | 78 + src/kvirc/kvs/KviKvsEvent.h | 54 + src/kvirc/kvs/KviKvsEventHandler.cpp | 76 + src/kvirc/kvs/KviKvsEventHandler.h | 106 + src/kvirc/kvs/KviKvsEventManager.cpp | 673 ++++ src/kvirc/kvs/KviKvsEventManager.h | 123 + src/kvirc/kvs/KviKvsEventTable.cpp | 3804 +++++++++++++++++++ src/kvirc/kvs/KviKvsEventTable.h | 371 ++ src/kvirc/kvs/KviKvsEventTriggers.h | 289 ++ src/kvirc/kvs/KviKvsHash.cpp | 99 + src/kvirc/kvs/KviKvsHash.h | 137 + src/kvirc/kvs/KviKvsKernel.cpp | 223 ++ src/kvirc/kvs/KviKvsKernel.h | 158 + src/kvirc/kvs/KviKvsModuleInterface.cpp | 196 + src/kvirc/kvs/KviKvsModuleInterface.h | 230 ++ src/kvirc/kvs/KviKvsObject.cpp | 1814 +++++++++ src/kvirc/kvs/KviKvsObject.h | 199 + src/kvirc/kvs/KviKvsObjectClass.cpp | 235 ++ src/kvirc/kvs/KviKvsObjectClass.h | 112 + src/kvirc/kvs/KviKvsObjectController.cpp | 258 ++ src/kvirc/kvs/KviKvsObjectController.h | 70 + src/kvirc/kvs/KviKvsObjectFunctionCall.cpp | 26 + src/kvirc/kvs/KviKvsObjectFunctionCall.h | 49 + src/kvirc/kvs/KviKvsObjectFunctionHandler.cpp | 59 + src/kvirc/kvs/KviKvsObjectFunctionHandler.h | 62 + src/kvirc/kvs/KviKvsObjectFunctionHandlerImpl.cpp | 147 + src/kvirc/kvs/KviKvsObjectFunctionHandlerImpl.h | 119 + src/kvirc/kvs/KviKvsParameterProcessor.cpp | 366 ++ src/kvirc/kvs/KviKvsParameterProcessor.h | 245 ++ src/kvirc/kvs/KviKvsParser.cpp | 3909 ++++++++++++++++++++ src/kvirc/kvs/KviKvsParser.h | 303 ++ src/kvirc/kvs/KviKvsParserMacros.h | 47 + src/kvirc/kvs/KviKvsParser_command.cpp | 348 ++ src/kvirc/kvs/KviKvsParser_comment.cpp | 90 + src/kvirc/kvs/KviKvsParser_dollar.cpp | 321 ++ src/kvirc/kvs/KviKvsParser_expression.cpp | 629 ++++ src/kvirc/kvs/KviKvsParser_lside.cpp | 958 +++++ src/kvirc/kvs/KviKvsParser_specialCommands.cpp | 2045 ++++++++++ src/kvirc/kvs/KviKvsPopupManager.cpp | 123 + src/kvirc/kvs/KviKvsPopupManager.h | 61 + src/kvirc/kvs/KviKvsPopupMenu.cpp | 1229 ++++++ src/kvirc/kvs/KviKvsPopupMenu.h | 293 ++ src/kvirc/kvs/KviKvsProcessManager.cpp | 379 ++ src/kvirc/kvs/KviKvsProcessManager.h | 106 + src/kvirc/kvs/KviKvsRWEvaluationResult.cpp | 70 + src/kvirc/kvs/KviKvsRWEvaluationResult.h | 70 + src/kvirc/kvs/KviKvsReport.cpp | 244 ++ src/kvirc/kvs/KviKvsReport.h | 75 + src/kvirc/kvs/KviKvsRunTimeCall.cpp | 48 + src/kvirc/kvs/KviKvsRunTimeCall.h | 82 + src/kvirc/kvs/KviKvsRunTimeContext.cpp | 204 + src/kvirc/kvs/KviKvsRunTimeContext.h | 265 ++ src/kvirc/kvs/KviKvsScript.cpp | 352 ++ src/kvirc/kvs/KviKvsScript.h | 324 ++ src/kvirc/kvs/KviKvsScriptAddonManager.cpp | 412 +++ src/kvirc/kvs/KviKvsScriptAddonManager.h | 137 + src/kvirc/kvs/KviKvsSwitchList.cpp | 74 + src/kvirc/kvs/KviKvsSwitchList.h | 87 + src/kvirc/kvs/KviKvsTimerManager.cpp | 249 ++ src/kvirc/kvs/KviKvsTimerManager.h | 124 + src/kvirc/kvs/KviKvsTreeNode.h | 378 ++ src/kvirc/kvs/KviKvsTreeNodeAliasFunctionCall.cpp | 76 + src/kvirc/kvs/KviKvsTreeNodeAliasFunctionCall.h | 84 + src/kvirc/kvs/KviKvsTreeNodeAliasSimpleCommand.cpp | 122 + src/kvirc/kvs/KviKvsTreeNodeAliasSimpleCommand.h | 83 + src/kvirc/kvs/KviKvsTreeNodeArrayCount.cpp | 82 + src/kvirc/kvs/KviKvsTreeNodeArrayCount.h | 93 + src/kvirc/kvs/KviKvsTreeNodeArrayElement.cpp | 152 + src/kvirc/kvs/KviKvsTreeNodeArrayElement.h | 120 + src/kvirc/kvs/KviKvsTreeNodeArrayOrHashElement.cpp | 43 + src/kvirc/kvs/KviKvsTreeNodeArrayOrHashElement.h | 42 + .../kvs/KviKvsTreeNodeArrayReferenceAssert.cpp | 99 + src/kvirc/kvs/KviKvsTreeNodeArrayReferenceAssert.h | 118 + src/kvirc/kvs/KviKvsTreeNodeBase.cpp | 32 + src/kvirc/kvs/KviKvsTreeNodeBase.h | 102 + .../kvs/KviKvsTreeNodeBaseObjectFunctionCall.cpp | 60 + .../kvs/KviKvsTreeNodeBaseObjectFunctionCall.h | 50 + src/kvirc/kvs/KviKvsTreeNodeCallbackCommand.cpp | 61 + src/kvirc/kvs/KviKvsTreeNodeCallbackCommand.h | 48 + src/kvirc/kvs/KviKvsTreeNodeCommand.cpp | 65 + src/kvirc/kvs/KviKvsTreeNodeCommand.h | 54 + src/kvirc/kvs/KviKvsTreeNodeCommandEvaluation.cpp | 48 + src/kvirc/kvs/KviKvsTreeNodeCommandEvaluation.h | 46 + .../kvs/KviKvsTreeNodeCommandWithParameters.cpp | 58 + .../kvs/KviKvsTreeNodeCommandWithParameters.h | 49 + src/kvirc/kvs/KviKvsTreeNodeCompositeData.cpp | 82 + src/kvirc/kvs/KviKvsTreeNodeCompositeData.h | 46 + src/kvirc/kvs/KviKvsTreeNodeConstantData.cpp | 78 + src/kvirc/kvs/KviKvsTreeNodeConstantData.h | 50 + .../kvs/KviKvsTreeNodeCoreCallbackCommand.cpp | 70 + src/kvirc/kvs/KviKvsTreeNodeCoreCallbackCommand.h | 51 + src/kvirc/kvs/KviKvsTreeNodeCoreFunctionCall.cpp | 60 + src/kvirc/kvs/KviKvsTreeNodeCoreFunctionCall.h | 48 + src/kvirc/kvs/KviKvsTreeNodeCoreSimpleCommand.cpp | 68 + src/kvirc/kvs/KviKvsTreeNodeCoreSimpleCommand.h | 49 + src/kvirc/kvs/KviKvsTreeNodeData.cpp | 104 + src/kvirc/kvs/KviKvsTreeNodeData.h | 62 + src/kvirc/kvs/KviKvsTreeNodeDataList.cpp | 108 + src/kvirc/kvs/KviKvsTreeNodeDataList.h | 55 + src/kvirc/kvs/KviKvsTreeNodeExpression.cpp | 728 ++++ src/kvirc/kvs/KviKvsTreeNodeExpression.h | 238 ++ src/kvirc/kvs/KviKvsTreeNodeExpressionReturn.cpp | 58 + src/kvirc/kvs/KviKvsTreeNodeExpressionReturn.h | 45 + .../kvs/KviKvsTreeNodeExtendedScopeVariable.cpp | 77 + .../kvs/KviKvsTreeNodeExtendedScopeVariable.h | 45 + src/kvirc/kvs/KviKvsTreeNodeFunctionCall.cpp | 59 + src/kvirc/kvs/KviKvsTreeNodeFunctionCall.h | 47 + src/kvirc/kvs/KviKvsTreeNodeGlobalVariable.cpp | 61 + src/kvirc/kvs/KviKvsTreeNodeGlobalVariable.h | 45 + src/kvirc/kvs/KviKvsTreeNodeHashCount.cpp | 79 + src/kvirc/kvs/KviKvsTreeNodeHashCount.h | 47 + src/kvirc/kvs/KviKvsTreeNodeHashElement.cpp | 148 + src/kvirc/kvs/KviKvsTreeNodeHashElement.h | 52 + .../kvs/KviKvsTreeNodeHashReferenceAssert.cpp | 95 + src/kvirc/kvs/KviKvsTreeNodeHashReferenceAssert.h | 53 + src/kvirc/kvs/KviKvsTreeNodeIndirectData.cpp | 42 + src/kvirc/kvs/KviKvsTreeNodeIndirectData.h | 42 + src/kvirc/kvs/KviKvsTreeNodeInstruction.cpp | 36 + src/kvirc/kvs/KviKvsTreeNodeInstruction.h | 85 + src/kvirc/kvs/KviKvsTreeNodeInstructionBlock.cpp | 85 + src/kvirc/kvs/KviKvsTreeNodeInstructionBlock.h | 55 + src/kvirc/kvs/KviKvsTreeNodeLocalVariable.cpp | 70 + src/kvirc/kvs/KviKvsTreeNodeLocalVariable.h | 45 + .../kvs/KviKvsTreeNodeModuleCallbackCommand.cpp | 94 + .../kvs/KviKvsTreeNodeModuleCallbackCommand.h | 50 + src/kvirc/kvs/KviKvsTreeNodeModuleFunctionCall.cpp | 87 + src/kvirc/kvs/KviKvsTreeNodeModuleFunctionCall.h | 48 + .../kvs/KviKvsTreeNodeModuleSimpleCommand.cpp | 94 + src/kvirc/kvs/KviKvsTreeNodeModuleSimpleCommand.h | 48 + .../KviKvsTreeNodeMultipleParameterIdentifier.cpp | 87 + .../KviKvsTreeNodeMultipleParameterIdentifier.h | 49 + src/kvirc/kvs/KviKvsTreeNodeObjectField.cpp | 67 + src/kvirc/kvs/KviKvsTreeNodeObjectField.h | 47 + src/kvirc/kvs/KviKvsTreeNodeObjectFunctionCall.cpp | 54 + src/kvirc/kvs/KviKvsTreeNodeObjectFunctionCall.h | 45 + src/kvirc/kvs/KviKvsTreeNodeOperation.cpp | 1275 +++++++ src/kvirc/kvs/KviKvsTreeNodeOperation.h | 296 ++ src/kvirc/kvs/KviKvsTreeNodeParameterReturn.cpp | 76 + src/kvirc/kvs/KviKvsTreeNodeParameterReturn.h | 45 + src/kvirc/kvs/KviKvsTreeNodeRebindingSwitch.cpp | 93 + src/kvirc/kvs/KviKvsTreeNodeRebindingSwitch.h | 49 + src/kvirc/kvs/KviKvsTreeNodeScopeOperator.cpp | 144 + src/kvirc/kvs/KviKvsTreeNodeScopeOperator.h | 58 + src/kvirc/kvs/KviKvsTreeNodeSimpleCommand.cpp | 50 + src/kvirc/kvs/KviKvsTreeNodeSimpleCommand.h | 43 + .../KviKvsTreeNodeSingleParameterIdentifier.cpp | 63 + .../kvs/KviKvsTreeNodeSingleParameterIdentifier.h | 50 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommand.cpp | 49 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommand.h | 41 + .../kvs/KviKvsTreeNodeSpecialCommandBreak.cpp | 52 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandBreak.h | 45 + .../kvs/KviKvsTreeNodeSpecialCommandClass.cpp | 164 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandClass.h | 71 + .../kvs/KviKvsTreeNodeSpecialCommandContinue.cpp | 52 + .../kvs/KviKvsTreeNodeSpecialCommandContinue.h | 45 + .../kvs/KviKvsTreeNodeSpecialCommandDefpopup.cpp | 347 ++ .../kvs/KviKvsTreeNodeSpecialCommandDefpopup.h | 193 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandDo.cpp | 86 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandDo.h | 51 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandFor.cpp | 137 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandFor.h | 53 + .../kvs/KviKvsTreeNodeSpecialCommandForeach.cpp | 235 ++ .../kvs/KviKvsTreeNodeSpecialCommandForeach.h | 53 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandIf.cpp | 76 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandIf.h | 50 + .../kvs/KviKvsTreeNodeSpecialCommandSwitch.cpp | 357 ++ src/kvirc/kvs/KviKvsTreeNodeSpecialCommandSwitch.h | 117 + .../kvs/KviKvsTreeNodeSpecialCommandUnset.cpp | 71 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandUnset.h | 47 + .../kvs/KviKvsTreeNodeSpecialCommandWhile.cpp | 86 + src/kvirc/kvs/KviKvsTreeNodeSpecialCommandWhile.h | 51 + src/kvirc/kvs/KviKvsTreeNodeStringCase.cpp | 64 + src/kvirc/kvs/KviKvsTreeNodeStringCase.h | 45 + src/kvirc/kvs/KviKvsTreeNodeSwitchList.cpp | 167 + src/kvirc/kvs/KviKvsTreeNodeSwitchList.h | 61 + .../kvs/KviKvsTreeNodeThisObjectFunctionCall.cpp | 60 + .../kvs/KviKvsTreeNodeThisObjectFunctionCall.h | 49 + src/kvirc/kvs/KviKvsTreeNodeVariable.cpp | 50 + src/kvirc/kvs/KviKvsTreeNodeVariable.h | 47 + src/kvirc/kvs/KviKvsTreeNodeVoidFunctionCall.cpp | 56 + src/kvirc/kvs/KviKvsTreeNodeVoidFunctionCall.h | 47 + src/kvirc/kvs/KviKvsTypes.h | 38 + src/kvirc/kvs/KviKvsUserAction.cpp | 360 ++ src/kvirc/kvs/KviKvsUserAction.h | 100 + src/kvirc/kvs/KviKvsVariant.cpp | 1759 +++++++++ src/kvirc/kvs/KviKvsVariant.h | 874 +++++ src/kvirc/kvs/KviKvsVariantList.cpp | 214 ++ src/kvirc/kvs/KviKvsVariantList.h | 321 ++ src/kvirc/kvs/kvi_kvs.cpp | 141 - src/kvirc/kvs/kvi_kvs.h | 59 - src/kvirc/kvs/kvi_kvs_action.cpp | 50 - src/kvirc/kvs/kvi_kvs_action.h | 82 - src/kvirc/kvs/kvi_kvs_aliasmanager.cpp | 156 - src/kvirc/kvs/kvi_kvs_aliasmanager.h | 67 - src/kvirc/kvs/kvi_kvs_array.cpp | 249 -- src/kvirc/kvs/kvi_kvs_array.h | 163 - src/kvirc/kvs/kvi_kvs_arraycast.cpp | 44 - src/kvirc/kvs/kvi_kvs_arraycast.h | 50 - src/kvirc/kvs/kvi_kvs_asyncdnsoperation.cpp | 122 - src/kvirc/kvs/kvi_kvs_asyncdnsoperation.h | 53 - src/kvirc/kvs/kvi_kvs_asyncoperation.cpp | 66 - src/kvirc/kvs/kvi_kvs_asyncoperation.h | 60 - src/kvirc/kvs/kvi_kvs_callbackobject.cpp | 108 - src/kvirc/kvs/kvi_kvs_callbackobject.h | 84 - src/kvirc/kvs/kvi_kvs_corecallbackcommands.cpp | 1205 ------ src/kvirc/kvs/kvi_kvs_corecallbackcommands.h | 74 - src/kvirc/kvs/kvi_kvs_corefunctions.cpp | 167 - src/kvirc/kvs/kvi_kvs_corefunctions.h | 156 - src/kvirc/kvs/kvi_kvs_corefunctions_af.cpp | 1528 -------- src/kvirc/kvs/kvi_kvs_corefunctions_gl.cpp | 1050 ------ src/kvirc/kvs/kvi_kvs_corefunctions_mr.cpp | 752 ---- src/kvirc/kvs/kvi_kvs_corefunctions_sz.cpp | 1136 ------ src/kvirc/kvs/kvi_kvs_coresimplecommands.cpp | 246 -- src/kvirc/kvs/kvi_kvs_coresimplecommands.h | 140 - src/kvirc/kvs/kvi_kvs_coresimplecommands_af.cpp | 1565 -------- src/kvirc/kvs/kvi_kvs_coresimplecommands_gl.cpp | 694 ---- src/kvirc/kvs/kvi_kvs_coresimplecommands_mr.cpp | 1306 ------- src/kvirc/kvs/kvi_kvs_coresimplecommands_sz.cpp | 1129 ------ src/kvirc/kvs/kvi_kvs_dnsmanager.cpp | 179 - src/kvirc/kvs/kvi_kvs_dnsmanager.h | 87 - src/kvirc/kvs/kvi_kvs_event.cpp | 78 - src/kvirc/kvs/kvi_kvs_event.h | 54 - src/kvirc/kvs/kvi_kvs_eventhandler.cpp | 76 - src/kvirc/kvs/kvi_kvs_eventhandler.h | 106 - src/kvirc/kvs/kvi_kvs_eventmanager.cpp | 673 ---- src/kvirc/kvs/kvi_kvs_eventmanager.h | 123 - src/kvirc/kvs/kvi_kvs_eventtable.cpp | 3804 ------------------- src/kvirc/kvs/kvi_kvs_eventtable.h | 371 -- src/kvirc/kvs/kvi_kvs_eventtriggers.h | 289 -- src/kvirc/kvs/kvi_kvs_hash.cpp | 99 - src/kvirc/kvs/kvi_kvs_hash.h | 137 - src/kvirc/kvs/kvi_kvs_kernel.cpp | 223 -- src/kvirc/kvs/kvi_kvs_kernel.h | 158 - src/kvirc/kvs/kvi_kvs_moduleinterface.cpp | 196 - src/kvirc/kvs/kvi_kvs_moduleinterface.h | 230 -- src/kvirc/kvs/kvi_kvs_object.cpp | 1814 --------- src/kvirc/kvs/kvi_kvs_object.h | 199 - src/kvirc/kvs/kvi_kvs_object_class.cpp | 235 -- src/kvirc/kvs/kvi_kvs_object_class.h | 112 - src/kvirc/kvs/kvi_kvs_object_controller.cpp | 258 -- src/kvirc/kvs/kvi_kvs_object_controller.h | 70 - src/kvirc/kvs/kvi_kvs_object_functioncall.cpp | 26 - src/kvirc/kvs/kvi_kvs_object_functioncall.h | 49 - src/kvirc/kvs/kvi_kvs_object_functionhandler.cpp | 59 - src/kvirc/kvs/kvi_kvs_object_functionhandler.h | 62 - .../kvs/kvi_kvs_object_functionhandlerimpl.cpp | 147 - src/kvirc/kvs/kvi_kvs_object_functionhandlerimpl.h | 119 - src/kvirc/kvs/kvi_kvs_parameterprocessor.cpp | 366 -- src/kvirc/kvs/kvi_kvs_parameterprocessor.h | 245 -- src/kvirc/kvs/kvi_kvs_parser.cpp | 3909 -------------------- src/kvirc/kvs/kvi_kvs_parser.h | 303 -- src/kvirc/kvs/kvi_kvs_parser_command.cpp | 348 -- src/kvirc/kvs/kvi_kvs_parser_comment.cpp | 90 - src/kvirc/kvs/kvi_kvs_parser_dollar.cpp | 321 -- src/kvirc/kvs/kvi_kvs_parser_expression.cpp | 629 ---- src/kvirc/kvs/kvi_kvs_parser_lside.cpp | 958 ----- src/kvirc/kvs/kvi_kvs_parser_macros.h | 47 - src/kvirc/kvs/kvi_kvs_parser_specialcommands.cpp | 2045 ---------- src/kvirc/kvs/kvi_kvs_popupmanager.cpp | 123 - src/kvirc/kvs/kvi_kvs_popupmanager.h | 61 - src/kvirc/kvs/kvi_kvs_popupmenu.cpp | 1229 ------ src/kvirc/kvs/kvi_kvs_popupmenu.h | 293 -- src/kvirc/kvs/kvi_kvs_processmanager.cpp | 379 -- src/kvirc/kvs/kvi_kvs_processmanager.h | 106 - src/kvirc/kvs/kvi_kvs_report.cpp | 244 -- src/kvirc/kvs/kvi_kvs_report.h | 75 - src/kvirc/kvs/kvi_kvs_runtimecall.cpp | 48 - src/kvirc/kvs/kvi_kvs_runtimecall.h | 82 - src/kvirc/kvs/kvi_kvs_runtimecontext.cpp | 204 - src/kvirc/kvs/kvi_kvs_runtimecontext.h | 265 -- src/kvirc/kvs/kvi_kvs_rwevaluationresult.cpp | 70 - src/kvirc/kvs/kvi_kvs_rwevaluationresult.h | 70 - src/kvirc/kvs/kvi_kvs_script.cpp | 352 -- src/kvirc/kvs/kvi_kvs_script.h | 324 -- src/kvirc/kvs/kvi_kvs_scriptaddonmanager.cpp | 412 --- src/kvirc/kvs/kvi_kvs_scriptaddonmanager.h | 137 - src/kvirc/kvs/kvi_kvs_switchlist.cpp | 74 - src/kvirc/kvs/kvi_kvs_switchlist.h | 87 - src/kvirc/kvs/kvi_kvs_timermanager.cpp | 249 -- src/kvirc/kvs/kvi_kvs_timermanager.h | 124 - src/kvirc/kvs/kvi_kvs_treenode.h | 378 -- .../kvs/kvi_kvs_treenode_aliasfunctioncall.cpp | 76 - src/kvirc/kvs/kvi_kvs_treenode_aliasfunctioncall.h | 84 - .../kvs/kvi_kvs_treenode_aliassimplecommand.cpp | 122 - .../kvs/kvi_kvs_treenode_aliassimplecommand.h | 83 - src/kvirc/kvs/kvi_kvs_treenode_arraycount.cpp | 82 - src/kvirc/kvs/kvi_kvs_treenode_arraycount.h | 93 - src/kvirc/kvs/kvi_kvs_treenode_arrayelement.cpp | 152 - src/kvirc/kvs/kvi_kvs_treenode_arrayelement.h | 120 - .../kvs/kvi_kvs_treenode_arrayorhashelement.cpp | 43 - .../kvs/kvi_kvs_treenode_arrayorhashelement.h | 42 - .../kvs/kvi_kvs_treenode_arrayreferenceassert.cpp | 99 - .../kvs/kvi_kvs_treenode_arrayreferenceassert.h | 118 - src/kvirc/kvs/kvi_kvs_treenode_base.cpp | 32 - src/kvirc/kvs/kvi_kvs_treenode_base.h | 102 - .../kvi_kvs_treenode_baseobjectfunctioncall.cpp | 60 - .../kvs/kvi_kvs_treenode_baseobjectfunctioncall.h | 50 - src/kvirc/kvs/kvi_kvs_treenode_callbackcommand.cpp | 61 - src/kvirc/kvs/kvi_kvs_treenode_callbackcommand.h | 48 - src/kvirc/kvs/kvi_kvs_treenode_command.cpp | 65 - src/kvirc/kvs/kvi_kvs_treenode_command.h | 54 - .../kvs/kvi_kvs_treenode_commandevaluation.cpp | 48 - src/kvirc/kvs/kvi_kvs_treenode_commandevaluation.h | 46 - .../kvs/kvi_kvs_treenode_commandwithparameters.cpp | 58 - .../kvs/kvi_kvs_treenode_commandwithparameters.h | 49 - src/kvirc/kvs/kvi_kvs_treenode_compositedata.cpp | 82 - src/kvirc/kvs/kvi_kvs_treenode_compositedata.h | 46 - src/kvirc/kvs/kvi_kvs_treenode_constantdata.cpp | 78 - src/kvirc/kvs/kvi_kvs_treenode_constantdata.h | 50 - .../kvs/kvi_kvs_treenode_corecallbackcommand.cpp | 70 - .../kvs/kvi_kvs_treenode_corecallbackcommand.h | 51 - .../kvs/kvi_kvs_treenode_corefunctioncall.cpp | 60 - src/kvirc/kvs/kvi_kvs_treenode_corefunctioncall.h | 48 - .../kvs/kvi_kvs_treenode_coresimplecommand.cpp | 68 - src/kvirc/kvs/kvi_kvs_treenode_coresimplecommand.h | 49 - src/kvirc/kvs/kvi_kvs_treenode_data.cpp | 104 - src/kvirc/kvs/kvi_kvs_treenode_data.h | 62 - src/kvirc/kvs/kvi_kvs_treenode_datalist.cpp | 108 - src/kvirc/kvs/kvi_kvs_treenode_datalist.h | 55 - src/kvirc/kvs/kvi_kvs_treenode_expression.cpp | 728 ---- src/kvirc/kvs/kvi_kvs_treenode_expression.h | 238 -- .../kvs/kvi_kvs_treenode_expressionreturn.cpp | 58 - src/kvirc/kvs/kvi_kvs_treenode_expressionreturn.h | 45 - .../kvs/kvi_kvs_treenode_extendedscopevariable.cpp | 77 - .../kvs/kvi_kvs_treenode_extendedscopevariable.h | 45 - src/kvirc/kvs/kvi_kvs_treenode_functioncall.cpp | 59 - src/kvirc/kvs/kvi_kvs_treenode_functioncall.h | 47 - src/kvirc/kvs/kvi_kvs_treenode_globalvariable.cpp | 61 - src/kvirc/kvs/kvi_kvs_treenode_globalvariable.h | 45 - src/kvirc/kvs/kvi_kvs_treenode_hashcount.cpp | 79 - src/kvirc/kvs/kvi_kvs_treenode_hashcount.h | 47 - src/kvirc/kvs/kvi_kvs_treenode_hashelement.cpp | 148 - src/kvirc/kvs/kvi_kvs_treenode_hashelement.h | 52 - .../kvs/kvi_kvs_treenode_hashreferenceassert.cpp | 95 - .../kvs/kvi_kvs_treenode_hashreferenceassert.h | 53 - src/kvirc/kvs/kvi_kvs_treenode_indirectdata.cpp | 42 - src/kvirc/kvs/kvi_kvs_treenode_indirectdata.h | 42 - src/kvirc/kvs/kvi_kvs_treenode_instruction.cpp | 36 - src/kvirc/kvs/kvi_kvs_treenode_instruction.h | 85 - .../kvs/kvi_kvs_treenode_instructionblock.cpp | 85 - src/kvirc/kvs/kvi_kvs_treenode_instructionblock.h | 55 - src/kvirc/kvs/kvi_kvs_treenode_localvariable.cpp | 70 - src/kvirc/kvs/kvi_kvs_treenode_localvariable.h | 45 - .../kvs/kvi_kvs_treenode_modulecallbackcommand.cpp | 94 - .../kvs/kvi_kvs_treenode_modulecallbackcommand.h | 50 - .../kvs/kvi_kvs_treenode_modulefunctioncall.cpp | 87 - .../kvs/kvi_kvs_treenode_modulefunctioncall.h | 48 - .../kvs/kvi_kvs_treenode_modulesimplecommand.cpp | 94 - .../kvs/kvi_kvs_treenode_modulesimplecommand.h | 48 - ...vi_kvs_treenode_multipleparameteridentifier.cpp | 87 - .../kvi_kvs_treenode_multipleparameteridentifier.h | 49 - src/kvirc/kvs/kvi_kvs_treenode_objectfield.cpp | 67 - src/kvirc/kvs/kvi_kvs_treenode_objectfield.h | 47 - .../kvs/kvi_kvs_treenode_objectfunctioncall.cpp | 54 - .../kvs/kvi_kvs_treenode_objectfunctioncall.h | 45 - src/kvirc/kvs/kvi_kvs_treenode_operation.cpp | 1275 ------- src/kvirc/kvs/kvi_kvs_treenode_operation.h | 296 -- src/kvirc/kvs/kvi_kvs_treenode_parameterreturn.cpp | 76 - src/kvirc/kvs/kvi_kvs_treenode_parameterreturn.h | 45 - src/kvirc/kvs/kvi_kvs_treenode_rebindingswitch.cpp | 93 - src/kvirc/kvs/kvi_kvs_treenode_rebindingswitch.h | 49 - src/kvirc/kvs/kvi_kvs_treenode_scopeoperator.cpp | 144 - src/kvirc/kvs/kvi_kvs_treenode_scopeoperator.h | 58 - src/kvirc/kvs/kvi_kvs_treenode_simplecommand.cpp | 50 - src/kvirc/kvs/kvi_kvs_treenode_simplecommand.h | 43 - .../kvi_kvs_treenode_singleparameteridentifier.cpp | 63 - .../kvi_kvs_treenode_singleparameteridentifier.h | 50 - src/kvirc/kvs/kvi_kvs_treenode_specialcommand.cpp | 49 - src/kvirc/kvs/kvi_kvs_treenode_specialcommand.h | 41 - .../kvs/kvi_kvs_treenode_specialcommandbreak.cpp | 52 - .../kvs/kvi_kvs_treenode_specialcommandbreak.h | 45 - .../kvs/kvi_kvs_treenode_specialcommandclass.cpp | 164 - .../kvs/kvi_kvs_treenode_specialcommandclass.h | 71 - .../kvi_kvs_treenode_specialcommandcontinue.cpp | 52 - .../kvs/kvi_kvs_treenode_specialcommandcontinue.h | 45 - .../kvi_kvs_treenode_specialcommanddefpopup.cpp | 347 -- .../kvs/kvi_kvs_treenode_specialcommanddefpopup.h | 193 - .../kvs/kvi_kvs_treenode_specialcommanddo.cpp | 86 - src/kvirc/kvs/kvi_kvs_treenode_specialcommanddo.h | 51 - .../kvs/kvi_kvs_treenode_specialcommandfor.cpp | 137 - src/kvirc/kvs/kvi_kvs_treenode_specialcommandfor.h | 53 - .../kvs/kvi_kvs_treenode_specialcommandforeach.cpp | 235 -- .../kvs/kvi_kvs_treenode_specialcommandforeach.h | 53 - .../kvs/kvi_kvs_treenode_specialcommandif.cpp | 76 - src/kvirc/kvs/kvi_kvs_treenode_specialcommandif.h | 50 - .../kvs/kvi_kvs_treenode_specialcommandswitch.cpp | 357 -- .../kvs/kvi_kvs_treenode_specialcommandswitch.h | 117 - .../kvs/kvi_kvs_treenode_specialcommandunset.cpp | 71 - .../kvs/kvi_kvs_treenode_specialcommandunset.h | 47 - .../kvs/kvi_kvs_treenode_specialcommandwhile.cpp | 86 - .../kvs/kvi_kvs_treenode_specialcommandwhile.h | 51 - src/kvirc/kvs/kvi_kvs_treenode_stringcast.cpp | 64 - src/kvirc/kvs/kvi_kvs_treenode_stringcast.h | 45 - src/kvirc/kvs/kvi_kvs_treenode_switchlist.cpp | 167 - src/kvirc/kvs/kvi_kvs_treenode_switchlist.h | 61 - .../kvi_kvs_treenode_thisobjectfunctioncall.cpp | 60 - .../kvs/kvi_kvs_treenode_thisobjectfunctioncall.h | 49 - src/kvirc/kvs/kvi_kvs_treenode_variable.cpp | 50 - src/kvirc/kvs/kvi_kvs_treenode_variable.h | 47 - .../kvs/kvi_kvs_treenode_voidfunctioncall.cpp | 56 - src/kvirc/kvs/kvi_kvs_treenode_voidfunctioncall.h | 47 - src/kvirc/kvs/kvi_kvs_types.h | 38 - src/kvirc/kvs/kvi_kvs_useraction.cpp | 360 -- src/kvirc/kvs/kvi_kvs_useraction.h | 100 - src/kvirc/kvs/kvi_kvs_variant.cpp | 1759 --------- src/kvirc/kvs/kvi_kvs_variant.h | 874 ----- src/kvirc/kvs/kvi_kvs_variantlist.cpp | 214 -- src/kvirc/kvs/kvi_kvs_variantlist.h | 321 -- src/kvirc/module/KviMexLinkFilter.cpp | 35 + src/kvirc/module/KviMexLinkFilter.h | 46 + src/kvirc/module/KviMexServerImport.cpp | 34 + src/kvirc/module/KviMexServerImport.h | 46 + src/kvirc/module/KviMexToolBar.cpp | 38 + src/kvirc/module/KviMexToolBar.h | 40 + src/kvirc/module/KviModule.cpp | 223 ++ src/kvirc/module/KviModule.h | 199 + src/kvirc/module/KviModuleExtension.cpp | 241 ++ src/kvirc/module/KviModuleExtension.h | 145 + src/kvirc/module/KviModuleManager.cpp | 364 ++ src/kvirc/module/KviModuleManager.h | 69 + src/kvirc/module/kvi_mexlinkfilter.cpp | 35 - src/kvirc/module/kvi_mexlinkfilter.h | 46 - src/kvirc/module/kvi_mexserverimport.cpp | 34 - src/kvirc/module/kvi_mexserverimport.h | 46 - src/kvirc/module/kvi_mextoolbar.cpp | 38 - src/kvirc/module/kvi_mextoolbar.h | 40 - src/kvirc/module/kvi_module.cpp | 223 -- src/kvirc/module/kvi_module.h | 199 - src/kvirc/module/kvi_moduleextension.cpp | 241 -- src/kvirc/module/kvi_moduleextension.h | 145 - src/kvirc/module/kvi_modulemanager.cpp | 364 -- src/kvirc/module/kvi_modulemanager.h | 69 - src/kvirc/sparser/KviAntiSpam.cpp | 124 + src/kvirc/sparser/KviAntiSpam.h | 33 + src/kvirc/sparser/KviIrcMessage.cpp | 179 + src/kvirc/sparser/KviIrcMessage.h | 106 + src/kvirc/sparser/KviIrcNumericCodes.h | 440 +++ src/kvirc/sparser/KviIrcServerParser.cpp | 149 + src/kvirc/sparser/KviIrcServerParser.h | 279 ++ src/kvirc/sparser/KviIrcServerParser_ctcp.cpp | 1869 ++++++++++ .../sparser/KviIrcServerParser_literalHandlers.cpp | 2243 +++++++++++ .../sparser/KviIrcServerParser_numericHandlers.cpp | 2417 ++++++++++++ src/kvirc/sparser/KviIrcServerParser_tables.cpp | 1091 ++++++ src/kvirc/sparser/kvi_antispam.cpp | 124 - src/kvirc/sparser/kvi_antispam.h | 33 - src/kvirc/sparser/kvi_ircmessage.cpp | 179 - src/kvirc/sparser/kvi_ircmessage.h | 106 - src/kvirc/sparser/kvi_numeric.h | 440 --- src/kvirc/sparser/kvi_sp_ctcp.cpp | 1869 ---------- src/kvirc/sparser/kvi_sp_literal.cpp | 2243 ----------- src/kvirc/sparser/kvi_sp_numeric.cpp | 2417 ------------ src/kvirc/sparser/kvi_sp_tables.cpp | 1091 ------ src/kvirc/sparser/kvi_sparser.cpp | 149 - src/kvirc/sparser/kvi_sparser.h | 279 -- src/kvirc/ui/KviActionDrawer.cpp | 184 + src/kvirc/ui/KviActionDrawer.h | 164 + src/kvirc/ui/KviChannelWindow.cpp | 2027 ++++++++++ src/kvirc/ui/KviChannelWindow.h | 1074 ++++++ src/kvirc/ui/KviColorSelectionWindow.cpp | 131 + src/kvirc/ui/KviColorSelectionWindow.h | 73 + src/kvirc/ui/KviConsoleWindow.cpp | 1284 +++++++ src/kvirc/ui/KviConsoleWindow.h | 245 ++ src/kvirc/ui/KviCryptController.cpp | 374 ++ src/kvirc/ui/KviCryptController.h | 108 + src/kvirc/ui/KviCtcpPageDialog.cpp | 145 + src/kvirc/ui/KviCtcpPageDialog.h | 57 + src/kvirc/ui/KviCustomToolBar.cpp | 579 +++ src/kvirc/ui/KviCustomToolBar.h | 88 + src/kvirc/ui/KviDebugWindow.cpp | 112 + src/kvirc/ui/KviDebugWindow.h | 54 + src/kvirc/ui/KviDynamicToolTip.cpp | 65 + src/kvirc/ui/KviDynamicToolTip.h | 63 + src/kvirc/ui/KviFileDialog.cpp | 263 ++ src/kvirc/ui/KviFileDialog.h | 117 + src/kvirc/ui/KviHistoryWindow.cpp | 280 ++ src/kvirc/ui/KviHistoryWindow.h | 144 + src/kvirc/ui/KviHtmlDialog.cpp | 156 + src/kvirc/ui/KviHtmlDialog.h | 133 + src/kvirc/ui/KviImageDialog.cpp | 357 ++ src/kvirc/ui/KviImageDialog.h | 107 + src/kvirc/ui/KviInput.cpp | 494 +++ src/kvirc/ui/KviInput.h | 216 ++ src/kvirc/ui/KviInputEditor.cpp | 2537 +++++++++++++ src/kvirc/ui/KviInputEditor.h | 963 +++++ src/kvirc/ui/KviInputHistory.cpp | 117 + src/kvirc/ui/KviInputHistory.h | 130 + src/kvirc/ui/KviIpEditor.cpp | 415 +++ src/kvirc/ui/KviIpEditor.h | 63 + src/kvirc/ui/KviIrcToolBar.cpp | 446 +++ src/kvirc/ui/KviIrcToolBar.h | 90 + src/kvirc/ui/KviIrcView.cpp | 2782 ++++++++++++++ src/kvirc/ui/KviIrcView.h | 252 ++ src/kvirc/ui/KviIrcView_events.cpp | 1098 ++++++ src/kvirc/ui/KviIrcView_getTextLine.cpp | 1153 ++++++ src/kvirc/ui/KviIrcView_loghandling.cpp | 293 ++ src/kvirc/ui/KviIrcView_private.h | 165 + src/kvirc/ui/KviIrcView_tools.cpp | 361 ++ src/kvirc/ui/KviIrcView_tools.h | 124 + src/kvirc/ui/KviMainWindow.cpp | 1153 ++++++ src/kvirc/ui/KviMainWindow.h | 244 ++ src/kvirc/ui/KviMaskEditor.cpp | 355 ++ src/kvirc/ui/KviMaskEditor.h | 124 + src/kvirc/ui/KviMdiChild.cpp | 272 ++ src/kvirc/ui/KviMdiChild.h | 227 ++ src/kvirc/ui/KviMdiManager.cpp | 675 ++++ src/kvirc/ui/KviMdiManager.h | 204 + src/kvirc/ui/KviMenuBar.cpp | 417 +++ src/kvirc/ui/KviMenuBar.h | 78 + src/kvirc/ui/KviMessageBox.cpp | 86 + src/kvirc/ui/KviMessageBox.h | 54 + src/kvirc/ui/KviModeEditor.cpp | 441 +++ src/kvirc/ui/KviModeEditor.h | 68 + src/kvirc/ui/KviModeWidget.cpp | 282 ++ src/kvirc/ui/KviModeWidget.h | 54 + src/kvirc/ui/KviOptionsWidget.cpp | 776 ++++ src/kvirc/ui/KviOptionsWidget.h | 164 + src/kvirc/ui/KviQueryWindow.cpp | 906 +++++ src/kvirc/ui/KviQueryWindow.h | 327 ++ src/kvirc/ui/KviScriptButton.cpp | 87 + src/kvirc/ui/KviScriptButton.h | 66 + src/kvirc/ui/KviScriptEditor.cpp | 142 + src/kvirc/ui/KviScriptEditor.h | 73 + src/kvirc/ui/KviSelectors.cpp | 931 +++++ src/kvirc/ui/KviSelectors.h | 424 +++ src/kvirc/ui/KviSplashScreen.cpp | 197 + src/kvirc/ui/KviSplashScreen.h | 113 + src/kvirc/ui/KviStatusBar.cpp | 702 ++++ src/kvirc/ui/KviStatusBar.h | 318 ++ src/kvirc/ui/KviStatusBarApplet.cpp | 858 +++++ src/kvirc/ui/KviStatusBarApplet.h | 243 ++ src/kvirc/ui/KviTextIconWindow.cpp | 188 + src/kvirc/ui/KviTextIconWindow.h | 106 + src/kvirc/ui/KviThemedComboBox.cpp | 134 + src/kvirc/ui/KviThemedComboBox.h | 49 + src/kvirc/ui/KviThemedLabel.cpp | 103 + src/kvirc/ui/KviThemedLabel.h | 52 + src/kvirc/ui/KviThemedLineEdit.cpp | 124 + src/kvirc/ui/KviThemedLineEdit.h | 49 + src/kvirc/ui/KviThemedTreeWidget.cpp | 94 + src/kvirc/ui/KviThemedTreeWidget.h | 50 + src/kvirc/ui/KviToolBar.cpp | 108 + src/kvirc/ui/KviToolBar.h | 42 + src/kvirc/ui/KviTopicWidget.cpp | 700 ++++ src/kvirc/ui/KviTopicWidget.h | 127 + src/kvirc/ui/KviTreeWindowList.cpp | 644 ++++ src/kvirc/ui/KviTreeWindowList.h | 123 + src/kvirc/ui/KviUserListView.cpp | 2479 +++++++++++++ src/kvirc/ui/KviUserListView.h | 859 +++++ src/kvirc/ui/KviWindow.cpp | 1400 +++++++ src/kvirc/ui/KviWindow.h | 398 ++ src/kvirc/ui/KviWindowListBase.cpp | 747 ++++ src/kvirc/ui/KviWindowListBase.h | 185 + src/kvirc/ui/KviWindowToolWidget.cpp | 67 + src/kvirc/ui/KviWindowToolWidget.h | 53 + src/kvirc/ui/kvi_actiondrawer.cpp | 184 - src/kvirc/ui/kvi_actiondrawer.h | 164 - src/kvirc/ui/kvi_channel.cpp | 2027 ---------- src/kvirc/ui/kvi_channel.h | 1074 ------ src/kvirc/ui/kvi_colorwin.cpp | 131 - src/kvirc/ui/kvi_colorwin.h | 73 - src/kvirc/ui/kvi_console.cpp | 1284 ------- src/kvirc/ui/kvi_console.h | 245 -- src/kvirc/ui/kvi_cryptcontroller.cpp | 374 -- src/kvirc/ui/kvi_cryptcontroller.h | 108 - src/kvirc/ui/kvi_ctcppagedialog.cpp | 145 - src/kvirc/ui/kvi_ctcppagedialog.h | 57 - src/kvirc/ui/kvi_customtoolbar.cpp | 579 --- src/kvirc/ui/kvi_customtoolbar.h | 88 - src/kvirc/ui/kvi_debugwindow.cpp | 112 - src/kvirc/ui/kvi_debugwindow.h | 54 - src/kvirc/ui/kvi_dynamictooltip.cpp | 65 - src/kvirc/ui/kvi_dynamictooltip.h | 63 - src/kvirc/ui/kvi_filedialog.cpp | 263 -- src/kvirc/ui/kvi_filedialog.h | 117 - src/kvirc/ui/kvi_frame.cpp | 1153 ------ src/kvirc/ui/kvi_frame.h | 244 -- src/kvirc/ui/kvi_historywin.cpp | 280 -- src/kvirc/ui/kvi_historywin.h | 144 - src/kvirc/ui/kvi_htmldialog.cpp | 156 - src/kvirc/ui/kvi_htmldialog.h | 133 - src/kvirc/ui/kvi_imagedialog.cpp | 357 -- src/kvirc/ui/kvi_imagedialog.h | 107 - src/kvirc/ui/kvi_input.cpp | 494 --- src/kvirc/ui/kvi_input.h | 216 -- src/kvirc/ui/kvi_input_editor.cpp | 2537 ------------- src/kvirc/ui/kvi_input_editor.h | 963 ----- src/kvirc/ui/kvi_input_history.cpp | 117 - src/kvirc/ui/kvi_input_history.h | 130 - src/kvirc/ui/kvi_ipeditor.cpp | 415 --- src/kvirc/ui/kvi_ipeditor.h | 63 - src/kvirc/ui/kvi_irctoolbar.cpp | 446 --- src/kvirc/ui/kvi_irctoolbar.h | 90 - src/kvirc/ui/kvi_ircview.cpp | 2782 -------------- src/kvirc/ui/kvi_ircview.h | 252 -- src/kvirc/ui/kvi_ircview_events.cpp | 1098 ------ src/kvirc/ui/kvi_ircview_gettextline.cpp | 1153 ------ src/kvirc/ui/kvi_ircview_loghandling.cpp | 293 -- src/kvirc/ui/kvi_ircviewprivate.h | 165 - src/kvirc/ui/kvi_ircviewtools.cpp | 361 -- src/kvirc/ui/kvi_ircviewtools.h | 124 - src/kvirc/ui/kvi_maskeditor.cpp | 355 -- src/kvirc/ui/kvi_maskeditor.h | 124 - src/kvirc/ui/kvi_mdichild.cpp | 272 -- src/kvirc/ui/kvi_mdichild.h | 227 -- src/kvirc/ui/kvi_mdimanager.cpp | 675 ---- src/kvirc/ui/kvi_mdimanager.h | 204 - src/kvirc/ui/kvi_menubar.cpp | 417 --- src/kvirc/ui/kvi_menubar.h | 78 - src/kvirc/ui/kvi_modeeditor.cpp | 441 --- src/kvirc/ui/kvi_modeeditor.h | 68 - src/kvirc/ui/kvi_modew.cpp | 282 -- src/kvirc/ui/kvi_modew.h | 54 - src/kvirc/ui/kvi_msgbox.cpp | 86 - src/kvirc/ui/kvi_msgbox.h | 54 - src/kvirc/ui/kvi_optionswidget.cpp | 776 ---- src/kvirc/ui/kvi_optionswidget.h | 164 - src/kvirc/ui/kvi_query.cpp | 906 ----- src/kvirc/ui/kvi_query.h | 327 -- src/kvirc/ui/kvi_scriptbutton.cpp | 87 - src/kvirc/ui/kvi_scriptbutton.h | 66 - src/kvirc/ui/kvi_scripteditor.cpp | 142 - src/kvirc/ui/kvi_scripteditor.h | 73 - src/kvirc/ui/kvi_selectors.cpp | 931 ----- src/kvirc/ui/kvi_selectors.h | 424 --- src/kvirc/ui/kvi_splash.cpp | 197 - src/kvirc/ui/kvi_splash.h | 113 - src/kvirc/ui/kvi_statusbar.cpp | 702 ---- src/kvirc/ui/kvi_statusbar.h | 318 -- src/kvirc/ui/kvi_statusbarapplet.cpp | 858 ----- src/kvirc/ui/kvi_statusbarapplet.h | 243 -- src/kvirc/ui/kvi_texticonwin.cpp | 188 - src/kvirc/ui/kvi_texticonwin.h | 106 - src/kvirc/ui/kvi_themedcombobox.cpp | 134 - src/kvirc/ui/kvi_themedcombobox.h | 49 - src/kvirc/ui/kvi_themedlabel.cpp | 103 - src/kvirc/ui/kvi_themedlabel.h | 52 - src/kvirc/ui/kvi_themedlineedit.cpp | 124 - src/kvirc/ui/kvi_themedlineedit.h | 49 - src/kvirc/ui/kvi_themedtreewidget.cpp | 94 - src/kvirc/ui/kvi_themedtreewidget.h | 50 - src/kvirc/ui/kvi_toolbar.cpp | 108 - src/kvirc/ui/kvi_toolbar.h | 42 - src/kvirc/ui/kvi_toolwindows_container.cpp | 67 - src/kvirc/ui/kvi_toolwindows_container.h | 53 - src/kvirc/ui/kvi_topicw.cpp | 700 ---- src/kvirc/ui/kvi_topicw.h | 127 - src/kvirc/ui/kvi_userlistview.cpp | 2479 ------------- src/kvirc/ui/kvi_userlistview.h | 859 ----- src/kvirc/ui/kvi_window.cpp | 1400 ------- src/kvirc/ui/kvi_window.h | 398 -- src/kvirc/ui/kvi_windowlist.cpp | 747 ---- src/kvirc/ui/kvi_windowlist.h | 185 - src/kvirc/ui/kvi_windowlist_tree.cpp | 644 ---- src/kvirc/ui/kvi_windowlist_tree.h | 123 - src/modules/about/aboutdialog.cpp | 4 +- src/modules/about/libkviabout.cpp | 2 +- src/modules/action/libkviaction.cpp | 12 +- src/modules/actioneditor/actioneditor.cpp | 24 +- src/modules/actioneditor/actioneditor.h | 4 +- src/modules/actioneditor/libkviactioneditor.cpp | 4 +- src/modules/addon/addonfunctions.cpp | 14 +- src/modules/addon/libkviaddon.cpp | 12 +- src/modules/addon/managementdialog.cpp | 14 +- src/modules/addon/packaddondialog.cpp | 6 +- src/modules/addon/packaddondialog.h | 2 +- src/modules/aliaseditor/aliaseditor.cpp | 22 +- src/modules/aliaseditor/aliaseditor.h | 4 +- src/modules/aliaseditor/libkvialiaseditor.cpp | 4 +- src/modules/avatar/libkviavatar.cpp | 22 +- src/modules/chan/libkvichan.cpp | 102 +- src/modules/channelsjoin/channelsjoinwindow.cpp | 14 +- src/modules/channelsjoin/channelsjoinwindow.h | 2 +- src/modules/channelsjoin/libkvichannelsjoin.cpp | 6 +- src/modules/classeditor/classeditor.cpp | 40 +- src/modules/classeditor/classeditor.h | 6 +- src/modules/classeditor/libkviclasseditor.cpp | 4 +- src/modules/codetester/codetester.cpp | 18 +- src/modules/codetester/codetester.h | 4 +- src/modules/codetester/libkvicodetester.cpp | 4 +- src/modules/config/libkviconfig.cpp | 8 +- src/modules/context/libkvicontext.cpp | 20 +- src/modules/dcc/broker.cpp | 16 +- src/modules/dcc/broker.h | 2 +- src/modules/dcc/canvas.cpp | 18 +- src/modules/dcc/canvas.h | 4 +- src/modules/dcc/chat.cpp | 30 +- src/modules/dcc/chat.h | 6 +- src/modules/dcc/descriptor.cpp | 6 +- src/modules/dcc/descriptor.h | 2 +- src/modules/dcc/dialogs.cpp | 4 +- src/modules/dcc/dialogs.h | 2 +- src/modules/dcc/libkvidcc.cpp | 18 +- src/modules/dcc/marshal.cpp | 2 +- src/modules/dcc/marshal.h | 2 +- src/modules/dcc/requests.cpp | 18 +- src/modules/dcc/send.cpp | 26 +- src/modules/dcc/send.h | 4 +- src/modules/dcc/thread.cpp | 4 +- src/modules/dcc/utils.cpp | 6 +- src/modules/dcc/utils.h | 4 +- src/modules/dcc/video.cpp | 22 +- src/modules/dcc/video.h | 6 +- src/modules/dcc/voice.cpp | 12 +- src/modules/dcc/voice.h | 4 +- src/modules/dcc/window.cpp | 2 +- src/modules/dcc/window.h | 4 +- src/modules/dialog/libkvidialog.cpp | 16 +- src/modules/dialog/libkvidialog.h | 8 +- src/modules/editor/libkvieditor.cpp | 6 +- src/modules/editor/scripteditor.cpp | 24 +- src/modules/editor/scripteditor.h | 4 +- src/modules/eventeditor/eventeditor.cpp | 18 +- src/modules/eventeditor/eventeditor.h | 4 +- src/modules/eventeditor/libkvieventeditor.cpp | 4 +- src/modules/file/libkvifile.cpp | 12 +- .../filetransferwindow/filetransferwindow.cpp | 16 +- .../filetransferwindow/filetransferwindow.h | 16 +- .../libkvifiletransferwindow.cpp | 10 +- src/modules/help/helpwidget.cpp | 14 +- src/modules/help/helpwidget.h | 4 +- src/modules/help/helpwindow.cpp | 14 +- src/modules/help/helpwindow.h | 4 +- src/modules/help/libkvihelp.cpp | 20 +- src/modules/http/httpfiletransfer.cpp | 12 +- src/modules/http/httpfiletransfer.h | 4 +- src/modules/http/libkvihttp.cpp | 10 +- src/modules/ident/libkviident.cpp | 8 +- src/modules/iograph/libkviiograph.cpp | 12 +- src/modules/iograph/libkviiograph.h | 8 +- src/modules/lamerizer/libkvilamerizer.cpp | 2 +- src/modules/language/libkvilanguage.cpp | 4 +- src/modules/links/libkvilinks.cpp | 6 +- src/modules/links/linkswindow.cpp | 14 +- src/modules/links/linkswindow.h | 14 +- src/modules/list/libkvilist.cpp | 6 +- src/modules/list/listwindow.cpp | 26 +- src/modules/list/listwindow.h | 14 +- src/modules/log/libkvilog.cpp | 8 +- src/modules/logview/libkvilogview.cpp | 8 +- src/modules/logview/logviewmdiwindow.cpp | 22 +- src/modules/logview/logviewmdiwindow.h | 6 +- src/modules/logview/logviewwidget.cpp | 4 +- src/modules/logview/logviewwidget.h | 4 +- src/modules/mask/libkvimask.cpp | 2 +- src/modules/math/libkvimath.cpp | 2 +- src/modules/mediaplayer/libkvimediaplayer.cpp | 4 +- src/modules/mediaplayer/mp_amipinterface.cpp | 4 +- src/modules/mediaplayer/mp_interface.cpp | 2 +- src/modules/mediaplayer/mp_interface.h | 2 +- src/modules/mediaplayer/mp_mp3.cpp | 2 +- src/modules/mediaplayer/mp_winampinterface.cpp | 4 +- src/modules/mircimport/libkvimircimport.cpp | 6 +- src/modules/mircimport/libkvimircimport.h | 2 +- src/modules/my/libkvimy.cpp | 14 +- src/modules/notifier/libkvinotifier.cpp | 14 +- src/modules/notifier/notifiermessage.cpp | 4 +- src/modules/notifier/notifierwindow.cpp | 12 +- src/modules/notifier/notifierwindowborder.cpp | 2 +- src/modules/notifier/notifierwindowtab.cpp | 8 +- src/modules/objects/class_button.cpp | 2 +- src/modules/objects/class_buttongroup.cpp | 2 +- src/modules/objects/class_datetimeedit.cpp | 2 +- src/modules/objects/class_dialog.cpp | 4 +- src/modules/objects/class_dockwindow.cpp | 2 +- src/modules/objects/class_groupbox.cpp | 2 +- src/modules/objects/class_label.cpp | 2 +- src/modules/objects/class_lcd.cpp | 2 +- src/modules/objects/class_list.h | 2 +- src/modules/objects/class_listwidget.cpp | 2 +- src/modules/objects/class_mainwindow.cpp | 2 +- src/modules/objects/class_painter.cpp | 2 +- src/modules/objects/class_popupmenu.cpp | 2 +- src/modules/objects/class_progressbar.cpp | 2 +- src/modules/objects/class_radiobutton.cpp | 2 +- src/modules/objects/class_slider.cpp | 2 +- src/modules/objects/class_spinbox.cpp | 2 +- src/modules/objects/class_sql.h | 2 +- src/modules/objects/class_tablewidget.cpp | 6 +- src/modules/objects/class_tablewidget.h | 2 +- src/modules/objects/class_tabwidget.cpp | 2 +- src/modules/objects/class_tbrowser.cpp | 2 +- src/modules/objects/class_toolbar.cpp | 2 +- src/modules/objects/class_toolbutton.cpp | 2 +- src/modules/objects/class_trayicon.cpp | 2 +- src/modules/objects/class_treewidget.cpp | 2 +- src/modules/objects/class_treewidgetitem.cpp | 2 +- src/modules/objects/class_widget.cpp | 10 +- src/modules/objects/class_window.cpp | 4 +- src/modules/objects/class_window.h | 4 +- src/modules/objects/class_workspace.cpp | 2 +- src/modules/objects/class_wrapper.cpp | 22 +- src/modules/objects/class_xmlreader.cpp | 4 +- src/modules/objects/libkviobjects.cpp | 12 +- src/modules/objects/object_macros.h | 10 +- src/modules/options/container.cpp | 4 +- src/modules/options/container.h | 2 +- src/modules/options/dialog.cpp | 10 +- src/modules/options/dialog.h | 2 +- src/modules/options/instances.cpp | 2 +- src/modules/options/instances.h | 4 +- src/modules/options/libkvioptions.cpp | 12 +- src/modules/options/optw_antispam.cpp | 2 +- src/modules/options/optw_antispam.h | 2 +- src/modules/options/optw_avatar.cpp | 4 +- src/modules/options/optw_avatar.h | 2 +- src/modules/options/optw_away.cpp | 2 +- src/modules/options/optw_away.h | 2 +- src/modules/options/optw_channel.cpp | 2 +- src/modules/options/optw_channel.h | 2 +- src/modules/options/optw_connection.cpp | 4 +- src/modules/options/optw_connection.h | 2 +- src/modules/options/optw_ctcp.cpp | 2 +- src/modules/options/optw_ctcp.h | 2 +- src/modules/options/optw_ctcpfloodprotection.cpp | 2 +- src/modules/options/optw_ctcpfloodprotection.h | 2 +- src/modules/options/optw_dcc.cpp | 2 +- src/modules/options/optw_dcc.h | 2 +- src/modules/options/optw_generalopt.cpp | 2 +- src/modules/options/optw_generalopt.h | 2 +- src/modules/options/optw_highlighting.cpp | 2 +- src/modules/options/optw_highlighting.h | 2 +- src/modules/options/optw_identity.cpp | 16 +- src/modules/options/optw_identity.h | 4 +- src/modules/options/optw_ignore.cpp | 2 +- src/modules/options/optw_ignore.h | 4 +- src/modules/options/optw_input.cpp | 2 +- src/modules/options/optw_input.h | 2 +- src/modules/options/optw_interfacefeatures.cpp | 8 +- src/modules/options/optw_interfacefeatures.h | 2 +- src/modules/options/optw_interfacelookglobal.cpp | 4 +- src/modules/options/optw_interfacelookglobal.h | 4 +- src/modules/options/optw_irc.cpp | 2 +- src/modules/options/optw_irc.h | 2 +- src/modules/options/optw_ircoutput.cpp | 2 +- src/modules/options/optw_ircoutput.h | 2 +- src/modules/options/optw_ircview.cpp | 2 +- src/modules/options/optw_ircview.h | 2 +- src/modules/options/optw_lag.cpp | 2 +- src/modules/options/optw_lag.h | 2 +- src/modules/options/optw_logging.cpp | 2 +- src/modules/options/optw_logging.h | 2 +- src/modules/options/optw_mediatypes.cpp | 4 +- src/modules/options/optw_mediatypes.h | 2 +- src/modules/options/optw_messages.cpp | 16 +- src/modules/options/optw_messages.h | 2 +- src/modules/options/optw_nickserv.cpp | 4 +- src/modules/options/optw_nickserv.h | 2 +- src/modules/options/optw_notifier.cpp | 2 +- src/modules/options/optw_notifier.h | 2 +- src/modules/options/optw_notify.cpp | 2 +- src/modules/options/optw_notify.h | 2 +- src/modules/options/optw_protection.cpp | 2 +- src/modules/options/optw_protection.h | 4 +- src/modules/options/optw_proxy.cpp | 6 +- src/modules/options/optw_proxy.h | 2 +- src/modules/options/optw_query.cpp | 2 +- src/modules/options/optw_query.h | 2 +- src/modules/options/optw_servers.cpp | 34 +- src/modules/options/optw_servers.h | 2 +- src/modules/options/optw_sound.cpp | 6 +- src/modules/options/optw_sound.h | 2 +- src/modules/options/optw_textencoding.cpp | 6 +- src/modules/options/optw_textencoding.h | 2 +- src/modules/options/optw_texticons.cpp | 6 +- src/modules/options/optw_texticons.h | 4 +- src/modules/options/optw_tools.cpp | 2 +- src/modules/options/optw_tools.h | 4 +- src/modules/options/optw_topiclabel.cpp | 2 +- src/modules/options/optw_topiclabel.h | 2 +- src/modules/options/optw_tray.cpp | 6 +- src/modules/options/optw_tray.h | 2 +- src/modules/options/optw_uparser.cpp | 2 +- src/modules/options/optw_uparser.h | 2 +- src/modules/options/optw_urlhandlers.cpp | 2 +- src/modules/options/optw_urlhandlers.h | 2 +- src/modules/options/optw_userlist.cpp | 4 +- src/modules/options/optw_userlist.h | 2 +- src/modules/options/optw_windowlist.cpp | 2 +- src/modules/options/optw_windowlist.h | 2 +- src/modules/perl/libkviperl.cpp | 8 +- src/modules/perlcore/libkviperlcore.cpp | 14 +- src/modules/perlcore/perlcoreinterface.h | 2 +- src/modules/popup/libkvipopup.cpp | 4 +- src/modules/popupeditor/libkvipopupeditor.cpp | 4 +- src/modules/popupeditor/popupeditor.cpp | 20 +- src/modules/popupeditor/popupeditor.h | 4 +- src/modules/proxydb/libkviproxydb.cpp | 4 +- src/modules/python/libkvipython.cpp | 8 +- src/modules/pythoncore/kvircmodule.cpp | 10 +- src/modules/pythoncore/libkvipythoncore.cpp | 8 +- src/modules/pythoncore/pythoncoreinterface.h | 2 +- src/modules/raweditor/libkviraweditor.cpp | 4 +- src/modules/raweditor/raweditor.cpp | 20 +- src/modules/raweditor/raweditor.h | 6 +- src/modules/regchan/libkviregchan.cpp | 6 +- src/modules/reguser/dialog.cpp | 14 +- src/modules/reguser/dialog.h | 2 +- src/modules/reguser/edituser.cpp | 14 +- src/modules/reguser/edituser.h | 2 +- src/modules/reguser/libkvireguser.cpp | 14 +- src/modules/reguser/wizard.cpp | 6 +- src/modules/rijndael/libkvirijndael.cpp | 2 +- src/modules/rijndael/libkvirijndael_cryptopp.cpp | 2 +- src/modules/rot13/libkvirot13.cpp | 2 +- src/modules/serverdb/libkviserverdb.cpp | 4 +- src/modules/setup/libkvisetup.cpp | 20 +- src/modules/setup/setupwizard.cpp | 16 +- src/modules/setup/setupwizard.h | 2 +- src/modules/sharedfile/libkvisharedfile.cpp | 6 +- .../sharedfileswindow/libkvisharedfileswindow.cpp | 10 +- .../sharedfileswindow/sharedfileswindow.cpp | 14 +- src/modules/sharedfileswindow/sharedfileswindow.h | 10 +- src/modules/snd/libkvisnd.cpp | 4 +- src/modules/snd/libkvisnd.h | 2 +- src/modules/socketspy/libkvisocketspy.cpp | 6 +- src/modules/socketspy/socketspywindow.cpp | 12 +- src/modules/socketspy/socketspywindow.h | 6 +- src/modules/spaste/controller.cpp | 8 +- src/modules/spaste/controller.h | 2 +- src/modules/spaste/libkvispaste.cpp | 8 +- src/modules/spaste/libkvispaste.h | 2 +- src/modules/str/libkvistr.cpp | 6 +- src/modules/system/libkvisystem.cpp | 6 +- src/modules/system/plugin.cpp | 8 +- src/modules/system/plugin.h | 2 +- src/modules/term/libkviterm.cpp | 6 +- src/modules/term/termwidget.cpp | 8 +- src/modules/term/termwidget.h | 4 +- src/modules/term/termwindow.cpp | 8 +- src/modules/term/termwindow.h | 4 +- src/modules/texticons/libkvitexticons.cpp | 4 +- src/modules/theme/libkvitheme.cpp | 16 +- src/modules/theme/managementdialog.cpp | 22 +- src/modules/theme/managementdialog.h | 4 +- src/modules/theme/packthemedialog.cpp | 14 +- src/modules/theme/packthemedialog.h | 2 +- src/modules/theme/savethemedialog.cpp | 16 +- src/modules/theme/savethemedialog.h | 2 +- src/modules/theme/themefunctions.cpp | 14 +- src/modules/theme/themefunctions.h | 2 +- src/modules/tip/libkvitip.cpp | 12 +- src/modules/tmphighlight/libkvitmphighlight.cpp | 10 +- src/modules/toolbar/libkvitoolbar.cpp | 16 +- src/modules/toolbareditor/libkvitoolbareditor.cpp | 8 +- src/modules/toolbareditor/toolbareditor.cpp | 22 +- src/modules/torrent/libkvitorrent.cpp | 6 +- src/modules/torrent/tc_ktorrentdbusinterface.cpp | 2 +- src/modules/torrent/tc_statusbarapplet.cpp | 2 +- src/modules/torrent/tc_statusbarapplet.h | 4 +- src/modules/trayicon/libkvitrayicon.cpp | 28 +- src/modules/trayicon/libkvitrayicon.h | 10 +- src/modules/upnp/libkviupnp.cpp | 2 +- src/modules/upnp/rootservice.cpp | 4 +- src/modules/url/libkviurl.cpp | 36 +- src/modules/url/libkviurl.h | 8 +- src/modules/userlist/libkviuserlist.cpp | 12 +- src/modules/window/libkviwindow.cpp | 32 +- src/modules/window/userwindow.cpp | 12 +- src/modules/window/userwindow.h | 4 +- 1154 files changed, 131145 insertions(+), 131145 deletions(-) create mode 100644 src/kvirc/kernel/KviAction.cpp create mode 100644 src/kvirc/kernel/KviAction.h create mode 100644 src/kvirc/kernel/KviActionManager.cpp create mode 100644 src/kvirc/kernel/KviActionManager.h create mode 100644 src/kvirc/kernel/KviApplication.cpp create mode 100644 src/kvirc/kernel/KviApplication.h create mode 100644 src/kvirc/kernel/KviApplication_filesystem.cpp create mode 100644 src/kvirc/kernel/KviApplication_setup.cpp create mode 100644 src/kvirc/kernel/KviAsynchronousConnectionData.cpp create mode 100644 src/kvirc/kernel/KviAsynchronousConnectionData.h create mode 100644 src/kvirc/kernel/KviCoreActions.cpp create mode 100644 src/kvirc/kernel/KviCoreActions.h create mode 100644 src/kvirc/kernel/KviCustomToolBarDescriptor.cpp create mode 100644 src/kvirc/kernel/KviCustomToolBarDescriptor.h create mode 100644 src/kvirc/kernel/KviCustomToolBarManager.cpp create mode 100644 src/kvirc/kernel/KviCustomToolBarManager.h create mode 100644 src/kvirc/kernel/KviDefaultScript.cpp create mode 100644 src/kvirc/kernel/KviDefaultScript.h create mode 100644 src/kvirc/kernel/KviFileTransfer.cpp create mode 100644 src/kvirc/kernel/KviFileTransfer.h create mode 100644 src/kvirc/kernel/KviHtmlGenerator.cpp create mode 100644 src/kvirc/kernel/KviHtmlGenerator.h create mode 100644 src/kvirc/kernel/KviIconManager.cpp create mode 100644 src/kvirc/kernel/KviIconManager.h create mode 100644 src/kvirc/kernel/KviInternalCommand.cpp create mode 100644 src/kvirc/kernel/KviInternalCommand.h create mode 100644 src/kvirc/kernel/KviIpcSentinel.cpp create mode 100644 src/kvirc/kernel/KviIpcSentinel.h create mode 100644 src/kvirc/kernel/KviIrcConnection.cpp create mode 100644 src/kvirc/kernel/KviIrcConnection.h create mode 100644 src/kvirc/kernel/KviIrcConnectionAntiCtcpFloodData.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionAntiCtcpFloodData.h create mode 100644 src/kvirc/kernel/KviIrcConnectionAsyncData.h create mode 100644 src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.h create mode 100644 src/kvirc/kernel/KviIrcConnectionNetsplitDetectorData.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionNetsplitDetectorData.h create mode 100644 src/kvirc/kernel/KviIrcConnectionRequestQueue.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionRequestQueue.h create mode 100644 src/kvirc/kernel/KviIrcConnectionServerInfo.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionServerInfo.h create mode 100644 src/kvirc/kernel/KviIrcConnectionStateData.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionStateData.h create mode 100644 src/kvirc/kernel/KviIrcConnectionStatistics.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionStatistics.h create mode 100644 src/kvirc/kernel/KviIrcConnectionTarget.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionTarget.h create mode 100644 src/kvirc/kernel/KviIrcConnectionTargetResolver.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionTargetResolver.h create mode 100644 src/kvirc/kernel/KviIrcConnectionUserInfo.cpp create mode 100644 src/kvirc/kernel/KviIrcConnectionUserInfo.h create mode 100644 src/kvirc/kernel/KviIrcContext.cpp create mode 100644 src/kvirc/kernel/KviIrcContext.h create mode 100644 src/kvirc/kernel/KviIrcDataStreamMonitor.cpp create mode 100644 src/kvirc/kernel/KviIrcDataStreamMonitor.h create mode 100644 src/kvirc/kernel/KviIrcLink.cpp create mode 100644 src/kvirc/kernel/KviIrcLink.h create mode 100644 src/kvirc/kernel/KviIrcSocket.cpp create mode 100644 src/kvirc/kernel/KviIrcSocket.h create mode 100644 src/kvirc/kernel/KviIrcUrl.cpp create mode 100644 src/kvirc/kernel/KviIrcUrl.h create mode 100644 src/kvirc/kernel/KviLagMeter.cpp create mode 100644 src/kvirc/kernel/KviLagMeter.h create mode 100644 src/kvirc/kernel/KviMain.cpp create mode 100644 src/kvirc/kernel/KviNotifyList.cpp create mode 100644 src/kvirc/kernel/KviNotifyList.h create mode 100644 src/kvirc/kernel/KviOptions.cpp create mode 100644 src/kvirc/kernel/KviOptions.h create mode 100644 src/kvirc/kernel/KviSSLMaster.cpp create mode 100644 src/kvirc/kernel/KviSSLMaster.h create mode 100644 src/kvirc/kernel/KviTextIconManager.cpp create mode 100644 src/kvirc/kernel/KviTextIconManager.h create mode 100644 src/kvirc/kernel/KviTheme.cpp create mode 100644 src/kvirc/kernel/KviTheme.h create mode 100644 src/kvirc/kernel/KviUserAction.cpp create mode 100644 src/kvirc/kernel/KviUserAction.h create mode 100644 src/kvirc/kernel/KviUserInput.cpp create mode 100644 src/kvirc/kernel/KviUserInput.h delete mode 100644 src/kvirc/kernel/kvi_action.cpp delete mode 100644 src/kvirc/kernel/kvi_action.h delete mode 100644 src/kvirc/kernel/kvi_actionmanager.cpp delete mode 100644 src/kvirc/kernel/kvi_actionmanager.h delete mode 100644 src/kvirc/kernel/kvi_app.cpp delete mode 100644 src/kvirc/kernel/kvi_app.h delete mode 100644 src/kvirc/kernel/kvi_app_fs.cpp delete mode 100644 src/kvirc/kernel/kvi_app_setup.cpp delete mode 100644 src/kvirc/kernel/kvi_asynchronousconnectiondata.cpp delete mode 100644 src/kvirc/kernel/kvi_asynchronousconnectiondata.h delete mode 100644 src/kvirc/kernel/kvi_coreactions.cpp delete mode 100644 src/kvirc/kernel/kvi_coreactions.h delete mode 100644 src/kvirc/kernel/kvi_customtoolbardescriptor.cpp delete mode 100644 src/kvirc/kernel/kvi_customtoolbardescriptor.h delete mode 100644 src/kvirc/kernel/kvi_customtoolbarmanager.cpp delete mode 100644 src/kvirc/kernel/kvi_customtoolbarmanager.h delete mode 100644 src/kvirc/kernel/kvi_defaultscript.cpp delete mode 100644 src/kvirc/kernel/kvi_defaultscript.h delete mode 100644 src/kvirc/kernel/kvi_filetransfer.cpp delete mode 100644 src/kvirc/kernel/kvi_filetransfer.h delete mode 100644 src/kvirc/kernel/kvi_htmlgenerator.cpp delete mode 100644 src/kvirc/kernel/kvi_htmlgenerator.h delete mode 100644 src/kvirc/kernel/kvi_iconmanager.cpp delete mode 100644 src/kvirc/kernel/kvi_iconmanager.h delete mode 100644 src/kvirc/kernel/kvi_internalcmd.cpp delete mode 100644 src/kvirc/kernel/kvi_internalcmd.h delete mode 100644 src/kvirc/kernel/kvi_ipc.cpp delete mode 100644 src/kvirc/kernel/kvi_ipc.h delete mode 100644 src/kvirc/kernel/kvi_ircconnection.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnection.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionantictcpflooddata.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectionantictcpflooddata.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionasynctemplatedata.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionnetsplitdetectordata.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectionnetsplitdetectordata.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionrequestqueue.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectionrequestqueue.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionserverinfo.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectionserverinfo.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionstatedata.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectionstatedata.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionstatistics.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectionstatistics.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectiontarget.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectiontarget.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectiontargetresolver.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectiontargetresolver.h delete mode 100644 src/kvirc/kernel/kvi_ircconnectionuserinfo.cpp delete mode 100644 src/kvirc/kernel/kvi_ircconnectionuserinfo.h delete mode 100644 src/kvirc/kernel/kvi_irccontext.cpp delete mode 100644 src/kvirc/kernel/kvi_irccontext.h delete mode 100644 src/kvirc/kernel/kvi_ircdatastreammonitor.cpp delete mode 100644 src/kvirc/kernel/kvi_ircdatastreammonitor.h delete mode 100644 src/kvirc/kernel/kvi_irclink.cpp delete mode 100644 src/kvirc/kernel/kvi_irclink.h delete mode 100644 src/kvirc/kernel/kvi_ircsocket.cpp delete mode 100644 src/kvirc/kernel/kvi_ircsocket.h delete mode 100644 src/kvirc/kernel/kvi_ircurl.cpp delete mode 100644 src/kvirc/kernel/kvi_ircurl.h delete mode 100644 src/kvirc/kernel/kvi_lagmeter.cpp delete mode 100644 src/kvirc/kernel/kvi_lagmeter.h delete mode 100644 src/kvirc/kernel/kvi_main.cpp delete mode 100644 src/kvirc/kernel/kvi_notifylist.cpp delete mode 100644 src/kvirc/kernel/kvi_notifylist.h delete mode 100644 src/kvirc/kernel/kvi_options.cpp delete mode 100644 src/kvirc/kernel/kvi_options.h delete mode 100644 src/kvirc/kernel/kvi_sslmaster.cpp delete mode 100644 src/kvirc/kernel/kvi_sslmaster.h delete mode 100644 src/kvirc/kernel/kvi_texticonmanager.cpp delete mode 100644 src/kvirc/kernel/kvi_texticonmanager.h delete mode 100644 src/kvirc/kernel/kvi_theme.cpp delete mode 100644 src/kvirc/kernel/kvi_theme.h delete mode 100644 src/kvirc/kernel/kvi_useraction.cpp delete mode 100644 src/kvirc/kernel/kvi_useraction.h delete mode 100644 src/kvirc/kernel/kvi_userinput.cpp delete mode 100644 src/kvirc/kernel/kvi_userinput.h create mode 100644 src/kvirc/kvs/KviKvs.cpp create mode 100644 src/kvirc/kvs/KviKvs.h create mode 100644 src/kvirc/kvs/KviKvsAction.cpp create mode 100644 src/kvirc/kvs/KviKvsAction.h create mode 100644 src/kvirc/kvs/KviKvsAliasManager.cpp create mode 100644 src/kvirc/kvs/KviKvsAliasManager.h create mode 100644 src/kvirc/kvs/KviKvsArray.cpp create mode 100644 src/kvirc/kvs/KviKvsArray.h create mode 100644 src/kvirc/kvs/KviKvsArrayCast.cpp create mode 100644 src/kvirc/kvs/KviKvsArrayCast.h create mode 100644 src/kvirc/kvs/KviKvsAsyncDnsOperation.cpp create mode 100644 src/kvirc/kvs/KviKvsAsyncDnsOperation.h create mode 100644 src/kvirc/kvs/KviKvsAsyncOperation.cpp create mode 100644 src/kvirc/kvs/KviKvsAsyncOperation.h create mode 100644 src/kvirc/kvs/KviKvsCallbackObject.cpp create mode 100644 src/kvirc/kvs/KviKvsCallbackObject.h create mode 100644 src/kvirc/kvs/KviKvsCoreCallbackCommands.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreCallbackCommands.h create mode 100644 src/kvirc/kvs/KviKvsCoreFunctions.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreFunctions.h create mode 100644 src/kvirc/kvs/KviKvsCoreFunctions_af.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreFunctions_gl.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreFunctions_mr.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreFunctions_sz.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreSimpleCommands.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreSimpleCommands.h create mode 100644 src/kvirc/kvs/KviKvsCoreSimpleCommands_af.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreSimpleCommands_gl.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreSimpleCommands_mr.cpp create mode 100644 src/kvirc/kvs/KviKvsCoreSimpleCommands_sz.cpp create mode 100644 src/kvirc/kvs/KviKvsDnsManager.cpp create mode 100644 src/kvirc/kvs/KviKvsDnsManager.h create mode 100644 src/kvirc/kvs/KviKvsEvent.cpp create mode 100644 src/kvirc/kvs/KviKvsEvent.h create mode 100644 src/kvirc/kvs/KviKvsEventHandler.cpp create mode 100644 src/kvirc/kvs/KviKvsEventHandler.h create mode 100644 src/kvirc/kvs/KviKvsEventManager.cpp create mode 100644 src/kvirc/kvs/KviKvsEventManager.h create mode 100644 src/kvirc/kvs/KviKvsEventTable.cpp create mode 100644 src/kvirc/kvs/KviKvsEventTable.h create mode 100644 src/kvirc/kvs/KviKvsEventTriggers.h create mode 100644 src/kvirc/kvs/KviKvsHash.cpp create mode 100644 src/kvirc/kvs/KviKvsHash.h create mode 100644 src/kvirc/kvs/KviKvsKernel.cpp create mode 100644 src/kvirc/kvs/KviKvsKernel.h create mode 100644 src/kvirc/kvs/KviKvsModuleInterface.cpp create mode 100644 src/kvirc/kvs/KviKvsModuleInterface.h create mode 100644 src/kvirc/kvs/KviKvsObject.cpp create mode 100644 src/kvirc/kvs/KviKvsObject.h create mode 100644 src/kvirc/kvs/KviKvsObjectClass.cpp create mode 100644 src/kvirc/kvs/KviKvsObjectClass.h create mode 100644 src/kvirc/kvs/KviKvsObjectController.cpp create mode 100644 src/kvirc/kvs/KviKvsObjectController.h create mode 100644 src/kvirc/kvs/KviKvsObjectFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsObjectFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsObjectFunctionHandler.cpp create mode 100644 src/kvirc/kvs/KviKvsObjectFunctionHandler.h create mode 100644 src/kvirc/kvs/KviKvsObjectFunctionHandlerImpl.cpp create mode 100644 src/kvirc/kvs/KviKvsObjectFunctionHandlerImpl.h create mode 100644 src/kvirc/kvs/KviKvsParameterProcessor.cpp create mode 100644 src/kvirc/kvs/KviKvsParameterProcessor.h create mode 100644 src/kvirc/kvs/KviKvsParser.cpp create mode 100644 src/kvirc/kvs/KviKvsParser.h create mode 100644 src/kvirc/kvs/KviKvsParserMacros.h create mode 100644 src/kvirc/kvs/KviKvsParser_command.cpp create mode 100644 src/kvirc/kvs/KviKvsParser_comment.cpp create mode 100644 src/kvirc/kvs/KviKvsParser_dollar.cpp create mode 100644 src/kvirc/kvs/KviKvsParser_expression.cpp create mode 100644 src/kvirc/kvs/KviKvsParser_lside.cpp create mode 100644 src/kvirc/kvs/KviKvsParser_specialCommands.cpp create mode 100644 src/kvirc/kvs/KviKvsPopupManager.cpp create mode 100644 src/kvirc/kvs/KviKvsPopupManager.h create mode 100644 src/kvirc/kvs/KviKvsPopupMenu.cpp create mode 100644 src/kvirc/kvs/KviKvsPopupMenu.h create mode 100644 src/kvirc/kvs/KviKvsProcessManager.cpp create mode 100644 src/kvirc/kvs/KviKvsProcessManager.h create mode 100644 src/kvirc/kvs/KviKvsRWEvaluationResult.cpp create mode 100644 src/kvirc/kvs/KviKvsRWEvaluationResult.h create mode 100644 src/kvirc/kvs/KviKvsReport.cpp create mode 100644 src/kvirc/kvs/KviKvsReport.h create mode 100644 src/kvirc/kvs/KviKvsRunTimeCall.cpp create mode 100644 src/kvirc/kvs/KviKvsRunTimeCall.h create mode 100644 src/kvirc/kvs/KviKvsRunTimeContext.cpp create mode 100644 src/kvirc/kvs/KviKvsRunTimeContext.h create mode 100644 src/kvirc/kvs/KviKvsScript.cpp create mode 100644 src/kvirc/kvs/KviKvsScript.h create mode 100644 src/kvirc/kvs/KviKvsScriptAddonManager.cpp create mode 100644 src/kvirc/kvs/KviKvsScriptAddonManager.h create mode 100644 src/kvirc/kvs/KviKvsSwitchList.cpp create mode 100644 src/kvirc/kvs/KviKvsSwitchList.h create mode 100644 src/kvirc/kvs/KviKvsTimerManager.cpp create mode 100644 src/kvirc/kvs/KviKvsTimerManager.h create mode 100644 src/kvirc/kvs/KviKvsTreeNode.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeAliasFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeAliasFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeAliasSimpleCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeAliasSimpleCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeArrayCount.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeArrayCount.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeArrayElement.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeArrayElement.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeArrayOrHashElement.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeArrayOrHashElement.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeArrayReferenceAssert.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeArrayReferenceAssert.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeBase.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeBase.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeBaseObjectFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeBaseObjectFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCallbackCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCallbackCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCommandEvaluation.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCommandEvaluation.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCommandWithParameters.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCommandWithParameters.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCompositeData.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCompositeData.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeConstantData.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeConstantData.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCoreCallbackCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCoreCallbackCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCoreFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCoreFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCoreSimpleCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeCoreSimpleCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeData.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeData.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeDataList.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeDataList.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeExpression.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeExpression.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeExpressionReturn.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeExpressionReturn.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeExtendedScopeVariable.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeExtendedScopeVariable.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeGlobalVariable.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeGlobalVariable.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeHashCount.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeHashCount.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeHashElement.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeHashElement.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeHashReferenceAssert.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeHashReferenceAssert.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeIndirectData.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeIndirectData.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeInstruction.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeInstruction.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeInstructionBlock.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeInstructionBlock.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeLocalVariable.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeLocalVariable.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeModuleCallbackCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeModuleCallbackCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeModuleFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeModuleFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeModuleSimpleCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeModuleSimpleCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeMultipleParameterIdentifier.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeMultipleParameterIdentifier.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeObjectField.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeObjectField.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeObjectFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeObjectFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeOperation.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeOperation.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeParameterReturn.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeParameterReturn.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeRebindingSwitch.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeRebindingSwitch.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeScopeOperator.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeScopeOperator.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSimpleCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSimpleCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSingleParameterIdentifier.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSingleParameterIdentifier.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommand.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommand.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandBreak.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandBreak.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandClass.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandClass.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandContinue.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandContinue.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandDefpopup.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandDefpopup.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandDo.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandDo.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandFor.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandFor.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandForeach.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandForeach.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandIf.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandIf.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandSwitch.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandSwitch.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandUnset.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandUnset.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandWhile.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSpecialCommandWhile.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeStringCase.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeStringCase.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSwitchList.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeSwitchList.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeThisObjectFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeThisObjectFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeVariable.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeVariable.h create mode 100644 src/kvirc/kvs/KviKvsTreeNodeVoidFunctionCall.cpp create mode 100644 src/kvirc/kvs/KviKvsTreeNodeVoidFunctionCall.h create mode 100644 src/kvirc/kvs/KviKvsTypes.h create mode 100644 src/kvirc/kvs/KviKvsUserAction.cpp create mode 100644 src/kvirc/kvs/KviKvsUserAction.h create mode 100644 src/kvirc/kvs/KviKvsVariant.cpp create mode 100644 src/kvirc/kvs/KviKvsVariant.h create mode 100644 src/kvirc/kvs/KviKvsVariantList.cpp create mode 100644 src/kvirc/kvs/KviKvsVariantList.h delete mode 100644 src/kvirc/kvs/kvi_kvs.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs.h delete mode 100644 src/kvirc/kvs/kvi_kvs_action.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_action.h delete mode 100644 src/kvirc/kvs/kvi_kvs_aliasmanager.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_aliasmanager.h delete mode 100644 src/kvirc/kvs/kvi_kvs_array.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_array.h delete mode 100644 src/kvirc/kvs/kvi_kvs_arraycast.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_arraycast.h delete mode 100644 src/kvirc/kvs/kvi_kvs_asyncdnsoperation.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_asyncdnsoperation.h delete mode 100644 src/kvirc/kvs/kvi_kvs_asyncoperation.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_asyncoperation.h delete mode 100644 src/kvirc/kvs/kvi_kvs_callbackobject.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_callbackobject.h delete mode 100644 src/kvirc/kvs/kvi_kvs_corecallbackcommands.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_corecallbackcommands.h delete mode 100644 src/kvirc/kvs/kvi_kvs_corefunctions.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_corefunctions.h delete mode 100644 src/kvirc/kvs/kvi_kvs_corefunctions_af.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_corefunctions_gl.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_corefunctions_mr.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_corefunctions_sz.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_coresimplecommands.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_coresimplecommands.h delete mode 100644 src/kvirc/kvs/kvi_kvs_coresimplecommands_af.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_coresimplecommands_gl.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_coresimplecommands_mr.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_coresimplecommands_sz.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_dnsmanager.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_dnsmanager.h delete mode 100644 src/kvirc/kvs/kvi_kvs_event.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_event.h delete mode 100644 src/kvirc/kvs/kvi_kvs_eventhandler.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_eventhandler.h delete mode 100644 src/kvirc/kvs/kvi_kvs_eventmanager.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_eventmanager.h delete mode 100644 src/kvirc/kvs/kvi_kvs_eventtable.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_eventtable.h delete mode 100644 src/kvirc/kvs/kvi_kvs_eventtriggers.h delete mode 100644 src/kvirc/kvs/kvi_kvs_hash.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_hash.h delete mode 100644 src/kvirc/kvs/kvi_kvs_kernel.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_kernel.h delete mode 100644 src/kvirc/kvs/kvi_kvs_moduleinterface.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_moduleinterface.h delete mode 100644 src/kvirc/kvs/kvi_kvs_object.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_object.h delete mode 100644 src/kvirc/kvs/kvi_kvs_object_class.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_object_class.h delete mode 100644 src/kvirc/kvs/kvi_kvs_object_controller.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_object_controller.h delete mode 100644 src/kvirc/kvs/kvi_kvs_object_functioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_object_functioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_object_functionhandler.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_object_functionhandler.h delete mode 100644 src/kvirc/kvs/kvi_kvs_object_functionhandlerimpl.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_object_functionhandlerimpl.h delete mode 100644 src/kvirc/kvs/kvi_kvs_parameterprocessor.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_parameterprocessor.h delete mode 100644 src/kvirc/kvs/kvi_kvs_parser.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_parser.h delete mode 100644 src/kvirc/kvs/kvi_kvs_parser_command.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_parser_comment.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_parser_dollar.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_parser_expression.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_parser_lside.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_parser_macros.h delete mode 100644 src/kvirc/kvs/kvi_kvs_parser_specialcommands.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_popupmanager.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_popupmanager.h delete mode 100644 src/kvirc/kvs/kvi_kvs_popupmenu.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_popupmenu.h delete mode 100644 src/kvirc/kvs/kvi_kvs_processmanager.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_processmanager.h delete mode 100644 src/kvirc/kvs/kvi_kvs_report.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_report.h delete mode 100644 src/kvirc/kvs/kvi_kvs_runtimecall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_runtimecall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_runtimecontext.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_runtimecontext.h delete mode 100644 src/kvirc/kvs/kvi_kvs_rwevaluationresult.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_rwevaluationresult.h delete mode 100644 src/kvirc/kvs/kvi_kvs_script.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_script.h delete mode 100644 src/kvirc/kvs/kvi_kvs_scriptaddonmanager.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_scriptaddonmanager.h delete mode 100644 src/kvirc/kvs/kvi_kvs_switchlist.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_switchlist.h delete mode 100644 src/kvirc/kvs/kvi_kvs_timermanager.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_timermanager.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_aliasfunctioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_aliasfunctioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_aliassimplecommand.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_aliassimplecommand.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_arraycount.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_arraycount.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_arrayelement.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_arrayelement.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_arrayorhashelement.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_arrayorhashelement.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_arrayreferenceassert.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_arrayreferenceassert.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_base.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_base.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_baseobjectfunctioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_baseobjectfunctioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_callbackcommand.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_callbackcommand.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_command.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_command.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_commandevaluation.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_commandevaluation.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_commandwithparameters.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_commandwithparameters.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_compositedata.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_compositedata.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_constantdata.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_constantdata.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_corecallbackcommand.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_corecallbackcommand.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_corefunctioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_corefunctioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_coresimplecommand.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_coresimplecommand.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_data.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_data.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_datalist.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_datalist.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_expression.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_expression.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_expressionreturn.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_expressionreturn.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_extendedscopevariable.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_extendedscopevariable.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_functioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_functioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_globalvariable.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_globalvariable.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_hashcount.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_hashcount.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_hashelement.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_hashelement.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_hashreferenceassert.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_hashreferenceassert.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_indirectdata.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_indirectdata.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_instruction.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_instruction.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_instructionblock.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_instructionblock.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_localvariable.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_localvariable.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_modulecallbackcommand.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_modulecallbackcommand.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_modulefunctioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_modulefunctioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_modulesimplecommand.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_modulesimplecommand.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_multipleparameteridentifier.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_multipleparameteridentifier.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_objectfield.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_objectfield.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_objectfunctioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_objectfunctioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_operation.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_operation.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_parameterreturn.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_parameterreturn.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_rebindingswitch.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_rebindingswitch.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_scopeoperator.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_scopeoperator.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_simplecommand.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_simplecommand.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_singleparameteridentifier.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_singleparameteridentifier.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommand.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommand.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandbreak.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandbreak.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandclass.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandclass.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandcontinue.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandcontinue.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommanddefpopup.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommanddefpopup.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommanddo.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommanddo.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandfor.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandfor.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandforeach.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandforeach.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandif.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandif.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandswitch.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandswitch.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandunset.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandunset.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandwhile.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_specialcommandwhile.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_stringcast.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_stringcast.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_switchlist.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_switchlist.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_thisobjectfunctioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_thisobjectfunctioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_variable.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_variable.h delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_voidfunctioncall.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_treenode_voidfunctioncall.h delete mode 100644 src/kvirc/kvs/kvi_kvs_types.h delete mode 100644 src/kvirc/kvs/kvi_kvs_useraction.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_useraction.h delete mode 100644 src/kvirc/kvs/kvi_kvs_variant.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_variant.h delete mode 100644 src/kvirc/kvs/kvi_kvs_variantlist.cpp delete mode 100644 src/kvirc/kvs/kvi_kvs_variantlist.h create mode 100644 src/kvirc/module/KviMexLinkFilter.cpp create mode 100644 src/kvirc/module/KviMexLinkFilter.h create mode 100644 src/kvirc/module/KviMexServerImport.cpp create mode 100644 src/kvirc/module/KviMexServerImport.h create mode 100644 src/kvirc/module/KviMexToolBar.cpp create mode 100644 src/kvirc/module/KviMexToolBar.h create mode 100644 src/kvirc/module/KviModule.cpp create mode 100644 src/kvirc/module/KviModule.h create mode 100644 src/kvirc/module/KviModuleExtension.cpp create mode 100644 src/kvirc/module/KviModuleExtension.h create mode 100644 src/kvirc/module/KviModuleManager.cpp create mode 100644 src/kvirc/module/KviModuleManager.h delete mode 100644 src/kvirc/module/kvi_mexlinkfilter.cpp delete mode 100644 src/kvirc/module/kvi_mexlinkfilter.h delete mode 100644 src/kvirc/module/kvi_mexserverimport.cpp delete mode 100644 src/kvirc/module/kvi_mexserverimport.h delete mode 100644 src/kvirc/module/kvi_mextoolbar.cpp delete mode 100644 src/kvirc/module/kvi_mextoolbar.h delete mode 100644 src/kvirc/module/kvi_module.cpp delete mode 100644 src/kvirc/module/kvi_module.h delete mode 100644 src/kvirc/module/kvi_moduleextension.cpp delete mode 100644 src/kvirc/module/kvi_moduleextension.h delete mode 100644 src/kvirc/module/kvi_modulemanager.cpp delete mode 100644 src/kvirc/module/kvi_modulemanager.h create mode 100644 src/kvirc/sparser/KviAntiSpam.cpp create mode 100644 src/kvirc/sparser/KviAntiSpam.h create mode 100644 src/kvirc/sparser/KviIrcMessage.cpp create mode 100644 src/kvirc/sparser/KviIrcMessage.h create mode 100644 src/kvirc/sparser/KviIrcNumericCodes.h create mode 100644 src/kvirc/sparser/KviIrcServerParser.cpp create mode 100644 src/kvirc/sparser/KviIrcServerParser.h create mode 100644 src/kvirc/sparser/KviIrcServerParser_ctcp.cpp create mode 100644 src/kvirc/sparser/KviIrcServerParser_literalHandlers.cpp create mode 100644 src/kvirc/sparser/KviIrcServerParser_numericHandlers.cpp create mode 100644 src/kvirc/sparser/KviIrcServerParser_tables.cpp delete mode 100644 src/kvirc/sparser/kvi_antispam.cpp delete mode 100644 src/kvirc/sparser/kvi_antispam.h delete mode 100644 src/kvirc/sparser/kvi_ircmessage.cpp delete mode 100644 src/kvirc/sparser/kvi_ircmessage.h delete mode 100644 src/kvirc/sparser/kvi_numeric.h delete mode 100644 src/kvirc/sparser/kvi_sp_ctcp.cpp delete mode 100644 src/kvirc/sparser/kvi_sp_literal.cpp delete mode 100644 src/kvirc/sparser/kvi_sp_numeric.cpp delete mode 100644 src/kvirc/sparser/kvi_sp_tables.cpp delete mode 100644 src/kvirc/sparser/kvi_sparser.cpp delete mode 100644 src/kvirc/sparser/kvi_sparser.h create mode 100644 src/kvirc/ui/KviActionDrawer.cpp create mode 100644 src/kvirc/ui/KviActionDrawer.h create mode 100644 src/kvirc/ui/KviChannelWindow.cpp create mode 100644 src/kvirc/ui/KviChannelWindow.h create mode 100644 src/kvirc/ui/KviColorSelectionWindow.cpp create mode 100644 src/kvirc/ui/KviColorSelectionWindow.h create mode 100644 src/kvirc/ui/KviConsoleWindow.cpp create mode 100644 src/kvirc/ui/KviConsoleWindow.h create mode 100644 src/kvirc/ui/KviCryptController.cpp create mode 100644 src/kvirc/ui/KviCryptController.h create mode 100644 src/kvirc/ui/KviCtcpPageDialog.cpp create mode 100644 src/kvirc/ui/KviCtcpPageDialog.h create mode 100644 src/kvirc/ui/KviCustomToolBar.cpp create mode 100644 src/kvirc/ui/KviCustomToolBar.h create mode 100644 src/kvirc/ui/KviDebugWindow.cpp create mode 100644 src/kvirc/ui/KviDebugWindow.h create mode 100644 src/kvirc/ui/KviDynamicToolTip.cpp create mode 100644 src/kvirc/ui/KviDynamicToolTip.h create mode 100644 src/kvirc/ui/KviFileDialog.cpp create mode 100644 src/kvirc/ui/KviFileDialog.h create mode 100644 src/kvirc/ui/KviHistoryWindow.cpp create mode 100644 src/kvirc/ui/KviHistoryWindow.h create mode 100644 src/kvirc/ui/KviHtmlDialog.cpp create mode 100644 src/kvirc/ui/KviHtmlDialog.h create mode 100644 src/kvirc/ui/KviImageDialog.cpp create mode 100644 src/kvirc/ui/KviImageDialog.h create mode 100644 src/kvirc/ui/KviInput.cpp create mode 100644 src/kvirc/ui/KviInput.h create mode 100644 src/kvirc/ui/KviInputEditor.cpp create mode 100644 src/kvirc/ui/KviInputEditor.h create mode 100644 src/kvirc/ui/KviInputHistory.cpp create mode 100644 src/kvirc/ui/KviInputHistory.h create mode 100644 src/kvirc/ui/KviIpEditor.cpp create mode 100644 src/kvirc/ui/KviIpEditor.h create mode 100644 src/kvirc/ui/KviIrcToolBar.cpp create mode 100644 src/kvirc/ui/KviIrcToolBar.h create mode 100644 src/kvirc/ui/KviIrcView.cpp create mode 100644 src/kvirc/ui/KviIrcView.h create mode 100644 src/kvirc/ui/KviIrcView_events.cpp create mode 100644 src/kvirc/ui/KviIrcView_getTextLine.cpp create mode 100644 src/kvirc/ui/KviIrcView_loghandling.cpp create mode 100644 src/kvirc/ui/KviIrcView_private.h create mode 100644 src/kvirc/ui/KviIrcView_tools.cpp create mode 100644 src/kvirc/ui/KviIrcView_tools.h create mode 100644 src/kvirc/ui/KviMainWindow.cpp create mode 100644 src/kvirc/ui/KviMainWindow.h create mode 100644 src/kvirc/ui/KviMaskEditor.cpp create mode 100644 src/kvirc/ui/KviMaskEditor.h create mode 100644 src/kvirc/ui/KviMdiChild.cpp create mode 100644 src/kvirc/ui/KviMdiChild.h create mode 100644 src/kvirc/ui/KviMdiManager.cpp create mode 100644 src/kvirc/ui/KviMdiManager.h create mode 100644 src/kvirc/ui/KviMenuBar.cpp create mode 100644 src/kvirc/ui/KviMenuBar.h create mode 100644 src/kvirc/ui/KviMessageBox.cpp create mode 100644 src/kvirc/ui/KviMessageBox.h create mode 100644 src/kvirc/ui/KviModeEditor.cpp create mode 100644 src/kvirc/ui/KviModeEditor.h create mode 100644 src/kvirc/ui/KviModeWidget.cpp create mode 100644 src/kvirc/ui/KviModeWidget.h create mode 100644 src/kvirc/ui/KviOptionsWidget.cpp create mode 100644 src/kvirc/ui/KviOptionsWidget.h create mode 100644 src/kvirc/ui/KviQueryWindow.cpp create mode 100644 src/kvirc/ui/KviQueryWindow.h create mode 100644 src/kvirc/ui/KviScriptButton.cpp create mode 100644 src/kvirc/ui/KviScriptButton.h create mode 100644 src/kvirc/ui/KviScriptEditor.cpp create mode 100644 src/kvirc/ui/KviScriptEditor.h create mode 100644 src/kvirc/ui/KviSelectors.cpp create mode 100644 src/kvirc/ui/KviSelectors.h create mode 100644 src/kvirc/ui/KviSplashScreen.cpp create mode 100644 src/kvirc/ui/KviSplashScreen.h create mode 100644 src/kvirc/ui/KviStatusBar.cpp create mode 100644 src/kvirc/ui/KviStatusBar.h create mode 100644 src/kvirc/ui/KviStatusBarApplet.cpp create mode 100644 src/kvirc/ui/KviStatusBarApplet.h create mode 100644 src/kvirc/ui/KviTextIconWindow.cpp create mode 100644 src/kvirc/ui/KviTextIconWindow.h create mode 100644 src/kvirc/ui/KviThemedComboBox.cpp create mode 100644 src/kvirc/ui/KviThemedComboBox.h create mode 100644 src/kvirc/ui/KviThemedLabel.cpp create mode 100644 src/kvirc/ui/KviThemedLabel.h create mode 100644 src/kvirc/ui/KviThemedLineEdit.cpp create mode 100644 src/kvirc/ui/KviThemedLineEdit.h create mode 100644 src/kvirc/ui/KviThemedTreeWidget.cpp create mode 100644 src/kvirc/ui/KviThemedTreeWidget.h create mode 100644 src/kvirc/ui/KviToolBar.cpp create mode 100644 src/kvirc/ui/KviToolBar.h create mode 100644 src/kvirc/ui/KviTopicWidget.cpp create mode 100644 src/kvirc/ui/KviTopicWidget.h create mode 100644 src/kvirc/ui/KviTreeWindowList.cpp create mode 100644 src/kvirc/ui/KviTreeWindowList.h create mode 100644 src/kvirc/ui/KviUserListView.cpp create mode 100644 src/kvirc/ui/KviUserListView.h create mode 100644 src/kvirc/ui/KviWindow.cpp create mode 100644 src/kvirc/ui/KviWindow.h create mode 100644 src/kvirc/ui/KviWindowListBase.cpp create mode 100644 src/kvirc/ui/KviWindowListBase.h create mode 100644 src/kvirc/ui/KviWindowToolWidget.cpp create mode 100644 src/kvirc/ui/KviWindowToolWidget.h delete mode 100644 src/kvirc/ui/kvi_actiondrawer.cpp delete mode 100644 src/kvirc/ui/kvi_actiondrawer.h delete mode 100644 src/kvirc/ui/kvi_channel.cpp delete mode 100644 src/kvirc/ui/kvi_channel.h delete mode 100644 src/kvirc/ui/kvi_colorwin.cpp delete mode 100644 src/kvirc/ui/kvi_colorwin.h delete mode 100644 src/kvirc/ui/kvi_console.cpp delete mode 100644 src/kvirc/ui/kvi_console.h delete mode 100644 src/kvirc/ui/kvi_cryptcontroller.cpp delete mode 100644 src/kvirc/ui/kvi_cryptcontroller.h delete mode 100644 src/kvirc/ui/kvi_ctcppagedialog.cpp delete mode 100644 src/kvirc/ui/kvi_ctcppagedialog.h delete mode 100644 src/kvirc/ui/kvi_customtoolbar.cpp delete mode 100644 src/kvirc/ui/kvi_customtoolbar.h delete mode 100644 src/kvirc/ui/kvi_debugwindow.cpp delete mode 100644 src/kvirc/ui/kvi_debugwindow.h delete mode 100644 src/kvirc/ui/kvi_dynamictooltip.cpp delete mode 100644 src/kvirc/ui/kvi_dynamictooltip.h delete mode 100644 src/kvirc/ui/kvi_filedialog.cpp delete mode 100644 src/kvirc/ui/kvi_filedialog.h delete mode 100644 src/kvirc/ui/kvi_frame.cpp delete mode 100644 src/kvirc/ui/kvi_frame.h delete mode 100644 src/kvirc/ui/kvi_historywin.cpp delete mode 100644 src/kvirc/ui/kvi_historywin.h delete mode 100644 src/kvirc/ui/kvi_htmldialog.cpp delete mode 100644 src/kvirc/ui/kvi_htmldialog.h delete mode 100644 src/kvirc/ui/kvi_imagedialog.cpp delete mode 100644 src/kvirc/ui/kvi_imagedialog.h delete mode 100644 src/kvirc/ui/kvi_input.cpp delete mode 100644 src/kvirc/ui/kvi_input.h delete mode 100644 src/kvirc/ui/kvi_input_editor.cpp delete mode 100644 src/kvirc/ui/kvi_input_editor.h delete mode 100644 src/kvirc/ui/kvi_input_history.cpp delete mode 100644 src/kvirc/ui/kvi_input_history.h delete mode 100644 src/kvirc/ui/kvi_ipeditor.cpp delete mode 100644 src/kvirc/ui/kvi_ipeditor.h delete mode 100644 src/kvirc/ui/kvi_irctoolbar.cpp delete mode 100644 src/kvirc/ui/kvi_irctoolbar.h delete mode 100644 src/kvirc/ui/kvi_ircview.cpp delete mode 100644 src/kvirc/ui/kvi_ircview.h delete mode 100644 src/kvirc/ui/kvi_ircview_events.cpp delete mode 100644 src/kvirc/ui/kvi_ircview_gettextline.cpp delete mode 100644 src/kvirc/ui/kvi_ircview_loghandling.cpp delete mode 100644 src/kvirc/ui/kvi_ircviewprivate.h delete mode 100644 src/kvirc/ui/kvi_ircviewtools.cpp delete mode 100644 src/kvirc/ui/kvi_ircviewtools.h delete mode 100644 src/kvirc/ui/kvi_maskeditor.cpp delete mode 100644 src/kvirc/ui/kvi_maskeditor.h delete mode 100644 src/kvirc/ui/kvi_mdichild.cpp delete mode 100644 src/kvirc/ui/kvi_mdichild.h delete mode 100644 src/kvirc/ui/kvi_mdimanager.cpp delete mode 100644 src/kvirc/ui/kvi_mdimanager.h delete mode 100644 src/kvirc/ui/kvi_menubar.cpp delete mode 100644 src/kvirc/ui/kvi_menubar.h delete mode 100644 src/kvirc/ui/kvi_modeeditor.cpp delete mode 100644 src/kvirc/ui/kvi_modeeditor.h delete mode 100644 src/kvirc/ui/kvi_modew.cpp delete mode 100644 src/kvirc/ui/kvi_modew.h delete mode 100644 src/kvirc/ui/kvi_msgbox.cpp delete mode 100644 src/kvirc/ui/kvi_msgbox.h delete mode 100644 src/kvirc/ui/kvi_optionswidget.cpp delete mode 100644 src/kvirc/ui/kvi_optionswidget.h delete mode 100644 src/kvirc/ui/kvi_query.cpp delete mode 100644 src/kvirc/ui/kvi_query.h delete mode 100644 src/kvirc/ui/kvi_scriptbutton.cpp delete mode 100644 src/kvirc/ui/kvi_scriptbutton.h delete mode 100644 src/kvirc/ui/kvi_scripteditor.cpp delete mode 100644 src/kvirc/ui/kvi_scripteditor.h delete mode 100644 src/kvirc/ui/kvi_selectors.cpp delete mode 100644 src/kvirc/ui/kvi_selectors.h delete mode 100644 src/kvirc/ui/kvi_splash.cpp delete mode 100644 src/kvirc/ui/kvi_splash.h delete mode 100644 src/kvirc/ui/kvi_statusbar.cpp delete mode 100644 src/kvirc/ui/kvi_statusbar.h delete mode 100644 src/kvirc/ui/kvi_statusbarapplet.cpp delete mode 100644 src/kvirc/ui/kvi_statusbarapplet.h delete mode 100644 src/kvirc/ui/kvi_texticonwin.cpp delete mode 100644 src/kvirc/ui/kvi_texticonwin.h delete mode 100644 src/kvirc/ui/kvi_themedcombobox.cpp delete mode 100644 src/kvirc/ui/kvi_themedcombobox.h delete mode 100644 src/kvirc/ui/kvi_themedlabel.cpp delete mode 100644 src/kvirc/ui/kvi_themedlabel.h delete mode 100644 src/kvirc/ui/kvi_themedlineedit.cpp delete mode 100644 src/kvirc/ui/kvi_themedlineedit.h delete mode 100644 src/kvirc/ui/kvi_themedtreewidget.cpp delete mode 100644 src/kvirc/ui/kvi_themedtreewidget.h delete mode 100644 src/kvirc/ui/kvi_toolbar.cpp delete mode 100644 src/kvirc/ui/kvi_toolbar.h delete mode 100644 src/kvirc/ui/kvi_toolwindows_container.cpp delete mode 100644 src/kvirc/ui/kvi_toolwindows_container.h delete mode 100644 src/kvirc/ui/kvi_topicw.cpp delete mode 100644 src/kvirc/ui/kvi_topicw.h delete mode 100644 src/kvirc/ui/kvi_userlistview.cpp delete mode 100644 src/kvirc/ui/kvi_userlistview.h delete mode 100644 src/kvirc/ui/kvi_window.cpp delete mode 100644 src/kvirc/ui/kvi_window.h delete mode 100644 src/kvirc/ui/kvi_windowlist.cpp delete mode 100644 src/kvirc/ui/kvi_windowlist.h delete mode 100644 src/kvirc/ui/kvi_windowlist_tree.cpp delete mode 100644 src/kvirc/ui/kvi_windowlist_tree.h diff --git a/src/kvilib/core/KviCString.h b/src/kvilib/core/KviCString.h index ccc114e5b..f4ad4184c 100644 --- a/src/kvilib/core/KviCString.h +++ b/src/kvilib/core/KviCString.h @@ -173,7 +173,7 @@ public: int len() const { return m_len; }; // I hate this operator...but sometimes it is really useful - // especially in macros (kvi_options.cpp) + // especially in macros (KviOptions.cpp) operator const char * () const { return m_ptr; }; bool isEmpty() const { return (m_len == 0); }; diff --git a/src/kvilib/core/kvi_hstrEqualCIN.cpp b/src/kvilib/core/kvi_hstrEqualCIN.cpp index db34d3d5b..a746a40fa 100644 --- a/src/kvilib/core/kvi_hstrEqualCIN.cpp +++ b/src/kvilib/core/kvi_hstrEqualCIN.cpp @@ -22,7 +22,7 @@ // //=========================================================================== // -// This file was originally part of kvi_ircview.cpp +// This file was originally part of KviIrcView.cpp // //=========================================================================== diff --git a/src/kvilib/core/kvi_hstrEqualCIN.h b/src/kvilib/core/kvi_hstrEqualCIN.h index 516b3a3a6..1cb803ad3 100644 --- a/src/kvilib/core/kvi_hstrEqualCIN.h +++ b/src/kvilib/core/kvi_hstrEqualCIN.h @@ -22,7 +22,7 @@ // //=========================================================================== // -// This file was originally part of kvi_ircview.h +// This file was originally part of KviIrcView.h // //=========================================================================== diff --git a/src/kvilib/irc/KviIrcServerDataBase.h b/src/kvilib/irc/KviIrcServerDataBase.h index a2c2d04dd..cd2b2e27f 100644 --- a/src/kvilib/irc/KviIrcServerDataBase.h +++ b/src/kvilib/irc/KviIrcServerDataBase.h @@ -94,7 +94,7 @@ public: /** * \brief Returns a list of servers to connect on startup * This list is computed when the data are loaded from disk during the startup - * and is used by KviApp to start the connections. + * and is used by KviApplication to start the connections. * The pointer is zero if there are no autoConnect servers. The list is valid * only during the startup phase because it contains shallow pointers to the * servers really contained in the server/network list and it is never updated @@ -106,7 +106,7 @@ public: /** * \brief Returns a list of networks to connect on startup * This list is computed when the data are loaded from disk during the startup - * and is used by KviApp to start the connections. + * and is used by KviApplication to start the connections. * The pointer is zero if there are no autoConnect networks. The list is valid * only during the startup phase because it contains shallow pointers to the * networks really contained in the server/network list and it is never diff --git a/src/kvilib/system/KviThread.h b/src/kvilib/system/KviThread.h index cfb13ade0..9b6feaf31 100644 --- a/src/kvilib/system/KviThread.h +++ b/src/kvilib/system/KviThread.h @@ -325,7 +325,7 @@ protected: }; // =============================================================================================// -// This is private stuff...only KviThread and KviApp may use it +// This is private stuff...only KviThread and KviApplication may use it // and may call only specific functions...don't touch. typedef struct _KviThreadPendingEvent @@ -336,7 +336,7 @@ typedef struct _KviThreadPendingEvent class KVILIB_API KviThreadManager : public QObject { - friend class KviApp; + friend class KviApplication; friend class KviThread; Q_OBJECT protected: @@ -368,7 +368,7 @@ protected: void postSlaveEvent(QObject *o,QEvent *e); void killPendingEventsByReceiver(QObject * receiver); - // Public to KviApp only + // Public to KviApplication only static void globalInit(); static void globalDestroy(); private slots: diff --git a/src/kvirc/CMakeLists.txt b/src/kvirc/CMakeLists.txt index bd1858d8d..251327c0c 100644 --- a/src/kvirc/CMakeLists.txt +++ b/src/kvirc/CMakeLists.txt @@ -17,308 +17,308 @@ INCLUDE_DIRECTORIES( ) SET(kvirc_MOC_HDRS - ui/kvi_actiondrawer.h - ui/kvi_channel.h - ui/kvi_colorwin.h - ui/kvi_console.h - ui/kvi_cryptcontroller.h - ui/kvi_ctcppagedialog.h - ui/kvi_customtoolbar.h - ui/kvi_debugwindow.h - ui/kvi_dynamictooltip.h - ui/kvi_filedialog.h - ui/kvi_frame.h - ui/kvi_historywin.h - ui/kvi_htmldialog.h - ui/kvi_imagedialog.h - ui/kvi_input.h - ui/kvi_input_editor.h - ui/kvi_ipeditor.h - ui/kvi_irctoolbar.h - ui/kvi_ircview.h - ui/kvi_ircviewtools.h - ui/kvi_maskeditor.h - ui/kvi_mdichild.h - ui/kvi_mdimanager.h - ui/kvi_menubar.h - ui/kvi_modeeditor.h - ui/kvi_modew.h - ui/kvi_optionswidget.h - ui/kvi_query.h - ui/kvi_scriptbutton.h - ui/kvi_scripteditor.h - ui/kvi_selectors.h - ui/kvi_splash.h - ui/kvi_statusbar.h - ui/kvi_statusbarapplet.h - ui/kvi_texticonwin.h - ui/kvi_themedcombobox.h - ui/kvi_themedlabel.h - ui/kvi_themedlineedit.h - ui/kvi_themedtreewidget.h - ui/kvi_toolbar.h - ui/kvi_toolwindows_container.h - ui/kvi_topicw.h - ui/kvi_userlistview.h - ui/kvi_window.h - ui/kvi_windowlist.h - ui/kvi_windowlist_tree.h - sparser/kvi_sparser.h - module/kvi_mexlinkfilter.h - module/kvi_mexserverimport.h - module/kvi_mextoolbar.h - module/kvi_modulemanager.h - kvs/kvi_kvs_action.h - kvs/kvi_kvs_aliasmanager.h - kvs/kvi_kvs_asyncdnsoperation.h - kvs/kvi_kvs_asyncoperation.h - kvs/kvi_kvs_dnsmanager.h - kvs/kvi_kvs_eventmanager.h - kvs/kvi_kvs_object.h - kvs/kvi_kvs_popupmenu.h - kvs/kvi_kvs_popupmanager.h - kvs/kvi_kvs_processmanager.h - kvs/kvi_kvs_timermanager.h - kvs/kvi_kvs_useraction.h - kernel/kvi_action.h - kernel/kvi_actionmanager.h - kernel/kvi_app.h - kernel/kvi_coreactions.h - kernel/kvi_defaultscript.h - kernel/kvi_filetransfer.h - kernel/kvi_iconmanager.h - kernel/kvi_ipc.h - kernel/kvi_ircconnection.h - kernel/kvi_ircconnectionrequestqueue.h - kernel/kvi_ircconnectiontargetresolver.h - kernel/kvi_irccontext.h - kernel/kvi_irclink.h - kernel/kvi_ircsocket.h - kernel/kvi_lagmeter.h - kernel/kvi_notifylist.h - kernel/kvi_texticonmanager.h + ui/KviActionDrawer.h + ui/KviChannelWindow.h + ui/KviColorSelectionWindow.h + ui/KviConsoleWindow.h + ui/KviCryptController.h + ui/KviCtcpPageDialog.h + ui/KviCustomToolBar.h + ui/KviDebugWindow.h + ui/KviDynamicToolTip.h + ui/KviFileDialog.h + ui/KviMainWindow.h + ui/KviHistoryWindow.h + ui/KviHtmlDialog.h + ui/KviImageDialog.h + ui/KviInput.h + ui/KviInputEditor.h + ui/KviIpEditor.h + ui/KviIrcToolBar.h + ui/KviIrcView.h + ui/KviIrcView_tools.h + ui/KviMaskEditor.h + ui/KviMdiChild.h + ui/KviMdiManager.h + ui/KviMenuBar.h + ui/KviModeEditor.h + ui/KviModeWidget.h + ui/KviOptionsWidget.h + ui/KviQueryWindow.h + ui/KviScriptButton.h + ui/KviScriptEditor.h + ui/KviSelectors.h + ui/KviSplashScreen.h + ui/KviStatusBar.h + ui/KviStatusBarApplet.h + ui/KviTextIconWindow.h + ui/KviThemedComboBox.h + ui/KviThemedLabel.h + ui/KviThemedLineEdit.h + ui/KviThemedTreeWidget.h + ui/KviToolBar.h + ui/KviWindowToolWidget.h + ui/KviTopicWidget.h + ui/KviUserListView.h + ui/KviWindow.h + ui/KviWindowListBase.h + ui/KviTreeWindowList.h + sparser/KviIrcServerParser.h + module/KviMexLinkFilter.h + module/KviMexServerImport.h + module/KviMexToolBar.h + module/KviModuleManager.h + kvs/KviKvsAction.h + kvs/KviKvsAliasManager.h + kvs/KviKvsAsyncDnsOperation.h + kvs/KviKvsAsyncOperation.h + kvs/KviKvsDnsManager.h + kvs/KviKvsEventManager.h + kvs/KviKvsObject.h + kvs/KviKvsPopupMenu.h + kvs/KviKvsPopupManager.h + kvs/KviKvsProcessManager.h + kvs/KviKvsTimerManager.h + kvs/KviKvsUserAction.h + kernel/KviAction.h + kernel/KviActionManager.h + kernel/KviApplication.h + kernel/KviCoreActions.h + kernel/KviDefaultScript.h + kernel/KviFileTransfer.h + kernel/KviIconManager.h + kernel/KviIpcSentinel.h + kernel/KviIrcConnection.h + kernel/KviIrcConnectionRequestQueue.h + kernel/KviIrcConnectionTargetResolver.h + kernel/KviIrcContext.h + kernel/KviIrcLink.h + kernel/KviIrcSocket.h + kernel/KviLagMeter.h + kernel/KviNotifyList.h + kernel/KviTextIconManager.h ) SET(kvirc_SRCS - ui/kvi_actiondrawer.cpp - ui/kvi_channel.cpp - ui/kvi_colorwin.cpp - ui/kvi_console.cpp - ui/kvi_cryptcontroller.cpp - ui/kvi_ctcppagedialog.cpp - ui/kvi_customtoolbar.cpp - ui/kvi_debugwindow.cpp - ui/kvi_dynamictooltip.cpp - ui/kvi_filedialog.cpp - ui/kvi_frame.cpp - ui/kvi_historywin.cpp - ui/kvi_htmldialog.cpp - ui/kvi_imagedialog.cpp - ui/kvi_input.cpp - ui/kvi_input_editor.cpp - ui/kvi_input_history.cpp - ui/kvi_ipeditor.cpp - ui/kvi_irctoolbar.cpp - ui/kvi_ircview.cpp - ui/kvi_ircview_events.cpp - ui/kvi_ircview_gettextline.cpp - ui/kvi_ircview_loghandling.cpp - ui/kvi_ircviewtools.cpp - ui/kvi_maskeditor.cpp - ui/kvi_mdichild.cpp - ui/kvi_mdimanager.cpp - ui/kvi_menubar.cpp - ui/kvi_modeeditor.cpp - ui/kvi_modew.cpp - ui/kvi_msgbox.cpp - ui/kvi_optionswidget.cpp - ui/kvi_query.cpp - ui/kvi_scriptbutton.cpp - ui/kvi_scripteditor.cpp - ui/kvi_selectors.cpp - ui/kvi_splash.cpp - ui/kvi_statusbar.cpp - ui/kvi_statusbarapplet.cpp - ui/kvi_texticonwin.cpp - ui/kvi_themedcombobox.cpp - ui/kvi_themedlabel.cpp - ui/kvi_themedlineedit.cpp - ui/kvi_themedtreewidget.cpp - ui/kvi_toolbar.cpp - ui/kvi_toolwindows_container.cpp - ui/kvi_topicw.cpp - ui/kvi_userlistview.cpp - ui/kvi_window.cpp - ui/kvi_windowlist.cpp - ui/kvi_windowlist_tree.cpp - sparser/kvi_antispam.cpp - sparser/kvi_ircmessage.cpp - sparser/kvi_sp_ctcp.cpp - sparser/kvi_sp_literal.cpp - sparser/kvi_sp_numeric.cpp - sparser/kvi_sp_tables.cpp - sparser/kvi_sparser.cpp - module/kvi_mexlinkfilter.cpp - module/kvi_mexserverimport.cpp - module/kvi_mextoolbar.cpp - module/kvi_module.cpp - module/kvi_moduleextension.cpp - module/kvi_modulemanager.cpp - kvs/kvi_kvs.cpp - kvs/kvi_kvs_action.cpp - kvs/kvi_kvs_aliasmanager.cpp - kvs/kvi_kvs_array.cpp - kvs/kvi_kvs_arraycast.cpp - kvs/kvi_kvs_asyncdnsoperation.cpp - kvs/kvi_kvs_asyncoperation.cpp - kvs/kvi_kvs_callbackobject.cpp - kvs/kvi_kvs_corecallbackcommands.cpp - kvs/kvi_kvs_corefunctions.cpp - kvs/kvi_kvs_corefunctions_af.cpp - kvs/kvi_kvs_corefunctions_gl.cpp - kvs/kvi_kvs_corefunctions_mr.cpp - kvs/kvi_kvs_corefunctions_sz.cpp - kvs/kvi_kvs_coresimplecommands.cpp - kvs/kvi_kvs_coresimplecommands_af.cpp - kvs/kvi_kvs_coresimplecommands_gl.cpp - kvs/kvi_kvs_coresimplecommands_mr.cpp - kvs/kvi_kvs_coresimplecommands_sz.cpp - kvs/kvi_kvs_dnsmanager.cpp - kvs/kvi_kvs_event.cpp - kvs/kvi_kvs_eventhandler.cpp - kvs/kvi_kvs_eventmanager.cpp - kvs/kvi_kvs_eventtable.cpp - kvs/kvi_kvs_hash.cpp - kvs/kvi_kvs_kernel.cpp - kvs/kvi_kvs_moduleinterface.cpp - kvs/kvi_kvs_object.cpp - kvs/kvi_kvs_object_class.cpp - kvs/kvi_kvs_object_controller.cpp - kvs/kvi_kvs_object_functioncall.cpp - kvs/kvi_kvs_object_functionhandler.cpp - kvs/kvi_kvs_object_functionhandlerimpl.cpp - kvs/kvi_kvs_parameterprocessor.cpp - kvs/kvi_kvs_parser.cpp - kvs/kvi_kvs_parser_command.cpp - kvs/kvi_kvs_parser_comment.cpp - kvs/kvi_kvs_parser_dollar.cpp - kvs/kvi_kvs_parser_expression.cpp - kvs/kvi_kvs_parser_lside.cpp - kvs/kvi_kvs_parser_specialcommands.cpp - kvs/kvi_kvs_popupmanager.cpp - kvs/kvi_kvs_popupmenu.cpp - kvs/kvi_kvs_processmanager.cpp - kvs/kvi_kvs_report.cpp - kvs/kvi_kvs_runtimecall.cpp - kvs/kvi_kvs_runtimecontext.cpp - kvs/kvi_kvs_rwevaluationresult.cpp - kvs/kvi_kvs_script.cpp - kvs/kvi_kvs_scriptaddonmanager.cpp - kvs/kvi_kvs_switchlist.cpp - kvs/kvi_kvs_timermanager.cpp - kvs/kvi_kvs_treenode_aliasfunctioncall.cpp - kvs/kvi_kvs_treenode_aliassimplecommand.cpp - kvs/kvi_kvs_treenode_arraycount.cpp - kvs/kvi_kvs_treenode_arrayelement.cpp - kvs/kvi_kvs_treenode_arrayorhashelement.cpp - kvs/kvi_kvs_treenode_arrayreferenceassert.cpp - kvs/kvi_kvs_treenode_base.cpp - kvs/kvi_kvs_treenode_baseobjectfunctioncall.cpp - kvs/kvi_kvs_treenode_callbackcommand.cpp - kvs/kvi_kvs_treenode_command.cpp - kvs/kvi_kvs_treenode_commandevaluation.cpp - kvs/kvi_kvs_treenode_commandwithparameters.cpp - kvs/kvi_kvs_treenode_compositedata.cpp - kvs/kvi_kvs_treenode_constantdata.cpp - kvs/kvi_kvs_treenode_corecallbackcommand.cpp - kvs/kvi_kvs_treenode_corefunctioncall.cpp - kvs/kvi_kvs_treenode_coresimplecommand.cpp - kvs/kvi_kvs_treenode_data.cpp - kvs/kvi_kvs_treenode_datalist.cpp - kvs/kvi_kvs_treenode_expression.cpp - kvs/kvi_kvs_treenode_expressionreturn.cpp - kvs/kvi_kvs_treenode_extendedscopevariable.cpp - kvs/kvi_kvs_treenode_functioncall.cpp - kvs/kvi_kvs_treenode_globalvariable.cpp - kvs/kvi_kvs_treenode_hashcount.cpp - kvs/kvi_kvs_treenode_hashelement.cpp - kvs/kvi_kvs_treenode_hashreferenceassert.cpp - kvs/kvi_kvs_treenode_indirectdata.cpp - kvs/kvi_kvs_treenode_instruction.cpp - kvs/kvi_kvs_treenode_instructionblock.cpp - kvs/kvi_kvs_treenode_localvariable.cpp - kvs/kvi_kvs_treenode_modulecallbackcommand.cpp - kvs/kvi_kvs_treenode_modulefunctioncall.cpp - kvs/kvi_kvs_treenode_modulesimplecommand.cpp - kvs/kvi_kvs_treenode_multipleparameteridentifier.cpp - kvs/kvi_kvs_treenode_objectfield.cpp - kvs/kvi_kvs_treenode_objectfunctioncall.cpp - kvs/kvi_kvs_treenode_operation.cpp - kvs/kvi_kvs_treenode_parameterreturn.cpp - kvs/kvi_kvs_treenode_rebindingswitch.cpp - kvs/kvi_kvs_treenode_scopeoperator.cpp - kvs/kvi_kvs_treenode_simplecommand.cpp - kvs/kvi_kvs_treenode_singleparameteridentifier.cpp - kvs/kvi_kvs_treenode_specialcommand.cpp - kvs/kvi_kvs_treenode_specialcommandbreak.cpp - kvs/kvi_kvs_treenode_specialcommandclass.cpp - kvs/kvi_kvs_treenode_specialcommandcontinue.cpp - kvs/kvi_kvs_treenode_specialcommanddefpopup.cpp - kvs/kvi_kvs_treenode_specialcommanddo.cpp - kvs/kvi_kvs_treenode_specialcommandfor.cpp - kvs/kvi_kvs_treenode_specialcommandforeach.cpp - kvs/kvi_kvs_treenode_specialcommandif.cpp - kvs/kvi_kvs_treenode_specialcommandswitch.cpp - kvs/kvi_kvs_treenode_specialcommandunset.cpp - kvs/kvi_kvs_treenode_specialcommandwhile.cpp - kvs/kvi_kvs_treenode_stringcast.cpp - kvs/kvi_kvs_treenode_switchlist.cpp - kvs/kvi_kvs_treenode_thisobjectfunctioncall.cpp - kvs/kvi_kvs_treenode_variable.cpp - kvs/kvi_kvs_treenode_voidfunctioncall.cpp - kvs/kvi_kvs_useraction.cpp - kvs/kvi_kvs_variant.cpp - kvs/kvi_kvs_variantlist.cpp - kernel/kvi_action.cpp - kernel/kvi_actionmanager.cpp - kernel/kvi_app.cpp - kernel/kvi_app_fs.cpp - kernel/kvi_app_setup.cpp - kernel/kvi_asynchronousconnectiondata.cpp - kernel/kvi_coreactions.cpp - kernel/kvi_customtoolbardescriptor.cpp - kernel/kvi_customtoolbarmanager.cpp - kernel/kvi_defaultscript.cpp - kernel/kvi_filetransfer.cpp - kernel/kvi_htmlgenerator.cpp - kernel/kvi_iconmanager.cpp - kernel/kvi_internalcmd.cpp - kernel/kvi_ipc.cpp - kernel/kvi_ircconnection.cpp - kernel/kvi_ircconnectionantictcpflooddata.cpp - kernel/kvi_ircconnectionasyncwhoisdata.cpp - kernel/kvi_ircconnectionnetsplitdetectordata.cpp - kernel/kvi_ircconnectionrequestqueue.cpp - kernel/kvi_ircconnectionserverinfo.cpp - kernel/kvi_ircconnectionstatedata.cpp - kernel/kvi_ircconnectionstatistics.cpp - kernel/kvi_ircconnectiontarget.cpp - kernel/kvi_ircconnectiontargetresolver.cpp - kernel/kvi_ircconnectionuserinfo.cpp - kernel/kvi_irccontext.cpp - kernel/kvi_ircdatastreammonitor.cpp - kernel/kvi_irclink.cpp - kernel/kvi_ircsocket.cpp - kernel/kvi_ircurl.cpp - kernel/kvi_lagmeter.cpp - kernel/kvi_main.cpp - kernel/kvi_notifylist.cpp - kernel/kvi_options.cpp - kernel/kvi_sslmaster.cpp - kernel/kvi_texticonmanager.cpp - kernel/kvi_theme.cpp - kernel/kvi_useraction.cpp - kernel/kvi_userinput.cpp + ui/KviActionDrawer.cpp + ui/KviChannelWindow.cpp + ui/KviColorSelectionWindow.cpp + ui/KviConsoleWindow.cpp + ui/KviCryptController.cpp + ui/KviCtcpPageDialog.cpp + ui/KviCustomToolBar.cpp + ui/KviDebugWindow.cpp + ui/KviDynamicToolTip.cpp + ui/KviFileDialog.cpp + ui/KviMainWindow.cpp + ui/KviHistoryWindow.cpp + ui/KviHtmlDialog.cpp + ui/KviImageDialog.cpp + ui/KviInput.cpp + ui/KviInputEditor.cpp + ui/KviInputHistory.cpp + ui/KviIpEditor.cpp + ui/KviIrcToolBar.cpp + ui/KviIrcView.cpp + ui/KviIrcView_events.cpp + ui/KviIrcView_getTextLine.cpp + ui/KviIrcView_loghandling.cpp + ui/KviIrcView_tools.cpp + ui/KviMaskEditor.cpp + ui/KviMdiChild.cpp + ui/KviMdiManager.cpp + ui/KviMenuBar.cpp + ui/KviModeEditor.cpp + ui/KviModeWidget.cpp + ui/KviMessageBox.cpp + ui/KviOptionsWidget.cpp + ui/KviQueryWindow.cpp + ui/KviScriptButton.cpp + ui/KviScriptEditor.cpp + ui/KviSelectors.cpp + ui/KviSplashScreen.cpp + ui/KviStatusBar.cpp + ui/KviStatusBarApplet.cpp + ui/KviTextIconWindow.cpp + ui/KviThemedComboBox.cpp + ui/KviThemedLabel.cpp + ui/KviThemedLineEdit.cpp + ui/KviThemedTreeWidget.cpp + ui/KviToolBar.cpp + ui/KviWindowToolWidget.cpp + ui/KviTopicWidget.cpp + ui/KviUserListView.cpp + ui/KviWindow.cpp + ui/KviWindowListBase.cpp + ui/KviTreeWindowList.cpp + sparser/KviAntiSpam.cpp + sparser/KviIrcMessage.cpp + sparser/KviIrcServerParser_ctcp.cpp + sparser/KviIrcServerParser_literalHandlers.cpp + sparser/KviIrcServerParser_numericHandlers.cpp + sparser/KviIrcServerParser_tables.cpp + sparser/KviIrcServerParser.cpp + module/KviMexLinkFilter.cpp + module/KviMexServerImport.cpp + module/KviMexToolBar.cpp + module/KviModule.cpp + module/KviModuleExtension.cpp + module/KviModuleManager.cpp + kvs/KviKvs.cpp + kvs/KviKvsAction.cpp + kvs/KviKvsAliasManager.cpp + kvs/KviKvsArray.cpp + kvs/KviKvsArrayCast.cpp + kvs/KviKvsAsyncDnsOperation.cpp + kvs/KviKvsAsyncOperation.cpp + kvs/KviKvsCallbackObject.cpp + kvs/KviKvsCoreCallbackCommands.cpp + kvs/KviKvsCoreFunctions.cpp + kvs/KviKvsCoreFunctions_af.cpp + kvs/KviKvsCoreFunctions_gl.cpp + kvs/KviKvsCoreFunctions_mr.cpp + kvs/KviKvsCoreFunctions_sz.cpp + kvs/KviKvsCoreSimpleCommands.cpp + kvs/KviKvsCoreSimpleCommands_af.cpp + kvs/KviKvsCoreSimpleCommands_gl.cpp + kvs/KviKvsCoreSimpleCommands_mr.cpp + kvs/KviKvsCoreSimpleCommands_sz.cpp + kvs/KviKvsDnsManager.cpp + kvs/KviKvsEvent.cpp + kvs/KviKvsEventHandler.cpp + kvs/KviKvsEventManager.cpp + kvs/KviKvsEventTable.cpp + kvs/KviKvsHash.cpp + kvs/KviKvsKernel.cpp + kvs/KviKvsModuleInterface.cpp + kvs/KviKvsObject.cpp + kvs/KviKvsObjectClass.cpp + kvs/KviKvsObjectController.cpp + kvs/KviKvsObjectFunctionCall.cpp + kvs/KviKvsObjectFunctionHandler.cpp + kvs/KviKvsObjectFunctionHandlerImpl.cpp + kvs/KviKvsParameterProcessor.cpp + kvs/KviKvsParser.cpp + kvs/KviKvsParser_command.cpp + kvs/KviKvsParser_comment.cpp + kvs/KviKvsParser_dollar.cpp + kvs/KviKvsParser_expression.cpp + kvs/KviKvsParser_lside.cpp + kvs/KviKvsParser_specialCommands.cpp + kvs/KviKvsPopupManager.cpp + kvs/KviKvsPopupMenu.cpp + kvs/KviKvsProcessManager.cpp + kvs/KviKvsReport.cpp + kvs/KviKvsRunTimeCall.cpp + kvs/KviKvsRunTimeContext.cpp + kvs/KviKvsRWEvaluationResult.cpp + kvs/KviKvsScript.cpp + kvs/KviKvsScriptAddonManager.cpp + kvs/KviKvsSwitchList.cpp + kvs/KviKvsTimerManager.cpp + kvs/KviKvsTreeNodeAliasFunctionCall.cpp + kvs/KviKvsTreeNodeAliasSimpleCommand.cpp + kvs/KviKvsTreeNodeArrayCount.cpp + kvs/KviKvsTreeNodeArrayElement.cpp + kvs/KviKvsTreeNodeArrayOrHashElement.cpp + kvs/KviKvsTreeNodeArrayReferenceAssert.cpp + kvs/KviKvsTreeNodeBase.cpp + kvs/KviKvsTreeNodeBaseObjectFunctionCall.cpp + kvs/KviKvsTreeNodeCallbackCommand.cpp + kvs/KviKvsTreeNodeCommand.cpp + kvs/KviKvsTreeNodeCommandEvaluation.cpp + kvs/KviKvsTreeNodeCommandWithParameters.cpp + kvs/KviKvsTreeNodeCompositeData.cpp + kvs/KviKvsTreeNodeConstantData.cpp + kvs/KviKvsTreeNodeCoreCallbackCommand.cpp + kvs/KviKvsTreeNodeCoreFunctionCall.cpp + kvs/KviKvsTreeNodeCoreSimpleCommand.cpp + kvs/KviKvsTreeNodeData.cpp + kvs/KviKvsTreeNodeDataList.cpp + kvs/KviKvsTreeNodeExpression.cpp + kvs/KviKvsTreeNodeExpressionReturn.cpp + kvs/KviKvsTreeNodeExtendedScopeVariable.cpp + kvs/KviKvsTreeNodeFunctionCall.cpp + kvs/KviKvsTreeNodeGlobalVariable.cpp + kvs/KviKvsTreeNodeHashCount.cpp + kvs/KviKvsTreeNodeHashElement.cpp + kvs/KviKvsTreeNodeHashReferenceAssert.cpp + kvs/KviKvsTreeNodeIndirectData.cpp + kvs/KviKvsTreeNodeInstruction.cpp + kvs/KviKvsTreeNodeInstructionBlock.cpp + kvs/KviKvsTreeNodeLocalVariable.cpp + kvs/KviKvsTreeNodeModuleCallbackCommand.cpp + kvs/KviKvsTreeNodeModuleFunctionCall.cpp + kvs/KviKvsTreeNodeModuleSimpleCommand.cpp + kvs/KviKvsTreeNodeMultipleParameterIdentifier.cpp + kvs/KviKvsTreeNodeObjectField.cpp + kvs/KviKvsTreeNodeObjectFunctionCall.cpp + kvs/KviKvsTreeNodeOperation.cpp + kvs/KviKvsTreeNodeParameterReturn.cpp + kvs/KviKvsTreeNodeRebindingSwitch.cpp + kvs/KviKvsTreeNodeScopeOperator.cpp + kvs/KviKvsTreeNodeSimpleCommand.cpp + kvs/KviKvsTreeNodeSingleParameterIdentifier.cpp + kvs/KviKvsTreeNodeSpecialCommand.cpp + kvs/KviKvsTreeNodeSpecialCommandBreak.cpp + kvs/KviKvsTreeNodeSpecialCommandClass.cpp + kvs/KviKvsTreeNodeSpecialCommandContinue.cpp + kvs/KviKvsTreeNodeSpecialCommandDefpopup.cpp + kvs/KviKvsTreeNodeSpecialCommandDo.cpp + kvs/KviKvsTreeNodeSpecialCommandFor.cpp + kvs/KviKvsTreeNodeSpecialCommandForeach.cpp + kvs/KviKvsTreeNodeSpecialCommandIf.cpp + kvs/KviKvsTreeNodeSpecialCommandSwitch.cpp + kvs/KviKvsTreeNodeSpecialCommandUnset.cpp + kvs/KviKvsTreeNodeSpecialCommandWhile.cpp + kvs/KviKvsTreeNodeStringCase.cpp + kvs/KviKvsTreeNodeSwitchList.cpp + kvs/KviKvsTreeNodeThisObjectFunctionCall.cpp + kvs/KviKvsTreeNodeVariable.cpp + kvs/KviKvsTreeNodeVoidFunctionCall.cpp + kvs/KviKvsUserAction.cpp + kvs/KviKvsVariant.cpp + kvs/KviKvsVariantList.cpp + kernel/KviAction.cpp + kernel/KviActionManager.cpp + kernel/KviApplication.cpp + kernel/KviApplication_filesystem.cpp + kernel/KviApplication_setup.cpp + kernel/KviAsynchronousConnectionData.cpp + kernel/KviCoreActions.cpp + kernel/KviCustomToolBarDescriptor.cpp + kernel/KviCustomToolBarManager.cpp + kernel/KviDefaultScript.cpp + kernel/KviFileTransfer.cpp + kernel/KviHtmlGenerator.cpp + kernel/KviIconManager.cpp + kernel/KviInternalCommand.cpp + kernel/KviIpcSentinel.cpp + kernel/KviIrcConnection.cpp + kernel/KviIrcConnectionAntiCtcpFloodData.cpp + kernel/KviIrcConnectionAsyncWhoisData.cpp + kernel/KviIrcConnectionNetsplitDetectorData.cpp + kernel/KviIrcConnectionRequestQueue.cpp + kernel/KviIrcConnectionServerInfo.cpp + kernel/KviIrcConnectionStateData.cpp + kernel/KviIrcConnectionStatistics.cpp + kernel/KviIrcConnectionTarget.cpp + kernel/KviIrcConnectionTargetResolver.cpp + kernel/KviIrcConnectionUserInfo.cpp + kernel/KviIrcContext.cpp + kernel/KviIrcDataStreamMonitor.cpp + kernel/KviIrcLink.cpp + kernel/KviIrcSocket.cpp + kernel/KviIrcUrl.cpp + kernel/KviLagMeter.cpp + kernel/KviMain.cpp + kernel/KviNotifyList.cpp + kernel/KviOptions.cpp + kernel/KviSSLMaster.cpp + kernel/KviTextIconManager.cpp + kernel/KviTheme.cpp + kernel/KviUserAction.cpp + kernel/KviUserInput.cpp ) # After this call, files will be moc'ed to moc_kvi_*.cpp diff --git a/src/kvirc/kernel/KviAction.cpp b/src/kvirc/kernel/KviAction.cpp new file mode 100644 index 000000000..6f809151f --- /dev/null +++ b/src/kvirc/kernel/KviAction.cpp @@ -0,0 +1,503 @@ +//============================================================================= +// +// File : KviAction.cpp +// Creation date : Sun 21 Nov 2004 03:36:34 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviAction.h" +#include "KviCustomToolBar.h" +#include "KviMainWindow.h" +#include "KviIrcContext.h" +#include "KviIconManager.h" +#include "KviApplication.h" +#include "KviWindow.h" +#include "KviChannelWindow.h" +#include "KviQueryWindow.h" +#include "KviTalPopupMenu.h" + +#include + +KviActionCategory::KviActionCategory(const QString & szName, const QString & szVisibleName, const QString & szDescription) +: m_szName(szName), m_szVisibleName(szVisibleName), m_szDescription(szDescription) +{ +} + +KviActionCategory::~KviActionCategory() +{ +} + + +KviAction::KviAction(QObject * pParent, const QString & szName, const QString & szVisibleName, const QString & szDescription, KviActionCategory * pCategory, const QString & szBigIconId, const QString & szSmallIconId, unsigned int uFlags, const QString & szKeySequence) +: QObject(pParent),m_szName(szName),m_szVisibleName(szVisibleName),m_szDescription(szDescription),m_pCategory(pCategory),m_szBigIconId(szBigIconId),m_szSmallIconId(szSmallIconId),m_pWidgetList(NULL),m_uInternalFlags(KviAction::Enabled),m_uFlags(uFlags),m_szKeySequence(szKeySequence),m_pAccel(NULL) +{ +} + +KviAction::~KviAction() +{ + if(m_pWidgetList) + { + for(QWidget * pWidget = m_pWidgetList->first(); pWidget; pWidget = m_pWidgetList->next()) + disconnect(pWidget,SIGNAL(destroyed()),this,SLOT(widgetDestroyed())); + m_pWidgetList->setAutoDelete(true); + delete m_pWidgetList; + } +} + +const QString & KviAction::visibleName() +{ + return m_szVisibleName; +} + +const QString & KviAction::description() +{ + return m_szDescription; +} + +bool KviAction::isKviUserActionNeverOverrideThis() +{ + return false; +} + +void KviAction::registerAccelerator() +{ + if(!m_szKeySequence.isEmpty()) + { + m_pAccel = new QShortcut(m_szKeySequence,g_pFrame,0,0,Qt::ApplicationShortcut); + connect(m_pAccel,SIGNAL(activated()),this,SLOT(activate())); + //no way to have Ctrl+Alt+Key events fired as no-ambiguous, probably qt bug + connect(m_pAccel,SIGNAL(activatedAmbiguously()),this,SLOT(activate())); + } +} + +void KviAction::unregisterAccelerator() +{ + if(m_pAccel != 0) + { + if(g_pFrame) + g_pFrame->releaseShortcut(m_pAccel->id()); + m_pAccel = 0; + } +} + +void KviAction::setEnabled(bool bEnabled) +{ + if(bEnabled) + m_uInternalFlags |= KviAction::Enabled; + else + m_uInternalFlags &= ~KviAction::Enabled; + + if(m_pWidgetList) + { + if(bEnabled) + { + for(QWidget * pWidget = m_pWidgetList->first(); pWidget; pWidget = m_pWidgetList->next()) + { + if(!pWidget->isEnabled()) + pWidget->setEnabled(true); + } + } else { + for(QWidget * pWidget = m_pWidgetList->first(); pWidget; pWidget = m_pWidgetList->next()) + { + if(pWidget->isEnabled()) + pWidget->setEnabled(false); + } + } + } +} + +int KviAction::validateFlags(int iFlagsToValidate) +{ + if(iFlagsToValidate & EnableAtLogin) + iFlagsToValidate |= NeedsConnection; + if(iFlagsToValidate & NeedsConnection) + iFlagsToValidate |= NeedsContext; + if(iFlagsToValidate & WindowOnlyIfUsersSelected) + { + if(!(iFlagsToValidate & InternalWindowMask)) + iFlagsToValidate &= ~WindowOnlyIfUsersSelected; + } + return iFlagsToValidate; +} + +QPixmap * KviAction::smallIcon() +{ + if(m_szSmallIconId.isEmpty()) + return NULL; + return g_pIconManager->getImage(m_szSmallIconId); +} + +QPixmap * KviAction::bigIcon() +{ + if(m_szBigIconId.isEmpty()) + return NULL; + return g_pIconManager->getImage(m_szBigIconId); +} + +void KviAction::setup() +{ + connect(g_pApp,SIGNAL(reloadImages()),this,SLOT(reloadImages())); + if(m_uFlags & InternalWindowMask) + { + connect(g_pFrame,SIGNAL(activeWindowChanged()),this,SLOT(activeWindowChanged())); + if((m_uFlags & WindowOnlyIfUsersSelected) && (m_uFlags & (WindowChannel | WindowConsole | WindowQuery))) + connect(g_pFrame,SIGNAL(activeWindowSelectionStateChanged(bool)),this,SLOT(activeWindowSelectionStateChanged(bool))); + activeWindowChanged(); + } else { + if(m_uFlags & NeedsConnection) + { + connect(g_pFrame,SIGNAL(activeContextChanged()),this,SLOT(activeContextChanged())); + connect(g_pFrame,SIGNAL(activeContextStateChanged()),this,SLOT(activeContextStateChanged())); + KviIrcContext * pContext = g_pFrame->activeContext(); + if(!pContext) + setEnabled(false); + else { + switch(pContext->state()) + { + case KviIrcContext::LoggingIn: + setEnabled(m_uFlags & EnableAtLogin); + break; + case KviIrcContext::Connected: + setEnabled(true); + break; + default: + setEnabled(false); + break; + } + } + } else { + if(m_uFlags & NeedsContext) + { + connect(g_pFrame,SIGNAL(activeContextChanged()),this,SLOT(activeContextChanged())); + if(!g_pFrame->activeContext()) + setEnabled(false); + else + setEnabled(true); + } + } + } + + m_uInternalFlags |= KviAction::SetupDone; +} + + +void KviAction::reloadImages() +{ + if(!m_pWidgetList) + return; + QPixmap * pPix = bigIcon(); + for(QWidget * pWidget = m_pWidgetList->first(); pWidget; pWidget = m_pWidgetList->next()) + { + if(pWidget->inherits("QToolButton")) + ((QToolButton *)pWidget)->setIcon(pPix ? *pPix : QPixmap()); + } +} + +void KviAction::activeWindowChanged() +{ + if(m_uFlags & NeedsContext) + { + if(!g_pFrame->activeContext()) + { + if(isEnabled()) + setEnabled(false); + return; + } + } + + if(m_uFlags & NeedsConnection) + { + switch(g_pFrame->activeContext()->state()) + { + case KviIrcContext::LoggingIn: + if(!(m_uFlags & EnableAtLogin)) + { + if(isEnabled()) + setEnabled(false); + return; + } + break; + case KviIrcContext::Connected: + // this is ok + break; + default: + if(isEnabled()) + setEnabled(false); + return; + break; + } + } + + if(!g_pActiveWindow) + { + if(isEnabled()) + setEnabled(false); + return; + } + + switch(g_pActiveWindow->type()) + { + case KVI_WINDOW_TYPE_CONSOLE: + if(m_uFlags & WindowConsole) + { + if(m_uFlags & WindowOnlyIfUsersSelected) + { + bool bEnabled = ((KviConsole *)g_pActiveWindow)->selectedCount() > 0; + if(bEnabled != isEnabled()) + setEnabled(bEnabled); + } else { + if(!isEnabled()) + setEnabled(true); + } + } else { + if(isEnabled()) + setEnabled(false); + } + break; + case KVI_WINDOW_TYPE_CHANNEL: + if(m_uFlags & WindowChannel) + { + if(m_uFlags & WindowOnlyIfUsersSelected) + { + bool bEnabled = ((KviChannelWindow *)g_pActiveWindow)->selectedCount() > 0; + if(bEnabled != isEnabled()) + setEnabled(bEnabled); + } else { + if(!isEnabled()) + setEnabled(true); + } + } else { + if(isEnabled()) + setEnabled(false); + } + break; + case KVI_WINDOW_TYPE_QUERY: + if(m_uFlags & WindowQuery) + { + if(m_uFlags & WindowOnlyIfUsersSelected) + { + bool bEnabled = ((KviQueryWindow *)g_pActiveWindow)->selectedCount() > 0; + if(bEnabled != isEnabled()) + setEnabled(bEnabled); + } else { + if(!isEnabled()) + setEnabled(true); + } + } else { + if(isEnabled()) + setEnabled(false); + } + break; + case KVI_WINDOW_TYPE_DCCCHAT: + if(m_uFlags & WindowDccChat) + { + if(!isEnabled()) + setEnabled(true); + } else { + if(isEnabled()) + setEnabled(false); + } + break; + default: + if(m_uFlags & InternalWindowMask) + { + if(isEnabled()) + setEnabled(false); + } else { + if(!isEnabled()) + setEnabled(true); + } + break; + } +} + +void KviAction::activeWindowSelectionStateChanged(bool bSelectedNow) +{ + // we jump here ONLY if m_uFlags & WindowOnlyIfUsersSelected + // and thus also m_uFlags & InternalWindowMask + switch(g_pActiveWindow->type()) + { + case KVI_WINDOW_TYPE_CONSOLE: + if(m_uFlags & WindowConsole) + { + if(bSelectedNow != isEnabled()) + setEnabled(bSelectedNow); + } else { + if(isEnabled()) + setEnabled(false); + } + break; + case KVI_WINDOW_TYPE_CHANNEL: + if(m_uFlags & WindowChannel) + { + if(bSelectedNow != isEnabled()) + setEnabled(bSelectedNow); + } else { + if(isEnabled()) + setEnabled(false); + } + break; + case KVI_WINDOW_TYPE_QUERY: + if(m_uFlags & WindowQuery) + { + if(bSelectedNow != isEnabled()) + setEnabled(bSelectedNow); + } else { + if(isEnabled()) + setEnabled(false); + } + break; + case KVI_WINDOW_TYPE_DCCCHAT: + if(m_uFlags & WindowDccChat) + { + if(!isEnabled()) + setEnabled(true); + } else { + if(isEnabled()) + setEnabled(false); + } + break; + default: + if(isEnabled()) + setEnabled(false); + break; + } +} + +void KviAction::activeContextChanged() +{ + // works only if NeedsContext is specified! + KviIrcContext * pContext = g_pFrame->activeContext(); + if(pContext) + { + if(m_uFlags & NeedsConnection) + activeContextStateChanged(); + else + if(!isEnabled()) + setEnabled(true); + } else { + if(isEnabled()) + setEnabled(false); + } +} + +void KviAction::activeContextStateChanged() +{ + KviIrcContext * pContext = g_pFrame->activeContext(); + if(pContext) + { + switch(pContext->state()) + { + case KviIrcContext::Idle: + case KviIrcContext::Connecting: + if(isEnabled()) + setEnabled(false); + break; + case KviIrcContext::LoggingIn: + if(m_uFlags & EnableAtLogin) + { + if(!isEnabled()) + setEnabled(true); + } else { + if(isEnabled()) + setEnabled(false); + } + break; + case KviIrcContext::Connected: + if(!isEnabled()) + setEnabled(true); + break; + default: + if(isEnabled()) + setEnabled(false); + break; + } + } else { + if(isEnabled()) + setEnabled(false); + } +} + +bool KviAction::addToPopupMenu(KviTalPopupMenu * pMenu) +{ + if(!setupDone()) + setup(); + QPixmap * pPix = smallIcon(); + int iId; + QString szTmp = visibleName(); + + if(!m_szKeySequence.isEmpty()) + szTmp += '\t' + m_szKeySequence; + + if(pPix) + iId = pMenu->insertItem(*pPix,szTmp,this,SLOT(activate())); + else + iId = pMenu->insertItem(szTmp,this,SLOT(activate())); + + if(!isEnabled()) + pMenu->setItemEnabled(iId,false); + return true; +} + +void KviAction::widgetDestroyed() +{ + if(!m_pWidgetList) + return; + QWidget * pWidget = (QWidget *)sender(); + m_pWidgetList->removeRef(pWidget); +} + +void KviAction::registerWidget(QWidget * pWidget) +{ + connect(pWidget,SIGNAL(destroyed()),this,SLOT(widgetDestroyed())); + if(!m_pWidgetList) + { + m_pWidgetList = new KviPointerList; + m_pWidgetList->setAutoDelete(false); + } + m_pWidgetList->append(pWidget); +} + +QWidget * KviAction::addToCustomToolBar(KviCustomToolBar * pParentToolBar) +{ + if(!setupDone()) + setup(); + QPixmap * pPix = bigIcon(); + QToolButton * pTool = new QToolButton(pParentToolBar); + + pTool->setIcon(pPix ? *pPix : QPixmap()); + pTool->setText(visibleName()); + pTool->setToolTip(visibleName()); + pTool->setObjectName(m_szName.toUtf8().data()); + connect(pTool,SIGNAL(clicked()),this,SLOT(activate())); + + QAction * pAction = pParentToolBar->addWidget(pTool); + pAction->setVisible(true); + if(!isEnabled()) + pTool->setEnabled(false); + registerWidget(pTool); + return pTool; +} + +void KviAction::activate() +{ + if(isEnabled()) + emit activated(); +} diff --git a/src/kvirc/kernel/KviAction.h b/src/kvirc/kernel/KviAction.h new file mode 100644 index 000000000..4ba2057cc --- /dev/null +++ b/src/kvirc/kernel/KviAction.h @@ -0,0 +1,375 @@ +#ifndef _KVI_ACTION_H_ +#define _KVI_ACTION_H_ +//============================================================================= +// +// File : KviAction.h +// Creation date : Sun 21 Nov 2004 03:36:34 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviAction.h +* \author Szymon Stefanek +* \brief Actions handling +*/ + +#include "kvi_settings.h" +#include "KviPointerList.h" + +#include + +class QShortcut; +class QPixmap; +class KviTalPopupMenu; +class KviCustomToolBar; + +/** +* \class KviActionCategory +* \brief Holds the categories of an action +* +* Known categories are: general (or empty), irc, script +*/ +class KVIRC_API KviActionCategory +{ +protected: + QString m_szName; + QString m_szVisibleName; + QString m_szDescription; +public: + /** + * \brief Constructs an action category object + * \param szName The name of the category + * \param szVisibleName Permanent visible name, visible at least in the action drawer + * \param szDescription Description of the category + * \return KviActionCategory + */ + KviActionCategory(const QString & szName, const QString & szVisibleName, const QString & szDescription); + + /** + * \brief Destroys an action category object + */ + ~KviActionCategory(); +public: + /** + * \brief Returns the name of the category + * \return const QString & + */ + const QString & name(){ return m_szName; }; + + /** + * \brief Returns the visible name of the category + * \return const QString & + */ + const QString & visibleName(){ return m_szVisibleName; }; + + /** + * \brief Returns the description of the category + * \return const QString & + */ + const QString & description(){ return m_szDescription; }; +}; + +/** +* \class KviAction +* \brief Defines an action inside KVIrc +*/ +class KVIRC_API KviAction : public QObject +{ + friend class KviActionManager; + Q_OBJECT +public: + /** + * \enum InternalFlags + * \brief Holds the internal flags of an action + */ + enum InternalFlags { + Enabled = 1, /**< the action is enabled */ + SetupDone = 2 /**< the setup of the action is done */ + }; + + /** + * \enum Flags + * \brief Holds the flags of an action + */ + enum Flags { + NeedsContext = 1, /**< the action needs a context */ + NeedsConnection = 2, /**< the action needs a connection; implies NeedsContext */ + WindowConsole = 4, /**< the action is bound to a console window */ + WindowChannel = 8, /**< the action is bound to a channel window */ + WindowQuery = 16, /**< the action is bound to a query window */ + WindowDccChat = 32, /**< the action is bound to a DCC Chat window */ + InternalWindowMask = WindowConsole | WindowChannel | WindowQuery | WindowDccChat, /**< the action is bound to a window */ + EnableAtLogin = 64, /**< the action is enabled at login; implies NeedsConnection */ + WindowOnlyIfUsersSelected = 128 /**< the action is bound to a window only if it's selected by the user; implies at least one of WindowConsole | WindowChannel | WindowQuery */ + }; +public: + /** + * \brief Constructs the action object + * \param pParent The parent object + * + * It can be 0, but using a QObject will help in deleting this action :) + * \param szName Internal name of this action, in form [module.]name + * + * The action name is INTERNAL: it should be never shown to the user. If it contains a dot + * then the part before the dot is considered to be a module name to be loaded when the + * module is loaded. + * \param szVisibleName Permanent visible name, visible at least in the action drawer + * \param szDescription What this action does + * \param pCategory One of KviActionManager::category*() or 0 (default category), not owned! + * \param szBigIconId The big icon associated to the action (32x32) + * \param szSmallIconId The small icon associated to the action (16x16) + * \param uFlags The flags of the action, like needs and configuration + * \param szKeySequence The shortcut to activate the action + * \return KviAction + */ + KviAction(QObject * pParent, const QString & szName, const QString & szVisibleName, const QString & szDescription, KviActionCategory * pCategory = NULL, const QString & szBigIconId = QString(), const QString & szSmallIconId = QString(), unsigned int uFlags = 0, const QString & szKeySequence = QString()); + + /** + * \brief Destroys the action object + */ + virtual ~KviAction(); +protected: + QString m_szName; + QString m_szVisibleName; + QString m_szDescription; + KviActionCategory * m_pCategory; + QString m_szBigIconId; + QString m_szSmallIconId; + KviPointerList * m_pWidgetList; + unsigned short int m_uInternalFlags; + unsigned int m_uFlags; + QString m_szKeySequence; + QShortcut * m_pAccel; +public: + /** + * \brief Validates the flags of the action + * \param iFlagsToValidate The flags to validate + * \return int + */ + static int validateFlags(int iFlagsToValidate); + + /** + * \brief Returns the name of the action + * \return const QString & + */ + const QString & name() const { return m_szName; }; + + /** + * \brief Returns the visible name of the action + * \return const QString & + */ + virtual const QString & visibleName(); + + /** + * \brief Returns the description of the action + * \return const QString & + */ + virtual const QString & description(); + + /** + * \brief Returns the shortcut of the action + * \return const QString & + */ + const QString & keySequence() const { return m_szKeySequence; }; + + /** + * \brief Returns the id of the big icon associated to the action + * \return const QString & + */ + const QString & bigIconId() const { return m_szBigIconId; }; + + /** + * \brief Returns the id of the small icon associated to the action + * \return const QString & + */ + const QString & smallIconId() const { return m_szSmallIconId; }; + + /** + * \brief Returns the category of the action + * \return const QString & + */ + KviActionCategory * category() const { return m_pCategory; }; + + /** + * \brief Returns true if the action is enabled + * \return bool + */ + bool isEnabled() const { return (m_uInternalFlags & KviAction::Enabled); }; + + /** + * \brief Returns the flag associated to the action + * \return unsigned int + */ + unsigned int flags(){ return m_uFlags; }; + + /** + * \brief Returns true if the action is user-defined + * \warning By default, this function returns always false + * \return bool + */ + virtual bool isKviUserActionNeverOverrideThis(); + + /** + * \brief Enables the action + * \param bEnabled Whether to enable the action + * \return void + */ + virtual void setEnabled(bool bEnabled); + + /** + * \brief Returns the small icon associated to the action + * \return const QString & + */ + QPixmap * smallIcon(); + + /** + * \brief Returns the big icon associated to the action + * \return const QString & + */ + QPixmap * bigIcon(); + + /** + * \brief Adds the action to the given popup + * \param pMenu The menu where to add the action + * \return bool + */ + virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); + + /** + * \brief Adds the action to the given toolbar + * \param pParentToolBar The toolbar where to add the action + * \return QWidget * + */ + virtual QWidget * addToCustomToolBar(KviCustomToolBar * pParentToolBar); + + /** + * \brief Destroys itself. Maybe the best function in the whole APIs :) + * \return void + */ + void suicide(){ delete this; }; +protected: + /** + * \brief Returns true if the setup is finished + * \note Called once before the FIRST button or menu item is created + * \return bool + */ + bool setupDone() const { return (m_uInternalFlags & KviAction::SetupDone); }; + + /** + * \brief Enables or disables the action upon starting KVIrc + * \return void + */ + virtual void setup(); + + /** + * \brief Returns the list of widgets associated to the action + * \return KviPointerList * + */ + KviPointerList * widgetList(){ return m_pWidgetList; }; + + /** + * \brief Registers the action shortcut in the application + * \return void + */ + void registerAccelerator(); + + /** + * \brief Removes the action shortcut from the application + * \return void + */ + void unregisterAccelerator(); + + /** + * \brief Adds the widget to the list + * \param pWidget The widget to add + * \return void + */ + void registerWidget(QWidget * pWidget); +public slots: + /** + * \brief Activates the action + * + * It's called when the user activates the action clicking on the toolbar, the menu or by + * hitting its shortcut. + * \return void + */ + virtual void activate(); +protected slots: + /** + * \brief Removes the widget from the list + * + * Called when the widget is being destroyed + * \return void + */ + virtual void widgetDestroyed(); + + /** + * \brief Reloads the images + * + * Called when the application wants to refresh the images in the toolbar + * \return void + */ + virtual void reloadImages(); + + /** + * \brief Enables or disables the action upon checking the active context + * + * If the context doesn't exist, the action is disabled + * + * Called when the frame changes the active context. + * \note It works only if NeedsContext is specified + * \return void + */ + virtual void activeContextChanged(); + + /** + * \brief Enables or disables the action upon checking the active context + * + * Called when the frame changes the state of the context + * \return void + */ + virtual void activeContextStateChanged(); + + /** + * \brief Enables or disables the action upon checking the active window + * + * Called when the frame changes the active window. + * \return void + */ + virtual void activeWindowChanged(); + + /** + * \brief Enables or disables the action upon checking the active window + * + * Called when the frame changes the active window. + * \note We jump here ONLY if m_uFlags & WindowOnlyIfUsersSelected and thus also + * m_uFlags & InternalWindowMask + * \return void + */ + virtual void activeWindowSelectionStateChanged(bool bSelectedNow); +signals: + /** + * \brief Emitted when the action is being activated + * \return void + */ + void activated(); +}; + +#endif // _KVI_ACTION_H_ diff --git a/src/kvirc/kernel/KviActionManager.cpp b/src/kvirc/kernel/KviActionManager.cpp new file mode 100644 index 000000000..de2f1876d --- /dev/null +++ b/src/kvirc/kernel/KviActionManager.cpp @@ -0,0 +1,318 @@ +//============================================================================= +// +// File : KviActionManager.cpp +// Creation date : Sun 21 Nov 2004 03:37:57 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviActionManager.h" +#include "KviModuleManager.h" +#include "KviCoreActions.h" +#include "KviCustomToolBar.h" +#include "KviCustomToolBarManager.h" +#include "KviApplication.h" +#include "KviLocale.h" +#include "KviKvsUserAction.h" +#include "KviConfigurationFile.h" +#include "KviQString.h" +#include "KviMainWindow.h" + +KviActionManager * KviActionManager::m_pInstance = 0; +KviActionCategory * KviActionManager::m_pCategoryIrc = 0; +KviActionCategory * KviActionManager::m_pCategoryGeneric = 0; +KviActionCategory * KviActionManager::m_pCategorySettings = 0; +KviActionCategory * KviActionManager::m_pCategoryScripting = 0; +KviActionCategory * KviActionManager::m_pCategoryGUI = 0; +KviActionCategory * KviActionManager::m_pCategoryChannel = 0; +KviActionCategory * KviActionManager::m_pCategoryTools = 0; +bool KviActionManager::m_bCustomizingToolBars = false; +KviCustomToolBar * KviActionManager::m_pCurrentToolBar = 0; +// KviCoreActions.cpp +extern void register_core_actions(KviActionManager *); + +KviActionManager::KviActionManager() +: QObject() +{ + m_pActions = new KviPointerHashTable(101); + m_pActions->setAutoDelete(false); + + m_pCategories = new KviPointerHashTable(17,false); + m_pCategories->setAutoDelete(true); + +#define CATEGORY(__var,__name,__vname,__descr) \ + __var = new KviActionCategory(__name,__vname,__descr); \ + m_pCategories->replace(__name,__var) + + CATEGORY(m_pCategoryIrc,"irc",__tr2qs("IRC"),__tr2qs("IRC Context related actions")); + CATEGORY(m_pCategoryGeneric,"generic",__tr2qs("Generic"),__tr2qs("Generic actions")); + CATEGORY(m_pCategorySettings,"settings",__tr2qs("Settings"),__tr2qs("Actions related to settings")); + CATEGORY(m_pCategoryScripting,"scripting",__tr2qs("Scripting"),__tr2qs("Scripting related actions")); + CATEGORY(m_pCategoryGUI,"gui",__tr2qs("GUI"),__tr2qs("Actions related to the Graphic User Interface")); + CATEGORY(m_pCategoryChannel,"channel",__tr2qs("Channel"),__tr2qs("IRC Channel related actions")); + CATEGORY(m_pCategoryTools,"tools",__tr2qs("Tools"),__tr2qs("Actions that will appear in the \"Tools\" menu")); + + m_bCustomizingToolBars = false; + m_pCurrentToolBar = 0; + m_bCoreActionsRegistered = false; +} + +KviActionManager::~KviActionManager() +{ + // the customizeToolBars dialog has been already + // destroyed since the module manager has already + // killed all the modules at this point... + //KviActionDialog::cleanup(); + + KviPointerHashTableIterator it(*m_pActions); + while(KviAction * a = it.current()) + { + disconnect(a,SIGNAL(destroyed()),this,SLOT(actionDestroyed())); + ++it; + } + delete m_pActions; + + delete m_pCategories; +} + +void KviActionManager::load(const QString &szFileName) +{ + KviConfigurationFile cfg(szFileName,KviConfigurationFile::Read); + + KviConfigurationFileIterator it(*(cfg.dict())); + while(it.current()) + { + cfg.setGroup(it.currentKey()); + KviKvsUserAction * a = new KviKvsUserAction(this); + if(a->load(&cfg))registerAction(a); + else delete a; + ++it; + } +} + +void KviActionManager::save(const QString &szFileName) +{ + KviConfigurationFile cfg(szFileName,KviConfigurationFile::Write); + cfg.clear(); + + KviPointerHashTableIterator it(*m_pActions); + while(KviAction * a = it.current()) + { + if(a->isKviUserActionNeverOverrideThis()) + { + cfg.setGroup(a->name()); + ((KviKvsUserAction *)a)->save(&cfg); + } + ++it; + } +} + +void KviActionManager::killAllKvsUserActions() +{ + KviPointerList dying; + dying.setAutoDelete(true); + + KviPointerHashTableIterator it(*m_pActions); + while(KviAction * a = it.current()) + { + if(a->isKviUserActionNeverOverrideThis()) + { + dying.append(((KviKvsUserAction *)a)); + } + ++it; + } + + dying.clear(); // bye :) +} + + +bool KviActionManager::coreActionExists(const QString &szName) +{ + KviAction *a = m_pActions->find(szName); + if(a)return (!a->isKviUserActionNeverOverrideThis()); + return false; +} + +QString KviActionManager::nameForAutomaticAction(const QString &szTemplate) +{ + QString ret; + + int i = 1; + do { + KviQString::sprintf(ret,"%Q%d",&szTemplate,i); + i++; + } while(m_pActions->find(ret)); + + return ret; +} + +void KviActionManager::emitRemoveActionsHintRequest() +{ + emit removeActionsHintRequest(); +} + +KviActionCategory * KviActionManager::category(const QString &szName) +{ + if(!szName.isEmpty()) + { + KviActionCategory * c = m_pCategories->find(szName); + if(c)return c; + } + return m_pCategoryGeneric; +} + +void KviActionManager::customizeToolBarsDialogCreated() +{ + m_bCustomizingToolBars = true; + m_pCurrentToolBar = KviCustomToolBarManager::instance()->firstExistingToolBar(); + if(m_pCurrentToolBar)m_pCurrentToolBar->update(); + emit beginCustomizeToolBars(); +} + +void KviActionManager::customizeToolBarsDialogDestroyed() +{ + m_bCustomizingToolBars = false; + emit endCustomizeToolBars(); + if(m_pCurrentToolBar) + { + m_pCurrentToolBar->update(); + m_pCurrentToolBar = 0; + } + g_pApp->saveToolBars(); +} + +void KviActionManager::setCurrentToolBar(KviCustomToolBar * t) +{ + if(m_pCurrentToolBar == t)return; + KviCustomToolBar * old = m_pCurrentToolBar; + m_pCurrentToolBar = t; + if(old)old->update(); + if(!m_pCurrentToolBar && m_bCustomizingToolBars) + m_pCurrentToolBar = KviCustomToolBarManager::instance()->firstExistingToolBar(); + if(m_pCurrentToolBar)m_pCurrentToolBar->update(); + emit currentToolBarChanged(); +} + +void KviActionManager::loadAllAvailableActions() +{ + // make sure that the core actions are registered now + if(!KviActionManager::instance()->m_bCoreActionsRegistered) + { + register_core_actions(KviActionManager::instance()); + KviActionManager::instance()->m_bCoreActionsRegistered = true; + } + g_pModuleManager->loadModulesByCaps("action"); +} + +void KviActionManager::init() +{ + if(!m_pInstance)m_pInstance = new KviActionManager(); +} + +void KviActionManager::done() +{ + if(m_pInstance) + { + delete m_pInstance; + m_pInstance = 0; + } +} + +void KviActionManager::delayedRegisterAccelerators() +{ + KviPointerHashTableIterator it(*m_pActions); + while(KviAction * a = it.current()) + { + a->registerAccelerator(); + ++it; + } +} + +bool KviActionManager::registerAction(KviAction * a) +{ + if(m_pActions->find(a->name()))return false; + connect(a,SIGNAL(destroyed()),this,SLOT(actionDestroyed())); + m_pActions->insert(a->name(),a); + if(g_pFrame)a->registerAccelerator(); // otherwise it is delayed! + return true; +} + +void KviActionManager::actionDestroyed() +{ + KviAction * a = (KviAction *)sender(); + m_pActions->remove(a->name()); +} + +bool KviActionManager::unregisterAction(const QString &szName) +{ + KviAction * a = m_pActions->find(szName); + if(!a)return false; + disconnect(a,SIGNAL(destroyed()),this,SLOT(actionDestroyed())); + a->unregisterAccelerator(); + return m_pActions->remove(szName); +} + +KviAction * KviActionManager::getAction(const QString &szName) +{ + KviAction * a = m_pActions->find(szName); + if(a)return a; + int idx = szName.indexOf('.'); + if(idx < 0) + { + // backward compatibility: try to lookup the name with the kvirc. prefix + QString s = "kvirc."; + s += szName; + return m_pActions->find(s); + } + if((idx == 5) && (!m_bCoreActionsRegistered)) + { + // the core actions are all like kvirc.name + // so the dot is at poisition 5 (6th char) + // the first requested core action will trigger this + // the nice thing is that we will probably already have a frame when + // the core actions are registered thus stuff like mdiManager() can be accessed... + if(szName.left(5) == "kvirc") + { + register_core_actions(this); + m_bCoreActionsRegistered = true; + a = m_pActions->find(szName); + return a; + } + } + // try to preload the module that might register this action... + QString szModule = szName.left(idx); + if(!g_pModuleManager->getModule(szModule))return 0; + return m_pActions->find(szName); +} + +void KviActionManager::listActionsByCategory(const QString &szCatName,KviPointerList * pBuffer) +{ + loadAllAvailableActions(); + KviActionCategory * pCat = category(szCatName); + pBuffer->setAutoDelete(false); + pBuffer->clear(); + if(!pCat)return; + KviPointerHashTableIterator it(*m_pActions); + while(KviAction * a = it.current()) + { + if(a->category() == pCat) + pBuffer->append(a); + ++it; + } +} diff --git a/src/kvirc/kernel/KviActionManager.h b/src/kvirc/kernel/KviActionManager.h new file mode 100644 index 000000000..93ca7fd94 --- /dev/null +++ b/src/kvirc/kernel/KviActionManager.h @@ -0,0 +1,118 @@ +#ifndef _KVI_ACTIONMANAGER_H_ +#define _KVI_ACTIONMANAGER_H_ +//============================================================================= +// +// File : KviActionManager.h +// Creation date : Sun 21 Nov 2004 03:37:57 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviAction.h" +#include "KviPointerHashTable.h" + +#include + +class KviActionDrawer; +class KviCustomToolBar; + +class KVIRC_API KviActionManager : public QObject +{ + friend class KviActionDrawer; + friend class KviCustomizeToolBarsDialog; + friend class KviCustomToolBar; + friend class KviMainWindow; + Q_OBJECT +public: + KviActionManager(); + ~KviActionManager(); +protected: + static KviActionManager * m_pInstance; + KviPointerHashTable * m_pActions; + KviPointerHashTable * m_pCategories; + static bool m_bCustomizingToolBars; + + // action categories + static KviActionCategory * m_pCategoryIrc; + static KviActionCategory * m_pCategoryGeneric; + static KviActionCategory * m_pCategorySettings; + static KviActionCategory * m_pCategoryScripting; + static KviActionCategory * m_pCategoryGUI; + static KviActionCategory * m_pCategoryChannel; + static KviActionCategory * m_pCategoryTools; + // internal, current toolbar to be edited (only when customizing) + static KviCustomToolBar * m_pCurrentToolBar; + bool m_bCoreActionsRegistered; +public: + static void init(); + static void done(); + static KviActionManager * instance(){ return m_pInstance; }; + static void loadAllAvailableActions(); + static bool customizingToolBars(){ return m_bCustomizingToolBars; }; + static KviActionCategory * categoryIrc(){ return m_pCategoryIrc; }; + static KviActionCategory * categoryGeneric(){ return m_pCategoryGeneric; }; + static KviActionCategory * categorySettings(){ return m_pCategorySettings; }; + static KviActionCategory * categoryScripting(){ return m_pCategoryScripting; }; + static KviActionCategory * categoryGUI(){ return m_pCategoryGUI; }; + static KviActionCategory * categoryChannel(){ return m_pCategoryChannel; }; + static KviActionCategory * categoryTools(){ return m_pCategoryTools; }; + + KviPointerHashTable * actions(){ return m_pActions; }; + KviActionCategory * category(const QString &szName); + KviPointerHashTable * categories(){ return m_pCategories; }; + + void killAllKvsUserActions(); + + static KviCustomToolBar * currentToolBar(){ return m_pCurrentToolBar; }; + KviAction * getAction(const QString &szName); + void listActionsByCategory(const QString &szCatName,KviPointerList * pBuffer); + QString nameForAutomaticAction(const QString &szTemplate); + bool coreActionExists(const QString &szName); + + void load(const QString &szFileName); + void save(const QString &szFileName); + + bool registerAction(KviAction * a); + bool unregisterAction(const QString &szName); + + void emitRemoveActionsHintRequest(); +protected: + void setCurrentToolBar(KviCustomToolBar * t); + KviAction * findAction(const QString &szName){ return m_pActions->find(szName); }; + void customizeToolBarsDialogCreated(); + void customizeToolBarsDialogDestroyed(); + void tryFindCurrentToolBar(); + void delayedRegisterAccelerators(); // this is called ONCE by KviMainWindow, at startup +protected slots: + void actionDestroyed(); +signals: + void beginCustomizeToolBars(); + void endCustomizeToolBars(); + void currentToolBarChanged(); // emitted only when customizing! + void removeActionsHintRequest(); // connected by the KviCustomToolBarDialog to flash the trashcan + // when the user tries to remove an action from the toolbar + // and it fails to drag it on the trashcan +}; + +#define ACTION_POPUP_ITEM(__name,__popup) \ + { KviAction * a = KviActionManager::instance()->getAction(__name); if(a)a->addToPopupMenu(__popup); } + + +#endif //!_KVI_ACTIONMANAGER_H_ diff --git a/src/kvirc/kernel/KviApplication.cpp b/src/kvirc/kernel/KviApplication.cpp new file mode 100644 index 000000000..8d1612d20 --- /dev/null +++ b/src/kvirc/kernel/KviApplication.cpp @@ -0,0 +1,1999 @@ +//============================================================================= +// +// File : KviApplication.cpp +// Creation date : Sun Jun 18 2000 12:39:45 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + +#define _KVI_APP_CPP_ + +#include "kvi_socket.h" +#include "KviApplication.h" +#include "kvi_debug.h" +#include "KviMainWindow.h" +#include "KviMessageBox.h" +#include "KviIconManager.h" +#include "KviInput.h" +#include "KviInputHistory.h" +#include "KviConfigurationFile.h" +#include "KviColorSelectionWindow.h" +#include "KviWindow.h" +#include "KviIrcServerDataBase.h" +#include "KviProxyDataBase.h" +#include "KviMenuBar.h" +#include "KviOptions.h" +#include "KviIrcServerParser.h" +#include "KviModuleManager.h" +#include "KviMediaType.h" +#include "KviRegisteredUserDataBase.h" +#include "KviThread.h" +#include "KviSharedFilesManager.h" +#include "kvi_confignames.h" +#include "KviWindowListBase.h" +#include "kvi_defaults.h" +#include "KviLocale.h" +#include "kvi_out.h" +#include "KviSplashScreen.h" +#include "KviNickServRuleSet.h" +#include "KviIdentityProfile.h" +#include "KviDefaultScript.h" +#include "KviXlib.h" +#include "KviTextIconManager.h" +#include "KviTextIconWindow.h" +#include "KviHistoryWindow.h" +#include "KviCtcpPageDialog.h" +#include "KviRegisteredChannel.h" +#include "KviModuleExtension.h" +#include "KviInternalCommand.h" +#include "KviFileTransfer.h" +#include "KviMircCntrl.h" +#include "KviIrcUrl.h" +#include "KviAvatarCache.h" +#include "KviActionManager.h" +#include "KviCustomToolBarManager.h" +#include "KviFileUtils.h" +#include "KviTimeUtils.h" +#include "KviStringConversion.h" +#include "KviUserIdentity.h" +#include "KviIrcView.h" +#include "KviEnvironment.h" +#include "KviAnimatedPixmapCache.h" +#include "KviKvs.h" +#include "KviKvsScript.h" +#include "KviKvsPopupManager.h" +#include "KviKvsKernel.h" +#include "KviKvsObjectController.h" +#include "KviKvsEventTriggers.h" +#include "kvi_sourcesdate.h" +#include "KviPointerHashTable.h" +#include "KviTalPopupMenu.h" + +#ifndef COMPILE_NO_IPC + #include "KviIpcSentinel.h" +#endif + +#ifdef COMPILE_SSL_SUPPORT + #include "KviSSL.h" +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef COMPILE_ON_WINDOWS + #include +#endif + +#if defined(COMPILE_KDE_SUPPORT) || defined(COMPILE_DBUS_SUPPORT) + #include +#endif + +/* +HACK These 2 hacks are defined because X11 defines Unsorted and None +which conflicts with QDir and KviApplication::KvircSubdir +DO NOT REMOVE THEM EVEN IF THEY ARE DEFINED ALSO IN KviApplication.h +*/ +#ifdef Unsorted + #undef Unsorted +#endif + +#ifdef None + #undef None +#endif + +#include + +#include // rand & srand +#include // time() in srand() + +// Global application pointer +KVIRC_API KviApplication * g_pApp = 0; + +KviConfigurationFile * g_pWinPropertiesConfig = 0; +KVIRC_API KviIrcServerDataBase * g_pServerDataBase = 0; +KVIRC_API KviProxyDataBase * g_pProxyDataBase = 0; + +// Global windows +KVIRC_API KviColorWindow * g_pColorWindow = 0; +KVIRC_API KviTextIconWindow * g_pTextIconWindow = 0; +KVIRC_API KviTalPopupMenu * g_pInputPopup = 0; +KVIRC_API QStringList * g_pRecentTopicList = 0; +KVIRC_API KviPointerHashTable * g_pGlobalWindowDict = 0; +KVIRC_API KviMediaManager * g_pMediaManager = 0; +KVIRC_API KviSharedFilesManager * g_pSharedFilesManager = 0; +KVIRC_API KviNickServRuleSet * g_pNickServRuleSet = 0; +KVIRC_API KviCtcpPageDialog * g_pCtcpPageDialog = 0; +KVIRC_API KviRegisteredChannelDataBase * g_pRegisteredChannelDataBase = 0; +KVIRC_API KviHistoryWindowWidget * g_pHistoryWindow = 0; + +// this is eventually set by libkviident +KVIRC_API int g_iIdentDaemonRunningUsers = 0; + +KVIRC_API KviSplashScreen * g_pSplashScreen = 0; + + +// Loaded and destroyed by KviIconManager +QPixmap * g_pUserChanStatePixmap = 0; +QPixmap * g_pActivityMeterPixmap = 0; + +#ifdef COMPILE_PSEUDO_TRANSPARENCY + + #include + + KVIRC_API QPixmap * g_pShadedParentGlobalDesktopBackground = 0; // the pixmap that we use for MdiManager + KVIRC_API QPixmap * g_pShadedChildGlobalDesktopBackground = 0; // the pixmap that we use for MdiChild + #if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + #include + #include + #endif +#endif + +#ifdef COMPILE_CRYPT_SUPPORT + #include "KviCryptEngine.h" + // global crypt engine manager + KVIRC_API KviCryptEngineManager * g_pCryptEngineManager = 0; +#endif + +#include + +KviApplication::KviApplication(int &argc,char ** argv) +: KviTalApplication(argc,argv) +{ + setApplicationName("KVIrc"); + setApplicationVersion(KVIRC_VERSION_RELEASE); + setOrganizationDomain("kvirc.net"); + setOrganizationName("KVIrc"); + +#ifdef COMPILE_ON_MAC + // Disable the native menubar on MacOSX as in Qt 4.6 it's quite buggy and + // *very* often crashes in QMenuBar::macUpdateMenuBar()->QAction::isVisible(). + // FIXME: Check it with later Qt versions + KviEnvironment::setVariable("QT_MAC_NO_NATIVE_MENUBAR","1"); +#endif //COMPILE_ON_MAC + + // Ok...everything begins here + g_pApp = this; + m_szConfigFile = QString(); + m_bCreateConfig = false; + m_bShowSplashScreen = true; + m_bUpdateGuiPending = false; + m_pPendingAvatarChanges = NULL; + m_pRecentChannelDict = NULL; +#ifndef COMPILE_NO_IPC + m_pIpcSentinel = NULL; +#endif + m_iHeartbeatTimerId = -1; + m_fntDefaultFont = font(); + m_bSetupDone = false; + m_bClosingDown = false; + kvi_socket_flushTrafficCounters(); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + m_bPortable = KviFileUtils::fileExists(g_pApp->applicationDirPath()+KVI_PATH_SEPARATOR_CHAR+"portable"); + //workaround for #957 + QApplication::setEffectEnabled(Qt::UI_FadeMenu, FALSE); +#endif + // workaround for gtk+ style forcing a crappy white background (ticket #777, #964, #1009, ..) + if(QString("QGtkStyle").compare(qApp->style()->metaObject()->className())==0) + { + setStyle(new QCleanlooksStyle()); + setPalette(style()->standardPalette()); + } + +} + +void KviApplication::setup() +{ + // Here we start up all the substystems. + // This is a really critical phase since in general subsystems depend + // on each other and we must activate them in the right order. + // Don't move stuff around unless you really know what you're doing. + + // Initialize the random number generator + ::srand(::time(0)); + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + // setup winsock.dll + WSADATA w; + WSAStartup(MAKELONG((unsigned short)2,(unsigned short)0),&w); +#endif + +#ifndef COMPILE_NO_IPC + // Create this very early + // FIXME: this is still not early enough... we actually HAVE race conditions (should use a file for locking this ?) + createIpcSentinel(); +#endif + + // Initialize the thread manager early + KviThreadManager::globalInit(); + +#ifdef COMPILE_SSL_SUPPORT + KviSSL::globalInit(); +#endif + + // Setup our filesystem and initalize locale + loadDirectories(); + KviStringConversion::init(m_szGlobalKvircDir,m_szLocalKvircDir); + + g_pIconManager = new KviIconManager(); + + // add KVIrc common dirs to QT searchpath + QString szPath; + getLocalKvircDirectory(szPath,None,"avatars"); + QDir::addSearchPath("avatars",szPath); + getLocalKvircDirectory(szPath,None,"pics"); + QDir::addSearchPath("pics",szPath); + getLocalKvircDirectory(szPath,None,"audio"); + QDir::addSearchPath("audio",szPath); + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + //need to load image plugins:( + QString szPluginsDir; + getGlobalKvircDirectory(szPluginsDir,None,"qt-plugins/"); + setLibraryPaths(QStringList(szPluginsDir)); + //KviMessageBox::information(libraryPaths().join(";")); + //qDebug("%1",loader.isLoaded()); +#endif + + // check if we want to permanently disable the splash screen + // we do it once for every version: the user should see the new splash screens at least once + QString szSplashDisableFile; + getLocalKvircDirectory(szSplashDisableFile,Pics,"disable-splash." KVI_VERSION); + + if(KviFileUtils::fileExists(szSplashDisableFile)) + m_bShowSplashScreen = false; + + // Now we can create the splash screen (we can locate the splash image) + if(m_bShowSplashScreen) + createSplashScreen(); + + KVI_SPLASH_SET_PROGRESS(0) + + // Make sure that the C strings are translated to utf8 + // This is a fallback solution anyway: we should use the appropriate + // encoding every time. + QTextCodec * pUTF8Codec = KviLocale::codecForName("UTF-8"); + if(pUTF8Codec) + QTextCodec::setCodecForCStrings(pUTF8Codec); + else + qDebug("Aaargh... have no UTF-8 codec?"); + + QString szTmp; + + KVI_SPLASH_SET_PROGRESS(1) + + // Initialize the scripting engine + KviKvs::init(); + + KVI_SPLASH_SET_PROGRESS(2) + + // Initialize the action manager + KviActionManager::init(); + + KVI_SPLASH_SET_PROGRESS(3) + + // Create the module manager early: so the other managers can load modules + g_pModuleExtensionManager = new KviModuleExtensionManager(); + + KVI_SPLASH_SET_PROGRESS(4); + + g_pModuleManager = new KviModuleManager(); + + KVI_SPLASH_SET_PROGRESS(5) + + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_USERACTIONS)) + KviActionManager::instance()->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(8); + + // Initialize and load the identities + KviUserIdentityManager::init(); + + KVI_SPLASH_SET_PROGRESS(9); + + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_IDENTITIES)) + KviUserIdentityManager::instance()->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(12); + + KviAnimatedPixmapCache::init(); + + KVI_SPLASH_SET_PROGRESS(13); + + // Load the remaining configuration + // Note that loadOptions() assumes that the current progress is 12 and + // will bump it up to 45 in small steps + loadOptions(); + + KVI_SPLASH_SET_PROGRESS(47) + + // set the global font if needed + updateApplicationFont(); + +#ifdef COMPILE_PSEUDO_TRANSPARENCY + updatePseudoTransparency(); +#endif + + KVI_SPLASH_SET_PROGRESS(48) + + // Load the win properties config + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_WINPROPERTIES); + g_pWinPropertiesConfig = new KviConfigurationFile(szTmp,KviConfigurationFile::ReadWrite); + + KVI_SPLASH_SET_PROGRESS(50) + + // Load the server database + g_pServerDataBase = new KviIrcServerDataBase(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_SERVERDB)) + g_pServerDataBase->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(53) + + // Load the proxy database + g_pProxyDataBase = new KviProxyDataBase(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_PROXYDB)) + g_pProxyDataBase->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(54) + + // Event manager + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_EVENTS)) + KviKvs::loadAppEvents(szTmp); + + KVI_SPLASH_SET_PROGRESS(59) + + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_RAWEVENTS)) + KviKvs::loadRawEvents(szTmp); + + KVI_SPLASH_SET_PROGRESS(62) + + // Popup manager + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_POPUPS)) + KviKvs::loadPopups(szTmp); + + KVI_SPLASH_SET_PROGRESS(67) + + KviCustomToolBarManager::init(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_CUSTOMTOOLBARS)) + KviCustomToolBarManager::instance()->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(70) + + // Alias manager + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_ALIASES)) + KviKvs::loadAliases(szTmp); + + KVI_SPLASH_SET_PROGRESS(75) + + // Script addons manager (this in fact has delayed loading, so we don't even care + // about showing up an entry in the splash screen) + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_SCRIPTADDONS)) + KviKvs::loadScriptAddons(szTmp); + + KVI_SPLASH_SET_PROGRESS(77) + + g_pTextIconManager = new KviTextIconManager(); + g_pTextIconManager->load(); + + KVI_SPLASH_SET_PROGRESS(80) + + // load the recent data lists + g_pRecentTopicList = new QStringList(); + //g_pBookmarkList = new QStringList(); + loadRecentEntries(); + + KVI_SPLASH_SET_PROGRESS(81) + + // media manager + g_pMediaManager = new KviMediaManager(); + g_pMediaManager->lock(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_MEDIATYPES)) + g_pMediaManager->load(szTmp); + g_pMediaManager->unlock(); + + KVI_SPLASH_SET_PROGRESS(82) + + // registered user data base + g_pRegisteredUserDataBase = new KviRegisteredUserDataBase(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_REGUSERDB)) + g_pRegisteredUserDataBase->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(83) + + // registered channel data base + g_pRegisteredChannelDataBase = new KviRegisteredChannelDataBase(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_REGCHANDB)) + g_pRegisteredChannelDataBase->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(84) + + // file trader + g_pSharedFilesManager = new KviSharedFilesManager(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_SHAREDFILES)) + g_pSharedFilesManager->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(85) + + // nick serv data base + g_pNickServRuleSet = new KviNickServRuleSet(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_NICKSERVDATABASE)) + g_pNickServRuleSet->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(86) + + // Identity profiles database + KviIdentityProfileSet::init(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_PROFILESDATABASE)) + KviIdentityProfileSet::instance()->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(87) + + KviAvatarCache::init(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_AVATARCACHE)) + KviAvatarCache::instance()->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(88) + + KviInputHistory::init(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_INPUTHISTORY)) + KviInputHistory::instance()->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(89) + + KviDefaultScriptManager::init(); + if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_DEFAULTSCRIPT)) + KviDefaultScriptManager::instance()->load(szTmp); + + KVI_SPLASH_SET_PROGRESS(90) + + // Eventually initialize the crypt engine manager +#ifdef COMPILE_CRYPT_SUPPORT + g_pCryptEngineManager = new KviCryptEngineManager(); +#endif + + //g_pGarbageCollector = new KviGarbageCollector(); + + // and the input popup + g_pInputPopup = new KviTalPopupMenu(); + + // create the server parser + g_pServerParser = new KviIrcServerParser(); + + KVI_SPLASH_SET_PROGRESS(91) + + // Global window dictionary + g_pGlobalWindowDict = new KviPointerHashTable(41); + g_pGlobalWindowDict->setAutoDelete(false); + // Script object controller + //g_pScriptObjectController = new KviScriptObjectController(); gone + + KVI_SPLASH_SET_PROGRESS(92) + + QString szStylesheetFile; + getGlobalKvircDirectory(szStylesheetFile,Config,"style.css"); + if(KviFileUtils::fileExists(szStylesheetFile)) + { + QString szStyleData; + KviFileUtils::readFile(szStylesheetFile,szStyleData); + szStyleData.replace("global://",m_szGlobalKvircDir); + szStyleData.replace("local://",m_szLocalKvircDir); + setStyleSheet(szStyleData); + } + + // create the frame window, we're almost up and running... + createFrame(); + + // ok, we also have an UI now + + // check if this is the first time this version of KVIrc runs... + if(firstTimeRun()) + { + // Finish the setup... + setupFinish(); + } + + // hello world! + m_bSetupDone = true; + + // We're REALLY up and running! + // kill the splash screen + + KVI_SPLASH_SET_PROGRESS(100) + //KVI_SPLASH_SET_TEXT(__tr2qs("Have fun! :)")) + + if(KVI_OPTION_BOOL(KviOption_boolShowServersConnectDialogOnStart)) + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_SERVERSJOIN_OPEN); + + destroySplashScreen(); + + // check if we're in trouble... + checkSuggestRestoreDefaultScript(); + + // start our heartbeat now + m_iHeartbeatTimerId = startTimer(1000); +} + +void KviApplication::frameDestructorCallback() +{ + // here we should kill anything that depends on g_pFrame, g_pActiveWindow and related being non zero... + + // kill all the objects, while we have windows... + if(KviKvsKernel::instance()) + { + if(KviKvsKernel::instance()->objectController()) + { + KviKvsKernel::instance()->objectController()->clearInstances(); + } + } +} + +KviApplication::~KviApplication() +{ + // Another critical phase. + // We shutdown our subsystems in the right order here. + + m_bClosingDown = true; + +#ifndef COMPILE_NO_IPC + destroyIpcSentinel(); +#endif + + if(g_pSplashScreen) + delete g_pSplashScreen; + if(g_pCtcpPageDialog) + delete g_pCtcpPageDialog; + + // if we still have a frame: kill it + if(g_pFrame) + delete g_pFrame; + g_pActiveWindow = 0; // .. but it should be already 0 anyway + + // execute pending deletes (this may still contain some UI elements) + //delete g_pGarbageCollector; + + if(!m_bSetupDone) + return; // killed with IPC (nothing except the m_pFrameList was created yet) + + KviFileTransferManager::cleanup(); + + // No more events are triggered from now on and no KVS commands are executed + + // Dangerous part.... we're unloading all the modules + // We need to unload them early since they may use other subsystems + // that we are going to kill now. + delete g_pModuleManager; + delete g_pModuleExtensionManager; + // No more external modules exist: all that happens from now is generated + // from inside the kvirc core. + + // We should have almost no UI here: only certain dialogs or popup windows may + // still exist: they should be harmless tough. + saveOptions(); + saveIdentities(); + KviUserIdentityManager::done(); + if(m_pRecentChannelDict) + delete m_pRecentChannelDict; + // now kill the stuff that the frame depends on + saveIrcServerDataBase(); + delete g_pServerDataBase; + saveProxyDataBase(); + delete g_pProxyDataBase; + delete g_pWinPropertiesConfig; + saveTextIcons(); + if(g_pTextIconWindow)delete g_pTextIconWindow; + delete g_pTextIconManager; + delete g_pIconManager; + delete g_pServerParser; + saveMediaTypes(); + delete g_pMediaManager; + saveRecentEntries(); + saveAvatarCache(); + KviAvatarCache::done(); + //delete g_pBookmarkList; + delete g_pRecentTopicList; + saveRegisteredUsers(); + delete g_pRegisteredUserDataBase; + saveRegisteredChannels(); + delete g_pRegisteredChannelDataBase; + saveNickServ(); + delete g_pNickServRuleSet; + saveIdentityProfiles(); + KviIdentityProfileSet::done(); + saveDefaultScripts(); + KviDefaultScriptManager::done(); + saveSharedFiles(); + delete g_pSharedFilesManager; + saveAppEvents(); + saveRawEvents(); + saveToolBars(); + KviCustomToolBarManager::done(); + savePopups(); + saveAliases(); + delete g_pGlobalWindowDict; + saveScriptAddons(); + // kill the remaining resources + delete g_pColorWindow; + if(g_pHistoryWindow)delete g_pHistoryWindow; + saveInputHistory(); + KviInputHistory::done(); + delete g_pInputPopup; + //delete g_pScriptObjectController; +#ifdef COMPILE_CRYPT_SUPPORT + delete g_pCryptEngineManager; +#endif +#ifdef COMPILE_PSEUDO_TRANSPARENCY + destroyPseudoTransparency(); +#endif + if(m_pPendingAvatarChanges) + delete m_pPendingAvatarChanges; + KviAnimatedPixmapCache::done(); + // Kill the thread manager.... all the slave threads should have been already terminated ... +#ifdef COMPILE_SSL_SUPPORT + KviSSL::globalDestroy(); +#endif + KviThreadManager::globalDestroy(); + // kill the scripting engine + KviKvs::done(); + // shut up the action manager + saveActions(); + KviActionManager::done(); + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + WSACleanup(); +#endif + + KviLocale::done(this); + + // goodbye cruel world... +} + +static int g_iGloballyUniqueId = 0; + +int KviApplication::getGloballyUniqueId() +{ + g_iGloballyUniqueId++; + return g_iGloballyUniqueId; +} + +void KviApplication::notifierMessage(KviWindow * pWnd, int iIconId, const QString & szMsg, unsigned int uMessageLifetime) +{ +#if defined(COMPILE_KDE_SUPPORT) || defined(COMPILE_DBUS_SUPPORT) + if(KVI_OPTION_BOOL(KviOption_boolUseDBusNotifier)) + { + if(!pWnd) + return; + + QString szText = __tr2qs("Message arriving from %1:\n\n").arg(pWnd->target()); + szText += KviMircCntrl::stripControlBytes(szMsg); + + // org.freedesktop.Notifications.Notify + QVariantList args; + args << QString("KVIrc"); // application name + args << QVariant(QVariant::UInt); // notification id + args << QString(g_pIconManager->getSmallIconName(16)); // application icon + args << __tr2qs("KVIrc messaging system"); // summary text + args << szText; // detailed text + args << QStringList(); // actions, optional + args << QVariantMap(); // hints, optional + args << (int)uMessageLifetime*1000; // timeout in msecs + + QDBusInterface * pNotify = new QDBusInterface("org.freedesktop.Notifications","/org/freedesktop/Notifications","org.freedesktop.Notifications",QDBusConnection::sessionBus(),this); + QDBusMessage reply = pNotify->callWithArgumentList(QDBus::Block,"Notify",args); + if(reply.type() == QDBusMessage::ErrorMessage) + { + QDBusError err = reply; + qDebug("DBus notify error\nID: %u\nName: %s\nMessage: %s\n",reply.arguments().first().toUInt(),qPrintable(err.name()),qPrintable(err.message())); + } + } else { +#endif + KviModule * m = g_pModuleManager->getModule("notifier"); + if(!m) + return; + + KviNotifierMessageParam s; + s.pWindow = pWnd; + s.szIcon.sprintf("%d",iIconId); + s.szMessage = szMsg; + s.uMessageLifetime = uMessageLifetime; + + m->ctrl("notifier::message",(void *)&s); +#if defined(COMPILE_KDE_SUPPORT) || defined(COMPILE_DBUS_SUPPORT) + } +#endif +} + +QTextCodec * KviApplication::defaultTextCodec() +{ + QTextCodec * pCodec = 0; + if(!KVI_OPTION_STRING(KviOption_stringDefaultTextEncoding).isEmpty()) + { + pCodec = KviLocale::codecForName(KVI_OPTION_STRING(KviOption_stringDefaultTextEncoding).toLatin1()); + if(pCodec) + return pCodec; + } + pCodec = QTextCodec::codecForLocale(); + if(pCodec) + return pCodec; + pCodec = KviLocale::codecForName("UTF-8"); + if(!pCodec) + qDebug("KviApplication::defaultTextCodec(): cannot find a suitable text codec for locale :/"); + return pCodec; +} + +QTextCodec * KviApplication::defaultSrvCodec() +{ + QTextCodec * pCodec = 0; + if(!KVI_OPTION_STRING(KviOption_stringDefaultSrvEncoding).isEmpty()) + { + pCodec = KviLocale::codecForName(KVI_OPTION_STRING(KviOption_stringDefaultSrvEncoding).toLatin1()); + if(pCodec) + return pCodec; + } + pCodec = QTextCodec::codecForLocale(); + if(pCodec) + return pCodec; + pCodec = KviLocale::codecForName("UTF-8"); + if(!pCodec) + qDebug("KviApplication::defaultSrcCodec(): cannot find a suitable text codec for locale :/"); + return pCodec; +} + +void KviApplication::loadDefaultScript(QString szItem) +{ + QString szCmd; + + if(szItem.isEmpty()) + szItem = "default"; + + getGlobalKvircDirectory(szCmd,KviApplication::DefScript,QString("%1.kvs").arg(szItem)); + szCmd.prepend("parse \""); + szCmd.append("\""); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + szCmd.replace("\\","\\\\"); +#endif + KviKvsScript::run(szCmd,g_pFrame->firstConsole()); +} + +void KviApplication::checkSuggestRestoreDefaultScript() +{ + static bool bSuggestedOnce = false; + if(KVI_OPTION_BOOL(KviOption_boolDoNotSuggestRestoreDefaultScript)) + return; + if(bSuggestedOnce) + return; // already suggested in this kvirc session + + // first: check if the user configuration has ever been updated to the current version + if(!KviDefaultScriptManager::instance()->isDefscriptUpToDate()) + { + switch( + QMessageBox::question(0,__tr2qs("Update default scripts"), + __tr2qs("Hi!

" \ + "It seems that you have just upgraded KVirc from a previous version.

" \ + "The KVIrc default scripts needs to be updated too, to play nice with your fresh new KVIrc.
" \ + "You may want to avoid this update if you plan to revert to a previous KVIrc version soon," \ + "or if you have created a lot of custom scripts and want to stay safe and avoid any deletion or overwrite.
" \ + "If you want to update the default scripts, i can restore the new default script for you.
" \ + "Do you want the default script to be restored?

"), + __tr2qs("No and Don't Ask Me Again"),__tr2qs("No"),__tr2qs("Yes"),1,1) + ) + { + case 0: + KVI_OPTION_BOOL(KviOption_boolDoNotSuggestRestoreDefaultScript) = true; + return; + break; + case 1: + // we want to execute the next checks, don't return now + break; + default: + restoreDefaultScript(); + // we want to execute the next checks after the attempted restore, don't return now + break; + } + } + + //second, check for some common corruptions in scripts + int iScore = 0; + + if(KviCustomToolBarManager::instance()->descriptorCount() < 1) + iScore += 100; // straight suggest + else if(KviKvsPopupManager::instance()->popupCount() < 1) + iScore += 100; // straight suggest + else { + // other stuff is not that critical + if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnChannelNickPopupRequest)) + iScore += 80; + if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnDCCChatPopupRequest)) + iScore += 20; + if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnConsolePopupRequest)) + iScore += 20; + if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnChannelPopupRequest)) + iScore += 20; + if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnChannelNickPopupRequest)) + iScore += 20; + if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnQueryPopupRequest)) + iScore += 20; + if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnQueryNickPopupRequest)) + iScore += 20; + if(KviCustomToolBarManager::instance()->descriptorCount() < 4) + iScore += 20; + if(KviKvsPopupManager::instance()->popupCount() < 3) + iScore += 20; + if(KviCustomToolBarManager::instance()->visibleToolBarCount() < 2) + { + iScore += 20; + if(KviCustomToolBarManager::instance()->visibleToolBarCount() < 1) + iScore += 20; + } + } + + if(iScore < 100) + return; + + bSuggestedOnce = true; + + switch( + QMessageBox::question(0,__tr2qs("Installation problems?"), + __tr2qs("Ooops...

" \ + "There are some reasons that make me think that your KVIrc installation is incomplete.

" \ + "I might be wrong, but you seem to miss some of the features that the default KVIrc script provides." \ + "This may happen because you have upgraded to an unstable svn version, " \ + "because you have accidentally deleted or damaged your configuration files, " \ + "because you have installed an incomplete script " \ + "or because you have hit a bug in KVIrc.

" \ + "I can repeat the installation of the default script in order " \ + "to restore the missing features.
" \ + "Do you want the default script to be restored?

" \ + "Hint: If you're a scripter and have intentionally removed some of the scripting features " \ + "then you may safely click on \"No and Don't Ask Me Again\", otherwise it might be " \ + "a good idea to click \"Yes\". If you still want to choose \"No\" you can always restore the " \ + "default script by choosing the appropriate entry from the \"Scripting\" menu."), + __tr2qs("No and Don't Ask Me Again"),__tr2qs("No"),__tr2qs("Yes"),1,1) + ) + { + case 0: + KVI_OPTION_BOOL(KviOption_boolDoNotSuggestRestoreDefaultScript) = true; + return; + break; + case 1: + return; + break; + default: + restoreDefaultScript(); + break; + } +} + +void KviApplication::restoreDefaultScript() +{ + KviDefaultScriptManager::instance()->restore(); +} + +#ifndef COMPILE_NO_IPC +void KviApplication::createIpcSentinel() +{ + m_pIpcSentinel = new KviIpcSentinel(); +} + +void KviApplication::destroyIpcSentinel() +{ + if(m_pIpcSentinel) + delete m_pIpcSentinel; + m_pIpcSentinel = 0; +} + +void KviApplication::ipcMessage(char * pcMessage) +{ + if(!g_pFrame) + return; + KviConsole * pConsole = g_pFrame->firstConsole(); + if(!pConsole) + return; + if(_OUTPUT_VERBOSE) + { + KviCString szCmd = pcMessage; + if(szCmd.len() > 30) + szCmd.cutRight(szCmd.len() - 30); + int iIdx = szCmd.findFirstIdx('\n'); + if(iIdx != -1) + szCmd.cutRight(szCmd.len() - (iIdx + 1)); + pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Remote command received (%s ...)"),szCmd.ptr()); + } + KviKvsScript::run(pcMessage,pConsole); +} +#endif // COMPILE_NO_IPC + +void KviApplication::createSplashScreen() +{ + g_pSplashScreen = new KviSplashScreen(); + g_pSplashScreen->show(); +} + +void KviApplication::destroySplashScreen() +{ + if(g_pSplashScreen) + g_pSplashScreen->die(); +} + +void KviApplication::setAvatarFromOptions() +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) + { + ((KviConsole *)it.current())->setAvatarFromOptions(); + } + ++it; + } + +} + +void KviApplication::setAvatarOnFileReceived(KviConsole * pConsole, const QString & szRemoteUrl, const QString & szNick, const QString & szUser, const QString & szHost) +{ + if(!m_pPendingAvatarChanges) + { + m_pPendingAvatarChanges = new KviPointerList; + m_pPendingAvatarChanges->setAutoDelete(true); + } + + if(m_pPendingAvatarChanges->count() >= KVI_MAX_PENDING_AVATARS) // can't be... + { + m_pPendingAvatarChanges->removeFirst(); // kill the first entry + } + + KviPendingAvatarChange * pAvatar = new KviPendingAvatarChange; + pAvatar->pConsole = pConsole; + pAvatar->szRemoteUrl = szRemoteUrl; + pAvatar->szNick = szNick; + pAvatar->szUser = szUser; + pAvatar->szHost = szHost; + + m_pPendingAvatarChanges->append(pAvatar); +} + +KviPendingAvatarChange * KviApplication::findPendingAvatarChange(KviConsole * pConsole, const QString & szNick, const QString & szRemoteUrl) +{ + if(!m_pPendingAvatarChanges) + return 0; + + KviPendingAvatarChange * pAvatar; + + for(pAvatar = m_pPendingAvatarChanges->first(); pAvatar; pAvatar = m_pPendingAvatarChanges->next()) + { + if(!pConsole || (pAvatar->pConsole == pConsole)) + { + if(szNick.isNull() || (szNick == pAvatar->szNick)) + { + if(szRemoteUrl == pAvatar->szRemoteUrl) + return pAvatar; + } + } + } + + return 0; +} + +void KviApplication::fileDownloadTerminated(bool bSuccess, const QString & szRemoteUrl, const QString & szLocalFileName, const QString & szNick, const QString & szError, bool bQuiet) +{ + KviPendingAvatarChange * pAvatar; + + if(m_pPendingAvatarChanges) + pAvatar = findPendingAvatarChange(0,szNick,szRemoteUrl); + else + pAvatar = 0; + + if(!pAvatar) + { + // signal dcc completion only for NON-avatars + // FIXME: This option is misnamed and misplaced in the options dialog :( + // it seems to refer only to DCC while it refers to any file transfer + if(KVI_OPTION_BOOL(KviOption_boolNotifyDccSendSuccessInNotifier) && (!bQuiet)) + { + if(!g_pActiveWindow) + return; + if(g_pActiveWindow->hasAttention()) + return; + QString szMsg; + int iIconId; + if(!bSuccess) + { + iIconId = KVI_SMALLICON_DCCERROR; + if(szNick.isEmpty()) + szMsg = __tr2qs("File download failed"); + else + szMsg = __tr2qs("File download from %1 failed").arg(szNick); + szMsg += ": "; + szMsg += szError; + szMsg += " ("; + szMsg += szLocalFileName; + szMsg += ")"; + } else { + iIconId = KVI_SMALLICON_DCCMSG; + if(szNick.isEmpty()) + szMsg = __tr2qs("File download successfully complete"); + else + szMsg = __tr2qs("File download from %1 successfully complete").arg(szNick); + szMsg += " ("; + szMsg += szLocalFileName; + szMsg += ")"; + } + notifierMessage(0,iIconId,Qt::escape(szMsg),KVI_OPTION_UINT(KviOption_uintNotifierAutoHideTime)); + } + return; + } + + if(bSuccess) + { + if(windowExists(pAvatar->pConsole)) + { + pAvatar->pConsole->setAvatar(pAvatar->szNick,pAvatar->szUser,pAvatar->szHost,szLocalFileName,KviQString::equalCIN("http://",szRemoteUrl,7) ? szRemoteUrl : QString()); + } + } else { + if((!_OUTPUT_MUTE) && (!bQuiet)) + { + pAvatar->pConsole->output(KVI_OUT_AVATAR,__tr2qs("Avatar download failed for %Q!%Q@%Q and url %Q: %Q"), + &(pAvatar->szNick),&(pAvatar->szUser),&(pAvatar->szHost),&(szRemoteUrl),&(szError)); + } + } + + m_pPendingAvatarChanges->removeRef(pAvatar); + + if(m_pPendingAvatarChanges->count() == 0) + { + delete m_pPendingAvatarChanges; + m_pPendingAvatarChanges = 0; + } +} + +#ifdef COMPILE_PSEUDO_TRANSPARENCY +void KviApplication::destroyPseudoTransparency() +{ + if(g_pShadedParentGlobalDesktopBackground) + { + delete g_pShadedParentGlobalDesktopBackground; + g_pShadedParentGlobalDesktopBackground = 0; + } + if(g_pShadedChildGlobalDesktopBackground) + { + delete g_pShadedChildGlobalDesktopBackground; + g_pShadedChildGlobalDesktopBackground = 0; + } +} + +void KviApplication::triggerUpdatePseudoTransparency() +{ + if(m_bUpdatePseudoTransparencyPending) + return; + m_bUpdatePseudoTransparencyPending = true; + QTimer::singleShot(0,this,SLOT(updatePseudoTransparency())); +} + +// +// This function is taken from the KDE3 kimageeffect.cpp +// The authors listed at the top of the file are :) +// Copyright (C) 1998, 1999 Christian Tibirna +// (C) 1998, 1999 Daniel M. Duley +// (C) 1998, 1999 Dirk A. Mueller +// (C) 2000 Josef Weidendorfer +// + +QImage & kimageeffect_fade(QImage &img,float val,const QColor &color) +{ + if(img.width() == 0 || img.height() == 0)return img; + + // We don't handle bitmaps + if (img.depth() == 1)return img; + + unsigned char tbl[256]; + for (int i=0; i<256; i++)tbl[i] = (int) (val * i + 0.5); + + int red = color.red(); + int green = color.green(); + int blue = color.blue(); + + QRgb col; + int r, g, b, cr, cg, cb; + + if (img.depth() <= 8) + { + // pseudo color + int c = img.numColors(); + for(int i=0; i red)r = cr - tbl[cr - red]; + else r = cr + tbl[red - cr]; + if (cg > green)g = cg - tbl[cg - green]; + else g = cg + tbl[green - cg]; + if (cb > blue)b = cb - tbl[cb - blue]; + else b = cb + tbl[blue - cb]; + img.setColor(i, qRgb(r, g, b)); + } + } else { + // truecolor + int h = img.height(); + int w = img.width(); + for(int y=0; y red)r = cr - tbl[cr - red]; + else r = cr + tbl[red - cr]; + if (cg > green)g = cg - tbl[cg - green]; + else g = cg + tbl[green - cg]; + if (cb > blue)b = cb - tbl[cb - blue]; + else b = cb + tbl[blue - cb]; + *data++ = qRgb(r, g, b); + } + } + } + return img; +} + +void KviApplication::createGlobalBackgrounds(QPixmap * pix) +{ + // create shaded copies... + if(g_pShadedParentGlobalDesktopBackground) + delete g_pShadedParentGlobalDesktopBackground; + if(g_pShadedChildGlobalDesktopBackground) + delete g_pShadedChildGlobalDesktopBackground; + g_pShadedParentGlobalDesktopBackground = new QPixmap(); + g_pShadedChildGlobalDesktopBackground = new QPixmap(); + QImage img = pix->toImage(); + // play with the fade factors + KVI_OPTION_UINT(KviOption_uintGlobalTransparencyParentFadeFactor) %= 100; + if(KVI_OPTION_UINT(KviOption_uintGlobalTransparencyParentFadeFactor) > 0) + { + *g_pShadedParentGlobalDesktopBackground = QPixmap::fromImage( + kimageeffect_fade(img, + (float)((float)KVI_OPTION_UINT(KviOption_uintGlobalTransparencyParentFadeFactor) / (float)100), + KVI_OPTION_COLOR(KviOption_colorGlobalTransparencyFade))); + } + KVI_OPTION_UINT(KviOption_uintGlobalTransparencyChildFadeFactor) %= 100; + if(KVI_OPTION_UINT(KviOption_uintGlobalTransparencyChildFadeFactor) > 0) + { + *g_pShadedChildGlobalDesktopBackground = QPixmap::fromImage( + kimageeffect_fade(img, + (float)((float)KVI_OPTION_UINT(KviOption_uintGlobalTransparencyChildFadeFactor) / (float)100), + KVI_OPTION_COLOR(KviOption_colorGlobalTransparencyFade))); + } + if(g_pFrame + )g_pFrame->updatePseudoTransparency(); +} +#endif //COMPILE_PSEUDO_TRANSPARENCY + + +void KviApplication::updatePseudoTransparency() +{ +#ifdef COMPILE_PSEUDO_TRANSPARENCY + m_bUpdatePseudoTransparencyPending = false; + if(KVI_OPTION_BOOL(KviOption_boolUseGlobalPseudoTransparency)) + { +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + //TODO this has been tested only under mingw! + //TODO this needs winxp: #if (_WIN32_WINNT >= 0x0501) + if(KVI_OPTION_BOOL(KviOption_boolUseWindowsDesktopForTransparency)) + { + QSize size = g_pApp->desktop()->screenGeometry(g_pApp->desktop()->primaryScreen()).size(); + // get the Program Manager + HWND hWnd = FindWindow ("Progman", "Program Manager"); + // Create and setup bitmap + HDC bitmap_dc = CreateCompatibleDC(qt_win_display_dc()); + HBITMAP bitmap = CreateCompatibleBitmap(qt_win_display_dc(), size.width(), size.height()); + HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap); + + PrintWindow (hWnd, bitmap_dc, 0); + + SelectObject(bitmap_dc, null_bitmap); + DeleteDC(bitmap_dc); + + QPixmap pix = QPixmap::fromWinHBITMAP(bitmap); + + DeleteObject(bitmap); + + createGlobalBackgrounds(&pix); + } else +#endif // COMPILE_ON_WINDOWS || COMPILE_ON_MINGW + + if(KVI_OPTION_PIXMAP(KviOption_pixmapGlobalTransparencyBackground).pixmap()) + { + createGlobalBackgrounds(KVI_OPTION_PIXMAP(KviOption_pixmapGlobalTransparencyBackground).pixmap()); + } else { + //destroy pseudo transparency pixmaps + destroyPseudoTransparency(); + //if we get here, no pseudo transparency method can be used / is enabled. +#ifdef COMPILE_X11_SUPPORT + //under x11, we still have to check real transparency methods + if(!KVI_OPTION_BOOL(KviOption_boolUseCompositingForTransparency)) + { + //real transparency is off => turn off transparency support at all + KVI_OPTION_BOOL(KviOption_boolUseGlobalPseudoTransparency) = false; + } +#else + // on other platforms, no way to proceed + KVI_OPTION_BOOL(KviOption_boolUseGlobalPseudoTransparency) = false; +#endif // COMPILE_X11_SUPPORT + } + } else { + //transparency is disabled + + //destroy pseudo transparency pixmaps + destroyPseudoTransparency(); + //make sure real transparency is disabled + KVI_OPTION_BOOL(KviOption_boolUseCompositingForTransparency) = false; + + //update widgets + if(g_pFrame) + g_pFrame->updatePseudoTransparency(); + } +#endif //COMPILE_PSEUDO_TRANSPARENCY +} + +void KviApplication::triggerUpdateGui() +{ + if(m_bUpdateGuiPending) + return; + m_bUpdateGuiPending = true; + QTimer::singleShot(0,this,SLOT(updateGui())); +} + +void KviApplication::updateGui() +{ + m_bUpdateGuiPending = false; + g_pFrame->applyOptions(); +} + +void KviApplication::updateApplicationFont() +{ + if(KVI_OPTION_BOOL(KviOption_boolUseGlobalApplicationFont)) + { + setFont(KVI_OPTION_FONT(KviOption_fontApplication)); + if(g_pFrame) + g_pFrame->setFont(font()); + } else { + setFont(m_fntDefaultFont); + if(g_pFrame) + g_pFrame->setFont(m_fntDefaultFont); + } +} + +void KviApplication::loadRecentEntries() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_RECENT); + KviConfigurationFile cfg(szTmp,KviConfigurationFile::Read); + *g_pRecentTopicList = cfg.readStringListEntry("RecentTopicList",QStringList()); + //*g_pBookmarkList = cfg.readStringListEntry("Bookmarks",QStringList()); +} + +void KviApplication::saveRecentEntries() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_RECENT); + KviConfigurationFile cfg(szTmp,KviConfigurationFile::Write); + cfg.writeEntry("RecentTopicList",*g_pRecentTopicList); + //cfg.writeEntry("Bookmarks",*g_pBookmarkList); +} + +void KviApplication::saveAvatarCache() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_AVATARCACHE); + KviAvatarCache::instance()->save(szTmp); +} + +void KviApplication::saveToolBars() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_CUSTOMTOOLBARS); + KviCustomToolBarManager::instance()->save(szTmp); +} + +void KviApplication::savePopups() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_POPUPS); + KviKvs::savePopups(szTmp); +} + +void KviApplication::saveInputHistory() +{ + if(KVI_OPTION_BOOL(KviOption_boolEnableInputHistory)) + { + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_INPUTHISTORY); + KviInputHistory::instance()->save(szTmp); + } +} + +void KviApplication::saveAliases() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_ALIASES); + KviKvs::saveAliases(szTmp); +} + +void KviApplication::saveScriptAddons() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_SCRIPTADDONS); + KviKvs::saveScriptAddons(szTmp); +} + +void KviApplication::saveTextIcons() +{ + g_pTextIconManager->save(); +} + +void KviApplication::saveAppEvents() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_EVENTS); + KviKvs::saveAppEvents(szTmp); +} + +void KviApplication::saveRawEvents() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_RAWEVENTS); + KviKvs::saveRawEvents(szTmp); +} + +void KviApplication::saveMediaTypes() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_MEDIATYPES); + g_pMediaManager->lock(); + g_pMediaManager->save(szTmp); + g_pMediaManager->unlock(); +} + +void KviApplication::saveIrcServerDataBase() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_SERVERDB); + g_pServerDataBase->save(szTmp); +} + +void KviApplication::saveProxyDataBase() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_PROXYDB); + g_pProxyDataBase->save(szTmp); +} + +void KviApplication::saveRegisteredUsers() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_REGUSERDB); + g_pRegisteredUserDataBase->save(szTmp); +} + +void KviApplication::saveRegisteredChannels() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_REGCHANDB); + g_pRegisteredChannelDataBase->save(szTmp); +} + +void KviApplication::saveNickServ() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_NICKSERVDATABASE); + g_pNickServRuleSet->save(szTmp); +} + +void KviApplication::saveIdentityProfiles() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_PROFILESDATABASE); + KviIdentityProfileSet::instance()->save(szTmp); +} + +void KviApplication::saveDefaultScripts() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_DEFAULTSCRIPT); + KviDefaultScriptManager::instance()->save(szTmp); +} + +void KviApplication::saveSharedFiles() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_SHAREDFILES); + g_pSharedFilesManager->save(szTmp); +} + +void KviApplication::saveActions() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_USERACTIONS); + KviActionManager::instance()->save(szTmp); +} + +void KviApplication::saveIdentities() +{ + QString szTmp; + getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_IDENTITIES); + KviUserIdentityManager::instance()->save(szTmp); +} + +void KviApplication::saveConfiguration() +{ + // this is NOT called when the application is closing down + KviCustomToolBarManager::instance()->storeVisibilityState(); + saveOptions(); + saveIdentities(); + saveActions(); + saveIrcServerDataBase(); + saveProxyDataBase(); + saveRecentEntries(); + saveAvatarCache(); + saveAppEvents(); + saveRawEvents(); + saveMediaTypes(); + saveRegisteredUsers(); + saveRegisteredChannels(); + saveNickServ(); + saveIdentityProfiles(); + saveDefaultScripts(); + saveSharedFiles(); + savePopups(); + saveToolBars(); + saveAliases(); + saveTextIcons(); + saveInputHistory(); + saveScriptAddons(); + KviKvs::flushUserClasses(); + g_pWinPropertiesConfig->sync(); +} + +void KviApplication::autoConnectToServers() +{ + KviPointerList * pList = g_pServerDataBase->autoConnectOnStartupServers(); + if(pList) + { + for(KviIrcServer * pServer = pList->first(); pServer; pServer = pList->next()) + { + QString szCommand = "server -u \"id:"; + if(pServer->id().isEmpty()) + pServer->generateUniqueId(); + szCommand += pServer->id(); + szCommand += "\""; + KviKvsScript::run(szCommand,activeConsole()); + } + g_pServerDataBase->clearAutoConnectOnStartupServers(); + } + + KviPointerList * pListNet = g_pServerDataBase->autoConnectOnStartupNetworks(); + if(pListNet) + { + for(KviIrcNetwork * pNetwork = pListNet->first(); pNetwork; pNetwork = pListNet->next()) + { + QString szCommandx = "server -u \"net:"; + szCommandx += pNetwork->name(); + szCommandx += "\""; + KviKvsScript::run(szCommandx,activeConsole()); + } + g_pServerDataBase->clearAutoConnectOnStartupNetworks(); + } +} + +void KviApplication::createFrame() +{ + if(g_pFrame) + qDebug("WARNING: Creating the main frame twice!"); + g_pFrame = new KviMainWindow(); + g_pFrame->createNewConsole(true); + + if(m_szExecAfterStartup.hasData()) + { + // FIXME, this should be a QString + KviKvsScript::run(m_szExecAfterStartup.ptr(),g_pFrame->firstConsole()); + m_szExecAfterStartup = ""; + } + + // auto connect to servers if needed + if(g_pServerDataBase->autoConnectOnStartupServers() || g_pServerDataBase->autoConnectOnStartupNetworks()) + { + autoConnectToServers(); + } + + if(KVI_OPTION_BOOL(KviOption_boolShowDockExtension)) + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_TRAYICON_SHOW); + + if(KVI_OPTION_BOOL(KviOption_boolStartupMinimized)) + g_pFrame->showMinimized(); + else + g_pFrame->show(); +} + +void KviApplication::destroyFrame() +{ + m_bClosingDown=true; + if(g_pFrame) + g_pFrame->deleteLater(); + g_pActiveWindow = 0; +} + +bool KviApplication::connectionExists(KviIrcConnection * pConn) +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current()->connection() == pConn) + return true; + ++it; + } + return false; +} + +bool KviApplication::windowExists(KviWindow * pWnd) +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current() == pWnd) + return true; + ++it; + } + return false; +} + +unsigned int KviApplication::windowCount() +{ + return g_pGlobalWindowDict->count(); +} + +KviConsole * KviApplication::findConsole(QString & szServer, QString & szNick) +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) + { + if(((KviConsole *)it.current())->isConnected()) + { + if(!szServer.isEmpty()) + { + if(KviQString::equalCI(szServer, + ((KviConsole *)it.current())->connection()->currentServerName())) + { + if(!szNick.isEmpty()) + { + if(KviQString::equalCI(szNick, + ((KviConsole *)it.current())->connection()->currentNickName())) + return ((KviConsole *)it.current()); + } else return ((KviConsole *)it.current()); + } + } else { + if(!szNick.isEmpty()) + { + if(KviQString::equalCI(szNick, + ((KviConsole *)it.current())->connection()->currentNickName())) + return ((KviConsole *)it.current()); + } + } + } + } + ++it; + } + return 0; +} + +void KviApplication::restartLagMeters() +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) + { + if(((KviConsole *)it.current())->connection()) + ((KviConsole *)it.current())->connection()->restartLagMeter(); + } + ++it; + } +} + +void KviApplication::restartNotifyLists() +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) + { + if(((KviConsole *)it.current())->connection()) + ((KviConsole *)it.current())->connection()->restartNotifyList(); + } + ++it; + } +} + +void KviApplication::resetAvatarForMatchingUsers(KviRegisteredUser * pUser) +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) + { + ((KviConsole *)it.current())->resetAvatarForMatchingUsers(pUser); + } + ++it; + } +} + +KviConsole * KviApplication::findConsole(unsigned int uIrcContextId) +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) + { + if(((KviConsole *)it.current())->context()->id() == uIrcContextId) + return ((KviConsole *)it.current()); + } + ++it; + } + return 0; +} + +KviConsole * KviApplication::topmostConnectedConsole() +{ + // check the foreground window console + + KviConsole * pConsole = activeConsole(); + if(!pConsole) + return 0; + if(pConsole->isConnected()) + return pConsole; + + // try ANY connected console + + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) + { + if(((KviConsole *)it.current())->isConnected()) + return (KviConsole *)(it.current()); + } + ++it; + } + + return 0; +} + +KviWindow * KviApplication::findWindow(const QString & szWindowId) +{ + return g_pGlobalWindowDict->find(szWindowId); +} + +KviWindow * KviApplication::findWindowByCaption(const QString & szWindowCaption, int iContextId) +{ + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + + while(it.current()) + { + if(KviQString::equalCI(szWindowCaption,it.current()->plainTextCaption()) && + (iContextId==-1 || it.current()->context()->id() == (uint) iContextId)) + return it.current(); + ++it; + } + return 0; +} + +void KviApplication::registerWindow(KviWindow * pWnd) +{ + g_pGlobalWindowDict->insert(pWnd->id(),pWnd); +} + +void KviApplication::unregisterWindow(KviWindow * pWnd) +{ + g_pGlobalWindowDict->remove(pWnd->id()); +} + +KviConsole * KviApplication::activeConsole() +{ + if(!g_pFrame) + return 0; + if(g_pActiveWindow) + { + if(g_pActiveWindow->console()) + return g_pActiveWindow->console(); + } + return g_pFrame->firstConsole(); +} + + +/////////////////// RECENT STUFF LISTS & POPUPS HANDLING + +// Helper for KviApplication::addRecent*() +static void merge_to_stringlist_option(const QString & szItem, int iOption, int iMaxEntries) +{ + for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(iOption).begin(); + it != KVI_OPTION_STRINGLIST(iOption).end(); ++it) + { + // Do a case-insensitive search (for nicknames, servers, and channels) + if(!QString::compare(szItem.toLower(),(*it).toLower())) + { + // In the recent list, remove and put as first so more recent items + // are always first + it = KVI_OPTION_STRINGLIST(iOption).erase(it); + --it; + } + } + while(KVI_OPTION_STRINGLIST(iOption).count() >= iMaxEntries) + { + KVI_OPTION_STRINGLIST(iOption).erase(KVI_OPTION_STRINGLIST(iOption).isEmpty() ? KVI_OPTION_STRINGLIST(iOption).end() : --KVI_OPTION_STRINGLIST(iOption).end()); + } + KVI_OPTION_STRINGLIST(iOption).prepend(szItem); +} + +void KviApplication::addRecentUrl(const QString & szText) +{ + merge_to_stringlist_option(szText,KviOption_stringlistRecentIrcUrls,50); + emit(recentUrlsChanged()); +} + +void KviApplication::addRecentNickname(const QString & szNewNick) +{ + merge_to_stringlist_option(szNewNick,KviOption_stringlistRecentNicknames,KVI_MAX_RECENT_NICKNAMES); +} + +void KviApplication::addRecentChannel(const QString & szChan, const QString & szNet) +{ + if(!m_pRecentChannelDict) + buildRecentChannels(); + + QStringList * pList = m_pRecentChannelDict->find(szNet); + if(!pList) + { + pList = new QStringList(szChan); + m_pRecentChannelDict->insert(szNet,pList); + } + + if(!pList->contains(szChan)) + pList->append(szChan); +} + +void KviApplication::buildRecentChannels() +{ + if(m_pRecentChannelDict) + delete m_pRecentChannelDict; + + m_pRecentChannelDict = new KviPointerHashTable; + m_pRecentChannelDict->setAutoDelete(true); + + QString szChan,szNet; + + for( + QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistRecentChannels).begin(); + it != KVI_OPTION_STRINGLIST(KviOption_stringlistRecentChannels).end(); + ++it + ) + { + if((*it).isEmpty()) + continue; + + szChan = (*it).section(KVI_RECENT_CHANNELS_SEPARATOR,0,0); + szNet = (*it).section(KVI_RECENT_CHANNELS_SEPARATOR,1); + + if(szNet.isEmpty()) + continue; + + QStringList * pList = m_pRecentChannelDict->find(szNet); + if(!pList) + { + pList = new QStringList(szChan); + m_pRecentChannelDict->insert(szNet,pList); + } + + if(!pList->contains(szChan)) + pList->append(szChan); + } +} + +void KviApplication::saveRecentChannels() +{ + if(!m_pRecentChannelDict) + return; + + QString szTmp; + + KVI_OPTION_STRINGLIST(KviOption_stringlistRecentChannels).clear(); + + KviPointerHashTableIterator it(*m_pRecentChannelDict); + + for(; it.current(); ++it) + { + for(QStringList::Iterator it_str = it.current()->begin(); it_str != it.current()->end(); ++it_str) + { + szTmp = *it_str; + szTmp.append(KVI_RECENT_CHANNELS_SEPARATOR); + szTmp.append(it.currentKey()); + KVI_OPTION_STRINGLIST(KviOption_stringlistRecentChannels).append(szTmp); + } + } +} + +QStringList * KviApplication::recentChannelsForNetwork(const QString & szNet) +{ + if(!m_pRecentChannelDict) + buildRecentChannels(); + return m_pRecentChannelDict->find(szNet); +} + +void KviApplication::addRecentServer(const QString & szServer) +{ + merge_to_stringlist_option(szServer,KviOption_stringlistRecentServers,KVI_MAX_RECENT_SERVERS); +} + +void KviApplication::fillRecentServersPopup(KviTalPopupMenu * pMenu) +{ + // FIXME: #warning "MAYBE DISABLE THE SERVERS THAT WE ARE ALREADY CONNECTED TO ?" + pMenu->clear(); + for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistRecentServers).begin(); it != KVI_OPTION_STRINGLIST(KviOption_stringlistRecentServers).end(); ++it) + { + if(*it == "") + continue; + pMenu->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SERVER)),*it); + } +} + +void KviApplication::fillRecentNicknamesPopup(KviTalPopupMenu * pMenu, KviConsole * pConsole) +{ + pMenu->clear(); + int iId; + bool bAlreadyFound = false; + for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistRecentNicknames).begin(); it != KVI_OPTION_STRINGLIST(KviOption_stringlistRecentNicknames).end(); ++it) + { + if(*it == "") + continue; + iId = pMenu->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NICK)),*it); + if(!pConsole->isConnected()) + pMenu->setItemEnabled(iId,false); + else { + if(!bAlreadyFound) + { + bool bIsCurrent = KviQString::equalCS(pConsole->connection()->currentNickName(),*it); + pMenu->setItemEnabled(iId,!bIsCurrent); + if(bIsCurrent) + bAlreadyFound = true; + } + } + } +} + +void KviApplication::fillRecentChannelsPopup(KviTalPopupMenu * pMenu, KviConsole * pConsole) +{ + pMenu->clear(); + QStringList * pList = recentChannelsForNetwork(pConsole->currentNetworkName()); + if(pList) + { + for(QStringList::Iterator it = pList->begin(); it != pList->end(); ++it) + { + if(*it == "") + continue; // ? + int iId = pMenu->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_CHANNEL)),*it); + if(!pConsole->isConnected()) + pMenu->setItemEnabled(iId,false); + else + pMenu->setItemEnabled(iId,!(pConsole->connection()->findChannel(*it))); + } + } +} + + +/* +void KviApplication::fillRecentServersListBox(KviTalListBox * l) +{ + l->clear(); + for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistRecentServers).begin(); it != KVI_OPTION_STRINGLIST(KviOption_stringlistRecentServers).end(); ++it) + l->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SERVER)),*it); +} +*/ + +//#include + +void KviApplication::heartbeat(kvi_time_t tNow) +{ + const struct tm * pTm = localtime(&tNow); + + if(g_pApp->topmostConnectedConsole()) + { + // FIXME: this has huge precision problems... + KVI_OPTION_UINT(KviOption_uintTotalConnectionTime)++; + } + + if(pTm && !pTm->tm_hour && !pTm->tm_min && !pTm->tm_sec) + { + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + while(it.current()) + { + if(it.current()->view() && it.current()->view()->isLogging()) + it.current()->view()->startLogging(0); + ++it; + } + } + + //qDebug("Clearing Qt pixmap cache..."); + //QPixmapCache::clear(); +} + +void KviApplication::timerEvent(QTimerEvent * e) +{ + if(e->timerId() != m_iHeartbeatTimerId) + { + QObject::timerEvent(e); + return; + } + + // our heartbeat + + kvi_time_t tNow = kvi_unixTime(); + + heartbeat(tNow); +} + +// qvariant.h uses this, and it is included by the qt generated moc file for Qt >= 3.0.0 +#ifdef Bool + #undef Bool +#endif + + +#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES +#include "kvi_app.moc" +#endif //!COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/KviApplication.h b/src/kvirc/kernel/KviApplication.h new file mode 100644 index 000000000..2f1787358 --- /dev/null +++ b/src/kvirc/kernel/KviApplication.h @@ -0,0 +1,383 @@ +#ifndef _KVI_APP_H_ +#define _KVI_APP_H_ + +//============================================================================= +// +// File : KviApplication.h +// Creation date : Sun Jun 18 2000 12:40:00 CEST by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviCString.h" +#include "KviQString.h" +#include "KviTalApplication.h" +#include "KviPointerList.h" +#include "KviTimeUtils.h" +#include "KviPointerHashTable.h" // ? + +#include +#include + +#ifdef COMPILE_ON_WINDOWS + // The brain damaged MSVC compiler can't instantiate templates without this + #include "KviMainWindow.h" + #include "KviWindow.h" +#else // !COMPILE_ON_WINDOWS + class KviMainWindow; + class KviWindow; +#endif // !COMPILE_ON_WINDOWS + +#ifndef COMPILE_NO_IPC + class KviIpcSentinel; +#endif // !COMPILE_NO_IPC + +#ifdef COMPILE_X11_SUPPORT + #include +#endif + +class KviTalPopupMenu; +class KviTalListBox; +class KviConsole; +class KviConfigurationFile; +class KviRegisteredUser; +class KviIrcConnection; +class KviIrcServerDataBase; +class QPixmap; +class QTextCodec; +class QDomElement; +class QStringList; + +typedef struct _KviPendingAvatarChange +{ + KviConsole * pConsole; + QString szRemoteUrl; + QString szNick; + QString szUser; + QString szHost; +} KviPendingAvatarChange; + +/** +* \typedef KviNotifierMessageParam +* \struct _KviNotifierMessageParam +* \brief Defines a struct which holds information about the notifier message +*/ +typedef struct _KviNotifierMessageParam +{ + KviWindow * pWindow; /**< The window where the notifier was triggered */ + QString szIcon; /**< The id of the icon (channel, query, ...) */ + QString szMessage; /**< The message which triggered the notifier */ + unsigned int uMessageLifetime; /**< The timeout of the notifier; 0 means no hide */ +} KviNotifierMessageParam; + +typedef struct _KviDBusNotifierMessageQueue +{ + QStringList lMessages; +} KviDBusNotifierMessageQueue; + + +#ifdef Unsorted + #undef Unsorted +#endif +#ifdef None + #undef None +#endif + +class KVIRC_API KviApplication : public KviTalApplication +{ + friend class KviMainWindow; + friend class KviWindow; + friend class KviSetupWizard; // this resides in a module! + Q_OBJECT +public: + KviApplication(int &argc,char ** argv); + ~KviApplication(); + +protected: + // directories + QString m_szGlobalKvircDir; + QString m_szLocalKvircDir; + int m_iHeartbeatTimerId; + bool m_bFirstTimeRun; + bool m_bClosingDown; +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + bool m_bPortable; +#endif + KviWindow * m_pActiveWindow; + bool m_bUpdateGuiPending; + KviPointerList * m_pPendingAvatarChanges; + bool m_bSetupDone; + KviPointerHashTable * m_pRecentChannelDict; +#ifdef COMPILE_PSEUDO_TRANSPARENCY + bool m_bUpdatePseudoTransparencyPending; +#endif +#ifndef COMPILE_NO_IPC + KviIpcSentinel * m_pIpcSentinel; +#endif + QFont m_fntDefaultFont; +public: + // setup stuff (accessed from KviMain.cpp: consider private othwerise) + QString m_szConfigFile; // setup + bool m_bCreateConfig; // setup + KviCString m_szExecAfterStartup; + bool m_bShowSplashScreen; +public: + // FIXME: "Plugins" and "ConfigPlugins" should become "Modules" and "ConfigModules" + enum KvircSubdir + { + None, Pics, Config, + Help, HelpEN, HelpNoIntl, + Log, Incoming, Audio, + Scripts, Plugins, ConfigPlugins, + Trash, MsgColors, Charmaps, + Avatars, DefScript, License, + Modules, ConfigScripts, Filters, + Tmp, Locale, Themes, + Classes, SmallIcons, EasyPlugins + }; + +public: + void destroyFrame(); + void setup(); // THIS SHOULD BE PRIVATE! (but is accessed from KviMain.cpp) + +#ifndef COMPILE_NO_IPC + void ipcMessage(char * message); +#endif + + static int getGloballyUniqueId(); // returns an unique integer identifier across the application + + bool firstTimeRun() const { return m_bFirstTimeRun; }; + bool kviClosingDown() const { return m_bClosingDown; }; + + inline bool supportsCompositing() + { +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + //we need >= win2000 + return true; +#endif +#ifdef COMPILE_X11_SUPPORT + return QX11Info::isCompositingManagerRunning(); +#endif +#ifdef COMPILE_ON_MAC + return true; +#endif + return false; + }; + void setupBegin(); + void setupFinish(); + + /* + Unused + inline void emitRecentUrlsChanged() { emit(recentUrlsChanged()); }; + */ + + // KviApplication.cpp (Saving options) + void saveIrcServerDataBase(); + void saveProxyDataBase(); + void saveRecentEntries(); + void saveAppEvents(); + void saveRawEvents(); + void saveMediaTypes(); + void saveRegisteredUsers(); + void saveSharedFiles(); + void savePopups(); + void saveAliases(); + void saveNickServ(); + void saveIdentityProfiles(); + void saveDefaultScripts(); + void saveTextIcons(); + void saveRegisteredChannels(); + void saveInputHistory(); + void saveAvatarCache(); + void saveToolBars(); + void saveActions(); + void saveScriptAddons(); + void saveIdentities(); + + // KviOptions.cpp : Options saving and loading (kvi.main.conf)) + void loadOptions(); + void saveOptions(); + + void listAvailableOptions(KviWindow *wnd); + bool getOptionString(const QString &optName,QString &buffer); + bool setOptionValue(const QString &optName,const QString &value); + bool setCommonOptionValue(const QString &optName,const QString &value); + + void optionResetUpdate(int flags); + + // KviApplication_filesystem.cpp : Filesystem thingies + void getGlobalKvircDirectory(QString &szData,KvircSubdir dir,const QString &appendFile = QString()); + void getLocalKvircDirectory(QString &szData,KvircSubdir dir,const QString &appendFile = QString(),bool bCreateIfNeeded = true); + + void getTmpFileName(QString &szBuffer,const QString &szEndingFileName = QString()); + void getChannelDumpLogFileName(QString &str); + + static QTextCodec * defaultTextCodec(); + static QTextCodec * defaultSrvCodec(); + + bool findImageInImageSearchPath(QString &szRetPath,const QString &filename); + + bool findImage(QString &szRetPath,const QString &filename); + bool findImageThemeOnlyCompat(QString &szRetPath,const QString &filename); // temporary compat, will be removed soon (do not use) + bool findSmallIcon(QString &szRetPath,const QString &filename); + // tries to map the full path filename to one of the KVIrc's mapped directories + // if it doesn't succeed it just returns the complete filename in szRetPath + //bool mapImageFile(KviCString &szRetPath,const char * filename); + bool mapImageFile(QString &szRetPath,const QString &filename); + + //void getDefaultDccSaveFilePath(KviCString &path,const char *filename); + void completeDirectory(const QString &word,KviPointerList * matches); + // + // Returns a config path suitable for reading (at least) + // First lookups the user local config directory, + // if no config file is found, it earches in the global one + // returns false if no config file has been found + // If bNoFail is true, the buffer is filled with the file name even + // if no config file has been found: in this case the local config + // directory is used + // + bool getReadOnlyConfigPath(QString &buffer,const char *config_name,KvircSubdir sbd = Config,bool bNoFail = false); + + + /// + /// Attempts to locate the audio file specified by szFileName and put it's + /// absolute path in szRetPath. Returns true if the audio file is found and false otherwise. + /// + /// If szFileName is already an absolute path then it's returned directly + /// after testing for its existence. If szFileName is not an absolute path + /// then it's searched in the local KVIrc "audio" directory, then in the global one + /// and finally in the user's home. + /// + bool findAudioFile(QString &szRetPath,const QString &szFileName); + + // KviApplication.cpp : Window stuff + KviWindow * findWindow(const QString &windowId); + KviWindow * findWindowByCaption(const QString &windowCaption,int iContextId=-1); + KviConsole * findConsole(unsigned int ircContextId); + KviConsole * findConsole(QString & servr,QString & nick); + KviConsole * topmostConnectedConsole(); + KviConsole * activeConsole(); + bool windowExists(KviWindow *wnd); + bool connectionExists(KviIrcConnection *cnn); + unsigned int windowCount(); + + // KviApplication.cpp : Utilities + void resetAvatarForMatchingUsers(KviRegisteredUser * u); + void restartNotifyLists(); + void restartLagMeters(); + void triggerUpdateGui(); +#ifdef COMPILE_PSEUDO_TRANSPARENCY + void triggerUpdatePseudoTransparency(); +#endif + + // KviApplication.cpp : DCC (and CTCP AVATAR & SOUND) related stuff + void setAvatarOnFileReceived(KviConsole * pConsole,const QString &szRemoteUrl,const QString &szNick,const QString &szUser,const QString &szHost); + KviPendingAvatarChange * findPendingAvatarChange(KviConsole * pConsole,const QString &szNick,const QString &szRemoteUrl); + void fileDownloadTerminated(bool bSuccess,const QString &szRemoteUrl,const QString &szLocalFileName,const QString &szNick = QString(),const QString &szError = QString(),bool bQuiet = false); + + void setAvatarFromOptions(); + + // uMessageLifetime is in seconds! and 0 means "forever" + void notifierMessage(KviWindow * pWnd,int iIconId,const QString &szMsg,unsigned int uMessageLifetime); + + void addRecentNickname(const QString& newNick); + void addRecentChannel(const QString& chan,const QString& net); + + QStringList * recentChannelsForNetwork(const QString& net); + + KviPointerHashTable * recentChannels() const + { + return m_pRecentChannelDict; + } + + + void addRecentServer(const QString& server); + void fillRecentServersPopup(KviTalPopupMenu * m); + void fillRecentNicknamesPopup(KviTalPopupMenu * m,KviConsole * pConsole); + void fillRecentChannelsPopup(KviTalPopupMenu * m,KviConsole * pConsole); +// + void autoConnectToServers(); + + void checkSuggestRestoreDefaultScript(); + + void loadDefaultScript(QString szItem = QString()); + QStyle * themedStyle(); +protected: + void buildRecentChannels(); + void saveRecentChannels(); + // KviApplication.cpp : KviWindow global database + void registerWindow(KviWindow *wnd); + void unregisterWindow(KviWindow *wnd); + void frameDestructorCallback(); + void heartbeat(kvi_time_t tNow); + virtual void timerEvent(QTimerEvent *e); +public slots: + // KviApplication.cpp : Slots + void saveConfiguration(); + void updateGui(); + void updatePseudoTransparency(); + void restoreDefaultScript(); + void addRecentUrl(const QString& text); +private: + void createSplashScreen(); + void destroySplashScreen(); + + // KviApplication_setup.cpp : Setup stuff + void loadDirectories(); + void findGlobalKvircDirectory(); + bool findLocalKvircDirectory(); + bool checkGlobalKvircDirectory(const QString); + bool checkLocalKvircDirectory(const QString &szSpecificPath); + bool checkLocalKvircDirectory(); // check the m_szLocalKvircDirectory path + bool checkFileAssociations(); + void setupFileAssociations(); + + bool checkUriAssociations(const char * proto); + void setupUriAssociations(const char * proto); + + void saveKvircDirectory(); + + // KviApplication.cpp : GUI stuff + void updateApplicationFont(); + +#ifdef COMPILE_PSEUDO_TRANSPARENCY + void createGlobalBackgrounds(QPixmap * pix); + void destroyPseudoTransparency(); +#endif //COMPILE_PSEUDO_TRANSPARENCY +private: + // KviApplication.cpp : parts of setup() + void loadRecentEntries(); +#ifndef COMPILE_NO_IPC + void createIpcSentinel(); + void destroyIpcSentinel(); +#endif //!COMPILE_NO_IPC + void createFrame(); +signals: + void reloadImages(); + void updateNotifier(); + void recentUrlsChanged(); +}; + +#ifndef _KVI_APP_CPP_ + extern KVIRC_API KviApplication * g_pApp; + extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; +#endif + +#endif //_KVI_APP_H_ diff --git a/src/kvirc/kernel/KviApplication_filesystem.cpp b/src/kvirc/kernel/KviApplication_filesystem.cpp new file mode 100644 index 000000000..3642a033e --- /dev/null +++ b/src/kvirc/kernel/KviApplication_filesystem.cpp @@ -0,0 +1,603 @@ +//============================================================================= +// +// File : KviApplication_filesystem.cpp +// Creation date : Thu Dec 24 1998 04:05:26 by Szymon Stefanek +// +// This file is part of the Kvirc irc client distribution +// Copyright (C) 1998-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_debug.h" +#include "KviApplication.h" +#include "KviLocale.h" +#include "KviFileUtils.h" +#include "KviMediaType.h" +#include "KviEnvironment.h" +#include "KviTimeUtils.h" +#include "KviOptions.h" +#include "kvi_defaults.h" +#include "KviIconManager.h" + +#include +#include +#include + +extern KviMediaManager * g_pMediaManager; + +//============ getGlobalKvircDirectory ================// + +void KviApplication::getGlobalKvircDirectory(QString &szData,KvircSubdir dir,const QString &appendFile) +{ + szData=m_szGlobalKvircDir; + KviQString::ensureLastCharIs(szData,KVI_PATH_SEPARATOR_CHAR); + + switch(dir) + { + case None : break; + case Pics : szData.append("pics"); break; + case Modules : + #ifdef KVIRC_MODULES_DIR + szData = KVIRC_MODULES_DIR; + #else + szData.append("modules"); + #endif + break; + case Plugins : szData.append("modules"); break; + case EasyPlugins : szData.append("easyplugins"); break; + case ConfigPlugins : KviQString::appendFormatted(szData,"config%smodules",KVI_PATH_SEPARATOR); break; + case ConfigScripts : KviQString::appendFormatted(szData,"config%sscripts",KVI_PATH_SEPARATOR); break; + case Help : + szData.append("help"); + { + // Localized help + QString tmp(KviLocale::localeName().ptr()); + tmp.prepend(KVI_PATH_SEPARATOR_CHAR); + tmp.prepend(szData); + if(KviFileUtils::directoryExists(tmp))szData = tmp; + else { + tmp = szData; KviQString::appendFormatted(tmp,"%sen",KVI_PATH_SEPARATOR); + if(KviFileUtils::directoryExists(tmp))szData = tmp; + } + } + break; + case HelpEN : KviQString::appendFormatted(szData,"help%sen",KVI_PATH_SEPARATOR); break; + case HelpNoIntl : szData.append("help"); break; + case Log : qDebug("WARNING Global log directory requested!"); break; + case Incoming : qDebug("WARNING Global incoming directory requested!"); break; + case Trash : qDebug("WARNING Global trash directory requested!"); break; + case Config : szData.append("config"); break; + case Audio : szData.append("audio"); break; + case Scripts : szData.append("scripts"); break; + case MsgColors : szData.append("msgcolors"); break; + case Charmaps : szData.append("charmaps"); break; + case Avatars : szData.append("avatars"); break; + case DefScript : szData.append("defscript"); break; + case License : szData.append("license"); break; + case Filters : szData.append("filters"); break; + case Locale : szData.append("locale"); break; + case Tmp : qDebug("WARNING Global tmp directory requested!"); break; + case Themes : szData.append("themes"); break; + case Classes : szData.append("classes"); break; + case SmallIcons : szData.append("pics"KVI_PATH_SEPARATOR KVI_SMALLICONS_SUBDIRECTORY); break; + } + + if(!appendFile.isEmpty()) + { + KviQString::ensureLastCharIs(szData,KVI_PATH_SEPARATOR_CHAR); + szData.append(appendFile); + } + + KviFileUtils::adjustFilePath(szData); +} + +void KviApplication::getLocalKvircDirectory(QString &szData,KvircSubdir dir,const QString & appendFile,bool bCreateIfNeeded) +{ + szData=m_szLocalKvircDir; + KviQString::ensureLastCharIs(szData,KVI_PATH_SEPARATOR_CHAR); + + switch(dir) + { + case None : break; + case Pics : szData.append("pics"); break; + case EasyPlugins : szData.append("easyplugins"); break; + case Config : szData.append("config"); break; + case ConfigPlugins : szData.append("config"KVI_PATH_SEPARATOR"modules"); break; + case ConfigScripts : szData.append("config"KVI_PATH_SEPARATOR"scripts"); break; + case Log : + szData = KVI_OPTION_STRING(KviOption_stringLogsPath); + // we should take special care here + // the user is likely to mess the path behind our back + // try to recover from most common problems + while(szData.endsWith(KVI_PATH_SEPARATOR_CHAR)) + szData = szData.remove(szData.length()-1,1); + if(szData.isEmpty()) + { + szData = m_szLocalKvircDir; + if(!szData.endsWith(QString(QChar(KVI_PATH_SEPARATOR_CHAR)))) + szData.append(KVI_PATH_SEPARATOR_CHAR); + szData.append("log"); + KVI_OPTION_STRING(KviOption_stringLogsPath) = szData; + } + break; + case Incoming : + szData = KVI_OPTION_STRING(KviOption_stringIncomingPath); + // we should take special care here + // the user is likely to mess the path behind our back + // try to recover from most common problems + while(szData.endsWith(KVI_PATH_SEPARATOR_CHAR)) + szData = szData.remove(szData.length()-1,1); + if(szData.isEmpty()) + { +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + if(m_bPortable) + { + szData = m_szLocalKvircDir; + } else { +#endif + szData = QDir::homePath(); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + } +#endif + if(!szData.endsWith(QString(QChar(KVI_PATH_SEPARATOR_CHAR)))) + szData.append(KVI_PATH_SEPARATOR_CHAR); + szData.append(KVI_DEFAULT_INCOMING_SUBDIRECTORY_NAME); + KVI_OPTION_STRING(KviOption_stringLogsPath) = szData; + } + break; + case Help : + szData.append("help"); + { + // Localized help + QString tmp = KviLocale::localeName().ptr(); + tmp.prepend(KVI_PATH_SEPARATOR_CHAR); + tmp.prepend(szData); + if(KviFileUtils::directoryExists(tmp))szData = tmp; + else { + tmp = szData; tmp.append(KVI_PATH_SEPARATOR"en"); + if(KviFileUtils::directoryExists(tmp))szData = tmp; + } + } + break; + case HelpEN : szData.append("help"KVI_PATH_SEPARATOR"en"); break; + case HelpNoIntl : szData.append("help"); break; + case Audio : szData.append("audio"); break; + case Scripts : szData.append("scripts"); break; + case Modules : + case Plugins : szData.append("modules"); break; + case Trash : szData.append("trash"); break; + case MsgColors : szData.append("msgcolors"); break; + case Charmaps : szData.append("charmaps"); break; + case Avatars : szData.append("avatars"); break; + case License : szData.append("license"); break; + case Filters : szData.append("filters"); break; + case Tmp : szData.append("tmp"); break; + case Locale : szData.append("locale"); break; + case Themes : szData.append("themes"); break; + case DefScript : szData.append("defscript"); /* should never happen! */ break; + case Classes : szData.append("classes"); break; + case SmallIcons : szData.append("pics"KVI_PATH_SEPARATOR KVI_SMALLICONS_SUBDIRECTORY); break; + } + if(bCreateIfNeeded)KviFileUtils::makeDir(szData); + + if(!appendFile.isEmpty()) + { + KviQString::ensureLastCharIs(szData,KVI_PATH_SEPARATOR_CHAR); + szData.append(appendFile); + } + + KviFileUtils::adjustFilePath(szData); +} + +void KviApplication::getTmpFileName(QString &szBuffer,const QString &szEndingFileName) +{ + QString tmp; + getLocalKvircDirectory(tmp,Tmp); + KviQString::ensureLastCharIs(tmp,KVI_PATH_SEPARATOR_CHAR); + + struct timeval tmv; + kvi_gettimeofday(&tmv,0); + + QString szFileName = szEndingFileName.isNull() ? QString("file.tmp") : szEndingFileName; + do { + szBuffer = tmp; + KviQString::appendFormatted(szBuffer,"kvirc_%d_%Q",tmv.tv_usec,&szFileName); + tmv.tv_usec++; + } while(KviFileUtils::fileExists(szBuffer)); +} + +void KviApplication::completeDirectory(const QString &word,KviPointerList * matches) +{ + QString szDir = word; + QString szFile = word; + KviQString::cutToLast(szFile,KVI_PATH_SEPARATOR_CHAR); + KviQString::cutFromLast(szDir,KVI_PATH_SEPARATOR_CHAR); + KviFileUtils::adjustFilePath(szDir); + KviQString::ensureLastCharIs(szDir,KVI_PATH_SEPARATOR_CHAR); + QDir d(szDir); + + // FIXME: maybe check timestamps ? (old modules) + QStringList sl = d.entryList(QDir::Dirs); + QStringList::Iterator it; + + for(it = sl.begin();it != sl.end();++it) + { + QString * t = new QString(*it); + if(KviQString::equalCS(*t,".") || KviQString::equalCS(*t,"..")) + { + delete t; + } else { +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + if(KviQString::equalCIN(szFile,*t,szFile.length())) +#else + if(KviQString::equalCSN(szFile,*t,szFile.length())) +#endif + { + t->prepend(szDir); + t->append(KVI_PATH_SEPARATOR_CHAR); + matches->append(t); + } else { + delete t; + } + } + } + + sl = d.entryList(QDir::Files); + + for(it = sl.begin();it != sl.end();++it) + { + QString * t = new QString(*it); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + if(KviQString::equalCIN(szFile,*t,szFile.length())) +#else + if(KviQString::equalCSN(szFile,*t,szFile.length())) +#endif + { + t->prepend(szDir); + matches->append(t); + } else { + delete t; + } + } +} + + +//============= getChannelDumpLogFileName ==============// +// +// Returns a valid filename for the channel dump log +// + +void KviApplication::getChannelDumpLogFileName(QString &str) +{ + unsigned int logN = 0; + QString fPrefix="kick_"; + do{ + QString fName; + KviQString::sprintf(fName,"%Q%u.log",&fPrefix,logN); + getLocalKvircDirectory(str,Log,fName); + logN++; + if(logN > 9999) + { + // Time to clear logs! :) + fPrefix+="x"; + logN = 0; + } + } while(KviFileUtils::fileExists(str)); + KviFileUtils::adjustFilePath(str); +} + +//========================= findImage ===========================// +// +// Find a file inside the default "Image" directories +// This should be thread safe (and in fact IS used by other threads) +// This function should be used only for finding the INTERNAL +// pixmaps... (so we expect them to be in the pics directory or +// Eventually in user's $HOME +// + +// FIXME: #warning "Check WHEN findImage is used and when findUserFile is used...we have a mess here" + +bool KviApplication::findImageInImageSearchPath(QString &szRetPath,const QString &filename) +{ + // first lookup the user defined paths + for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).begin(); + it != KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).end();++it) + { + szRetPath = *it; + KviQString::ensureLastCharIs(szRetPath,KVI_PATH_SEPARATOR_CHAR); + szRetPath.append(filename); + //qDebug("LOOK FOR %s",szRetPath.ptr()); + if(KviFileUtils::fileExists(szRetPath))return true; + } + + return false; +} + +static KviApplication::KvircSubdir pics_localsubdirs[2]={ KviApplication::Pics, KviApplication::Avatars }; +static KviApplication::KvircSubdir pics_globalsubdirs[2]={ KviApplication::Pics, KviApplication::Avatars }; + +/*bool KviApplication::mapImageFile(KviCString &szRetPath,const char * filename) +{ + QString buff; + bool ret=mapImageFile(buff,filename); + szRetPath=buff; + return ret; +}*/ + +bool KviApplication::mapImageFile(QString &szRetPath,const QString &filename) +{ + szRetPath = filename; + // can't map non absolute paths + if(!KviFileUtils::isAbsolutePath(filename))return false; + // can't map non existing paths + if(!KviFileUtils::fileExists(filename))return false; + + QFileInfo fi = QFileInfo(filename); + + unsigned int size = fi.size(); + + QString szBestMatch; + + while(szRetPath.indexOf(KVI_PATH_SEPARATOR) != -1) + { + KviQString::cutToFirst(szRetPath,KVI_PATH_SEPARATOR); + + if(szRetPath.isEmpty())break; + + QString szBuffer; + + int i; + + for(i=0;i<2;i++) + { + getLocalKvircDirectory(szBuffer,pics_localsubdirs[i],szRetPath); + if(KviFileUtils::fileExists(szBuffer)) + { + QFileInfo fi2(szBuffer); + if(size == fi2.size()) + { + // probably the same file + szBestMatch = szRetPath; + } + } + } + + for(i=0;i<2;i++) + { + getGlobalKvircDirectory(szBuffer,pics_globalsubdirs[i],szRetPath); + //qDebug("CHECK %s",szBuffer.ptr()); + if(KviFileUtils::fileExists(szBuffer)) + { + QFileInfo fi2(szBuffer); + if(size == fi2.size()) + { + // probably the same file + szBestMatch = szRetPath; + } + } + } + + // Last resort + szBuffer = QDir::homePath(); + KviQString::ensureLastCharIs(szBuffer,KVI_PATH_SEPARATOR_CHAR); + szBuffer.append(szRetPath); + if(KviFileUtils::fileExists(szBuffer)) + { + QFileInfo fi2(szBuffer); + if(size == fi2.size()) + { + // prolly the same file + szBestMatch = szRetPath; + } + } + } + + if(!szBestMatch.isEmpty()) + { + szRetPath = szBestMatch; + return true; + } + + + // no way to map it :/ + szRetPath = filename; + return false; +} + +bool KviApplication::findImage(QString &szRetPath,const QString &filename) +{ + // Find an user file... + if(KviFileUtils::isAbsolutePath(filename)) + { + szRetPath=filename; + return KviFileUtils::fileExists(filename); + } + + // if we have a theme, look it up as first + if(!KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).isEmpty()) + { + QString szTmp = KVI_OPTION_STRING(KviOption_stringIconThemeSubdir); + szTmp.append(KVI_PATH_SEPARATOR_CHAR); + szTmp.append(filename); + + getLocalKvircDirectory(szRetPath,KviApplication::Themes,szTmp); + if(KviFileUtils::fileExists(szRetPath))return true; + + getGlobalKvircDirectory(szRetPath,KviApplication::Themes,szTmp); + if(KviFileUtils::fileExists(szRetPath))return true; + } + + int i; + + for(i=0;i<2;i++) + { + getLocalKvircDirectory(szRetPath,pics_localsubdirs[i],filename); + if(KviFileUtils::fileExists(szRetPath))return true; + } + + for(i=0;i<2;i++) + { + getGlobalKvircDirectory(szRetPath,pics_globalsubdirs[i],filename); + if(KviFileUtils::fileExists(szRetPath))return true; + } + + if(findImageInImageSearchPath(szRetPath,filename))return true; + + // Last resort + szRetPath = QDir::homePath(); + KviQString::ensureLastCharIs(szRetPath,KVI_PATH_SEPARATOR_CHAR); + szRetPath.append(filename); + if(KviFileUtils::fileExists(szRetPath))return true; + + szRetPath = filename; + + return false; +} + +bool KviApplication::findImageThemeOnlyCompat(QString &szRetPath,const QString &filename) +{ + // if we have a theme, look it up as first + if(!KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).isEmpty()) + { + QString szTmp = KVI_OPTION_STRING(KviOption_stringIconThemeSubdir); + szTmp.append(KVI_PATH_SEPARATOR_CHAR); + szTmp.append(filename); + + getLocalKvircDirectory(szRetPath,KviApplication::Themes,szTmp); + if(KviFileUtils::fileExists(szRetPath))return true; + + getGlobalKvircDirectory(szRetPath,KviApplication::Themes,szTmp); + if(KviFileUtils::fileExists(szRetPath))return true; + } + + getLocalKvircDirectory(szRetPath,KviApplication::Pics,filename); + if(KviFileUtils::fileExists(szRetPath))return true; + + + if(findImageInImageSearchPath(szRetPath,filename))return true; + + szRetPath = filename; + + return false; +} + +bool KviApplication::findSmallIcon(QString &szRetPath,const QString &filename) +{ + // this is a bit optimized for the small builtin icons + // looks up less places. + + //if(kvi_isAbsolutePath(filename)) + //{ + // BUG!.. we should never + //szRetPath=filename; + //return KviFileUtils::fileExists(filename); + //} + + // if we have a theme, look it up as first + if(!KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).isEmpty()) + { + QString szTmp = KVI_OPTION_STRING(KviOption_stringIconThemeSubdir); + szTmp.append(KVI_PATH_SEPARATOR_CHAR); + szTmp.append(KVI_SMALLICONS_SUBDIRECTORY); + szTmp.append(KVI_PATH_SEPARATOR_CHAR); + szTmp.append(filename); + + getLocalKvircDirectory(szRetPath,KviApplication::Themes,szTmp); + if(KviFileUtils::fileExists(szRetPath))return true; + + getGlobalKvircDirectory(szRetPath,KviApplication::Themes,szTmp); + if(KviFileUtils::fileExists(szRetPath))return true; + } + + // unlikely + getLocalKvircDirectory(szRetPath,KviApplication::SmallIcons,filename); + if(KviFileUtils::fileExists(szRetPath))return true; + + getLocalKvircDirectory(szRetPath,KviApplication::Pics,filename); + if(KviFileUtils::fileExists(szRetPath))return true; + + // likely + getGlobalKvircDirectory(szRetPath,KviApplication::SmallIcons,filename); + if(KviFileUtils::fileExists(szRetPath))return true; + + if(findImageInImageSearchPath(szRetPath,filename))return true; + + // Last resort... bleah :/ + szRetPath = QDir::homePath(); + KviQString::ensureLastCharIs(szRetPath,KVI_PATH_SEPARATOR_CHAR); + szRetPath.append(filename); + if(KviFileUtils::fileExists(szRetPath))return true; + + szRetPath = filename; + + return false; +} + +bool KviApplication::findAudioFile(QString &szRetPath,const QString &szFileName) +{ + if(KviFileUtils::isAbsolutePath(szFileName)) + { + szRetPath = szFileName; + return KviFileUtils::fileExists(szFileName); + } + + getLocalKvircDirectory(szRetPath,KviApplication::Audio,szFileName); + if(KviFileUtils::fileExists(szRetPath)) + return true; + + getGlobalKvircDirectory(szRetPath,KviApplication::Audio,szFileName); + if(KviFileUtils::fileExists(szRetPath)) + return true; + + // Last resort + szRetPath = QDir::homePath(); + KviQString::ensureLastCharIs(szRetPath,KVI_PATH_SEPARATOR_CHAR); + szRetPath.append(szFileName); + if(KviFileUtils::fileExists(szRetPath)) + return true; + + szRetPath = szFileName; + + return false; +} + + +//================== getReadOnlyConfigPath ====================// +// +// We want to READ a config file...find it +// + +bool KviApplication::getReadOnlyConfigPath(QString &buffer,const char *config_name,KvircSubdir sbd,bool bNoFail) +{ + // Take a look in the local directory.... + getLocalKvircDirectory(buffer,sbd,config_name); + //qDebug("%s %s %i |%s| %i",__FILE__,__FUNCTION__,__LINE__,buffer.ptr(),KviFileUtils::fileExists(buffer.ptr())); + if(!KviFileUtils::fileExists(buffer)) + { + // No saved config yet... check for defaults + QString tmp; + getGlobalKvircDirectory(tmp,sbd,config_name); + if(!KviFileUtils::fileExists(tmp)) + { + // No defaults...no such config file at all. + if(bNoFail)getLocalKvircDirectory(buffer,sbd,config_name); + return false; + } else buffer = tmp; // get the defaults this time + } // else file exists... + return true; +} diff --git a/src/kvirc/kernel/KviApplication_setup.cpp b/src/kvirc/kernel/KviApplication_setup.cpp new file mode 100644 index 000000000..75aa2f89c --- /dev/null +++ b/src/kvirc/kernel/KviApplication_setup.cpp @@ -0,0 +1,856 @@ +//============================================================================= +// +// File : KviApplication_setup.cpp +// Creation date : Fri Apr 2 1999 02:38:05 by Szymon Stefanek +// +// This file is part of the Kvirc irc client distribution +// Copyright (C) 1999-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + + + +//#define _KVI_DEBUG_CHECK_RANGE_ +//#include "kvi_debug.h" + +#include "kvi_settings.h" +#include "kvi_defaults.h" +#include "KviWindow.h" +#include "KviMainWindow.h" +#include "KviApplication.h" +#include "KviFileUtils.h" +#include "KviLocale.h" +#include "KviMessageBox.h" +#include "kvi_sourcesdate.h" +#include "KviIconManager.h" +#include "KviConfigurationFile.h" + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + #include + #include // at least for GetModuleFileName and *PrivateProfileString +#else + #include // for getenv() + #include // for symlink() <-- unused ? + + #ifdef COMPILE_KDE_SUPPORT + #include + #include +// #include + #endif +#endif + +#include +#include +#include +#include +#include + +static QLibrary * g_pSetupLibrary = 0; + +// +// Things launched at startup: +// - Attempt to find the global Kvirc directory +// - Attempt to find the local Kvirc directory +// and if it is not found, ask the user to choose one +// + +bool KviApplication::checkGlobalKvircDirectory(const QString szDir) +{ + //First check if the help subdir exists + QString szHelpDir = szDir; + szHelpDir += KVI_PATH_SEPARATOR"help"; + if(!KviFileUtils::directoryExists(szHelpDir)) + return false; + //Then check if the pics subdir exists + QString szPicsDir = szDir; + szPicsDir += KVI_PATH_SEPARATOR"pics"; + if(!KviFileUtils::directoryExists(szPicsDir)) + return false; + //Now make sure that it is the dir that we're looking for. + //Check for an image file that we need. + szPicsDir.append(KVI_PATH_SEPARATOR); + szPicsDir.append(KVI_ACTIVITYMETER_IMAGE_NAME); + return KviFileUtils::isReadable(szPicsDir); +} + +bool KviApplication::checkLocalKvircDirectory(const QString &szSpecificPath) +{ + QString szSavedLocalKvircDir = m_szLocalKvircDir; + m_szLocalKvircDir = szSpecificPath; + bool bRet = checkLocalKvircDirectory(); + m_szLocalKvircDir = szSavedLocalKvircDir; + return bRet; +} + +bool KviApplication::checkLocalKvircDirectory() +{ + //First check if the dir exists + if(!KviFileUtils::directoryExists(m_szLocalKvircDir)) + return false; + if(!QFileInfo(m_szLocalKvircDir).isWritable()) + return false; + + QString szBuff; + getLocalKvircDirectory(szBuff,Config); + if(!KviFileUtils::directoryExists(szBuff)) + return false; + + return true; +} + +bool KviApplication::checkFileAssociations() +{ +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) +#define QUERY_BUFFER 2048 + char * pcBuffer; + DWORD len = QUERY_BUFFER; + DWORD err; + pcBuffer = (char*)malloc(len*sizeof(char)); + HKEY hKey; + + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,".kvs",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if((err=RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + if(!kvi_strEqualCIN("KVIrcScript",pcBuffer,11)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if((err=RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + if(!kvi_strEqualCI(__tr2qs("KVIrc KVS Script").toLocal8Bit().data(),pcBuffer)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\DefaultIcon",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if(RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + QString szIcon = applicationFilePath()+",1"; + szIcon.replace('/',"\\"); + if(!kvi_strEqualCI(szIcon.toLocal8Bit().data(),pcBuffer)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\Shell\\Parse",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if(RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + if(!kvi_strEqualCI(__tr2qs("Run KVS Script").toLocal8Bit().data(),pcBuffer)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\Shell\\Parse\\command",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if(RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + QString szCmd = applicationFilePath()+" \"%1\""; + szCmd.replace('/',"\\"); + if(!kvi_strEqualCI(szCmd.toLocal8Bit().data(),pcBuffer)) + { + free(pcBuffer); + return false; + } + } + + //Config + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,".kvc",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if( (err=RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + if(!kvi_strEqualCIN("KVIrcConfig",pcBuffer,11)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcConfig",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + //Addon + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,".kva",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if((err=RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + if(!kvi_strEqualCIN("KVIrcAddon",pcBuffer,11)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + //Theme + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,".kvt",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if((err=RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + if(!kvi_strEqualCIN("KVIrcTheme",pcBuffer,11)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme",0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + free(pcBuffer); +#endif + return true; + +} + + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) +bool KviApplication::checkUriAssociations(const char * pcProto) +{ +#define QUERY_BUFFER 2048 + char * pcBuffer; + DWORD len = QUERY_BUFFER; + DWORD err; + pcBuffer = (char*)malloc(len*sizeof(char)); + HKEY hKey; + + KviCString szStoredKey = pcProto; + KviCString szKey = szStoredKey; + + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,szKey,0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if((err=RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + if(!kvi_strEqualCI(__tr2qs("URL:IRC Protocol").toLocal8Bit().data(),pcBuffer)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + if((err=RegQueryValueEx(hKey,"URL Protocol",0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + szKey = szStoredKey + "\\DefaultIcon"; + len = QUERY_BUFFER; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,szKey,0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if(RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + QString szIcon = applicationFilePath() + ",0"; + szIcon.replace('/',"\\"); + if(!kvi_strEqualCI(szIcon.toLocal8Bit().data(),pcBuffer)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + szKey = szStoredKey + "\\Shell\\open"; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,szKey,0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if(RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + if(!kvi_strEqualCI(__tr2qs("Open with KVIrc").toLocal8Bit().data(),pcBuffer)) + { + free(pcBuffer); + return false; + } + } + + len = QUERY_BUFFER; + szKey = szStoredKey + "\\Shell\\open\\command"; + if(RegOpenKeyEx(HKEY_CLASSES_ROOT,szKey,0,KEY_READ,&hKey) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } + + if(RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) + { + free(pcBuffer); + return false; + } else { + QString szCmd = applicationFilePath() + " \"%1\""; + szCmd.replace('/',"\\"); + if(!kvi_strEqualCI(szCmd.toLocal8Bit().data(),pcBuffer)) + { + free(pcBuffer); + return false; + } + } + + free(pcBuffer); +#else +bool KviApplication::checkUriAssociations(const char *) +{ +#endif + return true; +} + + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) +void KviApplication::setupUriAssociations(const char * pcProto) +{ + HKEY hKey; + DWORD err; + + KviCString szStoredKey = pcProto; + KviCString szKey = szStoredKey; + + QByteArray tmp; + QString szAppPath = applicationFilePath(); + szAppPath.replace('/',"\\"); + + SHDeleteKey(HKEY_CLASSES_ROOT,szKey); + + err = RegCreateKeyEx(HKEY_CLASSES_ROOT,szKey,0,0,0,KEY_WRITE,0,&hKey,0); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"URL:IRC Protocol",16); + RegSetValueEx(hKey,"URL Protocol",0,REG_SZ,(LPBYTE)"",0); + + szKey = szStoredKey + "\\DefaultIcon"; + RegCreateKeyEx(HKEY_CLASSES_ROOT,szKey,0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + ",0").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + szKey = szStoredKey + "\\Shell\\open"; + RegCreateKeyEx(HKEY_CLASSES_ROOT,szKey,0,0,0,KEY_WRITE,0,&hKey,0); + tmp = __tr2qs("Open with KVIrc").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + szKey = szStoredKey + "\\Shell\\open\\command"; + RegCreateKeyEx(HKEY_CLASSES_ROOT,szKey,0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + " --external \"%1\"").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); +#else +void KviApplication::setupUriAssociations(const char *) +{ +#endif +} + +void KviApplication::setupFileAssociations() +{ +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + HKEY hKey; + DWORD err; + + QByteArray tmp; + QString szAppPath = applicationFilePath(); + szAppPath.replace('/',"\\"); + + SHDeleteKey(HKEY_CLASSES_ROOT,".kvs"); + + err = RegCreateKeyEx(HKEY_CLASSES_ROOT,".kvs",0,0,0,KEY_WRITE,0,&hKey,0); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"KVIrcScript",11); + + SHDeleteKey(HKEY_CLASSES_ROOT,"KVIrcScript"); + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = __tr2qs("KVIrc KVS Script").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\DefaultIcon",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + ",1").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\Shell\\Parse",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = __tr2qs("Run KVS Script").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\Shell\\Parse\\command",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + " \"%1\"").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + //Configs + SHDeleteKey(HKEY_CLASSES_ROOT,".kvc"); + + err = RegCreateKeyEx(HKEY_CLASSES_ROOT,".kvc",0,0,0,KEY_WRITE,0,&hKey,0); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"KVIrcConfig",11); + + SHDeleteKey(HKEY_CLASSES_ROOT,"KVIrcConfig"); + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcConfig",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = __tr2qs("KVIrc Configuration File").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcConfig\\DefaultIcon",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + ",2").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + // Themes + SHDeleteKey(HKEY_CLASSES_ROOT,".kvt"); + + err = RegCreateKeyEx(HKEY_CLASSES_ROOT,".kvt",0,0,0,KEY_WRITE,0,&hKey,0); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"KVIrcTheme",11); + + SHDeleteKey(HKEY_CLASSES_ROOT,"KVIrcTheme"); + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = __tr2qs("KVIrc Theme Package").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme\\DefaultIcon",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + ",3").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme\\Shell\\Install",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = __tr2qs("Install Theme Package").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme\\Shell\\Install\\command",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + " \"%1\"").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + //Addons + SHDeleteKey(HKEY_CLASSES_ROOT,".kva"); + + err = RegCreateKeyEx(HKEY_CLASSES_ROOT,".kva",0,0,0,KEY_WRITE,0,&hKey,0); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"KVIrcAddon",11); + + SHDeleteKey(HKEY_CLASSES_ROOT,"KVIrcAddon"); + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = __tr2qs("KVIrc Addon Package").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon\\DefaultIcon",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + ",4").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon\\Shell\\Install",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = __tr2qs("Install Package").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + + RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon\\Shell\\Install\\command",0,0,0,KEY_WRITE,0,&hKey,0); + tmp = QString(szAppPath + " \"%1\"").toLocal8Bit(); + RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); + +#endif +} + +void KviApplication::findGlobalKvircDirectory() +{ + // Look for the installation directory + // with the image and help files inside +#ifdef GLOBAL_KVIRC_DIR + m_szGlobalKvircDir = GLOBAL_KVIRC_DIR; + KviFileUtils::adjustFilePath(m_szGlobalKvircDir); + if(checkGlobalKvircDirectory(m_szGlobalKvircDir)) + return; +#endif //GLOBAL_KVIRC_DIR + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + + m_szGlobalKvircDir = applicationDirPath(); + KviFileUtils::adjustFilePath(m_szGlobalKvircDir); + if(checkGlobalKvircDirectory(m_szGlobalKvircDir)) + return; + + KviMessageBox::warning("Unable to find the shared Kvirc directory.\n"\ + "I have tried %Q, but it seemed to fail\n" \ + "Trying to run anyway...\n",&m_szGlobalKvircDir); +#else + + // Check for MacOS X Bundle compilation + #ifdef COMPILE_ON_MAC + m_szGlobalKvircDir = applicationDirPath(); + m_szGlobalKvircDir += "/../Resources/"; + #else + m_szGlobalKvircDir = KVIRC_RESOURCES_DIR; + #endif //COMPILE_ON_MAC + + if(checkGlobalKvircDirectory(m_szGlobalKvircDir)) + return; + + m_szGlobalKvircDir = ""; + + // DO NOT TRANSLATE THIS + // THE TRANSLATION DIRECTORY WAS NOT FOUND YET + // AND THE LOCALE IS NOT INITIALIZED AT ALL + + #ifdef COMPILE_KDE_SUPPORT + KviMessageBox::warning("Unable to find the shared Kvirc directory.\n"\ + "The usual path for this directory is $KDEDIR/share/apps/kvirc.\n"\ + "Are you sure that 'make install' worked correctly ?\n"\ + "Please make sure that you have the read permission to that directory\n"\ + "and you have set KDEDIR correctly. You may also try to rerun 'make install'.\n"\ + "A detailed explaination of the Kvirc directory system is in the INSTALL document\n"\ + "shipped with the kvirc source dirstribution.\n"\ + "Trying to run anyway..."); + #elif defined(COMPILE_ON_MAC) + KviMessageBox::warning("Unable to find the shared KVIrc directory.\n"\ + "The usual path for this directory is ./Contents/Resources/kvirc within your application bundle.\n"\ + "Something went wrong during the bundle creation.\n"\ + "Please read the documentation and make sure to set proper paths for --prefix, -bindir, -libdir and --datadir during the configure run.\n"\ + "Trying to run anyway...\n"); + #else //!defined(COMPILE_KDE_SUPPORT) && !defined(COMPILE_ON_MAC) + KviMessageBox::warning("Unable to find the shared KVIrc directory.\n"\ + "The usual path for this directory is /usr/local/share/kvirc.\n"\ + "Are you sure that 'make install' worked correctly ?\n"\ + "Please make sure that you have the read permission to that directory.\n"\ + "You may also need to rerun 'make install'.\n"\ + "A detailed explaination of the KVIrc directory system is in the INSTALL document\n"\ + "shipped with the kvirc source dirstribution.\n"\ + "Trying to run anyway...\n"); + #endif //!COMPILE_ON_MAC +#endif +} + + +bool KviApplication::findLocalKvircDirectory() +{ + // Here we check if we already did the setup + // and we have the kvirc local directory saved somewhere +#ifdef COMPILE_KDE_SUPPORT + if(m_szConfigFile.isEmpty()) + { + // don't do that if user supplied a config file :) + KConfig oKCfg("kvirc"); + KConfigGroup oKCfgMainGroup(&oKCfg, "Main"); + + m_szLocalKvircDir = oKCfgMainGroup.readEntry("LocalKvircDirectory"); + + unsigned int uSourcesDate = oKCfgMainGroup.readEntry("SourcesDate").toInt(); + if(uSourcesDate < KVI_SOURCES_DATE_NUMERIC_FORCE_SETUP) + return false; // we force a setup anyway + + // If we have it, ok...done + if(checkLocalKvircDirectory()) + return true; + } +#endif //COMPILE_KDE_SUPPORT + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + if(m_bPortable) + { + m_szLocalKvircDir = g_pApp->applicationDirPath() + KVI_PATH_SEPARATOR_CHAR + "Settings"; + if(checkLocalKvircDirectory()) + return true; + } +#endif + //Check if we have a special .kvirc.rc in $HOME + QString szF = QDir::homePath(); + + if(!m_szConfigFile.isEmpty()) + { + QString szConfig = m_szConfigFile; + if(QDir::isRelativePath(szConfig)) + { + szF += KVI_PATH_SEPARATOR; + szF += szConfig; + } else { + szF = szConfig; + } + } else { + szF += KVI_PATH_SEPARATOR; + szF += KVI_HOME_CONFIG_FILE_NAME; + } + + //If the file exists, read the first non empty line. + KviConfigurationFile cfgx(szF,KviConfigurationFile::Read); + + cfgx.setGroup("Main"); + m_szLocalKvircDir = cfgx.readEntry("LocalKvircDirectory",""); + + unsigned int uSourcesDate = cfgx.readUIntEntry("SourcesDate",0); + if(uSourcesDate < KVI_SOURCES_DATE_NUMERIC_FORCE_SETUP) + return false; // we force a setup anyway + + // If we have it, ok...done + return checkLocalKvircDirectory(); +} + +void KviApplication::loadDirectories() +{ + // First find the global (readable) one... + findGlobalKvircDirectory(); + // Init locale + QString szLocalePath = m_szGlobalKvircDir; + szLocalePath.append(KVI_PATH_SEPARATOR); + szLocalePath.append("locale"); + szLocalePath.append(KVI_PATH_SEPARATOR); + + KviLocale::init(this,szLocalePath); + + //__debug_1arg("Global Kvirc directory is %s",m_szGlobalKvircDir.ptr()); + // Now look for the local (writable) one + m_bFirstTimeRun = !findLocalKvircDirectory(); + + if(m_bFirstTimeRun) + setupBegin(); + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + if(m_bPortable) return; +#endif + if(!checkFileAssociations()) setupFileAssociations(); + if(!checkUriAssociations("irc")) setupUriAssociations("irc"); + if(!checkUriAssociations("ircs")) setupUriAssociations("ircs"); + if(!checkUriAssociations("irc6")) setupUriAssociations("irc6"); + if(!checkUriAssociations("ircs6")) setupUriAssociations("ircs6"); +} + +void KviApplication::setupBegin() +{ + //We must do the setup...ask the user.. + QString szSetupLib; + +#ifdef KVIRC_MODULES_DIR + szSetupLib = KVIRC_MODULES_DIR; +#else + getGlobalKvircDirectory(szSetupLib,KviApplication::Modules); +#endif + + KviQString::ensureLastCharIs(szSetupLib, KVI_PATH_SEPARATOR_CHAR); + +#if defined(COMPILE_ON_WINDOWS) + szSetupLib.append("kvisetup.dll"); +#elif defined(COMPILE_ON_MINGW) + szSetupLib.append("libkvisetup.dll"); +#else + szSetupLib.append("libkvisetup.so"); +#endif + g_pSetupLibrary = new QLibrary(szSetupLib); + if(!g_pSetupLibrary->load()) + { + KviMessageBox::warning(__tr2qs("Ops...it looks like I can't load modules on this sytem.\n" \ + "I have been looking for the %s library but I haven't been able to load it\n" \ + "due to the following error: \"%s\"\nAborting."),szSetupLib.toUtf8().data(),g_pSetupLibrary->errorString().toUtf8().data()); +#if defined(COMPILE_ON_WINDOWS) + ExitProcess(-1); +#elif defined(COMPILE_ON_MINGW) + ExitProcess(1); +#else + ::exit(-1); +#endif + } + + bool (*sfunc)() = (bool(*)())g_pSetupLibrary->resolve("setup_begin"); + if(!sfunc) + { + KviMessageBox::warning(__tr2qs("Ops...it looks like you have a broken distribution.\n" \ + "The setup module does not export the \"setup_begin\" function.\n" \ + "Aborting!")); +#if defined(COMPILE_ON_WINDOWS) + ExitProcess(-1); +#elif defined(COMPILE_ON_MINGW) + ExitProcess(1); +#else + ::exit(-1); +#endif + } + + bool bRet = sfunc(); + + if(!bRet) + { + KviMessageBox::warning(__tr2qs("Setup aborted")); +#if defined(COMPILE_ON_WINDOWS) + ExitProcess(-1); +#elif defined(COMPILE_ON_MINGW) + ExitProcess(1); +#else + ::exit(-1); +#endif + } + + // Now save it + //Let it be done by setup function +// saveKvircDirectory(); +} + +void KviApplication::setupFinish() +{ + if(!g_pSetupLibrary) + { + qDebug("Oops... lost the setup library ?"); + return; + } + + void (*sfunc)() = (void(*)())g_pSetupLibrary->resolve("setup_finish"); + if(!sfunc) + { + KviMessageBox::warning(__tr2qs("Ops...it looks like you have a broken distribution.\n" \ + "The setup module does not export the \"setup_finish\" function.\n" \ + "Trying to continue anyway...")); + } + + sfunc(); + + g_pSetupLibrary->unload(); + delete g_pSetupLibrary; + g_pSetupLibrary = 0; +} + +void KviApplication::saveKvircDirectory() +{ + // Here we save the local directory path +#ifdef COMPILE_KDE_SUPPORT + // In KDE we use the application config file + if(m_szConfigFile.isEmpty()) + { + // not if user supplied a config file + KConfig * pCfg = new KConfig("kvirc"); + KConfigGroup * pCfgMainGroup = new KConfigGroup(pCfg,"Main"); + if(pCfg) + { + if(pCfg->accessMode() == KConfig::ReadWrite) + { + pCfgMainGroup->writeEntry("LocalKvircDirectory",m_szLocalKvircDir); + pCfgMainGroup->writeEntry("SourcesDate",KVI_SOURCES_DATE_NUMERIC); + pCfg->sync(); + delete pCfgMainGroup; + pCfgMainGroup = 0; + return; + } + } + } +#endif //COMPILE_KDE_SUPPORT + // In NON-KDE we use $HOME/.kvirc.rc or $HOME/kvirc.ini + QString szF = QDir::homePath(); + if(!m_szConfigFile.isEmpty()) + { + //Must be changed from QString::fromLocal8Bit to QTextCodec::codecForLocale() + QString szConfig = m_szConfigFile; + if(QDir::isRelativePath(szConfig)) + { + szF += KVI_PATH_SEPARATOR; + szF += szConfig; + } else { + szF = szConfig; + } + } else { + szF += KVI_PATH_SEPARATOR; + szF += KVI_HOME_CONFIG_FILE_NAME; + } + //FIXME: LOCALE BROKEN!!! + + KviConfigurationFile cfgx(szF,KviConfigurationFile::Write); + + cfgx.setGroup("Main"); + cfgx.writeEntry("LocalKvircDirectory",m_szLocalKvircDir); + cfgx.writeEntry("SourcesDate",KVI_SOURCES_DATE_NUMERIC); +} diff --git a/src/kvirc/kernel/KviAsynchronousConnectionData.cpp b/src/kvirc/kernel/KviAsynchronousConnectionData.cpp new file mode 100644 index 000000000..a02753adf --- /dev/null +++ b/src/kvirc/kernel/KviAsynchronousConnectionData.cpp @@ -0,0 +1,41 @@ +//============================================================================= +// +// File : KviAsynchronousConnectionData.cpp +// Creation date : Sun 04 Jul 2004 16:22:25 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviAsynchronousConnectionData.h" + +KviAsynchronousConnectionData::KviAsynchronousConnectionData() +: KviHeapObject() +{ + m_pReconnectInfo=0; + bUseLastServerInContext = false; +} + +KviAsynchronousConnectionData::~KviAsynchronousConnectionData() +{ + if(m_pReconnectInfo) + delete m_pReconnectInfo; +} + diff --git a/src/kvirc/kernel/KviAsynchronousConnectionData.h b/src/kvirc/kernel/KviAsynchronousConnectionData.h new file mode 100644 index 000000000..03062832d --- /dev/null +++ b/src/kvirc/kernel/KviAsynchronousConnectionData.h @@ -0,0 +1,56 @@ +#ifndef _KVI_ASYNCHRONOUSCONNECTIONDATA_H_ +#define _KVI_ASYNCHRONOUSCONNECTIONDATA_H_ +//============================================================================= +// +// File : KviAsynchronousConnectionData.h +// Creation date : Sun 04 Jul 2004 16:22:25 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviHeapObject.h" +#include "KviIrcServer.h" + +class KviAsynchronousConnectionData : public KviHeapObject +{ +public: + KviAsynchronousConnectionData(); + ~KviAsynchronousConnectionData(); +public: + QString szServer; + bool bUseLastServerInContext; // this is checked ONLY if szServer is empty + kvi_u32_t uPort; + bool bPortIsOk; + bool bUseIPv6; + bool bUseSSL; + bool bSTARTTLS; + QString szBindAddress; // ip address (or interface name) to bind the connection to + QString szCommandToExecAfterConnect; + QString szLinkFilter; + QString szPass; + QString szNick; + QString szInitUMode; + QString szServerId; + KviIrcServerReconnectInfo * m_pReconnectInfo; +}; + +#endif //!_KVI_ASYNCHRONOUSCONNECTIONDATA_H_ diff --git a/src/kvirc/kernel/KviCoreActions.cpp b/src/kvirc/kernel/KviCoreActions.cpp new file mode 100644 index 000000000..74c2ae9d9 --- /dev/null +++ b/src/kvirc/kernel/KviCoreActions.cpp @@ -0,0 +1,1179 @@ +//============================================================================= +// +// File : KviCoreActions.cpp +// Creation date : Mon 22 Nov 2004 02:30:47 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviCoreActions.h" +#include "kvi_shortcuts.h" +#include "KviMainWindow.h" +#include "KviLocale.h" +#include "KviIrcContext.h" +#include "KviIconManager.h" +#include "KviApplication.h" +#include "KviCustomToolBar.h" +#include "KviActionDrawer.h" +#include "KviActionManager.h" +#include "KviKvsAction.h" +#include "KviMdiManager.h" +#include "KviIrcToolBar.h" +#include "KviLocale.h" +#include "KviIrcUrl.h" +#include "KviIrcConnection.h" +#include "KviIrcConnectionUserInfo.h" +#include "kvi_coreactionnames.h" +#include "KviIrcConnectionServerInfo.h" +#include "KviKvsScript.h" +#include "KviTalPopupMenu.h" + +#include + +void register_core_actions(KviActionManager * m) +{ + m->registerAction(new KviConnectAction(m)); // this as parent will destroy it on exit! + m->registerAction(new KviSeparatorAction(m)); + m->registerAction(new KviIrcContextDisplayAction(m)); + m->registerAction(new KviJoinChannelAction(m)); + m->registerAction(new KviChangeNickAction(m)); + m->registerAction(new KviConnectToServerAction(m)); + m->registerAction(new KviChangeUserModeAction(m)); + m->registerAction(new KviGoAwayAction(m)); + m->registerAction(new KviIrcToolsAction(m)); + m->registerAction(new KviIrcOperationsAction(m)); + + KviAction * a; + +#define SCRIPT_ACTION(__name,__code,__visible,__description,__category,__icon,__smallicon,__flags,__accel) \ + a = new KviKvsAction(m, \ + QString(__name), \ + QString(__code), \ + QString(__visible), \ + QString(__description), \ + __category, \ + QString(__icon), \ + QString("%1").arg(__smallicon), \ + __flags, \ + __accel); \ + m->registerAction(a) + +#define SLOT_ACTION(__name,__object,__slot,__visible,__description,__category,__icon,__smallicon,__flags,__accel) \ + a = new KviAction(m, \ + QString(__name), \ + QString(__visible), \ + QString(__description), \ + __category, \ + QString(__icon), \ + QString("%1").arg(__smallicon), \ + __flags, \ + __accel); \ + QObject::connect(a,SIGNAL(activated()),__object,__slot); \ + m->registerAction(a) + + SCRIPT_ACTION( + KVI_COREACTION_SERVEROPTIONS, + "options.edit -t KviIrcServerOptionsWidget", + __tr2qs("Configure Servers..."), + __tr2qs("Allows you to configure the servers and eventually to connect to them"), + KviActionManager::categorySettings(), + "kvi_bigicon_servers.png", + KVI_SMALLICON_SERVER, + 0, + KVI_SHORTCUTS_SERVERS); + + SCRIPT_ACTION( + KVI_COREACTION_MANAGEADDONS, + "addon.dialog -t", + __tr2qs("Manage Addons..."), + __tr2qs("Allows you to manage the script-based addons"), + KviActionManager::categorySettings(), + "kvi_bigicon_addons.png", + KVI_SMALLICON_ADDONS, + 0, + KVI_SHORTCUTS_MANAGE_ADDONS); + + SCRIPT_ACTION( + KVI_COREACTION_EDITREGUSERS, + "reguser.edit -t", + __tr2qs("Configure Registered Users..."), + __tr2qs("Shows a dialog that allows editing the registered user entries"), + KviActionManager::categorySettings(), + "kvi_bigicon_regusers.png", + KVI_SMALLICON_REGUSERS, + 0, + KVI_SHORTCUTS_USERS); + + SCRIPT_ACTION( + KVI_COREACTION_IDENTITYOPTIONS, + "options.edit -t KviIdentityOptionsWidget", + __tr2qs("Configure Identity..."), + __tr2qs("Allows you to configure nickname, username, avatar etc..."), + KviActionManager::categorySettings(), + "kvi_bigicon_identity.png", + KVI_SMALLICON_WHO, + 0, + KVI_SHORTCUTS_IDENTITY); + + SCRIPT_ACTION( + KVI_COREACTION_SOCKETSPY, + "socketspy.open", + __tr2qs("Show SocketSpy..."), + __tr2qs("Shows a window that allows monitoring the socket traffic"), + KviActionManager::categoryScripting(), + "kvi_bigicon_socketspy.png", + KVI_SMALLICON_SPY, + KviAction::NeedsContext, + QString()); + + SCRIPT_ACTION( + KVI_COREACTION_NETWORKLINKS, + "links.open", + __tr2qs("Get Network Links"), + __tr2qs("Shows a window that allows viewing the network links"), + KviActionManager::categoryIrc(), + "kvi_bigicon_networklinks.png", + KVI_SMALLICON_LINKS, + KviAction::NeedsContext, + QString()); + + SCRIPT_ACTION( + KVI_COREACTION_CHANNELLIST, + "list.open", + __tr2qs("Get Channel List"), + __tr2qs("Shows a window that allows listing the network channels"), + KviActionManager::categoryIrc(), + "kvi_bigicon_channellist.png", + KVI_SMALLICON_LIST, + KviAction::NeedsContext, + QString()); + + SCRIPT_ACTION( + KVI_COREACTION_GENERALOPTIONS, + "options.dialog -t", + __tr2qs("Configure KVIrc..."), + __tr2qs("Shows the general options dialog"), + KviActionManager::categorySettings(), + "kvi_bigicon_settings.png", + KVI_SMALLICON_OPTIONS, + 0, + KVI_SHORTCUTS_OPTIONS); + + SCRIPT_ACTION( + KVI_COREACTION_THEMEOPTIONS, + "options.dialog -t theme", + __tr2qs("Configure Theme..."), + __tr2qs("Shows the theme options dialog"), + KviActionManager::categorySettings(), + "kvi_bigicon_themeoptions.png", + KVI_SMALLICON_THEMEOPTIONS, + 0, + KVI_SHORTCUTS_THEME); + + SCRIPT_ACTION( + KVI_COREACTION_MANAGETHEMES, + "theme.dialog -t", + __tr2qs("Manage Themes..."), + __tr2qs("Allows you to manage the themes"), + KviActionManager::categorySettings(), + "kvi_bigicon_theme.png", + KVI_SMALLICON_THEME, + 0, + KVI_SHORTCUTS_MANAGE_THEMES); + + SCRIPT_ACTION( + KVI_COREACTION_TOOLBAREDITOR, + "toolbareditor.open -t", + __tr2qs("Customize Toolbars..."), + __tr2qs("Shows a window that allows editing script toolbars"), + KviActionManager::categorySettings(), + "kvi_bigicon_toolbareditor.png", + KVI_SMALLICON_TOOLBAR, + 0, + KVI_SHORTCUTS_EDITORS_TOOLBAR); + + SCRIPT_ACTION( + KVI_COREACTION_JOINCHANNELS, + "channelsjoin.open", + __tr2qs("Join Channels..."), + __tr2qs("Shows a dialog that allows you join channels"), + KviActionManager::categoryIrc(), + "kvi_bigicon_channels.png", + KVI_SMALLICON_CHANNEL, + KviKvsAction::NeedsConnection | KviKvsAction::NeedsContext, + KVI_SHORTCUTS_JOIN); + + SCRIPT_ACTION( + KVI_COREACTION_ACTIONEDITOR, + "actioneditor.open", + __tr2qs("Edit Actions..."), + __tr2qs("Shows a window that allows editing actions"), + KviActionManager::categoryScripting(), + "kvi_bigicon_actioneditor.png", + KVI_SMALLICON_SCRIPTACTION, + 0, + KVI_SHORTCUTS_EDITORS_ACTION); + + SCRIPT_ACTION( + KVI_COREACTION_ALIASEDITOR, + "aliaseditor.open", + __tr2qs("Edit Aliases..."), + __tr2qs("Shows a window that allows editing aliases"), + KviActionManager::categoryScripting(), + "kvi_bigicon_aliaseditor.png", + KVI_SMALLICON_ALIAS, + 0, + KVI_SHORTCUTS_EDITORS_ALIAS); + + SCRIPT_ACTION( + KVI_COREACTION_CLASSEDITOR, + "classeditor.open", + __tr2qs("Edit Classes..."), + __tr2qs("Shows a window that allows editing classes"), + KviActionManager::categoryScripting(), + "kvi_bigicon_classeditor.png", + KVI_SMALLICON_CLASSEDITOR, + 0, + KVI_SHORTCUTS_EDITORS_CLASS); + + SCRIPT_ACTION( + KVI_COREACTION_EVENTEDITOR, + "eventeditor.open", + __tr2qs("Edit Events..."), + __tr2qs("Shows a window that allows editing script events"), + KviActionManager::categoryScripting(), + "kvi_bigicon_eventeditor.png", + KVI_SMALLICON_EVENT, + 0, + KVI_SHORTCUTS_EDITORS_EVENT); + + SCRIPT_ACTION( + KVI_COREACTION_POPUPEDITOR, + "popupeditor.open", + __tr2qs("Edit Popups..."), + __tr2qs("Shows a window that allows editing popup menus"), + KviActionManager::categoryScripting(), + "kvi_bigicon_popupeditor.png", + KVI_SMALLICON_POPUP, + 0, + KVI_SHORTCUTS_EDITORS_POPUP); + + SCRIPT_ACTION( + KVI_COREACTION_RAWEDITOR, + "raweditor.open", + __tr2qs("Edit Raw Events..."), + __tr2qs("Shows a window that allows editing raw scripting events"), + KviActionManager::categoryScripting(), + "kvi_bigicon_raweditor.png", + KVI_SMALLICON_RAWEVENT, + 0, + KVI_SHORTCUTS_EDITORS_RAW); + + SCRIPT_ACTION( + KVI_COREACTION_CODETESTER, + "codetester.open", + __tr2qs("Script Tester"), + __tr2qs("Creates an embedded editor for long scripts"), + KviActionManager::categoryScripting(), + "kvi_bigicon_codetester.png", + KVI_SMALLICON_BOMB, + 0, + KVI_SHORTCUTS_EDITORS_TESTER); + + SCRIPT_ACTION( + KVI_COREACTION_EXECUTEKVS, + "dialog.file(open,$tr(\"Select a Script File\")){ if(!$str.isEmpty($0))parse $0; }", + __tr2qs("Execute Script..."), + __tr2qs("Allows executing a KVS script from file"), + KviActionManager::categoryScripting(), + "kvi_bigicon_folder.png", + KVI_SMALLICON_FOLDER, + 0, + KVI_SHORTCUTS_EXEC); + + SCRIPT_ACTION( + KVI_COREACTION_HELPINDEX, + "help -m", + __tr2qs("Help Index"), + __tr2qs("Shows the documentation index"), + KviActionManager::categoryGeneric(), + "kvi_bigicon_help.png", + KVI_SMALLICON_HELP, + 0, + KVI_SHORTCUTS_HELP); + + SCRIPT_ACTION( + KVI_COREACTION_KVIRCMAILINGLIST, + "openurl http://www.kvirc.net/?id=mailinglist", + __tr2qs("Subscribe to the Mailing List"), + __tr2qs("Allows subscribing to the KVIrc mailing list"), + KviActionManager::categoryGeneric(), + "kvi_bigicon_mailinglist.png", + KVI_SMALLICON_MESSAGE, + 0, + QString()); + + SCRIPT_ACTION( + KVI_COREACTION_KVIRCHOMEPAGE, + "openurl http://www.kvirc.net", + __tr2qs("KVIrc WWW"), + __tr2qs("Opens the KVIrc homepage"), + KviActionManager::categoryGeneric(), + "kvi_bigicon_kvircwww.png", + KVI_SMALLICON_KVIRC, + 0, + QString()); + + SCRIPT_ACTION( + KVI_COREACTION_KVIRCRUHOMEPAGE, + "openurl http://www.kvirc.ru", + __tr2qs("KVIrc Russian WWW"), + __tr2qs("Opens the KVIrc homepage in russian"), + KviActionManager::categoryGeneric(), + "kvi_bigicon_kvircwww.png", + KVI_SMALLICON_KVIRC, + 0, + QString()); + + SCRIPT_ACTION( + KVI_COREACTION_SCREENSHOT, + "theme.screenshot", + __tr2qs("Acquire Screenshot"), + __tr2qs("Acquires a Screenshot of the KVIrc main window"), + KviActionManager::categoryGeneric(), + "kvi_bigicon_screenshot.png", + KVI_SMALLICON_SCREENSHOT, + 0, + QString()); + + + SLOT_ACTION( + KVI_COREACTION_CASCADEWINDOWS, + g_pFrame->mdiManager(), + SLOT(cascadeMaximized()), + __tr2qs("Cascade windows"), + __tr2qs("Arranges the MDI windows in a maximized-cascade fashion"), + KviActionManager::categoryGUI(), + "kvi_bigicon_cascadewindows.png", + KVI_SMALLICON_CASCADEWINDOWS, + 0, + QString()); + + SLOT_ACTION( + KVI_COREACTION_TILEWINDOWS, + g_pFrame->mdiManager(), + SLOT(tile()), + __tr2qs("Tile windows"), + __tr2qs("Tiles the MDI windows with the currently selected tile method"), + KviActionManager::categoryGUI(), + "kvi_bigicon_tilewindows.png", + KVI_SMALLICON_TILEWINDOWS, + 0, + QString()); + + SLOT_ACTION( + KVI_COREACTION_MINIMIZEALLWINDOWS, + g_pFrame->mdiManager(), + SLOT(minimizeAll()), + __tr2qs("Minimize all windows"), + __tr2qs("Minimized all the currently visible MDI windows"), + KviActionManager::categoryGUI(), + "kvi_bigicon_minimizeallwindows.png", + KVI_SMALLICON_MINIMIZE, + 0, + QString()); + + SLOT_ACTION( + KVI_COREACTION_NEWIRCCONTEXT, + g_pFrame, + SLOT(newConsole()), + __tr2qs("New IRC Context"), + __tr2qs("Creates a new IRC context console"), + KviActionManager::categoryIrc(), + "kvi_bigicon_newirccontext.png", + KVI_SMALLICON_CONSOLE, + 0, + KVI_SHORTCUTS_CONTEXT); + + SLOT_ACTION( + KVI_COREACTION_QUITKVIRC, + g_pApp, + SLOT(quit()), + __tr2qs("Quit KVIrc"), + __tr2qs("Quits KVIrc closing all the current connections"), + KviActionManager::categoryGeneric(), + "kvi_bigicon_quit.png", + KVI_SMALLICON_QUITAPP, + 0, + QString()); +} + + +KviIrcContextDisplayAction::KviIrcContextDisplayAction(QObject * pParent) +: KviAction(pParent, + QString(KVI_COREACTION_IRCCONTEXTDISPLAY), + __tr2qs("IRC Context Display"), + __tr2qs("Shows a small display with IRC context information"), + KviActionManager::categoryIrc(), + "kvi_bigicon_irccontextdisplay.png", + KVI_SMALLICON_NONE, + NeedsContext | NeedsConnection) +{ +} + +void KviIrcContextDisplayAction::setup() +{ + KviAction::setup(); + connect(g_pFrame,SIGNAL(activeConnectionServerInfoChanged()),this,SLOT(activeContextStateChanged())); + connect(g_pFrame,SIGNAL(activeConnectionNickNameChanged()),this,SLOT(activeContextStateChanged())); + connect(g_pFrame,SIGNAL(activeConnectionUserModeChanged()),this,SLOT(activeContextStateChanged())); + connect(g_pFrame,SIGNAL(activeConnectionAwayStateChanged()),this,SLOT(activeContextStateChanged())); + connect(g_pFrame,SIGNAL(activeConnectionLagChanged()),this,SLOT(activeContextStateChanged())); +} + +bool KviIrcContextDisplayAction::addToPopupMenu(KviTalPopupMenu *) +{ + // QT4SUX: Widgets can be no longer added to popup menus.. what about labels ? + return true; +} + +QWidget * KviIrcContextDisplayAction::addToCustomToolBar(KviCustomToolBar *t) +{ + if(!setupDone()) setup(); + KviIrcContextDisplay * w = new KviIrcContextDisplay(t,"kvirc.irccontextdisplay"); + t->addWidget(w); + registerWidget(w); + return w; +} + +void KviIrcContextDisplayAction::activeContextChanged() +{ + if(m_pWidgetList) + { + for(QWidget * w = m_pWidgetList->first();w;w = m_pWidgetList->next()) + w->update(); + } +} + +void KviIrcContextDisplayAction::activeContextStateChanged() +{ + if(m_pWidgetList) + { + for(QWidget * w = m_pWidgetList->first();w;w = m_pWidgetList->next()) + w->update(); + } +} + +void KviIrcContextDisplayAction::setEnabled(bool) +{ + // does nothing here : always enabled! +} + + + + +KviSeparatorAction::KviSeparatorAction(QObject * pParent) +: KviAction(pParent, + QString(KVI_COREACTION_SEPARATOR), + __tr2qs("Separator"), + __tr2qs("Acts as a separator for other items: performs no action"), + KviActionManager::categoryGeneric(), + KVI_BIGICON_SEPARATOR, + KVI_SMALLICON_NONE, + 0) +{ +} + + +bool KviSeparatorAction::addToPopupMenu(KviTalPopupMenu * p) +{ + if(!setupDone()) setup(); + p->insertSeparator(); + return true; +} + +QWidget * KviSeparatorAction::addToCustomToolBar(KviCustomToolBar * t) +{ + if(!setupDone()) setup(); + QWidget * w = new KviCustomToolBarSeparator(t,"kvirc.separator"); + registerWidget(w); + t->addWidget(w); + return w; +} + + +KviConnectAction::KviConnectAction(QObject * pParent) +: KviAction(pParent, + QString(KVI_COREACTION_CONNECT), + __tr2qs("Connect/Disconnect"), + __tr2qs("Allows you to connect to a server or to terminate the current connection"), + KviActionManager::categoryIrc(), + KVI_BIGICON_CONNECTED, + KVI_SMALLICON_NONE, // no small icon for now + NeedsContext | NeedsConnection, + QString(KVI_SHORTCUTS_CONNECT)) +{ +} + + +void KviConnectAction::reloadImages() +{ + activeContextStateChanged(); +} + +void KviConnectAction::activeContextChanged() +{ + activeContextStateChanged(); +} + +void KviConnectAction::activeContextStateChanged() +{ + + KviPointerList * bl = widgetList(); + if(!bl)return; + + QPixmap * p; + QString txt; + KviIrcContext * c = g_pFrame->activeContext(); + if(c) + { + switch(c->state()) + { + case KviIrcContext::Idle: + p = g_pIconManager->getBigIcon(KVI_BIGICON_DISCONNECTED); + txt = m_szConnectString; + break; + case KviIrcContext::Connecting: + case KviIrcContext::LoggingIn: + p = g_pIconManager->getBigIcon(KVI_BIGICON_CONNECTING); + txt = m_szAbortConnectionString; + break; + case KviIrcContext::Connected: + p = g_pIconManager->getBigIcon(KVI_BIGICON_CONNECTED); + txt = m_szDisconnectString; + break; + default: + p = 0; + break; + } + } else { + p = 0; + } + + if(p) + { + for(QToolButton * b = (QToolButton *)bl->first();b;b =(QToolButton *)bl->next()) + { + if(!b->isEnabled())b->setEnabled(true); + b->setIcon(QIcon(*p)); + b->setText(txt); + } + } else { + for(QToolButton * b = (QToolButton *)bl->first();b;b = (QToolButton *)bl->next()) + { + if(b->isEnabled())b->setEnabled(false); + } + } +} + +void KviConnectAction::setup() +{ + KviAction::setup(); + m_szConnectString = __tr2qs("Connect"); + m_szAbortConnectionString = __tr2qs("Abort Connection"); + m_szDisconnectString = __tr2qs("Disconnect"); +} + +void KviConnectAction::activate() +{ + KviIrcContext * c = g_pFrame->activeContext(); + if(c)c->connectOrDisconnect(); +} + +bool KviConnectAction::addToPopupMenu(KviTalPopupMenu *p) +{ + if(!setupDone())setup(); + KviIrcContext * c = g_pFrame->activeContext(); + int id; + + + QString t; + if(c) + { + switch(c->state()) + { + case KviIrcContext::Idle: + t = m_szConnectString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + p->insertItem(t,this,SLOT(activate())); + break; + case KviIrcContext::Connecting: + case KviIrcContext::LoggingIn: + t = m_szAbortConnectionString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + p->insertItem(t,this,SLOT(activate())); + break; + case KviIrcContext::Connected: + t = m_szDisconnectString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + p->insertItem(t,this,SLOT(activate())); + break; + default: + t = m_szConnectString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + id = p->insertItem(t,this,SLOT(activate())); + p->setItemEnabled(id,false); + break; + } + } else { + t = m_szConnectString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + id = p->insertItem(t,this,SLOT(activate())); + p->setItemEnabled(id,false); + } + return true; +} + +QWidget * KviConnectAction::addToCustomToolBar(KviCustomToolBar *t) +{ + if(!setupDone())setup(); + QToolButton * b = new QToolButton(t); + b->setIcon(*(g_pIconManager->getBigIcon(KVI_BIGICON_DISCONNECTED))); + b->setText(m_szConnectString); + b->setStatusTip(m_szConnectString); + b->setObjectName(name()); + connect(b, SIGNAL(clicked()), this, SLOT(activate())); + registerWidget(b); + t->addWidget(b); + activeContextStateChanged(); + return b; +} + + +KviSubmenuAction::KviSubmenuAction( + QObject * pParent, + const QString &szName, + const QString &szScriptCode, + const QString &szVisibleName, + const QString &szDescription, + KviActionCategory * pCategory, + const QString &szBigIconId, + const QString &szSmallIconId, + unsigned int uFlags + ) +: KviKvsAction( + pParent, + szName, + szScriptCode, + szVisibleName, + szDescription, + pCategory, + szBigIconId, + szSmallIconId, + uFlags + ) +{ + m_pPopup = 0; +} + +KviSubmenuAction::~KviSubmenuAction() +{ + if(m_pPopup)delete m_pPopup; +} + +void KviSubmenuAction::setup() +{ + KviKvsAction::setup(); + if(!m_pPopup) + { + m_pPopup = new KviTalPopupMenu(); + connect(m_pPopup,SIGNAL(aboutToShow()),this,SLOT(popupAboutToShow())); + connect(m_pPopup,SIGNAL(activated(int)),this,SLOT(popupActivated(int))); + } +} + +void KviSubmenuAction::popupAboutToShow() +{ +} + +void KviSubmenuAction::popupActivated(int) +{ +} + +bool KviSubmenuAction::addToPopupMenu(KviTalPopupMenu *p) +{ + if(!setupDone()) setup(); + int id = p->insertItem(*(smallIcon()),visibleName(),m_pPopup); + if(!isEnabled()) p->setItemEnabled(id,false); + return true; +} + +QWidget * KviSubmenuAction::addToCustomToolBar(KviCustomToolBar *t) +{ + if(!setupDone()) setup(); + QToolButton * b = new QToolButton(t); + QPixmap * p = bigIcon(); + b->setIcon(p ? *p : QPixmap()); + b->setText(visibleName()); + b->setStatusTip(visibleName()); + b->setObjectName(name()); + connect(b, SIGNAL(clicked()), this, SLOT(activate())); + + b->setMenu(m_pPopup); + + b->setPopupMode( scriptCode().isEmpty() ? QToolButton::InstantPopup : QToolButton::MenuButtonPopup); + t->addWidget(b); + registerWidget(b); + if(!isEnabled()) b->setEnabled(false); + return b; +} + + +KviJoinChannelAction::KviJoinChannelAction(QObject * pParent) +: KviSubmenuAction(pParent, + QString(KVI_COREACTION_CHANNELMENU), + QString("channelsjoin.open"), + __tr2qs("Join Channel"), + __tr2qs("Shows a popup menu that allows quickly selecting a channel to join"), + KviActionManager::categoryIrc(), + "kvi_bigicon_channelspopup.png", + QString("%1").arg(KVI_SMALLICON_CHANNEL), + NeedsConnection | NeedsContext) +{ +} + +void KviJoinChannelAction::popupAboutToShow() +{ + KviConsole * c = g_pActiveWindow->console(); + if(!c) return; + + g_pApp->fillRecentChannelsPopup(m_pPopup,c); + + m_pPopup->insertSeparator(); + m_pPopup->insertItem(*(smallIcon()),__tr2qs("Other...")); + m_pPopup->insertSeparator(); + m_pPopup->insertItem(__tr2qs("Clear Recent Channels List")); +} + +void KviJoinChannelAction::popupActivated(int id) +{ + KviConsole * c = g_pActiveWindow->console(); + if(!c)return; + + QString szItemText = m_pPopup->text(id); + if(!szItemText.isEmpty()) + { + QString szText; + if(szItemText == __tr2qs("Other...")) + { + szText = "channelsjoin.open"; + } else if(szItemText == __tr2qs("Clear Recent Channels List")) + { + szText = "option stringlistRecentChannels"; + } else { + szText = szItemText; + szText.prepend("join "); + } + KviKvsScript::run(szText,c); + } +} + + + +KviChangeNickAction::KviChangeNickAction(QObject * pParent) +: KviSubmenuAction( + pParent, + QString(KVI_COREACTION_NICKNAMEMENU), + QString("dialog.textinput(\"" + __tr2qs("Change Nickname") + "\",\"" + + __tr2qs("Please enter the new nickname") + "\",\"" + + __tr2qs("OK") + "\",\"" + + __tr2qs("Cancel") + "\"){ if($0 == 0 && $1 != \"\")nick $1; }"), + __tr2qs("Change Nickname"), + __tr2qs("Shows a popup menu that allows quickly changing the nickname"), + KviActionManager::categoryIrc(), + "kvi_bigicon_nickpopup.png", + QString("%1").arg(KVI_SMALLICON_NICK), + NeedsConnection | NeedsContext) +{ +} + +void KviChangeNickAction::popupAboutToShow() +{ + KviConsole * c = g_pActiveWindow->console(); + if(!c)return; + + g_pApp->fillRecentNicknamesPopup(m_pPopup,c); + + m_pPopup->insertSeparator(); + m_pPopup->insertItem(*(smallIcon()),__tr2qs("Other...")); + + m_pPopup->insertSeparator(); + m_pPopup->insertItem(*(smallIcon()),__tr2qs("Clear Recent Nicks List")); +} + +void KviChangeNickAction::popupActivated(int id) +{ + KviConsole * c = g_pActiveWindow->console(); + if(!c)return; + + QString text = m_pPopup->text(id); + if(!text.isEmpty()) + { + QString szText; + if(__tr2qs("Other...") == text) + { + activate(); + } else if(__tr2qs("Clear Recent Nicks List") == text) + { + KviKvsScript::run("option stringlistRecentNicknames",c); + } else { + szText = text; + szText.prepend("nick "); + KviKvsScript::run(szText,c); + } + } +} + + +KviConnectToServerAction::KviConnectToServerAction(QObject * pParent) +: KviSubmenuAction( + pParent, + QString(KVI_COREACTION_SERVERMENU), + QString("options.edit KviIrcServerOptionsWidget"), + __tr2qs("Connect To"), + __tr2qs("Shows a popup menu that allows quickly connecting to a server"), + KviActionManager::categoryIrc(), + "kvi_bigicon_server.png", + QString("%1").arg(KVI_SMALLICON_SERVER), + NeedsContext) +{ +} + +void KviConnectToServerAction::popupAboutToShow() +{ + g_pApp->fillRecentServersPopup(m_pPopup); + m_pPopup->insertSeparator(); + m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SERVER)),__tr2qs("Other...")); + m_pPopup->insertSeparator(); + m_pPopup->insertItem(__tr2qs("Clear Recent Servers List")); +} + +void KviConnectToServerAction::popupActivated(int id) +{ + KviConsole * c = g_pActiveWindow->console(); + if(!c)return; + + QString szItemText = m_pPopup->text(id); + if(!szItemText.isEmpty()) + { + if(szItemText == __tr2qs("Other...")) + { + activate(); + } else if(szItemText == __tr2qs("Clear Recent Servers List")) + { + KviKvsScript::run("option stringlistRecentServers",c); + } else { + KviCString szCommand; + QString szText = szItemText; + if(KviIrcUrl::parse(szText.toUtf8().data(),szCommand,KVI_IRCURL_CONTEXT_FIRSTFREE)) + { + KviKvsScript::run(szCommand.ptr(),c); + } + } + } +} + + +KviChangeUserModeAction::KviChangeUserModeAction(QObject * pParent) +: KviSubmenuAction( + pParent, + QString(KVI_COREACTION_USERMODEMENU), + QString(""), + __tr2qs("User Mode"), + __tr2qs("Shows a popup menu that allows quickly changing user modes"), + KviActionManager::categoryIrc(), + "kvi_bigicon_usermode.png", + QString("%1").arg(KVI_SMALLICON_MODE), + NeedsContext | NeedsConnection) +{ +} + +void KviChangeUserModeAction::popupAboutToShow() +{ + KviConsole * c = g_pActiveWindow->console(); + if(!c)return; + + m_pPopup->clear(); + int id; + QString szModes = g_pActiveWindow->connection()->serverInfo()->supportedUserModes(); + + id = m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_WALLOPS)),__tr2qs("Wallops (+w)")); + m_pPopup->setItemChecked(id,c->connection()->userInfo()->hasUserMode('w')); + id = m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SERVERNOTICE)),__tr2qs("Server Notices (+s)")); + m_pPopup->setItemChecked(id,c->connection()->userInfo()->hasUserMode('s')); + id = m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_INVISIBLE)),__tr2qs("Invisible (+i)")); + m_pPopup->setItemChecked(id,c->connection()->userInfo()->hasUserMode('i')); + + szModes.replace("w",""); + szModes.replace("s",""); + szModes.replace("i",""); + while(!szModes.isEmpty()) + { + QChar ccc = szModes[0]; + szModes.remove(0,1); + id = m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_MODE)),QString("+%1 Mode").arg(ccc)); + m_pPopup->setItemChecked(id,c->connection()->userInfo()->hasUserMode(ccc.toLatin1())); + } +} + +void KviChangeUserModeAction::popupActivated(int id) +{ + KviConsole * c = g_pActiveWindow->console(); + if(!c)return; + + QString text = m_pPopup->text(id); + if(!c->isConnected())return; + if(!text.isEmpty()) + { + int idx = text.indexOf('+'); + if(idx != -1) + { + idx++; + if(idx < text.length()) + { + QChar m = text[idx]; + QString szNick = c->connection()->userInfo()->nickName(); + KviQString::escapeKvs(&szNick); + QString command = "mode "; + command.append(szNick); + command.append(c->connection()->userInfo()->hasUserMode(m) ? " -" : " +"); + command.append(m); + KviKvsScript::run(command,c); + } + } + } +} + + +KviGoAwayAction::KviGoAwayAction(QObject * pParent) +: KviKvsAction( + pParent, + QString(KVI_COREACTION_AWAYBACK), + QString("if($away())back; else away;"), + __tr2qs("Away/Back"), + __tr2qs("Allows entering and leaving away state"), + KviActionManager::categoryIrc(), + "kvi_bigicon_nokeyboard.png", + QString("%1").arg(KVI_SMALLICON_NOTAWAY), + KviKvsAction::NeedsContext | KviKvsAction::NeedsConnection, + KVI_SHORTCUTS_AWAY + ) +{ +} + +void KviGoAwayAction::reloadImages() +{ + activeContextStateChanged(); +} + +void KviGoAwayAction::activeContextChanged() +{ + activeContextStateChanged(); +} + +void KviGoAwayAction::activeContextStateChanged() +{ + KviPointerList * bl = widgetList(); + if(!bl)return; + + QPixmap * p; + QString txt; + KviIrcContext * c = g_pFrame->activeContext(); + if(c) + { + if(c->state() == KviIrcContext::Connected) + { + if(c->connection()->userInfo()->isAway()) + { + p = g_pIconManager->getBigIcon("kvi_bigicon_keyboard.png"); + txt = m_szBackString; + } else { + p = g_pIconManager->getBigIcon("kvi_bigicon_nokeyboard.png"); + txt = m_szAwayString; + } + } else { + p = 0; + } + } else { + p = 0; + } + + if(p) + { + for(QToolButton * b = (QToolButton *)bl->first();b;b =(QToolButton *)bl->next()) + { + if(!b->isEnabled())b->setEnabled(true); + b->setIcon(QIcon(*p)); + b->setText(txt); + } + m_uInternalFlags |= KviAction::Enabled; + setEnabled(true); + } else { + for(QToolButton * b = (QToolButton *)bl->first();b;b = (QToolButton *)bl->next()) + { + if(b->isEnabled())b->setEnabled(false); + } + m_uInternalFlags &= ~KviAction::Enabled; + setEnabled(true); + } +} + +void KviGoAwayAction::setup() +{ + KviKvsAction::setup(); + m_szAwayString = __tr2qs("Enter Away Mode"); + m_szBackString = __tr2qs("Leave Away Mode"); + connect(g_pFrame,SIGNAL(activeConnectionAwayStateChanged()),this,SLOT(activeContextStateChanged())); +} + +bool KviGoAwayAction::addToPopupMenu(KviTalPopupMenu *p) +{ + if(!setupDone())setup(); + KviIrcContext * c = g_pFrame->activeContext(); + int id; + QString t; + if(c) + { + if(c->state() == KviIrcContext::Connected) + { + if(c->connection()->userInfo()->isAway()) + { + t = m_szBackString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + p->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_AWAY)),t,this,SLOT(activate())); + } else { + t = m_szAwayString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + p->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NOTAWAY)),t,this,SLOT(activate())); + } + } else { + t = m_szAwayString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + id = p->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NOTAWAY)),t,this,SLOT(activate())); + p->setItemEnabled(id,false); + } + } else { + t = m_szAwayString; + if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; + id = p->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NOTAWAY)),t,this,SLOT(activate())); + p->setItemEnabled(id,false); + } + return true; +} + +QWidget * KviGoAwayAction::addToCustomToolBar(KviCustomToolBar *t) +{ + if(!setupDone())setup(); + + QToolButton * b = new QToolButton(t); + b->setIcon(*(g_pIconManager->getBigIcon("kvi_bigicon_nokeyboard.png"))); + b->setText(m_szAwayString); + b->setStatusTip(m_szAwayString); + b->setObjectName(name()); + connect(b, SIGNAL(clicked()), this, SLOT(activate())); + + registerWidget(b); + t->addWidget(b); + activeContextStateChanged(); + return b; +} + + +KviIrcToolsAction::KviIrcToolsAction(QObject * pParent) +: KviSubmenuAction( + pParent, + QString(KVI_COREACTION_IRCTOOLS), + QString(""), + __tr2qs("Irc Tools"), + __tr2qs("Shows a popup menu with some IRC Tools"), + KviActionManager::categoryIrc(), + "kvi_bigicon_tools.png", + QString("%1").arg(KVI_SMALLICON_NONE), + NeedsConnection | NeedsContext) +{ +} + +void KviIrcToolsAction::popupAboutToShow() +{ + m_pPopup->clear(); + KviAction * a; + a = KviActionManager::instance()->getAction(KVI_COREACTION_SOCKETSPY); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_SEPARATOR); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_CHANNELLIST); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_NETWORKLINKS); + if(a)a->addToPopupMenu(m_pPopup); +} + +void KviIrcToolsAction::popupActivated(int) +{ +} + + +KviIrcOperationsAction::KviIrcOperationsAction(QObject * pParent) +: KviSubmenuAction( + pParent, + QString(KVI_COREACTION_IRCACTIONS), + QString(""), + __tr2qs("Irc Actions"), + __tr2qs("Shows a popup menu with some IRC Actions"), + KviActionManager::categoryIrc(), + "kvi_bigicon_actions.png", + QString("%1").arg(KVI_SMALLICON_NONE), + NeedsConnection | NeedsContext) +{ +} + +void KviIrcOperationsAction::popupAboutToShow() +{ + m_pPopup->clear(); + KviAction * a; + a = KviActionManager::instance()->getAction(KVI_COREACTION_AWAYBACK); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_USERMODEMENU); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_SEPARATOR); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_CHANNELMENU); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_NICKNAMEMENU); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_SEPARATOR); + if(a)a->addToPopupMenu(m_pPopup); + a = KviActionManager::instance()->getAction(KVI_COREACTION_SERVERMENU); + if(a)a->addToPopupMenu(m_pPopup); +} + +void KviIrcOperationsAction::popupActivated(int) +{ +} diff --git a/src/kvirc/kernel/KviCoreActions.h b/src/kvirc/kernel/KviCoreActions.h new file mode 100644 index 000000000..978d7cb50 --- /dev/null +++ b/src/kvirc/kernel/KviCoreActions.h @@ -0,0 +1,188 @@ +#ifndef _KVI_COREACTIONS_H_ +#define _KVI_COREACTIONS_H_ +//============================================================================= +// +// File : KviCoreActions.h +// Creation date : Mon 22 Nov 2004 02:30:47 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviAction.h" +#include "KviKvsAction.h" +#include "KviPointerList.h" + +class KviConnectAction : public KviAction +{ + Q_OBJECT +public: + KviConnectAction(QObject * pParent); +protected: + QString m_szConnectString; + QString m_szAbortConnectionString; + QString m_szDisconnectString; +public: + virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); + virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); +protected: + virtual void setup(); + virtual void reloadImages(); + virtual void activate(); + virtual void activeContextChanged(); + virtual void activeContextStateChanged(); +}; + +class KviSeparatorAction : public KviAction +{ + Q_OBJECT +public: + KviSeparatorAction(QObject * pParent); +public: + virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); + virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); +}; + +class KviTalPopupMenu; + +class KviSubmenuAction : public KviKvsAction +{ + Q_OBJECT +public: + KviSubmenuAction( + QObject * pParent, + const QString & szName, + const QString & szScriptCode, + const QString & szVisibleName, + const QString & szDescription, + KviActionCategory * pCategory = NULL, + const QString & szBigIconId = QString(), + const QString & szSmallIcoNId = QString(), + unsigned int uFlags = 0 + ); + ~KviSubmenuAction(); +protected: + KviTalPopupMenu * m_pPopup; +protected: + virtual void setup(); +public: + virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); + virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); +protected slots: + virtual void popupAboutToShow(); + virtual void popupActivated(int iId); +}; + +class KviJoinChannelAction : public KviSubmenuAction +{ + Q_OBJECT +public: + KviJoinChannelAction(QObject * pParent); +protected slots: + virtual void popupAboutToShow(); + virtual void popupActivated(int); +}; + +class KviChangeNickAction : public KviSubmenuAction +{ + Q_OBJECT +public: + KviChangeNickAction(QObject * pParent); +protected slots: + void popupAboutToShow(); + void popupActivated(int); +}; + +class KviConnectToServerAction : public KviSubmenuAction +{ + Q_OBJECT +public: + KviConnectToServerAction(QObject * pParent); +protected slots: + void popupAboutToShow(); + void popupActivated(int); +}; + +class KviChangeUserModeAction : public KviSubmenuAction +{ + Q_OBJECT +public: + KviChangeUserModeAction(QObject * pParent); +protected slots: + void popupAboutToShow(); + void popupActivated(int); +}; + +class KviIrcToolsAction : public KviSubmenuAction +{ + Q_OBJECT +public: + KviIrcToolsAction(QObject * pParent); +protected slots: + void popupAboutToShow(); + void popupActivated(int); +}; + + +class KviIrcOperationsAction : public KviSubmenuAction +{ + Q_OBJECT +public: + KviIrcOperationsAction(QObject * pParent); +protected slots: + void popupAboutToShow(); + void popupActivated(int); +}; + +#include "KviIrcToolBar.h" + +class KviIrcContextDisplayAction : public KviAction +{ + Q_OBJECT +public: + KviIrcContextDisplayAction(QObject * pParent); +public: + virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); + virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); + virtual void activeContextStateChanged(); + virtual void activeContextChanged(); + virtual void setEnabled(bool); + virtual void setup(); +}; + + +class KviGoAwayAction : public KviKvsAction +{ + Q_OBJECT +public: + KviGoAwayAction(QObject * pParent); +protected: + QString m_szAwayString; + QString m_szBackString; +public: + virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); + virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); +protected: + virtual void setup(); + virtual void reloadImages(); + virtual void activeContextChanged(); + virtual void activeContextStateChanged(); +}; + +#endif //_KVI_COREACTIONS_H_ diff --git a/src/kvirc/kernel/KviCustomToolBarDescriptor.cpp b/src/kvirc/kernel/KviCustomToolBarDescriptor.cpp new file mode 100644 index 000000000..c84e2b1eb --- /dev/null +++ b/src/kvirc/kernel/KviCustomToolBarDescriptor.cpp @@ -0,0 +1,220 @@ +//============================================================================= +// +// File : KviCustomToolBarDescriptor.cpp +// Creation date : Sun 05 Dec 2004 18:20:58 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviCustomToolBarDescriptor.h" +#include "KviCustomToolBar.h" +#include "KviConfigurationFile.h" +#include "KviAction.h" +#include "KviActionManager.h" +#include "KviApplication.h" +#include "KviLocale.h" +#include "KviKvsScript.h" +#include "KviWindow.h" + +KviCustomToolBarDescriptor::KviCustomToolBarDescriptor(const QString &szId,const QString &szLabelCode) +{ + m_iInternalId = g_pApp->getGloballyUniqueId(); + m_szId = szId; + m_pActions = new KviPointerList; + m_pActions->setAutoDelete(true); + m_pToolBar = 0; + m_bVisibleAtStartup = false; + createLabelScript(szLabelCode); +} + +KviCustomToolBarDescriptor::~KviCustomToolBarDescriptor() +{ + if(m_pToolBar)delete m_pToolBar; // first kill the toolbar (so eventually leave it sync the actions) + delete m_pActions; // THEN kill the actions + delete m_pLabelScript; +} + +void KviCustomToolBarDescriptor::createLabelScript(const QString &szLabelCode) +{ + QString szTmp = "toolbar::"; + szTmp += m_szId; + szTmp += "::label"; + m_pLabelScript = new KviKvsScript(szTmp,szLabelCode,KviKvsScript::Parameter); +} + +const QString & KviCustomToolBarDescriptor::label() +{ + if(!m_pLabelScript->run(g_pActiveWindow,0,m_szParsedLabel))m_szParsedLabel = m_pLabelScript->code(); + return m_szParsedLabel; +} + +const QString & KviCustomToolBarDescriptor::labelCode() +{ + return m_pLabelScript->code(); +} + +bool KviCustomToolBarDescriptor::addAction(const QString &szAction) +{ + KviAction *a = KviActionManager::instance()->getAction(szAction); + if(a) + { + m_pActions->append(new QString(szAction)); + if(m_pToolBar)a->addToCustomToolBar(m_pToolBar); + return true; + } + return false; +} + +bool KviCustomToolBarDescriptor::removeAction(unsigned int iAction) +{ + if(iAction >= m_pActions->count())return false; + if(!m_pActions->remove(iAction))return false; + if(m_pToolBar) + { + // need to refill it :/ + m_pToolBar->clear(); + fillToolBar(); + } + return true; +} + +bool KviCustomToolBarDescriptor::removeAction(const QString &szAction) +{ + for(QString *s = m_pActions->first();s;s = m_pActions->next()) + { + if(*s == szAction) + { + m_pActions->removeRef(s); + if(m_pToolBar) + { + // need to refill it :/ + m_pToolBar->clear(); + fillToolBar(); + } + return true; + } + } + return false; +} + +void KviCustomToolBarDescriptor::updateToolBar() +{ + if(!m_pToolBar)return; + m_pToolBar->clear(); + fillToolBar(); +} + + +void KviCustomToolBarDescriptor::fillToolBar() +{ + if(m_pActions->count() == 0) + { + // force layout of the toolbar + QApplication::postEvent(m_pToolBar,new QEvent(QEvent::LayoutRequest)); + } else { + KviPointerList dying; + dying.setAutoDelete(false); + for(QString *p = m_pActions->first();p;p = m_pActions->next()) + { + KviAction *a = KviActionManager::instance()->getAction(*p); + if(a)a->addToCustomToolBar(m_pToolBar); + else dying.append(p); + } + for(QString *d = dying.first();d;d = dying.next()) + m_pActions->removeRef(d); + } +} + +KviCustomToolBar * KviCustomToolBarDescriptor::createToolBar() +{ + if(!m_pToolBar) + { + QByteArray dd = id().toUtf8(); + m_pToolBar = new KviCustomToolBar(this,label(),Qt::TopToolBarArea,false,dd.data()); + fillToolBar(); + } + return m_pToolBar; +} + +void KviCustomToolBarDescriptor::registerToolBar(KviCustomToolBar * t) +{ + m_pToolBar = t; +} + +void KviCustomToolBarDescriptor::unregisterToolBar(KviCustomToolBar *) +{ + m_pToolBar = 0; +} + +void KviCustomToolBarDescriptor::rename(const QString &szNewLabelCode) +{ + delete m_pLabelScript; + createLabelScript(szNewLabelCode); + if(m_pToolBar)m_pToolBar->setWindowTitle(label()); +} + +void KviCustomToolBarDescriptor::clear() +{ + m_pActions->clear(); + if(m_pToolBar) + { + delete m_pToolBar; + m_pToolBar = 0; + } +} + +bool KviCustomToolBarDescriptor::load(KviConfigurationFile * cfg) +{ + m_pActions->clear(); + m_szId = cfg->group(); + QString szLabelCode = cfg->readEntry("Label"); + if(szLabelCode.isEmpty())szLabelCode = "$tr(Unnamed)"; + delete m_pLabelScript; + createLabelScript(szLabelCode); + m_szIconId = cfg->readEntry("IconId",""); + unsigned int n = cfg->readUIntEntry("Count",0); + QString tmp; + for(unsigned int i=0;ireadEntry(tmp)); + if(p->isEmpty())delete p; + else m_pActions->append(p); + } + return true; +} + +void KviCustomToolBarDescriptor::save(KviConfigurationFile * cfg) +{ + cfg->setGroup(m_szId); + cfg->writeEntry("Label",m_pLabelScript->code()); + cfg->writeEntry("Count",m_pActions->count()); + if(!m_szIconId.isEmpty())cfg->writeEntry("IconId",m_szIconId); + int i = 0; + QString tmp; + for(QString * p = m_pActions->first();p;p = m_pActions->next()) + { + tmp.setNum(i); + cfg->writeEntry(tmp,*p); + i++; + } +} + diff --git a/src/kvirc/kernel/KviCustomToolBarDescriptor.h b/src/kvirc/kernel/KviCustomToolBarDescriptor.h new file mode 100644 index 000000000..8fb8359b0 --- /dev/null +++ b/src/kvirc/kernel/KviCustomToolBarDescriptor.h @@ -0,0 +1,78 @@ +#ifndef _KVI_CUSTOMTOOLBARDESCRIPTOR_H_ +#define _KVI_CUSTOMTOOLBARDESCRIPTOR_H_ +//============================================================================= +// +// File : KviCustomToolBarDescriptor.h +// Creation date : Sun 05 Dec 2004 18:20:58 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviPointerList.h" + +class KviCustomToolBar; +class KviConfigurationFile; +class KviKvsScript; + + +class KVIRC_API KviCustomToolBarDescriptor +{ + friend class KviCustomToolBar; + friend class KviCustomToolBarManager; +protected: + KviCustomToolBarDescriptor(const QString & szId, const QString & szLabelCode); +public: + ~KviCustomToolBarDescriptor(); +protected: + QString m_szId; + QString m_szIconId; + QString m_szParsedLabel; + KviPointerList * m_pActions; + KviCustomToolBar * m_pToolBar; + int m_iInternalId; + bool m_bVisibleAtStartup; + KviKvsScript * m_pLabelScript; +public: + const QString & iconId(){ return m_szIconId; }; + const QString & label(); + const QString & labelCode(); + const QString & id(){ return m_szId; }; + int internalId(){ return m_iInternalId; }; // useful only for KviMainWindow + KviCustomToolBar * toolBar(){ return m_pToolBar; }; + KviCustomToolBar * createToolBar(); + void setIconId(const QString &szIconId){ m_szIconId = szIconId; }; + bool addAction(const QString &szAction); + bool removeAction(const QString &szAction); + bool removeAction(unsigned int iAction); + void clear(); + void rename(const QString &szNewName); + KviPointerList * actions(){ return m_pActions; }; + void updateToolBar(); +protected: + void createLabelScript(const QString &szNewLabelCode); + void fillToolBar(); + bool load(KviConfigurationFile * cfg); + void save(KviConfigurationFile * cfg); + void registerToolBar(KviCustomToolBar * t); + void unregisterToolBar(KviCustomToolBar * t); +}; + +#endif //_KVI_CUSTOMTOOLBARDESCRIPTOR_H_ diff --git a/src/kvirc/kernel/KviCustomToolBarManager.cpp b/src/kvirc/kernel/KviCustomToolBarManager.cpp new file mode 100644 index 000000000..fe52719f8 --- /dev/null +++ b/src/kvirc/kernel/KviCustomToolBarManager.cpp @@ -0,0 +1,212 @@ +//============================================================================= +// +// File : KviCustomToolBarManager.cpp +// Creation date : Sun 05 Dec 2004 18:20:18 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviCustomToolBarManager.h" +#include "KviCustomToolBarDescriptor.h" +#include "KviConfigurationFile.h" +#include "KviLocale.h" + +KviCustomToolBarManager * KviCustomToolBarManager::m_pInstance = 0; + +KviCustomToolBarManager::KviCustomToolBarManager() +{ + m_pDescriptors = new KviPointerHashTable(17,false); + m_pDescriptors->setAutoDelete(true); +} + +KviCustomToolBarManager::~KviCustomToolBarManager() +{ + delete m_pDescriptors; +} + +KviCustomToolBar * KviCustomToolBarManager::firstExistingToolBar() +{ + KviPointerHashTableIterator it(*m_pDescriptors); + while(KviCustomToolBarDescriptor * d = it.current()) + { + if(d->toolBar())return d->toolBar(); + ++it; + } + return 0; +} + +void KviCustomToolBarManager::init() +{ + if(!m_pInstance)m_pInstance = new KviCustomToolBarManager(); +} + +void KviCustomToolBarManager::done() +{ + if(m_pInstance) + { + delete m_pInstance; + m_pInstance = 0; + } +} + +QString KviCustomToolBarManager::idForNewToolBar(const QString &szTemplate) +{ + QString s; + QString szTT = szTemplate.toLower(); + szTT.remove(" "); + szTT.remove("$tr"); + szTT.remove("("); + szTT.remove(")"); + szTT.remove("\""); + int idx = 0; + for(;;) + { + s = szTT; + if(idx > 0) + { + QString tmp; + tmp.setNum(idx); + s += tmp; + } + if(!m_pDescriptors->find(s))return s; + idx++; + } + return s; +} + +KviCustomToolBarDescriptor * KviCustomToolBarManager::findDescriptorByInternalId(int id) +{ + KviPointerHashTableIterator it(*m_pDescriptors); + while(KviCustomToolBarDescriptor * d = it.current()) + { + if(d->internalId() == id)return d; + ++it; + } + return 0; +} + +bool KviCustomToolBarManager::renameDescriptor(const QString &szId,const QString &szNewId,const QString &szNewLabelCode) +{ + KviCustomToolBarDescriptor * d = m_pDescriptors->find(szId); + if(!d)return false; + d->rename(szNewLabelCode); + if(szId == szNewId)return true; // already done + m_pDescriptors->setAutoDelete(false); + m_pDescriptors->remove(szId); + m_pDescriptors->replace(szNewId,d); + m_pDescriptors->setAutoDelete(true); + return true; +} + +bool KviCustomToolBarManager::destroyDescriptor(const QString &szId) +{ + KviCustomToolBarDescriptor * d = m_pDescriptors->find(szId); + if(!d)return false; + m_pDescriptors->remove(szId); // will delete it too! + return true; +} + +void KviCustomToolBarManager::clear() +{ + m_pDescriptors->clear(); // bye! +} + +KviCustomToolBarDescriptor * KviCustomToolBarManager::create(const QString &szId,const QString &szLabelCode) +{ + KviCustomToolBarDescriptor * d = m_pDescriptors->find(szId); + if(d)return d; + d = new KviCustomToolBarDescriptor(szId,szLabelCode); + m_pDescriptors->replace(szId,d); + return d; +} + +void KviCustomToolBarManager::storeVisibilityState() +{ + KviPointerHashTableIterator it(*m_pDescriptors); + while(KviCustomToolBarDescriptor * d = it.current()) + { + d->m_bVisibleAtStartup = d->toolBar() != 0; + ++it; + } + +} + +int KviCustomToolBarManager::visibleToolBarCount() +{ + int cnt = 0; + KviPointerHashTableIterator it(*m_pDescriptors); + while(KviCustomToolBarDescriptor * d = it.current()) + { + if(d->toolBar() != 0)cnt++; + ++it; + } + return cnt; +} + +void KviCustomToolBarManager::createToolBarsVisibleAtStartup() +{ + KviPointerHashTableIterator it(*m_pDescriptors); + while(KviCustomToolBarDescriptor * d = it.current()) + { + if(d->m_bVisibleAtStartup && (!d->toolBar())) + d->createToolBar(); + ++it; + } +} + +void KviCustomToolBarManager::updateVisibleToolBars() +{ + KviPointerHashTableIterator it(*m_pDescriptors); + while(KviCustomToolBarDescriptor * d = it.current()) + { + if(d->toolBar())d->updateToolBar(); + ++it; + } +} + +void KviCustomToolBarManager::load(const QString &szFileName) +{ + KviConfigurationFile cfg(szFileName,KviConfigurationFile::Read); + + KviConfigurationFileIterator it(*(cfg.dict())); + while(it.current()) + { + cfg.setGroup(it.currentKey()); + KviCustomToolBarDescriptor * d = new KviCustomToolBarDescriptor(it.currentKey(),QString()); + d->m_bVisibleAtStartup = (cfg.readIntEntry("Visible",0) > 0); + if(!d->load(&cfg))delete d; + else m_pDescriptors->replace(it.currentKey(),d); + ++it; + } +} + +void KviCustomToolBarManager::save(const QString &szFileName) +{ + KviConfigurationFile cfg(szFileName,KviConfigurationFile::Write); + KviPointerHashTableIterator it(*m_pDescriptors); + while(KviCustomToolBarDescriptor * d = it.current()) + { + cfg.setGroup(d->id()); + cfg.writeEntry("Visible",d->m_bVisibleAtStartup ? 1 : 0); + d->save(&cfg); + ++it; + } +} diff --git a/src/kvirc/kernel/KviCustomToolBarManager.h b/src/kvirc/kernel/KviCustomToolBarManager.h new file mode 100644 index 000000000..d25b24546 --- /dev/null +++ b/src/kvirc/kernel/KviCustomToolBarManager.h @@ -0,0 +1,68 @@ +#ifndef _KVI_CUSTOMTOOLBARMANAGER_H_ +#define _KVI_CUSTOMTOOLBARMANAGER_H_ +//============================================================================= +// +// File : KviCustomToolBarManager.h +// Creation date : Sun 05 Dec 2004 18:20:18 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviPointerHashTable.h" + +#ifdef COMPILE_ON_WINDOWS + #include "KviCustomToolBarDescriptor.h" +#else + class KviCustomToolBarDescriptor; +#endif + +class KviCustomToolBar; + +class KVIRC_API KviCustomToolBarManager +{ +protected: + KviCustomToolBarManager(); + ~KviCustomToolBarManager(); +protected: + static KviCustomToolBarManager * m_pInstance; + KviPointerHashTable * m_pDescriptors; +public: + static KviCustomToolBarManager * instance(){ return m_pInstance; }; + static void init(); + static void done(); + void clear(); + int descriptorCount(){ return m_pDescriptors->count(); }; + int visibleToolBarCount(); + QString idForNewToolBar(const QString &szTemplate); + KviPointerHashTable * descriptors(){ return m_pDescriptors; }; + KviCustomToolBar * firstExistingToolBar(); + KviCustomToolBarDescriptor * create(const QString &szId,const QString &szLabelCode); + KviCustomToolBarDescriptor * find(const QString &szId){ return m_pDescriptors->find(szId); }; + KviCustomToolBarDescriptor * findDescriptorByInternalId(int id); + void updateVisibleToolBars(); + void createToolBarsVisibleAtStartup(); + void storeVisibilityState(); + bool renameDescriptor(const QString &szId,const QString &szNewId,const QString &szNewLabelCode); + bool destroyDescriptor(const QString &szId); + void load(const QString &szFileName); + void save(const QString &szFileName); +}; + +#endif //_KVI_CUSTOMTOOLBARMANAGER_H_ diff --git a/src/kvirc/kernel/KviDefaultScript.cpp b/src/kvirc/kernel/KviDefaultScript.cpp new file mode 100644 index 000000000..4af722e05 --- /dev/null +++ b/src/kvirc/kernel/KviDefaultScript.cpp @@ -0,0 +1,489 @@ +//============================================================================= +// +// File : KviDefaultScript.cpp +// Creation date : Fri Oct 01 2010 19:14:48 by Elvio Basello +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2010 Elvio Basello (hell at hellvis69 dot netsons dot org) +// +// 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 opinion) 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 "KviDefaultScript.h" + +#include "KviApplication.h" +#include "KviKvs.h" +#include "KviConfigurationFile.h" +#include "KviLocale.h" +#include "KviMiscUtils.h" +#include "KviActionManager.h" +#include "KviIconManager.h" +#include "KviCustomToolBarManager.h" + +#include +#include +#include +#include +#include +#include + +KviDefaultScriptManager * KviDefaultScriptManager::m_pSelf = NULL; +unsigned int KviDefaultScriptManager::m_uCount = 0; + +KviDefaultScriptManager::KviDefaultScriptManager() +: QObject() +{ + m_bNoNeedToRestore = false; + + // Check if versions' file exists in personal settings + QString szLocal; + g_pApp->getLocalKvircDirectory(szLocal,KviApplication::Config,"default.kvc"); + + if(!QFile::exists(szLocal)) + { + QString szGlobal; + g_pApp->getGlobalKvircDirectory(szGlobal,KviApplication::DefScript,"default.kvc"); + QFile::copy(szGlobal,szLocal); + } +} + +KviDefaultScriptManager::~KviDefaultScriptManager() +{ +} + +void KviDefaultScriptManager::init() +{ + if((!m_pSelf) && (m_pSelf->count() == 0)) + { + m_pSelf = new KviDefaultScriptManager(); + m_uCount++; + } +} + +void KviDefaultScriptManager::done() +{ + m_uCount--; + if(m_pSelf->count() == 0) + delete m_pSelf; +} + +bool KviDefaultScriptManager::isDefscriptUpToDate() +{ + QString szConfig, szTmp; + g_pApp->getGlobalKvircDirectory(szConfig,KviApplication::DefScript,"default.kvc"); + KviConfigurationFile * pCfg = new KviConfigurationFile(szConfig,KviConfigurationFile::Read); + + szTmp = pCfg->readEntry("Date"); + QDate cfgDate = QDate::fromString(szTmp,"yyyy-MM-dd"); + QDate userDate = QDate::fromString(m_szDate,"yyyy-MM-dd"); + + return (cfgDate == userDate); +} + +void KviDefaultScriptManager::restore() +{ + QString szGlobal, szError, szLocal; + g_pApp->getGlobalKvircDirectory(szGlobal,KviApplication::DefScript,"default.kvc"); + + m_pDialog = new KviDefaultScriptDialog(); + if(m_pDialog->exec() == QDialog::Rejected) + { + delete m_pDialog; + return; + } + + // Check data + if(!compareVersions(szGlobal,&szError)) + { + QMessageBox::warning(0,__tr2qs("Restore Default Script - Error"),szError,QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton); + return; + } + + if(m_bNoNeedToRestore) + { + if(QMessageBox::warning(0,__tr2qs("Restore Default Script - Warning"),szError,QMessageBox::Yes, QMessageBox::No,QMessageBox::Cancel) != QMessageBox::Yes) + return; + } + + restoreInternal(); +} + +void KviDefaultScriptManager::restoreInternal() +{ + QString szConfig, szTmp; + g_pApp->getGlobalKvircDirectory(szConfig,KviApplication::DefScript,"default.kvc"); + KviConfigurationFile * pCfg = new KviConfigurationFile(szConfig,KviConfigurationFile::Read); + + m_szDate = pCfg->readEntry("Date"); + + // Select elements to restore + if((m_pDialog->m_pAction->isEnabled() && m_pDialog->m_pAction->isChecked()) || m_pDialog->m_pAll->isChecked()) + { + if(m_pDialog->m_pData->isChecked()) + KviActionManager::instance()->killAllKvsUserActions(); + // No need to load here since we haven't a default actions script yet + //g_pApp->loadDefaultScript("action"); + m_szAction = pCfg->readEntry("ActionVersion"); + } + + if((m_pDialog->m_pAddon->isEnabled() && m_pDialog->m_pAddon->isChecked()) || m_pDialog->m_pAll->isChecked()) + { + if(m_pDialog->m_pData->isChecked()) + KviKvs::clearScriptAddons(); + // No need to load here since we haven't a default actions script yet + //g_pApp->loadDefaultScript("addons"); + m_szAddon = pCfg->readEntry("AddonVersion"); + } + + if((m_pDialog->m_pAlias->isEnabled() && m_pDialog->m_pAlias->isChecked()) || m_pDialog->m_pAll->isChecked()) + { + if(m_pDialog->m_pData->isChecked()) + KviKvs::clearAliases(); + g_pApp->loadDefaultScript("aliases"); + m_szAlias = pCfg->readEntry("AliasVersion"); + } + + if((m_pDialog->m_pClass->isEnabled() && m_pDialog->m_pClass->isChecked()) || m_pDialog->m_pAll->isChecked()) + { + // TODO: clear classes + g_pApp->loadDefaultScript("classes"); + m_szClass = pCfg->readEntry("ClassVersion"); + } + + if((m_pDialog->m_pEvent->isEnabled() && m_pDialog->m_pEvent->isChecked()) || m_pDialog->m_pAll->isChecked()) + { + if(m_pDialog->m_pData->isChecked()) + KviKvs::clearAppEvents(); + g_pApp->loadDefaultScript("events"); + m_szEvent = pCfg->readEntry("EventVersion"); + } + + if((m_pDialog->m_pPopup->isEnabled() && m_pDialog->m_pPopup->isChecked()) || m_pDialog->m_pAll->isChecked()) + { + if(m_pDialog->m_pData->isChecked()) + KviKvs::clearPopups(); + g_pApp->loadDefaultScript("popups"); + m_szPopup = pCfg->readEntry("PopupVersion"); + } + + if((m_pDialog->m_pRaw->isEnabled() && m_pDialog->m_pRaw->isChecked()) || m_pDialog->m_pAll->isChecked()) + { + if(m_pDialog->m_pData->isChecked()) + KviKvs::clearRawEvents(); + // No need to load here since we haven't a default raw events script yet + //g_pApp->loadDefaultScript("raws"); + m_szRaw = pCfg->readEntry("RawVersion"); + } + + if((m_pDialog->m_pToolbar->isEnabled() && m_pDialog->m_pToolbar->isChecked()) || m_pDialog->m_pAll->isChecked()) + { + if(m_pDialog->m_pData->isChecked()) + KviCustomToolBarManager::instance()->clear(); + g_pApp->loadDefaultScript("toolbars"); + m_szToolbar = pCfg->readEntry("ToolbarVersion"); + } +} + +#define CHECK(__name,__global,__local) \ + if(KviMiscUtils::compareVersions(__global,__local) == 1) \ + { \ + *pszError = __tr2qs("There's something wrong in your personal data: my '%1' is %2, while yours is %3").arg(__name,__global,__local); \ + return false; \ + } + +bool KviDefaultScriptManager::compareVersions(QString & szConfig, QString * pszError) +{ + QString szTmp, szTmp2; + + if(pszError) + *pszError = ""; + + KviConfigurationFile * pCfg = new KviConfigurationFile(szConfig,KviConfigurationFile::Read); + + szTmp = "Date"; + szTmp2 = pCfg->readEntry(szTmp); + QDate cfgDate = QDate::fromString(szTmp2,"yyyy-MM-dd"); + QDate userDate = QDate::fromString(m_szDate,"yyyy-MM-dd"); + + if(cfgDate <= userDate) + { + m_bNoNeedToRestore = true; + *pszError = __tr2qs("Your default script is up to date.\nDo you want to restore it anyway?"); + return true; + } + + szTmp = "Version"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szVersion) + + szTmp = "ActionVersion"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szAction) + + szTmp = "AddonVersion"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szAction) + + szTmp = "AliasVersion"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szAlias) + + szTmp = "ClassVersion"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szClass) + + szTmp = "EventVersion"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szEvent) + + szTmp = "PopupVersion"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szPopup) + + szTmp = "RawVersion"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szRaw) + + szTmp = "ToolbarVersion"; + szTmp2 = pCfg->readEntry(szTmp); + CHECK(szTmp,szTmp2,m_szToolbar) + + return true; +} + +void KviDefaultScriptManager::load(const QString & szConfigFile) +{ + KviConfigurationFile cfg(szConfigFile,KviConfigurationFile::Read); + loadInternal(&cfg); +} + +#define IS_EMPTY(__var,__default) \ + if(__var.isEmpty()) \ + __var = __default; + +void KviDefaultScriptManager::loadInternal(KviConfigurationFile * pCfg) +{ + QString szTmp; + QString szDate = QDate::currentDate().toString("yyyy-MM-dd"); + + szTmp = "Version"; + m_szVersion = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szVersion,KVI_VERSION) + + szTmp = "Date"; + m_szDate = pCfg->readEntry(szTmp,szDate); + IS_EMPTY(m_szDate,szDate) + + szTmp = "ActionVersion"; + m_szAction = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szAction,KVI_VERSION) + + szTmp = "AddonVersion"; + m_szAddon = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szAddon,KVI_VERSION) + + szTmp = "AliasVersion"; + m_szAlias = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szAlias,KVI_VERSION) + + szTmp = "ClassVersion"; + m_szClass = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szClass,KVI_VERSION) + + szTmp = "EventVersion"; + m_szEvent = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szEvent,KVI_VERSION) + + szTmp = "PopupVersion"; + m_szPopup = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szPopup,KVI_VERSION) + + szTmp = "RawVersion"; + m_szRaw = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szRaw,KVI_VERSION) + + szTmp = "ToolbarVersion"; + m_szToolbar = pCfg->readEntry(szTmp,KVI_VERSION); + IS_EMPTY(m_szToolbar,KVI_VERSION) +} + +void KviDefaultScriptManager::save(const QString & szConfigFile) +{ + KviConfigurationFile cfg(szConfigFile,KviConfigurationFile::Write); + cfg.clear(); + saveInternal(&cfg); +} + +void KviDefaultScriptManager::saveInternal(KviConfigurationFile * pCfg) +{ + QString szTmp; + + szTmp = "Version"; + pCfg->writeEntry(szTmp,m_szVersion); + + szTmp = "Date"; + pCfg->writeEntry(szTmp,m_szDate); + + szTmp = "ActionVersion"; + pCfg->writeEntry(szTmp,m_szAction); + + szTmp = "AddonVersion"; + pCfg->writeEntry(szTmp,m_szAddon); + + szTmp = "AliasVersion"; + pCfg->writeEntry(szTmp,m_szAlias); + + szTmp = "ClassVersion"; + pCfg->writeEntry(szTmp,m_szClass); + + szTmp = "EventVersion"; + pCfg->writeEntry(szTmp,m_szEvent); + + szTmp = "PopupVersion"; + pCfg->writeEntry(szTmp,m_szPopup); + + szTmp = "RawVersion"; + pCfg->writeEntry(szTmp,m_szRaw); + + szTmp = "ToolbarVersion"; + pCfg->writeEntry(szTmp,m_szToolbar); +} + + +KviDefaultScriptDialog::KviDefaultScriptDialog() +: QDialog() +{ + setObjectName("restore_default_script"); + setWindowTitle(__tr2qs("Restore Default Script - KVIrc")); + setWindowModality(Qt::WindowModal); + setModal(true); + + QGridLayout * pLayout = new QGridLayout(this); + + QLabel * pLabel = new QLabel(this); + pLabel->setText(__tr2qs("You are about to restore the default script.\nAny script changes you have made will be erased if you\nrestore all stuff or \"Clear personal data\" is selected.\n\nDo you wish to proceed?\n")); + pLayout->addWidget(pLabel,0,0,1,4); + + // Construct the advanced widget + m_pAdvanced = new QGroupBox(__tr2qs("Select default script's elements to restore"),this); + m_pAdvanced->hide(); + + QGridLayout * pAdvLayout = new QGridLayout(m_pAdvanced); + pAdvLayout->setContentsMargins(0,10,0,0); + pLayout->addWidget(m_pAdvanced,1,0,1,4); + + m_pAll = new QCheckBox(__tr2qs("All"),m_pAdvanced); + m_pAll->setChecked(true); + pAdvLayout->addWidget(m_pAll,0,0); + connect(m_pAll,SIGNAL(clicked(bool)),this,SLOT(toggleAll(bool))); + + m_pData = new QCheckBox(__tr2qs("Clear custom scripts"),m_pAdvanced); + m_pData->setChecked(false); + m_pData->setEnabled(true); + pAdvLayout->addWidget(m_pData,0,1); + + pLabel = new QLabel(m_pAdvanced); + pAdvLayout->addWidget(pLabel,1,1,1,2); + + m_pAction = new QCheckBox(__tr2qs("Actions"),m_pAdvanced); + m_pAction->setChecked(true); + m_pAction->setEnabled(false); + pAdvLayout->addWidget(m_pAction,2,0); + + m_pAddon = new QCheckBox(__tr2qs("Addons"),m_pAdvanced); + m_pAddon->setChecked(true); + m_pAddon->setEnabled(false); + pAdvLayout->addWidget(m_pAddon,2,1); + + m_pAlias = new QCheckBox(__tr2qs("Aliases"),m_pAdvanced); + m_pAlias->setChecked(true); + m_pAlias->setEnabled(false); + pAdvLayout->addWidget(m_pAlias,3,0); + + m_pClass = new QCheckBox(__tr2qs("Classes"),m_pAdvanced); + m_pClass->setChecked(true); + m_pClass->setEnabled(false); + pAdvLayout->addWidget(m_pClass,3,1); + + m_pEvent = new QCheckBox(__tr2qs("Events"),m_pAdvanced); + m_pEvent->setChecked(true); + m_pEvent->setEnabled(false); + pAdvLayout->addWidget(m_pEvent,4,0); + + m_pPopup = new QCheckBox(__tr2qs("Popups"),m_pAdvanced); + m_pPopup->setChecked(true); + m_pPopup->setEnabled(false); + pAdvLayout->addWidget(m_pPopup,4,1); + + m_pRaw = new QCheckBox(__tr2qs("Raw Events"),m_pAdvanced); + m_pRaw->setChecked(true); + m_pRaw->setEnabled(false); + pAdvLayout->addWidget(m_pRaw,5,0); + + m_pToolbar = new QCheckBox(__tr2qs("Toolbars"),m_pAdvanced); + m_pToolbar->setChecked(true); + m_pToolbar->setEnabled(false); + pAdvLayout->addWidget(m_pToolbar,5,1); + + m_pAdvanced->setLayout(pAdvLayout); + + QPixmap * pImage = g_pIconManager->getSmallIcon(262); + QPushButton * pAdvanced = new QPushButton(*pImage,__tr2qs("Advanced..."),this); + connect(pAdvanced,SIGNAL(clicked()),this,SLOT(advanced())); + pLayout->addWidget(pAdvanced,2,0,1,1); + + pImage = g_pIconManager->getSmallIcon(44); + QPushButton * pCancel = new QPushButton(*pImage,__tr2qs("Cancel"),this); + pCancel->setDefault(true); + connect(pCancel,SIGNAL(clicked()),this,SLOT(reject())); + pLayout->addWidget(pCancel,2,2,1,1); + + pImage = g_pIconManager->getSmallIcon(43); + QPushButton * pAccept = new QPushButton(*pImage,__tr2qs("Restore"),this); + connect(pAccept,SIGNAL(clicked()),this,SLOT(accept())); + pLayout->addWidget(pAccept,2,3,1,1); +} + +KviDefaultScriptDialog::~KviDefaultScriptDialog() +{ +} + +void KviDefaultScriptDialog::toggleAll(bool) +{ + m_pAction->setEnabled(!m_pAction->isEnabled()); + m_pAddon->setEnabled(!m_pAddon->isEnabled()); + m_pAlias->setEnabled(!m_pAlias->isEnabled()); + m_pClass->setEnabled(!m_pClass->isEnabled()); + m_pEvent->setEnabled(!m_pEvent->isEnabled()); + m_pPopup->setEnabled(!m_pPopup->isEnabled()); + m_pRaw->setEnabled(!m_pRaw->isEnabled()); + m_pToolbar->setEnabled(!m_pToolbar->isEnabled()); +} + +void KviDefaultScriptDialog::advanced() +{ + m_pAdvanced->isVisible() ? m_pAdvanced->hide() : m_pAdvanced->show(); +} + +void KviDefaultScriptDialog::accept() +{ + QDialog::accept(); +} + +void KviDefaultScriptDialog::reject() +{ + QDialog::reject(); +} diff --git a/src/kvirc/kernel/KviDefaultScript.h b/src/kvirc/kernel/KviDefaultScript.h new file mode 100644 index 000000000..585db0084 --- /dev/null +++ b/src/kvirc/kernel/KviDefaultScript.h @@ -0,0 +1,239 @@ +#ifndef _KVI_DEFAULTSCRIPT_H_ +#define _KVI_DEFAULTSCRIPT_H_ +//============================================================================= +// +// File : KviDefaultScript.h +// Creation date : Fri Oct 01 2010 19:14:48 by Elvio Basello +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2010 Elvio Basello (hell at hellvis69 dot netsons dot org) +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviDefaultScript.h +* \author Elvio Basello +* \brief Default script handling +*/ + +#include "kvi_settings.h" + +#include +#include + +class QGroupBox; +class QCheckBox; +class KviConfigurationFile; +class KviDefaultScriptDialog; + +/** +* \class KviDefaultScriptManager +* \brief The manager who handles the restoring of the default script +*/ +class KVIRC_API KviDefaultScriptManager : public QObject +{ + Q_OBJECT +public: + /** + * \brief Constructs the default script manager + * \return KviDefaultScriptManager + */ + KviDefaultScriptManager(); + + /** + * \brief Destroys the default script manager + */ + ~KviDefaultScriptManager(); +private: + static KviDefaultScriptManager * m_pSelf; + static unsigned int m_uCount; + bool m_bNoNeedToRestore; + KviDefaultScriptDialog * m_pDialog; + QString m_szVersion; + QString m_szDate; + QString m_szAction; + QString m_szAddon; + QString m_szAlias; + QString m_szClass; + QString m_szEvent; + QString m_szPopup; + QString m_szRaw; + QString m_szToolbar; +public: + /** + * \brief Initializes the class instance + * \return void + */ + static void init(); + + /** + * \brief Destroys the class instance + * \return void + */ + static void done(); + + /** + * \brief Returns the instance of the class + * \return KviDefaultScriptManager * + */ + static inline KviDefaultScriptManager * instance(){ return m_pSelf; } + + /** + * \brief Returns the number of instances of the class + * \return unsigned int + */ + unsigned int count(){ return m_uCount; }; + + /** + * \brief Checks if the local defscript is up to date + * \return bool + */ + bool isDefscriptUpToDate(); + + /** + * \brief Restores the default script + * + * If this function is suggested by KVIrc, the default script will be wiped out and then + * it will be reloaded. Otherwise, when the user wants to restore it, he can choose which + * part of the default script have to be restored + * + * This is an external helper to the real function + * \return void + */ + void restore(); + + /** + * \brief Loads the configuration of the default script + * + * This is an external helper to the real function + * \param szConfigFile The file where to load + * \return void + */ + void load(const QString & szConfigFile); + + /** + * \brief Saves the configuration of the default script + * + * This is an external helper to the real function + * \param szConfigFile The file to save + * \return void + */ + void save(const QString & szConfigFile); +private: + /** + * \brief Restores the default script + * + * This is the real function + * \return void + * \todo This function still misses class clearing due to a missing function in class editor + */ + void restoreInternal(); + + /** + * \brief Loads the configuration of the default script + * + * This is the real function + * \param pCfg The configuration file + * \return void + */ + void loadInternal(KviConfigurationFile * pCfg); + + /** + * \brief Saves the configuration of the default script + * + * This is the real function + * \param pCfg The configuration file + * \return void + */ + void saveInternal(KviConfigurationFile * pCfg); + + /** + * \brief Compares versions between global and personal data + * \param szConfig The global configuration file + * \param pszError The buffer containing errors + * \return bool + */ + bool compareVersions(QString & szConfig, QString * pszError); +}; + +/** +* \class KviDefaultScriptDialog +* \brief A dialog which allow the user to choose which elements to restore +*/ +class KVIRC_API KviDefaultScriptDialog : public QDialog +{ + Q_OBJECT + friend class KviDefaultScriptManager; +public: + /** + * \brief Constructs the default script dialog + * \return KviDefaultScriptDialog + */ + KviDefaultScriptDialog(); + + /** + * \brief Destroys the default script dialog + */ + ~KviDefaultScriptDialog(); +protected: + QGroupBox * m_pAdvanced; + QCheckBox * m_pAll; + QCheckBox * m_pData; + QCheckBox * m_pAction; + QCheckBox * m_pAddon; + QCheckBox * m_pAlias; + QCheckBox * m_pClass; + QCheckBox * m_pEvent; + QCheckBox * m_pPopup; + QCheckBox * m_pRaw; + QCheckBox * m_pToolbar; +protected slots: + /** + * \brief Enables or disables all checkboxes + * + * Called when the user (de)selects the 'All' one + * \return void + */ + void toggleAll(bool); + + /** + * \brief Open/close the advanced widget + * + * Called when the user clicks on 'Advanced...' + * \return void + */ + void advanced(); + + /** + * \brief Accepts the dialog + * + * Called when the user clicks on 'Ok' + * \return void + */ + virtual void accept(); + + /** + * \brief Rejects the dialog + * + * Called when the user clicks on 'Cancel' or closes the dialog using the window + * decoration or pressing ESC + * \return void + */ + virtual void reject(); +}; + +#endif // _KVI_DEFAULTSCRIPT_H_ \ No newline at end of file diff --git a/src/kvirc/kernel/KviFileTransfer.cpp b/src/kvirc/kernel/KviFileTransfer.cpp new file mode 100644 index 000000000..4971799dd --- /dev/null +++ b/src/kvirc/kernel/KviFileTransfer.cpp @@ -0,0 +1,202 @@ +//============================================================================= +// +// File : KviFileTransfer.cpp +// Creation date : Mon Apr 21 22:14:31 2003 GMT by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviFileTransfer.h" +#include "KviModuleExtension.h" +#include "KviWindow.h" + +#include "KviApplication.h" + +#include "KviTalPopupMenu.h" + +static KviFileTransferManager * g_pFileTransferManager = 0; + + +KviFileTransferManager::KviFileTransferManager() +: QObject() +{ + m_pTransferList = 0; + m_pTransferWindow = 0; +} + +KviFileTransferManager::~KviFileTransferManager() +{ + killAllTransfers(); +} + +KviFileTransferManager * KviFileTransferManager::instance() +{ + if(!g_pFileTransferManager) { + g_pFileTransferManager = new KviFileTransferManager(); + } + return g_pFileTransferManager; +} + +void KviFileTransferManager::cleanup() +{ + if(g_pFileTransferManager) { + delete g_pFileTransferManager; + g_pFileTransferManager = 0; + } +} + +void KviFileTransferManager::killAllTransfers() +{ + while(m_pTransferList) + { + KviFileTransfer * t = m_pTransferList->first(); + t->die(); + } +} + +void KviFileTransferManager::killTerminatedTransfers() +{ + if(m_pTransferList) + { + KviPointerList l; + l.setAutoDelete(false); + + for(KviFileTransfer * f = m_pTransferList->first();f;f = m_pTransferList->next()) + { + if(f->terminated()) { + l.append(f); + } + } + + for(KviFileTransfer * d = l.first();d;d = l.next()) + d->die(); + } +} + +void KviFileTransferManager::invokeTransferWindow(KviWindow * pWnd,bool bCreateMinimized,bool bNoRaise) +{ + if(!m_pTransferWindow) + { + KviPointerHashTable d(7,false); + d.setAutoDelete(true); + d.replace("bCreateMinimized",new QVariant(bCreateMinimized)); + d.replace("bNoRaise",new QVariant(bNoRaise)); + + KviModuleExtensionManager::instance()->allocateExtension( + "tool", + KVI_FILE_TRANSFER_WINDOW_EXTENSION_NAME, + pWnd,&d,0, + "filetransferwindow"); + } +} + +void KviFileTransferManager::registerTransfer(KviFileTransfer * t) +{ + if(!m_pTransferList) + { + m_pTransferList = new KviPointerList; + m_pTransferList->setAutoDelete(false); + } + + m_pTransferList->append(t); + + emit transferRegistered(t); +} + +void KviFileTransferManager::unregisterTransfer(KviFileTransfer * t) +{ + if(!m_pTransferList) + { + qDebug("Ops: unregistering transfer with no transfer list!"); + return; + } + + emit transferUnregistering(t); + + m_pTransferList->removeRef(t); + if(m_pTransferList->isEmpty()) + { + delete m_pTransferList; + m_pTransferList = 0; + } +} + + + +KviFileTransfer::KviFileTransfer() +: QObject() +{ + m_pDisplayItem = 0; + m_iId = g_pApp->getGloballyUniqueId(); + manager()->registerTransfer(this); +} + +KviFileTransfer::~KviFileTransfer() +{ + manager()->unregisterTransfer(this); +} + +KviWindow * KviFileTransfer::outputWindow() +{ + KviWindow * o = transferWindow(); + if(o)return o; + return g_pActiveWindow; +} + +void KviFileTransfer::invokeTransferWindow(KviWindow * pWnd,bool bCreateMinimized,bool bNoRaise) +{ + manager()->invokeTransferWindow(pWnd,bCreateMinimized,bNoRaise); +} + +QString KviFileTransfer::localFileName() +{ + return QString(); +} + +QString KviFileTransfer::retryCommand() +{ + return QString(); +} + +bool KviFileTransfer::terminated() +{ + return !active(); +} + +QString KviFileTransfer::tipText() +{ + return QString(); +} + +int KviFileTransfer::displayHeight(int iLineSpacing) +{ + return iLineSpacing * 2; +} + +void KviFileTransfer::displayUpdate() +{ + if(m_pDisplayItem)m_pDisplayItem->displayUpdate(); +} + +void KviFileTransfer::die() +{ + if(m_pDisplayItem) + m_pDisplayItem->tableWidget()->removeRow(m_pDisplayItem->row()); + delete this; +} diff --git a/src/kvirc/kernel/KviFileTransfer.h b/src/kvirc/kernel/KviFileTransfer.h new file mode 100644 index 000000000..5350e2c59 --- /dev/null +++ b/src/kvirc/kernel/KviFileTransfer.h @@ -0,0 +1,114 @@ +#ifndef _KVI_FILETRANSFER_H_ +#define _KVI_FILETRANSFER_H_ + +//============================================================================= +// +// File : KviFileTransfer.h +// Creation date : Mon Apr 21 22:14:31 2003 GMT by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviPointerList.h" +#include "KviTalTableWidget.h" + +#include + +class KviFileTransfer; +class KviWindow; +class KviTalPopupMenu; +class QPainter; + +// This is for the external extension +#define KVI_FILE_TRANSFER_WINDOW_EXTENSION_NAME "File transfer extension" + + +class KVIRC_API KviFileTransferManager : public QObject +{ + friend class KviApplication; + friend class KviFileTransfer; + friend class KviFileTransferWindow; + Q_OBJECT +public: + KviFileTransferManager(); + ~KviFileTransferManager(); +protected: + KviPointerList * m_pTransferList; + KviWindow * m_pTransferWindow; +protected: + static void cleanup(); + void registerTransfer(KviFileTransfer * t); + void unregisterTransfer(KviFileTransfer * t); + void setTransferWindow(KviWindow * wnd){ m_pTransferWindow = wnd; }; +public: + // might be zero! + KviWindow * transferWindow(){ return m_pTransferWindow; }; + static KviFileTransferManager * instance(); + KviPointerList * transferList(){ return m_pTransferList; }; + void invokeTransferWindow(KviWindow * pWnd = 0,bool bCreateMinimized = false,bool bNoRaise = false); + void killAllTransfers(); + void killTerminatedTransfers(); +signals: + void transferRegistered(KviFileTransfer *t); + void transferUnregistering(KviFileTransfer *t); +}; + +#define COLUMN_TRANSFERTYPE 0 +#define COLUMN_FILEINFO 1 +#define COLUMN_PROGRESS 2 + +class KVIRC_API KviFileTransfer : public QObject +{ + Q_OBJECT +public: + KviFileTransfer(); + ~KviFileTransfer(); +protected: + int m_iId; + KviTalTableWidgetItemEx * m_pDisplayItem; +public: + // This is called by KviFileTransferItem at any time + void setDisplayItem(KviTalTableWidgetItemEx * i){ m_pDisplayItem = i; }; + int id(){ return m_iId; }; + // this is just a convenience function : it's equivalent to !active() + bool terminated(); + // This may be used to invoke the transfer window + void invokeTransferWindow(KviWindow * pWnd = 0,bool bCreateMinimized = false,bool bNoRaise = false); + KviFileTransferManager * manager(){ return KviFileTransferManager::instance(); }; + // this returns the pointer to the transfer window : may be 0! + KviWindow * transferWindow(){ return manager()->transferWindow(); }; + // this returns transferWindow() if not 0, otherwise the application's active window + KviWindow * outputWindow(); + + // this may be called by the transfers to update the display when the state changes + void displayUpdate(); + + // this must be implemented by the transfer + virtual bool active() = 0; + virtual void displayPaint(QPainter * p,int column, QRect rect) = 0; + virtual QString tipText(); + virtual QString localFileName(); + virtual QString retryCommand(); + virtual int displayHeight(int iLineSpacing); + virtual void fillContextPopup(KviTalPopupMenu * m) = 0; + virtual void die(); +}; + +#endif //! _KVI_FILETRANSFER_H_ diff --git a/src/kvirc/kernel/KviHtmlGenerator.cpp b/src/kvirc/kernel/KviHtmlGenerator.cpp new file mode 100644 index 000000000..cea2d08cb --- /dev/null +++ b/src/kvirc/kernel/KviHtmlGenerator.cpp @@ -0,0 +1,304 @@ +//============================================================================= +// +// File : KviHtmlGenerator.cpp +// Creation date : Mon 04 Jan 2010 22:09:18 by Fabio Bas +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2010 Fabio Bas < ctrlaltca at gmail dot 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 opinion) 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 "KviHtmlGenerator.h" + +#include "KviIconManager.h" +#include "KviMircCntrl.h" +#include "KviOptions.h" +#include "KviTextIconManager.h" + +#define KVI_LABEL_DEF_BACK 100 +#define KVI_LABEL_DEF_FORE 101 + +namespace KviHtmlGenerator +{ + + QString convertToHtml(const QString &szText) + { + QString szResult=""; + bool bCurBold = false; + bool bCurUnderline = false; + bool bIgnoreIcons = false; + bool bShowIcons = KVI_OPTION_BOOL(KviOption_boolDrawEmoticons); + + unsigned char uCurFore = KVI_LABEL_DEF_FORE; //default fore + unsigned char uCurBack = KVI_LABEL_DEF_BACK; //default back + + unsigned int uIdx = 0; + + while(uIdx < (unsigned int)szText.length()) + { + unsigned short c = szText[(int)uIdx].unicode(); + unsigned int uStart = uIdx; + + while( + (c != KVI_TEXT_COLOR) && + (c != KVI_TEXT_BOLD) && + (c != KVI_TEXT_UNDERLINE) && + (c != KVI_TEXT_REVERSE) && + (c != KVI_TEXT_RESET) && + (c != KVI_TEXT_ICON) && + ((c != ':') || bIgnoreIcons) && + ((c != ';') || bIgnoreIcons) && + ((c != '=') || bIgnoreIcons) + ) + { + bIgnoreIcons=FALSE; + if(c == '&') + { + //look for an html entity + QString szEntity = szText.mid((int)uIdx,6); + if(szEntity==""") + { + uIdx+=5; + } else { + szEntity.truncate(5); + if(szEntity=="&") + { + uIdx+=4; + } else { + szEntity.truncate(4); + if(szEntity=="<" || szEntity==">") uIdx+=3; + } + } + } + + uIdx++; + if(uIdx >= (unsigned int)szText.length()) break; + else c = szText[(int)uIdx].unicode(); + } + + bIgnoreIcons=FALSE; + int iLen = uIdx - uStart; + + if(iLen > 0) + { + bool bOpened = FALSE; + + if(uCurFore != KVI_LABEL_DEF_FORE) + { + szResult.append(""); + + szResult.append(szText.mid(uStart,iLen)); + + if( bOpened ) + szResult.append(""); + } + + switch(c) + { + case KVI_TEXT_BOLD: bCurBold = !bCurBold; ++uIdx; break; + case KVI_TEXT_UNDERLINE: bCurUnderline = !bCurUnderline; ++uIdx; break; + case KVI_TEXT_REVERSE: + { + char auxBack = uCurBack; + uCurBack = uCurFore; + uCurFore = auxBack; + } + ++uIdx; + break; + case KVI_TEXT_RESET: + uCurFore = KVI_LABEL_DEF_FORE; + uCurBack = KVI_LABEL_DEF_BACK; + bCurBold = false; + bCurUnderline = false; + ++uIdx; + break; + case KVI_TEXT_COLOR: + { + ++uIdx; + unsigned char fore; + unsigned char back; + uIdx = getUnicodeColorBytes(szText,uIdx,&fore,&back); + if(fore != KVI_NOCHANGE) + { + uCurFore = fore; + if(back != KVI_NOCHANGE)uCurBack = back; + } else { + // only a CTRL+K + uCurBack = KVI_LABEL_DEF_BACK; + uCurFore = KVI_LABEL_DEF_FORE; + } + } + break; + case ':': + case ';': + case '=': + { + //potential emoticon, got eyes + if(bShowIcons) + { + ++uIdx; + QString szLookup; + szLookup.append(QChar(c)); + unsigned short uIsEmoticon=0; + unsigned int uIcoStart = uIdx; + + if(uIdx < (unsigned int)szText.length()) + { + //look up for a nose + if(szText[(int)uIdx] == '-') + { + szLookup.append('-'); + uIdx++; + } + } + + if(uIdx < (unsigned int)szText.length()) + { + //look up for a mouth + unsigned short m = szText[(int)uIdx].unicode(); + switch(m) + { + case ')': + case '(': + case '/': + case 'D': + case 'P': + case 'S': + case 'O': + case '*': + case '|': + szLookup+=QChar(m); + uIsEmoticon++; + uIdx++; + break; + default: + break; + } + } + + if(uIdx < (unsigned int)szText.length()) + { + //look up for a space + if(szText[(int)uIdx]== ' ') + { + uIsEmoticon++; + } + } else { + //got a smile at the end of the szText + uIsEmoticon++; + } + + if(uIsEmoticon>1) + { + KviTextIcon * pIcon = g_pTextIconManager->lookupTextIcon(szLookup); + // do we have that emoticon-icon association ? + if(pIcon) + { + szResult.append("getSmallIconResourceName(pIcon->id())); + if(uCurBack != KVI_LABEL_DEF_BACK) + { + szResult.append("\" style=\"background-color:"); + szResult.append(KVI_OPTION_MIRCCOLOR(uCurBack).name()); + } + szResult.append("\">"); + } else { + bIgnoreIcons=TRUE; + uIdx = uIcoStart-1; + } + } else { + bIgnoreIcons=TRUE; + uIdx = uIcoStart-1; + } + } else { + bIgnoreIcons=TRUE; + } + } + break; + case KVI_TEXT_ICON: + { + ++uIdx; + if(bShowIcons) + { + unsigned int uIcoStart = uIdx; + while((uIdx < (unsigned int)szText.length()) && (szText[(int)uIdx].unicode() > 32))uIdx++; + + QString szLookup = szText.mid(uIcoStart,uIdx - uIcoStart); + + KviTextIcon * pIcon = g_pTextIconManager->lookupTextIcon(szLookup); + if(pIcon) + { + szResult.append("getSmallIconResourceName(pIcon->id())); + if(uCurBack != KVI_LABEL_DEF_BACK) + { + szResult.append("\" style=\"background-color:"); + szResult.append(KVI_OPTION_MIRCCOLOR(uCurBack).name()); + } + szResult.append("\">"); + } else { + uIdx = uIcoStart; + } + } + } + break; + } + } + szResult.append(""); + //qDebug("%s",szResult.toUtf8().data()); + return szResult; + } +} diff --git a/src/kvirc/kernel/KviHtmlGenerator.h b/src/kvirc/kernel/KviHtmlGenerator.h new file mode 100644 index 000000000..afdc4ce5b --- /dev/null +++ b/src/kvirc/kernel/KviHtmlGenerator.h @@ -0,0 +1,49 @@ +#ifndef _KVI_HTMLGENERATOR_H_ +#define _KVI_HTMLGENERATOR_H_ +//============================================================================= +// +// File : KviHtmlGenerator.h +// Creation date : Mon 04 Jan 2010 22:09:18 by Fabio Bas +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2010 Fabio Bas < ctrlaltca at gmail dot 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviHtmlGenerator.h +* \author Fabio Bas +* \brief Irc => Html format converter; this should better live in kdelibs, but uses kvirc options +*/ + +#include "kvi_settings.h" + +/** +* \namespace KviHtmlGenerator +* \brief A namespace to handle html-related functions +*/ +namespace KviHtmlGenerator +{ + /** + * \brief Converts a raw irc message to its html equivalent text + * \param szText const reference to a message text + * \return QString + */ + extern KVIRC_API QString convertToHtml(const QString &szText); +}; + +#endif //_KVI_HTMLGENERATOR_H_ \ No newline at end of file diff --git a/src/kvirc/kernel/KviIconManager.cpp b/src/kvirc/kernel/KviIconManager.cpp new file mode 100644 index 000000000..7b4d6d6bc --- /dev/null +++ b/src/kvirc/kernel/KviIconManager.cpp @@ -0,0 +1,956 @@ +//============================================================================= +// +// File : KviIconManager.cpp +// Creation date : Sat Jun 24 2000 14:50:11 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + + +#define _KVI_ICONMANAGER_CPP_ + +#include "KviIconManager.h" +#include "KviApplication.h" +#include "kvi_settings.h" +#include "kvi_defaults.h" +#include "KviLocale.h" +#include "KviFileUtils.h" +#include "KviOptions.h" + +#include +#include +#include +#include +#include +#include +#include + +// KviApplication.cpp +extern QPixmap * g_pUserChanStatePixmap; +extern QPixmap * g_pActivityMeterPixmap; + +KviIconManager * g_pIconManager = 0; + +static const char * g_szIconNames[KVI_NUM_SMALL_ICONS]= +{ + "none", // 0 + "close", // 1 + "maximize", // 2 + "minimize", // 3 + "restore", // 4 + "default", // 5 + "dock", // 6 + "undock", // 7 + "quitapp", // 8 + "console", // 9 + "floppy", // 10 + "parsererror", // 11 + "parserwarning", // 12 + "server", // 13 + "world", // 14 + "proxy", // 15 + "kvirc", // 16 + "cut", // 17 + "copy", // 18 + "paste", // 19 + "options", // 20 + "socketmessage", // 21 + "socketwarning", // 22 + "socketerror", // 23 + "systemerror", // 24 + "raw", // 25 + "systemwarning", // 26 + "systemmessage", // 27 + "unhandled", // 28 + "serverinfo", // 29 + "motd", // 30 + "channel", // 31 + "hidedoubleview", // 32 + "showdoubleview", // 33 + "op", // 34 + "voice", // 35 + "serverping", // 36 + "showlistview", // 37 + "hidelistview", // 38 + "join", // 39 + "part", // 40 + "unrecognized", // 41 + "topic", // 42 + "accept", // 43 + "discard", // 44 + "ownprivmsg", // 45 + "chanprivmsg", // 46 + "query", // 48 + "queryprivmsg", // 49 + "help", // 49 + "mdihelp", // 50 + "ctcpreply", // 51 + "ctcprequestreplied", // 52 + "ctcprequestignored", // 53 + "ctcprequestflood", // 54 + "ctcprequestunknown", // 55 + "action", // 56 + "avatar", // 57 + "quit", // 58 + "split", // 59 + "quitsplit", // 60 + "nick", // 61 + "deop", // 62 + "devoice", // 63 + "mode", // 64 + "key", // 65 + "limit", // 66 + "ban", // 67 + "unban", // 68 + "banexcept", // 69 + "banunexcept", // 70 + "inviteexcept", // 71 + "inviteunexcept", // 72 + "chanmode", // 73 + "chanmodehide", // 74 + "who", // 75 + "editor", // 76 + "dccrequest", // 77 + "dccmsg", // 78 + "dccerror", // 79 + "iconmanager", // 80 + "scriptcenter", // 81 + "bomb", // 82 + "event", // 83 + "eventnohandlers", // 84 + "handler", // 85 + "handlerdisabled", // 86 + "nicknameproblem", // 87 + "whoisuser", // 88 + "whoischannels", // 89 + "whoisidle", // 90 + "whoisserver", // 91 + "whoisother", // 92 + "time", // 93 + "notifyonline", // 94 + "notifyoffline", // 95 + "locked", // 96 + "unlocked", // 97 + "lockedoff", // 98 + "unlockedoff", // 99 + "ownprivmsgcrypted", // 100 + "chanprivmsgcrypted", // 101 + "queryprivmsgcrypted", // 102 + "dccchatmsg", // 103 + "dccchatmsgcrypted", // 104 + "irc", // 105 + "folder", // 106 + "home", // 107 + "bookmarks", // 108 + "spy", // 109 + "kick", // 110 + "linux", // 111 + "links", // 112 + "regusers", // 113 + "dockwidget", // 114 + "cascadewindows", // 115 + "maxvertical", // 116 + "maxhorizontal", // 117 + "tilewindows", // 118 + "log", // 119 + "spam", // 120 + "file", // 121 + "icq", // 122 + "icqyellow", // 123 + "icqred", // 124 + "icqblue", // 125 + "icqlightgreen", // 126 + "icqlightyellow", // 127 + "message", // 128 + "messagesent", // 129 + "bluesquare", // 130 + "violetsquare", // 131 + "yellowsquare", // 132 + "greensquare", // 133 + "blacksquare", // 134 + "redsquare", // 135 + "cyansquare", // 136 + "dkgreensquare", // 137 + "terminal", // 138 + "wallops", // 139 + "invisible", // 140 + "servernotice", // 141 + "gnutella", // 142 + "search", // 143 + "files", // 144 + "transfer", // 145 + "package", // 146 + "retry", // 147 + "idea", // 148 + "colors", // 149 + "gui", // 150 + "ircview", // 151 + "alias", // 152 + "channelnotice",// 153 + "channelnoticecrypted", // 154 + "querynotice", // 155 + "querynoticecrypted", // 156 + "servnotice", // 157 + "popup", // 158 + "prologue", // 159 + "epilogue", // 160 + "sharedfiles", // 161 + "ctcpreplyunknown", // 162 + "canvas", // 163 + "nickserv", // 164 + "chanserv", // 165 + "dccvoice", // 166 + "play", // 167 + "record", // 168 + "autotilewindows", // 169 + "away", // 170 + "ident", // 171 + "homepage", // 172 + "list", // 173 + "halfop", // 174 + "halfdeop", // 175 + "invite", // 176 + "multimedia", // 177 + "look", // 178 + "input", // 179 + "messages", // 180 + "querytrace", // 181 + "nochannel", // 182 + "broadcastprivmsg", // 183 + "broadcastnotice", // 184 + "url", // 185 + "rawevent", // 186 + "raweventnohandlers", // 187 + "mekick", // 188 + "meop", // 189 + "mevoice", // 190 + "medeop", // 191 + "medevoice", // 192 + "mehalfop", // 193 + "medehalfop", // 194 + "meban", // 195 + "meunban", // 196 + "mebanexcept", // 197 + "mebanunexcept", // 198 + "meinviteexcept", // 199 + "meinviteunexcept", // 200 + "classicwindowlist", // 201 + "treewindowlist", // 202 + "ignore", // 203 + "userlist",// 204 + "stats", // 205 + "popupmenu", // 206 + "xy", // 207 + "irc0", // 208 + "irc1", // 209 + "irc2", // 210 + "irc3", // 211 + "irc4", // 212 + "irc5", // 213 + "heart", // 214 + "heartbroken", // 215 + "rose", // 215 + "biggrin", // 217 + "biggringlasses", // 218 + "biggrineyes", // 219 + "textexclamative", // 220 + "textpoints", // 221 + "kiss", // 222 + "surprised1", // 223 + "ugly", // 224 + "angry", // 225 + "surprised2", // 226 + "smile", // 227 + "tongue", // 228 + "ssl", // 229 + "cry", // 230 + "eye", // 231 + "deadchannel", // 232 + "deadquery", // 233 + "sound", // 234 + "toolbar", // 235 + "textencoding",// 236 + "newitem", // 237 + "newitembywizard", // 238 + "deleteitem", // 239 + "edititem", // 240 + "filetransfer", // 241 + "chanadmin", // 242 + "chanunadmin", // 243 + "mechanadmin", // 244 + "mechanunadmin", // 245 + "userop", // 246 + "deuserop", // 247 + "meuserop", // 248 + "medeuserop", // 249 + "applet", // 250 + "caption", // 251 + "transparent", // 252 + "alert", // 253 + "userwindow", // 254 + "statusbar", // 255 + "notaway", // 256 + "plus", // 257 + "minus", // 258 + "binarytext", // 259 + "chanowner", // 260 + "chanunowner", // 261 + "mechanowner", // 262 + "mechanunowner", // 263 + "afraid", // 264 + "tongue2", // 265 + "sayicon", // 266 + "saycolors", // 267 + "finger", // 268 + "scriptaction", // 269 + "tearsmile", // 270 + "shy", // 271 + "servererror", // 272 + "cafe", // 273 + "addons", // 274 + "chanowneraway", // 275 + "opaway", // 276 + "voiceaway", // 277 + "chanadminaway", // 278 + "useropaway", // 279 + "halfopaway", // 280 + "classeditor", // 281 + "demoralized", // 282 + "slurp", // 283 + "namespace", // 284 + "saysmile", // 285 + "saykvs", // 286 + "themeoptions", // 287 + "bug", // 288 + "refresh", //289 + "theme", // 290 + "screenshot", // 291 + "update", // 292 + "notupdate", // 293 + "failupdate", // 294 + "unreadtext", // 295 + "ircop", // 296 + "ircopaway", // 297 + "deircop", // 298 + "meircop", // 299 + "medeircop", // 300 + "angel", // 301 + "clown", // 302 + "devil", // 303 + "inlove", // 304 + "ninja", // 305 + "pirate", // 306 + "puke", // 307 + "rage", // 308 + "class", // 309 + "classnotbuilt", // 310 + "function", // 311 + "sexmale", // 312 + "sexfemale", // 313 + "sexbot", // 314 + "sexircop" // 315 +}; + +KviIconWidget::KviIconWidget() +: QWidget(0 /*,WType_TopLevel | WStyle_Customize | WStyle_Title | WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_SysMenu | WStyle_Minimize*/) +{ + setObjectName("global_icon_widget"); + init(); +} + +KviIconWidget::KviIconWidget(QWidget * par) +: QWidget(par) +{ + setObjectName("global_icon_widget"); + init(); +} + +void KviIconWidget::init() +{ + setWindowTitle(__tr2qs("Icon Table")); + setWindowIcon(QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ICONMANAGER)))); + + int rows = KVI_NUM_SMALL_ICONS / 20; + if((rows * 20) < KVI_NUM_SMALL_ICONS)rows++; + QGridLayout * g = new QGridLayout(this); + int i; + for(i = 0;i < 20;i++) + { + KviCString tmp(KviCString::Format,"%d",i); + QLabel * l = new QLabel(tmp.ptr(),this); + g->addWidget(l,0,i + 1); + } + for(i = 0;i < rows;i++) + { + KviCString tmp(KviCString::Format,"%d",i * 20); + QLabel * l = new QLabel(tmp.ptr(),this); + g->addWidget(l,i + 1,0); + } + for(i = 0;i < KVI_NUM_SMALL_ICONS;i++) + { + KviCString tmp(KviCString::Format,"%d",i); + QLabel * l = new QLabel(this); + l->setObjectName(tmp.ptr()); + l->setPixmap(*(g_pIconManager->getSmallIcon(i))); + g->addWidget(l,(i / 20) + 1,(i % 20) + 1); + l->installEventFilter(this); + l->setAcceptDrops(true); + } +} + +KviIconWidget::~KviIconWidget() +{ +} + +void KviIconWidget::closeEvent(QCloseEvent * e) +{ + e->ignore(); + emit closed(); +} + +bool KviIconWidget::eventFilter(QObject * o,QEvent *e) +{ + if(e->type() == QEvent::MouseButtonPress) + { + if(o->inherits("QLabel")) + { + KviCString szName = ((QLabel *)o)->objectName(); + bool bOk; + int iVal = szName.toInt(&bOk); + if(bOk)emit selected(iVal); + + if(parentWidget() && isVisible() && parentWidget()->inherits("KviTalPopupMenu")) + { + parentWidget()->close(); + return true; + } else { + if(const QPixmap * pix = ((QLabel *)o)->pixmap()) + { + QDrag *drobj = new QDrag(this); + QMimeData *mimeData = new QMimeData; + + mimeData->setText(o->objectName()); + mimeData->setImageData(*pix); + drobj->setMimeData(mimeData); + drobj->setPixmap(*pix); + } + } + } + } else if(e->type() == QEvent::DragEnter) + { + ((QDragEnterEvent *)e)->setAccepted(true); + return true; + } + return QWidget::eventFilter(o,e); +} + + +KviCachedPixmap::KviCachedPixmap(QPixmap * ptr,const QString &szPath) +{ + m_szPath = szPath; + m_tLastAccess = kvi_unixTime(); + m_pPixmap = ptr; + m_uSize = m_pPixmap->width() * m_pPixmap->height() * (m_pPixmap->depth() / 8); +} + +KviCachedPixmap::~KviCachedPixmap() +{ + delete m_pPixmap; +} + +void KviCachedPixmap::updateLastAccessTime() +{ + m_tLastAccess = kvi_unixTime(); +} + + +KviIconManager::KviIconManager() +{ + int i=0; + for(i=0;i(21,true); + m_pCachedImages->setAutoDelete(true); + + m_uCacheTotalSize = 0; + m_uCacheMaxSize = 1024 * 1024; // 1 MB + + m_pIconWidget = 0; + + QString buffer; + + // Load the userchanstate image + g_pApp->findImage(buffer,KVI_USERCHANSTATE_IMAGE_NAME); + g_pUserChanStatePixmap = new QPixmap(buffer); + + g_pApp->findImage(buffer,KVI_ACTIVITYMETER_IMAGE_NAME); + g_pActivityMeterPixmap = new QPixmap(buffer); + + m_pIconNames = 0; +} + +KviIconManager::~KviIconManager() +{ + delete g_pUserChanStatePixmap; + delete g_pActivityMeterPixmap; + + if(m_pIconWidget)delete m_pIconWidget; + int i; + + for(i=0;igetLocalKvircDirectory(szPath,KviApplication::Pics); + QDir::addSearchPath("icons", szPath); + + g_pApp->getGlobalKvircDirectory(szPath,KviApplication::Pics); + QDir::addSearchPath("icons", szPath); + + g_pApp->getLocalKvircDirectory(szPath,KviApplication::SmallIcons); + QDir::addSearchPath("smallicons", szPath); + + g_pApp->getGlobalKvircDirectory(szPath,KviApplication::SmallIcons); + QDir::addSearchPath("smallicons", szPath); + +} + +QString KviIconManager::getSmallIconResourceName(int idx) +{ + QString szName("smallicons:kcs_"); + szName.append(g_szIconNames[idx]); + szName.append(".png"); + return szName; +} + +const char * KviIconManager::getSmallIconName(int idx) +{ + return g_szIconNames[idx]; +} + +int KviIconManager::getSmallIconIdFromName(const QString &szName) +{ + if(!m_pIconNames) + { + m_pIconNames = new KviPointerHashTable(257,false); + m_pIconNames->setAutoDelete(true); + + for(int i=0;ireplace(QString(g_szIconNames[i]),pInt); + } + } + int * pInt = m_pIconNames->find(szName); + if(!pInt)return 0; + return *pInt; +} + +void KviIconManager::showIconWidget() +{ + if(!m_pIconWidget) + { + m_pIconWidget = new KviIconWidget(); + connect(m_pIconWidget,SIGNAL(closed()),this,SLOT(iconWidgetClosed())); + } + m_pIconWidget->show(); + m_pIconWidget->raise(); + m_pIconWidget->setFocus(); +} + +void KviIconManager::iconWidgetClosed() +{ + delete m_pIconWidget; + m_pIconWidget = 0; +} + +/* + @doc: image_id + @title: + The image identifier + @keyterms: + image identifier, using builtin images, how kvirc locates image files + @type: + language + @short: + Semantics of the parameter + @body: + Some KVIrc commands and functions accept + the as a parameter. + The indicates an image to be displayed + by some gui element. Since KVIrc has a set of + builtin icons, we want the user to be able to use it :).[br] + The can be either a signed integer number + or a filename.[br] + If it is a signed integer it is interpreted as + index of the internal KVIrc image to use: + positive integers (starting at 0) indicate + small (16x16) icons (the ones used in the view widget).[br] + If is anything else than a signed integer, + it is interpreted as a filename. + The filename can be an absolute file path or a relative one. + In this last case KVIrc will look for the file in a predefined set + of directories: First in the local "pics" directory (usually + in ~/kvirc-version/pics/), then in the local "incoming" directory, + then in the global "pics" directory, then in the user home (~) + and in the current directory.[br] +*/ + +KviCachedPixmap * KviIconManager::getPixmapWithCache(const QString &szName) +{ + if(szName.isEmpty())return 0; + + KviCachedPixmap * p = m_pCachedImages->find(szName); + + if(p) + { + p->updateLastAccessTime(); + return p; + } + + QPixmap * pix = 0; + + QString szRetPath; + + if(g_pApp->findImage(szRetPath,szName)) + { + pix = new QPixmap(szRetPath); + if(pix->isNull()) + { + delete pix; // it is not an valid image!!! (really bad situation...) + pix = 0; + return 0; + } + } else { + return 0; + } + + p = new KviCachedPixmap(pix,QString(szRetPath)); + addToCache(szName,p); + + return p; +} + +KviCachedPixmap * KviIconManager::getPixmapWithCacheScaleOnLoad(const QString &szName,int iMaxWidth,int iMaxHeight) +{ + if(szName.isEmpty())return 0; + + KviCachedPixmap * p = m_pCachedImages->find(szName); + + if(p) + { + p->updateLastAccessTime(); + return p; + } + + QPixmap * pix = 0; + + QString szRetPath; + + if(g_pApp->findImage(szRetPath,szName)) + { + pix = new QPixmap(szRetPath); + if(pix->isNull()) + { + delete pix; // it is not an valid image!!! (really bad situation...) + pix = 0; + return 0; + } + if((pix->width() > iMaxWidth) || (pix->height() > iMaxHeight)) + { + // scale to fit + int scaleW = iMaxWidth; + int scaleH; + scaleH = (pix->height() * iMaxWidth) / pix->width(); + if(scaleH > iMaxHeight) + { + scaleH = iMaxHeight; + scaleW = (scaleH * pix->width()) / pix->height(); + } + + QImage img = pix->toImage(); + *pix = QPixmap::fromImage(img.scaled(scaleW,scaleH,Qt::IgnoreAspectRatio,Qt::SmoothTransformation)); + } + } else { + return 0; + } + + p = new KviCachedPixmap(pix,QString(szRetPath)); + addToCache(szName,p); + + return p; +} + +void KviIconManager::addToCache(const QString &szName,KviCachedPixmap * p) +{ + if((m_uCacheTotalSize + p->size()) >= m_uCacheMaxSize)cacheCleanup(); + + m_pCachedImages->insert(szName,p); + m_uCacheTotalSize += p->size(); +} + +QPixmap * KviIconManager::getImage(const QString &id,bool bCanBeNumber,QString* pRetPath) +{ + if(id.isEmpty()) + return NULL; + + if(bCanBeNumber) + { + bool bOk; + int idx = id.toInt(&bOk); + if(bOk) + { + // was a number : this is not a filename + if(idx >= 0) + return getSmallIcon(idx % KVI_NUM_SMALL_ICONS); + } else { + if(id.startsWith("$icon")) + { + QString szTmp = id.trimmed(); + szTmp.replace("$icon(",""); + szTmp.replace(")",""); + szTmp = szTmp.trimmed(); + szTmp.replace("\"",""); + idx = getSmallIconIdFromName(szTmp.trimmed()); + if(idx >= 0) + return getSmallIcon(idx % KVI_NUM_SMALL_ICONS); + + } + } + } + + KviCachedPixmap * p = getPixmapWithCache(id); + if(!p) + return NULL; + + if(pRetPath) + *pRetPath = p->path(); + + return p->pixmap(); +} + + +QPixmap * KviIconManager::getBigIcon(const QString &szName) +{ + QPixmap * p = getPixmap(szName); + if(p)return p; + + bool bOk; + int idx = szName.toInt(&bOk); + if(bOk && (idx >= 0)) + { + // was a number : this is not a filename + // it was a small icon: scale it and cache it + QString tmpName = szName; + tmpName += ".scaled16to32"; + p = getPixmap(tmpName); + if(p)return p; + p = getSmallIcon(idx % KVI_NUM_SMALL_ICONS); + if(p) + { + QImage tmpi = p->toImage(); + QImage tmp2 = tmpi.scaled(32,32,Qt::IgnoreAspectRatio,Qt::SmoothTransformation); + QPixmap *pix=new QPixmap(); + *pix = QPixmap::fromImage(tmp2); + KviCachedPixmap * cp = new KviCachedPixmap(pix,QString()); + addToCache(tmpName,cp); + return cp->pixmap(); + } + } + + p = getPixmap("kvi_bigicon_unknown.png"); + if(p)return p; + KviCachedPixmap * cp = new KviCachedPixmap(new QPixmap(32,32),QString()); + addToCache(szName,cp); + return cp->pixmap(); +} + +void KviIconManager::urlToCachedFileName(QString &szFName) +{ + szFName.replace(":","_"); + szFName.replace(";","_"); + szFName.replace("/","_"); + szFName.replace("\\","_"); + szFName.replace("\"","_"); + szFName.replace("\'","_"); + szFName.replace("(","_"); + szFName.replace(")","_"); + szFName.replace("?","_"); + szFName.replace("___","."); + //cut filenames to 255 chars, trying to preserve file name/extension (bug #616) + if(szFName.size()>255) + { + QString ext = szFName.right(55); + szFName.truncate(200); + szFName.append(ext); + } +} + +KviAvatar * KviIconManager::getAvatar(const QString &szLocalPath,const QString &szName) +{ + QString szP,szN; + + if(szLocalPath.isEmpty()) + { + //both path and name empty => fail + if(szName.isEmpty()) + return 0; + if(KviQString::equalCIN("http://",szName,7)) + { + // it's an url, cache it locally + szN = szName; + urlToCachedFileName(szN); + g_pApp->getLocalKvircDirectory(szP,KviApplication::Avatars,szN); + szN = szName; // keep the remote url as name + } else { + //locally cached avatar, called only by its szName + szN = KviFileUtils::extractFileName(szName); + g_pApp->getLocalKvircDirectory(szP,KviApplication::Avatars,szN); + } + } else if(szName.isEmpty()) + { + if(szLocalPath.isEmpty()) + return 0; + szP = szLocalPath; + szN = KviFileUtils::extractFileName(szLocalPath); + } else { + szP = szLocalPath; + szN = szName; + } + + // avatars bigger than 1024x768 just sux: they can't be seen on tooltips anyway + //KviCachedPixmap * p = KVI_OPTION_BOOL(KviOption_boolScaleAvatarsOnLoad) ? getPixmapWithCacheScaleOnLoad(szP, + // KVI_OPTION_UINT(KviOption_uintScaleAvatarsOnLoadWidth) + // ,KVI_OPTION_UINT(KviOption_uintScaleAvatarsOnLoadHeight)) : getPixmapWithCache(szP); + //if(!p)return 0; + + + KviAvatar* result = 0; + + if(KviFileUtils::fileExists(szP)) + { + if(KVI_OPTION_BOOL(KviOption_boolScaleAvatarsOnLoad)) + { + result = new KviAvatar(szP,szN, + QSize( + KVI_OPTION_UINT(KviOption_uintScaleAvatarsOnLoadWidth), + KVI_OPTION_UINT(KviOption_uintScaleAvatarsOnLoadHeight) + ) + ); + } else { + result = new KviAvatar(szP,szN); + } + } + + //Can't load it + if(result && !result->isValid()) + { + delete result; + result = 0; + } + + return result; +} + +void KviIconManager::clearCache() +{ + m_pCachedImages->clear(); +} + +void KviIconManager::reloadImages() +{ + clearCache(); + for(int i=0;i= KVI_NUM_SMALL_ICONS)return 0; + if(idx < 0)return 0; + + QString szPath; + QString buffer; + KviQString::sprintf(szPath,KVI_SMALLICONS_PREFIX "%s.png",g_szIconNames[idx]); + + g_pApp->findSmallIcon(buffer,szPath); + m_smallIcons[idx] = new QPixmap(buffer); + + //if(m_smallIcon[idx]->isNull()) + //{ + // // load an "unknown" image ?.. but should never happen + //} + return m_smallIcons[idx]; +} + +void KviIconManager::cacheCleanup() +{ + QStringList l; + + KviPointerHashTableIterator it(*m_pCachedImages); + + +//#warning "IMPLEMENT CLEANUP" +/* + while(it.current()) + { + kvi_time_t curTime = kvi_unixTime(); + + if((((unsigned int)it.current()->timestamp) - ((unsigned int)curTime)) > 120) + { + // unused since 2 minutes + // time to cleanup it... + l.append(new KviCString(it.currentKey())); + } + ++it; + } + + for(QStringList::Iterator it = l.begin();it != l.end();++it) + { + m_pCachedImages->remove(*it); + } +*/ +/* + for(KviCString * p =l.first();p;p = l.next()) + { + m_pCachedImages->remove(p->ptr()); + } + if(m_pCachedImages->isEmpty())m_pCleanupTimer->stop(); +*/ +} + +#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES +#include "kvi_iconmanager.moc" +#endif //!COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/KviIconManager.h b/src/kvirc/kernel/KviIconManager.h new file mode 100644 index 000000000..aaaf2b729 --- /dev/null +++ b/src/kvirc/kernel/KviIconManager.h @@ -0,0 +1,528 @@ +#ifndef _KVI_ICONMANAGER_H_ +#define _KVI_ICONMANAGER_H_ + +//============================================================================= +// +// File : KviIconManager.h +// Creation date : Sat Jun 24 2000 14:49:24 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviCString.h" +#include "KviAvatar.h" +#include "KviTimeUtils.h" +#include "KviPointerHashTable.h" + +#include +#include +#include + +#define KVI_SMALLICON_NONE 0 +#define KVI_SMALLICON_CLOSE 1 +#define KVI_SMALLICON_MAXIMIZE 2 +#define KVI_SMALLICON_MINIMIZE 3 +#define KVI_SMALLICON_RESTORE 4 +#define KVI_SMALLICON_DEFAULTICON 5 +#define KVI_SMALLICON_DOCK 6 +#define KVI_SMALLICON_UNDOCK 7 +#define KVI_SMALLICON_QUITAPP 8 +#define KVI_SMALLICON_CONSOLE 9 +#define KVI_SMALLICON_FLOPPY 10 +#define KVI_SMALLICON_PARSERERROR 11 +#define KVI_SMALLICON_PARSERWARNING 12 +#define KVI_SMALLICON_SERVER 13 +#define KVI_SMALLICON_WORLD 14 +#define KVI_SMALLICON_PROXY 15 +#define KVI_SMALLICON_KVIRC 16 +#define KVI_SMALLICON_CUT 17 +#define KVI_SMALLICON_COPY 18 +#define KVI_SMALLICON_PASTE 19 +#define KVI_SMALLICON_OPTIONS 20 +#define KVI_SMALLICON_SOCKETMESSAGE 21 +#define KVI_SMALLICON_SOCKETWARNING 22 +#define KVI_SMALLICON_SOCKETERROR 23 +#define KVI_SMALLICON_SYSTEMERROR 24 +#define KVI_SMALLICON_RAW 25 +#define KVI_SMALLICON_SYSTEMWARNING 26 +#define KVI_SMALLICON_SYSTEMMESSAGE 27 +#define KVI_SMALLICON_UNHANDLED 28 +#define KVI_SMALLICON_SERVERINFO 29 +#define KVI_SMALLICON_MOTD 30 +#define KVI_SMALLICON_CHANNEL 31 +#define KVI_SMALLICON_HIDEDOUBLEVIEW 32 +#define KVI_SMALLICON_SHOWDOUBLEVIEW 33 +#define KVI_SMALLICON_OP 34 +#define KVI_SMALLICON_VOICE 35 +#define KVI_SMALLICON_SERVERPING 36 +#define KVI_SMALLICON_SHOWLISTVIEW 37 +#define KVI_SMALLICON_HIDELISTVIEW 38 +#define KVI_SMALLICON_JOIN 39 +#define KVI_SMALLICON_PART 40 +#define KVI_SMALLICON_UNRECOGNIZED 41 +#define KVI_SMALLICON_TOPIC 42 +#define KVI_SMALLICON_ACCEPT 43 +#define KVI_SMALLICON_DISCARD 44 +#define KVI_SMALLICON_OWNPRIVMSG 45 +#define KVI_SMALLICON_CHANPRIVMSG 46 +#define KVI_SMALLICON_QUERY 47 +#define KVI_SMALLICON_QUERYPRIVMSG 48 +#define KVI_SMALLICON_HELP 49 +#define KVI_SMALLICON_MDIHELP 50 +#define KVI_SMALLICON_CTCPREPLY 51 +#define KVI_SMALLICON_CTCPREQUESTREPLIED 52 +#define KVI_SMALLICON_CTCPREQUESTIGNORED 53 +#define KVI_SMALLICON_CTCPREQUESTFLOOD 54 +#define KVI_SMALLICON_CTCPREQUESTUNKNOWN 55 +#define KVI_SMALLICON_ACTION 56 +#define KVI_SMALLICON_AVATAR 57 +#define KVI_SMALLICON_QUIT 58 +#define KVI_SMALLICON_SPLIT 59 +#define KVI_SMALLICON_QUITSPLIT 60 +#define KVI_SMALLICON_NICK 61 +#define KVI_SMALLICON_DEOP 62 +#define KVI_SMALLICON_DEVOICE 63 +#define KVI_SMALLICON_MODE 64 +#define KVI_SMALLICON_KEY 65 +#define KVI_SMALLICON_LIMIT 66 +#define KVI_SMALLICON_BAN 67 +#define KVI_SMALLICON_UNBAN 68 +#define KVI_SMALLICON_BANEXCEPT 69 +#define KVI_SMALLICON_BANUNEXCEPT 70 +#define KVI_SMALLICON_INVITEEXCEPT 71 +#define KVI_SMALLICON_INVITEUNEXCEPT 72 +#define KVI_SMALLICON_CHANMODE 73 +#define KVI_SMALLICON_CHANMODEHIDE 74 +#define KVI_SMALLICON_WHO 75 +#define KVI_SMALLICON_EDITOR 76 +#define KVI_SMALLICON_DCCREQUEST 77 +#define KVI_SMALLICON_DCCMSG 78 +#define KVI_SMALLICON_DCCERROR 79 +#define KVI_SMALLICON_ICONMANAGER 80 +#define KVI_SMALLICON_SCRIPTCENTER 81 +#define KVI_SMALLICON_BOMB 82 +#define KVI_SMALLICON_EVENT 83 +#define KVI_SMALLICON_EVENTNOHANDLERS 84 +#define KVI_SMALLICON_HANDLER 85 +#define KVI_SMALLICON_HANDLERDISABLED 86 +#define KVI_SMALLICON_NICKNAMEPROBLEM 87 +#define KVI_SMALLICON_WHOISUSER 88 +#define KVI_SMALLICON_WHOISCHANNELS 89 +#define KVI_SMALLICON_WHOISIDLE 90 +#define KVI_SMALLICON_WHOISSERVER 91 +#define KVI_SMALLICON_WHOISOTHER 92 +#define KVI_SMALLICON_TIME 93 +#define KVI_SMALLICON_NOTIFYONLINE 94 +#define KVI_SMALLICON_NOTIFYOFFLINE 95 +#define KVI_SMALLICON_LOCKED 96 +#define KVI_SMALLICON_UNLOCKED 97 +#define KVI_SMALLICON_LOCKEDOFF 98 +#define KVI_SMALLICON_UNLOCKEDOFF 99 +#define KVI_SMALLICON_OWNPRIVMSGCRYPTED 100 +#define KVI_SMALLICON_CHANPRIVMSGCRYPTED 101 +#define KVI_SMALLICON_QUERYPRIVMSGCRYPTED 102 +#define KVI_SMALLICON_DCCCHATMSG 103 +#define KVI_SMALLICON_DCCCHATMSGCRYPTED 104 +#define KVI_SMALLICON_IRC 105 +#define KVI_SMALLICON_FOLDER 106 +#define KVI_SMALLICON_HOME 107 +#define KVI_SMALLICON_BOOKMARKS 108 +#define KVI_SMALLICON_SPY 109 +#define KVI_SMALLICON_KICK 110 +#define KVI_SMALLICON_LINUX 111 +#define KVI_SMALLICON_LINKS 112 +#define KVI_SMALLICON_REGUSERS 113 +#define KVI_SMALLICON_TRAYICON 114 +#define KVI_SMALLICON_CASCADEWINDOWS 115 +#define KVI_SMALLICON_MAXVERTICAL 116 +#define KVI_SMALLICON_MAXHORIZONTAL 117 +#define KVI_SMALLICON_TILEWINDOWS 118 +#define KVI_SMALLICON_LOG 119 +#define KVI_SMALLICON_SPAM 120 +#define KVI_SMALLICON_FILE 121 +#define KVI_SMALLICON_ICQ 122 +#define KVI_SMALLICON_ICQYELLOW 123 +#define KVI_SMALLICON_ICQRED 124 +#define KVI_SMALLICON_ICQBLUE 125 +#define KVI_SMALLICON_ICQLIGHTGREEN 126 +#define KVI_SMALLICON_ICQLIGHTYELLOW 127 +#define KVI_SMALLICON_MESSAGE 128 +#define KVI_SMALLICON_MESSAGESENT 129 +#define KVI_SMALLICON_BLUESQUARE 130 +#define KVI_SMALLICON_VIOLETSQUARE 131 +#define KVI_SMALLICON_YELLOWSQUARE 132 +#define KVI_SMALLICON_GREENSQUARE 133 +#define KVI_SMALLICON_BLACKSQUARE 134 +#define KVI_SMALLICON_REDSQUARE 135 +#define KVI_SMALLICON_CYANSQUARE 136 +#define KVI_SMALLICON_DKGREENSQUARE 137 +#define KVI_SMALLICON_TERMINAL 138 +#define KVI_SMALLICON_WALLOPS 139 +#define KVI_SMALLICON_INVISIBLE 140 +#define KVI_SMALLICON_SERVERNOTICE 141 +#define KVI_SMALLICON_GNUTELLA 142 +#define KVI_SMALLICON_SEARCH 143 +#define KVI_SMALLICON_FILES 144 +#define KVI_SMALLICON_TRANSFER 145 +#define KVI_SMALLICON_PACKAGE 146 +#define KVI_SMALLICON_RETRY 147 +#define KVI_SMALLICON_IDEA 148 +#define KVI_SMALLICON_COLORS 149 +#define KVI_SMALLICON_GUI 150 +#define KVI_SMALLICON_IRCVIEW 151 +#define KVI_SMALLICON_ALIAS 152 +#define KVI_SMALLICON_CHANNELNOTICE 153 +#define KVI_SMALLICON_CHANNELNOTICECRYPTED 154 +#define KVI_SMALLICON_QUERYNOTICE 155 +#define KVI_SMALLICON_QUERYNOTICECRYPTED 156 +#define KVI_SMALLICON_SERVNOTICE 157 +#define KVI_SMALLICON_POPUP 158 +#define KVI_SMALLICON_PROLOGUE 159 +#define KVI_SMALLICON_EPILOGUE 160 +#define KVI_SMALLICON_SHAREDFILES 161 +#define KVI_SMALLICON_CTCPREPLYUNKNOWN 162 +#define KVI_SMALLICON_CANVAS 163 +#define KVI_SMALLICON_NICKSERV 164 +#define KVI_SMALLICON_CHANSERV 165 +#define KVI_SMALLICON_DCCVOICE 166 +#define KVI_SMALLICON_PLAY 167 +#define KVI_SMALLICON_RECORD 168 +#define KVI_SMALLICON_AUTOTILEWINDOWS 169 +#define KVI_SMALLICON_AWAY 170 +#define KVI_SMALLICON_IDENT 171 +#define KVI_SMALLICON_HOMEPAGE 172 +#define KVI_SMALLICON_LIST 173 +#define KVI_SMALLICON_HALFOP 174 +#define KVI_SMALLICON_HALFDEOP 175 +#define KVI_SMALLICON_INVITE 176 +#define KVI_SMALLICON_MULTIMEDIA 177 +#define KVI_SMALLICON_LOOK 178 +#define KVI_SMALLICON_INPUT 179 +#define KVI_SMALLICON_MESSAGES 180 +#define KVI_SMALLICON_QUERYTRACE 181 +#define KVI_SMALLICON_NOCHANNEL 182 +#define KVI_SMALLICON_BROADCASTPRIVMSG 183 +#define KVI_SMALLICON_BROADCASTNOTICE 184 +#define KVI_SMALLICON_URL 185 +#define KVI_SMALLICON_RAWEVENT 186 +#define KVI_SMALLICON_RAWEVENTNOHANDLERS 187 +#define KVI_SMALLICON_MEKICK 188 +#define KVI_SMALLICON_MEOP 189 +#define KVI_SMALLICON_MEVOICE 190 +#define KVI_SMALLICON_MEDEOP 191 +#define KVI_SMALLICON_MEDEVOICE 192 +#define KVI_SMALLICON_MEHALFOP 193 +#define KVI_SMALLICON_MEDEHALFOP 194 +#define KVI_SMALLICON_MEBAN 195 +#define KVI_SMALLICON_MEUNBAN 196 +#define KVI_SMALLICON_MEBANEXCEPT 197 +#define KVI_SMALLICON_MEBANUNEXCEPT 198 +#define KVI_SMALLICON_MEINVITEEXCEPT 199 +#define KVI_SMALLICON_MEINVITEUNEXCEPT 200 +#define KVI_SMALLICON_CLASSICWINDOWLIST 201 +#define KVI_SMALLICON_TREEWINDOWLIST 202 +#define KVI_SMALLICON_IGNORE 203 +#define KVI_SMALLICON_USERLIST 204 +#define KVI_SMALLICON_STATS 205 +#define KVI_SMALLICON_POPUPMENU 206 +#define KVI_SMALLICON_XY 207 +#define KVI_SMALLICON_IRC0 208 +#define KVI_SMALLICON_IRC1 209 +#define KVI_SMALLICON_IRC2 210 +#define KVI_SMALLICON_IRC3 211 +#define KVI_SMALLICON_IRC4 212 +#define KVI_SMALLICON_IRC5 213 +#define KVI_SMALLICON_HEART 214 +#define KVI_SMALLICON_HEARTBROKEN 215 +#define KVI_SMALLICON_ROSE 216 +#define KVI_SMALLICON_BIGGRIN 217 +#define KVI_SMALLICON_BIGGRINGLASSES 218 +#define KVI_SMALLICON_BIGGRINEYES 219 +#define KVI_SMALLICON_TEXTEXCLAMATIVE 220 +#define KVI_SMALLICON_TEXTPOINTS 221 +#define KVI_SMALLICON_KISS 222 +#define KVI_SMALLICON_SURPRISED1 223 +#define KVI_SMALLICON_UGLY 224 +#define KVI_SMALLICON_ANGRY 225 +#define KVI_SMALLICON_SURPRISED2 226 +#define KVI_SMALLICON_SMILE 227 +#define KVI_SMALLICON_TONGUE 228 +#define KVI_SMALLICON_SSL 229 +#define KVI_SMALLICON_CRY 230 +#define KVI_SMALLICON_EYE 231 +#define KVI_SMALLICON_DEADCHANNEL 232 +#define KVI_SMALLICON_DEADQUERY 233 +#define KVI_SMALLICON_SOUND 234 +#define KVI_SMALLICON_TOOLBAR 235 +#define KVI_SMALLICON_TEXTENCODING 236 +#define KVI_SMALLICON_NEWITEM 237 +#define KVI_SMALLICON_NEWITEMBYWIZARD 238 +#define KVI_SMALLICON_DELETEITEM 239 +#define KVI_SMALLICON_EDITITEM 240 +#define KVI_SMALLICON_FILETRANSFER 241 +#define KVI_SMALLICON_CHANADMIN 242 +#define KVI_SMALLICON_CHANUNADMIN 243 +#define KVI_SMALLICON_MECHANADMIN 244 +#define KVI_SMALLICON_MECHANUNADMIN 245 +#define KVI_SMALLICON_USEROP 246 +#define KVI_SMALLICON_DEUSEROP 247 +#define KVI_SMALLICON_MEUSEROP 248 +#define KVI_SMALLICON_MEDEUSEROP 249 +#define KVI_SMALLICON_APPLET 250 +#define KVI_SMALLICON_CAPTION 251 +#define KVI_SMALLICON_TRANSPARENT 252 +#define KVI_SMALLICON_ALERT 253 +#define KVI_SMALLICON_USERWINDOW 254 +#define KVI_SMALLICON_STATUSBAR 255 +#define KVI_SMALLICON_NOTAWAY 256 +#define KVI_SMALLICON_PLUS 257 +#define KVI_SMALLICON_MINUS 258 +#define KVI_SMALLICON_BINARYTEXT 259 +#define KVI_SMALLICON_CHANOWNER 260 +#define KVI_SMALLICON_CHANUNOWNER 261 +#define KVI_SMALLICON_MECHANOWNER 262 +#define KVI_SMALLICON_MECHANUNOWNER 263 +#define KVI_SMALLICON_AFRAID 264 +#define KVI_SMALLICON_TONGUE2 265 +#define KVI_SMALLICON_SAYICON 266 +#define KVI_SMALLICON_SAYCOLORS 267 +#define KVI_SMALLICON_FINGER 268 +#define KVI_SMALLICON_SCRIPTACTION 269 +#define KVI_SMALLICON_TEARSMILE 270 +#define KVI_SMALLICON_SHY 271 +#define KVI_SMALLICON_SERVERERROR 272 +#define KVI_SMALLICON_CAFE 273 +#define KVI_SMALLICON_ADDONS 274 +#define KVI_SMALLICON_CHANOWNERAWAY 275 +#define KVI_SMALLICON_OPAWAY 276 +#define KVI_SMALLICON_VOICEAWAY 277 +#define KVI_SMALLICON_CHANADMINAWAY 278 +#define KVI_SMALLICON_USEROPAWAY 279 +#define KVI_SMALLICON_HALFOPAWAY 280 +#define KVI_SMALLICON_CLASSEDITOR 281 +#define KVI_SMALLICON_DEMORALIZED 282 +#define KVI_SMALLICON_SLURP 283 +#define KVI_SMALLICON_NAMESPACE 284 +#define KVI_SMALLICON_SAYSMILE 285 +#define KVI_SMALLICON_SAYKVS 286 +#define KVI_SMALLICON_THEMEOPTIONS 287 +#define KVI_SMALLICON_BUG 288 +#define KVI_SMALLICON_REFRESH 289 +#define KVI_SMALLICON_THEME 290 +#define KVI_SMALLICON_SCREENSHOT 291 +#define KVI_SMALLICON_UPDATE 292 +#define KVI_SMALLICON_NOTUPDATE 293 +#define KVI_SMALLICON_FAILUPDATE 294 +#define KVI_SMALLICON_UNREADTEXT 295 +#define KVI_SMALLICON_IRCOP 296 +#define KVI_SMALLICON_IRCOPAWAY 297 +#define KVI_SMALLICON_DEIRCOP 298 +#define KVI_SMALLICON_MEIRCOP 299 +#define KVI_SMALLICON_MEDEIRCOP 300 +#define KVI_SMALLICON_ANGEL 301 +#define KVI_SMALLICON_CLOWN 302 +#define KVI_SMALLICON_DEVIL 303 +#define KVI_SMALLICON_INLOVE 304 +#define KVI_SMALLICON_NINJA 305 +#define KVI_SMALLICON_PIRATE 306 +#define KVI_SMALLICON_PUKE 307 +#define KVI_SMALLICON_RAGE 308 +#define KVI_SMALLICON_CLASS 309 +#define KVI_SMALLICON_CLASSNOTBUILT 310 +#define KVI_SMALLICON_FUNCTION 311 +#define KVI_SMALLICON_SEXMALE 312 +#define KVI_SMALLICON_SEXFEMALE 313 +#define KVI_SMALLICON_SEXBOT 314 +#define KVI_SMALLICON_SEXIRCOP 315 + +#define KVI_NUM_SMALL_ICONS 316 + + +#define KVI_BIGICON_DISCONNECTED "kvi_bigicon_disconnected.png" +#define KVI_BIGICON_CONNECTING "kvi_bigicon_connecting.png" +#define KVI_BIGICON_CONNECTED "kvi_bigicon_connected.png" +#define KVI_BIGICON_TOOLS "kvi_bigicon_tools.png" +#define KVI_BIGICON_ACTIONS "kvi_bigicon_actions.png" +#define KVI_BIGICON_FOLDER "kvi_bigicon_folder.png" +#define KVI_BIGICON_UNKNOWN "kvi_bigicon_unknown.png" +#define KVI_BIGICON_SEPARATOR "kvi_bigicon_separator.png" +#define KVI_BIGICON_KVS "kvi_bigicon_kvs.png" +#define KVI_BIGICON_THEME "kvi_bigicon_theme.png" +#define KVI_BIGICON_ADDONS "kvi_bigicon_addons.png" + +#define KVI_BIGICON_HELP "kvi_bigicon_help.png" +#define KVI_BIGICON_HELPINDEX "kvi_bigicon_helpindex.png" +#define KVI_BIGICON_HELPBACK "kvi_bigicon_helpback.png" +#define KVI_BIGICON_HELPFORWARD "kvi_bigicon_helpforward.png" +#define KVI_BIGICON_HELPCLOSE "kvi_bigicon_helpclose.png" +#define KVI_BIGICON_HELPSEARCH "kvi_bigicon_helpsearch.png" + +#define KVI_BIGICON_OPEN "kvi_bigicon_open.png" +#define KVI_BIGICON_SAVE "kvi_bigicon_save.png" +#define KVI_BIGICON_REMOVE "kvi_bigicon_remove.png" +#define KVI_BIGICON_WWW "kvi_bigicon_www.png" +#define KVI_BIGICON_PACK "kvi_bigicon_pack.png" +#define KVI_BIGICON_SCREENSHOT "kvi_bigicon_screenshot.png" +#define KVI_BIGICON_REGUSERS "kvi_bigicon_regusers.png" + +#define KVI_SMALLICONS_SUBDIRECTORY "coresmall" +#define KVI_SMALLICONS_PREFIX "kcs_" + +// FIXME: this should be removed +#define KVI_SMALLICONS_IMAGELIB_PREFIX "kvi_smallicon_" + +#define KVI_USERCHANSTATE_IMAGE_NAME "kvi_userchanstate.png" +#define KVI_ACTIVITYMETER_IMAGE_NAME "kvi_activitymeter.png" + +#define KVI_REFRESH_IMAGE_NAME "kvi_icon_refresh.png" + +class KviIconManager; + +class KVIRC_API KviCachedPixmap +{ +public: + // the pixmap MUST be allocated with new QPixmap() + // this calss takes the ownership + KviCachedPixmap(QPixmap * ptr,const QString &szPath); + ~KviCachedPixmap(); +private: + QString m_szPath; + kvi_time_t m_tLastAccess; + QPixmap * m_pPixmap; + unsigned int m_uSize; +public: + QPixmap * pixmap(){ return m_pPixmap; }; + const QString & path(){ return m_szPath; }; + unsigned int size(){ return m_uSize; }; + kvi_time_t lastAccessTime(){ return m_tLastAccess; }; + void updateLastAccessTime(); +}; + +class KVIRC_API KviIconWidget : public QWidget +{ + Q_OBJECT +public: + KviIconWidget(); + KviIconWidget(QWidget * par); + ~KviIconWidget(); +protected: + void init(); + virtual void closeEvent(QCloseEvent *e); + virtual bool eventFilter(QObject * o,QEvent *e); +signals: + void closed(); + void selected(int iIcon); +}; + + + +// +// This class manages the images used by KVIrc. +// +// We handle three types of images: builtin small icons, builtin big icons and generic images. +// +// The builtin small icons are in the pics/coresmall directory (this is to optimize the directory size +// since it's a linear search...), are 16x16 in size and are indexed by numbers in a way that their +// access is really fast. The icons used here are used mostly in KviIrcView (but not exclusively). +// +// The generic images are just "any" image that the underlying Qt engine +// is able to load. They are loaded by (relative) path and +// cached by name. +// +// The builtin big icons are (actually) just generic images +// that are eventually scaled to 32x32 if needed. One can request +// a builtin small icon indexed by number to be scaled +// to the size of 32x32 as a big icon too. +// + +class KVIRC_API KviIconManager : public QObject +{ + Q_OBJECT +public: + KviIconManager(); + ~KviIconManager(); +private: + QPixmap * m_smallIcons[KVI_NUM_SMALL_ICONS]; + KviIconWidget * m_pIconWidget; + + KviPointerHashTable * m_pCachedImages; + KviPointerHashTable * m_pIconNames; + unsigned int m_uCacheTotalSize; + unsigned int m_uCacheMaxSize; +public: + // WARNING: Don't store this pointer! + // id == filename | number that indicates an internal pixmap + // 0 stands for "any" + QPixmap * getImage(const QString &id,bool bCanBeNumber = true,QString* pRetPath = 0); + + // The returned pointer is owned by the icon manager + // and can be deleted at any time : so don't store it + KviCachedPixmap * getPixmapWithCache(const QString &szName); + + // The returned pointer is owned by the icon manager + // and can be deleted at any time : so don't store it + KviCachedPixmap * getPixmapWithCacheScaleOnLoad(const QString &szName,int iMaxWidth,int iMaxHeight); + + // The returned pointer is owned by the icon manager + // and can be deleted at any time : so don't store it + QPixmap * getPixmap(const QString &szName) + { KviCachedPixmap * p = getPixmapWithCache(szName); return p ? p->pixmap() : 0; }; + + // this one never fails... if the image can't be found + // a default 32x32 image is returned + QPixmap * getBigIcon(const QString &szName); + + // this one never fails... if the icon isn't there + // then a default 16x16 image is returned + QPixmap * getSmallIcon(int idx){ return idx < KVI_NUM_SMALL_ICONS ? (m_smallIcons[idx] ? m_smallIcons[idx] : loadSmallIcon(idx) ) : 0; }; + + const char * getSmallIconName(int idx); + + QString getSmallIconResourceName(int idx); + + int getSmallIconIdFromName(const QString &szName); + + // if szLocalPath is empty then szName can be the identification + // string for the avatar + // if szName is empty then it is found from szLocalPath + KviAvatar * getAvatar(const QString &szLocalPath,const QString &szName); + + void urlToCachedFileName(QString &szFName); + + void clearCache(); + void reloadImages(); + + void cacheCleanup(); + +protected: + void addToCache(const QString &szName,KviCachedPixmap * p); + //void loadSmallIcons(); + QPixmap * loadSmallIcon(int idx); + + void initQResourceBackend(); +public slots: + void showIconWidget(); +protected slots: + void iconWidgetClosed(); +}; + +extern KVIRC_API KviIconManager * g_pIconManager; + +#endif //_KVI_ICONMANAGER_H_ diff --git a/src/kvirc/kernel/KviInternalCommand.cpp b/src/kvirc/kernel/KviInternalCommand.cpp new file mode 100644 index 000000000..e6769be15 --- /dev/null +++ b/src/kvirc/kernel/KviInternalCommand.cpp @@ -0,0 +1,83 @@ +//============================================================================= +// +// File : KviInternalCommand.cpp +// Creation date : Sun Aug 13 2000 19:22:45 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + +#define _KVI_INTERNALCMD_CPP_ + +#include "KviInternalCommand.h" + +// FIXME: #warning "LOCALIZE THIS!" + +static const char * internalCommandTable[KVI_NUM_INTERNAL_COMMANDS]= +{ + "echo INTERNAL COMMAND ERROR: INDEX OUT OF RANGE", + "help.open -n -m", + "help.open -n", + "about.kvirc", + "if($option(boolShowGeneralOptionsDialogAsToplevel))options.dialog -t; else options.dialog", + "codetester.open", + "socketspy.open", + "links.open", + "if($option(boolShowRegisteredUsersDialogAsToplevel))reguser.edit -t; else reguser.edit", + "trayicon.show", + "trayicon.hide", + "toolbareditor.open", + "aliaseditor.open", + "term.open -m", + "eventeditor.open", + "dirbrowser.open -m", + "dirbrowser.open", + "ident.start", + "ident.stop", + "tip.open", + "openurl http://www.kvirc.net", + "list.open", + "if($option(boolShowChannelsJoinDialogAsToplevel))channelsjoin.open -t;else channelsjoin.open", + "if($option(boolShowServersConnectDialogAsToplevel))options.edit -t KviIrcServerOptionsWidget;else options.edit KviIrcServerOptionsWidget", + "url.list", + "openurl http://www.kvirc.net/?id=themes", + "openurl http://www.kvirc.net/?id=mailinglist", + "openurl https://svn.kvirc.de/kvirc/wiki#Bugreportticket", + "raweditor.open", + "popupeditor.open", + "dialog.file(open,\"Select a Script File\"){ if(!$str.isEmpty($0))parse $0; }", + "actioneditor.open", + "quit", + "openurl http://www.kvirc.ru", + "openurl irc://freenode/kvirc", + "openurl irc://ircnet/kvirc", + "openurl irc://azzurra/kvirc.net", + "openurl http://kvirc-fr.info", + "openurl irc://freenode/kvirc-fr", + "openurl irc://irc.europnet.org/kvirc" +}; + + +const char * kvi_getInternalCommandBuffer(int idx) +{ + if(idx > 0 && idx < KVI_NUM_INTERNAL_COMMANDS) + { + return internalCommandTable[idx]; + } + return internalCommandTable[0]; +} diff --git a/src/kvirc/kernel/KviInternalCommand.h b/src/kvirc/kernel/KviInternalCommand.h new file mode 100644 index 000000000..b31ac6d3e --- /dev/null +++ b/src/kvirc/kernel/KviInternalCommand.h @@ -0,0 +1,74 @@ +#ifndef _KVI_INTERNALCMD_H_ +#define _KVI_INTERNALCMD_H_ +//============================================================================= +// +// File : KviInternalCommand.h +// Creation date : Sun Aug 13 2000 19:21:12 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" + +#define KVI_INTERNALCOMMAND_ECHO_INTERNALERROR 0 +#define KVI_INTERNALCOMMAND_HELP_NEWMDIWINDOW 1 +#define KVI_INTERNALCOMMAND_HELP_NEWSTATICWINDOW 2 +#define KVI_INTERNALCOMMAND_ABOUT_ABOUTKVIRC 3 +#define KVI_INTERNALCOMMAND_OPTIONS_DIALOG 4 +#define KVI_INTERNALCOMMAND_CODETESTER_OPEN 5 +#define KVI_INTERNALCOMMAND_SOCKETSPY_OPEN 6 +#define KVI_INTERNALCOMMAND_LINKS_OPEN 7 +#define KVI_INTERNALCOMMAND_REGUSER_EDIT 8 +#define KVI_INTERNALCOMMAND_TRAYICON_SHOW 9 +#define KVI_INTERNALCOMMAND_TRAYICON_HIDE 10 +#define KVI_INTERNALCOMMAND_TOOLBAREDITOR_OPEN 11 +#define KVI_INTERNALCOMMAND_ALIASEDITOR_OPEN 12 +#define KVI_INTERNALCOMMAND_TERM_OPEN 13 +#define KVI_INTERNALCOMMAND_EVENTEDITOR_OPEN 14 +#define KVI_INTERNALCOMMAND_BROWSER_OPEN_MDI 15 +#define KVI_INTERNALCOMMAND_BROWSER_OPEN 16 +#define KVI_INTERNALCOMMAND_IDENT_START 17 +#define KVI_INTERNALCOMMAND_IDENT_STOP 18 +#define KVI_INTERNALCOMMAND_TIP_OPEN 19 +#define KVI_INTERNALCOMMAND_KVIRC_HOMEPAGE 20 +#define KVI_INTERNALCOMMAND_LIST_OPEN 21 +#define KVI_INTERNALCOMMAND_CHANNELSJOIN_OPEN 22 +#define KVI_INTERNALCOMMAND_SERVERSJOIN_OPEN 23 +#define KVI_INTERNALCOMMAND_URL_OPEN 24 +#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_THEMES 25 +#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_MAILINGLIST 26 +#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_BUGTRACK 27 +#define KVI_INTERNALCOMMAND_RAWEDITOR_OPEN 28 +#define KVI_INTERNALCOMMAND_POPUPEDITOR_OPEN 29 +#define KVI_INTERNALCOMMAND_EXECUTE_SCRIPT_FROM_DISK 30 +#define KVI_INTERNALCOMMAND_ACTIONEDITOR_OPEN 31 +#define KVI_INTERNALCOMMAND_QUIT 32 +#define KVI_INTERNALCOMMAND_KVIRC_HOMEPAGE_RU 33 +#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_ON_FREENODE 34 +#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_ON_IRCNET 35 +#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_IT_ON_AZZURRA 36 +#define KVI_INTERNALCOMMAND_KVIRC_HOMEPAGE_FR 37 +#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_FR_ON_FREENODE 38 +#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_FR_ON_EUROPNET 39 + +#define KVI_NUM_INTERNAL_COMMANDS 40 + +extern KVIRC_API const char * kvi_getInternalCommandBuffer(int idx); + +#endif //_KVI_INTERNALCMD_H_ diff --git a/src/kvirc/kernel/KviIpcSentinel.cpp b/src/kvirc/kernel/KviIpcSentinel.cpp new file mode 100644 index 000000000..200ff747e --- /dev/null +++ b/src/kvirc/kernel/KviIpcSentinel.cpp @@ -0,0 +1,284 @@ +//============================================================================= +// +// File : KviIpcSentinel.hcpp +// Creation date : Tue Apr 10 2001 15:04:45 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2001-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 +#include "KviIpcSentinel.h" + + +#ifndef COMPILE_NO_IPC + + #include "KviMemory.h" + #include "KviApplication.h" + #include "KviQString.h" + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + + static HWND kvi_win_findIpcSentinel() + { + HWND hWnd = ::FindWindow("QWidget","[Non-Commercial] - kvirc4_ipc_sentinel"); + if(hWnd)return hWnd; + hWnd = ::FindWindow("QWidget","[Freeware] - kvirc4_ipc_sentinel"); + if(hWnd)return hWnd; + hWnd = ::FindWindow("QWidget","kvirc4_ipc_sentinel"); + return hWnd; + } + +#else + + #ifdef COMPILE_X11_SUPPORT + #include + + #include // for getuid + #include // for getuid + + //#include + #include + #define kvi_ipc_get_xdisplay QX11Info::display + #define kvi_ipc_get_xrootwin QX11Info::appRootWindow + + static Atom kvi_atom_ipc_sentinel_window; + static Atom kvi_atom_ipc_remote_command; + static Atom kvi_atom_ipc_remote_message; + static KviCString kvi_sentinel_id; + static bool g_bIpcAtomsLoaded = false; + + static void kvi_ipcLoadAtoms() + { + if(g_bIpcAtomsLoaded)return; + g_bIpcAtomsLoaded = true; + kvi_sentinel_id.sprintf("pane tonno e mistero - %d",getuid()); + kvi_atom_ipc_sentinel_window = XInternAtom(kvi_ipc_get_xdisplay(),"XA_KVI4_IPC_SENTINEL_WINDOW",False); + kvi_atom_ipc_remote_command = XInternAtom(kvi_ipc_get_xdisplay(),"XA_KVI4_IPC_REMOTE_COMMAND",False); + kvi_atom_ipc_remote_message = XInternAtom(kvi_ipc_get_xdisplay(),"XA_KVI4_IPC_REMOTE_MESSAGE",False); + } + + static void kvi_ipcSetRemoteCommand(Window w,const char * command) + { + XChangeProperty(kvi_ipc_get_xdisplay(),w,kvi_atom_ipc_remote_command, + XA_STRING,8,PropModeReplace,(const unsigned char *)command,kvi_strLen(command) + 1); + } + + static Window kvi_x11_findIpcSentinel(Window win) + { + Atom type; + int format; + unsigned long nItems,after; + unsigned char * data = 0; + if(XGetWindowProperty(kvi_ipc_get_xdisplay(),win,kvi_atom_ipc_sentinel_window,0,32,FALSE,XA_STRING, + &type,&format,&nItems,&after,&data) == Success) + { + if((type == XA_STRING) && (format == 8)) + { + if((nItems == ((unsigned long)(kvi_sentinel_id.len()))) && data) + { + if(kvi_strEqualCSN((const char *)data,kvi_sentinel_id.ptr(),kvi_sentinel_id.len())) + { + XFree((char *)data); + return win; + } + } + } + } + + Window root,parent; + Window * children; + unsigned int nChildren; + + if(!XQueryTree(kvi_ipc_get_xdisplay(),win,&root,&parent,&children,&nChildren)) + { + if(children)XFree((char *)children); + return 0; + } + + Window found = 0; + + for(int i=nChildren-1;(!found) && (i >= 0);i--) + found = kvi_x11_findIpcSentinel(children[i]); + + if(children)XFree((char *)children); + + return found; + } + #endif //!COMPILE_NO_X + +#endif + + + #define KVI_WINDOWS_IPC_MESSAGE 0x2FACE5 + + bool kvi_sendIpcMessage(const char * message) + { +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + + HWND hSentinel = kvi_win_findIpcSentinel(); + if(hSentinel != NULL) + { + COPYDATASTRUCT cpd; + cpd.cbData = strlen(message)+1; + cpd.dwData = KVI_WINDOWS_IPC_MESSAGE; + cpd.lpData = (void *)message; + DWORD dwResult; + //qDebug(message); +#if defined(COMPILE_ON_WINDOWS) && !(defined(MINGW)) + if(!::SendMessageTimeout(hSentinel,WM_COPYDATA,(WPARAM)NULL,(LPARAM)&cpd,SMTO_BLOCK,1000,(PDWORD_PTR)&dwResult)) +#else + if(!::SendMessageTimeout(hSentinel,WM_COPYDATA,(WPARAM)NULL,(LPARAM)&cpd,SMTO_BLOCK,1000,&dwResult)) +#endif + { + qDebug("Failed to send IPC message: error code 0x%x",::GetLastError()); + } + return true; + } +#else + #ifdef COMPILE_X11_SUPPORT + + kvi_ipcLoadAtoms(); + + Window sentinel = kvi_x11_findIpcSentinel(kvi_ipc_get_xrootwin()); + if(sentinel != 0) + { +// XChangeProperty(kvi_ipc_get_xdisplay(),sentinel,kvi_atom_ipc_remote_command,XA_STRING,8, +// PropModeReplace,(const unsigned char *)message,kvi_strLen(message)); + kvi_ipcSetRemoteCommand(sentinel,message); + + XEvent e; + KviMemory::set(&e,0,sizeof(XEvent)); + e.type = ClientMessage; + e.xclient.display = kvi_ipc_get_xdisplay(); + e.xclient.window = sentinel; + e.xclient.message_type = kvi_atom_ipc_remote_message; + e.xclient.format = 8; + + XSendEvent(kvi_ipc_get_xdisplay(),sentinel,False,0,&e); + + return true; + } + #endif //!COMPILE_NO_X +#endif + return false; + } + + + ////////////////////////////////////////////////////////////////////// + // class KviIpcSentinel + // + // hidden sentinel of ipc messages + // + ////////////////////////////////////////////////////////////////////// + + KviIpcSentinel::KviIpcSentinel() + : QWidget(0) + { + setObjectName("kvirc4_ipc_sentinel"); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + setWindowTitle("kvirc4_ipc_sentinel"); + setWindowFlags(Qt::FramelessWindowHint); +#else + #ifdef COMPILE_X11_SUPPORT + kvi_ipcLoadAtoms(); + + XChangeProperty(kvi_ipc_get_xdisplay(),winId(),kvi_atom_ipc_sentinel_window,XA_STRING,8, + PropModeReplace,(const unsigned char *)kvi_sentinel_id.ptr(),kvi_sentinel_id.len()); + + kvi_ipcSetRemoteCommand(winId(),""); + #endif //!COMPILE_NO_X +#endif + + move(-50,-50); + resize(1,1); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + // we need to show the window once otherwise it will never get "realized" + // and we will not be able to find it via FindWindow() + show(); +#endif + hide(); + + } + + KviIpcSentinel::~KviIpcSentinel() + { + } + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + + bool KviIpcSentinel::winEvent(MSG * msg, long * result) + { + if(msg->message == WM_COPYDATA) + { + COPYDATASTRUCT * cpd = (COPYDATASTRUCT *)msg->lParam; + if(cpd) + { + if(cpd->dwData == KVI_WINDOWS_IPC_MESSAGE) + { + qDebug((char *)(cpd->lpData)); + if(g_pApp) + g_pApp->ipcMessage((char *)(cpd->lpData)); + if(result) + *result = 0; + return true; + } + } + } + return false; + } + +#else + #ifdef COMPILE_X11_SUPPORT + bool KviIpcSentinel::x11Event(XEvent *e) + { + if(e->type == ClientMessage) + { + if((e->xclient.message_type = kvi_atom_ipc_remote_message) && (e->xclient.format == 8)) + { + Atom type; + int format; + unsigned long nItems,after; + unsigned char * data = 0; + KviCString szData; + if(XGetWindowProperty(kvi_ipc_get_xdisplay(),winId(),kvi_atom_ipc_remote_command,0,1024,FALSE,XA_STRING, + &type,&format,&nItems,&after,&data) == Success) + { + if((type == XA_STRING) && (format == 8) && (nItems > 0) && data) + { + szData = (char *)data; + XFree((char *)data); + } + } + kvi_ipcSetRemoteCommand(winId(),""); + + if(g_pApp)g_pApp->ipcMessage(szData.ptr()); + return true; + } + } + return false; + } + #endif //!COMPILE_NO_X +#endif + #ifndef COMPILE_USE_STANDALONE_MOC_SOURCES + #include "kvi_ipc.moc" + #endif //!COMPILE_USE_STANDALONE_MOC_SOURCES + +#endif diff --git a/src/kvirc/kernel/KviIpcSentinel.h b/src/kvirc/kernel/KviIpcSentinel.h new file mode 100644 index 000000000..4f0a1d0b9 --- /dev/null +++ b/src/kvirc/kernel/KviIpcSentinel.h @@ -0,0 +1,68 @@ +#ifndef _KVI_IPC_H_ +#define _KVI_IPC_H_ +//============================================================================= +// +// File : KviIpcSentinel.h +// Creation date : Tue Apr 10 2001 15:04:45 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2001-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" + + +#ifndef COMPILE_NO_IPC + + #include "KviCString.h" + + #include + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + #include + #include +#else + #ifdef COMPILE_X11_SUPPORT + #include + #include "KviXlib.h" // for XEvent + #endif //!COMPILE_X11_SUPPORT +#endif + + ////////////////////////////////////////////////////////////////////// + // class KviIpcSentinel + // + ////////////////////////////////////////////////////////////////////// + + class KVIRC_API KviIpcSentinel : public QWidget + { + Q_OBJECT + public: + KviIpcSentinel(); + ~KviIpcSentinel(); + protected: // protected members +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + virtual bool winEvent(MSG * msg, long * result); +#else + #ifdef COMPILE_X11_SUPPORT + virtual bool x11Event(XEvent *e); + #endif //!COMPILE_X11_SUPPORT +#endif + }; +#endif //!COMPILE_NO_IPC + +#endif //_KVI_IPC_H_ diff --git a/src/kvirc/kernel/KviIrcConnection.cpp b/src/kvirc/kernel/KviIrcConnection.cpp new file mode 100644 index 000000000..8c5862327 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnection.cpp @@ -0,0 +1,1745 @@ +//============================================================================= +// +// File : KviIrcConnection.cpp +// Creation date : Mon 03 May 2004 01:45:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnection.h" +#include "KviIrcConnectionTarget.h" +#include "KviIrcConnectionUserInfo.h" +#include "KviIrcConnectionServerInfo.h" +#include "KviIrcConnectionStateData.h" +#include "KviIrcConnectionAntiCtcpFloodData.h" +#include "KviIrcConnectionNetsplitDetectorData.h" +#include "KviIrcConnectionAsyncWhoisData.h" +#include "KviIrcConnectionRequestQueue.h" +#include "KviIrcConnectionStatistics.h" +#include "KviIrcConnectionUserInfo.h" +#include "KviIrcConnectionServerInfo.h" +#include "KviIrcLink.h" +#include "KviIrcSocket.h" +#include "KviLocale.h" +#include "KviIrcServerDataBase.h" +#include "KviProxyDataBase.h" +#include "KviError.h" +#include "kvi_out.h" +#include "KviOptions.h" +#include "KviConsoleWindow.h" +#include "KviNetUtils.h" +#include "KviInternalCommand.h" +#include "KviMainWindow.h" +#include "KviMexLinkFilter.h" +#include "KviMemory.h" +#include "KviMemory.h" +#include "kvi_debug.h" +#include "KviChannelWindow.h" +#include "KviQueryWindow.h" +#include "KviApplication.h" +#include "KviDataBuffer.h" +#include "KviNotifyList.h" +#include "KviDnsResolver.h" +#include "kvi_defaults.h" +#include "KviIrcServerParser.h" +#include "KviIrcDataStreamMonitor.h" +#include "KviDataBuffer.h" +#include "KviLagMeter.h" +#include "KviKvsEventTriggers.h" +#include "KviKvsScript.h" +#include "KviMircCntrl.h" +#include "KviUserIdentity.h" +#include "KviIdentityProfile.h" +#include "KviSASL.h" +#include "KviNickColors.h" + +#include +#include + +extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; +extern KVIRC_API KviProxyDataBase * g_pProxyDataBase; + +KviIrcConnection::KviIrcConnection(KviIrcContext * pContext,KviIrcConnectionTarget * pTarget,KviUserIdentity * pIdentity) +: QObject() +{ + m_bIdentdAttached = false; + m_pContext = pContext; + m_pConsole = pContext->console(); + m_pTarget = pTarget; + m_pUserIdentity = pIdentity; + m_pChannelList = new KviPointerList; + m_pChannelList->setAutoDelete(false); + m_pQueryList = new KviPointerList; + m_pQueryList->setAutoDelete(false); + m_pLink = new KviIrcLink(this); + m_pUserDataBase = new KviIrcUserDataBase(); + m_pUserInfo = new KviIrcConnectionUserInfo(); + m_pServerInfo = new KviIrcConnectionServerInfo(); + m_pStateData = new KviIrcConnectionStateData(); + m_pAntiCtcpFloodData = new KviIrcConnectionAntiCtcpFloodData(); + m_pNetsplitDetectorData = new KviIrcConnectionNetsplitDetectorData(); + m_pAsyncWhoisData = new KviIrcConnectionAsyncWhoisData(); + m_pStatistics = new KviIrcConnectionStatistics(); + m_pNotifyListTimer = 0; + m_pNotifyListManager = 0; + m_pLocalhostDns = 0; + m_pLagMeter = 0; + m_eState = Idle; + m_pRequestQueue = new KviIrcConnectionRequestQueue(); + setupSrvCodec(); + setupTextCodec(); +} + +KviIrcConnection::~KviIrcConnection() +{ + if(m_bIdentdAttached) + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); + + m_bIdentdAttached = false; + if(m_pLocalhostDns) + { + QObject::disconnect(m_pLocalhostDns,SIGNAL(lookupDone(KviDnsResolver *)),0,0); + if(m_pLocalhostDns->isRunning()) + { + m_pLocalhostDns->deleteLater(); + } else { + delete m_pLocalhostDns; + } + } + + + if(m_pNotifyListTimer) + { + delete m_pNotifyListTimer; + m_pNotifyListTimer = 0; + } + + if(m_pNotifyListManager) + { + delete m_pNotifyListManager; // destroy this before the userDb + m_pNotifyListManager = 0; + } + + if(m_pLagMeter) + { + delete m_pLagMeter; + m_pLagMeter = 0; + } + + delete m_pLink; // <-- this MAY trigger a linkTerminated() or something like this! + delete m_pChannelList; + delete m_pQueryList; + delete m_pTarget; + delete m_pUserDataBase; + delete m_pUserInfo; + delete m_pServerInfo; + delete m_pStateData; + delete m_pAntiCtcpFloodData; + delete m_pNetsplitDetectorData; + delete m_pAsyncWhoisData; + delete m_pStatistics; + delete m_pUserIdentity; + m_pRequestQueue->deleteLater(); +} + +void KviIrcConnection::clearOutputQueue(bool bPrivateMessagesOnly) +{ + m_pLink->clearOutputQueue(bPrivateMessagesOnly); +} + +void KviIrcConnection::setEncoding(const QString & szEncoding) +{ + QTextCodec * c = KviLocale::codecForName(szEncoding.toLatin1()); + if(c == m_pTextCodec) + return; + if(!c) + { + m_pConsole->output(KVI_OUT_SYSTEMERROR,__tr2qs("Failed to set the encoding to %Q: mapping not available."),&szEncoding); + return; + } + + QString szTmp = c->name(); + for(KviChannelWindow * ch = m_pChannelList->first(); ch; ch = m_pChannelList->next()) + { + if((ch->textCodec() != c) && (ch->textCodec() != ch->defaultTextCodec())) // actually not using the default! + { + ch->forceTextCodec(c); + if(_OUTPUT_VERBOSE) + ch->output(KVI_OUT_VERBOSE,__tr2qs("Changed text encoding to %Q"),&szTmp); + } + } + + for(KviQueryWindow * q = m_pQueryList->first(); q; q = m_pQueryList->next()) + { + if((q->textCodec() != c) && (q->textCodec() != q->defaultTextCodec())) // actually not using the default! + { + q->forceTextCodec(c); + if(_OUTPUT_VERBOSE) + q->output(KVI_OUT_VERBOSE,__tr2qs("Changed text encoding to %Q"),&szTmp); + } + } + m_pTextCodec = c; + m_pConsole->setTextEncoding(szEncoding); +} + +void KviIrcConnection::setupSrvCodec() +{ + // grab the codec: first look it up in the server data + m_pSrvCodec = 0; + if(!m_pTarget->server()->encoding().isEmpty()) + { + m_pSrvCodec = KviLocale::codecForName(m_pTarget->server()->encoding().toLatin1()); + if(!m_pSrvCodec) + qDebug("KviIrcConnection: can't find QTextCodec for encoding %s",m_pTarget->server()->encoding().toUtf8().data()); + } + + if(!m_pSrvCodec) + { + // try the network + if(!m_pTarget->network()->encoding().isEmpty()) + { + m_pSrvCodec = KviLocale::codecForName(m_pTarget->network()->encoding().toLatin1()); + if(!m_pSrvCodec) + qDebug("KviIrcConnection: can't find QTextCodec for encoding %s",m_pTarget->network()->encoding().toUtf8().data()); + } + } + + if(!m_pSrvCodec) + { + m_pSrvCodec = KviApplication::defaultSrvCodec(); + } + m_pConsole->setTextEncoding(QString(m_pSrvCodec->name())); +} + +void KviIrcConnection::setupTextCodec() +{ + // grab the codec: first look it up in the server data + m_pTextCodec = 0; + if(!m_pTarget->server()->textEncoding().isEmpty()) + { + m_pTextCodec = KviLocale::codecForName(m_pTarget->server()->textEncoding().toLatin1()); + if(!m_pTextCodec)qDebug("KviIrcConnection: can't find QTextCodec for encoding %s",m_pTarget->server()->textEncoding().toUtf8().data()); + } + + if(!m_pTextCodec) + { + // try the network + if(!m_pTarget->network()->textEncoding().isEmpty()) + { + m_pTextCodec = KviLocale::codecForName(m_pTarget->network()->textEncoding().toLatin1()); + if(!m_pTextCodec)qDebug("KviIrcConnection: can't find QTextCodec for encoding %s",m_pTarget->network()->textEncoding().toUtf8().data()); + } + } + + if(!m_pTextCodec) + { + m_pTextCodec = KviApplication::defaultTextCodec(); + } +} + +/* + * We're asking the connection itself to encode/decode text: use server specific encoding, + * instead of the "user text" encoding used in channels + */ +QByteArray KviIrcConnection::encodeText(const QString & szText) +{ + if(!m_pSrvCodec) + return szText.toUtf8(); + return m_pSrvCodec->fromUnicode(szText); +} + +QString KviIrcConnection::decodeText(const char * pcText) +{ + if(!m_pSrvCodec) + return QString(pcText); + return m_pSrvCodec->toUnicode(pcText); +} + +void KviIrcConnection::serverInfoReceived(const QString & szServerName, const QString & szUserModes, const QString & szChanModes) +{ + serverInfo()->setName(szServerName); + serverInfo()->setSupportedUserModes(szUserModes); + serverInfo()->setSupportedChannelModes(szChanModes); + m_pConsole->updateCaption(); // for server name + m_pConsole->frame()->childConnectionServerInfoChange(this); +} + +const QString & KviIrcConnection::currentNetworkName() +{ + //return m_pTarget->networkName(); + return m_pServerInfo->networkName(); +} + +void KviIrcConnection::abort() +{ + // this WILL trigger linkAttemptFailed() or linkTerminated() + m_pLink->abort(); +} + +void KviIrcConnection::start() +{ + m_eState = Connecting; + if(KVI_OPTION_BOOL(KviOption_boolUseIdentService) && KVI_OPTION_BOOL(KviOption_boolUseIdentServiceOnlyOnConnect)) + { + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_START); + m_bIdentdAttached=true; + } + m_pLink->start(); +} + +void KviIrcConnection::linkEstabilished() +{ + m_eState = Connected; + + // setup reasonable defaults before notifying anyone + m_pStatistics->setConnectionStartTime(kvi_unixTime()); + m_pStatistics->setLastMessageTime(kvi_unixTime()); + m_pServerInfo->setName(target()->server()->hostName()); + m_pServerInfo->setNetworkName(target()->network()->name()); + + // FIXME: With STARTTLS this is called TWICE! + if(KviPointerList * l = context()->monitorList()) + { + for(KviIrcDataStreamMonitor *m =l->first();m;m =l->next()) + m->connectionInitiated(); + } + + // FIXME: With STARTTLS this is called TWICE! + context()->connectionEstabilished(); + + // Ok...we're loggin in now + resolveLocalHost(); + + if(target()->server()->enabledCAP()) + { + /* + * HACK: this is needed to avoid timeouts connecting to server that does not + * support thye CAP extension (yet). Adding a somewhat broken message to a + * CAP LS request will force the server to output an error message. + * + * I'm currently aware of 2 methods: + * 1) using a broken nick (NICK -) to force a 437: ERR_UNAVAILRESOURCE + * 2) ping the server before registration to get a // 451: ERR_NOTREGISTERED + * + * Both method works, but the first method could compromise STARTTLS on some + * server that won't allow you to use tsl if the registration has already started + * + * Please note that irc bouncers are currently broken for this setup: eg. psyBNC + * will let the user login with a "-" (single dash) nickname or executing any + * invalid command without throwing any error at all. + * + * This MUST go as one network packet to avoid possible handshake problems + * on slow connections. + */ + + m_pStateData->setInsideInitialCapLs(true); + m_pStateData->setIgnoreOneYouHaveNotRegisteredError(true); + + // FIXME: The PING method does NOT work with bouncers. We need a timeout here. + + sendFmtData("CAP LS\r\nPING :%Q",&(target()->server()->hostName())); + } else { + loginToIrcServer(); + } +} + +void KviIrcConnection::handleInitialCapLs() +{ + if(!m_pStateData->isInsideInitialCapLs()) + return; // We shouldn't be here... + + m_pStateData->setInsideInitialCapLs(false); + + // STARTTLS support: this has to be checked first because it could imply + // a full cap renegotiation +#ifdef COMPILE_SSL_SUPPORT + if( + KVI_OPTION_BOOL(KviOption_boolUseStartTlsIfAvailable) && + (!link()->socket()->usingSSL()) && + target()->server()->enabledSTARTTLS() && + serverInfo()->supportedCaps().contains("tls",Qt::CaseInsensitive) + ) + { + trySTARTTLS(); // FIXME: Shouldn't we be able to STARTTLS even without CAP support ? + return; + } +#endif + + QString szRequests; + + //SASL + if(KVI_OPTION_BOOL(KviOption_boolUseSaslIfAvailable) && + target()->server()->enabledSASL() && + serverInfo()->supportedCaps().contains("sasl",Qt::CaseInsensitive) + ) + { + szRequests.append("sasl "); + } + +#if 0 + if(serverInfo()->supportedCaps().contains("multi-prefix",Qt::CaseInsensitive)) + { + szRequest.append("multi-prefix"); // NAMES supports this, WHO probably not yet + } +#endif + + //TODO MULTI-PREFIX, others goes here + + if(szRequests.isEmpty()) + { + endInitialCapNegotiation(); + } else { + sendFmtData("CAP REQ :%s",szRequests.trimmed().toUtf8().data()); + m_pStateData->setInsideInitialCapReq(true); + } +} + +void KviIrcConnection::handleInitialCapAck() +{ + if(!m_pStateData->isInsideInitialCapReq()) + return; // We shouldn't be here + + m_pStateData->setInsideInitialCapReq(false); + + bool bUsed=false; + + //SASL + if(KVI_OPTION_BOOL(KviOption_boolUseSaslIfAvailable) && + target()->server()->enabledSASL() && + m_pStateData->enabledCaps().contains("sasl",Qt::CaseInsensitive) + ) + { + m_pStateData->setInsideAuthenticate(true); + bUsed=true; + +#ifdef COMPILE_SSL_SUPPORT + sendFmtData("AUTHENTICATE DH-BLOWFISH"); +#else + sendFmtData("AUTHENTICATE PLAIN"); +#endif + } + + if(!bUsed) + endInitialCapNegotiation(); +} + +void KviIrcConnection::handleAuthenticate(KviCString & szAuth) +{ + //SASL + if(!m_pStateData->isInsideAuthenticate()) + return; + + QByteArray szNick = encodeText(target()->server()->saslNick()); + QByteArray szPass = encodeText(target()->server()->saslPass()); + if(szAuth=="+") + { + //PLAIN + KviCString szOut; + if(KviSASL::plainMethod(szAuth, + szOut, + szNick, + szPass + )) + { + sendFmtData("AUTHENTICATE %s",szOut.ptr()); + } else { + sendFmtData("AUTHENTICATE *"); + } + } else { + //DH-BLOWFISH sasl auth + KviCString szOut; + if(KviSASL::dh_blowfishMethod(szAuth, + szOut, + szNick, + szPass + )) + { + sendFmtData("AUTHENTICATE %s",szOut.ptr()); + } else { + sendFmtData("AUTHENTICATE *"); + } + } +} + +void KviIrcConnection::handleInitialCapNak() +{ + endInitialCapNegotiation(); +} + +void KviIrcConnection::endInitialCapNegotiation() +{ + m_pStateData->setInsideAuthenticate(false); + sendFmtData("CAP END"); + loginToIrcServer(); +} + +void KviIrcConnection::handleFailedInitialCapLs() +{ + m_pStateData->setInsideInitialCapLs(false); + loginToIrcServer(); +} + +void KviIrcConnection::linkTerminated() +{ + if(m_bIdentdAttached) + { + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); + m_bIdentdAttached=false; + } + m_eState = Idle; + + if(m_pNotifyListManager) + { + delete m_pNotifyListManager; + m_pNotifyListManager = 0; + } + + if(m_pLagMeter) + { + delete m_pLagMeter; + m_pLagMeter = 0; + } + + if(KviPointerList * l = context()->monitorList()) + { + for(KviIrcDataStreamMonitor *m =l->first();m;m =l->next()) + m->connectionTerminated(); + } + + // Prepare data for an eventual reconnect + context()->connectionTerminated(); +} + +void KviIrcConnection::linkAttemptFailed(int iError) +{ + if(m_bIdentdAttached) + { + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); + m_bIdentdAttached=false; + } + m_eState = Idle; + context()->connectionFailed(iError); +} + +KviChannelWindow * KviIrcConnection::findChannel(const QString & szName) +{ + for(KviChannelWindow * c = m_pChannelList->first(); c; c = m_pChannelList->next()) + { + if(KviQString::equalCI(szName,c->windowName())) + return c; + } + return 0; +} + +int KviIrcConnection::getCommonChannels(const QString & szNick, QString & szChansBuffer, bool bAddEscapeSequences) +{ + int iCount = 0; + for(KviChannelWindow * c = m_pChannelList->first(); c; c = m_pChannelList->next()) + { + if(c->isOn(szNick)) + { + if(!szChansBuffer.isEmpty()) + szChansBuffer.append(", "); + + char uFlag = c->getUserFlag(szNick); + if(uFlag) + { + KviQString::appendFormatted(szChansBuffer,bAddEscapeSequences ? "%c\r!c\r%Q\r" : "%c%Q",uFlag,&(c->windowName())); + } else { + if(bAddEscapeSequences) + KviQString::appendFormatted(szChansBuffer,"\r!c\r%Q\r",&(c->windowName())); + else szChansBuffer.append(c->windowName()); + } + iCount++; + } + } + return iCount; +} + +void KviIrcConnection::unhighlightAllChannels() +{ + for(KviChannelWindow * c = m_pChannelList->first(); c; c = m_pChannelList->next()) + c->unhighlight(); +} + +void KviIrcConnection::unhighlightAllQueries() +{ + for(KviQueryWindow * c = m_pQueryList->first(); c; c = m_pQueryList->next()) + c->unhighlight(); +} + +void KviIrcConnection::closeAllChannels() +{ + while(m_pChannelList->first()) + { + m_pChannelList->first()->close(); + QApplication::processEvents(QEventLoop::ExcludeSocketNotifiers & QEventLoop::ExcludeUserInputEvents); + } +} + +void KviIrcConnection::closeAllQueries() +{ + while(m_pQueryList->first()) + { + m_pQueryList->first()->close(); + QApplication::processEvents(QEventLoop::ExcludeSocketNotifiers & QEventLoop::ExcludeUserInputEvents); + } +} + +KviChannelWindow * KviIrcConnection::createChannel(const QString & szName) +{ + KviChannelWindow * c = m_pContext->findDeadChannel(szName); + if(c) + { + c->setAliveChan(); + if(!KVI_OPTION_BOOL(KviOption_boolCreateMinimizedChannels)) + { + c->raise(); + c->setFocus(); + } + } else { + c = new KviChannelWindow(m_pConsole->frame(),m_pConsole,szName); + m_pConsole->frame()->addWindow(c,!KVI_OPTION_BOOL(KviOption_boolCreateMinimizedChannels)); + + if(KVI_OPTION_BOOL(KviOption_boolPasteLastLogOnChannelJoin)) + c->pasteLastLog(); + } + return c; +} + +KviQueryWindow * KviIrcConnection::createQuery(const QString & szNick) +{ + KviQueryWindow * q = m_pContext->findDeadQuery(szNick); + if(!q) + { + q = findQuery(szNick); + if(q) + return q; // hm ? + } + if(q) + { + q->setAliveQuery(); + if(!KVI_OPTION_BOOL(KviOption_boolCreateMinimizedQuery)) + { + q->raise(); + q->setFocus(); + } + } else { + q = new KviQueryWindow(m_pConsole->frame(),m_pConsole,szNick); + m_pConsole->frame()->addWindow(q,!KVI_OPTION_BOOL(KviOption_boolCreateMinimizedQuery)); + } + return q; +} + +KviQueryWindow * KviIrcConnection::findQuery(const QString & szName) +{ + for(KviQueryWindow * c = m_pQueryList->first(); c; c = m_pQueryList->next()) + { + if(KviQString::equalCI(szName,c->windowName())) + return c; + } + return 0; +} + +void KviIrcConnection::registerChannel(KviChannelWindow * c) +{ + m_pChannelList->append(c); + if(KVI_OPTION_BOOL(KviOption_boolLogChannelHistory)) + g_pApp->addRecentChannel(c->windowName(),m_pServerInfo->networkName()); + emit(channelRegistered(c)); + emit(chanListChanged()); +} + +void KviIrcConnection::unregisterChannel(KviChannelWindow * c) +{ + m_pChannelList->removeRef(c); + requestQueue()->dequeueChannel(c); + emit(channelUnregistered(c)); + emit(chanListChanged()); +} + +void KviIrcConnection::registerQuery(KviQueryWindow * q) +{ + m_pQueryList->append(q); +} + +void KviIrcConnection::unregisterQuery(KviQueryWindow * q) +{ + if(m_pQueryList->removeRef(q)) + return; +} + +void KviIrcConnection::keepChannelsOpenAfterDisconnect() +{ + while(KviChannelWindow * c = m_pChannelList->first()) + { + c->outputNoFmt(KVI_OUT_SOCKETERROR,__tr2qs("Connection to server lost")); + c->setDeadChan(); + } +} + +void KviIrcConnection::keepQueriesOpenAfterDisconnect() +{ + while(KviQueryWindow * q = m_pQueryList->first()) + { + q->outputNoFmt(KVI_OUT_SOCKETERROR,__tr2qs("Connection to server lost")); + q->setDeadQuery(); + } +} + +void KviIrcConnection::resurrectDeadQueries() +{ + while(KviQueryWindow * q = m_pContext->firstDeadQuery()) + { + q->outputNoFmt(KVI_OUT_SOCKETMESSAGE,__tr2qs("Connection to server established")); + q->setAliveQuery(); + } +} + + +//=== Message send stuff ====================================================// +// Max buffer that can be sent to an IRC server is 512 bytes +// including CRLF. (ircd simply 'cuts' messages to 512 bytes +// and discards the remainig part) +// Note that 510 bytes of data is a reasonably long message :) +// +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 01234567890123456789012345678901234567890123456789 +// 0123456789\r\n +// +// We keep a list of data to send, and flush it as soon as we can. +// + +bool KviIrcConnection::sendFmtData(const char * pcFmt, ...) +{ + KviDataBuffer * pData = new KviDataBuffer(512); + kvi_va_list(list); + kvi_va_start(list,pcFmt); + bool bTruncated; + //sprintf the buffer up to 512 chars (adds a CRLF too) + int iLen = kvi_irc_vsnprintf((char *)(pData->data()),pcFmt,list,&bTruncated); + kvi_va_end(list); + + //adjust the buffer size + if(iLen < 512) + pData->resize(iLen); + + if(bTruncated) + { + if(!_OUTPUT_MUTE) + m_pConsole->outputNoFmt(KVI_OUT_SOCKETWARNING,__tr2qs("[LINK WARNING]: Socket message truncated to 512 bytes.")); + } + + QString szMsg = QString::fromLatin1((const char *)(pData->data()), iLen-2); + + // notify the monitors + if(KviPointerList * l = context()->monitorList()) + { + for(KviIrcDataStreamMonitor * m = l->first(); m; m = l->next()) + { + if(m->outgoingMessage(szMsg.toLatin1().data())) + return true; + } + } + + // Trigger OnOutboundTraffic event + KVS_TRIGGER_EVENT_1(KviEvent_OnOutboundTraffic,m_pConsole->activeWindow(),szMsg); + + return m_pLink->sendPacket(pData); +} + +bool KviIrcConnection::sendData(const char * pcBuffer, int iBuflen) +{ + if(iBuflen < 0) + iBuflen = (int)strlen(pcBuffer); + if(iBuflen > 510) + { + iBuflen = 510; + if(!_OUTPUT_MUTE) + m_pConsole->outputNoFmt(KVI_OUT_SOCKETWARNING,__tr2qs("[LINK WARNING]: Socket message truncated to 512 bytes.")); + } + + KviDataBuffer * pData = new KviDataBuffer(iBuflen + 2); + KviMemory::move(pData->data(),pcBuffer,iBuflen); + *(pData->data() + iBuflen) = '\r'; + *(pData->data() + iBuflen + 1) = '\n'; + + QString szMsg = (const char *)(pData->data()); + szMsg.truncate(iBuflen); + + // notify the monitors + if(KviPointerList * l = context()->monitorList()) + { + for(KviIrcDataStreamMonitor * m = l->first(); m; m = l->next()) + { + if(m->outgoingMessage(szMsg.toUtf8().data())) + return true; + } + } + + // Trigger OnOutboundTraffic event + KVS_TRIGGER_EVENT_1(KviEvent_OnOutboundTraffic,m_pConsole->activeWindow(),szMsg); + + return m_pLink->sendPacket(pData); +} + +//============================================================================================== +// notify list management +//============================================================================================== + +void KviIrcConnection::delayedStartNotifyList() +{ + KVI_ASSERT(!m_pNotifyListTimer); + + if(m_pNotifyListTimer) + delete m_pNotifyListTimer; + + m_pNotifyListTimer = new QTimer(); + m_pNotifyListTimer->setInterval(15000); + m_pNotifyListTimer->setSingleShot(true); + m_pNotifyListTimer->start(); + connect(m_pNotifyListTimer,SIGNAL(timeout()),this,SLOT(restartNotifyList())); + + // This delay is large enough to fire after the MOTD has been sent, + // even on the weirdest network. + // If there is no MOTD, this timer will fire after 15 secs, + // If there is a MOTD, restartNotifyList() will be triggered by RPL_ENDOFMOTD and + // will kill the timer before it has fired. +} + +void KviIrcConnection::endOfMotdReceived() +{ + // if the timer is still there running then just + if(m_pNotifyListTimer) + restartNotifyList(); +} + +void KviIrcConnection::restartNotifyList() +{ + if(m_pNotifyListTimer) + { + delete m_pNotifyListTimer; + m_pNotifyListTimer = 0; + } + + // clear it + if(m_pNotifyListManager) + { + m_pNotifyListManager->stop(); // may need to remove watch entries + delete m_pNotifyListManager; + m_pNotifyListManager = 0; + } + + if(!KVI_OPTION_BOOL(KviOption_boolUseNotifyList)) + return; + + if(serverInfo()->supportsWatchList() && KVI_OPTION_BOOL(KviOption_boolUseWatchListIfAvailable)) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("The server seems to support the WATCH notify list method, will try to use it")); + m_pNotifyListManager = new KviWatchNotifyListManager(this); + } else { + if(KVI_OPTION_BOOL(KviOption_boolUseIntelligentNotifyListManager)) + { + m_pNotifyListManager = new KviIsOnNotifyListManager(this); + } else { + m_pNotifyListManager = new KviStupidNotifyListManager(this); + } + } + m_pNotifyListManager->start(); +} + +void KviIrcConnection::restartLagMeter() +{ + if(m_pLagMeter) + { + delete m_pLagMeter; + m_pLagMeter = 0; + } + if(!KVI_OPTION_BOOL(KviOption_boolUseLagMeterEngine)) + return; + m_pLagMeter = new KviLagMeter(this); +} + +void KviIrcConnection::resolveLocalHost() +{ + QString szIp; + + if(!link()->socket()->getLocalHostIp(szIp,target()->server()->isIPv6())) + { + bool bGotIp = false; + if(!KVI_OPTION_STRING(KviOption_stringLocalHostIp).isEmpty()) + { +#ifdef COMPILE_IPV6_SUPPORT + if(target()->server()->isIPv6()) + { + if(KviNetUtils::isValidStringIPv6(KVI_OPTION_STRING(KviOption_stringLocalHostIp))) + bGotIp = true; + } else { +#endif + if(KviNetUtils::isValidStringIp(KVI_OPTION_STRING(KviOption_stringLocalHostIp))) + bGotIp = true; +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + } + + if(bGotIp) + { + m_pUserInfo->setLocalHostIp(KVI_OPTION_STRING(KviOption_stringLocalHostIp)); + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Can't resolve local host address, using user supplied one (%Q)"), + &(m_pUserInfo->localHostIp())); + + } else { + // FIXME : Maybe check for IPv6 here too ? + m_pUserInfo->setLocalHostIp("127.0.0.1"); + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Can't resolve local host address, using default 127.0.0.1"), + &(m_pUserInfo->localHostIp())); + } + } else { + m_pUserInfo->setLocalHostIp(szIp); + if(!_OUTPUT_QUIET) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Local host address is %Q"), + &(m_pUserInfo->localHostIp())); + } + + // For now this is the only we know + m_pUserInfo->setHostName(m_pUserInfo->localHostIp()); + m_pUserInfo->setHostIp(m_pUserInfo->localHostIp()); +} + +void KviIrcConnection::changeAwayState(bool bAway) +{ + if(bAway) + m_pUserInfo->setAway(); + else m_pUserInfo->setBack(); + + m_pConsole->updateCaption(); + m_pConsole->frame()->childConnectionAwayStateChange(this); + + emit awayStateChanged(); +} + +void KviIrcConnection::userInfoReceived(const QString & szUserName, const QString & szHostName) +{ + userInfo()->setUserName(szUserName); + QString szUnmaskedHost = m_pUserInfo->unmaskedHostName(); + // Update the user entry + KviIrcUserEntry * e = userDataBase()->find(userInfo()->nickName()); + if(e) // should be there! (we have the permanent entry in the notify list view) + { + e->setUser(szUserName); + if(!szHostName.isEmpty())e->setHost(szHostName); + } // else buuug + + if(szHostName.isEmpty()) + return; // nothing to do anyway + + if(KviQString::equalCS(m_pUserInfo->hostName(),szHostName)) + return; // again nothing to do + + static bool warned_once = false; + + if(!warned_once) + { + if(!(m_pUserInfo->hostName().isEmpty() || KviQString::equalCS(m_pUserInfo->hostName(),m_pUserInfo->localHostIp()))) + { + // ok, something weird is probably going on + // is is non-empty and it is NOT the IP address we have set + // at connection startup... + // ...the server (or more likely the bouncer) must have changed his mind... + if(!_OUTPUT_MUTE) + { + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("The server reports a hostname differing from what KVIrc set for the local hostname.")); + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("This can happen if you use a broken bouncer, the IRC server masks your IP/Hostname or something weird is happening on the IRC server.")); + } + warned_once = true; + } + } + + // set it + m_pUserInfo->setHostName(szHostName); + + bool bChangeIp = true; + + // if we don't have any routable IP yet, then it is worth to lookup the new hostname + +#ifdef COMPILE_IPV6_SUPPORT + if((KviNetUtils::isValidStringIp(m_pUserInfo->hostIp()) && + KviNetUtils::isRoutableIpString(m_pUserInfo->hostIp())) || + KviNetUtils::isValidStringIPv6(m_pUserInfo->hostIp())) +#else + if((KviNetUtils::isValidStringIp(m_pUserInfo->hostIp()) && + KviNetUtils::isRoutableIpString(m_pUserInfo->hostIp()))) +#endif + { + if(KVI_OPTION_BOOL(KviOption_boolDccGuessIpFromServerWhenLocalIsUnroutable) && + KVI_OPTION_BOOL(KviOption_boolDccBrokenBouncerHack)) + { + if(!_OUTPUT_MUTE) + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Here goes your \"broken bouncer hack\": The server has changed the hostname but I'll ignore the IP address change")); + bChangeIp = false; + } + } + + if(bChangeIp) + { + // lookup the new hostname then... +#ifdef COMPILE_IPV6_SUPPORT + if(KviNetUtils::isValidStringIp(szHostName) || KviNetUtils::isValidStringIPv6(szHostName)) +#else + if(KviNetUtils::isValidStringIp(szHostName)) +#endif + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("The local IP address as seen by the IRC server is %Q"),&szHostName); + m_pUserInfo->setHostIp(szHostName); + } else +#ifdef COMPILE_IPV6_SUPPORT + if(KviNetUtils::isValidStringIp(szUnmaskedHost) || KviNetUtils::isValidStringIPv6(szUnmaskedHost)) +#else + if(KviNetUtils::isValidStringIp(szUnmaskedHost)) +#endif + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("The local IP address as seen by the IRC server is %Q"),&szUnmaskedHost); + m_pUserInfo->setHostIp(szUnmaskedHost); + + } else { + // look it up too + if(m_pLocalhostDns) + delete m_pLocalhostDns; // it could be only another local host lookup + m_pLocalhostDns = new KviDnsResolver(); + connect(m_pLocalhostDns,SIGNAL(lookupDone(KviDnsResolver *)),this,SLOT(hostNameLookupTerminated(KviDnsResolver *))); + + if(!m_pLocalhostDns->lookup(szHostName,KviDnsResolver::Any)) + { + if(!_OUTPUT_MUTE) + { + // don't change the string to aid the translators + QString szTmp = __tr2qs("Can't start the DNS slave thread"); + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Unable to resolve the local hostname as seen by the IRC server: %Q"),&szTmp); + } + delete m_pLocalhostDns; + m_pLocalhostDns = 0; + } else { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Looking up the local hostname as seen by the IRC server (%Q)"),&szHostName); + } + } + } +} + +void KviIrcConnection::hostNameLookupTerminated(KviDnsResolver *) +{ + if(!m_pLocalhostDns) + { + qDebug("Something weird is happening: pDns != 0 but m_pLocalhostDns == 0 :/"); + return; + } + + if(m_pLocalhostDns->state() != KviDnsResolver::Success) + { + QString szErr = KviError::getDescription(m_pLocalhostDns->error()); + if(!m_pUserInfo->hostIp().isEmpty()) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Unable to resolve the local hostname as seen by the IRC server: %Q, using previously resolved %Q"), + &szErr,&(m_pUserInfo->hostIp())); + else + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Unable to resolve the local hostname as seen by the IRC server: %Q"), + &szErr); + } else { + QString szIpAddr = m_pLocalhostDns->firstIpAddress(); + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Local hostname as seen by the IRC server resolved to %Q"),&szIpAddr); + m_pUserInfo->setHostIp(m_pLocalhostDns->firstIpAddress()); + } + + delete m_pLocalhostDns; + m_pLocalhostDns = 0; +} + +#ifdef COMPILE_SSL_SUPPORT +void KviIrcConnection::trySTARTTLS() +{ + // Check if the server supports STARTTLS protocol and we want to + // connect through it + //qDebug("Sending STARTTLS command..."); + if(!sendFmtData("STARTTLS")) + { + // Cannot send command + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Impossible to send STARTTLS command to the IRC server. Your connection will NOT be encrypted")); + return; + } + m_pStateData->setSentStartTls(); +} + +void KviIrcConnection::enableStartTlsSupport(bool bEnable) +{ + if(bEnable) + { + // Ok, the server supports STARTTLS protocol + // ssl handshake e switch del socket + //qDebug("Starting SSL handshake..."); + link()->socket()->enterSSLMode(); // FIXME: this should be forwarded through KviIrcLink, probably + } else { + // The server does not support STARTTLS + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("The server does not support STARTTLS command. Your connection will NOT be encrypted")); + } +} +#endif // COMPILE_SSL_SUPPORT + +void KviIrcConnection::useRealName(const QString &szRealName) +{ + // Evaluate functions in the real name (so we can have $version() inside) + + QString szRealNameBuffer = szRealName; + + if(!szRealNameBuffer.isEmpty()) + { + KviQString::escapeKvs(&szRealNameBuffer, KviQString::PermitVariables | KviQString::PermitFunctions); + + KviKvsVariant vRet; + if(KviKvsScript::evaluate(szRealNameBuffer,console(),0,&vRet)) + vRet.asString(szRealNameBuffer); + } + + m_pUserInfo->setRealName(szRealNameBuffer); +} + +void KviIrcConnection::useProfileData(KviIdentityProfileSet * pSet, const QString & szNetwork) +{ + KviIdentityProfile * pProfile = pSet->findNetwork(szNetwork); + if(!pProfile) return; + + // Update connection data + m_pUserInfo->setNickName(pProfile->nick()); + m_pUserInfo->setUserName(pProfile->userName()); + useRealName(pProfile->realName()); +} + +void KviIrcConnection::loginToIrcServer() +{ + KviIrcServer * pServer = target()->server(); + KviIrcNetwork * pNet = target()->network(); + + // For now this is the only we know + m_pServerInfo->setName(pServer->m_szHostname); + + QString szTmpNick, szTmpUser, szTmpPass, szTmpName; + // Username + szTmpUser = pServer->m_szUser.trimmed(); + if(!szTmpUser.isEmpty()) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using server specific username (%Q)"),&(szTmpUser)); + } else { + szTmpUser = pNet->userName().trimmed(); + if(!szTmpUser.isEmpty()) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using network specific username (%Q)"),&(szTmpUser)); + } else { + szTmpUser = KVI_OPTION_STRING(KviOption_stringUsername).trimmed(); + if(szTmpUser.isEmpty()) + szTmpUser = KVI_DEFAULT_USERNAME; + } + } + + m_pUserInfo->setUserName(szTmpUser); + + // Nick + if(pServer->m_pReconnectInfo) + { + szTmpNick=pServer->m_pReconnectInfo->m_szNick; + } + + if(!szTmpNick.isEmpty()) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using connection specific nickname (%Q)"),&(szTmpNick)); + m_pStateData->setLoginNickIndex(0); + } else { + szTmpNick = pServer->m_szNick.trimmed(); + if(!szTmpNick.isEmpty()) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using server specific nickname (%Q)"),&(szTmpNick)); + m_pStateData->setLoginNickIndex(0); + } else { + szTmpNick = pNet->nickName().trimmed(); + if(!szTmpNick.isEmpty()) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using network specific nickname (%Q)"),&(szTmpNick)); + m_pStateData->setLoginNickIndex(0); + } else { + szTmpNick = KVI_OPTION_STRING(KviOption_stringNickname1).trimmed(); + if(szTmpNick.isEmpty()) + { + szTmpNick = KVI_OPTION_STRING(KviOption_stringNickname1) = KVI_DEFAULT_NICKNAME1; + } + m_pStateData->setLoginNickIndex(1); + } + } + } + + m_pUserInfo->setNickName(szTmpNick); + + // Real name + szTmpName=pServer->m_szRealName.trimmed(); + if(!szTmpName.isEmpty()) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using server specific real name (%Q)"),&(szTmpName)); + } else { + szTmpName=pNet->realName().trimmed(); + if(!szTmpName.isEmpty()) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using network specific real name (%Q)"),&(szTmpName)); + } else { + szTmpName=KVI_OPTION_STRING(KviOption_stringRealname); + } + } + + useRealName(szTmpName); + + // Pass + if(pServer->m_pReconnectInfo) + { + szTmpPass=pServer->m_pReconnectInfo->m_szPass; + } + + if(!szTmpPass.isEmpty()) + { + if(!_OUTPUT_MUTE) + { + QString szHidden = QString(szTmpPass.length(), QChar('*')); + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using connection specific password (%Q)"),&(szHidden)); + } + } else { + szTmpPass = pServer->m_szPass.trimmed(); + if(!szTmpPass.isEmpty()) + { + if(!_OUTPUT_MUTE) + { + QString szHidden = QString(szTmpPass.length(), QChar('*')); + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using server specific password (%Q)"),&(szHidden)); + } + } else { + szTmpPass = pNet->password().trimmed(); + if(!szTmpPass.isEmpty()) + { + if(!_OUTPUT_MUTE) + { + QString szHidden = QString(szTmpPass.length(), QChar('*')); + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using network specific password (%Q)"),&(szHidden)); + } + } + } + } + + m_pUserInfo->setPassword(szTmpPass); + + // Check for identity profiles + KviIdentityProfileSet * pSet = KviIdentityProfileSet::instance(); + bool bProfilesEnabled = pSet ? (pSet->isEnabled() && !pSet->isEmpty()) : false; + if(bProfilesEnabled) useProfileData(pSet,pNet->name()); + + // FIXME: The server's encoding! + setupTextCodec(); + QByteArray szNick = encodeText(m_pUserInfo->nickName()); // never empty + QByteArray szUser = encodeText(m_pUserInfo->userName()); // never empty + QByteArray szReal = encodeText(m_pUserInfo->realName()); // may be empty + QByteArray szPass = encodeText(m_pUserInfo->password()); // may be empty + + if(!szReal.data())szReal = ""; + if(!szPass.data())szReal = ""; + + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Logging in as %Q!%Q :%Q"), + &(m_pUserInfo->nickName()),&(m_pUserInfo->userName()),&(m_pUserInfo->realName())); + + // spity, 27.03.2005: follow the RFC2812 suggested order for connection registration + // first the PASS, then NICK and then USER + + // The pass ? + if(!m_pUserInfo->password().isEmpty()) + { + if(!sendFmtData("PASS :%s",szPass.data())) + { + // disconnected in the meantime + return; + } + } + + if(!sendFmtData("NICK %s",szNick.data())) + { + // disconnected :( + return; + } + + unsigned int iGenderAvatarTag=0; + + if(KVI_OPTION_BOOL(KviOption_boolPrependGenderInfoToRealname) && !KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).isEmpty()) + { + if(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).startsWith("m",Qt::CaseInsensitive)) + { + iGenderAvatarTag|=1; + } else if(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).startsWith("f",Qt::CaseInsensitive)) + { + iGenderAvatarTag|=2; + } + } + + if(KVI_OPTION_BOOL(KviOption_boolPrependAvatarInfoToRealname) && !KVI_OPTION_STRING(KviOption_stringMyAvatar).isEmpty()) + { + iGenderAvatarTag|=4; + } + + if(KVI_OPTION_BOOL(KviOption_boolPrependNickColorInfoToRealname) && + KVI_OPTION_BOOL(KviOption_boolUseSpecifiedSmartColorForOwnNick)) + { + QString szTags; + szTags.sprintf("%c%d,%d%c", + KVI_TEXT_COLOR, + KVI_OPTION_UINT(KviOption_uintUserIrcViewOwnForeground), + KVI_OPTION_UINT(KviOption_uintUserIrcViewOwnBackground), + KVI_TEXT_RESET); + szReal.prepend(KviQString::toUtf8(szTags)); + } + + if(iGenderAvatarTag!=0) + { + QString szTags; + szTags.sprintf("%c%d%c", + KVI_TEXT_COLOR, + iGenderAvatarTag, + KVI_TEXT_RESET); + szReal.prepend(KviQString::toUtf8(szTags)); + } + + if(!sendFmtData("USER %s 0 %s :%s",szUser.data(), + KviQString::toUtf8(pServer->m_szHostname).data(),szReal.data())) + { + // disconnected in the meantime! + return; + } + + // permanent info in the user database + m_pConsole->notifyListView()->join(m_pUserInfo->nickName(),"*","*"); + + // set own avatar if we have it + KviIrcUserEntry * e = userDataBase()->find(userInfo()->nickName()); + if(e) // should be there! + { + if(!e->avatar()) + { + KviAvatar * av = m_pConsole->defaultAvatarFromOptions(); + if(av) + { + e->setAvatar(av); + m_pConsole->notifyListView()->avatarChanged(userInfo()->nickName()); + } + } + } // else buuug + + if(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).startsWith("m",Qt::CaseInsensitive)){ + e->setGender(KviIrcUserEntry::Male); + } else if(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).startsWith("f",Qt::CaseInsensitive)){ + e->setGender(KviIrcUserEntry::Female); + } + + // on connect stuff ? + + QString szTmp = pNet->onConnectCommand().trimmed(); + if(!szTmp.isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled network specific \"on connect\" commands")); + KviKvsScript::run(szTmp,m_pConsole); + } + + szTmp = pServer->onConnectCommand().trimmed(); + if(!szTmp.isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled server specific \"on connect\" commands")); + KviKvsScript::run(szTmp,m_pConsole); + } + + szTmp = m_pUserIdentity->onConnectCommand().trimmed(); + if(!szTmp.isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled identity specific \"on connect\" commands")); + KviKvsScript::run(szTmp,m_pConsole); + } + + // and wait for the server to agree... +} + +void KviIrcConnection::nickChange(const QString & szNewNick) +{ + // FIXME: should the new nickname be decoded in some way ? + m_pConsole->notifyListView()->nickChange(m_pUserInfo->nickName(),szNewNick); + m_pUserInfo->setNickName(szNewNick); + m_pConsole->output(KVI_OUT_NICK,__tr2qs("You have changed your nickname to %Q"),&szNewNick); + m_pConsole->updateCaption(); + m_pConsole->frame()->childConnectionNickNameChange(this); + emit nickNameChanged(); + g_pApp->addRecentNickname(szNewNick); +} + +bool KviIrcConnection::changeUserMode(char cMode, bool bSet) +{ + if(bSet) + { + if(m_pUserInfo->hasUserMode(cMode)) + return false; + m_pUserInfo->addUserMode(cMode); + } else { + if(!m_pUserInfo->hasUserMode(cMode)) + return false; + m_pUserInfo->removeUserMode(cMode); + } + m_pConsole->updateCaption(); + console()->frame()->childConnectionUserModeChange(this); + emit userModeChanged(); + return true; +} + +void KviIrcConnection::loginComplete(const QString & szNickName) +{ + if(context()->state() == KviIrcContext::Connected) + return; + + // Stop ignoring ERR_NOTREGISTERED errors. This is related to the initial CAP LS message. + // Well.. we should already have stopped ignoring the errors as we should have received + // the one we expected (because of the PING after CAP LS). Moreover the server shouldn't + // be sending these messages after the login has been completed. + // ...but to be on the safe side we just disable the special handling here. + m_pStateData->setIgnoreOneYouHaveNotRegisteredError(false); + + context()->loginComplete(); + + if(m_bIdentdAttached) + { + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); + m_bIdentdAttached = false; + } + + if(szNickName != m_pUserInfo->nickName()) + { + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("The server refused the suggested nickname (%s) and named you %s instead"),m_pUserInfo->nickName().toUtf8().data(),szNickName.toUtf8().data()); + m_pConsole->notifyListView()->nickChange(m_pUserInfo->nickName(),szNickName); + m_pUserInfo->setNickName(szNickName); + } + + g_pApp->addRecentNickname(szNickName); + + bool bHaltOutput = false; + bHaltOutput = KVS_TRIGGER_EVENT_0_HALTED(KviEvent_OnIRC,m_pConsole); + + if(!bHaltOutput) + m_pConsole->outputNoFmt(KVI_OUT_IRC,__tr2qs("Login operations complete, happy ircing!")); + + resurrectDeadQueries(); + + // on connect stuff ? + QString szTmp = target()->network()->onLoginCommand().trimmed(); + if(!szTmp.isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled network specific \"on login\" commands")); + KviKvsScript::run(szTmp,m_pConsole); + } + + szTmp = target()->server()->onLoginCommand().trimmed(); + if(!szTmp.isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled server specific \"on login\" commands")); + KviKvsScript::run(szTmp,m_pConsole); + } + + szTmp = m_pUserIdentity->onLoginCommand().trimmed(); + if(!szTmp.isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled identity specific \"on login\" commands")); + KviKvsScript::run(szTmp,m_pConsole); + } + + // Set the configured umode + QString szModeStr = target()->server()->initUMode(); + + if(szModeStr.isEmpty()) + szModeStr = KVI_OPTION_STRING(KviOption_stringDefaultUserMode); + + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Setting configured user mode")); + sendFmtData("MODE %s +%s",encodeText(m_pUserInfo->nickName()).data(),encodeText(szModeStr).data()); + + delayedStartNotifyList(); + restartLagMeter(); + + if(KVI_OPTION_BOOL(KviOption_boolShowChannelsJoinOnIrc)) + m_pConsole->frame()->executeInternalCommand(KVI_INTERNALCOMMAND_CHANNELSJOIN_OPEN); + + + // join saved channels + + // FIXME: It should be possible to delay the channel join process after identification + // (or maybe just delay by a fixed amount ?) + // (or maybe retry joining after a while ?) + + QString szChannels,szProtectedChannels,szPasswords,szCurPass,szCurChan; + + if(!(m_pStateData->commandToExecAfterConnect().isEmpty())) + { + KviCString tmp = m_pStateData->commandToExecAfterConnect(); + KviKvsScript::run(tmp.ptr(),m_pConsole); + } + + bool bJoinStdChannels=true; + + if(target()->server()->m_pReconnectInfo) + { + if(!target()->server()->m_pReconnectInfo->m_szJoinChannels.isEmpty()) + { + bJoinStdChannels=false; + sendFmtData("JOIN %s",encodeText(target()->server()->m_pReconnectInfo->m_szJoinChannels).data()); + } + + KviQueryWindow * pQuery; + + for(QStringList::Iterator it = target()->server()->m_pReconnectInfo->m_szOpenQueryes.begin(); + it != target()->server()->m_pReconnectInfo->m_szOpenQueryes.end();it++) + { + QString szNick = *it; + pQuery = findQuery(szNick); + if(!pQuery) + { + pQuery = createQuery(szNick); + QString szUser; + QString szHost; + + KviIrcUserDataBase * db = userDataBase(); + if(db) + { + KviIrcUserEntry * e = db->find(szNick); + if(e) + { + szUser = e->user(); + szHost = e->host(); + } + } + pQuery->setTarget(szNick,szUser,szHost); + } + pQuery->autoRaise(); + pQuery->setFocus(); + } + delete target()->server()->m_pReconnectInfo; + target()->server()->m_pReconnectInfo=0; + } + + if(bJoinStdChannels) + { + if(target()->network()->autoJoinChannelList()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Auto-joining network specific channels")); + + QStringList * l = target()->network()->autoJoinChannelList(); + for(QStringList::Iterator it = l->begin(); it != l->end(); ++it) + { + szCurPass=(*it).section(':',1); + szCurChan = (*it).section(':',0,0); + if(szCurChan.isEmpty()) + continue; + if(szCurPass.isEmpty()) + { + if(!szChannels.isEmpty()) + szChannels.append(","); + if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!' || szCurChan[0]=='+')) + szCurChan.prepend('#'); + szChannels.append(szCurChan); + } else { + if(!szProtectedChannels.isEmpty()) + szProtectedChannels.append(","); + if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!' || szCurChan[0]=='+')) + szCurChan.prepend('#'); + szProtectedChannels.append(szCurChan); + if(!szPasswords.isEmpty()) + szPasswords.append(","); + szPasswords.append(szCurPass); + } + } + } + + if(target()->server()->autoJoinChannelList()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Auto-joining server specific channels")); + + QStringList * l = target()->server()->autoJoinChannelList(); + for(QStringList::Iterator it = l->begin(); it != l->end(); ++it) + { + szCurPass=(*it).section(':',1); + szCurChan = (*it).section(':',0,0); + if(szCurChan.isEmpty()) + continue; + if(szCurPass.isEmpty()) + { + if(!szChannels.isEmpty()) + szChannels.append(","); + if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!' || szCurChan[0]=='+')) + szCurChan.prepend('#'); + szChannels.append(szCurChan); + } else { + if(!szProtectedChannels.isEmpty()) + szProtectedChannels.append(","); + if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!' || szCurChan[0]=='+')) + szCurChan.prepend('#'); + szProtectedChannels.append(szCurChan); + if(!szPasswords.isEmpty()) + szPasswords.append(","); + szPasswords.append(szCurPass); + } + } + } + + QString szCommand; + if( (!szChannels.isEmpty()) || (!szProtectedChannels.isEmpty()) ) + { + szCommand.append(szProtectedChannels); + if(!szProtectedChannels.isEmpty() && !szChannels.isEmpty()) + szCommand.append(','); + szCommand.append(szChannels); + szCommand.append(" "); + szCommand.append(szPasswords); + + sendFmtData("JOIN %s",encodeText(szCommand).data()); + } + } + // minimize after connect + if(KVI_OPTION_BOOL(KviOption_boolMinimizeConsoleAfterConnect)) + m_pConsole->minimize(); +} + +void KviIrcConnection::incomingMessage(const char * pcMessage) +{ + // A message has arrived from the current server + // First of all, notify the monitors + if(KviPointerList * l = context()->monitorList()) + { + for(KviIrcDataStreamMonitor * m = l->first(); m; m = l->next()) + { + if(m->incomingMessage(pcMessage)) + return; + } + } + // set the last message time + m_pStatistics->setLastMessageTime(kvi_unixTime()); + // and pass it to the server parser for processing + g_pServerParser->parseMessage(pcMessage,this); +} + +void KviIrcConnection::incomingMessageNoFilter(const char * pcMessage) +{ + // set the last message time + m_pStatistics->setLastMessageTime(kvi_unixTime()); + // and pass it to the server parser for processing + g_pServerParser->parseMessage(pcMessage,this); +} + +void KviIrcConnection::heartbeat(kvi_time_t tNow) +{ + if(m_eState == Connected) + { + if(KVI_OPTION_BOOL(KviOption_boolEnableAwayListUpdates)) + { + // update the channel WHO lists (fixes users away state) + // first of all, we send our request not more often than every 50 secs + if((tNow - stateData()->lastSentChannelWhoRequest()) > 50) + { + // we also make sure that the last sent request is older than + // the last received reply + if(stateData()->lastSentChannelWhoRequest() <= stateData()->lastReceivedChannelWhoReply()) + { + // find the channel that has the older list now + kvi_time_t tOldest = tNow; + KviChannelWindow * pOldest = 0; + for(KviChannelWindow * pChan = m_pChannelList->first();pChan;pChan = m_pChannelList->next()) + { + if(pChan->lastReceivedWhoReply() < tOldest) + { + pOldest = pChan; + tOldest = pChan->lastReceivedWhoReply(); + } + } + // if the oldest chan who list is older than 150 secs, update it + if((tNow - tOldest) > 150) + { + // ok, sent the request for this channel + stateData()->setLastSentChannelWhoRequest(tNow); + QString szChanName = encodeText(pOldest->windowName()).data(); + if(_OUTPUT_PARANOIC) + console()->output(KVI_OUT_VERBOSE,__tr2qs("Updating away state for channel %Q"),&szChanName); + if(lagMeter()) + { + KviCString tmp(KviCString::Format,"WHO %s",encodeText(pOldest->windowName()).data()); + lagMeter()->lagCheckRegister(tmp.ptr(),70); + } + pOldest->setSentSyncWhoRequest(); + if(!sendFmtData("WHO %s",encodeText(pOldest->windowName()).data())) + return; + } + } + } + } + } +} + +const QString & KviIrcConnection::currentServerName() +{ + return serverInfo()->name(); +} + +const QString & KviIrcConnection::currentNickName() +{ + return userInfo()->nickName(); +} + +const QString & KviIrcConnection::currentUserName() +{ + return userInfo()->userName(); +} \ No newline at end of file diff --git a/src/kvirc/kernel/KviIrcConnection.h b/src/kvirc/kernel/KviIrcConnection.h new file mode 100644 index 000000000..e0a03dc2a --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnection.h @@ -0,0 +1,947 @@ +#ifndef _KVI_IRCCONNECTION_H_ +#define _KVI_IRCCONNECTION_H_ +//============================================================================= +// +// File : KviIrcConnection.h +// Creation date : Mon 03 May 2004 01:45:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviIrcConnection.h +* \author Szymon Stefanek +* \brief An abstraction of a connection to an IRC server +*/ + +#include "kvi_settings.h" +#include "KviQString.h" +#include "KviPointerList.h" +#include "KviTimeUtils.h" + +#include +#include + +class QTimer; +class QTextCodec; +class KviConsole; +class KviIrcNetworkData; +class KviIrcServer; +class KviProxy; +class KviIrcSocket; +class KviIrcLink; +class KviDataBuffer; +class KviIrcContext; +class KviMainWindow; +class KviChannelWindow; +class KviQueryWindow; +class KviIrcConnectionTarget; +class KviIrcUserDataBase; +class KviIrcConnectionUserInfo; +class KviIrcConnectionServerInfo; +class KviIrcConnectionStateData; +class KviIrcConnectionAntiCtcpFloodData; +class KviIrcConnectionNetsplitDetectorData; +class KviIrcConnectionAsyncWhoisData; +class KviIrcConnectionStatistics; +class KviIrcConnectionRequestQueue; +class KviLagMeter; +class KviNotifyListManager; +class KviDnsResolver; +class KviUserIdentity; +class KviIdentityProfileSet; +class KviCString; + + +/** +* \class KviIrcConnection +* \brief An abstraction of a connection to an IRC server +* +* This class deals with the high-level logic of a connection to an IRC server. +* It's always attached to a KviIrcContext and thus to a KviConsole window. +* The connection has a KviIrcConnectionTarget object which specifies the +* data of the server that needs to be contacted and a KviUserIdentity object +* which specifies the user data to use. +* +* The connection is the upper layer of the KVIrc networking stack. It owns +* KviIrcLink which is the layer immediately below and which in turn contains +* a KviIrcSocket. +* +* The connection creates and manages a lot of objects that handle +* runtime information. These objects include a KviIrcConnectionUserInfo which +* contains the ACTUAL user information, KviIrcConnectionServerInfo which +* contains the ACTUAL server information, KviIrcUserDataBase which is +* substantially a big hash table containing all the users visible to KVIrc in +* this connection, a list of channels, a list of queries etc... +*/ +class KVIRC_API KviIrcConnection : public QObject +{ + friend class KviConsole; + friend class KviIrcContext; + friend class KviIrcLink; + friend class KviIrcServerParser; + Q_OBJECT +protected: + /** + * \brief Creates a KviIrcConnection object. + * + * This is actually used only by KviConsole. + * + * pContext must not be NULL and is kept as shallow pointer (that is, it's + * not owned and must persists for the entire life of KviIrcConnection: + * caller is responsable for that). + * + * pTarget must not be NULL and must be allocated with new as this class + * takes the ownership. + * + * pIdentity must not be NULL and must be allocated with new as this class + * takes the ownership. + * \param pContext The KviIrcContext we're attacched to + * \param pTarget The server data + * \param pIdentity User information to use in ths connection + * \return KviIrcConnection + */ + KviIrcConnection(KviIrcContext * pContext,KviIrcConnectionTarget * pTarget,KviUserIdentity * pIdentity); + + /** + * \brief Destroys a KviIrcConnection object. KviConsole uses this. + */ + ~KviIrcConnection(); +public: + /** + * \enum State + * \brief The possible "high level" states of this connection. + */ + enum State + { + Idle, /**< The connection is doing nothing */ + Connecting, /**< A connection attempt is in progress */ + Connected /**< We're connected to an IRC server */ + }; +private: + KviConsole * m_pConsole; // shallow, never null + KviIrcContext * m_pContext; // shallow, never null + + State m_eState; + bool m_bIdentdAttached; + + KviIrcConnectionTarget * m_pTarget; // owned, never null + + KviIrcLink * m_pLink; // owned, never null + + // The initial information about the user we'll send out to the server + // Note that the ACTUAL user information are in m_pUserInfo instead + KviUserIdentity * m_pUserIdentity; // owned, never null + + // The ACTUAL user information + KviIrcConnectionUserInfo * m_pUserInfo; // owned, never null + // The ACTUAL server information + KviIrcConnectionServerInfo * m_pServerInfo; // owned, never null + + KviIrcConnectionStateData * m_pStateData; // owned, never null + + KviPointerList * m_pChannelList; // owned, never null, elements shallow + KviPointerList * m_pQueryList; // owned, never null, elements shallow + + KviIrcUserDataBase * m_pUserDataBase; // owned, never null + + KviNotifyListManager * m_pNotifyListManager; // owned, see restartNotifyList() + QTimer * m_pNotifyListTimer; // delayed startup timer for the notify lists + + KviLagMeter * m_pLagMeter; // owned, may be null (when not running) + + KviIrcConnectionAntiCtcpFloodData * m_pAntiCtcpFloodData; // owned, never null + KviIrcConnectionNetsplitDetectorData * m_pNetsplitDetectorData; // owned, never null + KviIrcConnectionAsyncWhoisData * m_pAsyncWhoisData; // owned, never null + + KviIrcConnectionStatistics * m_pStatistics; // owned, never null + + KviDnsResolver * m_pLocalhostDns; // FIXME: this should go to an aux structure + + QTextCodec * m_pSrvCodec; // connection codec: never null + QTextCodec * m_pTextCodec; // connection codec: never null + KviIrcConnectionRequestQueue * m_pRequestQueue; // owned, never null +public: + /** + * \brief Returns a pointer to the owning console + * + * The pointer is never NULL + * \return KviConsole * + */ + inline KviConsole * console(){ return m_pConsole; }; + + /** + * \brief Returns a pointer to the owning KviIrcContext. + * + * The returned value is never NULL + * \return KviIrcContext * + */ + inline KviIrcContext * context(){ return m_pContext; }; + + /** + * \brief Returns the target of this connection. + * + * Please note that the target doesn't necessairly contain up-to-date data. + * You might want to look at serverInfo() instead. + * The returned pointer is never NULL. + * \return KviIrcConnectionTarget * + */ + inline KviIrcConnectionTarget * target(){ return m_pTarget; }; + + /** + * \brief Returns the underlying KviIrcLink object + * + * The returned pointer is never NULL. + * \return KviIrcLink * + */ + inline KviIrcLink * link(){ return m_pLink; }; + + /** + * \brief Returns the current state of the connection + * \return State + */ + inline State state(){ return m_eState; }; + + /** + * \brief Returns a pointer to the big connection user database. + * + * The database contains ALL the users KVIrc can "see" in this connection. + * The returned pointer is never NULL. + * \return KviIrcUserDataBase * + */ + inline KviIrcUserDataBase * userDataBase(){ return m_pUserDataBase; }; + + /** + * \brief Returns a pointer to the KviIrcConnectionUserInfo object + * + * It contains runtime information about the user. This includes the + * current nickname, username, flags and other stuff that KviUserIdentity + * actually doesn't contain (or has only "default" values for). + * The returned pointer is never NULL. + * Include "KviIrcConnectionUserInfo.h" as the class is only + * forwarded here. + * \return KviIrcConnectionUserInfo * + */ + inline KviIrcConnectionUserInfo * userInfo(){ return m_pUserInfo; }; + + /** + * \brief Returns a pointer to the KviIrcConnectionServerInfo object + * + * It contains runtime information about the current server. This includes + * the current servername, the server capabilities and other stuff that + * KviConnectionTarget actually doesn't contain (or has only "default" + * values for). + * The returned pointer is never NULL. + * Include "KviIrcConnectionServerInfo.h" as the class is only + * forwarded here. + * \return KviIrcConnectionServerInfo * + */ + inline KviIrcConnectionServerInfo * serverInfo(){ return m_pServerInfo; }; + + /** + * \brief Returns a pointer to the KviIrcConnectionStateData object + * + * It contains _generic_ connection state data. This includes the current + * nickname index at login time, flags that signal "micro-states" etc... + * This data *could* be part of KviIrcConnection itself but we prefer to + * keep it in a separate class in order to cleanup the implementation. + * The returned pointer is never NULL. + * Include "KviIrcConnectionStateData.h" as the class is only + * forwarded here. + * \return KviIrcConnectionStateData * + */ + inline KviIrcConnectionStateData * stateData(){ return m_pStateData; }; + + /** + * \brief Returns a pointer to the KviIrcConnectionAntiCtcpFloodData object + * + * It contains data private to the Anti CTCP Flood engine. Very similar + * to KviIrcConnectionStateData but dedicated to Ctcp flood. + * The returned pointer is never NULL. + * Include "KviIrcConnectionAntiCtcpFloodData.h" as the class is + * only forwarded here. + * \return KviIrcConnectionAntiCtcpFloodData * + */ + inline KviIrcConnectionAntiCtcpFloodData * antiCtcpFloodData() + { return m_pAntiCtcpFloodData; }; + + /** + * \brief Returns a pointer to the KviIrcConnectionNetsplitDetectorData object + * + * It contains data private to the netsplit detector engine. Very similar + * to KviIrcConnectionStateData but dedicated to netsplit detection. + * The returned pointer is never NULL. + * Include "KviIrcConnectionNetsplitDetectorData.h" as the class is + * only forwarded here. + * \return KviIrcConnectionNetsplitDetectorData * + */ + inline KviIrcConnectionNetsplitDetectorData * netsplitDetectorData() + { return m_pNetsplitDetectorData; }; + + /** + * \brief Returns a pointer to the KviIrcConnectionAsyncWhoisData object + * + * It contains data private to the async whois engine. Very similar to + * KviIrcConnectionStateData but dedicated to async whois. + * The returned pointer is never NULL. + * Include "KviIrcConnectionAsyncWhoisData.h" as the class is only + * forwarded here. + * \return KviIrcConnectionAsyncWhoisData * + */ + inline KviIrcConnectionAsyncWhoisData * asyncWhoisData() + { return m_pAsyncWhoisData; }; + + /** + * \brief Returns a pointer to the KviIrcConnectionStatistics object + * + * It contains runtime statistics about the connection. Very similar to + * KviIrcConnectionStateData but dedicated to statistics. + * The returned pointer is never NULL. + * Include "KviIrcConnectionStatistics.h" as the class is only + * forwarded here. + * \return KviIrcConnectionStatistics * + */ + inline KviIrcConnectionStatistics * statistics(){ return m_pStatistics; }; + + /** + * \brief Returns a pointer to the current KviNotifyListManager. + * + * The returned pointer is NULL if notify list management is disabled for + * the current connection. + * \return KviNotifyListManager * + */ + inline KviNotifyListManager * notifyListManager() + { return m_pNotifyListManager; }; + + /** + * \brief Returns a pointer to the current KviLagMeter. + * + * The returned pointer is NULL if lag measurement is disabled for the + * current connection. + * \return KviLagMeter * + */ + inline KviLagMeter * lagMeter(){ return m_pLagMeter; }; + + /** + * \brief Returns a pointer to the current KviIrcConnectionRequestQueue. + * \return KviIrcConnectionRequestQueue * + */ + inline KviIrcConnectionRequestQueue * requestQueue(){ return m_pRequestQueue; }; + + /** + * \brief Returns the list of the channels bound to the current connection. + * + * The pointer itself is never null (though the list may be empty). + * \return KviPointerList * + */ + inline KviPointerList * channelList(){ return m_pChannelList; }; + + /** + * \brief Helper that provides a shortcut for really common access to serverInfo()->networkName() + * \return const QString & + */ + const QString & currentNetworkName(); + + /** + * \brief Helper that provides a shortcut for really common access to userInfo()->nickName() + * \return const QString & + */ + const QString & currentNickName(); + + /** + * \brief Helper that provides a shortcut for really common access to userInfo()->userName() + * \return const QString & + */ + const QString & currentUserName(); + + /** + * \brief Helper that provides a shortcut for really common access to serverInfo()->name() + * \return const QString & + */ + const QString & currentServerName(); + + // + // Channel management + // + // FIXME: Delegate to a KviChannelManager + // + + /** + * \brief Finds the channel with the specified unicode name. + * + * Returns the pointer to the channel found or NULL if there is no such + * channel. + * \param szName The name of the channel + * \return KviChannelWindow * + */ + KviChannelWindow * findChannel(const QString & szName); + + /** + * \brief Returns a list of channels bound to the current connection + * + * This is actually the list of channels that the local user has in common + * with the specified user. + * The list is returned as a comma separated string. If bAddEscapeSequences + * is true, then the string includes special escape sequences for + * KviIrcView that will make the channel names clickable. + * + * Returns the number of channels found. + * \param szNick The nickname of the user + * \param szChansBuffer The buffer where to store data + * \param bAddEscapeSequences Whether to include escape sequences + * \return int + */ + int getCommonChannels(const QString & szNick, QString & szChansBuffer, bool bAddEscapeSequences = true); + + /** + * \brief Creates a new channel with the specified name. + * + * This should be called in response to a JOIN message. + * This function _assumes_ that such a channel doesn't exist yet (or if it + * exists then it's actually in DEAD state). You can assume that channel + * creation never fails: if the returned pointer is NULL then we're screwed + * anyway as virtual memory is exausted. + * \param szName The name of the channel + * \return KviChannelWindow * + */ + KviChannelWindow * createChannel(const QString & szName); + + /// + /// This is called by KviChannelWindow upon creation. You shouldn't need to call it. + /// + /// FIXME: Could be made protected. + /// + void registerChannel(KviChannelWindow *c); + + /// + /// This is called by KviChannelWindow just before destruction. You shouldn't need to call it. + /// + /// FIXME: Could be made protected. + /// + void unregisterChannel(KviChannelWindow *c); + + /** + * \brief Marks all the currently existing channels as DEAD + * + * They are preserved across connections. Marking a channel as dead + * actually removes the ownership of KviChannelWindow from KviIrcConnection and + * moves it to KviIrcContext (as the contex is preserved across + * connections). + * \return void + */ + void keepChannelsOpenAfterDisconnect(); + + /** + * \brief Closes all the currently open channels not marked as dead. + * \return void + */ + void closeAllChannels(); + + /** + * \brief Closes all the currently open queries not marked as dead. + * \return void + */ + void closeAllQueries(); + + // + // Query management + // + // FIXME: Delegate to a KviQueryManager ? + // + + /** + * \brief Finds the query with the specified nick. + * + * Returns the pointer to the query found or NULL if there is no such + * query. + * \param szNick The nickname of the user + * \return KviQueryWindow * + */ + KviQueryWindow * findQuery(const QString & szNick); + + /** + * \brief Returns the list of the currently open queries. + * + * The returned pointer is never NULL (the list may be empty though). + * \return KviPointerList * + */ + inline KviPointerList * queryList(){ return m_pQueryList; }; + + /** + * \brief Creates a query with the specified nick as target. + * + * This function assumes that such a query doesn't exist yet (or if it + * exists it's actually marked as dead and needs to be resurrected). + * \param szNick The nickname of the user + * \return KviQueryWindow * + */ + KviQueryWindow * createQuery(const QString & szNick); + + /// + /// This is called by KviQueryWindow upon creation, you shouldn't need to use it. + /// + /// FIXME: Could be made protected. + /// + void registerQuery(KviQueryWindow *q); + + /// + /// This is called by KviQueryWindow just before destruction, you shouldn't need to use it. + /// + /// FIXME: Could be made protected. + /// + void unregisterQuery(KviQueryWindow *q); + + /** + * \brief Marks all the currently open queries as DEAD + * + * They are kept open after a disconnect. Marking a query as dead removes + * ownership from this class and gives it to KviIrcContext (which survives + * disconnects). + * \return void + */ + void keepQueriesOpenAfterDisconnect(); + + /** + * \brief This is the inverse of keepQueriesOpenAfterDisconnect(). + * + * It's meant to be called upon reconnection (as queries don't need a JOIN + * message to be opened). + * \return void + */ + void resurrectDeadQueries(); + + /// + /// This function actually restarts the lag meter. + /// + /// FIXME: Why ? + /// + void restartLagMeter(); + + // + // Networking stack public stuff + // + + /** + * \brief Sends the specified text on the connected link (and thus socket). + * + * This function basically works like sprintf(). Please note that you + * should send only ENCODED text to the server. This is why the accepted + * parameter is a const char *. IRC is an 8 (I'd say even 7 sometimes) bit + * protocol. + * + * Please note that you don't actually need to append a CRLF pair to your + * buffer: + * the implementation of the networking stack will do it for you. Hovewer + * you can send multiple IRC commands by separating them by CRLF pairs. + * Just take care of avoiding a CRLF after the last command you specify. + * + * Returns true on success or false if the data can't be actually + * enqueued/sent (and this usually means that there is no connection at + * the moment). Please note that it MAY happen that a send attempt on a + * correctly connected link causes the link to actually disconnect (or + * rather "discover" the fact that it's disconnected at OS level). + * \param pcBuffer The _encoded_ text data to send + * \param iBuflen The length of the data: if -1 the length is determined via strlen(). + * \return bool + */ + bool sendData(const char * pcBuffer, int iBuflen = -1); + + /** + * \brief Sends the specified text on the connected link (and thus socket). + * + * This function basically works like sprintf(). Please note that you + * should send only ENCODED text to the server. This is why the accepted + * parameter is a const char *. IRC is an 8 (I'd say even 7 sometimes) bit + * protocol. + * + * Please note that you don't actually need to append a CRLF pair to your + * buffer: + * the implementation of the networking stack will do it for you. Hovewer + * you can send multiple IRC commands by separating them by CRLF pairs. + * Just take care of avoiding a CRLF after the last command you specify. + * + * Returns true on success or false if the data can't be actually + * enqueued/sent (and this usually means that there is no connection at + * the moment). Please note that it MAY happen that a send attempt on a + * correctly connected link causes the link to actually disconnect (or + * rather "discover" the fact that it's disconnected at OS level). + * \param pcFmt The format string to be first sprintf'ed with the variadic params and then sent + * \param ... The variadic arguments (see man sprintf for an explaination) + * \return bool + * + * FIXME: change name to sendFormattedData() ? + */ + bool sendFmtData(const char * pcFmt, ...); + + /** + * Clears the underlying output queue. + * Exposed basically for /context.clearQueue + * You shouldn't need it for any other reason :) + */ + void clearOutputQueue(bool bPrivateMessagesOnly); + + /** + * \brief This function is part of the networking stack. + * + * It's called by KviIrcLink OR KviMexLinkFilter when a message is arriving + * from the server. Needs to be public because subclasses of + * KviMexLinkFilter may call it. + * \param pcMessage The message :) + * \return void + */ + void incomingMessage(const char * pcMessage); + + /** + * \brief This function is part of the networking stack. + * + * It's called by KviIrcDataStreamMonitor subclasses when they want to + * inject some message without getting it filtered again + * \param pcMessage The message :) + * \return void + */ + void incomingMessageNoFilter(const char * pcMessage); + + // + // Encoding related stuff + // + + /** + * \brief Returns a pointer to the current global codec for outbound text. + * + * This codec is a global setting and may be overridden by specific + * windows. The returned pointer may be null if things really went wrong. + * \return QTextCodec * + */ + inline QTextCodec * textCodec(){ return m_pTextCodec; }; + + /** + * \brief Returns a pointer to the current global codec for inbound data. + * + * This codec is a global setting and may be overridden by specific + * windows. The returned pointer may be null if things really went wrong. + * \return QTextCodec * + */ + inline QTextCodec * serverCodec(){ return m_pSrvCodec; }; + + /** + * \brief Sets the global encoding for this connection. + * + * This is a default value and can be overridden by specific windows. + * \param szEncoding The encoding to use + * \return void + * + * FIXME: This is quite unclear (why it forces encoding to all the windows?) + */ + void setEncoding(const QString & szEncoding); + + /** + * \brief Decodes the specified text by using the server codec. + * + * You should first attempt to decode the text by using the window codec + * (if you belong to a window). + * \param szText The text to decode + * \return QString + */ + QString decodeText(const char * szText); + + /** + * \brief Encodes the specified text by using the local text codec. + * + * You should first attempt to encode the text by using the window codec + * (if you belong to a window). + * \param szText The text to encode + * \return QByteArray + */ + QByteArray encodeText(const QString & szText); +protected: + // + // Notify list management + // + + /** + * \brief Starts the notify list in 15 seconds + * + * We have this delay to wait an eventual RPL_PROTOCTL from the server + * telling us that the WATCH notify list method is supported + * \return void + */ + void delayedStartNotifyList(); + + // + // Login operations + // + + /** + * \brief Resolves the localhost into an IP address + * \return void + */ + void resolveLocalHost(); + +#ifdef COMPILE_SSL_SUPPORT + void trySTARTTLS(); + void enableStartTlsSupport(bool bEnable); +#endif + + /** + * \brief Uses the profiles' data as connection data + * + * It checks if the identity profiles are enabled and updates the data + * of the connection if a profile rule matches the network name + * \param pSet The instance of the network identity profile set + * \param szNetwork The name of the network + * \return void + */ + void useProfileData(KviIdentityProfileSet * pSet, const QString & szNetwork); + + /** + * Sets the specified real name in the user information set after + * evaluating it via KVS engine (so identifiers are substituted). + * Call this function instead of m_pUserInfo->setRealName(). + */ + void useRealName(const QString &szRealName); + + /** + * \brief Logins to the irc server + * \return void + */ + void loginToIrcServer(); + + // + // KviIrcServerParser interface + // + + /** + * \brief Called to start the notify lists when RPL_ENDOFMOTD is received + * \return void + */ + void endOfMotdReceived(); + + /** + * \brief Called when RPL_SERVINFO (004) is received and sets the info + * \param szServerName The name of the server + * \param szUserModes The user modes supported by the server + * \param szChanModes The chan modes supported by the server + * \return void + */ + void serverInfoReceived(const QString & szServerName, const QString & szUserModes, const QString & szChanModes); + + /** + * \brief Called when AUTHENTICATE answer is received + * \return void + */ + void handleAuthenticate(KviCString & szResponse); + + /** + * \brief Called when CAP LS answer is received + * \return void + */ + void handleInitialCapLs(); + + /** + * \brief Called when CAP LS negotiation fails + * \return void + */ + void handleFailedInitialCapLs(); + + /** + * \brief Called when CAP ACK answer is received + * \return void + */ + void handleInitialCapAck(); + + /** + * \brief Called when CAP NAK answer is received + * \return void + */ + void handleInitialCapNak(); + + /** + * \brief Called when we want to end CAP negotiation and go on wi the login + * \return void + */ + void endInitialCapNegotiation(); + + /** + * \brief Called to update the away state + * \param bAway Whether we enter the away mode + * \return void + */ + void changeAwayState(bool bAway); + + /** + * \brief Called on each JOIN and sets the info + * + * It's called meaningful almost only on the first time + * \param szUserName The username + * \param szHostName The hostname + * \return void + * FIXME: call it also on other messages ? + */ + void userInfoReceived(const QString & szUserName, const QString & szHostName); + + /** + * \brief Called when NICK is received + * \param szNewNick The new nickname for the user + * \return void + */ + void nickChange(const QString & szNewNick); + + /** + * \brief Called when MODE is received for each mode character + * \param cMode The mode flag :) + * \param bSet Whether to set the mode + * \return bool + */ + bool changeUserMode(char cMode, bool bSet); + + /** + * \brief Called on the first numeric received from server + * \param szNickName The nickname to use + * \return void + */ + void loginComplete(const QString & szNickName); + + // + // KviIrcContext interface + // + + /** + * \brief This starts an asynchronous connection attempt + * + * You must return control to the Qt core for the connection operations to + * be initiated + * \return void + */ + void start(); + + /** + * \brief Kills any running connection or attempt + * \return void + */ + void abort(); + + /** + * \brief Called once in a while (every 5 secs at the moment) + * \param tNow The current time + * \return void + */ + void heartbeat(kvi_time_t tNow); + + // + // KviIrcLink interface (down) + // + + /** + * \brief This signals that the connection attempt has failed + * \param iError The error code + * \return void + */ + void linkAttemptFailed(int iError); + + /** + * \brief Called by KviIrcLink when the socket state changes to Connected + * \return void + */ + void linkEstabilished(); + + /** + * \brief Called by KviIrcLink when the socket state changes to Ready + * \return void + */ + void linkTerminated(); +private: + /** + * \brief Setups the codec for the text + * \return void + */ + void setupTextCodec(); + + /** + * \brief Setups the codec for the server + * \return void + */ + void setupSrvCodec(); +public slots: + /** + * \brief Called when we unhighlight all channels + * \return void + */ + void unhighlightAllChannels(); + + /** + * \brief Called when we unhighlight all queries + * \return void + */ + void unhighlightAllQueries(); + + /** + * \brief Called to restart the notify list + * \return void + */ + void restartNotifyList(); +private slots: + /** + * \brief Called when the hostname lookup is finished + * \return void + */ + void hostNameLookupTerminated(KviDnsResolver * pDns); +signals: + /** + * \brief Emitted when the away state changes + * \return void + */ + void awayStateChanged(); + + /** + * \brief Emitted when the user modes change + * \return void + */ + void userModeChanged(); + + /** + * \brief Emitted when the nickname changes + * \return void + */ + void nickNameChanged(); + + /** + * \brief Emitted when we register a channel + * \param pChan The channel :) + * \return void + */ + void channelRegistered(KviChannelWindow * pChan); + + /** + * \brief Emitted when we unregister a channel + * \param pChan The channel :) + * \return void + */ + void channelUnregistered(KviChannelWindow * pChan); + + /** + * \brief Emitted when the channels list change + * \return void + */ + void chanListChanged(); +}; + + +// TODO: KviIdentity + +#endif //_KVI_IRCCONNECTION_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionAntiCtcpFloodData.cpp b/src/kvirc/kernel/KviIrcConnectionAntiCtcpFloodData.cpp new file mode 100644 index 000000000..aba05539f --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionAntiCtcpFloodData.cpp @@ -0,0 +1,38 @@ +//============================================================================= +// +// File : KviIrcConnectionAntiCtcpFloodData.cpp +// Creation date : Sat 26 Jun 2004 18:09:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionAntiCtcpFloodData.h" + +KviIrcConnectionAntiCtcpFloodData::KviIrcConnectionAntiCtcpFloodData() +{ + m_tLastCtcp = 0; + m_uCtcpCount = 0; +} + +KviIrcConnectionAntiCtcpFloodData::~KviIrcConnectionAntiCtcpFloodData() +{ +} + diff --git a/src/kvirc/kernel/KviIrcConnectionAntiCtcpFloodData.h b/src/kvirc/kernel/KviIrcConnectionAntiCtcpFloodData.h new file mode 100644 index 000000000..10c4ce4cf --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionAntiCtcpFloodData.h @@ -0,0 +1,48 @@ +#ifndef _KVI_IRCCONNECTIONANTICTCPFLOODDATA_H_ +#define _KVI_IRCCONNECTIONANTICTCPFLOODDATA_H_ +//============================================================================= +// +// File : KviIrcConnectionAntiCtcpFloodData.h +// Creation date : Sat 26 Jun 2004 18:09:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviTimeUtils.h" + +class KVIRC_API KviIrcConnectionAntiCtcpFloodData +{ +public: + KviIrcConnectionAntiCtcpFloodData(); + ~KviIrcConnectionAntiCtcpFloodData(); +protected: + // ctcp antiflood mechanism + kvi_time_t m_tLastCtcp; // the time we have received the last "may flood" ctcp request + unsigned int m_uCtcpCount; // the ctcp counter for the antiflooder +public: + kvi_time_t lastCtcpTime(){ return m_tLastCtcp; }; + unsigned int ctcpCount(){ return m_uCtcpCount; }; + void setLastCtcpTime(kvi_time_t tLastCtcp){ m_tLastCtcp = tLastCtcp; }; + void increaseCtcpCount(){ m_uCtcpCount++; }; + void setCtcpCount(unsigned int uCtcpCount){ m_uCtcpCount = uCtcpCount; }; +}; + + +#endif //!_KVI_IRCCONNECTIONANTICTCPFLOODDATA_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionAsyncData.h b/src/kvirc/kernel/KviIrcConnectionAsyncData.h new file mode 100644 index 000000000..ef11b8218 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionAsyncData.h @@ -0,0 +1,82 @@ +#ifndef _KVI_IRCCONNECTIONASYNCTEMPLATEDATA_H_ +#define _KVI_IRCCONNECTIONASYNCTEMPLATEDATA_H_ +//============================================================================= +// +// File : KviIrcConnectionAsyncWhoisData.h +// Creation date : Sat 26 Jun 2004 19:40:20 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 template class will be used to create some other classes for future commands +// KviIrcConnectionAsyncWhoData for creating an awho command +// KviIrcConnectionAsyncWhowasData for creating an awhowas command +// It is now also used by KviIrcConnectionAsyncWhoisData + +template +class KVIRC_API KviIrcConnectionAsyncData +{ +public: + KviIrcConnectionAsyncData() + { + m_pInfoList = 0; + } + + ~KviIrcConnectionAsyncData() + { + if(m_pInfoList)delete m_pInfoList; + } + +protected: + KviPointerList * m_pInfoList; // awhois pending stuff +public: + void add(T * i) + { + if(!m_pInfoList) + { + m_pInfoList = new KviPointerList; + m_pInfoList->setAutoDelete(true); + } + m_pInfoList->append(i); + } + + T * lookup(const QString &nick) + { + if(!m_pInfoList)return 0; + for(T * i = m_pInfoList->first();i;i = m_pInfoList->next()) + { + if(KviQString::equalCI(nick,i->szNick))return i; + } + return 0; + } + + void remove(T * i) + { + if(!m_pInfoList)return; + m_pInfoList->removeRef(i); + if(m_pInfoList->isEmpty()) + { + delete m_pInfoList; + m_pInfoList = 0; + } + } +}; + +#endif + diff --git a/src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.cpp b/src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.cpp new file mode 100644 index 000000000..58ef6729a --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.cpp @@ -0,0 +1,42 @@ +//============================================================================= +// +// File : KviIrcConnectionAsyncWhoisData.cpp +// Creation date : Sat 26 Jun 2004 19:40:20 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionAsyncWhoisData.h" +#include "KviKvsScript.h" + +KviAsyncWhoisInfo::KviAsyncWhoisInfo() +{ + pCallback = 0; + pMagic = 0; +} + +KviAsyncWhoisInfo::~KviAsyncWhoisInfo() +{ + if(pCallback)delete pCallback; + if(pMagic)delete pMagic; +} + + diff --git a/src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.h b/src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.h new file mode 100644 index 000000000..861e0deae --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionAsyncWhoisData.h @@ -0,0 +1,68 @@ +#ifndef _KVI_IRCCONNECTIONASYNCWHOISDATA_H_ +#define _KVI_IRCCONNECTIONASYNCWHOISDATA_H_ +//============================================================================= +// +// File : KviIrcConnectionAsyncWhoisData.h +// Creation date : Sat 26 Jun 2004 19:40:20 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviPointerList.h" +#include "KviIrcConnectionAsyncData.h" + +class KviWindow; +class KviKvsScript; +class KviKvsVariant; + +class KVIRC_API KviAsyncWhoisInfo +{ +public: + QString szNick; + QString szUser; + QString szHost; + QString szReal; + QString szServer; + QString szIdle; + QString szSignon; + QString szChannels; + QString szAway; // The szSpecial member is renamed szAway as its sole purpose is to tell whether the user is away or not + QString szAuth; + QString szAdditional; + KviKvsScript * pCallback; + KviKvsVariant * pMagic; + KviWindow * pWindow; +public: + KviAsyncWhoisInfo(); + ~KviAsyncWhoisInfo(); +}; + + + +// KviIrcConnectionAsyncWhoisData is now recreated using a template +// I'm using inheritance as i haven't been able to use a typedef +// This line didn't build +// typedef KviIrcConnectionAsyncData KviIrcConnectionAsyncWhoisData +class KVIRC_API KviIrcConnectionAsyncWhoisData : public KviIrcConnectionAsyncData +{ +}; + +#endif //!_KVI_IRCCONNECTIONASYNCWHOISDATA_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionNetsplitDetectorData.cpp b/src/kvirc/kernel/KviIrcConnectionNetsplitDetectorData.cpp new file mode 100644 index 000000000..0ab64744c --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionNetsplitDetectorData.cpp @@ -0,0 +1,37 @@ +//============================================================================= +// +// File : KviIrcConnectionNetsplitDetectorData.cpp +// Creation date : Sat 26 Jun 2004 18:20:58 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionNetsplitDetectorData.h" + +KviIrcConnectionNetsplitDetectorData::KviIrcConnectionNetsplitDetectorData() +{ + m_tLastNetsplitOnQuit = 0; +} + +KviIrcConnectionNetsplitDetectorData::~KviIrcConnectionNetsplitDetectorData() +{ +} + diff --git a/src/kvirc/kernel/KviIrcConnectionNetsplitDetectorData.h b/src/kvirc/kernel/KviIrcConnectionNetsplitDetectorData.h new file mode 100644 index 000000000..98439df8f --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionNetsplitDetectorData.h @@ -0,0 +1,46 @@ +#ifndef _KVI_IRCCONNECTIONNETSPLITDETECTORDATA_H_ +#define _KVI_IRCCONNECTIONNETSPLITDETECTORDATA_H_ +//============================================================================= +// +// File : KviIrcConnectionNetsplitDetectorData.h +// Creation date : Sat 26 Jun 2004 18:20:58 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviTimeUtils.h" + +class KVIRC_API KviIrcConnectionNetsplitDetectorData +{ +public: + KviIrcConnectionNetsplitDetectorData(); + ~KviIrcConnectionNetsplitDetectorData(); +protected: + QString m_szLastNetsplitOnQuitReason; + kvi_time_t m_tLastNetsplitOnQuit; +public: + const QString & lastNetsplitOnQuitReason(){ return m_szLastNetsplitOnQuitReason; }; + void setLastNetsplitOnQuitReason(const QString &szReason){ m_szLastNetsplitOnQuitReason = szReason; }; + kvi_time_t lastNetsplitOnQuitTime(){ return m_tLastNetsplitOnQuit; }; + void setLastNetsplitOnQuitTime(kvi_time_t t){ m_tLastNetsplitOnQuit = t; }; +}; + +#endif //!_KVI_IRCCONNECTIONNETSPLITDETECTORDATA_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionRequestQueue.cpp b/src/kvirc/kernel/KviIrcConnectionRequestQueue.cpp new file mode 100644 index 000000000..e5b3b4286 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionRequestQueue.cpp @@ -0,0 +1,175 @@ +//============================================================================= +// +// File : KviIrcConnectionRequestQueue.h +// Creation date : Tue 09 Feb 2010 10:24:32 by Fabio Bas +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2010 Fabio Bas +// +// 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 opinion) 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 "KviIrcConnectionRequestQueue.h" + +#include "KviChannelWindow.h" +#include "KviOptions.h" +#include "KviLagMeter.h" +#include "KviIrcConnectionStateData.h" +#include "KviIrcConnectionServerInfo.h" + +#include + +KviIrcConnectionRequestQueue::KviIrcConnectionRequestQueue() +{ + m_curType = Mode; + connect(&m_timer, SIGNAL(timeout()), this, SLOT(timerSlot())); +} + +KviIrcConnectionRequestQueue::~KviIrcConnectionRequestQueue() +{ + disconnect(&m_timer, SIGNAL(timeout()), this, SLOT(timerSlot())); +} + +void KviIrcConnectionRequestQueue::enqueueChannel(KviChannelWindow * pChan) +{ + if(!m_channels.contains(pChan)) + { + m_channels.enqueue(pChan); + if(!m_timer.isActive()) + { + m_timer.start(KVI_OPTION_UINT(KviOption_uintOnJoinRequestsDelay)*1000); + } + } +} + +void KviIrcConnectionRequestQueue::dequeueChannel(KviChannelWindow * pChan) +{ + if(m_channels.contains(pChan)) + { + m_channels.removeOne(pChan); + if(m_channels.isEmpty()) + m_timer.stop(); + } +} + +void KviIrcConnectionRequestQueue::clearAll() +{ + m_timer.stop(); + m_channels.clear(); + m_curType = Mode; +} + +void KviIrcConnectionRequestQueue::timerSlot() +{ + if(m_channels.isEmpty()) + { + m_timer.stop(); + } else { + KviChannelWindow * pChan = m_channels.head(); + QByteArray encodedChan = pChan->connection()->encodeText(pChan->target()).data(); + /* The following switch will let the execution flow pass-trought if any request type + * is currently disabled (or not available on the server). Channel's "MODE" request is + * the only mandatory request. + */ + switch(m_curType) + { + case BanException: + if(pChan->serverInfo()->supportedListModes().contains('e') && + !KVI_OPTION_BOOL(KviOption_boolDisableBanExceptionListRequestOnJoin) && + !( pChan->serverInfo()->getNeedsOpToListModeseI() && + !pChan->isMeOp() + ) + ) + { + if(!pChan->connection()->sendFmtData("MODE %s e",encodedChan.data())) + clearAll(); // disconnected + else pChan->setSentListRequest('e'); + m_curType = Invite; + break; + } + case Invite: + if(pChan->serverInfo()->supportedListModes().contains('I') && + !KVI_OPTION_BOOL(KviOption_boolDisableInviteListRequestOnJoin) && + !( pChan->serverInfo()->getNeedsOpToListModeseI() && + !pChan->isMeOp() + ) + ) + { + if(!pChan->connection()->sendFmtData("MODE %s I",encodedChan.data())) + clearAll(); // disconnected + else pChan->setSentListRequest('I'); + m_curType = QuietBan; + break; + } + case QuietBan: + if(pChan->serverInfo()->supportedListModes().contains('q') && + !KVI_OPTION_BOOL(KviOption_boolDisableQuietBanListRequestOnJoin)) + { + if(!pChan->connection()->sendFmtData("MODE %s q",encodedChan.data())) + clearAll(); // disconnected + else pChan->setSentListRequest('q'); + m_curType = Who; + break; + } + case Who: + if(!KVI_OPTION_BOOL(KviOption_boolDisableWhoRequestOnJoin)) + { + pChan->connection()->stateData()->setLastSentChannelWhoRequest(kvi_unixTime()); + if(pChan->connection()->lagMeter()) + { + KviCString tmp; + tmp.sprintf("WHO %s",encodedChan.data()); + pChan->connection()->lagMeter()->lagCheckRegister(tmp.ptr(),60); + } + if(!pChan->connection()->sendFmtData("WHO %s",encodedChan.data())) + clearAll(); // disconnected + else pChan->setSentWhoRequest(); + m_curType = Ban; + break; + } + case Ban: + if(!KVI_OPTION_BOOL(KviOption_boolDisableBanListRequestOnJoin)) + { + if(!pChan->connection()->sendFmtData("MODE %s b",encodedChan.data())) + clearAll(); // disconnected + else pChan->setSentListRequest('b'); + m_channels.dequeue(); + m_curType = Mode; + break; + } + default: + // we're at the end of the list + m_channels.dequeue(); + pChan->checkChannelSync(); + m_curType = Mode; + if(m_channels.isEmpty()) + { + m_timer.stop(); + return; + } + pChan = m_channels.head(); + encodedChan = pChan->connection()->encodeText(pChan->target()); + case Mode: + if(!pChan->connection()->sendFmtData("MODE %s",encodedChan.data())) + { + clearAll(); // disconnected + break; + } + m_curType = BanException; + break; + } + } +} \ No newline at end of file diff --git a/src/kvirc/kernel/KviIrcConnectionRequestQueue.h b/src/kvirc/kernel/KviIrcConnectionRequestQueue.h new file mode 100644 index 000000000..53102c3cb --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionRequestQueue.h @@ -0,0 +1,115 @@ +#ifndef _KVI_IRCCONNECTIONREQUESTQUEUE_H_ +#define _KVI_IRCCONNECTIONREQUESTQUEUE_H_ +//============================================================================= +// +// File : KviIrcConnectionRequestQueue.h +// Creation date : Tue 09 Feb 2010 10:24:32 by Fabio Bas +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2010 Fabio Bas +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviIrcConnectionRequestQueue.h +* \author Fabio Bas +* \brief IRC connection request queue +*/ + +#include "kvi_settings.h" + +#include +#include + +class KviChannelWindow; + +/** +* \class KviIrcConnectionRequestQueue +* \brief Class to enqueue commands to IRC server +* +* This class is designed to delay channel requests like MODE and WHO to avoid +* excess floods on some servers +*/ +class KVIRC_API KviIrcConnectionRequestQueue: public QObject +{ + Q_OBJECT +public: + /** + * \brief Constructs the request queue objects + * \return KviIrcConnectionRequestQueue + */ + KviIrcConnectionRequestQueue(); + + /** + * \brief Destroys the request queue objects + */ + virtual ~KviIrcConnectionRequestQueue(); +protected: + /** + * \enum RequestTypes + * + * \warning MODE %s b MUST BE THE LAST AUTOMATIC CHANNEL QUERY so we get + * RPL_ENDOFBANLIST as the last reply and we know that the channel is in sync + */ + enum RequestTypes { + Mode = 0, /**< Channel modes request */ + BanException = 1, /**< Ban exceptions request */ + Invite = 2, /**< Invites request */ + Who = 3, /**< Who request */ + QuietBan = 4, /**< Quiet ban request */ + Ban = 5 /**< Ban request */ + }; + + QQueue m_channels; + QTimer m_timer; + RequestTypes m_curType; +public: + /** + * \brief Enqueues the channel in the queue stack + * \param pChan The channel to enqueue + * \return void + */ + void enqueueChannel(KviChannelWindow * pChan); + + /** + * \brief Removes the channel from the queue stack + * \param pChan The channel to dequeue + * \return void + */ + void dequeueChannel(KviChannelWindow * pChan); + + /** + * \brief Checks if a channel is in the queue stack + * \param pChan The channel to check + * \return bool + */ + bool isQueued(KviChannelWindow * pChan) { return m_channels.contains(pChan); }; + + /** + * \brief Clears the queue stack + * \return void + */ + void clearAll(); +private slots: + /** + * \brief Performs time based requests + * \return void + */ + void timerSlot(); +}; + +#endif //!_KVI_IRCCONNECTIONREQUESTQUEUE_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionServerInfo.cpp b/src/kvirc/kernel/KviIrcConnectionServerInfo.cpp new file mode 100644 index 000000000..5a4369d39 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionServerInfo.cpp @@ -0,0 +1,488 @@ +//============================================================================= +// +// File : KviIrcConnectionServerInfo.cpp +// Creation date : Tue 22 Jun 2004 03:57:32 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionServerInfo.h" +#include "KviLocale.h" +#include "KviMemory.h" +#include "KviIrcUserDataBase.h" + +KviIrcConnectionServerInfo::KviIrcConnectionServerInfo() +{ + // default assumptions + m_szSupportedChannelTypes = "#&!+"; + m_szSupportedModePrefixes = "@+"; + m_szSupportedModeFlags = "ov"; + m_pModePrefixTable = 0; + buildModePrefixTable(); + m_bSupportsWatchList = false; + m_bSupportsCodePages = false; + m_bSupportsCap = false; + m_iMaxTopicLen = -1; + m_iMaxModeChanges = 3; + m_szListModes = "b"; + m_szParameterModes = "k"; + m_szParameterWhenSetModes = "l"; + m_szPlainModes = "pstnmi"; + m_szSupportedChannelModes = "pstnmiklb"; + m_pServInfo = new KviBasicIrcServerInfo(this); +} + +KviIrcConnectionServerInfo::~KviIrcConnectionServerInfo() +{ + if(m_pServInfo) + delete m_pServInfo; + if(m_pModePrefixTable) + KviMemory::free(m_pModePrefixTable); +} + +void KviIrcConnectionServerInfo::addSupportedCaps(const QString &szCapList) +{ + m_bSupportsCap = true; + + QStringList lTmp = szCapList.split(' ',QString::SkipEmptyParts); + foreach(QString szCap,lTmp) + { + // cap modifiers are: + // '-' : disable a capability (should not be present in a LS message...) + // '=' : sticky (can't be disabled once enabled) + // '~' : needs ack for modification + + if(szCap.length() < 1) + continue; // shouldn't happen + + switch(szCap[0].unicode()) + { + case '-': + case '~': + case '=': + szCap.remove(0,1); + break; + default: + // ok + break; + } + + szCap = szCap.toLower(); + + if(!m_lSupportedCaps.contains(szCap)) + m_lSupportedCaps.append(szCap); + } +} + +void KviIrcConnectionServerInfo::setSupportedChannelModes(const QString &szSupportedChannelModes) +{ + QStringList szAllModes = szSupportedChannelModes.split(',', QString::KeepEmptyParts); + + if(szAllModes.count() != 4) + { + // in this situation, better not to make assumptions about which modes needs a parameter + return; + } + + m_szListModes = szAllModes.at(0); + m_szParameterModes = szAllModes.at(1); + m_szParameterWhenSetModes = szAllModes.at(2); + m_szPlainModes = szAllModes.at(3); + + m_szSupportedChannelModes = szSupportedChannelModes; +} + +void KviIrcConnectionServerInfo::setSupportedModePrefixes(const QString &szSupportedModePrefixes,const QString &szSupportedModeFlags) +{ + m_szSupportedModeFlags = szSupportedModeFlags; + m_szSupportedModePrefixes = szSupportedModePrefixes; + buildModePrefixTable(); +} + +void KviIrcConnectionServerInfo::buildModePrefixTable() +{ + if(m_pModePrefixTable) KviMemory::free(m_pModePrefixTable); + const QChar * cPrefix = KviQString::nullTerminatedArray(m_szSupportedModePrefixes); + const QChar * cFlag = KviQString::nullTerminatedArray(m_szSupportedModeFlags); + if(!cPrefix || !cFlag)return; // eh ? + + m_uPrefixes=qMin(m_szSupportedModePrefixes.length(),m_szSupportedModePrefixes.length()); + m_pModePrefixTable=(kvi_u32_t*)KviMemory::allocate(sizeof(kvi_u32_t)*3*m_uPrefixes); + + unsigned short uPrefix,uFlag; + + // Pragma: FIXME: The whole mode handling needs rethinking! + // Alexey: FIXED: rethinked:) + // Pragma: LOL :DDDD + unsigned int i=0; + while( (uPrefix = cPrefix->unicode()) && (uFlag = cFlag->unicode()) && i:)"); break; + case 'h': return __tr2qs("Half-operators");break; + case 'j': return __tr2qs("Join throttling (:)"); break; + case 'q': return __tr2qs("Channel owners"); break; + case 'r': return __tr2qs("Registered"); break; + case 'u': return __tr2qs("Auditorium: /NAMES and /WHO show only ops"); break; + case 'z': return __tr2qs("Need SSL connection to join"); break; + } + return KviBasicIrcServerInfo::getChannelModeDescription(mode); +} + + +const QString & KviIrcdSevenIrcServerInfo::getChannelModeDescription(char mode) +{ + switch(mode) + { + case 'C': return __tr2qs("Forbid channel CTCPs"); break; + case 'F': return __tr2qs("Enable forwarding"); break; + case 'L': return __tr2qs("Large ban/exempt/invex lists (staff only)"); break; + case 'M': return __tr2qs("Disallow kicking opers (staff only)"); break; + case 'P': return __tr2qs("Persistent (staff only)"); break; + case 'Q': return __tr2qs("Block forwarded users"); break; + case 'R': return __tr2qs("Only registered nicks can join"); break; + case 'S': return __tr2qs("Strip colors"); break; + case 'T': return __tr2qs("Forbid channel NOTICEs"); break; + case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; + case 'f': return __tr2qs("Forward to another channel on uninvited"); break; + case 'g': return __tr2qs("Allow anybody to invite");break; + case 'j': return __tr2qs("Join throttling (:)"); break; + case 'p': return __tr2qs("Paranoid (disable KNOCK)"); break; + case 'q': return __tr2qs("Quiet Ban Editor"); break; + case 'r': return __tr2qs("Need auth to join channel"); break; + case 'z': return __tr2qs("Reduced moderation for ops"); break; + } + return KviBasicIrcServerInfo::getChannelModeDescription(mode); +} + +const QString & KviBahamutIrcServerInfo::getChannelModeDescription(char mode) +{ + switch(mode) + { + case 'L': return __tr2qs("Channel visible in LIST"); break; + case 'M': return __tr2qs("Need auth to speak and change nick"); break; + case 'O': return __tr2qs("IRC-Op only channel"); break; + case 'R': return __tr2qs("Only registered nicks can join"); break; + case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; + case 'j': + if(m_pParent) + { + if(m_pParent->supportedPlainModes().contains('j')) + { + // Azzurra (bahamut 1.4) similar to 'R' + return __tr2qs("Only registered nicks can join"); + } + } + + // Dalnet (bahamut 1.8) + return __tr2qs("Join throttling (:)"); + break; + // azzurra (bahamuth 1.4) specific addition: + case 'S': return __tr2qs("Need SSL connection to join"); break; + case 'U': return __tr2qs("Permit foreign users without auth to JOIN"); break; + case 'd': return __tr2qs("Need op/voice to change nick"); break; + case 'h': return __tr2qs("Half-operators");break; + case 'r': return __tr2qs("Registered"); break; + case 'u': return __tr2qs("Hide QUIT and PART messages"); break; + } + return KviBasicIrcServerInfo::getChannelModeDescription(mode); +} + +const QString & KviInspIRCdIrcServerInfo::getChannelModeDescription(char mode) +{ + switch(mode) + { + case 'A': return __tr2qs("Allow anybody to invite");break; + case 'B': return __tr2qs("Block messages with too many CAPS");break; + case 'C': return __tr2qs("Forbid channel CTCPs"); break; + case 'D': return __tr2qs("Delay users join to first message"); break; + case 'F': return __tr2qs("Limit nick changes (:)"); break; + case 'G': return __tr2qs("Censor bad words"); break; + case 'J': return __tr2qs("Disable join after kick ()"); break; + case 'K': return __tr2qs("Forbid /KNOCK"); break; + case 'L': return __tr2qs("Redirect on channel full (mode +l)"); break; + case 'M': return __tr2qs("Need auth to speak and change nick"); break; + case 'N': return __tr2qs("Need auth to change nick"); break; + case 'O': return __tr2qs("IRC-Op only channel"); break; + case 'P': return __tr2qs("Persistent (staff only)"); break; + case 'Q': return __tr2qs("Disallow KICK (unless U-Line)"); break; + case 'R': return __tr2qs("Only registered nicks can join"); break; + case 'S': return __tr2qs("Strip colors"); break; + case 'T': return __tr2qs("Forbid channel NOTICEs"); break; + case 'a': return __tr2qs("Protected/admin nicks"); break; + case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; + case 'f': return __tr2qs("Kick/[*]ban on message flood ([*]:)"); break; + case 'g': return __tr2qs("Block message matching"); break; + case 'j': return __tr2qs("Join throttling (:)"); break; + case 'q': return __tr2qs("Channel owners"); break; + case 'u': return __tr2qs("Auditorium: /NAMES and /WHO show only ops"); break; + case 'y': return __tr2qs("Channel IRC op"); break; + case 'z': return __tr2qs("Need SSL connection to join"); break; + } + return KviBasicIrcServerInfo::getChannelModeDescription(mode); +} + +const QString & KviIrcdRatboxIrcServerInfo::getChannelModeDescription(char mode) +{ + switch(mode) + { + // not present of efnet, but supported by ratbox + case 'r': return __tr2qs("Only registered nicks can join"); break; + case 'S': return __tr2qs("Need SSL connection to join"); break; + } + return KviBasicIrcServerInfo::getChannelModeDescription(mode); +} + +const QString & KviSnircdIrcServerInfo::getChannelModeDescription(char mode) +{ + switch(mode) + { + case 'C': return __tr2qs("Forbid channel CTCPs"); break; + case 'D': return __tr2qs("Delay users join to first message"); break; + case 'M': return __tr2qs("Moderate non auth users"); break; + case 'N': return __tr2qs("Forbid channel NOTICEs"); break; + case 'R': return __tr2qs("Registered"); break; + case 'T': return __tr2qs("No multitarget messages"); break; + case 'd': return __tr2qs("Contains hidden users (previously +D)"); break; + case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; + case 'r': return __tr2qs("Only registered nicks can join"); break; + case 'u': return __tr2qs("Hide QUIT and PART messages"); break; + } + return KviBasicIrcServerInfo::getChannelModeDescription(mode); +} + +const QString & KviIrcuIrcServerInfo::getChannelModeDescription(char mode) +{ + switch(mode) + { + case 'D': return __tr2qs("Delay users join to first message"); break; + case 'R': return __tr2qs("Registered"); break; + case 'd': return __tr2qs("Contains hidden users (previously +D)"); break; + case 'r': return __tr2qs("Only registered nicks can join"); break; + } + return KviBasicIrcServerInfo::getChannelModeDescription(mode); +} + +const QString & KviPlexusIrcServerInfo::getChannelModeDescription(char mode) +{ + switch(mode) + { + case 'B': return __tr2qs("Bandwidth Saver"); break; + case 'M': return __tr2qs("Moderate non auth users"); break; + case 'N': return __tr2qs("Forbid channel NOTICEs"); break; + case 'O': return __tr2qs("IRC-Op only channel"); break; + case 'R': return __tr2qs("Only registered nicks can join"); break; + case 'S': return __tr2qs("Need SSL connection to join"); break; + case 'a': return __tr2qs("Protected/admin nicks"); break; + case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; + case 'h': return __tr2qs("Half-operators");break; + case 'p': return __tr2qs("Paranoia"); break; + case 'q': return __tr2qs("Channel owners"); break; + case 'z': return __tr2qs("Persistent (staff only)"); break; + } + return KviBasicIrcServerInfo::getChannelModeDescription(mode); +} diff --git a/src/kvirc/kernel/KviIrcConnectionServerInfo.h b/src/kvirc/kernel/KviIrcConnectionServerInfo.h new file mode 100644 index 000000000..d51989b90 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionServerInfo.h @@ -0,0 +1,241 @@ +#ifndef _KVI_IRCCONNECTIONSERVERINFO_H_ +#define _KVI_IRCCONNECTIONSERVERINFO_H_ +//============================================================================= +// +// File : KviIrcConnectionServerInfo.h +// Creation date : Tue 22 Jun 2004 03:57:32 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "kvi_inttypes.h" + +#include + +class KviIrcConnectionServerInfo; + +class KVIRC_API KviBasicIrcServerInfo +{ + //ircnet +protected: + QString m_szServerVersion; + KviIrcConnectionServerInfo * m_pParent; +public: + KviBasicIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty); + virtual ~KviBasicIrcServerInfo(); +public: + virtual const QString & getChannelModeDescription(char mode); + virtual const QString & getUserModeDescription(QChar mode); + virtual char getRegisterModeChar() { return 0; }; + virtual const char * getSoftware() { return "Ircd"; }; + virtual bool getNeedsOpToListModeseI() { return false; }; +}; + +class KVIRC_API KviUnrealIrcServerInfo : public KviBasicIrcServerInfo +{ +public: + KviUnrealIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 'r'; }; + virtual const char * getSoftware() { return "Unreal"; }; + virtual bool getNeedsOpToListModeseI() { return false; }; + virtual const QString & getChannelModeDescription(char mode); +}; + +class KVIRC_API KviBahamutIrcServerInfo : public KviBasicIrcServerInfo +{ + //dalnet, azzurranet +public: + KviBahamutIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 'r'; }; + virtual const char * getSoftware() { return "Bahamut"; }; + virtual bool getNeedsOpToListModeseI() { return false; }; + virtual const QString & getChannelModeDescription(char mode); +}; + +class KVIRC_API KviHyperionIrcServerInfo : public KviBasicIrcServerInfo +{ + // legacy freenode : no longer mantained +public: + KviHyperionIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 'e'; }; + virtual const char * getSoftware() { return "Hyperion"; }; + virtual bool getNeedsOpToListModeseI() { return true; }; +}; + +class KVIRC_API KviIrcdSevenIrcServerInfo : public KviBasicIrcServerInfo +{ + //freenode +public: + KviIrcdSevenIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 0; }; + virtual const char * getSoftware() { return "Ircd-seven"; }; + virtual bool getNeedsOpToListModeseI() { return true; }; + virtual const QString & getChannelModeDescription(char mode); +}; + +class KVIRC_API KviIrcdRatboxIrcServerInfo : public KviBasicIrcServerInfo +{ + //efnet +public: + KviIrcdRatboxIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 0; }; + virtual const char * getSoftware() { return "Ircd-ratbox"; }; + virtual bool getNeedsOpToListModeseI() { return true; }; + virtual const QString & getChannelModeDescription(char mode); +}; + +class KVIRC_API KviInspIRCdIrcServerInfo : public KviBasicIrcServerInfo +{ + //chatspike +public: + KviInspIRCdIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 'r'; }; + virtual const char * getSoftware() { return "InspIRCd"; }; + virtual bool getNeedsOpToListModeseI() { return true; }; + virtual const QString & getChannelModeDescription(char mode); +}; + +class KVIRC_API KviSnircdIrcServerInfo : public KviBasicIrcServerInfo +{ + //quakenet; note: snird is an extension to ircu +public: + KviSnircdIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 0; }; + virtual const char * getSoftware() { return "Snircd"; }; + virtual bool getNeedsOpToListModeseI() { return false; }; //modes eI doesn't exists + virtual const QString & getChannelModeDescription(char mode); +}; + +class KVIRC_API KviIrcuIrcServerInfo : public KviBasicIrcServerInfo +{ + //undernet +public: + KviIrcuIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 0; }; + virtual const char * getSoftware() { return "Ircu"; }; + virtual bool getNeedsOpToListModeseI() { return true; }; + virtual const QString & getChannelModeDescription(char mode); +}; + +class KVIRC_API KviPlexusIrcServerInfo : public KviBasicIrcServerInfo +{ + //rizon; note: plexus is an extension to hybrid +public: + KviPlexusIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) + :KviBasicIrcServerInfo(pParent, version) {;}; + virtual char getRegisterModeChar() { return 'r'; }; + virtual const char * getSoftware() { return "Plexus"; }; + virtual bool getNeedsOpToListModeseI() { return true; }; + virtual const QString & getChannelModeDescription(char mode); +}; + +class KVIRC_API KviIrcConnectionServerInfo +{ + friend class KviConsole; // for now + friend class KviIrcServerParser; + friend class KviIrcConnection; +protected: + KviIrcConnectionServerInfo(); + ~KviIrcConnectionServerInfo(); +private: + KviBasicIrcServerInfo * m_pServInfo; + QString m_szNetworkName; // the most actual network name (may be the one we specify or the one that the server reports) + QString m_szName; // the most actual server name (may be the one we specify or the one that the server wants to be known as) + QString m_szSupportedUserModes; // the supported user modes + QString m_szSupportedChannelModes; // the supported channel modes (all of them) + QString m_szSupportedModePrefixes; // the actually used mode prefixes @+ + kvi_u32_t * m_pModePrefixTable; // the mode prefixes above in a table + unsigned int m_uPrefixes; + QString m_szSupportedModeFlags; // the actually used mode flags ov + QString m_szSupportedChannelTypes; // the supported channel types + bool m_bSupportsWatchList; // supports the watch list ? + bool m_bSupportsCodePages; // supports the /CODEPAGE command ? + int m_iMaxTopicLen; + int m_iMaxModeChanges; + // Mode that adds or removes a nick or address to a list. Always has a parameter (eg: "b" as ban) + QString m_szListModes; + // Mode that changes a setting and always has a parameter (eg: "k" as channel key) + QString m_szParameterModes; + // Mode that changes a setting and only has a parameter when set (eg: "l" as channel limit) + QString m_szParameterWhenSetModes; + // Mode that changes a setting and never has a parameter (eg: "m" as channel moderated) + QString m_szPlainModes; + bool m_bSupportsCap; + QStringList m_lSupportedCaps; +public: + char registerModeChar() { return m_pServInfo ? m_pServInfo->getRegisterModeChar() : 0; }; + const char * software() { return m_pServInfo ? m_pServInfo->getSoftware() : 0; }; + bool getNeedsOpToListModeseI() { return m_pServInfo ? m_pServInfo->getNeedsOpToListModeseI() : false; }; + const QString & name() { return m_szName; }; + const QString & networkName() { return m_szNetworkName; }; + const QString & supportedUserModes() { return m_szSupportedUserModes; }; + const QString & supportedChannelModes() { return m_szSupportedChannelModes; }; + const QString & supportedChannelTypes() { return m_szSupportedChannelTypes; }; + const QString & supportedModePrefixes() { return m_szSupportedModePrefixes; }; + const QString & supportedModeFlags() { return m_szSupportedModeFlags; }; + const QString & supportedListModes() { return m_szListModes; }; + const QString & supportedParameterModes() { return m_szParameterModes; }; + const QString & supportedParameterWhenSetModes() { return m_szParameterWhenSetModes; }; + const QString & supportedPlainModes() { return m_szPlainModes; }; + bool supportsCap() { return m_bSupportsCap; }; + const QStringList & supportedCaps() { return m_lSupportedCaps; }; + bool supportsWatchList() { return m_bSupportsWatchList; }; + bool supportsCodePages() { return m_bSupportsCodePages; }; + + int maxTopicLen() { return m_iMaxTopicLen; }; + int maxModeChanges() { return m_iMaxModeChanges; }; + + void setServerVersion(const QString & version); + + const QString & getChannelModeDescription(char mode) { return m_pServInfo->getChannelModeDescription(mode); }; + const QString & getUserModeDescription(QChar mode) { return m_pServInfo->getUserModeDescription(mode); }; + + bool isSupportedModePrefix(QChar c); + bool isSupportedModeFlag(QChar c); + QChar modePrefixChar(kvi_u32_t flag); + QChar modeFlagChar(kvi_u32_t flag); + kvi_u32_t modeFlagFromPrefixChar(QChar c); + kvi_u32_t modeFlagFromModeChar(QChar c); +protected: + void setNetworkName(const QString &szName){ m_szNetworkName = szName; }; + void setName(const QString &szName) { m_szName = szName; }; + void setSupportedUserModes(const QString &szSupportedUserModes) { m_szSupportedUserModes = szSupportedUserModes; }; + void setSupportedChannelModes(const QString &szSupportedChannelModes); + void setSupportedModePrefixes(const QString &szSupportedModePrefixes,const QString &szSupportedModeFlags); + void setSupportedChannelTypes(const QString &szSupportedChannelTypes) { m_szSupportedChannelTypes = szSupportedChannelTypes; }; + void setSupportsWatchList(bool bSupportsWatchList) { m_bSupportsWatchList = bSupportsWatchList; }; + void setSupportsCodePages(bool bSupportsCodePages) { m_bSupportsCodePages = bSupportsCodePages; }; + void addSupportedCaps(const QString &szCapList); + void setMaxTopicLen(int iTopLen) { m_iMaxTopicLen=iTopLen; }; + void setMaxModeChanges(int iModes) { m_iMaxModeChanges=iModes; }; +private: + void buildModePrefixTable(); +}; + +#endif //!_KVI_IRCCONNECTIONSERVERINFO_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionStateData.cpp b/src/kvirc/kernel/KviIrcConnectionStateData.cpp new file mode 100644 index 000000000..aa0ae7425 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionStateData.cpp @@ -0,0 +1,91 @@ +//============================================================================= +// +// File : KviIrcConnectionStateData.cpp +// Creation date : Sat 26 Jun 2004 09:31:52 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionStateData.h" + +KviIrcConnectionStateData::KviIrcConnectionStateData() +{ + m_bSentStartTls = false; + m_bSentQuit = false; + m_bInsideInitialCapLs = false; + m_bInsideInitialCapReq = false; + m_bIgnoreOneYouHaveNotRegisteredError = false; + m_uLoginNickIndex = 0; + m_bSimulateUnexpectedDisconnect = false; + m_tLastReceivedChannelWhoReply = kvi_unixTime(); + m_tLastSentChannelWhoRequest = m_tLastReceivedChannelWhoReply; + m_tLastReceivedWhoisReply = 0; + m_bIdentifyMsgCapabilityEnabled = false; +} + +KviIrcConnectionStateData::~KviIrcConnectionStateData() +{ +} + +void KviIrcConnectionStateData::changeEnabledCapList(const QString &szCapList) +{ + QStringList lTmp = szCapList.split(' ',QString::SkipEmptyParts); + foreach(QString szCap,lTmp) + { + // cap modifiers are: + // '-' : disable a capability (should not be present in a LS message...) + // '=' : sticky (can't be disabled once enabled) + // '~' : needs ack for modification + + if(szCap.length() < 1) + continue; // shouldn't happen + + bool bRemove = false; + + switch(szCap[0].unicode()) + { + case '-': + bRemove = true; + // fall through + case '~': + case '=': + szCap.remove(0,1); + break; + default: + // ok + break; + } + + szCap = szCap.toLower(); + + if(szCap == "identify-msg") + m_bIdentifyMsgCapabilityEnabled = !bRemove; + + if(bRemove) + { + m_lEnabledCaps.removeAll(szCap); + } else { + if(!m_lEnabledCaps.contains(szCap)) + m_lEnabledCaps.append(szCap); + } + } +} + diff --git a/src/kvirc/kernel/KviIrcConnectionStateData.h b/src/kvirc/kernel/KviIrcConnectionStateData.h new file mode 100644 index 000000000..438b24436 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionStateData.h @@ -0,0 +1,109 @@ +#ifndef _KVI_IRCCONNECTIONSTATEDATA_H_ +#define _KVI_IRCCONNECTIONSTATEDATA_H_ +//============================================================================= +// +// File : KviIrcConnectionStateData.h +// Creation date : Sat 26 Jun 2004 09:31:52 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviTimeUtils.h" +#include "KviQString.h" + +#include + +// +// This class is used as container for miscelaneous connection state variables +// that do not have a class for their own. +// If you need to add some "minor" variable to the connection state then +// this is the right place for it. +// + +class KVIRC_API KviIrcConnectionStateData +{ + friend class KviIrcConnection; + friend class KviIrcServerParser; + friend class KviUserParser; +public: + KviIrcConnectionStateData(); + ~KviIrcConnectionStateData(); +protected: + bool m_bInsideInitialCapLs; // true if there's a CAP LS request pending + bool m_bIgnoreOneYouHaveNotRegisteredError; // true if we have sent a CAP LS request followed by a PING which will generate an error (and we need to ignore it) + bool m_bInsideInitialCapReq; // true if there's a CAP REQ request pending + bool m_bInsideAuthenticate; // true if there's a AUTHENTICATE request pending + bool m_bSentStartTls; // the state of STARTTLS protocol + bool m_bSentQuit; // have we sent the quit message for this connection ? + unsigned int m_uLoginNickIndex; // the index of the identity nicknames used until now (see KviIrcConnection::loginToIrcServer()) + QString m_szCommandToExecAfterConnect; // yes.. this is a special command to execute after connection + bool m_bSimulateUnexpectedDisconnect; // this is set to true if we have to simulate an unexpected disconnect even if we have sent a normal quit message + kvi_time_t m_tLastReceivedChannelWhoReply; // the time that we have received our last channel who reply + kvi_time_t m_tLastSentChannelWhoRequest; // the time that we have sent our last channel who request + kvi_time_t m_tLastReceivedWhoisReply; // the time that we have received the last whois reply, reset to 0 when we receive an /END OF WHOIS + QStringList m_lEnabledCaps; // the CAPs currently enabled + bool m_bIdentifyMsgCapabilityEnabled; // do we have the msg-identity CAP enabled ? +public: + const QStringList & enabledCaps(){ return m_lEnabledCaps; }; + void changeEnabledCapList(const QString &szCapList); + + bool identifyMsgCapabilityEnabled() const + { return m_bIdentifyMsgCapabilityEnabled; }; + + bool sentStartTls(){ return m_bSentStartTls; }; + void setSentStartTls(){ m_bSentStartTls = true; }; + + bool isInsideAuthenticate(){ return m_bInsideAuthenticate; }; + void setInsideAuthenticate(bool bInside){ m_bInsideAuthenticate = bInside; }; + + bool isInsideInitialCapLs(){ return m_bInsideInitialCapLs; }; + void setInsideInitialCapLs(bool bInside){ m_bInsideInitialCapLs = bInside; }; + + void setIgnoreOneYouHaveNotRegisteredError(bool bIgnore) + { m_bIgnoreOneYouHaveNotRegisteredError = bIgnore; }; + bool ignoreOneYouHaveNotRegisteredError() const + { return m_bIgnoreOneYouHaveNotRegisteredError; }; + + bool isInsideInitialCapReq(){ return m_bInsideInitialCapReq; }; + void setInsideInitialCapReq(bool bInside){ m_bInsideInitialCapReq = bInside; }; + + bool sentQuit(){ return m_bSentQuit; }; + void setSentQuit(){ m_bSentQuit = true; }; + + kvi_time_t lastReceivedChannelWhoReply(){ return m_tLastReceivedChannelWhoReply; }; + void setLastReceivedChannelWhoReply(kvi_time_t tTime){ m_tLastReceivedChannelWhoReply = tTime; }; + + kvi_time_t lastSentChannelWhoRequest(){ return m_tLastSentChannelWhoRequest; }; + void setLastSentChannelWhoRequest(kvi_time_t tTime){ m_tLastSentChannelWhoRequest = tTime; }; + + kvi_time_t lastReceivedWhoisReply(){ return m_tLastReceivedWhoisReply; }; + void setLastReceivedWhoisReply(kvi_time_t tTime){ m_tLastReceivedWhoisReply = tTime; }; + + bool simulateUnexpectedDisconnect(){ return m_bSimulateUnexpectedDisconnect; }; + void setSimulateUnexpectedDisconnect(bool bSimulate){ m_bSimulateUnexpectedDisconnect = bSimulate; }; + + unsigned int loginNickIndex(){ return m_uLoginNickIndex; }; + void setLoginNickIndex(unsigned int uNickIdx){ m_uLoginNickIndex = uNickIdx; }; + + const QString & commandToExecAfterConnect(){ return m_szCommandToExecAfterConnect; }; + void setCommandToExecAfterConnect(const QString &szCmd){ m_szCommandToExecAfterConnect = szCmd; }; +}; + +#endif //!_KVI_IRCCONNECTIONSTATEDATA_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionStatistics.cpp b/src/kvirc/kernel/KviIrcConnectionStatistics.cpp new file mode 100644 index 000000000..188be6184 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionStatistics.cpp @@ -0,0 +1,38 @@ +//============================================================================= +// +// File : KviIrcConnectionStatistics.cpp +// Creation date : Sun 27 Jun 2004 21:13:48 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionStatistics.h" + +KviIrcConnectionStatistics::KviIrcConnectionStatistics() +{ + m_tConnectionStart = 0; + m_tLastMessage = 0; +} + +KviIrcConnectionStatistics::~KviIrcConnectionStatistics() +{ +} + diff --git a/src/kvirc/kernel/KviIrcConnectionStatistics.h b/src/kvirc/kernel/KviIrcConnectionStatistics.h new file mode 100644 index 000000000..9b211d5ca --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionStatistics.h @@ -0,0 +1,50 @@ +#ifndef _KVI_IRCCONNECTIONSTATISTICS_H_ +#define _KVI_IRCCONNECTIONSTATISTICS_H_ +//============================================================================= +// +// File : KviIrcConnectionStatistics.h +// Creation date : Sun 27 Jun 2004 21:13:48 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviTimeUtils.h" + + +class KVIRC_API KviIrcConnectionStatistics +{ + friend class KviConsole; // to be removed + friend class KviIrcConnection; +public: + KviIrcConnectionStatistics(); + ~KviIrcConnectionStatistics(); +protected: + kvi_time_t m_tConnectionStart; // (valid only when Connected or LoggingIn) + kvi_time_t m_tLastMessage; // last message received from server +public: + kvi_time_t connectionStartTime(){ return m_tConnectionStart; }; + kvi_time_t lastMessageTime(){ return m_tLastMessage; }; +protected: + void setLastMessageTime(kvi_time_t t){ m_tLastMessage = t; }; + void setConnectionStartTime(kvi_time_t t){ m_tConnectionStart = t; }; +}; + +#endif //!_KVI_IRCCONNECTIONSTATISTICS_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionTarget.cpp b/src/kvirc/kernel/KviIrcConnectionTarget.cpp new file mode 100644 index 000000000..ccdc7783e --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionTarget.cpp @@ -0,0 +1,72 @@ +//============================================================================= +// +// File : KviIrcConnectionTarget.cpp +// Creation date : Tue 08 Jun 2004 14:11:59 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionTarget.h" +#include "KviIrcServer.h" +#include "KviIrcNetwork.h" +#include "KviProxyDataBase.h" + +KviIrcConnectionTarget::KviIrcConnectionTarget( + const KviIrcNetwork * pNetwork, + const KviIrcServer * pServer, + const KviProxy * pProxy, + const QString &szBindAddress + ) +{ + m_pNetwork = new KviIrcNetwork(*pNetwork); + m_pServer = new KviIrcServer(*pServer); + m_pProxy = pProxy ? new KviProxy(*pProxy) : NULL; + m_szBindAddress = szBindAddress; +} + +KviIrcConnectionTarget::~KviIrcConnectionTarget() +{ + delete m_pNetwork; + delete m_pServer; + if(m_pProxy) + delete m_pProxy; +} + +#if 0 +const QString & KviIrcConnectionTarget::networkName() +{ + return m_pNetwork->name(); +} + +void KviIrcConnectionTarget::setNetworkName(const QString &szNetName) +{ + m_pNetwork->setName(szNetName); +} +#endif + + +void KviIrcConnectionTarget::clearProxy() +{ + if(!m_pProxy)return; + delete m_pProxy; + m_pProxy = 0; +} + diff --git a/src/kvirc/kernel/KviIrcConnectionTarget.h b/src/kvirc/kernel/KviIrcConnectionTarget.h new file mode 100644 index 000000000..a07baa91d --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionTarget.h @@ -0,0 +1,100 @@ +#ifndef _KVI_IRCCONNECTIONTARGET_H_ +#define _KVI_IRCCONNECTIONTARGET_H_ +//============================================================================= +// +// File : KviIrcConnectionTarget.h +// Creation date : Tue 08 Jun 2004 14:11:59 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviHeapObject.h" + +class KviIrcNetwork; +class KviIrcServer; +class KviProxy; + +class KVIRC_API KviIrcConnectionTarget : public KviHeapObject +{ + friend class KviIrcConnectionTargetResolver; +public: + // pServer is a shallow pointer: this class makes a copy of it internally, must NOT be null + // pProxy may be null if a proxy is not desired. this class makes a copy of it internally + KviIrcConnectionTarget( + const KviIrcNetwork * pNetwork, + const KviIrcServer * pServer, + const KviProxy * pProxy = 0, + const QString &szBindAddress = QString() + ); + ~KviIrcConnectionTarget(); +private: + KviIrcNetwork * m_pNetwork; // owned, never null, it's a COPY of the entry in the db + KviIrcServer * m_pServer; // owned, never null, it's a COPY of the entry in the db + KviProxy * m_pProxy; // owned, may be null, it's a COPY of the entry in the db + QString m_szBindAddress; // forced bind address + +public: + + KviIrcServer * server() + { + return m_pServer; + } + + KviIrcNetwork * network() + { + return m_pNetwork; + } + + KviProxy * proxy() + { + return m_pProxy; + } + + const QString & bindAddress() + { + return m_szBindAddress; + } + + bool hasBindAddress() + { + return (!m_szBindAddress.isEmpty()); + } + +#if 0 + const QString & networkName(); + + // this allows to force the network name: it should be used only by KviConsole + // but it's KviIrcServerParser (KviIrcServerParser_numericHandlers.cpp) that first + // gets the new network name... thus we make it public + // to remove one level of indirection. + void setNetworkName(const QString &szNetName); +#endif + +protected: + // this is for KviIrcConnectionTargetResolver only + void clearProxy(); + void setBindAddress(const QString &szBindAddress) + { + m_szBindAddress = szBindAddress; + } +}; + +#endif //!_KVI_IRCCONNECTIONTARGET_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionTargetResolver.cpp b/src/kvirc/kernel/KviIrcConnectionTargetResolver.cpp new file mode 100644 index 000000000..27b36e365 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionTargetResolver.cpp @@ -0,0 +1,583 @@ +//============================================================================= +// +// File : KviIrcConnectionTargetResolver.cpp +// Creation date : Fri May 11 23:24:18 2002 GMT by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviIrcConnectionTargetResolver.h" +#include "KviDnsResolver.h" +#include "KviLocale.h" +#include "KviIrcServerDataBase.h" +#include "KviProxyDataBase.h" +#include "KviError.h" +#include "kvi_out.h" +#include "KviOptions.h" +#include "KviIrcSocket.h" +#include "KviConsoleWindow.h" +#include "KviNetUtils.h" +#include "KviInternalCommand.h" +#include "KviMainWindow.h" +#include "KviMexLinkFilter.h" +//#include "kvi_garbage.h" +#include "KviMemory.h" +#include "KviMemory.h" +#include "kvi_debug.h" +#include "KviIrcConnection.h" +#include "KviIrcConnectionTarget.h" +#include "KviIrcSocket.h" +#include "KviError.h" +#include "kvi_debug.h" + +#include + +#include + +extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; +extern KVIRC_API KviProxyDataBase * g_pProxyDataBase; +//extern KVIRC_API KviGarbageCollector * g_pGarbageCollector; + + + +KviIrcConnectionTargetResolver::KviIrcConnectionTargetResolver(KviIrcConnection * pConnection) +: QObject() +{ + m_pConnection = pConnection; + m_pTarget = 0; + m_pConsole = m_pConnection->console(); + + m_pStartTimer = 0; + m_pProxyDns = 0; + m_pServerDns = 0; + + m_eState = Idle; + m_eStatus = Success; + + m_iLastError = KviError_success; +} + +KviIrcConnectionTargetResolver::~KviIrcConnectionTargetResolver() +{ + cleanup(); +} + +void KviIrcConnectionTargetResolver::cleanup() +{ + if(m_pProxyDns) + { + if(m_pProxyDns->isRunning()) + { + // deleting a running dns may block + // thus garbage-collect it and delete later + //g_pGarbageCollector->collect(m_pProxyDns); + m_pProxyDns->deleteLater(); + } else { + // can't block : just delete it + delete m_pProxyDns; + } + m_pProxyDns = 0; + } + if(m_pServerDns) + { + if(m_pServerDns->isRunning()) + { + // deleting a running dns may block + // thus garbage-collect it and delete later + //g_pGarbageCollector->collect(m_pServerDns); + m_pServerDns->deleteLater(); + } else { + // can't block : just delete it + delete m_pServerDns; + } + m_pServerDns = 0; + } + if(m_pStartTimer) + { + delete m_pStartTimer; + m_pStartTimer = 0; + } +} + +void KviIrcConnectionTargetResolver::start(KviIrcConnectionTarget * t) +{ + KVI_ASSERT(m_eState == Idle); + + m_eState = Running; + + if(m_pStartTimer) // this should never happen I guess + { + delete m_pStartTimer; + m_pStartTimer = 0; + } + m_pStartTimer = new QTimer(this); + connect(m_pStartTimer,SIGNAL(timeout()),this,SLOT(asyncStartResolve())); + + m_pTarget = t; + + m_pStartTimer->start(0); +} + +void KviIrcConnectionTargetResolver::abort() +{ + cleanup(); // do a cleanup to kill the timers and dns slaves + + if(m_eState == Terminated)return; + + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR,__tr2qs("Hostname resolution aborted")); + terminate(Error,KviError_operationAborted); +} + +void KviIrcConnectionTargetResolver::asyncStartResolve() +{ + if(m_pStartTimer) + { + delete m_pStartTimer; + m_pStartTimer = 0; + } + + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Attempting %Q to %Q (%Q) on port %u"), + m_pTarget->server()->useSSL() ? &(__tr2qs("secure connection")) : &(__tr2qs("connection")), + &(m_pTarget->server()->m_szHostname), + &(m_pTarget->network()->name()), + m_pTarget->server()->m_uPort); + + if(m_pTarget->proxy()) + { + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Attempting to 'bounce' on proxy %s on port %u (protocol %s)"), + m_pTarget->proxy()->m_szHostname.toUtf8().data(), + m_pTarget->proxy()->m_uPort, + m_pTarget->proxy()->protocolName().toUtf8().data()); + + lookupProxyHostname(); + } else { + lookupServerHostname(); + } +} + +void KviIrcConnectionTargetResolver::lookupProxyHostname() +{ + bool bValidIp; +#ifdef COMPILE_IPV6_SUPPORT + if(m_pTarget->proxy()->isIPv6()) + { + bValidIp = KviNetUtils::isValidStringIPv6(m_pTarget->proxy()->m_szIp); + } else { +#endif + bValidIp = KviNetUtils::isValidStringIp(m_pTarget->proxy()->m_szIp); +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + + if(bValidIp) + { + if(!_OUTPUT_QUIET) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Using cached proxy IP address (%s)"), + m_pTarget->proxy()->m_szIp.toUtf8().data()); + if(m_pTarget->proxy()->protocol() != KviProxy::Http + && m_pTarget->proxy()->protocol() != KviProxy::Socks5) + lookupServerHostname(); + else terminate(Success,KviError_success); + } else { +#ifdef COMPILE_IPV6_SUPPORT + if(m_pTarget->proxy()->isIPv6()) + { + bValidIp = KviNetUtils::isValidStringIPv6(m_pTarget->proxy()->m_szHostname); + } else { +#endif + bValidIp = KviNetUtils::isValidStringIp(m_pTarget->proxy()->m_szHostname); +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + if(bValidIp) + { + m_pTarget->proxy()->m_szIp=m_pTarget->proxy()->m_szHostname; + if(m_pTarget->proxy()->protocol() != KviProxy::Http && + m_pTarget->proxy()->protocol() != KviProxy::Socks5) + { + lookupServerHostname(); + } else { + terminate(Success,KviError_success); + } + } else { + + if(m_pProxyDns) + { + qDebug("Something weird is happening, m_pProxyDns is non-zero in lookupProxyHostname()"); + delete m_pProxyDns; + m_pProxyDns = 0; + } + + m_pProxyDns = new KviDnsResolver(); + connect(m_pProxyDns,SIGNAL(lookupDone(KviDnsResolver *)),this,SLOT(proxyLookupTerminated(KviDnsResolver *))); + + if(!m_pProxyDns->lookup(m_pTarget->proxy()->m_szHostname, + m_pTarget->proxy()->isIPv6() ? KviDnsResolver::IPv6 : KviDnsResolver::IPv4)) + { + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMWARNING, + __tr2qs("Unable to look up the IRC proxy hostname: Can't start the DNS slave")); + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMWARNING, + __tr2qs("Resuming direct server connection")); + // FIXME: #warning "Option for resuming direct connection or not ?" + delete m_pProxyDns; + m_pProxyDns = 0; + m_pTarget->clearProxy(); + lookupServerHostname(); + } else { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Looking up the proxy hostname (%s)..."), + m_pTarget->proxy()->m_szHostname.toUtf8().data()); + } + } + } +} + +void KviIrcConnectionTargetResolver::proxyLookupTerminated(KviDnsResolver *) +{ + if(m_pProxyDns->state() != KviDnsResolver::Success) + { + QString szErr = KviError::getDescription(m_pProxyDns->error()); + m_pConsole->output(KVI_OUT_SYSTEMERROR, + __tr2qs("Can't find the proxy IP address: %Q"), + &szErr); + // FIXME: #warning "Option to resume the direct connection if proxy failed ?" + m_pConsole->output(KVI_OUT_SYSTEMERROR, + __tr2qs("Resuming direct server connection")); + m_pTarget->clearProxy(); + } else { + QString szFirstIpAddress = m_pProxyDns->firstIpAddress(); + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Proxy hostname resolved to %Q"),&szFirstIpAddress); + + m_pTarget->proxy()->m_szIp = m_pProxyDns->firstIpAddress(); + g_pProxyDataBase->updateProxyIp(m_pTarget->proxy()->m_szIp.toUtf8().data(),szFirstIpAddress.toUtf8().data()); + + if(m_pProxyDns->hostnameCount() > 1) + { + QString szFirstHostname = m_pProxyDns->firstHostname(); + + for(QString * addr = m_pProxyDns->hostnameList()->next();addr;addr = m_pProxyDns->hostnameList()->next()) + { + if(!_OUTPUT_QUIET) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Proxy %Q has a nickname: %Q"),&szFirstHostname,addr); + } + } + } + + delete m_pProxyDns; + m_pProxyDns = 0; + if(m_pTarget->proxy()) + { + if(m_pTarget->proxy()->protocol() == KviProxy::Http + || m_pTarget->proxy()->protocol() == KviProxy::Socks5) + { + terminate(Success,KviError_success); + return; + } + } + lookupServerHostname(); +} + +void KviIrcConnectionTargetResolver::lookupServerHostname() +{ + bool bValidIp; + +#ifdef COMPILE_IPV6_SUPPORT + if(m_pTarget->server()->isIPv6()) + { + bValidIp = KviNetUtils::isValidStringIPv6(m_pTarget->server()->m_szIp); + } else { +#endif + bValidIp = KviNetUtils::isValidStringIp(m_pTarget->server()->m_szIp); +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + + if(bValidIp && m_pTarget->server()->cacheIp()) + { + if(!_OUTPUT_QUIET) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Using cached server IP address (%s)"), + m_pTarget->server()->m_szIp.toUtf8().data()); + haveServerIp(); + } else { +#ifdef COMPILE_IPV6_SUPPORT + if(m_pTarget->server()->isIPv6()) + { + bValidIp = KviNetUtils::isValidStringIPv6(m_pTarget->server()->m_szHostname); + } else { +#endif + bValidIp = KviNetUtils::isValidStringIp(m_pTarget->server()->m_szHostname); +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + if(bValidIp) + { + m_pTarget->server()->m_szIp=m_pTarget->server()->m_szHostname; + haveServerIp(); + } else { + if(m_pServerDns) + { + qDebug("Something weird is happening, m_pServerDns is non-zero in lookupServerHostname()"); + delete m_pServerDns; + m_pServerDns = 0; + } + m_pServerDns = new KviDnsResolver(); + connect(m_pServerDns,SIGNAL(lookupDone(KviDnsResolver *)),this, + SLOT(serverLookupTerminated(KviDnsResolver *))); + if(!m_pServerDns->lookup(m_pTarget->server()->m_szHostname, + m_pTarget->server()->isIPv6() ? KviDnsResolver::IPv6 : KviDnsResolver::IPv4)) + { + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR, + __tr2qs("Unable to look up the server hostname: Can't start the DNS slave")); + terminate(Error,KviError_internalError); + } else { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Looking up the server hostname (%s)..."), + m_pTarget->server()->m_szHostname.toUtf8().data()); + } + } + } +} + + +void KviIrcConnectionTargetResolver::serverLookupTerminated(KviDnsResolver *) +{ + if(m_pServerDns->state() != KviDnsResolver::Success) + { + QString szErr = KviError::getDescription(m_pServerDns->error()); + m_pConsole->output(KVI_OUT_SYSTEMERROR, + __tr2qs("Can't find the server IP address: %Q"), + &szErr); + +#ifdef COMPILE_IPV6_SUPPORT + if(!(m_pTarget->server()->isIPv6())) + { + m_pConsole->output(KVI_OUT_SYSTEMERROR, + __tr2qs("If this server is an IPv6 one, try /server -i %Q"), + &(m_pTarget->server()->m_szHostname)); + } +#endif + terminate(Error,m_pServerDns->error()); + return; + } + + QString szIpAddress; + + if(m_pServerDns->ipAddressCount() > 1) + { + if(KVI_OPTION_BOOL(KviOption_boolPickRandomIpAddressForRoundRobinServers)) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Server has %d IP addresses, picking a random one"), + m_pServerDns->ipAddressCount() + ); + + int r = ::rand() % m_pServerDns->ipAddressCount(); + szIpAddress = *(m_pServerDns->ipAddressList()->at(r)); + } else { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Server has %d IP addresses, using the first one"), + m_pServerDns->ipAddressCount() + ); + szIpAddress = m_pServerDns->firstIpAddress(); + } + } else { + szIpAddress = m_pServerDns->firstIpAddress(); + } + + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Server hostname resolved to %Q"), + &szIpAddress); + m_pTarget->server()->setIp(szIpAddress); + + QString szFirstHostname = m_pServerDns->firstHostname(); + + if(!KviQString::equalCI(m_pTarget->server()->m_szHostname,m_pServerDns->firstHostname())) + { + if(!_OUTPUT_QUIET) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Real hostname for %Q is %Q"), + &(m_pTarget->server()->m_szHostname), + &szFirstHostname); + m_pTarget->server()->m_szHostname = szFirstHostname; + } + + m_pTarget->server()->m_szIp = szIpAddress; + + if(m_pServerDns->hostnameCount() > 1) + { + for(QString * addr = m_pServerDns->hostnameList()->next();addr;addr = m_pServerDns->hostnameList()->next()) + { + if(!_OUTPUT_QUIET) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Server %Q has a nickname: %Q"), + &szFirstHostname,addr); + } + } + + delete m_pServerDns; + m_pServerDns = 0; + haveServerIp(); +} + +bool KviIrcConnectionTargetResolver::validateLocalAddress(const QString &szAddress,QString &szBuffer) +{ + // szAddress may be an ip address or an interface name +#ifdef COMPILE_IPV6_SUPPORT + if(m_pTarget->server()->isIPv6()) + { + if(KviNetUtils::isValidStringIPv6(szAddress)) + { + szBuffer = szAddress; + return true; + } + } else { +#endif + if(KviNetUtils::isValidStringIp(szAddress)) + { + szBuffer = szAddress; + return true; + } +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + + // is it an interface name ? + return KviNetUtils::getInterfaceAddress(szAddress,szBuffer); +} + + +void KviIrcConnectionTargetResolver::haveServerIp() +{ + if(KVI_OPTION_BOOL(KviOption_boolUseIdentService) && !KVI_OPTION_BOOL(KviOption_boolUseIdentServiceOnlyOnConnect)) + m_pConsole->frame()->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_START); + + QString bindAddress; + + if(m_pTarget->hasBindAddress()) + { + if(!validateLocalAddress(m_pTarget->bindAddress(),bindAddress)) + { + QString szBindAddress = m_pTarget->bindAddress(); + if((szBindAddress.indexOf('.') != -1) || + (szBindAddress.indexOf(':') != -1)) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("The specified bind address (%Q) is not valid"), + &szBindAddress); + } else { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("The specified bind address (%Q) is not valid (the interface it refers to might be down)"), + &(szBindAddress)); + } + } + } else { + // the options specify a bind address ? +#ifdef COMPILE_IPV6_SUPPORT + if(m_pTarget->server()->isIPv6()) + { + if(KVI_OPTION_BOOL(KviOption_boolBindIrcIPv6ConnectionsToSpecifiedAddress)) + { + if(!KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress).isEmpty()) + { + if(!validateLocalAddress(KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress),bindAddress)) + { + // if it is not an interface name, kill it for now and let the user correct the address + if(KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress).indexOf(':') != -1) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("The system-wide IPv6 bind address (%s) is not valid"), + KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress).toUtf8().data()); + KVI_OPTION_BOOL(KviOption_boolBindIrcIPv6ConnectionsToSpecifiedAddress) = false; + } else { + // this is an interface address: might be down + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("The system-wide IPv6 bind address (%s) is not valid (the interface it refers to might be down)"), + KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress).toUtf8().data()); + } + } + } else { + // empty address....kill it + KVI_OPTION_BOOL(KviOption_boolBindIrcIPv6ConnectionsToSpecifiedAddress) = false; + } + } + } else { +#endif + if(KVI_OPTION_BOOL(KviOption_boolBindIrcIPv4ConnectionsToSpecifiedAddress)) + { + if(!KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress).isEmpty()) + { + if(!validateLocalAddress(KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress),bindAddress)) + { + // if it is not an interface name, kill it for now and let the user correct the address + if(KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress).indexOf(':') != -1) + { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("The system-wide IPv4 bind address (%s) is not valid"), + KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress).toUtf8().data()); + KVI_OPTION_BOOL(KviOption_boolBindIrcIPv4ConnectionsToSpecifiedAddress) = false; + } else { + // this is an interface address: might be down + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("The system-wide IPv4 bind address (%s) is not valid (the interface it refers to might be down)"), + KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress).toUtf8().data()); + } + } + } else { + // empty address....kill it + KVI_OPTION_BOOL(KviOption_boolBindIrcIPv4ConnectionsToSpecifiedAddress) = false; + } + } +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + } + + m_pTarget->setBindAddress(bindAddress); + terminate(Success,KviError_success); +} + +void KviIrcConnectionTargetResolver::terminate(Status s,int iLastError) +{ + KVI_ASSERT(m_eState != Terminated); + cleanup(); // do a cleanup anyway + m_eState = Terminated; + m_eStatus = s; + m_iLastError = iLastError; + emit terminated(); +} diff --git a/src/kvirc/kernel/KviIrcConnectionTargetResolver.h b/src/kvirc/kernel/KviIrcConnectionTargetResolver.h new file mode 100644 index 000000000..ddc6021b0 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionTargetResolver.h @@ -0,0 +1,89 @@ +#ifndef _KVI_IRCCONNECTIONTARGETRESOLVER_H_ +#define _KVI_IRCCONNECTIONTARGETRESOLVER_H_ +//============================================================================= +// +// File : KviIrcConnectionTargetResolver.h +// Creation date : Fri 11 May 2004 23:17:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" + +#include + +class KviConsole; +class KviDnsResolver; +class KviIrcConnection; +class KviIrcConnectionTarget; + +class QTimer; + +class KVIRC_API KviIrcConnectionTargetResolver : public QObject +{ + friend class KviIrcLink; // upper protocol in the stack + Q_OBJECT +protected: + KviIrcConnectionTargetResolver(KviIrcConnection * pConnection); + ~KviIrcConnectionTargetResolver(); +public: + enum Status { Success, Error }; + enum State { Idle, Running, Terminated }; +private: + KviIrcConnection * m_pConnection; // shallow, never null + KviIrcConnectionTarget * m_pTarget; // shallow, never null + KviConsole * m_pConsole; // shallow, never null + Status m_eStatus; + State m_eState; + + // Auxiliary stuff + QTimer * m_pStartTimer; // timer used to start the connection + KviDnsResolver * m_pProxyDns; // the dns object for the proxy hostnames + KviDnsResolver * m_pServerDns; // the dns object for the server hostnames + + char * m_pReadBuffer; + unsigned int m_uReadBufferLen; + unsigned int m_uReadPackets; + + int m_iLastError; +public: + void start(KviIrcConnectionTarget * t); + // valid only after the terminated() signal + Status status(){ return m_eStatus; }; + int lastError(){ return m_iLastError; }; + // causes the resolver to terminate with iLastError == KviError_operationAborted + // the terminated() signal is emitted. + void abort(); +protected slots: + void asyncStartResolve(); + void serverLookupTerminated(KviDnsResolver *); + void proxyLookupTerminated(KviDnsResolver *); +private: + void cleanup(); + void lookupProxyHostname(); + void lookupServerHostname(); + void haveServerIp(); + bool validateLocalAddress(const QString &szAddress,QString &szBuffer); + void terminate(Status s,int iLastError); +signals: + void terminated(); +}; + +#endif //!_KVI_IRCCONNECTIONTARGETRESOLVER_H_ diff --git a/src/kvirc/kernel/KviIrcConnectionUserInfo.cpp b/src/kvirc/kernel/KviIrcConnectionUserInfo.cpp new file mode 100644 index 000000000..64201db59 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionUserInfo.cpp @@ -0,0 +1,65 @@ +//============================================================================= +// +// File : KviIrcConnectionUserInfo.cpp +// Creation date : Sun 20 Jun 2004 01:45:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionUserInfo.h" + +KviIrcConnectionUserInfo::KviIrcConnectionUserInfo() +{ + m_bAway = false; +} + +bool KviIrcConnectionUserInfo::hasUserMode(const QChar &m) +{ + return m_szUserMode.contains(m) > 0; +} + +bool KviIrcConnectionUserInfo::addUserMode(const QChar &m) +{ + if(hasUserMode(m))return false; + m_szUserMode.append(m); + return true; +} + +bool KviIrcConnectionUserInfo::removeUserMode(const QChar &m) +{ + int idx = m_szUserMode.indexOf(m,0); + if(idx == -1)return false; + m_szUserMode.replace(m,QString("")); + return true; +} + +void KviIrcConnectionUserInfo::setAway() +{ + m_szNickBeforeAway = m_szNickName; + m_tAway = kvi_unixTime(); + m_bAway = true; +} + +void KviIrcConnectionUserInfo::setBack() +{ + m_szNickBeforeAway = ""; + m_bAway = false; +} diff --git a/src/kvirc/kernel/KviIrcConnectionUserInfo.h b/src/kvirc/kernel/KviIrcConnectionUserInfo.h new file mode 100644 index 000000000..233e1a6b2 --- /dev/null +++ b/src/kvirc/kernel/KviIrcConnectionUserInfo.h @@ -0,0 +1,91 @@ +#ifndef _KVI_IRCCONNECTIONUSERINFO_H_ +#define _KVI_IRCCONNECTIONUSERINFO_H_ +//============================================================================= +// +// File : KviIrcConnectionUserInfo.h +// Creation date : Sun 20 Jun 2004 01:45:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviTimeUtils.h" + +class KVIRC_API KviIrcConnectionUserInfo +{ + friend class KviIrcConnection; + friend class KviIrcServerParser; + friend class KviConsole; +protected: + KviIrcConnectionUserInfo(); + ~KviIrcConnectionUserInfo(){}; +private: + QString m_szRealName; // the actual real name sent from the server + QString m_szNickName; // the actual nick name acknowledged by the server + QString m_szPassword; // the password used connecting to the server + QString m_szUserMode; // the actual user mode + QString m_szUserName; // user name with ident char + QString m_szLocalHostIp; // the local host ip as found by resolveLocalHost() at connection startup + QString m_szHostName; // the local host name that the server reports + QString m_szHostIp; // the host name above resolved, if possible + QString m_szAwayReason; + bool m_bAway; // is the user away ? + kvi_time_t m_tAway; // time at that the user went away + QString m_szNickBeforeAway; // the nickname that the user had just before going away + // From bugtrack: + // On many IRC networks the host is masked or hashed, and if one also is connected through a LAN, + // it is basically impossible to initiate DCC transfers, as 192.168.0.13 or similar will be sent as IP. + // But IRC servers usually (at least in my experience) send the unmasked host in the 001 raw event + // with something like ":Welcome to the Internet Relay Chat network, nick!ident@host". I think + // it'd be a good idea to just grab the IP from that event and use it for DCC transfers by default. + QString m_szUnmaskedHostName; +public: + const QString & realName(){ return m_szRealName; }; + const QString & nickName(){ return m_szNickName; }; + const QString & userMode(){ return m_szUserMode; }; + const QString & userName(){ return m_szUserName; }; + const QString & password(){ return m_szPassword; }; + const QString & localHostIp(){ return m_szLocalHostIp; }; + const QString & hostName(){ return m_szHostName; }; + const QString & unmaskedHostName(){ return m_szUnmaskedHostName; }; + const QString & hostIp(){ return m_szHostIp; }; + const QString & awayReason() { return m_szAwayReason; }; + bool hasUserMode(const QChar & m); + bool isAway(){ return m_bAway; }; + time_t awayTime(){ return m_tAway; }; + const QString & nickNameBeforeAway(){ return m_szNickBeforeAway; }; +protected: + void setRealName(const QString &szRealName){ m_szRealName = szRealName; }; + void setNickName(const QString &szNickName){ m_szNickName = szNickName; }; + void setUserMode(const QString &szUserMode){ m_szUserMode = szUserMode; }; + void setUserName(const QString &szUserName){ m_szUserName = szUserName; }; + void setPassword(const QString &szPassword){ m_szPassword = szPassword; }; + void setHostName(const QString &szHostName){ m_szHostName = szHostName; }; + void setUnmaskedHostName(const QString &szHostName){ m_szUnmaskedHostName = szHostName; }; + void setHostIp(const QString &szHostIp){ m_szHostIp = szHostIp; }; + void setLocalHostIp(const QString &szLocalHostIp){ m_szLocalHostIp = szLocalHostIp; }; + bool addUserMode(const QChar &m); // returns false if the mode was already there + bool removeUserMode(const QChar &m); // returns fales if the mode was not there + void setAwayReason(const QString& szReazon) { m_szAwayReason=szReazon; }; + void setAway(); + void setBack(); +}; + +#endif //!_KVI_IRCCONNECTIONUSERINFO_H_ diff --git a/src/kvirc/kernel/KviIrcContext.cpp b/src/kvirc/kernel/KviIrcContext.cpp new file mode 100644 index 000000000..e517ad317 --- /dev/null +++ b/src/kvirc/kernel/KviIrcContext.cpp @@ -0,0 +1,926 @@ +//============================================================================= +// +// File : KviIrcContext.cpp +// Creation date : Sun 09 May 2004 20:37:46 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcContext.h" +#include "KviConsoleWindow.h" +#include "KviChannelWindow.h" +#include "KviQueryWindow.h" +#include "KviMainWindow.h" +#include "kvi_debug.h" +#include "KviIrcServerParser.h" +#include "KviIrcLink.h" +#include "KviIrcConnection.h" +#include "KviIrcConnectionTarget.h" +#include "KviAsynchronousConnectionData.h" +#include "KviIrcConnectionStateData.h" +#include "KviIrcConnectionUserInfo.h" +#include "KviIrcConnectionRequestQueue.h" +#include "KviIrcToolBar.h" +#include "kvi_out.h" +#include "KviIrcServerDataBase.h" +#include "KviProxyDataBase.h" +#include "KviOptions.h" +#include "KviLocale.h" +#include "KviIrcDataStreamMonitor.h" +#include "KviError.h" +#include "KviThread.h" // for KviThread::msleep() +#include "KviApplication.h" +#include "KviKvsEventTriggers.h" +#include "KviKvsScript.h" +#include "KviNetUtils.h" +#include "KviIrcUrl.h" +#include "KviUserIdentity.h" + +#define __KVI_DEBUG__ +#include "kvi_debug.h" + +#include +#include + +// the irc context identifiers start from 1 +static unsigned int g_uNextIrcContextId = 1; + +extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; +extern KVIRC_API KviProxyDataBase * g_pProxyDataBase; + + +KviIrcContext::KviIrcContext(KviConsole * pConsole) +: QObject(0) +{ + m_uId = g_uNextIrcContextId; + g_uNextIrcContextId++; + + m_pConsole = pConsole; + + m_pConnection = 0; + + m_pFrame = m_pConsole->frame(); + + m_pDeadChannels = 0; + m_pDeadQueries = 0; + m_pContextWindows = 0; + + m_pLinksWindow = 0; + m_pListWindow = 0; + + m_eState = Idle; + + m_pAsynchronousConnectionData = 0; + m_pSavedAsynchronousConnectionData = 0; + m_uConnectAttemptCount = 0; + m_pMonitorList = 0; + m_pReconnectTimer = 0; + + m_uConnectAttemptCount = 1; + + m_iHeartbeatTimerId = startTimer(5000); +} + +KviIrcContext::~KviIrcContext() +{ + killTimer(m_iHeartbeatTimerId); + + while(m_pMonitorList) + { + KviIrcDataStreamMonitor * m = m_pMonitorList->first(); + if(m)m->die(); + else { + delete m_pMonitorList; + m_pMonitorList = 0; + } + } + + if(m_pReconnectTimer)delete m_pReconnectTimer; + + if(m_pLinksWindow)m_pLinksWindow->die(); + if(m_pListWindow)m_pListWindow->die(); + + closeAllDeadChannels(); + closeAllDeadQueries(); + closeAllContextWindows(); + + destroyConnection(); + if(m_pAsynchronousConnectionData)delete m_pAsynchronousConnectionData; + if(m_pSavedAsynchronousConnectionData)delete m_pSavedAsynchronousConnectionData; +} + +void KviIrcContext::registerDataStreamMonitor(KviIrcDataStreamMonitor * m) +{ + if(!m_pMonitorList) + { + m_pMonitorList = new KviPointerList; + m_pMonitorList->setAutoDelete(false); + } + m_pMonitorList->append(m); +} + +void KviIrcContext::unregisterDataStreamMonitor(KviIrcDataStreamMonitor *m) +{ + if(!m_pMonitorList)return; + m_pMonitorList->removeRef(m); + if(m_pMonitorList->isEmpty()) + { + delete m_pMonitorList; + m_pMonitorList = 0; + } +} + +void KviIrcContext::closeAllDeadChannels() +{ + while(m_pDeadChannels) + { + KviChannelWindow * c = m_pDeadChannels->first(); + if(c) + { + m_pFrame->closeWindow(c); + } else { + // ops.... + delete m_pDeadChannels; + m_pDeadChannels = 0; + } + } +} + +void KviIrcContext::closeAllDeadQueries() +{ + while(m_pDeadQueries) + { + KviQueryWindow * q = m_pDeadQueries->first(); + if(q) + { + m_pFrame->closeWindow(q); + } else { + // ops.... + delete m_pDeadQueries; + m_pDeadQueries = 0; + } + } +} + +void KviIrcContext::closeAllContextWindows() +{ + while(m_pContextWindows) + { + KviWindow * w = m_pContextWindows->first(); + if(w) + { + m_pFrame->closeWindow(w); + } else { + // ops... + delete m_pContextWindows; + m_pContextWindows = 0; + } + } +} + +KviChannelWindow * KviIrcContext::findDeadChannel(const QString &name) +{ + if(!m_pDeadChannels)return 0; + for(KviChannelWindow * c = m_pDeadChannels->first();c;c = m_pDeadChannels->next()) + { + KVI_ASSERT(c->isDeadChan()); + if(KviQString::equalCI(name,c->windowName()))return c; + } + return 0; +} + +KviQueryWindow * KviIrcContext::findDeadQuery(const QString &name) +{ + if(!m_pDeadQueries)return 0; + for(KviQueryWindow * c = m_pDeadQueries->first();c;c = m_pDeadQueries->next()) + { + KVI_ASSERT(c->isDeadQuery()); + if(KviQString::equalCI(name,c->windowName()))return c; + } + return 0; +} + +KviQueryWindow * KviIrcContext::firstDeadQuery() +{ + if(!m_pDeadQueries) + return 0; + return m_pDeadQueries->first(); +} + +KviChannelWindow * KviIrcContext::firstDeadChannel() +{ + if(!m_pDeadChannels) + return 0; + return m_pDeadChannels->first(); +} + +void KviIrcContext::registerContextWindow(KviWindow * pWnd) +{ + if(!m_pContextWindows) + { + m_pContextWindows = new KviPointerList; + m_pContextWindows->setAutoDelete(false); + } + m_pContextWindows->append(pWnd); +} + +void KviIrcContext::registerDeadChannel(KviChannelWindow * c) +{ + if(!m_pDeadChannels) + { + m_pDeadChannels = new KviPointerList; + m_pDeadChannels->setAutoDelete(false); + } + m_pDeadChannels->append(c); +} + +void KviIrcContext::registerDeadQuery(KviQueryWindow * q) +{ + if(!m_pDeadQueries) + { + m_pDeadQueries = new KviPointerList; + m_pDeadQueries->setAutoDelete(false); + } + m_pDeadQueries->append(q); +} + +bool KviIrcContext::unregisterDeadChannel(KviChannelWindow * c) +{ + // was a dead channel ? + if(!m_pDeadChannels)return false; + if(!m_pDeadChannels->removeRef(c)) + { + return false; + } + if(m_pDeadChannels->isEmpty()) + { + delete m_pDeadChannels; + m_pDeadChannels = 0; + } + return true; +} + +bool KviIrcContext::unregisterContextWindow(KviWindow * pWnd) +{ + if(!m_pContextWindows)return false; + if(!m_pContextWindows->removeRef(pWnd)) + { + return false; + } + if(m_pContextWindows->isEmpty()) + { + delete m_pContextWindows; + m_pContextWindows = 0; + } + return true; +} + +bool KviIrcContext::unregisterDeadQuery(KviQueryWindow * q) +{ + if(!m_pDeadQueries)return false; + if(!m_pDeadQueries->removeRef(q)) + { + return false; + } + if(m_pDeadQueries->isEmpty()) + { + delete m_pDeadQueries; + m_pDeadQueries = 0; + } + return true; +} + +void KviIrcContext::createLinksWindow() +{ + if(m_pLinksWindow)return; + KviKvsScript::run("links.open",m_pConsole); +} + +void KviIrcContext::createListWindow() +{ + if(m_pListWindow)return; + KviKvsScript::run("list.open",m_pConsole); +} + +void KviIrcContext::destroyConnection() +{ + if(!m_pConnection)return; + m_pConnection->closeAllChannels(); + m_pConnection->closeAllQueries(); + + if(m_pLinksWindow)m_pLinksWindow->control(EXTERNAL_SERVER_DATA_PARSER_CONTROL_RESET); + if(m_pListWindow)m_pListWindow->control(EXTERNAL_SERVER_DATA_PARSER_CONTROL_RESET); + + m_pConsole->connectionDetached(); + + // make sure that m_pConnection is already 0 in any + // event triggered by KviIrcConnection destructor + KviIrcConnection * pTmp = m_pConnection; + m_pConnection = 0; + delete pTmp; +} + +void KviIrcContext::setState(State eState) +{ + if(m_eState == eState)return; + m_eState = eState; + + m_pFrame->childContextStateChange(this); + + emit stateChanged(); + + if(eState == KviIrcContext::Idle)destroyConnection(); + + m_pConsole->updateCaption(); +} + +void KviIrcContext::setAsynchronousConnectionData(KviAsynchronousConnectionData * d) +{ + if(m_pAsynchronousConnectionData)delete m_pAsynchronousConnectionData; + m_pAsynchronousConnectionData = d; +} + +void KviIrcContext::destroyAsynchronousConnectionData() +{ + if(!m_pAsynchronousConnectionData)return; + delete m_pAsynchronousConnectionData; + m_pAsynchronousConnectionData = 0; +} + +void KviIrcContext::loginComplete() +{ + setState(Connected); +} + +void KviIrcContext::connectButtonClicked() +{ + if(!connection()) + { + if(m_pReconnectTimer) + { + // reconnection was in progress... + delete m_pReconnectTimer; + m_pReconnectTimer = 0; + destroyAsynchronousConnectionData(); + + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR, + __tr2qs("Reconnect attempt aborted")); + + return; + } + + // No connections in progress + m_uConnectAttemptCount = 1; + connectToCurrentServer(); + } else { + // Sth is going on + terminateConnectionRequest(false); + } +} + +void KviIrcContext::connectToCurrentServer() +{ + if(m_pReconnectTimer) + { + delete m_pReconnectTimer; + m_pReconnectTimer = 0; + } + + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE," "); // spacer + + // No connection target specified. + // If we have a saved target, reuse it + if(!m_pAsynchronousConnectionData && m_pSavedAsynchronousConnectionData) + { + m_pAsynchronousConnectionData = m_pSavedAsynchronousConnectionData; + m_pSavedAsynchronousConnectionData = 0; + } + + if(m_pAsynchronousConnectionData) + { + // we have a specified connection target (either from outside or saved) + if(m_pAsynchronousConnectionData->szServer.isEmpty()) + { + // an empty server might mean "reuse the last server in context" + if( + m_pAsynchronousConnectionData->bUseLastServerInContext && + m_pSavedAsynchronousConnectionData + ) + { + // reuse the saved connection data + // the server for sure + m_pAsynchronousConnectionData->szServer = m_pSavedAsynchronousConnectionData->szServer; + m_pAsynchronousConnectionData->szServerId = m_pSavedAsynchronousConnectionData->szServerId; + m_pAsynchronousConnectionData->uPort = m_pSavedAsynchronousConnectionData->uPort; + m_pAsynchronousConnectionData->bPortIsOk = true; + m_pAsynchronousConnectionData->bUseIPv6 = m_pSavedAsynchronousConnectionData->bUseIPv6; + m_pAsynchronousConnectionData->bUseSSL = m_pSavedAsynchronousConnectionData->bUseSSL; + m_pAsynchronousConnectionData->bSTARTTLS = m_pSavedAsynchronousConnectionData->bSTARTTLS; + if(m_pSavedAsynchronousConnectionData->m_pReconnectInfo) + m_pAsynchronousConnectionData->m_pReconnectInfo = new KviIrcServerReconnectInfo(*(m_pSavedAsynchronousConnectionData->m_pReconnectInfo)); + else m_pAsynchronousConnectionData->m_pReconnectInfo = 0; + + // and the other info, only if not overridden by the user + if(m_pAsynchronousConnectionData->szBindAddress.isEmpty()) + m_pAsynchronousConnectionData->szBindAddress = m_pSavedAsynchronousConnectionData->szBindAddress; + if(m_pAsynchronousConnectionData->szCommandToExecAfterConnect.isEmpty()) + m_pAsynchronousConnectionData->szCommandToExecAfterConnect = m_pSavedAsynchronousConnectionData->szCommandToExecAfterConnect; + if(m_pAsynchronousConnectionData->szLinkFilter.isEmpty()) + m_pAsynchronousConnectionData->szLinkFilter = m_pSavedAsynchronousConnectionData->szLinkFilter; + if(m_pAsynchronousConnectionData->szPass.isEmpty()) + m_pAsynchronousConnectionData->szPass = m_pSavedAsynchronousConnectionData->szPass; + if(m_pAsynchronousConnectionData->szNick.isEmpty()) + m_pAsynchronousConnectionData->szNick = m_pSavedAsynchronousConnectionData->szNick; + if(m_pAsynchronousConnectionData->szInitUMode.isEmpty()) + m_pAsynchronousConnectionData->szInitUMode = m_pSavedAsynchronousConnectionData->szInitUMode; + } else { + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMWARNING,__tr2qs("This is the first connection in this IRC context: using the global server setting")); + } + } else { + // !m_pAsynchronousConnectionData->szServer.isEmpty() + // ok, have a server to look for in the db + // FIXME: this is a bit ugly... could it be managed in some completly different and nicer way ? + KviIrcServerDefinition d; + d.szServer = m_pAsynchronousConnectionData->szServer; + d.bPortIsValid = m_pAsynchronousConnectionData->bPortIsOk; + d.uPort = m_pAsynchronousConnectionData->uPort; + d.bIPv6 = m_pAsynchronousConnectionData->bUseIPv6; + d.bSSL = m_pAsynchronousConnectionData->bUseSSL; + d.bSTARTTLS = m_pAsynchronousConnectionData->bSTARTTLS; + d.szLinkFilter = m_pAsynchronousConnectionData->szLinkFilter; + d.szPass = m_pAsynchronousConnectionData->szPass; + d.szNick = m_pAsynchronousConnectionData->szNick; + d.szInitUMode = m_pAsynchronousConnectionData->szInitUMode; + d.szId = m_pAsynchronousConnectionData->szServerId; + QString szError; + if(!g_pServerDataBase->makeCurrentServer(&d,szError)) + { + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR,szError); + destroyAsynchronousConnectionData(); + return; + } + } // else we just connect to the globally selected irc server in the options dialog + } + + KviIrcNetwork * net = g_pServerDataBase->currentNetwork(); + KviIrcServer * srv = net ? net->currentServer() : 0; + + KviProxy * prx = 0; + + if(!srv) + { + if(g_pServerDataBase->networkCount()) + KviKvsScript::run("options.edit KviIrcServerOptionsWidget",m_pConsole); + else + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR,__tr2qs("No servers available. Check the options dialog or use the /SERVER command")); + destroyAsynchronousConnectionData(); + return; + } + + if(!net) + { + // BUG + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR,__tr2qs("Ooops.. you've hit a bug in the servers database... I have found a server but not a network...")); + destroyAsynchronousConnectionData(); + return; + } + + + prx = srv->proxyServer(g_pProxyDataBase); + + if(!prx && (srv->proxy()!=-1) && KVI_OPTION_BOOL(KviOption_boolUseProxyHost)) + { + prx = g_pProxyDataBase->currentProxy(); + if(!prx) + { + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMWARNING,__tr2qs("No proxy hosts available, resuming direct connection")); + } + } + + QString szBindAddress; + + srv->m_pReconnectInfo = 0; + if(m_pAsynchronousConnectionData) + { + szBindAddress = m_pAsynchronousConnectionData->szBindAddress; + if(m_pAsynchronousConnectionData->m_pReconnectInfo) + srv->m_pReconnectInfo = new KviIrcServerReconnectInfo(*(m_pAsynchronousConnectionData->m_pReconnectInfo)); + } + + // Find out the identity we'll be using in this connection + // First check the server for one + + const KviUserIdentity * pIdentity = 0; + + QString szUserIdentityId = srv->userIdentityId(); + if(!szUserIdentityId.isEmpty()) + pIdentity = KviUserIdentityManager::instance()->findIdentity(szUserIdentityId); + + // If not found, look in the network instead + if(!pIdentity) + szUserIdentityId = net->userIdentityId(); + + if(!szUserIdentityId.isEmpty()) + pIdentity = KviUserIdentityManager::instance()->findIdentity(szUserIdentityId); + + // If not found, get the default identity (this is GRANTED to be never null, eventually filled up with defaults) + pIdentity = KviUserIdentityManager::instance()->defaultIdentity(); + + if(m_pConnection) delete m_pConnection; + m_pConnection = new KviIrcConnection( + this, + new KviIrcConnectionTarget( + net, + srv, + prx, + szBindAddress + ), + new KviUserIdentity(*pIdentity) + ); + + setState(Connecting); + + if(m_pAsynchronousConnectionData) + { + m_pConnection->stateData()->setCommandToExecAfterConnect(m_pAsynchronousConnectionData->szCommandToExecAfterConnect); + destroyAsynchronousConnectionData(); + } + + m_pConsole->connectionAttached(); + + // save stuff for later + + // FIXME: this management of "next" connection should be reviewed a bit anyway + if(m_pSavedAsynchronousConnectionData) delete m_pSavedAsynchronousConnectionData; + m_pSavedAsynchronousConnectionData = new KviAsynchronousConnectionData(); + m_pSavedAsynchronousConnectionData->szServer = srv->m_szHostname; + m_pSavedAsynchronousConnectionData->uPort = srv->port(); + m_pSavedAsynchronousConnectionData->bPortIsOk = true; + m_pSavedAsynchronousConnectionData->bUseIPv6 = srv->isIPv6(); + m_pSavedAsynchronousConnectionData->bUseSSL = srv->useSSL(); + m_pSavedAsynchronousConnectionData->bSTARTTLS = srv->enabledSTARTTLS(); + m_pSavedAsynchronousConnectionData->szPass = srv->password(); + m_pSavedAsynchronousConnectionData->szServerId = srv->id(); + m_pSavedAsynchronousConnectionData->szInitUMode = srv->m_szInitUMode; + if(srv->m_pReconnectInfo) + m_pSavedAsynchronousConnectionData->m_pReconnectInfo = new KviIrcServerReconnectInfo(*(srv->m_pReconnectInfo)); + else m_pSavedAsynchronousConnectionData->m_pReconnectInfo = 0; + + // this never fails! + m_pConnection->start(); +} + +void KviIrcContext::connectionFailed(int iError) +{ + if(!m_pConnection)return; // this may happen in the destructor! + + m_pConsole->output(KVI_OUT_SYSTEMERROR, + __tr2qs("Connection attempt failed [%s]"), + m_pConnection->target()->server()->m_szHostname.toUtf8().data()); + + // if the connection has been aborted by the user then just go idle + if(iError == KviError_operationAborted) + goto enter_idle_state; + + // FIXME: this should stop on critical errors ! + if(KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) + { + if((!KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts) || + (m_uConnectAttemptCount < KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)))) + { + m_uConnectAttemptCount++; + //FIXME: Multiply the delay by (m_uConnectAttemptCount / 2) so later connects are less frequent. + if(!_OUTPUT_MUTE) + { + QString tmp; + KviQString::sprintf(tmp,__tr2qs("Will attempt to reconnect in %d seconds"),KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); + QString num; + + if(!KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)) + KviQString::sprintf(num,__tr2qs("%d"),m_uConnectAttemptCount); + else + KviQString::sprintf(num,__tr2qs("%d of %d"), + m_uConnectAttemptCount,KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)); + tmp += " [" + num + "]"; + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,tmp); + } + + KviIrcServer oldServer(*(connection()->target()->server())); + QString oldNickname = connection()->userInfo()->isAway() ? connection()->userInfo()->nickNameBeforeAway() : connection()->userInfo()->nickName(); + + KviAsynchronousConnectionData * d = new KviAsynchronousConnectionData(); + d->szServer = oldServer.m_szHostname; + d->szServerId = oldServer.id(); + d->uPort = oldServer.port(); + d->bPortIsOk = true; + d->bUseIPv6 = oldServer.isIPv6(); + d->bUseSSL = oldServer.useSSL(); + d->bSTARTTLS = oldServer.enabledSTARTTLS(); + d->szPass = oldServer.password(); + d->szNick = oldNickname; + d->szInitUMode = oldServer.m_szInitUMode; + d->szCommandToExecAfterConnect = ""; + setAsynchronousConnectionData(d); + beginAsynchronousConnect(1000 * KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); + + setState(Idle); // destroy the actual connection + + return; + } else { + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_SYSTEMERROR,__tr2qs("Maximum number of reconnect attempts reached (%d): giving up"),KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)); + } + } + + // reset the attempt count + m_uConnectAttemptCount = 1; + + if(connection()->target()->server()->cacheIp()) + { + if((((int)iError) == KviError_connectionTimedOut) || + (((int)iError) == KviError_connectionRefused) || + (((int)iError) == KviError_networkUnreachable) || + (((int)iError) == KviError_hostUnreachable)) + { + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("The connection attempt failed while using a cached IP address for the current server")); + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("The problem *might* be caused by an updated DNS entry")); + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Try reconnecting with caching disabled")); + } + } + +enter_idle_state: + setState(Idle); +} + +void KviIrcContext::connectionEstabilished() +{ + //qDebug("context::connectionEstabilished"); + // + // The connection has been estabilished, the + // KviIrcConnection will attempt to login now + // + m_uConnectAttemptCount = 1; + + bool bStopOutput = false; + + setState(LoggingIn); // this must be set in order for $server and other functions to return the correct values + + bStopOutput = KVS_TRIGGER_EVENT_0_HALTED(KviEvent_OnIRCConnectionEstabilished,m_pConsole); + + if(!bStopOutput) + { + m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("%Q established [%s (%s:%u)]"), + connection()->link()->socket()->usingSSL() ? &(__tr2qs("Secure connection")) : &(__tr2qs("Connection")), + connection()->target()->server()->m_szHostname.toUtf8().data(), + connection()->target()->server()->m_szIp.toUtf8().data(), + connection()->target()->server()->m_uPort); + } + + // Add to recent server list (build the url of type irc[6]://: + QString url; + KviIrcUrl::join(url,connection()->target()->server()); + g_pApp->addRecentServer(url); + + // save the last server this console used + //if(m_pLastIrcServer)delete m_pLastIrcServer; + //m_pLastIrcServer = new KviIrcServer(*(connection()->server())); +} + +void KviIrcContext::connectionTerminated() +{ + if(!m_pConnection)return; // this may happen in the destructor! + + KviIrcServer oldServer(*(connection()->target()->server())); + if(oldServer.m_pReconnectInfo) + { + KviIrcServerReconnectInfo *pOldInfo = oldServer.m_pReconnectInfo; + oldServer.m_pReconnectInfo = 0; + delete pOldInfo; + } + + KviIrcServerReconnectInfo info, *pInfo(&info); + pInfo->m_szNick = connection()->userInfo()->isAway() ? connection()->userInfo()->nickNameBeforeAway() : connection()->userInfo()->nickName(); + pInfo->m_szPass = connection()->userInfo()->password(); + pInfo->m_bIsAway = connection()->userInfo()->isAway(); + pInfo->m_szAwayReason = connection()->userInfo()->awayReason(); + + connection()->requestQueue()->clearAll(); + + // we consider it unexpected when we haven't sent a QUIT message and we're connected + // or alternatively when a simulation of such a termination is requested (this is used to keep the queries open etc..) + bool bUnexpectedDisconnect = ((!(connection()->stateData()->sentQuit())) && ((m_eState == KviIrcContext::Connected) || (m_eState == KviIrcContext::Connecting))) || connection()->stateData()->simulateUnexpectedDisconnect(); + + if(bUnexpectedDisconnect) + { + if(KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) + { + if(KVI_OPTION_BOOL(KviOption_boolRejoinChannelsAfterReconnect)) + { + // FIXME: THIS SHOULD BE A KviIrcConnection FUNCTION + KviChannelWindow * c; + QString szChannels, szProtectedChannels, szPasswords, szCurPass, szCurChan; + // first only chans without key, in groups of 4 + for(c = connection()->channelList()->first(); c; c = connection()->channelList()->next()) + { + szCurPass = c->hasChannelMode('k') ? c->channelModeParam('k') : ""; + szCurChan = c->windowName(); + if(szCurPass.isEmpty()) + { + if(!szChannels.isEmpty()) + szChannels.append(","); + szChannels.append(szCurChan); + } else { + if(!szProtectedChannels.isEmpty()) + szProtectedChannels.append(","); + szProtectedChannels.append(szCurChan); + if(!szPasswords.isEmpty()) + szPasswords.append(","); + szPasswords.append(szCurPass); + } + } + if((!szChannels.isEmpty()) || (!szProtectedChannels.isEmpty())) + { + pInfo->m_szJoinChannels.append(szProtectedChannels); + if(!szProtectedChannels.isEmpty() && !szChannels.isEmpty()) + pInfo->m_szJoinChannels.append(','); + pInfo->m_szJoinChannels.append(szChannels); + pInfo->m_szJoinChannels.append(" "); + pInfo->m_szJoinChannels.append(szPasswords); + } + } + + + if(KVI_OPTION_BOOL(KviOption_boolReopenQueriesAfterReconnect)) + { + for(KviQueryWindow * q = connection()->queryList()->first(); q; q = connection()->queryList()->next()) + { + pInfo->m_szOpenQueryes.append(q->target()); + } + } + } + + if(KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnUnexpectedDisconnect) || KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnDisconnect)) + connection()->keepChannelsOpenAfterDisconnect(); + + if(KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnUnexpectedDisconnect) || KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnDisconnect)) + connection()->keepQueriesOpenAfterDisconnect(); + } else { + if(KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnDisconnect)) + connection()->keepChannelsOpenAfterDisconnect(); + + if(KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnDisconnect)) + connection()->keepQueriesOpenAfterDisconnect(); + } + + setState(Idle); + + bool bStopOutput = false; + + bStopOutput = KVS_TRIGGER_EVENT_0_HALTED(KviEvent_OnIRCConnectionTerminated,m_pConsole); + + if(!bStopOutput) + { + m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("Connection terminated [%s (%s:%u)]"), + oldServer.hostName().toUtf8().data(), + oldServer.ip().toUtf8().data(), + oldServer.port()); + } + + // do reconnect + + if(bUnexpectedDisconnect && KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) + { + //m_uConnectAttemptCount = 1; + if(!_OUTPUT_MUTE) + m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("The connection terminated unexpectedly. Trying to reconnect...")); + KviAsynchronousConnectionData * d = new KviAsynchronousConnectionData(); + d->szServerId = oldServer.id(); + d->szServer = oldServer.m_szHostname; + d->uPort = oldServer.port(); + d->bPortIsOk = true; + d->bUseIPv6 = oldServer.isIPv6(); + d->bUseSSL = oldServer.useSSL(); + d->bSTARTTLS = oldServer.enabledSTARTTLS(); + d->szPass = oldServer.password(); + d->szInitUMode = oldServer.m_szInitUMode; + d->m_pReconnectInfo = new KviIrcServerReconnectInfo(*(pInfo)); + setAsynchronousConnectionData(d); + + beginAsynchronousConnect(1000 * KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); + } +} + +void KviIrcContext::beginAsynchronousConnect(unsigned int uDelayInMSecs) +{ + if(m_pReconnectTimer) delete m_pReconnectTimer; + m_pReconnectTimer = new QTimer(this); + connect(m_pReconnectTimer,SIGNAL(timeout()),this,SLOT(asynchronousConnect())); + m_pReconnectTimer->start(uDelayInMSecs); +} + +void KviIrcContext::asynchronousConnect() +{ + if(m_pReconnectTimer) + { + delete m_pReconnectTimer; + m_pReconnectTimer = 0; + } + + if(state() != Idle) // need a brutal disconnect here + terminateConnectionRequest(true,"Changing server..."); + + connectToCurrentServer(); +} + +void KviIrcContext::terminateConnectionRequest(bool bForce, const QString & szQuitMsg, bool bSimulateUnexpectedDisconnect) +{ + if(!connection())return; // hm ? + + connection()->stateData()->setSimulateUnexpectedDisconnect(bSimulateUnexpectedDisconnect); + + switch(m_eState) + { + case Connected: + { + // was connected : send a quit and abort the connection + bool bWasSentQuit = true; + if(!connection()->stateData()->sentQuit()) + { + KVS_TRIGGER_EVENT_0(KviEvent_OnDisconnectRequest,m_pConsole); + QString szQuit = szQuitMsg; + if(szQuit.isEmpty()) + szQuit = KVI_OPTION_STRING(KviOption_stringQuitMessage); + KviQString::escapeKvs(&szQuit, KviQString::PermitVariables | KviQString::PermitFunctions); + QString buffer; + KviKvsVariant ret; + if(KviKvsScript::evaluate(szQuit,console(),0,&ret)) + ret.asString(buffer); + else + buffer = szQuit; + QByteArray dat = connection()->encodeText(buffer); + bWasSentQuit = false; + connection()->stateData()->setSentQuit(); + connection()->sendFmtData("QUIT :%s",dat.data() ? dat.data() : ""); // here theoretically we COULD get disconnected + } // else it was already sent anyway + + if(KVI_OPTION_BOOL(KviOption_boolForceBrutalQuit) || bWasSentQuit || bForce) + { + if(!bWasSentQuit) + { + // idle for some milliseconds in order to allow the quit message to reach + // the remote end without breaking the connection + KviThread::msleep(100); + } + // and brutally abort the connection (if it still exists!!!) + if(connection())connection()->abort(); + } else { + if(!bWasSentQuit) + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Sent QUIT, waiting for the server to close the connection...")); + // else it was already sent anyway + } + } + break; + case Connecting: + case LoggingIn: + // was waiting for connection or login, just abort it: it will trigger an error anyway + connection()->abort(); + break; + default: + // should never end here! + KVI_ASSERT(false); + break; + } +} + +void KviIrcContext::timerEvent(QTimerEvent * e) +{ + if(e->timerId() != m_iHeartbeatTimerId) + { + QObject::timerEvent(e); + return; + } + + // our heartbeat + kvi_time_t tNow = kvi_unixTime(); + + if(m_pConnection) + m_pConnection->heartbeat(tNow); +} diff --git a/src/kvirc/kernel/KviIrcContext.h b/src/kvirc/kernel/KviIrcContext.h new file mode 100644 index 000000000..6348cdc55 --- /dev/null +++ b/src/kvirc/kernel/KviIrcContext.h @@ -0,0 +1,189 @@ +#ifndef _KVI_IRCCONTEXT_H_ +#define _KVI_IRCCONTEXT_H_ +//============================================================================= +// +// File : KviIrcContext.h +// Creation date : Sun 09 May 2004 20:37:46 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviPointerList.h" +#include + +class KviChannelWindow; +class KviQueryWindow; +class KviQueryWindow; +class KviMainWindow; +class KviIrcConnection; +class KviExternalServerDataParser; +class KviAsynchronousConnectionData; +class KviIrcDataStreamMonitor; +class KviWindow; +class QTimer; +class KviConsole; +class KviIrcNetwork; +class KviIrcServer; +/* + KviIrcContext is the structure that groups the objects and resources + usable for a single irc connection: a console, a set of channels and queries, + and a KviIrcConnection object. + + The objects grouped here are mostly permanent across connections. + + Each irc context has its own unique numeric identifier. The identifiers start + from 1 so 0 is an invalid irc context id (this is useful in the scripting engine). + + The irc context is created in the KviConsole constructor and destroyed + in the KviConsole destructor. No other class can allocate KviIrcContext objects. +*/ + +class KVIRC_API KviIrcContext : public QObject +{ + friend class KviConsole; + friend class KviChannelWindow; + friend class KviQueryWindow; + friend class KviIrcConnection; + friend class KviIrcContextToolBar; + Q_OBJECT +protected: + KviIrcContext(KviConsole * pConsole); // only KviConsole can create this +public: + ~KviIrcContext(); +public: + enum State + { + Idle, // connection() == 0 + Connecting, // connection() != 0 + LoggingIn, // connection() != 0 + Connected // connection() != 0 + }; +protected: + KviConsole * m_pConsole; // shallow, never null + KviIrcConnection * m_pConnection; + + unsigned int m_uId; // this irc context id + + State m_eState; // this context state + + // helper pointers + KviMainWindow * m_pFrame; // the owning frame, shallow, never null + + // permanent links and list window + KviExternalServerDataParser * m_pLinksWindow; + KviExternalServerDataParser * m_pListWindow; + + KviAsynchronousConnectionData * m_pAsynchronousConnectionData; // owned, may be null + KviAsynchronousConnectionData * m_pSavedAsynchronousConnectionData; // owned, may be null, this is used to reconnect to the last server in this context + + unsigned int m_uConnectAttemptCount; + QTimer * m_pReconnectTimer; + + KviPointerList * m_pMonitorList; // owned, may be null + + // dead channels and queries + KviPointerList * m_pDeadChannels; + KviPointerList * m_pDeadQueries; + // other context bound windows + KviPointerList * m_pContextWindows; + + int m_iHeartbeatTimerId; +public: + inline unsigned int id(){ return m_uId; }; + // never null and always the same! + inline KviConsole * console(){ return m_pConsole; }; + // never null and always the same + inline KviMainWindow * frame(){ return m_pFrame; }; + // may be null and may change! + inline KviIrcConnection * connection(){ return m_pConnection; }; + // state + inline State state(){ return m_eState; }; + inline bool isConnected(){ return m_eState == Connected; }; + inline bool isLoggingIn(){ return m_eState == LoggingIn; }; + // dead channels and queries + bool unregisterDeadChannel(KviChannelWindow * c); + bool unregisterDeadQuery(KviQueryWindow * q); + void registerDeadChannel(KviChannelWindow * c); + void registerDeadQuery(KviQueryWindow * q); + KviChannelWindow * findDeadChannel(const QString &name); + KviQueryWindow * findDeadQuery(const QString &nick); + KviQueryWindow * firstDeadQuery(); + KviChannelWindow * firstDeadChannel(); + // other windows bound to the context + void closeAllContextWindows(); + void registerContextWindow(KviWindow * pWnd); + bool unregisterContextWindow(KviWindow * pWnd); + + inline KviPointerList * monitorList(){ return m_pMonitorList; }; + + // links window + void createLinksWindow(); + inline void setLinksWindowPointer(KviExternalServerDataParser * l){ m_pLinksWindow = l; }; + inline KviExternalServerDataParser * linksWindow(){ return m_pLinksWindow; }; + + // list window + void createListWindow(); + inline void setListWindowPointer(KviExternalServerDataParser * l){ m_pListWindow = l; }; + inline KviExternalServerDataParser * listWindow(){ return m_pListWindow; }; + + void setAsynchronousConnectionData(KviAsynchronousConnectionData * d); + inline KviAsynchronousConnectionData * asynchronousConnectionData(){ return m_pAsynchronousConnectionData; }; + void destroyAsynchronousConnectionData(); + // used by KviConsole (for now) and KviUserParser + void connectToCurrentServer(); + + void beginAsynchronousConnect(unsigned int uDelayInMSecs); + + void registerDataStreamMonitor(KviIrcDataStreamMonitor * m); + void unregisterDataStreamMonitor(KviIrcDataStreamMonitor *m); + + void terminateConnectionRequest(bool bForce,const QString &szQuitMessage = QString(),bool bSimulateUnexpectedDisconnect = false); +public slots: + void closeAllDeadChannels(); + void closeAllDeadQueries(); + +protected: + // called by KviIrcContextToolBar: this will DIE in favor of connectOrDisconnect() + void connectButtonClicked(); + // used by KviConsole (for now) + void destroyConnection(); + // for KviConsole (for now) . later will be used only internally + void setState(State eState); + // called by KviIrcConnection + void loginComplete(); + // our heartbeat timer event + virtual void timerEvent(QTimerEvent *e); +public: + void connectOrDisconnect(){ connectButtonClicked(); }; +protected: + // + // KviIrcConnection interface + // + void connectionFailed(int iError); + void connectionEstabilished(); + void connectionTerminated(); +signals: + void stateChanged(); +protected slots: + void asynchronousConnect(); +}; + + +#endif //!_KVI_IRCCONTEXT_H_ diff --git a/src/kvirc/kernel/KviIrcDataStreamMonitor.cpp b/src/kvirc/kernel/KviIrcDataStreamMonitor.cpp new file mode 100644 index 000000000..fca864521 --- /dev/null +++ b/src/kvirc/kernel/KviIrcDataStreamMonitor.cpp @@ -0,0 +1,41 @@ +//============================================================================= +// +// File : KviIrcDataStreamMonitor.cpp +// Creation date : Sun 04 Jul 2004 21:27:22 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcDataStreamMonitor.h" +#include "KviIrcContext.h" + +KviIrcDataStreamMonitor::KviIrcDataStreamMonitor(KviIrcContext * pContext) +: KviHeapObject() +{ + m_pMyContext = pContext; + m_pMyContext->registerDataStreamMonitor(this); +} + +KviIrcDataStreamMonitor::~KviIrcDataStreamMonitor() +{ + m_pMyContext->unregisterDataStreamMonitor(this); +} + diff --git a/src/kvirc/kernel/KviIrcDataStreamMonitor.h b/src/kvirc/kernel/KviIrcDataStreamMonitor.h new file mode 100644 index 000000000..dfc8d1ddf --- /dev/null +++ b/src/kvirc/kernel/KviIrcDataStreamMonitor.h @@ -0,0 +1,49 @@ +#ifndef _KVI_IRCDATASTREAMMONITOR_H_ +#define _KVI_IRCDATASTREAMMONITOR_H_ +//============================================================================= +// +// File : KviIrcDataStreamMonitor.h +// Creation date : Sun 04 Jul 2004 21:27:22 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviHeapObject.h" + +class KviIrcContext; + +class KVIRC_API KviIrcDataStreamMonitor : public KviHeapObject +{ +public: + KviIrcDataStreamMonitor(KviIrcContext * pContext); + virtual ~KviIrcDataStreamMonitor(); +protected: + KviIrcContext * m_pMyContext; +public: + virtual bool incomingMessage(const char *) = 0; + // For proxy connections it might spit out binary data! + virtual bool outgoingMessage(const char *) = 0; + virtual void connectionInitiated(){}; + virtual void connectionTerminated(){}; + virtual void die(){ delete this; }; +}; + + +#endif //!_KVI_IRCDATASTREAMMONITOR_H_ diff --git a/src/kvirc/kernel/KviIrcLink.cpp b/src/kvirc/kernel/KviIrcLink.cpp new file mode 100644 index 000000000..546710f9b --- /dev/null +++ b/src/kvirc/kernel/KviIrcLink.cpp @@ -0,0 +1,424 @@ +//============================================================================= +// +// File : KviIrcLink.cpp +// Creation date : Mon 03 May 2004 01:45:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcLink.h" +#include "KviDnsResolver.h" +#include "KviLocale.h" +#include "KviIrcServerDataBase.h" +#include "KviProxyDataBase.h" +#include "KviError.h" +#include "kvi_out.h" +#include "KviOptions.h" +#include "KviIrcSocket.h" +#include "KviConsoleWindow.h" +#include "KviNetUtils.h" +#include "KviInternalCommand.h" +#include "KviMainWindow.h" +#include "KviMexLinkFilter.h" +//#include "kvi_garbage.h" +#include "KviMemory.h" +#include "KviMemory.h" +#include "KviIrcConnection.h" +#include "KviIrcConnectionTarget.h" +#include "KviIrcConnectionTargetResolver.h" +#include "KviIrcSocket.h" +#include "KviDataBuffer.h" +#include "kvi_debug.h" + +#include + +extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; +extern KVIRC_API KviProxyDataBase * g_pProxyDataBase; +//extern KVIRC_API KviGarbageCollector * g_pGarbageCollector; + + +KviIrcLink::KviIrcLink(KviIrcConnection * pConnection) +: QObject() +{ + m_pConnection = pConnection; + m_pTarget = pConnection->target(); + m_pConsole = m_pConnection->console(); + + m_pSocket = 0; + m_pLinkFilter = 0; + m_pResolver = 0; + + m_pReadBuffer = 0; // incoming data buffer + m_uReadBufferLen = 0; // incoming data buffer length + m_uReadPackets = 0; // total packets read per session + + m_eState = Idle; +} + +KviIrcLink::~KviIrcLink() +{ + if(m_pResolver) + delete m_pResolver; + + destroySocket(); + + if(m_pReadBuffer) + KviMemory::free(m_pReadBuffer); +} + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// KviIrcSocket management +// + +void KviIrcLink::linkFilterDestroyed() +{ + m_pLinkFilter = 0; + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("Ops... for some reason the link filter object has been destroyed")); +} + +void KviIrcLink::destroySocket() +{ + if(m_pLinkFilter) + { + QObject::disconnect(m_pLinkFilter,0,this,0); + // the module extension server links must be destroyed in the module that provided it + m_pLinkFilter->die(); + m_pLinkFilter = 0; + } + + if(m_pSocket) + { + // We use deleteLater() here, since we could actually be inside an event + // related to the QSocketNotifier that the socket is attached to... + m_pSocket->deleteLater(); + m_pSocket = 0; + } +} + +void KviIrcLink::createSocket(const QString & szLinkFilterName) +{ + destroySocket(); // make sure we do not leak memory + + m_pSocket = new KviIrcSocket(this); + + if(szLinkFilterName.isEmpty()) + return; + + if(KviQString::equalCI(szLinkFilterName,"irc")) + return; + + m_pLinkFilter = (KviMexLinkFilter *)g_pModuleExtensionManager->allocateExtension("linkfilter", + szLinkFilterName.toUtf8().data(),m_pConsole,0,this,szLinkFilterName.toUtf8().data()); + + if(m_pLinkFilter) + { + connect(m_pLinkFilter,SIGNAL(destroyed()),this,SLOT(linkFilterDestroyed())); + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr2qs("Using filtered IRC protocol: Link filter is \"%Q\""),&szLinkFilterName); + return; + } + + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("Failed to set up the link filter \"%Q\", will try with plain IRC"),&szLinkFilterName); +} + +////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Connection related operations +// + +void KviIrcLink::abort() +{ + if(m_pSocket) + { + m_pSocket->abort(); + return; + } + + if(m_pResolver) + { + m_pResolver->abort(); + return; + } +} + +void KviIrcLink::start() +{ + m_eState = Connecting; + if(m_pResolver) + delete m_pResolver; // this should never happen + + m_pResolver = new KviIrcConnectionTargetResolver(m_pConnection); + connect(m_pResolver,SIGNAL(terminated()),this,SLOT(resolverTerminated())); + m_pResolver->start(m_pTarget); +} + +void KviIrcLink::resolverTerminated() +{ + if(!m_pResolver) + { + qDebug("Oops... resoverTerminated() triggered without a resolver ?"); + return; + } + + if(m_pResolver->status() != KviIrcConnectionTargetResolver::Success) + { + m_eState = Idle; + m_pConnection->linkAttemptFailed(m_pResolver->lastError()); + return; + } + + // resolver terminated successfully + delete m_pResolver; + m_pResolver = 0; + + createSocket(m_pTarget->server()->linkFilter()); + + int iErr = m_pSocket->startConnection(m_pTarget->server(),m_pTarget->proxy(), + m_pTarget->bindAddress().isEmpty() ? 0 : m_pTarget->bindAddress().toUtf8().data()); + + if(iErr != KviError_success) + { + QString szStrDescription(KviError::getDescription(iErr)); + m_pConsole->output(KVI_OUT_SYSTEMERROR, + __tr2qs("Failed to start the connection: %Q"), + &szStrDescription); +// &(KviError::getDescription(iErr))); + + m_eState = Idle; + m_pConnection->linkAttemptFailed(iErr); + } +} + + +///////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Incoming data processing +// + +void KviIrcLink::processData(char * buffer, int iLen) +{ + if(m_pLinkFilter) + { + m_pLinkFilter->processData(buffer,iLen); + return; + } + + register char * p = buffer; + char * cBeginOfCurData = buffer; + int iBufLen = 0; + char * cMessageBuffer = (char *)KviMemory::allocate(1); + + while(*p) + { + if((*p == '\r' )||(*p == '\n')) + { + //found a CR or LF... + //prepare a message buffer + iBufLen = p - cBeginOfCurData; + //check for previous unterminated data + if(m_uReadBufferLen > 0) + { + KVI_ASSERT(m_pReadBuffer); + cMessageBuffer = (char *)KviMemory::reallocate(cMessageBuffer,iBufLen + m_uReadBufferLen + 1); + KviMemory::move(cMessageBuffer,m_pReadBuffer,m_uReadBufferLen); + KviMemory::move((void *)(cMessageBuffer + m_uReadBufferLen),cBeginOfCurData,iBufLen); + *(cMessageBuffer + iBufLen + m_uReadBufferLen) = '\0'; + m_uReadBufferLen = 0; + KviMemory::free(m_pReadBuffer); + m_pReadBuffer = 0; + } else { + KVI_ASSERT(!m_pReadBuffer); + cMessageBuffer = (char *)KviMemory::reallocate(cMessageBuffer,iBufLen + 1); + KviMemory::move(cMessageBuffer,cBeginOfCurData,iBufLen); + *(cMessageBuffer + iBufLen) = '\0'; + } + m_uReadPackets++; + + // FIXME: actually it can happen that the socket gets disconnected + // in a incomingMessage() call. + // The problem might be that some other parts of kvirc assume + // that the irc context still exists after a failed write to the socket + // (some parts don't even check the return value!) + // If the problem presents itself again then the solution is: + // disable queue flushing for the "incomingMessage" call + // and just call queue_insertMessage() + // then after the call terminates flush the queue (eventually detecting + // the disconnect and thus destroying the irc context). + // For now we try to rely on the remaining parts to handle correctly + // such conditions. Let's see... + if(*cMessageBuffer != 0) + m_pConnection->incomingMessage(cMessageBuffer); + + if(m_pSocket->state() != KviIrcSocket::Connected) + { + // Disconnected in KviConsole::incomingMessage() call. + // This may happen for several reasons (local event loop + // with the user hitting the disconnect button, a scripting + // handler event that disconnects explicitly) + // + // We handle it by simply returning control to readData() which + // will return immediately (and safely) control to Qt + KviMemory::free(cMessageBuffer); + return; + } + + while(*p && ((*p=='\r')||(*p=='\n')) )p++; + cBeginOfCurData = p; + + } else p++; + } + + //now *p == '\0' + //beginOfCurData points to '\0' if we have + //no more stuff to parse, or points to something + //different than '\r' or '\n'... + if(*cBeginOfCurData) + { + //Have remaining data...in the local buffer + iBufLen = p - cBeginOfCurData; + if(m_uReadBufferLen > 0) + { + //and there was more stuff saved... (really slow connection) + KVI_ASSERT(m_pReadBuffer); + m_pReadBuffer =(char *)KviMemory::reallocate(m_pReadBuffer,m_uReadBufferLen + iBufLen); + KviMemory::move((void *)(m_pReadBuffer+m_uReadBufferLen),cBeginOfCurData,iBufLen); + m_uReadBufferLen += iBufLen; + } else { + // + KVI_ASSERT(!m_pReadBuffer); + m_uReadBufferLen = iBufLen; + m_pReadBuffer =(char *)KviMemory::allocate(m_uReadBufferLen); + KviMemory::move(m_pReadBuffer,cBeginOfCurData,m_uReadBufferLen); + } + //The m_pReadBuffer contains at max 1 irc message... + //that can not be longer than 510 bytes (the message is not CRLF terminated) + // FIXME: Is this limit *really* valid on all servers ? + if(m_uReadBufferLen > 510) qDebug("WARNING: Receiving an invalid irc message from server."); + } + KviMemory::free(cMessageBuffer); +} + +///////////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Outgoing data processing +// + +void KviIrcLink::clearOutputQueue(bool bPrivateMessagesOnly) +{ + if(!m_pSocket) + return; // we have no queue at all + + if(m_pLinkFilter) + { + m_pLinkFilter->clearOutputQueue(bPrivateMessagesOnly); + return; + } + + m_pSocket->clearOutputQueue(bPrivateMessagesOnly); +} + + +bool KviIrcLink::sendPacket(KviDataBuffer * pData) +{ + if(!m_pSocket) + { + delete pData; + pData = 0; + return false; + } + + // if we have a filter, let it do its job + if(m_pLinkFilter) + return m_pLinkFilter->sendPacket(pData); + + return m_pSocket->sendPacket(pData); +} + +void KviIrcLink::socketStateChange() +{ + switch(m_pSocket->state()) + { + case KviIrcSocket::Connected: + m_eState = Connected; + m_pConnection->linkEstabilished(); + break; + case KviIrcSocket::Idle: + { + State old = m_eState; + m_eState = Idle; + switch(old) + { + case Connecting: + m_pConnection->linkAttemptFailed(m_pSocket->lastError()); + break; + case Connected: + m_pConnection->linkTerminated(); + break; + default: // currently can be only Idle + qDebug("Ooops... got a KviIrcSocket::Idle state change when KviIrcLink::m_eState was Idle"); + break; + } + } + break; + case KviIrcSocket::Connecting: + m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("Contacting %Q %s (%s) on port %u"), + connection()->target()->proxy() ? &(__tr2qs("proxy host")) : &(__tr2qs("IRC server")), + connection()->target()->proxy() ? connection()->target()->proxy()->m_szHostname.toUtf8().data() : connection()->target()->server()->m_szHostname.toUtf8().data(), + connection()->target()->proxy() ? connection()->target()->proxy()->m_szIp.toUtf8().data() : connection()->target()->server()->m_szIp.toUtf8().data(), + connection()->target()->proxy() ? connection()->target()->proxy()->m_uPort : connection()->target()->server()->m_uPort); + break; + case KviIrcSocket::SSLHandshake: + m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("Low-level transport connection established [%s (%s:%u)]"), + connection()->target()->proxy() ? connection()->target()->proxy()->m_szHostname.toUtf8().data() : connection()->target()->server()->m_szHostname.toUtf8().data(), + connection()->target()->proxy() ? connection()->target()->proxy()->m_szIp.toUtf8().data() : connection()->target()->server()->m_szIp.toUtf8().data(), + connection()->target()->proxy() ? connection()->target()->proxy()->m_uPort : connection()->target()->server()->m_uPort); + m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Starting Secure Socket Layer handshake")); + break; + case KviIrcSocket::ProxyLogin: + m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("%Q established [%s (%s:%u)]"), + connection()->link()->socket()->usingSSL() ? &(__tr2qs("Secure proxy connection")) : &(__tr2qs("Proxy connection")), + connection()->target()->proxy()->m_szHostname.toUtf8().data(), + connection()->target()->proxy()->m_szIp.toUtf8().data(), + connection()->target()->proxy()->m_uPort); + m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Negotiating relay information")); + break; + case KviIrcSocket::ProxyFinalV4: + m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent connection request, waiting for acknowledgement")); + break; + case KviIrcSocket::ProxyFinalV5: + m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent target host data, waiting for acknowledgement")); + break; + case KviIrcSocket::ProxySelectAuthMethodV5: + m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent auth method request, waiting for acknowledgement")); + break; + case KviIrcSocket::ProxyUserPassV5: + m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent username and password, waiting for acknowledgement")); + break; + case KviIrcSocket::ProxyFinalHttp: + m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent connection request, waiting for \"HTTP 200\" acknowledgement")); + break; + default: + break; + } +} diff --git a/src/kvirc/kernel/KviIrcLink.h b/src/kvirc/kernel/KviIrcLink.h new file mode 100644 index 000000000..5c4f8f55e --- /dev/null +++ b/src/kvirc/kernel/KviIrcLink.h @@ -0,0 +1,222 @@ +#ifndef _KVI_IRCLINK_H_ +#define _KVI_IRCLINK_H_ +//============================================================================= +// +// File : KviIrcLink.h +// Creation date : Mon 03 May 2004 01:45:42 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviIrcLink.h +* \author Szymon Stefanek +* \brief Middle stack protocol for IRC connection +*/ + +#include "kvi_settings.h" +#include "KviQString.h" + +#include + +class KviConsole; +class KviIrcServer; +class KviProxy; +class KviIrcSocket; +class KviDnsResolver; +class KviIrcConnection; +class KviIrcConnectionTarget; +class KviIrcConnectionTargetResolver; +class KviDataBuffer; +class KviMexLinkFilter; + +/** +* \class KviIrcLink +* \brief Middle stack class for IRC connection +* +* This class gets data from KviIrcSocket and pass it to KviIrcConnection +*/ +class KVIRC_API KviIrcLink : public QObject +{ + friend class KviIrcConnection; // upper protocol in the stack + friend class KviIrcSocket; // lower protocol in the stack + Q_OBJECT +public: + /** + * \enum State + */ + enum State { + Idle, /**< Socket idling */ + Connecting, /**< Socket connecting */ + Connected /**< Socket connected */ + }; +protected: + /** + * \brief Constructs the IrcLink object + * + * Only KviConsole can create this. + * pConsole must NOT be null; + * pServer is a shallow pointer: Connection makes a copy of it internally, + * must NOT be null; + * pProxy may be null if a proxy is not desired. Connection makes a copy + * of it internally; + * \param pConnection The pointer to the KviIrcConnection class + * \return KviIrcLink + */ + KviIrcLink(KviIrcConnection * pConnection); + + /** + * \brief Destroys the IrcLink object + */ + ~KviIrcLink(); +private: + KviIrcConnection * m_pConnection; // shallow, never null + KviIrcConnectionTarget * m_pTarget; // shallow, never null + KviConsole * m_pConsole; // shallow, never null + KviIrcSocket * m_pSocket; // owned, may be null! + KviMexLinkFilter * m_pLinkFilter; // owned, may be null! + + State m_eState; + + char * m_pReadBuffer; + unsigned int m_uReadBufferLen; + unsigned int m_uReadPackets; + + KviIrcConnectionTargetResolver * m_pResolver; // owned +public: + /** + * \brief Returns the socket + * + * May be null! + * \return KviIrcSocket * + */ + KviIrcSocket * socket(){ return m_pSocket; }; + + /** + * \brief Returns the connection object + * + * Never null + * \return KviIrcConnection * + */ + KviIrcConnection * connection(){ return m_pConnection; }; + + /** + * \brief Returns the console + * + * Never null + * \return KviConsole * + */ + KviConsole * console(){ return m_pConsole; }; + + /** + * \brief Returns the state of the socket + * \return State + */ + State state(){ return m_eState; }; +protected: + /** + * \brief Sends a data packet + * + * This is used by KviIrcConnection::send*() + * This should be used to intercept the outgoing packets when implementing + * a new protocol. + * It's an interface for KviIrcConnection (upper protocol in stack) + * \param pData The pointer to the data packet + * \return bool + */ + virtual bool sendPacket(KviDataBuffer * pData); + + /** + * \brief Clears the output queue + * + * Requests to clear the underlying packet queue. + */ + virtual void clearOutputQueue(bool bPrivateMessagesOnly); + + /** + * \brief Aborts any connection or attempt + * \return void + */ + void abort(); +protected: + /** + * \brief Starts a connection attempt. + * + * It starts the server or proxy DNS lookup. + * The function MUST be asynchronous: it must return successfully and + * report any error by using m_pConnection->linkAttemptFailed() + * It's called internally and it's overridable + * \return void + */ + void start(); +protected: + /** + * \brief Process a packet of raw data from the server + * + * This is called by KviIrcSocket. + * The buffer is iLength+1 bytes long and contains a null terminator + * It's an interface for KviIrcSocket (lower protocol in stack) + * \param buffer The buffer :) + * \param iLength The length of the buffer + * \return void + */ + void processData(char * buffer, int iLength); + + /** + * \brief Called at each state change + * \return void + */ + void socketStateChange(); +protected slots: + /** + * \brief Called when the link filter has been destroyed without permission :D + * + * This should NEVER happen (?) + * This is part of the KviIrcSocket management + * \return void + */ + void linkFilterDestroyed(); +private: + /** + * \brief Destroys the socket + * \return void + */ + void destroySocket(); + + /** + * \brief Creates the socket + * \param szLinkFilterName The source linkfilter name + * \return void + */ + void createSocket(const QString & szLinkFilterName); +signals: + /** + * \brief Emitted when the connection attempt has failed + * \return void + */ + void connectionFailed(); +private slots: + /** + * \brief Called when the DNS lookup has terminated + * \return void + */ + void resolverTerminated(); +}; + +#endif //_KVI_IRCLINK_H_ diff --git a/src/kvirc/kernel/KviIrcSocket.cpp b/src/kvirc/kernel/KviIrcSocket.cpp new file mode 100644 index 000000000..d16d6cee2 --- /dev/null +++ b/src/kvirc/kernel/KviIrcSocket.cpp @@ -0,0 +1,2014 @@ +//============================================================================= +// +// File : KviIrcSocket.cpp +// Creation date : Tue Jul 30 19:25:18 2002 GMT by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviIrcSocket.h" +#include "KviIrcServer.h" +#include "KviProxyDataBase.h" +#include "KviNetUtils.h" +#include "kvi_settings.h" +#include "KviError.h" +#include "KviLocale.h" +#include "KviMemory.h" +#include "kvi_debug.h" +#include "KviCString.h" +#include "KviOptions.h" +#include "KviMemory.h" +#include "kvi_socket.h" +#include "KviConsoleWindow.h" +#include "kvi_out.h" +#include "KviIrcLink.h" +#include "KviIrcConnection.h" +#include "KviDataBuffer.h" + +#ifdef COMPILE_SSL_SUPPORT + #include "KviSSLMaster.h" +#endif + +#include +#include + +#if !defined(COMPILE_ON_WINDOWS) && !defined(COMPILE_ON_MINGW) + #include //for gettimeofday() +#endif +//#include +//#include + +// FIXME: #warning "Lag-o-meter" + +unsigned int g_uNextIrcLinkId = 1; + +KviIrcSocket::KviIrcSocket(KviIrcLink * pLink) +: QObject() +{ + m_uId = g_uNextIrcLinkId; + g_uNextIrcLinkId++; + + m_pLink = pLink; + m_pConsole = m_pLink->console(); + + m_state = Idle; // current socket state + + m_pRsn = 0; // read socket notifier + m_pWsn = 0; // write socket notifier + m_sock = KVI_INVALID_SOCKET; // socket + + m_pIrcServer = 0; // current server data + m_pProxy = 0; // current proxy data + + m_pTimeoutTimer = 0; // timeout for connect() + + m_uReadBytes = 0; // total read bytes per session + m_uSentBytes = 0; // total sent bytes per session + m_uSentPackets = 0; // total packets sent per session + + m_pSendQueueHead = 0; // data queue + m_pSendQueueTail = 0; // + + m_iLastError = KviError_success; + +#ifdef COMPILE_SSL_SUPPORT + m_pSSL = 0; +#endif + + m_tAntiFloodLastMessageTime.tv_sec = 0; + m_tAntiFloodLastMessageTime.tv_usec = 0; + + if(KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout) < 100) + KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout) = 100; // this is our minimum, we don't want to lag the app + + m_bInProcessData = false; + + m_pFlushTimer = new QTimer(); // queue flush timer + connect(m_pFlushTimer,SIGNAL(timeout()),this,SLOT(flushSendQueue())); +} + +KviIrcSocket::~KviIrcSocket() +{ + reset(); + delete m_pFlushTimer; +} + +void KviIrcSocket::reset() +{ +#ifdef COMPILE_SSL_SUPPORT + if(m_pSSL) + { + KviSSLMaster::freeSSL(m_pSSL); + m_pSSL = 0; + } +#endif + if(m_pIrcServer) + { + delete m_pIrcServer; + m_pIrcServer = 0; + } + + if(m_pProxy) + { + delete m_pProxy; + m_pProxy = 0; + } + + if(m_pRsn) + { + delete m_pRsn; + m_pRsn = 0; + } + + if(m_pWsn) + { + delete m_pWsn; + m_pWsn = 0; + } + + if(kvi_socket_isValid(m_sock)) + { + kvi_socket_destroy(m_sock); + m_sock = KVI_INVALID_SOCKET; + } + + if(m_pTimeoutTimer) + { + m_pTimeoutTimer->stop(); + delete m_pTimeoutTimer; + m_pTimeoutTimer = 0; + } + + m_bInProcessData = false; + + m_uReadBytes = 0; + m_uSentBytes = 0; + m_uSentPackets = 0; + m_tAntiFloodLastMessageTime.tv_sec = 0; + m_tAntiFloodLastMessageTime.tv_usec = 0; + + m_bInProcessData = false; + + if(m_pFlushTimer->isActive()) + m_pFlushTimer->stop(); + + queue_removeAllMessages(); + + setState(Idle); +} + +void KviIrcSocket::clearOutputQueue(bool bPrivateMessagesOnly) +{ + if(bPrivateMessagesOnly) + queue_removePrivateMessages(); + else + queue_removeAllMessages(); +} + + +void KviIrcSocket::outputSSLMessage(const QString & szMsg) +{ + m_pConsole->output(KVI_OUT_SSL,__tr2qs("[SSL]: %Q"),&szMsg); +} + +void KviIrcSocket::outputSSLError(const QString & szMsg) +{ + m_pConsole->output(KVI_OUT_SSL,__tr2qs("[SSL ERROR]: %Q"),&szMsg); +} + +void KviIrcSocket::outputProxyMessage(const QString & szMsg) +{ + QStringList list = szMsg.isEmpty() ? QStringList() : szMsg.split("\n",QString::SkipEmptyParts); + + for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) + { + QString szTemporary = (*it).trimmed(); + m_pConsole->output(KVI_OUT_SOCKETMESSAGE,__tr2qs("[PROXY]: %Q"),&(szTemporary)); + } +} + +void KviIrcSocket::outputProxyError(const QString & szMsg) +{ + QStringList list = szMsg.isEmpty() ? QStringList() : szMsg.split("\n",QString::SkipEmptyParts); + + for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) + { + QString szTemporary = (*it).trimmed(); + m_pConsole->output(KVI_OUT_SOCKETERROR,__tr2qs("[PROXY ERROR]: %Q"),&(szTemporary)); + } + +} + +void KviIrcSocket::outputSocketMessage(const QString & szMsg) +{ + m_pConsole->output(KVI_OUT_SOCKETMESSAGE,__tr2qs("[SOCKET]: %Q"),&szMsg); +} + +void KviIrcSocket::outputSocketError(const QString & szMsg) +{ + m_pConsole->output(KVI_OUT_SOCKETERROR,__tr2qs("[SOCKET ERROR]: %Q"),&szMsg); +} + +void KviIrcSocket::outputSocketWarning(const QString & szMsg) +{ + m_pConsole->output(KVI_OUT_SOCKETWARNING,__tr2qs("[SOCKET WARNING]: %Q"),&szMsg); +} + +void KviIrcSocket::setState(SocketState state) +{ + if(state != m_state) + { + m_state = state; + m_pLink->socketStateChange(); + } +} + +void KviIrcSocket::raiseError(int iError) +{ + m_iLastError = iError; + //m_pConsole->socketError(iError); + if((m_iLastError == KviError_remoteEndClosedConnection) && + ( m_state == ProxyHttpError)) + outputSocketMessage(KviError::getDescription(iError)); + else + outputSocketError(KviError::getDescription(iError)); +} + +int KviIrcSocket::startConnection(KviIrcServer * pServer, KviProxy * pProxy, const char * pcBindAddress) +{ + // Attempts to estabilish an IRC connection + // to the server specified by *srv. + // Uses the proxy *prx if not 0 + if(m_state != Idle) + return KviError_anotherConnectionInProgress; + + // Coherent state, thnx. + reset(); + + if(pServer->useSSL()) + { +#ifndef COMPILE_SSL_SUPPORT + return KviError_noSSLSupport; +#endif //COMPILE_SSL_SUPPORT + } + + // Copy the server + m_pIrcServer = new KviIrcServer(*pServer); + + bool bTargetIPv6 = false; + bool bNeedServerIp = !pProxy; + if(pProxy) + bNeedServerIp = ( + (pProxy->protocol() != KviProxy::Http) && (pProxy->protocol() != KviProxy::Socks5) + ); + + // We're going to check the addresses now + + // check the proxy stuff... + if(pProxy) + { + // Yeah...here comes the proxy + m_pProxy = new KviProxy(*pProxy); + // check the proxy IP address + if(m_pProxy->isIPv6()) + { + // IPv6 proxy :) (STILL QUITE UNTESTED ?) +#ifdef COMPILE_IPV6_SUPPORT + bTargetIPv6 = true; + if(!KviNetUtils::isValidStringIPv6(m_pProxy->ip())) + return KviError_invalidProxyAddress; + // SOCKSv4 does not support IPv6 addresses + if(m_pProxy->protocol() == KviProxy::Socks4) + return KviError_socksV4LacksIPv6Support; +#else + return KviError_noIPv6Support; +#endif + } else { + // IPv4 proxy + if(!KviNetUtils::isValidStringIp(m_pProxy->ip())) + return KviError_invalidProxyAddress; + } + } + + if(bNeedServerIp) + { + // check the irc host ip +#ifdef COMPILE_IPV6_SUPPORT + if(m_pIrcServer->isIPv6()) + { + // We have an IPv6 server host (Interesting if proxy is IPv4) + if( !KviNetUtils::isValidStringIPv6(m_pIrcServer->ip()) ) + return KviError_invalidIpAddress; + if(!m_pProxy) + bTargetIPv6 = true; // otherwise the proxy rules + } else { +#endif + // We have an IPv4 server host + if(!KviNetUtils::isValidStringIp(m_pIrcServer->ip())) + return KviError_invalidIpAddress; +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + } + + KviSockaddr sa(pProxy ? m_pProxy->ip().toUtf8().data() : m_pIrcServer->ip().toUtf8().data(), pProxy ? m_pProxy->port() : m_pIrcServer->port(),bTargetIPv6); + + if(!sa.socketAddress()) + return KviError_invalidIpAddress; + + // create the socket +#ifdef COMPILE_IPV6_SUPPORT + m_sock = kvi_socket_create(bTargetIPv6 ? KVI_SOCKET_PF_INET6 : KVI_SOCKET_PF_INET,KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP); +#else + m_sock = kvi_socket_create(KVI_SOCKET_PF_INET,KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP); +#endif + + if(m_sock < 0) + return KviError_socketCreationFailed; + + if(pcBindAddress) + { + // we have to bind the socket to a local address + KviSockaddr localSa(pcBindAddress,0,bTargetIPv6); + bool bBindOk = localSa.socketAddress(); + + if(bBindOk) + { + bBindOk = kvi_socket_bind(m_sock,localSa.socketAddress(),((int)(localSa.addressLength()))); + } + + QString szTmp; + if(bBindOk) + { + if(_OUTPUT_VERBOSE) + KviQString::sprintf(szTmp,__tr2qs("Binding to local address %s"),pcBindAddress); + outputSocketMessage(szTmp); + } else { + if(_OUTPUT_VERBOSE) + KviQString::sprintf(szTmp,__tr2qs("Binding to local address %s failed: the kernel will choose the correct interface"),pcBindAddress); + outputSocketWarning(szTmp); + } + } + + // make it non blocking + if(!kvi_socket_setNonBlocking(m_sock)) + { + reset(); + return KviError_asyncSocketFailed; + } + + if(!kvi_socket_connect(m_sock,sa.socketAddress(),((int)(sa.addressLength())))) + { + // ops... + int iErr = kvi_socket_error(); + + if(!kvi_socket_recoverableConnectError(iErr)) + { + // Ops... + int iSockError = iErr; + if(iSockError == 0) + { + // Zero error ?...let's look closer + int iSize = sizeof(int); + if(!kvi_socket_getsockopt(m_sock,SOL_SOCKET,SO_ERROR,(void *)&iSockError,&iSize)) + iSockError = 0; + } + // die :( + reset(); + // And declare problems :) + if(iSockError) + return KviError::translateSystemError(iSockError); + else return KviError_unknownError; //Error 0 ? + } + } + + // and setup the WRITE notifier... + m_pWsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Write); + QObject::connect(m_pWsn,SIGNAL(activated(int)),this,SLOT(writeNotifierFired(int))); + m_pWsn->setEnabled(true); + + // set the timer + if(KVI_OPTION_UINT(KviOption_uintIrcSocketTimeout) < 5) + KVI_OPTION_UINT(KviOption_uintIrcSocketTimeout) = 5; + + m_pTimeoutTimer = new QTimer(); + QObject::connect(m_pTimeoutTimer,SIGNAL(timeout()),this,SLOT(connectionTimedOut())); + m_pTimeoutTimer->setSingleShot(true); + m_pTimeoutTimer->setInterval(KVI_OPTION_UINT(KviOption_uintIrcSocketTimeout) * 1000); + m_pTimeoutTimer->start(); + + // and wait for connect + setState(Connecting); + + return KviError_success; +} + +void KviIrcSocket::connectionTimedOut() +{ + // the m_pTimeoutTimer fired :( + raiseError(KviError_connectionTimedOut); + reset(); +} + +void KviIrcSocket::writeNotifierFired(int) +{ + // kill the timeout timer + if(m_pTimeoutTimer) + { + delete m_pTimeoutTimer; + m_pTimeoutTimer = 0; + } + + // Check for errors... + int iSockError; + int iSize = sizeof(int); + if(!kvi_socket_getsockopt(m_sock,SOL_SOCKET,SO_ERROR,(void *)&iSockError,&iSize)) + iSockError = -1; + + //sockError = 0; + if(iSockError != 0) + { + //failed + if(iSockError > 0) + iSockError = KviError::translateSystemError(iSockError); + else iSockError = KviError_unknownError; //Error 0 ? + + raiseError(iSockError); + reset(); + return; + } + + // kill the write notifier + delete m_pWsn; + m_pWsn = 0; + + //Succesfully connected... + connectionEstabilished(); +} + +void KviIrcSocket::connectionEstabilished() +{ + if(m_sock == KVI_INVALID_SOCKET) + return; // ops...disconnected in setState() ???? + + if(m_pProxy) + connectedToProxy(); + else connectedToIrcServer(); +} + +void KviIrcSocket::connectedToProxy() +{ + if(!m_pProxy) + qDebug("WARNING: connectedToProxy() without a m_pProxy!"); + + // FIXME: Do we want to support SSL proxies ? + // it would be just a matter of SSL handshaking + // with the proxy + + setState(ProxyLogin); + + if(m_pRsn) + { + delete m_pRsn; + m_pRsn = 0; + } + + m_pRsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); + + QObject::connect(m_pRsn,SIGNAL(activated(int)),this,SLOT(readProxyData(int))); + + switch(m_pProxy->protocol()) + { + case KviProxy::Http: + proxyLoginHttp(); + break; + case KviProxy::Socks5: + proxyLoginV5(); + break; + default: + proxyLoginV4(); + break; + } +} + +void KviIrcSocket::readHttpProxyErrorData(int) +{ + char cBuffer[256]; + int iReadLength; + + iReadLength = kvi_socket_recv(m_sock,cBuffer,255); + if(iReadLength <= 0) + { + handleInvalidSocketRead(iReadLength); + return; + } + + outputProxyMessage(m_pConsole->decodeText(cBuffer)); +} + +void KviIrcSocket::connectedToIrcServer() +{ +#ifdef COMPILE_SSL_SUPPORT + if(m_pIrcServer->useSSL()) + { + enterSSLMode(); + return; + } +#endif //COMPILE_SSL_SUPPORT + linkUp(); +} + +#ifdef COMPILE_SSL_SUPPORT +void KviIrcSocket::enterSSLMode() +{ + Q_ASSERT(!m_pSSL); // Don't call this function twice in a session + + m_pSSL = KviSSLMaster::allocSSL(m_pConsole,m_sock,KviSSL::Client); + if(!m_pSSL) + { + raiseSSLError(); + raiseError(KviError_SSLError); + reset(); + return; + } + setState(SSLHandshake); + doSSLHandshake(0); +} +#endif //COMPILE_SSL_SUPPORT + +void KviIrcSocket::readProxyData(int) +{ + char cBuffer[256]; + int iReadLength; +/* + // THIS IS WORKING CODE THAT SUPPORTS SSL PROXIES! +#ifdef COMPILE_SSL_SUPPORT + if(m_pSSL) + { + readLength = m_pSSL->read(buffer,256); + if(readLength <= 0) + { + // ssl error....? + switch(m_pSSL->getProtocolError(readLength)) + { + case KviSSL::ZeroReturn: + readLength = 0; + break; + case KviSSL::WantRead: + case KviSSL::WantWrite: + // hmmm... + return; + break; + case KviSSL::SyscallError: + { + int iE = m_pSSL->getLastError(true); + if(iE != 0) + { + raiseSSLError(); + raiseError(KviError_SSLError); + reset(); + return; + } + } + break; + case KviSSL::SSLError: + raiseSSLError(); + raiseError(KviError_SSLError); + reset(); + return; + break; + default: + raiseError(KviError_SSLError); + reset(); + return; + break; + + } + handleInvalidSocketRead(readLength); + return; + } + } else { +#endif +*/ + iReadLength = kvi_socket_recv(m_sock,cBuffer,255); + if(iReadLength <= 0) + { + handleInvalidSocketRead(iReadLength); + return; + } +/* +#ifdef COMPILE_SSL_SUPPORT + } +#endif +*/ + // we need at least two bytes... + if(iReadLength < 2) + { + // a single byte of reply means: + // - connection through a 1 bps modem + // - a totally blocked network + // - remote host is not a SOCKS/HTTP server + // Anyway....it is always a meaningless reply + // better to try again later :) + raiseError(KviError_unrecognizedProxyReply); + reset(); + return; + } + + // handle the reply + switch(m_state) + { + case ProxyFinalV4: + //V4 final reply + proxyHandleV4FinalReply((unsigned char)cBuffer[1]); + break; + case ProxySelectAuthMethodV5: + //V5 method selection reply + proxyHandleV5MethodReply((unsigned char)cBuffer[1]); + break; + case ProxyUserPassV5: + //V5 user and pass reply + proxyHandleV5AuthReply((unsigned char)cBuffer[1]); + break; + case ProxyFinalV5: + //V5 final reply + proxyHandleV5FinalReply((unsigned char)cBuffer[1]); + break; + case ProxyFinalHttp: + //Http final reply + cBuffer[iReadLength] = '\0'; + proxyHandleHttpFinalReply(cBuffer,iReadLength); + break; + default: + // what ? + raiseError(KviError_unrecognizedProxyReply); + reset(); + break; + } +} + +void KviIrcSocket::proxyLoginHttp() +{ + // Well..this is just plain and easy: connect to the proxy machine + // and say "CONNECT : HTTP/\n\n" + // if it requires auth then say Proxy-Authorization: Basic user:passwd + // Then expect a server reply header (2 newlines) + // HTTP 200 = Success + // HTTP Anything else = Failure + + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("Using HTTP protocol.")); + + setState(ProxyFinalHttp); + KviCString szTmp(KviCString::Format,"CONNECT %s:%u HTTP/1.0\r\n",m_pIrcServer->hostName().toUtf8().data(),(unsigned int)(m_pIrcServer->port())); + + szTmp.append(KviCString::Format,"User-Agent: KVIrc-ProxyClient/4.0\r\n"); + + if(m_pProxy->hasUser()) + { + KviCString szAuth(KviCString::Format,"%s:%s",m_pProxy->user().toUtf8().data(),m_pProxy->pass().toUtf8().data()); + KviCString szEncoded; + szEncoded.bufferToBase64(szAuth.ptr(),szAuth.len()); + szTmp.append(KviCString::Format,"Proxy-Authorization: Basic %s\r\n\r\n",szEncoded.ptr()); + } else { + szTmp.append("\r\n"); + } + + sendRawData(szTmp.ptr(),szTmp.len()); +} + +void KviIrcSocket::proxyLoginV4() +{ + // SOCKSv4 protocol + // + // 1) CONNECT + // + // The client connects to the SOCKS server and sends a CONNECT request when + // it wants to establish a connection to an application server. The client + // includes in the request packet the IP address and the port number of the + // destination host, and userid, in the following format. + // + // +----+----+----+----+----+----+----+----+----+----+....+----+ + // | VN | CD | DSTPORT | DSTIP | USERID |NULL| + // +----+----+----+----+----+----+----+----+----+----+....+----+ + // # of bytes: 1 1 2 4 variable 1 + // + // VN is the SOCKS protocol version number and should be 4. CD is the + // SOCKS command code and should be 1 for CONNECT request. NULL is a byte + // of all zero bits. + // + // The SOCKS server checks to see whether such a request should be granted + // based on any combination of source IP address, destination IP address, + // destination port number, the userid, and information it may obtain by + // consulting IDENT, cf. RFC 1413. If the request is granted, the SOCKS + // server makes a connection to the specified port of the destination host. + // A reply packet is sent to the client when this connection is established, + // or when the request is rejected or the operation fails. + // + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("Using SOCKSv4 protocol.")); + + m_pProxy->normalizeUserAndPass(); + // the protocol does not specify the "userid" format... + // so build an userid from the pass and/or username... + + KviCString szUserAndPass = m_pProxy->user(); + if(m_pProxy->hasPass()){ + if(szUserAndPass.hasData()) + szUserAndPass.append(' '); + szUserAndPass.append(m_pProxy->pass()); + } + + int iLen = szUserAndPass.len() + 9; + + // build the request packet + char * pcBufToSend = new char[iLen]; + pcBufToSend[0] = (unsigned char)4; //Version 4 + pcBufToSend[1] = (unsigned char)1; //Connect + + quint16 port = (quint16)htons(m_pIrcServer->port()); + KviMemory::move((void *)(pcBufToSend + 2),(void *)&port,2); + + struct in_addr ircInAddr; + + if(!KviNetUtils::stringIpToBinaryIp(m_pIrcServer->ip(),&ircInAddr)) + qDebug("SOCKET INTERNAL ERROR IN IPV4 (SOCKS4) ADDR CONVERSION"); + + quint32 host = (quint32)ircInAddr.s_addr; + KviMemory::move((void *)(pcBufToSend + 4),(void *)&host,4); + KviMemory::move((void *)(pcBufToSend + 8),(void *)(szUserAndPass.ptr()),szUserAndPass.len()); + + pcBufToSend[iLen-1] = 0; //NULL + + // send it into hyperspace... + setState(ProxyFinalV4); + sendRawData(pcBufToSend,iLen); + delete[] pcBufToSend; + // and wait for reply... +} + +void KviIrcSocket::proxyLoginV5() +{ + // SOCKSv5 protocol. + // + // When a TCP-based client wishes to establish a connection to an object + // that is reachable only via a firewall (such determination is left up + // to the implementation), it must open a TCP connection to the + // appropriate SOCKS port on the SOCKS server system. The SOCKS service + // is conventionally located on TCP port 1080. If the connection + // request succeeds, the client enters a negotiation for the + // authentication method to be used, authenticates with the chosen + // method, then sends a relay request. The SOCKS server evaluates the + // request, and either establishes the appropriate connection or denies + // it. + // + // The client connects to the server, and sends a version + // identifier/method selection message: + // + // +----+----------+----------+ + // |VER | NMETHODS | METHODS | + // +----+----------+----------+ + // | 1 | 1 | 1 to 255 | + // +----+----------+----------+ + // + // The VER field is set to X'05' for this version of the protocol. The + // NMETHODS field contains the number of method identifier octets that + // appear in the METHODS field. + // The values currently defined for METHOD are: + // + // o X'00' NO AUTHENTICATION REQUIRED + // o X'01' GSSAPI + // o X'02' USERNAME/PASSWORD + // o X'03' CHAP + // o X'04' to X'7F' IANA ASSIGNED + // o X'80' to X'FE' RESERVED FOR PRIVATE METHODS + // o X'FF' NO ACCEPTABLE METHODS + // + + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("Using SOCKSv5 protocol.")); + + m_pProxy->normalizeUserAndPass(); + // the protocol does not specify the "userid" format... + // so build an userid from the pass and/or username... + + char cBufToSend[4]; + cBufToSend[0] = (unsigned char)5; //use version 5 + int iSendLen = 3; + + if(!(m_pProxy->hasUser() || m_pProxy->hasPass())) + { + // no auth needed. + cBufToSend[1] = (unsigned char)1; //select one method + cBufToSend[2] = (unsigned char)0; //select method 0 : no auth + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("We can accept auth method 0 (no auth)")); + } else { + // we can provide a password and username if needed... + cBufToSend[1] = (unsigned char)2; //select from two methods + cBufToSend[2] = (unsigned char)0; //method 0 or + cBufToSend[3] = (unsigned char)2; //method 2 username/pass auth + iSendLen = 4; + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("We can accept auth method 0 (no auth) or 2 (user/pass)")); + } + + // notify the user before sending...since we may get disconnected + setState(ProxySelectAuthMethodV5); + sendRawData(cBufToSend,iSendLen); + // and wait for response +} + +void KviIrcSocket::proxyAuthUserPassV5() +{ + // Once the SOCKS V5 server has started, and the client has selected the + // Username/Password Authentication protocol, the Username/Password + // subnegotiation begins. This begins with the client producing a + // Username/Password request: + // + // +----+------+----------+------+----------+ + // |VER | ULEN | UNAME | PLEN | PASSWD | + // +----+------+----------+------+----------+ + // | 1 | 1 | 1 to 255 | 1 | 1 to 255 | + // +----+------+----------+------+----------+ + // + // The VER field contains the current version of the subnegotiation, + // which is X'01'. The ULEN field contains the length of the UNAME field + // that follows. The UNAME field contains the username as known to the + // source operating system. The PLEN field contains the length of the + // PASSWD field that follows. The PASSWD field contains the password + // association with the given UNAME. + // + unsigned int uPass = (unsigned int)m_pProxy->passLen(); + unsigned int uUser = (unsigned int)m_pProxy->userLen(); + + if(uPass > 255) + uPass = 255; + + if(uUser > 255) + uUser = 255; + + int iLen = uPass + uUser + 3; + char * pcBufToSend = new char[iLen]; + + //version x'01' + pcBufToSend[0] = (unsigned char)1; + + //length of the username + pcBufToSend[1] = (unsigned char)uUser; + + //username + KviMemory::move((void *)(pcBufToSend + 2),(void *)m_pProxy->user().toUtf8().data(),uUser); + + //length of the password + pcBufToSend[2 + uUser] = (unsigned char)uPass; + KviMemory::move((void *)(pcBufToSend + 3 + uUser),(void *)m_pProxy->pass().toUtf8().data(),uPass); + + // spit out the buffer and wait + setState(ProxyUserPassV5); + sendRawData(pcBufToSend,iLen); + delete[] pcBufToSend; + // and wait for response... +} + +void KviIrcSocket::proxySendTargetDataV5() +{ + // Once the method-dependent subnegotiation has completed, the client + // sends the request details. If the negotiated method includes + // encapsulation for purposes of integrity checking and/or + // confidentiality, these requests MUST be encapsulated in the method- + // dependent encapsulation. + // + // The SOCKS request is formed as follows: + // + // +----+-----+------+------+----------+----------+ + // |VER | CMD | FLAG | ATYP | DST.ADDR | DST.PORT | + // +----+-----+------+------+----------+----------+ + // | 1 | 1 | 1 | 1 | Variable | 2 | + // +----+-----+------+------+----------+----------+ + // + // Where: + // + // o VER protocol version: X'05' + // o CMD + // o CONNECT X'01' + // o BIND X'02' + // o UDP ASSOCIATE X'03' + // o X'04' to X'7F' IANA ASSIGNED + // o X'80' to X'FF' RESERVED FOR PRIVATE METHODS + // o FLAG command dependent flag (defaults to X'00') + // o ATYP address type of following address + // o IP V4 address: X'01' + // o DOMAINNAME: X'03' + // o IP V6 address: X'04' + // o DST.ADDR desired destination address + // o DST.PORT desired destination port in network octet + // order + // + // The SOCKS server will typically evaluate the request based on + // source and destination addresses, and return one or more reply + // messages, as appropriate for the request type. + // + // In an address field (DST.ADDR, BND.ADDR), the ATYP field specifies + // the type of address contained within the field: + // + // o X'01' + // + // The address is a version-4 IP address, with a length of 4 octets. + // + // o X'03' + // + // The address field contains a fully-qualified domain name. The first + // octet of the address field contains the number of octets of name that + // follow, there is no terminating NUL octet. + // + // o X'04' + // + // The address is a version-6 IP address, with a length of 16 octets. + bool bRemoteDns=!( + ( + KviNetUtils::isValidStringIp(m_pIrcServer->ip()) + #ifdef COMPILE_IPV6_SUPPORT + || KviNetUtils::isValidStringIPv6(m_pIrcServer->ip()) + #endif + ) + + && m_pIrcServer->cacheIp() + ); + int iBufLen = bRemoteDns ? 4 + 1 + m_pIrcServer->hostName().toUtf8().length() + 2 + : (m_pIrcServer->isIPv6() ? 22 : 10); + char * pcBufToSend = (char *)KviMemory::allocate(sizeof(char) * iBufLen); + pcBufToSend[0] = (unsigned char)5; //Proto 5 + pcBufToSend[1] = (unsigned char)1; //CONNECT + pcBufToSend[2] = (unsigned char)0; //RSV + + if(bRemoteDns) + { + bRemoteDns = true; + pcBufToSend[3] = 3; + pcBufToSend[4] = m_pIrcServer->hostName().toUtf8().length(); + } else { + pcBufToSend[3] = (unsigned char)m_pIrcServer->isIPv6() ? 4 : 1; // IPv6 : IPv4 + } + + if(bRemoteDns) + { + KviMemory::move((void *)(pcBufToSend + 5), + (void *)(m_pIrcServer->hostName().toUtf8().data()), + m_pIrcServer->hostName().toUtf8().length()); + quint16 port = (quint16)htons(m_pIrcServer->port()); + KviMemory::move((void *)(pcBufToSend + 4 + 1 + m_pIrcServer->hostName().toUtf8().length()),(void *)&port,2); + } else if(m_pIrcServer->isIPv6()) { +#ifdef COMPILE_IPV6_SUPPORT + struct in6_addr ircInAddr; + + if(!KviNetUtils::stringIpToBinaryIp_V6(m_pIrcServer->ip(),&ircInAddr)) + qDebug("SOCKET INTERNAL ERROR IN IPV6 ADDR CONVERSION"); + KviMemory::move((void *)(pcBufToSend + 4),(void *)(&ircInAddr),4); + quint16 port = (quint16)htons(m_pIrcServer->port()); + KviMemory::move((void *)(pcBufToSend + 20),(void *)&port,2); +#endif + } else { + struct in_addr ircInAddr; + + if(!KviNetUtils::stringIpToBinaryIp(m_pIrcServer->ip(),&ircInAddr)) + qDebug("SOCKET INTERNAL ERROR IN IPV4 ADDR CONVERSION"); + quint32 host = (quint32)ircInAddr.s_addr; + KviMemory::move((void *)(pcBufToSend + 4),(void *)&host,4); + quint16 port = (quint16)htons(m_pIrcServer->port()); + KviMemory::move((void *)(pcBufToSend + 8),(void *)&port,2); + } + + // send it into hyperspace... + setState(ProxyFinalV5); + sendRawData(pcBufToSend,iBufLen); + KviMemory::free(pcBufToSend); + // and wait for reply... +} + +void KviIrcSocket::proxyHandleV5AuthReply(unsigned char cReply) +{ + // The server verifies the supplied UNAME and PASSWD, and sends the + // following response: + // + // +----+--------+ + // |VER | STATUS | + // +----+--------+ + // | 1 | 1 | + // +----+--------+ + // + // A STATUS field of X'00' indicates success. If the server returns a + // `failure' (STATUS value other than X'00') status, it MUST close the + // connection. + // + if(cReply == 0) + { + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("Proxy response: auth OK: access granted")); + proxySendTargetDataV5(); + return; + } + raiseError(KviError_proxyAuthFailed); + reset(); +} + +void KviIrcSocket::proxyHandleV5MethodReply(unsigned char cReply) +{ + // The server selects from one of the methods given in METHODS, and + // sends a METHOD selection message: + // + // +----+--------+ + // |VER | METHOD | + // +----+--------+ + // | 1 | 1 | + // +----+--------+ + // + // If the selected METHOD is X'FF', none of the methods listed by the + // client are acceptable, and the client MUST close the connection. + // + // The values currently defined for METHOD are: + // + // o X'00' NO AUTHENTICATION REQUIRED + // o X'01' GSSAPI + // o X'02' USERNAME/PASSWORD + // o X'03' CHAP + // o X'04' to X'7F' IANA ASSIGNED + // o X'80' to X'FE' RESERVED FOR PRIVATE METHODS + // o X'FF' NO ACCEPTABLE METHODS + // + if(cReply == 0) + { + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("Proxy response: Auth method OK: using method 0 (no auth)")); + proxySendTargetDataV5(); + return; + } + + if(cReply == 2) + { + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("Proxy response: Auth method OK: using method 2 (user/pass)")); + proxyAuthUserPassV5(); + return; + } + + //Request rejected + if(cReply == 0xFF) + { + raiseError(KviError_proxyNoAcceptableAuthMethod); + reset(); + } else { + // unrecognized... + raiseError(KviError_unrecognizedProxyReply); + reset(); + } +} + +void KviIrcSocket::proxyHandleV5FinalReply(unsigned char cReply) +{ + // + // The SOCKS request information is sent by the client as soon as it has + // established a connection to the SOCKS server, and completed the + // authentication negotiations. The server evaluates the request, and + // returns a reply formed as follows: + // + // +----+-----+------+------+----------+----------+ + // |VER | REP | FLAG | ATYP | BND.ADDR | BND.PORT | + // +----+-----+------+------+----------+----------+ + // | 1 | 1 | 1 | 1 | Variable | 2 | + // +----+-----+------+------+----------+----------+ + // + // Where: + // o VER protocol version: X'05' + // o REP Reply field: + // o X'00' succeeded + // o X'01' general SOCKS server failure + // o X'02' connection not allowed by ruleset + // o X'03' Network unreachable + // o X'04' Host unreachable + // o X'05' Connection refused + // o X'06' TTL expired + // o X'07' Command not supported + // o X'08' Address type not supported + // o X'09' Invalid address + // o X'0A' to X'FF' unassigned + // o FLAG command dependent flag + // o ATYP address type of following address + // o IP V4 address: X'01' + // o DOMAINNAME: X'03' + // o IP V6 address: X'04' + // o BND.ADDR server bound address + // o BND.PORT server bound port in network octet order + // + if(cReply == 0) + { + // Request granted + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("Proxy response: target data OK: request granted")); + connectedToIrcServer(); + } else { + //Request rejected + int iErr; + switch(cReply) + { + case 1: iErr = KviError_proxyReply01GeneralSOCKSFailure; break; + case 2: iErr = KviError_proxyReply02ConnectionNotAllowed; break; + case 3: iErr = KviError_proxyReply03NetworkUnreachable; break; + case 4: iErr = KviError_proxyReply04HostUnreachable; break; + case 5: iErr = KviError_proxyReply05ConnectionRefused; break; + case 6: iErr = KviError_proxyReply06TTLExpired; break; + case 7: iErr = KviError_proxyReply07CommandNotSupported; break; + case 8: iErr = KviError_proxyReply08AddressTypeNotSupported; break; + case 9: iErr = KviError_proxyReply09InvalidAddress; break; + default: iErr = KviError_unrecognizedProxyReply; break; + } + raiseError(iErr); + reset(); + } +} + +void KviIrcSocket::proxyHandleV4FinalReply(unsigned char cReply) +{ + // If the request is granted, the SOCKS + // server makes a connection to the specified port of the destination host. + // A reply packet is sent to the client when this connection is established, + // or when the request is rejected or the operation fails. + // + // + // +----+----+----+----+----+----+----+----+ + // | VN | CD | DSTPORT | DSTIP | + // +----+----+----+----+----+----+----+----+ + // # of bytes: 1 1 2 4 + // + // VN is the version of the reply code and should be 0. CD is the result + // code with one of the following values: + // + // 90: request granted + // 91: request rejected or failed + // 92: request rejected becasue SOCKS server cannot connect to + // identd on the client + // 93: request rejected because the client program and identd + // report different user-ids + // + // The remaining fields are ignored. + // + // The SOCKS server closes its connection immediately after notifying + // the client of a failed or rejected request. For a successful request, + // the SOCKS server gets ready to relay traffic on both directions. This + // enables the client to do I/O on its connection as if it were directly + // connected to the application server. + if(cReply == 90) + { + // Request granted + if(_OUTPUT_VERBOSE) + outputProxyMessage(__tr2qs("Proxy response: target data OK: request granted")); + connectedToIrcServer(); + } else { + //Request rejected + int iErr; + switch(cReply) + { + case 91: iErr = KviError_proxyReply91RequestFailed; break; + case 92: iErr = KviError_proxyReply92IdentFailed; break; + case 93: iErr = KviError_proxyReply93IdentNotMatching; break; + default: iErr = KviError_unrecognizedProxyReply; break; + } + raiseError(iErr); + reset(); + } + // Just looked out of the window... + // Hmmmm...strange light outside... + // Looked at the clock...6:34 ! + // I think I'll go sleep.... :) +} + +void KviIrcSocket::proxyHandleHttpFinalReply(const char * pcBuffer, int) +{ + // Escape character is '^]'. + // CONNECT warszawa.irc.pl:6667 HTTP/1.0 + // + // HTTP/1.0 200 Connection established + + KviCString szTmp = pcBuffer; + // FIXME: #warning "We could even show the proxy output here...!" + szTmp.cutFromFirst('\n'); + szTmp.trimmed(); + + if(kvi_strEqualCIN(szTmp.ptr(),"HTTP",4)) + { + int iIdx = szTmp.findFirstIdx(" 200 "); + if(iIdx != -1) + { + if(iIdx == szTmp.findFirstIdx(' ')) + { + QString szMsg = __tr2qs("Proxy response: "); + szMsg += szTmp.ptr(); + if(_OUTPUT_VERBOSE) + outputProxyMessage(szMsg); + connectedToIrcServer(); + return; + } + } + } + + outputProxyError(__tr2qs("Proxy said something about: \n")); + outputProxyMessage(m_pConsole->decodeText(pcBuffer)); + + //Read HTTP error page and show it + + if(m_pWsn) + { + delete m_pWsn; + m_pWsn = 0; + } + + if(m_pRsn) + { + delete m_pRsn; + m_pRsn = 0; + } + + m_pRsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); + QObject::connect(m_pRsn,SIGNAL(activated(int)),this,SLOT(readHttpProxyErrorData(int))); + m_pRsn->setEnabled(true); + + setState(ProxyHttpError); + + //raiseError(KviError_proxyHttpFailure); + //reset(); +} + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// SSL HANDSHAKE +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + +#ifdef COMPILE_SSL_SUPPORT +void KviIrcSocket::printSSLPeerCertificate() +{ + KviSSLCertificate * c = m_pSSL->getPeerCertificate(); + if(c) + { + //m_pConsole->socketEvent(SSLCertificate,(void *)c); + if(_OUTPUT_VERBOSE) + KviSSLMaster::printSSLCertificate(m_pConsole,__tr("Server X509 certificate"),c); + delete c; + } else { + if(_OUTPUT_VERBOSE) + outputSSLMessage(__tr2qs("The server didn't provide a certificate")); + } +} + +void KviIrcSocket::printSSLCipherInfo() +{ + KviSSLCipherInfo * ci = m_pSSL->getCurrentCipherInfo(); + if(ci) + { + //m_pConsole->socketEvent(SSLCipherInfo,(void *)ci); + KviSSLMaster::printSSLCipherInfo(m_pConsole,__tr("Current transmission cipher"),ci); + delete ci; + } else { + if(_OUTPUT_VERBOSE) + outputSSLMessage(__tr2qs("Unable to determine the current cipher")); + } +} + +void KviIrcSocket::raiseSSLError() +{ + KviCString szBuffer; + while(m_pSSL->getLastErrorString(szBuffer)) + { + outputSSLError(szBuffer.ptr()); + } +} +#endif // COMPILE_SSL_SUPPORT + +void KviIrcSocket::doSSLHandshake(int) +{ +#ifdef COMPILE_SSL_SUPPORT + KVI_ASSERT(m_pSSL); + + if(m_pRsn) + { + delete m_pRsn; + m_pRsn = 0; + } + + if(m_pWsn) + { + delete m_pWsn; + m_pWsn = 0; + } + + if(!m_pSSL) + { + qDebug("Ops... Have I lost the SSL class ?"); + reset(); + return; // ops ? + } + + // We avoid to reset() the socket while in a processData() call (see bug #600) + switch(m_pSSL->connect()) + { + case KviSSL::Success: + // done! + printSSLCipherInfo(); + printSSLPeerCertificate(); + linkUp(); + break; + case KviSSL::WantRead: + m_pRsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); + QObject::connect(m_pRsn,SIGNAL(activated(int)),this,SLOT(doSSLHandshake(int))); + m_pRsn->setEnabled(true); + break; + case KviSSL::WantWrite: + m_pWsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Write); + QObject::connect(m_pWsn,SIGNAL(activated(int)),this,SLOT(doSSLHandshake(int))); + m_pWsn->setEnabled(true); + break; + case KviSSL::RemoteEndClosedConnection: + raiseError(KviError_remoteEndClosedConnection); +// reset(); + break; + case KviSSL::SSLError: + raiseSSLError(); + raiseError(KviError_SSLError); +// reset(); + break; + case KviSSL::SyscallError: + { + // syscall problem + int iErr = kvi_socket_error(); + if(!kvi_socket_recoverableError(iErr)) + { + // Declare problems :) + raiseError((iErr ? KviError::translateSystemError(iErr) : KviError_unknownError)); + } else { + // can recover ? (EAGAIN, EINTR ?) + m_pWsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Write); + QObject::connect(m_pWsn,SIGNAL(activated(int)),this,SLOT(doSSLHandshake(int))); + m_pWsn->setEnabled(true); + return; + } +// reset(); + } + break; + default: + raiseError(KviError_SSLError); +// reset(); + break; + } + +#else //COMPILE_SSL_SUPPORT + qDebug("Ops.. SSL handshake without SSL support! Aborting!"); + exit(-1); +#endif //COMPILE_SSL_SUPPORT +} + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// LINK UP +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +void KviIrcSocket::linkUp() +{ + setState(Connected); + + // the last check + if(m_sock == KVI_INVALID_SOCKET) + return; // ops...disconnected in setState() ???? + + // ok.. it seems that we're really up and running now! + if(m_pWsn) + { + delete m_pWsn; + m_pWsn = 0; + } + + if(m_pRsn) + { + delete m_pRsn; + m_pRsn = 0; + } + + m_pRsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); + QObject::connect(m_pRsn,SIGNAL(activated(int)),this,SLOT(readData(int))); + m_pRsn->setEnabled(true); + + // yahoo! +} + +void KviIrcSocket::readData(int) +{ + //read data + char cBuffer[1025]; + int iReadLength; +#ifdef COMPILE_SSL_SUPPORT + if(m_pSSL) + { + iReadLength = m_pSSL->read(cBuffer,1024); + if(iReadLength <= 0) + { + // ssl error....? + switch(m_pSSL->getProtocolError(iReadLength)) + { + case KviSSL::ZeroReturn: + iReadLength = 0; + break; + case KviSSL::WantRead: + case KviSSL::WantWrite: + // hmmm... + return; + break; + case KviSSL::SyscallError: + { + int iE = m_pSSL->getLastError(true); + if(iE != 0) + { + raiseSSLError(); + raiseError(KviError_SSLError); + reset(); + return; + } + } + break; + case KviSSL::SSLError: + raiseSSLError(); + raiseError(KviError_SSLError); + reset(); + return; + break; + default: + raiseError(KviError_SSLError); + reset(); + return; + break; + + } + handleInvalidSocketRead(iReadLength); + return; + } + } else { +#endif + iReadLength = kvi_socket_recv(m_sock,cBuffer,1024); + if(iReadLength <= 0) + { + handleInvalidSocketRead(iReadLength); + return; + } +#ifdef COMPILE_SSL_SUPPORT + } +#endif + + + //terminate our buffer + (*(cBuffer + iReadLength))='\0'; + + m_uReadBytes += iReadLength; + + // Shut up the socket notifier + // in case that we enter in a local loop somewhere + // while processing data... + m_pRsn->setEnabled(false); + // shut also the flushing of the message queue + // in this way we prevent disconnect detection + // during the processing of a message effectively + // making it always an asynchronous event. + m_bInProcessData = true; + + m_pLink->processData(cBuffer,iReadLength); + // after this line there should be nothing that relies + // on the "connected" state of this socket. + // It may happen that it has been reset() in the middle of the processData() call + // and (unverified) it might have been even deleted. + + // re-enable the socket notifier... (if it's still there) + if(m_pRsn) + m_pRsn->setEnabled(true); + // and the message queue flushing + m_bInProcessData = false; + // and flush the queue too! + if(m_pSendQueueHead) + flushSendQueue(); +} + +/* +void KviIrcSocket::processData(char * buffer,int) +{ + register char *p=buffer; + char *beginOfCurData = buffer; + int bufLen = 0; + char *messageBuffer = (char *)KviMemory::allocate(1); + + // Shut up the socket notifier + // in case that we enter in a local loop somewhere + // while processing data... + m_pRsn->setEnabled(false); + // shut also the flushing of the message queue + // in this way we prevent disconnect detection + // during the processing of a message effectively + // making it always an asynchronous event. + m_bInProcessData = true; + + while(*p) + { + if((*p == '\r' )||(*p == '\n')) + { + //found a CR or LF... + //prepare a message buffer + bufLen = p - beginOfCurData; + //check for previous unterminated data + if(m_uReadBufferLen > 0){ + KVI_ASSERT(m_pReadBuffer); + messageBuffer = (char *)KviMemory::reallocate(messageBuffer,bufLen + m_uReadBufferLen + 1); + KviMemory::move(messageBuffer,m_pReadBuffer,m_uReadBufferLen); + KviMemory::move((void *)(messageBuffer + m_uReadBufferLen),beginOfCurData,bufLen); + *(messageBuffer + bufLen + m_uReadBufferLen) = '\0'; + m_uReadBufferLen = 0; + KviMemory::free(m_pReadBuffer); + m_pReadBuffer = 0; + } else { + __range_invalid(m_pReadBuffer); + messageBuffer = (char *)KviMemory::reallocate(messageBuffer,bufLen + 1); + KviMemory::move(messageBuffer,beginOfCurData,bufLen); + *(messageBuffer + bufLen) = '\0'; + } + m_uReadPackets++; + + // FIXME: actually it can happen that the socket gets disconnected + // in a incomingMessage() call. + // The problem might be that some other parts of kvirc assume + // that the irc context still exists after a failed write to the socket + // (some parts don't even check the return value!) + // If the problem presents itself again then the solution is: + // disable queue flushing for the "incomingMessage" call + // and just call queue_insertMessage() + // then after the call terminates flush the queue (eventually detecting + // the disconnect and thus destroying the irc context). + // For now we try to rely on the remaining parts to handle correctly + // such conditions. Let's see... + + m_pConsole->incomingMessage(messageBuffer); + + if(m_state != Connected) + { + // Disconnected in KviConsole::incomingMessage() call. + // This may happen for several reasons (local event loop + // with the user hitting the disconnect button, a scripting + // handler event that disconnects explicitly) + // + // We handle it by simply returning control to readData() which + // will return immediately (and safely) control to Qt + KviMemory::free(messageBuffer); + m_bInProcessData = false; + return; + } + + while(*p && ((*p=='\r')||(*p=='\n')) )p++; + beginOfCurData = p; + + } else p++; + } + + //now *p == '\0' + //beginOfCurData points to '\0' if we have + //no more stuff to parse, or points to something + //different than '\r' or '\n'... + if(*beginOfCurData) + { + //Have remaining data...in the local buffer + bufLen = p - beginOfCurData; + if(m_uReadBufferLen > 0){ + //and there was more stuff saved... (really slow connection) + KVI_ASSERT(m_pReadBuffer); + m_pReadBuffer =(char *)KviMemory::reallocate(m_pReadBuffer,m_uReadBufferLen + bufLen); + KviMemory::move((void *)(m_pReadBuffer+m_uReadBufferLen),beginOfCurData,bufLen); + m_uReadBufferLen += bufLen; + } else { + // + __range_invalid(m_pReadBuffer); + m_uReadBufferLen = bufLen; + m_pReadBuffer =(char *)KviMemory::allocate(m_uReadBufferLen); + KviMemory::move(m_pReadBuffer,beginOfCurData,m_uReadBufferLen); + } + //The m_pReadBuffer contains at max 1 irc message... + //that can not be longer than 510 bytes (the message is not CRLF terminated) + // FIXME: Is this limit *really* valid on all servers ? + if(m_uReadBufferLen > 510)qDebug("WARNING : Receiving an invalid irc message from server."); + } + KviMemory::free(messageBuffer); + + // re-enable the socket notifier... + m_pRsn->setEnabled(true); + // and the message queue flushing + m_bInProcessData = false; + // and flush the queue too! + if(m_pSendQueueHead)flushSendQueue(); +} +*/ + +void KviIrcSocket::abort() +{ + // flush the send queue if possible (and if not yet disconnected in fact) + if(m_state == Connected) + flushSendQueue(); + if(m_state != Idle) + raiseError(KviError_operationAborted); + // and reset + reset(); +} + +void KviIrcSocket::handleInvalidSocketRead(int iReadLength) +{ + KVI_ASSERT(iReadLength <= 0); + if(iReadLength == 0) + { + raiseError(KviError_remoteEndClosedConnection); + reset(); + } else { + //check for transmission errors + int iErr = kvi_socket_error(); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + if((iErr != EAGAIN) && (iErr != EINTR) && (iErr != WSAEWOULDBLOCK)) +#else + if((iErr != EAGAIN) && (iErr != EINTR)) +#endif + { + if(iErr > 0) + raiseError((KviError::translateSystemError(iErr))); + else + raiseError(KviError_remoteEndClosedConnection); + reset(); + } //else transient error...wait again... + } +} + +void KviIrcSocket::queue_insertMessage(KviIrcSocketMsgEntry * pMsg) +{ + KVI_ASSERT(pMsg); + + pMsg->next_ptr = 0; + + if(m_pSendQueueHead) + { + m_pSendQueueTail->next_ptr = pMsg; + m_pSendQueueTail = pMsg; + } else { + m_pSendQueueHead = pMsg; + m_pSendQueueTail = pMsg; + } +} + +void KviIrcSocket::free_msgEntry(KviIrcSocketMsgEntry * e) +{ + if(e->pData) + delete e->pData; + + e->pData = 0; + KviMemory::free(e); +} + +bool KviIrcSocket::queue_removeMessage() +{ + KVI_ASSERT(m_pSendQueueTail); + KVI_ASSERT(m_pSendQueueHead); + + if(m_pSendQueueHead->pData) + delete m_pSendQueueHead->pData; + + KviIrcSocketMsgEntry * pEntry = m_pSendQueueHead; + m_pSendQueueHead = pEntry->next_ptr; + KviMemory::free((void *)pEntry); + + if(m_pSendQueueHead == 0) + { + m_pSendQueueTail = 0; + return false; + } else return true; +} + +void KviIrcSocket::queue_removeAllMessages() +{ + if(m_pSendQueueHead) + while(queue_removeMessage()) {} +} + +void KviIrcSocket::queue_removePrivateMessages() +{ + KviIrcSocketMsgEntry * pPrevEntry = 0; + KviIrcSocketMsgEntry * pEntry = m_pSendQueueHead; + while(pEntry) + { + if(pEntry->pData->size() > 7) + { + if(kvi_strEqualCIN((char *)(pEntry->pData->data()),"PRIVMSG",7)) + { + // remove it + if(pPrevEntry) + { + pPrevEntry->next_ptr = pEntry->next_ptr; + if(!pPrevEntry->next_ptr) + m_pSendQueueTail = 0; + free_msgEntry(pEntry); + pEntry = pPrevEntry->next_ptr; + } else { + m_pSendQueueHead = pEntry->next_ptr; + if(!m_pSendQueueHead) + m_pSendQueueTail = 0; + free_msgEntry(pEntry); + pEntry = m_pSendQueueHead; + } + continue; + } + } + pPrevEntry = pEntry; + pEntry = pEntry->next_ptr; + } +} + +void KviIrcSocket::flushSendQueue() +{ + // If we're called from the flush timer, stop it + if(m_pFlushTimer->isActive()) + m_pFlushTimer->stop(); + + // Ok...have something to send... + KVI_ASSERT(m_state != Idle); + + struct timeval curTime; + + while(m_pSendQueueHead) + { + if(KVI_OPTION_BOOL(KviOption_boolLimitOutgoingTraffic)) + { + kvi_gettimeofday(&curTime,0); + + int iTimeDiff = curTime.tv_usec - m_tAntiFloodLastMessageTime.tv_usec; + iTimeDiff += (curTime.tv_sec - m_tAntiFloodLastMessageTime.tv_sec) * 1000000; + + if(((unsigned int)iTimeDiff) < KVI_OPTION_UINT(KviOption_uintOutgoingTrafficLimitUSeconds)) + { + // need to wait for a while.... + m_pFlushTimer->start(((KVI_OPTION_UINT(KviOption_uintOutgoingTrafficLimitUSeconds) - iTimeDiff) / 1000) + 1); + return; + } // else can send + } + // Write one data buffer... + int iResult; +#ifdef COMPILE_SSL_SUPPORT + if(m_pSSL) + { + iResult = m_pSSL->write((char *)(m_pSendQueueHead->pData->data()),m_pSendQueueHead->pData->size()); + } else { +#endif + iResult = kvi_socket_send(m_sock,(char *)(m_pSendQueueHead->pData->data()),m_pSendQueueHead->pData->size()); +#ifdef COMPILE_SSL_SUPPORT + } +#endif + if(iResult == (int)m_pSendQueueHead->pData->size()) + { + // Succesfull send...remove this data buffer + m_uSentPackets++; + m_uSentBytes += iResult; + //if(m_pConsole->hasMonitors())outgoingMessageNotifyMonitors((char *)(m_pSendQueueHead->pData->data()),result); + queue_removeMessage(); + if(KVI_OPTION_BOOL(KviOption_boolLimitOutgoingTraffic)) + { + m_tAntiFloodLastMessageTime.tv_sec = curTime.tv_sec; + m_tAntiFloodLastMessageTime.tv_usec = curTime.tv_usec; + } + // And try next buffer... + continue; + } else { + // Something wrong ? +#ifdef COMPILE_SSL_SUPPORT + if(iResult <= 0) + { + if(m_pSSL) + { + // ops...might be an SSL error + switch(m_pSSL->getProtocolError(iResult)) + { + case KviSSL::WantWrite: + case KviSSL::WantRead: + // Async continue... + m_pFlushTimer->start(KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout)); + return; + break; + case KviSSL::SyscallError: + if(iResult == 0) + { + raiseSSLError(); + raiseError(KviError_remoteEndClosedConnection); + reset(); + return; + } else { + int iSSLErr = m_pSSL->getLastError(true); + if(iSSLErr != 0) + { + raiseSSLError(); + raiseError(KviError_SSLError); + reset(); + return; + } else { + goto handle_system_error; + } + } + break; + case KviSSL::SSLError: + raiseSSLError(); + raiseError(KviError_SSLError); + reset(); + return; + break; + default: + raiseError(KviError_SSLError); + reset(); + return; + break; + } + } + } else { +#else // COMPILE_SSL_SUPPORT + if(iResult >= 0) + { + if(iResult > 0) + { +#endif // COMPILE_SSL_SUPPORT + + // Partial send...need to finish it later + m_pSendQueueHead->pData->remove(iResult); + + m_uSentBytes += iResult; + if(_OUTPUT_VERBOSE) + outputSocketWarning(__tr2qs("Partial socket write: packet broken into smaller pieces.")); +#ifndef COMPILE_SSL_SUPPORT + } +#endif // COMPILE_SSL_SUPPORT + // Async continue... + m_pFlushTimer->start(KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout)); + return; + } + +handle_system_error: + // Oops...error ? + int iErr = kvi_socket_error(); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + if((iErr == EAGAIN) || (iErr == EINTR) || (iErr == WSAEWOULDBLOCK)) +#else + if((iErr == EAGAIN)||(iErr == EINTR)) +#endif + { + // Transient error...partial send as before... + if(_OUTPUT_VERBOSE) + outputSocketWarning(__tr2qs("Partial socket write: packet broken into smaller pieces.")); + // Async continue... + m_pFlushTimer->start(KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout)); + return; + } else { + // Disconnected... :( + raiseError((KviError::translateSystemError(iErr))); + reset(); + return; + } + } + } + //flushed completely ... +} + +bool KviIrcSocket::getLocalHostIp(QString & szIp, bool bIPv6) +{ + if(m_state != Connected) + return false; + + if(bIPv6) + { +#ifdef COMPILE_IPV6_SUPPORT + struct sockaddr_in6 name; + int iLen = sizeof(name); + if(!kvi_socket_getsockname(m_sock, (struct sockaddr *)&name,&iLen))return false; + //I assume that getsockname returns data in Network byte order... + //The man page misses to specify that... + if(!KviNetUtils::binaryIpToStringIp_V6(name.sin6_addr,szIp)) + return false; + + return true; +#else + return false; // no support +#endif + } + + struct sockaddr_in name; + int iLen = sizeof(name); + if(!kvi_socket_getsockname(m_sock, (struct sockaddr *)&name,&iLen)) + return false; + //I assume that getsockname returns data in Network byte order... + //The man page misses to specify that... + if(!KviNetUtils::binaryIpToStringIp(name.sin_addr,szIp)) + return false; + + return true; +} + +/* +bool KviIrcSocket::sendFmtData(const char *fmt,...) +{ + if(m_state != Connected)return false; + //new buffer + KviIrcSocketMsgEntry *ptr = (KviIrcSocketMsgEntry *)KviMemory::allocate(sizeof(KviIrcSocketMsgEntry)); + ptr->pData = new KviDataBuffer(512); + kvi_va_list(list); + kvi_va_start(list,fmt); + bool bTruncated; + //sprintf the buffer up to 512 chars (adds a CRLF too) + int iLen = kvi_irc_vsnprintf((char *)(ptr->pData->data()),fmt,list,&bTruncated); + kvi_va_end(list); + //adjust the buffer size + if(iLen < 512)ptr->pData->resize(iLen); + if(bTruncated) + { + if(_OUTPUT_VERBOSE) + outputSocketWarning(__tr2qs("Socket message truncated to 512 bytes.")); + } + + queue_insertMessage(ptr); + if(!m_bInProcessData)flushSendQueue(); + return (m_state != Idle); +} +*/ +/* +bool KviIrcSocket::sendData(const char *buffer,int buflen) +{ + if(m_state != Connected)return false; + //new buffer + KviIrcSocketMsgEntry *ptr = (KviIrcSocketMsgEntry *)KviMemory::allocate(sizeof(KviIrcSocketMsgEntry)); + if(buflen < 0)buflen = strlen(buffer); + if(buflen > 510) + { + buflen = 510; + if(_OUTPUT_VERBOSE) + outputSocketWarning(__tr2qs("Socket message truncated to 512 bytes.")); + } + ptr->pData = new KviDataBuffer(buflen + 2); + KviMemory::move(ptr->pData->data(),buffer,buflen); + *(ptr->pData->data()+buflen)='\r'; + *(ptr->pData->data()+buflen+1)='\n'; + + queue_insertMessage(ptr); + if(!m_bInProcessData)flushSendQueue(); + return (m_state != Idle); +} +*/ + +bool KviIrcSocket::sendRawData(const char * pcBuffer, int iBuflen) +{ + if((m_state == Idle) || (m_state == Connecting)) + return false; + + //new buffer + KviIrcSocketMsgEntry * pEntry = (KviIrcSocketMsgEntry *)KviMemory::allocate(sizeof(KviIrcSocketMsgEntry)); + pEntry->pData = new KviDataBuffer(iBuflen); + + KviMemory::move(pEntry->pData->data(),pcBuffer,iBuflen); + queue_insertMessage(pEntry); + + if(!m_bInProcessData) + flushSendQueue(); + + return (m_state != Idle); +} + +bool KviIrcSocket::sendPacket(KviDataBuffer * pData) +{ + if(m_state != Connected) + { + delete pData; + pData = 0; + return false; + } + + KviIrcSocketMsgEntry * pEntry = (KviIrcSocketMsgEntry *)KviMemory::allocate(sizeof(KviIrcSocketMsgEntry)); + pEntry->pData = pData; + queue_insertMessage(pEntry); + + if(!m_bInProcessData) + flushSendQueue(); + + return (m_state != Idle); +} diff --git a/src/kvirc/kernel/KviIrcSocket.h b/src/kvirc/kernel/KviIrcSocket.h new file mode 100644 index 000000000..e9b3b50ce --- /dev/null +++ b/src/kvirc/kernel/KviIrcSocket.h @@ -0,0 +1,520 @@ +#ifndef _KVI_IRCSOCKET_H_ +#define _KVI_IRCSOCKET_H_ +//============================================================================= +// +// File : KviIrcSocket.h +// Creation date : Tue Jul 30 19:25:17 2002 GMT by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviIrcSocket.h +* \author Szymon Stefanek +* \brief Lower stack protocol for IRC connection +*/ + +#include "kvi_settings.h" +#include "KviCString.h" +#include "kvi_sockettype.h" +#include "KviTimeUtils.h" +#include "KviPointerList.h" + +#include + +class QTimer; +class QSocketNotifier; +class KviIrcServer; +class KviProxy; +class KviIrcConnection; +class KviIrcConnectionTarget; +class KviIrcLink; +class KviSSL; +class KviConsole; +class KviDataBuffer; + +/** +* \typedef KviIrcSocketMsgEntry +* \struct _KviIrcSocketMsgEntry +* \brief Holds the messages entries +*/ +typedef struct _KviIrcSocketMsgEntry +{ + KviDataBuffer * pData; + struct _KviIrcSocketMsgEntry * next_ptr; +} KviIrcSocketMsgEntry; + +/** +* \class KviIrcSocket +* \brief This class is the lowest level of the KVIrc networking stack +* +* It sends and receives raw data packets from the underlying system socket. +* It should output only verbose "progress" messages. +*/ +class KVIRC_API KviIrcSocket : public QObject +{ + Q_OBJECT +public: + /** + * \brief Constructs the IRC socket object + * \param pLink The middle networking stack class + * \return KviIrcSocket + */ + KviIrcSocket(KviIrcLink * pLink); + + /** + * \brief Destroys the IRC socket object + */ + ~KviIrcSocket(); +public: + /** + * \enum SocketState + */ + enum SocketState { + Idle, /**< Socket idling */ + Connecting, /**< Socket connecting */ + ProxyLogin, /**< Socket loggin in to a proxy */ + ProxyHttpError, /**< Socket error on http proxy */ + Connected, /**< Socket connected */ + ProxyFinalV4, /**< Socket received the final proxy v4 reply */ + ProxyFinalV5, /**< Socket received the final proxy v5 reply */ + ProxyFinalHttp, /**< Socket received the final proxy http reply */ + ProxySelectAuthMethodV5, /**< Socket received v5 method select reply */ + ProxyUserPassV5, /**< Socket received user/pass reply */ + SSLHandshake /**< Socket is doing the SSL handshake */ + }; +protected: + unsigned int m_uId; + KviIrcLink * m_pLink; + KviConsole * m_pConsole; + kvi_socket_t m_sock; + SocketState m_state; + QSocketNotifier * m_pWsn; + QSocketNotifier * m_pRsn; + KviIrcServer * m_pIrcServer; + KviProxy * m_pProxy; + QTimer * m_pTimeoutTimer; + unsigned int m_uReadBytes; + unsigned int m_uSentBytes; + int m_iLastError; + unsigned int m_uSentPackets; + KviIrcSocketMsgEntry * m_pSendQueueHead; + KviIrcSocketMsgEntry * m_pSendQueueTail; + QTimer * m_pFlushTimer; + struct timeval m_tAntiFloodLastMessageTime; + bool m_bInProcessData; +#ifdef COMPILE_SSL_SUPPORT + KviSSL * m_pSSL; +#endif +public: + /** + * \brief Returns the console + * \return KviConsole * + */ + KviConsole * console(){ return m_pConsole; }; + + /** + * \brief Returns the link + * \return KviIrcLink * + */ + KviIrcLink * link(){ return m_pLink; }; + + /** + * \brief Returns the state of the socket + * \return SocketState + */ + SocketState state(){ return m_state; }; + + /** + * \brief Returns the last error + * \return int + */ + int lastError(){ return m_iLastError; }; + + /** + * \brief Returns the id of the socket + * \return unsigned int + */ + unsigned int id(){ return m_uId; }; + + /** + * \brief Returns true if the socket is a Secure Socket Layer (SSL) + * \return bool + */ +#ifdef COMPILE_SSL_SUPPORT + bool usingSSL(){ return m_pSSL; }; +#else + bool usingSSL(){ return false; }; +#endif + + /** + * \brief Returns the number of bytes read + * \return unsigned int + */ + unsigned int readBytes(){ return m_uReadBytes; }; + + /** + * \brief Returns the number of bytes sent + * \return unsigned int + */ + unsigned int sentBytes(){ return m_uSentBytes; }; + + /** + * \brief Returns the number of packets sent + * \return unsigned int + */ + unsigned int sentPackets(){ return m_uSentPackets; }; + //unsigned int readPackets(){ return m_uReadPackets; }; + + /** + * \brief Returns true if the socket is connected + * \return bool + */ + bool isConnected(){ return m_state == Connected; }; + + /** + * \brief Starts the connection + * \param pServer The server where to connect to + * \param pProxy The proxy to use during connection + * \param pcBindAddress The address to bind the connection to + * \return int + */ + int startConnection(KviIrcServer * pServer, KviProxy * pProxy = 0, const char * pcBindAddress = 0); + +#ifdef COMPILE_SSL_SUPPORT + /** + * \brief Called to enter SSL connection mode. + * + * It can be called either internally or from outside + * \return void + */ + void enterSSLMode(); +#endif // COMPILE_SSL_SUPPORT + + /** + * \brief Returns true if the packet is sent to the socket + * \param pData The source data packet + * \return bool + */ + bool sendPacket(KviDataBuffer * pData); + + /** + * \brief Aborts the connection + * \return void + */ + void abort(); + + /** + * \brief Gets the localhost IP + * \param szIp The source IP address + * \param bIPv6 Whether to use IPv6 sockets + * \return bool + */ + bool getLocalHostIp(QString & szIp, bool bIPv6); + + /** + * Clears the output queue + */ + void clearOutputQueue(bool bPrivateMessagesOnly); + +protected: + +#ifdef COMPILE_SSL_SUPPORT + /** + * \brief Raises an SSL error + * \return void + */ + void raiseSSLError(); + + /** + * \brief Prints the SSL certificate of the peer + * \return void + */ + void printSSLPeerCertificate(); + + /** + * \brief Prints the SSL cipher used + * \return void + */ + void printSSLCipherInfo(); +#endif // COMPILE_SSL_SUPPORT + + /** + * \brief Sends raw data to the socket + * \param pcBuffer The data buffer + * \param iBufLen The size of the buffer + * \return bool + */ + bool sendRawData(const char * pcBuffer, int iBufLen); + + /** + * \brief Raises an error + * \param iError The error to raise + * \return void + */ + void raiseError(int iError); + + /** + * \brief Called when the connection has been estabilished + * + * If it's a proxy we need to perform the login operations, otherwise + * we're connected to the irc server + * \return void + */ + void connectionEstabilished(); + + /** + * \brief Called when the connection to the proxy has been established + * \return void + */ + void connectedToProxy(); + + /** + * \brief Called when the connection to the irc server has been established + * \return void + */ + void connectedToIrcServer(); + + /** + * \brief Called to login to an HTTP proxy + * \return void + */ + void proxyLoginHttp(); + + /** + * \brief Called to login to a SOCKSv4 proxy + * \return void + */ + void proxyLoginV4(); + + /** + * \brief Called to login to a SOCKSv5 proxy + * \return void + */ + void proxyLoginV5(); + + /** + * \brief Starts the negotiation of user/pass for the proxy + * \return void + */ + void proxyAuthUserPassV5(); + + /** + * \brief Sends the request details + * \return void + */ + void proxySendTargetDataV5(); + + /** + * \brief Gets the authentication reply and handles it + * \param cReply The proxy reply + * \return void + */ + void proxyHandleV5AuthReply(unsigned char cReply); + + /** + * \brief Gets the method selection reply and handles it + * \param cReply The proxy reply + * \return void + */ + void proxyHandleV5MethodReply(unsigned char cReply); + + /** + * \brief Gets the final SOCKSv5 reply and handles it + * \param cReply The proxy reply + * \return void + */ + void proxyHandleV5FinalReply(unsigned char cReply); + + /** + * \brief Gets the final SOCKSv4 reply and handles it + * \param cReply The proxy reply + * \return void + */ + void proxyHandleV4FinalReply(unsigned char cReply); + + /** + * \brief Gets the final HTTP reply and handles it + * \param pcBuffer The buffer containing the proxy reply + * \param iBufLen Size of the buffer containing the proxy reply + * \return void + */ + void proxyHandleHttpFinalReply(const char * pcBuffer, int iBufLen); + + /** + * \brief Connection established. Sets the link up + * \return void + */ + void linkUp(); + + /** + * \brief Checks if the socket error is a transient error + * + * If it is not a transient error it resets the socket and fires the + * appropriate event. + * Otherwise it does nothing. + * \param iReadLength The number of bytes read + * \return void + */ + void handleInvalidSocketRead(int iReadLength); + + /** + * \brief Resets the connection + * \return void + */ + virtual void reset(); + + /** + * \brief Removes the message entry + * \param e The entry + * \return void + */ + void free_msgEntry(KviIrcSocketMsgEntry * e); + + /** + * \brief Appends a KviIrcSocketMsgEntry to the tail of the message queue. + * + * The pMsg for this message is set to 0. + * \param pMsg The message to append to the queue + * \return void + */ + virtual void queue_insertMessage(KviIrcSocketMsgEntry * pMsg); + + /** + * \brief Removes a message from the head of the queue. + * \return bool + */ + bool queue_removeMessage(); + + /** + * \brief Removes all messages from the queue. + * \return void + */ + void queue_removeAllMessages(); + + /** + * \brief Removes private messages from the queue. + * \return void + */ + void queue_removePrivateMessages(); + + /** + * \brief Sets the state of the socket + * \param state The state :) + * \return void + */ + virtual void setState(SocketState state); +private: + /** + * \brief Outputs a SSL message + * \param szMsg The message :) + * \return void + */ + void outputSSLMessage(const QString & szMsg); + + /** + * \brief Outputs a SSL error + * \param szMsg The message :) + * \return void + */ + void outputSSLError(const QString & szMsg); + + /** + * \brief Outputs a proxy message + * \param szMsg The message :) + * \return void + */ + void outputProxyMessage(const QString & szMsg); + + /** + * \brief Outputs a proxy error + * \param szMsg The message :) + * \return void + */ + void outputProxyError(const QString & szMsg); + + /** + * \brief Outputs a socket message + * \param szMsg The message :) + * \return void + */ + void outputSocketMessage(const QString & szMsg); + + /** + * \brief Outputs a socket warning + * \param szMsg The message :) + * \return void + */ + void outputSocketWarning(const QString & szMsg); + + /** + * \brief Outputs a socket error + * \param szMsg The message :) + * \return void + */ + void outputSocketError(const QString & szMsg); +protected slots: + /** + * \brief Called when the connection timeouts + * \return void + */ + void connectionTimedOut(); + + /** + * \brief Called when the write notifier is enabled + * \return void + */ + void writeNotifierFired(int); + + /** + * \brief Called when the read notifier is enabled + * \return void + */ + void readData(int); + + /** + * \brief Called when the proxy read notifier is enabled + * \return void + */ + void readProxyData(int); + + /** + * \brief Called when the proxy read notifier encounters an error + * \return void + */ + void readHttpProxyErrorData(int); + + /** + * \brief Attempts to send as much as possible to the server + * + * If fails (happens only on really lagged servers) calls itself with a + * QTimer shot after KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout) + * ms to retry again... + * \return void + */ + void flushSendQueue(); + + /** + * \brief Starts the SSL handshake + * \return void + */ + void doSSLHandshake(int); +}; + +#endif //_KVI_IRCSOCKET_H_ diff --git a/src/kvirc/kernel/KviIrcUrl.cpp b/src/kvirc/kernel/KviIrcUrl.cpp new file mode 100644 index 000000000..4f921b8f2 --- /dev/null +++ b/src/kvirc/kernel/KviIrcUrl.cpp @@ -0,0 +1,365 @@ +//============================================================================= +// +// File : KviIrcUrl.cpp +// Creation date : Sun Mar 04 2001 14:20:12 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2001-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviCString.h" +#include "kvi_inttypes.h" +#include "KviQString.h" +#include "KviIrcServer.h" +#include "KviKvsScript.h" +#include "KviMessageBox.h" +#include "KviChannelWindow.h" +#include "KviApplication.h" +#include "KviLocale.h" +#include "KviIrcConnectionTarget.h" +#include "KviIrcConnection.h" +#include "KviIrcContext.h" +#include "KviConsoleWindow.h" +#include "KviMainWindow.h" + +#define _KVI_IRCURL_CPP_ +#include "KviIrcUrl.h" + + +bool KviIrcUrl::parse(const char * url,KviCString &cmdBuffer,int contextSpec) +{ + // irc[6]://[:][/[?]] + KviCString szUrl = url; + //szUrl.replaceAll("$","\\$"); + //szUrl.replaceAll(";","\\;"); + bool bIPv6 = false; + bool bSSL = false; + KviCString szServer; + kvi_u32_t uPort = 0; + bool bGotPort = false; + if(kvi_strEqualCIN(szUrl.ptr(),"irc://",6)) + { + szUrl.cutLeft(6); + } else if(kvi_strEqualCIN(szUrl.ptr(),"irc6://",7)) + { + bIPv6 = true; + szUrl.cutLeft(7); + } else if(kvi_strEqualCIN(szUrl.ptr(),"ircs://",7)) + { + bSSL = true; + szUrl.cutLeft(7); + } else if(kvi_strEqualCIN(szUrl.ptr(),"ircs6://",8)) + { + bIPv6 = true; + bSSL = true; + szUrl.cutLeft(8); + } else return false; + + KviCString szServerAndPort; + + int idx = szUrl.findFirstIdx('/'); + if(idx != -1) + { + szServerAndPort = szUrl.left(idx); + szUrl.cutLeft(idx + 1); + } else { + szServerAndPort = szUrl; + szUrl = ""; + } + + if(szServerAndPort.isEmpty())return false; + + idx = szServerAndPort.findFirstIdx(':'); + + if(idx != -1) + { + szServer = szServerAndPort.left(idx); + szServerAndPort.cutLeft(idx + 1); + bool bOk; + uPort = szServerAndPort.toUInt(&bOk); + if(!bOk)uPort = 6667; + bGotPort = true; + } else { + szServer = szServerAndPort; + } + + cmdBuffer = "server "; + switch(contextSpec) + { + case KVI_IRCURL_CONTEXT_FIRSTFREE: + cmdBuffer.append("-u "); + break; + case KVI_IRCURL_CONTEXT_NEW: + cmdBuffer.append("-n "); + break; + } + if(bIPv6)cmdBuffer.append(" -i "); + if(bSSL)cmdBuffer.append(" -s "); + + if(szUrl.hasData()) + { + KviCString szChannel; + KviCString szPass; + + idx = szUrl.findFirstIdx('?'); + if(idx != -1) + { + szChannel = szUrl.left(idx); + szUrl.cutLeft(idx + 1); + szPass = szUrl; + } else { + szChannel = szUrl; + szPass = ""; + } + + if(!(szChannel.firstCharIs('#') || szChannel.firstCharIs('!') || szChannel.firstCharIs('&'))) + szChannel.prepend('#'); + + if(szPass.isEmpty())cmdBuffer.append(KviCString::Format," -c=\"join %s\" ",szChannel.ptr()); + else cmdBuffer.append(KviCString::Format," -c=\"join %s %s\" ",szChannel.ptr(),szPass.ptr()); + + } + + cmdBuffer.append(szServer); + if(bGotPort)cmdBuffer.append(KviCString::Format," %d",uPort); + + cmdBuffer.append(';'); + + return true; +} + +void KviIrcUrl::split(QString url, KviIrcUrlParts& result) +{ + // irc[s][6]://[:][/[?]][[,[?]] + + //defaults + result.bSsl=false; + result.bIPv6=false; + result.iPort = 6667; + result.iError=0; + + int iProtoLen = url.indexOf("://"); + if(iProtoLen!=-1) { + if(KviQString::equalCIN(url,"irc",3)) { + // OK, seems to be a valid proto; + url = url.right(url.length()-3); + if(KviQString::equalCIN(url,"s",1)) { + result.bSsl=true; + url = url.right(url.length()-1); + } + if(KviQString::equalCIN(url,"6",1)) { + result.bIPv6=true; + url = url.right(url.length()-1); + } + if(!KviQString::equalCIN(url,"://",3)) { + //irc(???):// proto?? + result.iError |= InvalidProtocol; + } + iProtoLen = url.indexOf("://"); + url = url.right(url.length()-iProtoLen-3); + } else { + result.iError |= InvalidProtocol; + } + } + //Ok, we understand a protocol.. Now we shuld find a server name:) + int iTmp; + iTmp = url.indexOf(':'); + if(iTmp!=-1) { + result.szHost = url.left(iTmp); + url = url.right(url.length()-iTmp-1); + // Accepted, now the time for the port:) + bool bOk; + if( (iTmp = url.indexOf('/')) != -1) { // any channels pending? + result.iPort = url.left(iTmp).toUInt(&bOk); + if(!bOk) { + result.iPort = 6667; + result.iError |= InvalidPort; + } + url = url.right(url.length()-iTmp-1); + } else { + result.iPort = url.toUInt(&bOk); + if(!bOk) { + result.iPort = 6667; + result.iError |= InvalidPort; + } + url = ""; + } + } else if( (iTmp = url.indexOf('/')) != -1) { // have channels?? + result.szHost = url.left(iTmp); + url = url.right(url.length()-iTmp-1); + } else { + result.szHost = url; + url = ""; + } + + //and, finally, channels:D + result.chanList = url.isEmpty()?QStringList():url.split(',',QString::SkipEmptyParts); + +} + +void KviIrcUrl::join(QString &uri, KviIrcServer* server) +{ + if(server) + { + uri="irc"; + + if(server->useSSL()) uri.append("s"); + if(server->isIPv6()) uri.append("6"); + + uri.append("://"); + uri.append(server->hostName()); + if(server->port()!=6667) uri.append(QString(":%1").arg(server->port())); + uri.append("/"); + } +} + +void KviIrcUrl::makeJoinCmd(const QStringList& chans, QString& szJoinCommand) +{ + QString szChannels,szProtectedChannels,szPasswords,szCurPass,szCurChan; + if(chans.count()!=0) + { + + for ( QStringList::ConstIterator it = chans.begin(); it != chans.end(); ++it ) { + + szCurPass=(*it).section('?',1); + if(szCurPass.isEmpty()) + { + if(!szChannels.isEmpty()) + szChannels.append(","); + szCurChan = (*it).section('?',0,0); + if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!')) + szCurChan.prepend('#'); + szChannels.append(szCurChan); + } else { + if(!szProtectedChannels.isEmpty()) + szProtectedChannels.append(","); + szCurChan = (*it).section('?',0,0); + if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!')) + szCurChan.prepend('#'); + szProtectedChannels.append(szCurChan); + if(!szPasswords.isEmpty()) + szPasswords.append(","); + szPasswords.append(szCurPass); + } + } + szJoinCommand = "JOIN "; + szJoinCommand.append(szProtectedChannels); + if(!szProtectedChannels.isEmpty() && !szChannels.isEmpty()) + szJoinCommand.append(','); + szJoinCommand.append(szChannels); + szJoinCommand.append(" "); + szJoinCommand.append(szPasswords); + } +} + +int KviIrcUrl::run(const QString& text,int contextSpec,KviConsole* pConsole) +{ + KviIrcUrlParts parts; + KviIrcUrl::split(text,parts); + QString cmdBuffer; + + if( (contextSpec & CurrentContext) && !pConsole) { + contextSpec = FirstFreeContext; + } + + if( (contextSpec & TryCurrentContext) && !pConsole) { + contextSpec = FirstFreeContext; + } + + if(contextSpec & FirstFreeContext) { + if(pConsole) { + if(pConsole->connectionInProgress()) + { + pConsole = g_pFrame->firstNotConnectedConsole(); + if(!pConsole) { + pConsole = g_pFrame->createNewConsole(); + } + } + } else { + pConsole = g_pFrame->firstNotConnectedConsole(); + if(!pConsole) { + pConsole = g_pFrame->createNewConsole(); + } + } + } + + if(!(parts.iError & KviIrcUrl::InvalidProtocol)) { + g_pApp->addRecentUrl(text); + + QString szJoinCommand; + makeJoinCmd(parts.chanList,szJoinCommand); + QString szCommand("server "); + if(parts.bSsl) szCommand.append("-s "); + if(parts.bIPv6) szCommand.append("-i "); + if(!szJoinCommand.isEmpty()){ + szCommand.append("-c=\""); + szCommand.append(szJoinCommand); + szCommand.append("\" "); + } + szCommand.append(QString("%1 %2 ").arg(parts.szHost).arg(parts.iPort)); + + if(pConsole->connection()) { + KviIrcServer* server = pConsole->connection()->target()->server(); + if( + ( server->hostName() != parts.szHost ) || + ( server->port() != parts.iPort ) || + ( server->useSSL() != parts.bSsl ) || + ( server->isIPv6() != parts.bIPv6) ) + { // New server, try to reconnect + KviKvsScript::run(szCommand,(contextSpec & TryCurrentContext) ? g_pFrame->createNewConsole() : pConsole); + return parts.iError; + } else { + // the same server, but probably new chanlist + QString tmp; + QString toPart; + for(KviChannelWindow * c = pConsole->connection()->channelList()->first();c;c = pConsole->connection()->channelList()->next()) + { + tmp=c->target(); + if(c->hasChannelMode('k')) + { + tmp.append("?"); + tmp.append(c->channelModeParam('k')); + } + if(!parts.chanList.removeAll(tmp)) + { + toPart.append(c->target()); + toPart.append(","); + } + } + if(!(contextSpec & DoNotPartChans)) + { + makeJoinCmd(parts.chanList,szJoinCommand); + if(!toPart.isEmpty()) + { + toPart.prepend("part "); + KviKvsScript::run(toPart,pConsole); + } + } + if(!szJoinCommand.isEmpty()) + { + pConsole->connection()->sendData(pConsole->connection()->encodeText(szJoinCommand).data()); + } + return parts.iError; + } + } + // New server + KviKvsScript::run(szCommand,pConsole); + } + //!invalid proto + return parts.iError; +} diff --git a/src/kvirc/kernel/KviIrcUrl.h b/src/kvirc/kernel/KviIrcUrl.h new file mode 100644 index 000000000..8b98bbfc3 --- /dev/null +++ b/src/kvirc/kernel/KviIrcUrl.h @@ -0,0 +1,79 @@ +#ifndef _KVI_IRCURL_H_ +#define _KVI_IRCURL_H_ +//============================================================================= +// +// File : KviIrcUrl.h +// Creation date : Sun Mar 04 2001 14:22:55 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2001-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviCString.h" +#include "kvi_inttypes.h" + +class KviIrcServer; +class KviConsole; + +#include + +// Create /server -u commands (first free context) +#define KVI_IRCURL_CONTEXT_FIRSTFREE 0 +// Create /server -n commands (new irc context) +#define KVI_IRCURL_CONTEXT_NEW 1 +// Create /server commands (this irc context) +#define KVI_IRCURL_CONTEXT_THIS 2 + +typedef struct _KviIrcUrlParts { + QString szHost; + kvi_u32_t iPort; + bool bIPv6; + bool bSsl; + QStringList chanList; + int iError; + } KviIrcUrlParts; + +namespace KviIrcUrl +{ + + enum KviIrcUrlParserError { + InvalidProtocol = 1, + InvalidPort = 2, + NeedNewContext = 4 + }; + + enum KviIrcUrlContextSpec { + FirstFreeContext = 1, + NewContext = 2, + CurrentContext = 4, + TryCurrentContext = 8, + + DoNotPartChans = 16 + }; + + extern KVIRC_API bool parse(const char * url,KviCString &cmdBuffer,int contextSpec = KVI_IRCURL_CONTEXT_FIRSTFREE); + + extern KVIRC_API int run(const QString& url,int contextSpec = FirstFreeContext,KviConsole* pConsole = 0); + + extern KVIRC_API void split(QString url, KviIrcUrlParts& parts); + extern KVIRC_API void join(QString &url, KviIrcServer* server); + extern KVIRC_API void makeJoinCmd(const QStringList& chans, QString& szJoinCommand); +} + +#endif // _KVI_IRCURL_H_ diff --git a/src/kvirc/kernel/KviLagMeter.cpp b/src/kvirc/kernel/KviLagMeter.cpp new file mode 100644 index 000000000..ad3b12c34 --- /dev/null +++ b/src/kvirc/kernel/KviLagMeter.cpp @@ -0,0 +1,266 @@ +//============================================================================= +// +// File : KviLagMeter.cpp +// Creation date : Fri Oct 18 13:31:36 CEST 1999 by Juanjo Álvarez +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 1999 Juanjo Álvarez +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviLagMeter.h" +#include "KviOptions.h" +#include "KviKvsEventTriggers.h" +#include "KviParameterList.h" +#include "KviIrcConnection.h" +#include "KviIrcContext.h" +#include "KviMainWindow.h" +#include "KviConsoleWindow.h" +#include "KviTimeUtils.h" +#include "KviIrcConnectionUserInfo.h" +#include "KviIrcConnectionServerInfo.h" +#include "kvi_out.h" +#include "KviLocale.h" + +KviLagMeter::KviLagMeter(KviIrcConnection * c) +: QObject() +{ + m_pConnection = c; + m_pCheckList = new KviPointerList; + m_pCheckList->setAutoDelete(true); + m_uLag = 0; + m_uLastEmittedLag = 0; + m_uLastReliability = 0; + m_tLastCompleted = 0; + m_tLastOwnCheck = 0; + m_tFirstOwnCheck = 0; + m_bOnAlarm = false; + m_pDeletionSignal = 0; + + // FIXME: We could use the KviIrcConnection::heartbeat() here! + if(KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) < 2000) + KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) = 2000; // kinda absurd + + if(KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) > 10000) + KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) = 10000; // kinda absurd + + startTimer(KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat)); // 5 seconds by default +} + +KviLagMeter::~KviLagMeter() +{ + if(m_pDeletionSignal)*m_pDeletionSignal = true; + delete m_pCheckList; +} + +unsigned int KviLagMeter::secondsSinceLastCompleted() +{ + struct timeval tv; + kvi_gettimeofday(&tv,0); + return tv.tv_sec - m_tLastCompleted; +} + +void KviLagMeter::timerEvent(QTimerEvent *) +{ + if(m_pConnection->state() != KviIrcConnection::Connected)return; // do nothing atm + + // If the lag has changed emit our signals + if((m_uLag / 10) != (m_uLastEmittedLag / 10)) + { + m_uLastEmittedLag = m_uLag; + g_pFrame->childConnectionLagChange(m_pConnection); + + KviCString szLag(KviCString::Format,"%u",m_uLag); + + bool bDeletionSignal = false; + m_pDeletionSignal = &bDeletionSignal; + + if((!m_bOnAlarm) && (m_uLag > KVI_OPTION_UINT(KviOption_uintLagAlarmTime))) + { + KVS_TRIGGER_EVENT_2_HALTED(KviEvent_OnLagAlarmTimeUp, + m_pConnection->console(),m_pConnection->serverInfo()->name(),QString(szLag.ptr())); + if(bDeletionSignal)return; // killed, probably by a quit -f -u + m_bOnAlarm = true; + } else if(m_bOnAlarm) + { + KVS_TRIGGER_EVENT_2_HALTED(KviEvent_OnLagAlarmTimeDown, + m_pConnection->console(),m_pConnection->serverInfo()->name(),QString(szLag.ptr())); + if(bDeletionSignal)return; // killed, probably by a quit -f -u + m_bOnAlarm = false; + } + + KVS_TRIGGER_EVENT_2_HALTED(KviEvent_OnLagCheck, + m_pConnection->console(),m_pConnection->serverInfo()->name(),QString(szLag.ptr())); + if(bDeletionSignal)return; // killed, probably by a quit -f -u + + m_pDeletionSignal = 0; + } + + // get current time + struct timeval tv; + kvi_gettimeofday(&tv,0); + unsigned int uDiff = tv.tv_sec - m_tLastCompleted; + unsigned int uHeartbeat = KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) / 1000; + if(uHeartbeat < 2)uHeartbeat = 2; + // we keep the last lag value for an amount of time + // depending on its reliability. + // Since reliability ranges from 10 to 100 we keep the lags + // for (hrtbt * 4) + (reliability / 2) seconds (which means from 25 to 70 seconds by default) + if(uDiff <= ((uHeartbeat * 4) + (m_uLastReliability / 2)))return; // nothing to do, the actual value is accurate + + // the last completed check has been completed a lot of time ago + // do we have some checks on the queue ? + if(m_pCheckList->count() > 0) + { + // if the first registered check is not too outdated + // we wait a little more for it to return + KviLagCheck * c = m_pCheckList->first(); + if(c) + { + if((tv.tv_sec - c->lSecs) <= 10)return; + } + // the first check was registered more than 10 secs before + if(m_tLastOwnCheck > 0) + { + // hm.. we have already sent our own (reliable) check after the last completed + // make the lag grow (we're pretty sure it's growing) + uDiff = (tv.tv_sec - m_tFirstOwnCheck) * 1000; + if(m_uLag < uDiff)m_uLag = uDiff; // the lag grows for sure + uDiff = tv.tv_sec - m_tLastOwnCheck; + if(uDiff < (uHeartbeat * 4))return; // wait a bit...send own checks only every 20 secs (by default) at this point + } + } + // or we have no checks in the queue at all + // or it's really time to do something... + if(m_tFirstOwnCheck == 0) + { + if(_OUTPUT_PARANOIC) + m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Sending out PING based lag probe")); + + // this is the first our own lag check since the last succesfull one: use the ping + lagCheckRegister("@ping@",70); // the ping may be fooled easily + m_pConnection->sendFmtData("PING %s %s", + m_pConnection->encodeText( m_pConnection->userInfo()->nickName() ).data(), + m_pConnection->encodeText( m_pConnection->serverInfo()->name() ).data() ); + m_tFirstOwnCheck = tv.tv_sec; + } else { + if(_OUTPUT_PARANOIC) + m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Sending out CTCP based lag probe")); + + // we have already sent a ping but we got no reply + // try with another method... even if this will reset our idle time + KviCString tmp(KviCString::Format,"%d%d-yeah-:)",tv.tv_sec,tv.tv_usec); + lagCheckRegister(tmp.ptr(),100); // almost impossible to fool + m_pConnection->sendFmtData("NOTICE %s :%cLAGCHECK %s%c", + m_pConnection->encodeText( m_pConnection->userInfo()->nickName() ).data(), + 0x01, + tmp.ptr(), + 0x01); + } + m_tLastOwnCheck = tv.tv_sec; +} + +void KviLagMeter::lagCheckRegister(const char * key,unsigned int uReliability) +{ + if(uReliability < 10)return; // what the heck of a lag check is this ? + // store the lagcheck structure and just return + + if(_OUTPUT_PARANOIC) + m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Registered lag check with reliability %u (%s)"),uReliability,key); + + KviLagCheck * c = new KviLagCheck; + c->szKey = key; + struct timeval tv; + kvi_gettimeofday(&tv,0); + c->lSecs = tv.tv_sec; + c->lUSecs = tv.tv_usec; + c->uReliability = uReliability <= 100 ? uReliability : 100; + m_pCheckList->append(c); + while(m_pCheckList->count() > 30) + { + // we're fried :/ + // either our ping mechanism is not working + // or the server is stoned... + m_pCheckList->removeFirst(); + } +} + +bool KviLagMeter::lagCheckComplete(const char * key) +{ + // find this lag check + KviLagCheck * c; + for(c = m_pCheckList->first();c;c = m_pCheckList->next()) + { + if(kvi_strEqualCS(c->szKey.ptr(),key))break; + } + if(!c)return false; // not found + // kill any earlier lag checks (IRC is a sequential proto) + while(m_pCheckList->first() != c)m_pCheckList->removeFirst(); + + if(_OUTPUT_PARANOIC) + m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Lag check completed (%s)"),key); + + struct timeval tv; + kvi_gettimeofday(&tv,0); + + unsigned int uLag = ((tv.tv_sec - c->lSecs) * 1000); + if(tv.tv_usec < c->lUSecs)uLag -= ((c->lUSecs - tv.tv_usec) / 1000); + else uLag += ((tv.tv_usec - c->lUSecs) / 1000); + + // now check the reliability + + if(m_uLastReliability > c->uReliability) + { + // the actual data is more reliable than the new one :/ + // change the real lag only by a certain amount + // c->uRel : 100 = uLag : m_uLag + m_uLag = ((uLag * c->uReliability) + (m_uLag * m_uLastReliability)) / (c->uReliability + m_uLastReliability); + } else { + // the actual data is less reliable than the new one + m_uLag = uLag; + } + + m_tLastCompleted = tv.tv_sec; // now + m_tLastOwnCheck = 0; + m_tFirstOwnCheck = 0; + m_uLastReliability = c->uReliability; + + m_pCheckList->removeFirst(); + + return true; +} + +void KviLagMeter::lagCheckAbort(const char * key) +{ + KviPointerList l; + l.setAutoDelete(false); + KviLagCheck * c; + + if(_OUTPUT_PARANOIC) + m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Lag check aborted (%s)"),key); + + for(c = m_pCheckList->first();c;c = m_pCheckList->next()) + if(kvi_strEqualCS(c->szKey.ptr(),key))l.append(c); + for(c = l.first();c;c = l.next())m_pCheckList->removeRef(c); +} + +#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES +#include "kvi_lagmeter.moc" +#endif //!COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/KviLagMeter.h b/src/kvirc/kernel/KviLagMeter.h new file mode 100644 index 000000000..6a8bfd937 --- /dev/null +++ b/src/kvirc/kernel/KviLagMeter.h @@ -0,0 +1,75 @@ +#ifndef _KVI_LAGMETER_H_ +#define _KVI_LAGMETER_H_ +//============================================================================= +// +// File : KviLagMeter.h +// Creation date : Fri Oct 18 13:30:26 CEST 1999 by Juanjo Álvarez +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 1999 Juanjo Álvarez +// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviCString.h" +#include "KviPointerList.h" + +#include + +class KviIrcConnection; + +class KviLagCheck +{ +public: + KviCString szKey; + long lSecs; // since epoch + long lUSecs; + unsigned int uReliability; // [0-100] +}; + +class KVIRC_API KviLagMeter : public QObject +{ + Q_OBJECT + friend class KviIrcConnection; +protected: + KviLagMeter(KviIrcConnection * c); + ~KviLagMeter(); +protected: + KviIrcConnection * m_pConnection; + unsigned int m_uLag; // last computed lag + unsigned int m_uLastEmittedLag; // last emitted lag + long m_tLastCompleted; // time when the last lag was completed (gettimeofday!) + unsigned int m_uLastReliability; // how much reliable was the last completed check ? + KviPointerList * m_pCheckList; + long m_tFirstOwnCheck; // time when the first ping after a completed check was sent + long m_tLastOwnCheck; // time when the last ping was sent + bool m_bOnAlarm; + bool * m_pDeletionSignal; // we use this to signal our own delete +public: + // lag checks should be done only against the user's server + // please make SURE that the key is unique! + void lagCheckRegister(const char * key,unsigned int uReliability = 50); + bool lagCheckComplete(const char * key); + void lagCheckAbort(const char * key); + unsigned int lag(){ return m_uLag; }; + unsigned int secondsSinceLastCompleted(); +protected: + virtual void timerEvent(QTimerEvent * e); +}; + +#endif // _KVI_LAGMETER_H_ diff --git a/src/kvirc/kernel/KviMain.cpp b/src/kvirc/kernel/KviMain.cpp new file mode 100644 index 000000000..d717010d7 --- /dev/null +++ b/src/kvirc/kernel/KviMain.cpp @@ -0,0 +1,462 @@ +//============================================================================= +// +// File : KviMain.cpp +// Creation date : Sun Jun 18 2000 12:38:45 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviApplication.h" +#include "KviCString.h" +#include "kvi_settings.h" +#include "KviIrcUrl.h" +#include "kvi_defaults.h" +#include "kvi_sourcesdate.h" +#include "KviMessageBox.h" +#include "KviBuildInfo.h" +#ifdef COMPILE_DBUS_SUPPORT + #ifndef COMPILE_KDE_SUPPORT // 'cause kde adds an interface itself + #include "KviDbusAdaptor.h" + #endif +#endif +#ifndef COMPILE_NO_IPC + extern bool kvi_sendIpcMessage(const char * message); // KviIpcSentinel.cpp +#endif + +#include //for qDebug() +#include + +#ifdef COMPILE_KDE_SUPPORT + #include + #include +#endif + +#define KVI_ARGS_RETCODE_OK 0 +#define KVI_ARGS_RETCODE_ERROR 1 +#define KVI_ARGS_RETCODE_STOP 2 + +typedef struct _ParseArgs +{ + int argc; + char ** argv; + char * configFile; + bool createFile; + bool bForceNewSession; + bool bShowPopup; + bool bShowSplashScreen; + bool bExecuteCommandAndClose; + KviCString szExecCommand; + KviCString szExecRemoteCommand; +} ParseArgs; + +int parseArgs(ParseArgs * a) +{ + KviCString szServer; + KviCString szPort; + int idx; + + if(a->argc < 2)return KVI_ARGS_RETCODE_OK; + + for(idx = 1;idx < a->argc;idx++) + { + QString szMessage; + char * p = a->argv[idx]; + + if((kvi_strLen(p) > 3) && (*p == '-') && (*(p+1) == '-'))p++; + + if(kvi_strEqualCI("-v",p) || kvi_strEqualCI("-version",p)) + { + KviQString::appendFormatted(szMessage,"KVIrc %s '%s'\n",KVI_VERSION,KVI_RELEASE_NAME); + KviQString::appendFormatted(szMessage,"Sources date: %s\n",KVI_SOURCES_DATE); + szMessage += "Build date: "; + szMessage += KviBuildInfo::buildDate(); + szMessage += "\n"; + + KviQString::appendFormatted(szMessage,"Home page: http://www.kvirc.net/\n"); + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + MessageBox(0,szMessage.toLocal8Bit().data(),"KVIrc",0); +#else + qDebug("%s",szMessage.toLocal8Bit().data()); +#endif + + return KVI_ARGS_RETCODE_STOP; + } + + if(kvi_strEqualCI("-h",p) || kvi_strEqualCI("-help",p)) + { + KviQString::appendFormatted(szMessage,"Usage:\n"); + KviQString::appendFormatted(szMessage," %s [options] [server [port]] [ircurl [ircurl [...]]]\n",a->argv[0]); + KviQString::appendFormatted(szMessage," \n"); + KviQString::appendFormatted(szMessage,"Available options:\n"); + KviQString::appendFormatted(szMessage," -h, --help : Print this help and exit\n"); + KviQString::appendFormatted(szMessage," -v, --version: Print version information and exit\n"); + KviQString::appendFormatted(szMessage," -c : Use as config file instead of ~/%s\n",KVI_HOME_CONFIG_FILE_NAME); + KviQString::appendFormatted(szMessage," (defaults to $HOME/%s if does not exist)\n",KVI_HOME_CONFIG_FILE_NAME); + KviQString::appendFormatted(szMessage," -n : Use as config file instead of $HOME/%s\n",KVI_HOME_CONFIG_FILE_NAME); + KviQString::appendFormatted(szMessage," (create if it does not exist)\n"); +#ifdef COMPILE_NO_IPC + KviQString::appendFormatted(szMessage," -f : Accepted but ignored (for compatibility)\n"); +#else + KviQString::appendFormatted(szMessage," -f : Force a new KVIrc session, even if there is already\n"); + KviQString::appendFormatted(szMessage," a running one.\n"); +#endif + KviQString::appendFormatted(szMessage," -e : If a KVIrc session is already running, execute\n"); + KviQString::appendFormatted(szMessage," the in that session, otherwise start up\n"); + KviQString::appendFormatted(szMessage," normally and execute \n"); + KviQString::appendFormatted(szMessage," must be a single shell token.\n"); + KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); + KviQString::appendFormatted(szMessage," -x : If a KVIrc session is already running, execute\n"); + KviQString::appendFormatted(szMessage," the in that session, otherwise exit from application without doing anything/\n"); + KviQString::appendFormatted(szMessage," must be a single shell token.\n"); + KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); + KviQString::appendFormatted(szMessage," -r : If a KVIrc session is already running, execute the \n"); + KviQString::appendFormatted(szMessage," in that session, otherwise start up normally (do not execute).\n"); + KviQString::appendFormatted(szMessage," must be a single shell token.\n"); + KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); + KviQString::appendFormatted(szMessage," -m : If a KVIrc session is already running, show an informational\n"); + KviQString::appendFormatted(szMessage," popup dialog instead of writing to the console\n"); + KviQString::appendFormatted(szMessage," --nosplash : Do not show the splash screen at startup\n"); + KviQString::appendFormatted(szMessage," [server] : Connect to this server after startup\n"); + KviQString::appendFormatted(szMessage," [port] : Use this port for connection\n"); + KviQString::appendFormatted(szMessage," [ircurl] : URL in the following form:\n"); + KviQString::appendFormatted(szMessage," irc[6]://[:][/[?]]\n"); + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + MessageBox(0,szMessage.toLocal8Bit().data(),"KVIrc",0); +#else + qDebug("%s",szMessage.toLocal8Bit().data()); +#endif + return KVI_ARGS_RETCODE_STOP; + } + + if(kvi_strEqualCI("-c",p)) + { + idx++; + if(idx >= a->argc) + { + qDebug("Option -c requires a config file name"); + return KVI_ARGS_RETCODE_ERROR; + } + p = a->argv[idx]; + a->configFile = p; + qDebug("Using file %s as config",p); + continue; + } + + if(kvi_strEqualCI("-e",p)) + { + idx++; + if(idx >= a->argc) + { + qDebug("Option -e requires a command"); + return KVI_ARGS_RETCODE_ERROR; + } + p = a->argv[idx]; + if(a->szExecCommand.hasData())a->szExecCommand.append("\n"); + a->szExecCommand.append(p); + continue; + } + + if(kvi_strEqualCI("-x",p)) + { + idx++; + if(idx >= a->argc) + { + qDebug("Option -x requires a command"); + return KVI_ARGS_RETCODE_ERROR; + } + p = a->argv[idx]; + if(a->szExecCommand.hasData())a->szExecCommand.append("\n"); + a->szExecCommand.append(p); + a->bExecuteCommandAndClose=true; + continue; + } + + if(kvi_strEqualCI("-r",p)) + { + idx++; + if(idx >= a->argc) + { + qDebug("Option -r requires a command"); + return KVI_ARGS_RETCODE_ERROR; + } + p = a->argv[idx]; + if(a->szExecRemoteCommand.hasData())a->szExecRemoteCommand.append("\n"); + a->szExecRemoteCommand.append(p); + continue; + } + + if(kvi_strEqualCI("-m",p)) + { + a->bShowPopup = true; + continue; + } + + if(kvi_strEqualCI("-n",p)) + { + idx++; + if(idx >= a->argc) + { + qDebug("Option -n requires a config file name"); + return KVI_ARGS_RETCODE_ERROR; + } + p = a->argv[idx]; + a->configFile = p; + a->createFile=true; + qDebug("Using file %s as config",p); + continue; + } + + if(kvi_strEqualCI("-nosplash",p)) + { + a->bShowSplashScreen = false; + continue; + } + + if(kvi_strEqualCI("-f",p)) + { + a->bForceNewSession = true; + continue; + } + + if(kvi_strEqualCI("-session",p)||kvi_strEqualCI("-display",p)||kvi_strEqualCI("-name",p)) + { + // Qt apps are supposed to handle the params to these switches, but we'll skip arg for now + idx++; + continue; + } + + if(kvi_strEqualCI("-external",p)) + { + idx++; + if(idx >= a->argc) + { + qDebug("Option --external requires n irc:// url"); + return KVI_ARGS_RETCODE_ERROR; + } + p = a->argv[idx]; + if(kvi_strEqualCIN(p,"irc://",6) || kvi_strEqualCIN(p,"irc6://",7) || kvi_strEqualCIN(p,"ircs://",7) || kvi_strEqualCIN(p,"ircs6://",8)) + { + KviCString tmp = QString::fromLocal8Bit(p); + a->szExecCommand ="openurl "; + tmp.replaceAll("$",""); // the urls can't contain $ signs + tmp.replaceAll(";",""); // the urls can't contain ; signs + tmp.replaceAll("%",""); // the urls can't contain % signs + a->szExecCommand.append(tmp); + return KVI_ARGS_RETCODE_OK; + } + return KVI_ARGS_RETCODE_ERROR; + } + + if(*p != '-') + { + // no dash + if(kvi_strEqualCIN(p,"irc://",6) || kvi_strEqualCIN(p,"irc6://",7) || kvi_strEqualCIN(p,"ircs://",7) || kvi_strEqualCIN(p,"ircs6://",8)) + { + KviCString szTmp = QString::fromLocal8Bit(p); + if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); + a->szExecCommand.append("openurl "); + szTmp.replaceAll("$",""); // the urls can't contain $ signs + szTmp.replaceAll(";",""); // the urls can't contain ; signs + szTmp.replaceAll("%",""); // the urls can't contain % signs + a->szExecCommand.append(szTmp); + } else { + QString szTmp = QString::fromLocal8Bit(p); + bool bOk; + szTmp.toUInt(&bOk); + if(bOk) + { + szPort = szTmp; + } else { + QString ri = szTmp.right(4); + if(KviQString::equalCI(ri,".kvs")) + { + if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); + a->szExecCommand.append("parse \""); + szTmp.replace('$',"\\$"); + szTmp.replace('\\',"\\\\"); + a->szExecCommand.append(szTmp); + a->szExecCommand.append('"'); + } else if(KviQString::equalCI(ri,".kvt")) + { + if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); + a->szExecCommand.append("theme.install \""); + szTmp.replace('$',"\\$"); + szTmp.replace('\\',"\\\\"); + a->szExecCommand.append(szTmp); + a->szExecCommand.append('"'); + } else if(KviQString::equalCI(ri,".kva")) + { + if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); + a->szExecCommand.append("addon.install \""); + szTmp.replace('$',"\\$"); + szTmp.replace('\\',"\\\\"); + a->szExecCommand.append(szTmp); + a->szExecCommand.append('"'); + } else { + szServer = szTmp; // assume a plain server name + } + } + } + } + } + + if(szServer.hasData()) + { + if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); + a->szExecCommand.append("server -u "); + a->szExecCommand.append(szServer); + if(szPort.hasData()) + { + a->szExecCommand.append(' '); + a->szExecCommand.append(szPort); + } + } + + return KVI_ARGS_RETCODE_OK; +} + +int main(int argc, char ** argv) +{ + ParseArgs a; + a.argc = argc; + a.argv = argv; + a.configFile = 0; + a.createFile = false; + a.bForceNewSession = false; + a.bShowPopup = false, + a.bShowSplashScreen = true; + a.bExecuteCommandAndClose = false; + + int iRetCode = parseArgs(&a); + + if(iRetCode != KVI_ARGS_RETCODE_OK) + { + return ((iRetCode == KVI_ARGS_RETCODE_ERROR) ? (-1) : 0); + } + +#ifdef COMPILE_KDE_SUPPORT + + KAboutData oAboutData( + "kvirc", // internal program name + "kvirc", // message catalogue name + ki18n("KVIrc"), // user-visible program name + KVI_VERSION, // program version + ki18n("Visual IRC Client"), // description + KAboutData::License_GPL, // license + ki18n("(c) 1998-2010 The KVIrc Development Team"), + ki18n("???"), // *some other text* ???? + "http://www.kvirc.net", // homepage + "https://svn.kvirc.de/kvirc/" // bug address (FIXME: this would be an E-MAIL address...) + ); + + //fake argc/argv initialization: kde will use argv[0] as out appName in some dialogs + // (eg: kdebase/workspace/kwin/killer/killer.cpp) + KCmdLineArgs::init(1, &argv[0], &oAboutData); + +#endif + + KviApplication * pTheApp = new KviApplication(argc,argv); + +#ifdef COMPILE_DBUS_SUPPORT + #ifndef COMPILE_KDE_SUPPORT + new KviDbusAdaptor(pTheApp); // FIXME: shouldn't this be deleted by someone ? + QDBusConnection::sessionBus().registerObject("/MainApplication", pTheApp); + #endif +#endif + + KviCString szRemoteCommand = a.szExecCommand; + if(a.szExecRemoteCommand.hasData()) + { + if(szRemoteCommand.hasData()) + { + szRemoteCommand.append('\n'); + } + szRemoteCommand.append(a.szExecRemoteCommand); + } + + /* + FIXME: There is a race condition in the IPC mechanism. + If one starts two instances of kvirc one immediately after another + then both instances may run through kvi_sendIpcMessage + without finding the sentinel window and thus both may decide + to start. + A weak file locking mechanism should be used too... + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + QString szLock = convertSeparators(cleanDirPath(QDir::homePath() + "/.kvirc.lock")); +#else + QString szLock = convertSeparators(cleanDirPath(QDir::homePath() + "/.kvirc.lock")); +#endif + + QFileInfo inf(szLock); + bool bLocked = false; + if(inf.exists()) + { + iLocked = inf.lastModified().secsTo(QDateTime::currentDateTime()); + } + */ + +#ifndef COMPILE_NO_IPC + if(!a.bForceNewSession) + { + // here we could use CreateMutex on win and semget() on linux + // in order to get a shared semaphore to ensure instance unicity. + + if(kvi_sendIpcMessage(szRemoteCommand.ptr())) + { + if(szRemoteCommand.isEmpty()) + { + KviCString szTmp(KviCString::Format,"Another KVIrc session is already running on this display and with this user id.\nUse %s -f if you want to force a new session.",argv[0]); + if(a.bShowPopup) + { + QMessageBox::information(0,"Session - KVIrc",szTmp.ptr(),QMessageBox::Ok); + } else { + qDebug("%s",szTmp.ptr()); + } + } + delete pTheApp; + return 0; + } + + if(a.bExecuteCommandAndClose) + { + delete pTheApp; + return 0; + } + } +#endif + + pTheApp->m_bCreateConfig = a.createFile; + pTheApp->m_szConfigFile = a.configFile; + pTheApp->m_szExecAfterStartup = a.szExecCommand; + pTheApp->m_bShowSplashScreen = a.bShowSplashScreen; + pTheApp->setup(); + + // YEAH! + int iRetVal = pTheApp->exec(); + // :) + + delete pTheApp; + + return iRetVal; +} diff --git a/src/kvirc/kernel/KviNotifyList.cpp b/src/kvirc/kernel/KviNotifyList.cpp new file mode 100644 index 000000000..1f4662e17 --- /dev/null +++ b/src/kvirc/kernel/KviNotifyList.cpp @@ -0,0 +1,1294 @@ +//============================================================================= +// +// File : KviNotifyList.cpp +// Creation date : Fri Oct 27 2000 23:41:01 CEST by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_debug.h" +#include "KviNotifyList.h" +#include "KviConsoleWindow.h" +#include "KviIrcSocket.h" +#include "KviRegisteredUserDataBase.h" +#include "KviUserListView.h" +#include "KviChannelWindow.h" +#include "KviOptions.h" +#include "KviWindow.h" +#include "KviLocale.h" +#include "kvi_out.h" +#include "KviIrcServerParser.h" +#include "KviIrcMask.h" +#include "KviIrcNumericCodes.h" +#include "KviParameterList.h" +#include "KviIrcConnection.h" +#include "KviApplication.h" +#include "KviQString.h" +#include "KviLagMeter.h" +#include "KviKvsEventTriggers.h" + +#include +#include + +// FIXME: #warning "Finish this doc!" + +/* + @doc: notify_list + @title: + Notify lists + @short: + Tracking users on IRC + @keyterms: + notify property, watch property, notify lists + @body: + The notify list is a means of keeping track of users on IRC.[br] + Once connected to an IRC server, you can tell KVIrc to check + periodically if your friends are online.[br] + This is basically achieved by setting a property in the [doc:registered_users]registered users database[/doc] + entry.[br] + The property is called "notify", and you have to set it to the nickname + that you want to look for.[br] + So for example, assume to register a frend of yours like Szymon:[br] + [example] + [cmd:reguser.add]reguser.add[/cmd] Szymon + [cmd:reguser.addmask]reguser.addmask[/cmd] Szymon Pragma!*@*.it + [/example] + And then want it in the notify list; nothing easier, just set + hist "notify" property to the nickname that you want him to be "looked for":[br] + [example] + [cmd:reguser.setproperty]reguser.setproperty[/cmd] Szymon notify Pragma + [/example] + In this way, once in a while, KVIrc will send to the server an ISON message + with the nickname Pragma. If Szymon is online, you will be notified with a message:[br] + "Pragma [someuser@somehost.it] is on IRC".[br] + If Szymon uses often "[Pragma]" as his secondary nickname, you can do the following:[br] + [example] + [cmd:reguser.addmask]reguser.addmask[/cmd] Szymon [Pragma]*@*.it + [cmd:reguser.setproperty]reguser.setproperty[/cmd] Szymon notify "Pragma [Pragma]" + [/example] + KVIrc will then look for both nicknames getting online.[br] + KVIrc supports three notify lists management methods:[br] + The "stupid ISON method", the "intelligent ISON method" and the "WATCH method".[br] + The "stupid ISON method" will assume that Szymon is online if any user with nickname + Pragma (or [Pragma] in the second example) gets online; this means that also Pragma!someuser@somehost.com will be + assumed to be "Szymon" and will be shown in the notify list.[br] + This might be a false assumption (since somehod.com does not even match *.it), + but it is the best result that the "stupid ISON method" can achieve.[br] + The "intelligent ISON method" will also check the Pragma's username and hostname + and match it in the registered masks; so in the example above, you will be notified if + any user that matches Pragma!*@*.it gets online; (but you will NOT be notified if + (for example) Pragma!someuser@somehost.com gets online).[br] + So what's the point in including a stupid method? :) Well...the intelligent + method "eats" some of your IRC bandwidth; it has to send USERHOST messages + for every group of 5 users in the notify list. If you have a lot of users + in the notify list, it might become slow and eventually cause a + client to server flood.[br] + So finally, the intelligent method is the default. If you have "flood" problems, + or if you think that the notify list is quite slow, try the "stupid" method: + it is not that bad after all.[br] + The third notify list management method is the "WATCH method".[br] + It uses a totally different (and better) approach to the notify lists management, + and can be used only on the networks that support the WATCH notify method (DALnet, WebNet, etc.).[br] + KVIrc will attempt to guess if the server you're currently using supports the WATCH command + and eventually use this last method.[br] + The WATCH method uses the "notify" property to get the nicknames that have to be + sent to the server in the /WATCH commands. +*/ + +// Basic NotifyListManager: this does completely nothing + +KviNotifyListManager::KviNotifyListManager(KviIrcConnection * pConnection) +: QObject(0) +{ + setObjectName("notify_list_manager"); + m_pConnection = pConnection; + m_pConsole = pConnection->console(); +} + +KviNotifyListManager::~KviNotifyListManager() +{ +} + +void KviNotifyListManager::start() +{ +} + +void KviNotifyListManager::stop() +{ +} + +bool KviNotifyListManager::handleUserhost(KviIrcMessage *) +{ + return false; +} + +bool KviNotifyListManager::handleIsOn(KviIrcMessage *) +{ + return false; +} + +bool KviNotifyListManager::handleWatchReply(KviIrcMessage *) +{ + return false; +} + +void KviNotifyListManager::notifyOnLine(const QString &nick,const QString &user,const QString &host,const QString &szReason,bool bJoin) +{ + if(bJoin) + m_pConsole->notifyListView()->join(nick,user,host); + + KviWindow * out = KVI_OPTION_BOOL(KviOption_boolNotifyListChangesToActiveWindow) ? m_pConsole->activeWindow() : m_pConsole; + if(KVS_TRIGGER_EVENT_1_HALTED(KviEvent_OnNotifyOnLine,out,nick))return; + + QString szWho; + QString szMsg; + + if(!(user.isEmpty() || host.isEmpty())) + KviQString::sprintf(szWho,"\r!n\r%Q\r [%Q@\r!h\r%Q\r]",&nick,&user,&host); + else + KviQString::sprintf(szWho,"\r!n\r%Q\r",&nick); + + KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); + KviPointerHashTableIterator it(*d); + QString szNotify; + + while(KviRegisteredUser * u = it.current()) + { + QString prop=u->getProperty("notify"); + if (!prop.isEmpty()) + { + if(prop.split(",",QString::SkipEmptyParts).indexOf(nick)!=-1) + { + QString szComment=u->getProperty("comment"); + if(!szComment.isEmpty()) + KviQString::sprintf(szMsg,"%Q (%Q), Group \"%Q\" is on IRC as (%Q)",&(u->name()),&szComment,&(u->group()),&szWho); + else + KviQString::sprintf(szMsg,"%Q, Group \"%Q\" is on IRC as (%Q)",&(u->name()),&(u->group()),&szWho); + break; + } + } + ++it; + } + QString szFmt = __tr2qs("%Q is on IRC"); + + if(szMsg.isEmpty()) + KviQString::sprintf(szMsg,szFmt,&szWho); + + if((!szReason.isEmpty()) && (_OUTPUT_VERBOSE)) + { + szMsg += "("; + szMsg += szReason; + szMsg += ")"; + } + + out->outputNoFmt(KVI_OUT_NOTIFYONLINE,szMsg); + + if(!(out->hasAttention())) + { + if(KVI_OPTION_BOOL(KviOption_boolFlashWindowOnNotifyOnLine)) + out->demandAttention(); + if(KVI_OPTION_BOOL(KviOption_boolPopupNotifierOnNotifyOnLine)) + { + szWho = ""; + szWho += nick; + szWho += ""; + KviQString::sprintf(szMsg,szFmt,&szWho); + g_pApp->notifierMessage(0,KVI_OPTION_MSGTYPE(KVI_OUT_NOTIFYONLINE).pixId(),szMsg,KVI_OPTION_UINT(KviOption_uintNotifierAutoHideTime)); + } + } +} + +void KviNotifyListManager::notifyOffLine(const QString &nick,const QString &user,const QString &host,const QString &szReason) +{ + KviWindow * out = KVI_OPTION_BOOL(KviOption_boolNotifyListChangesToActiveWindow) ? m_pConsole->activeWindow() : m_pConsole; + if(!KVS_TRIGGER_EVENT_1_HALTED(KviEvent_OnNotifyOffLine,out,nick)) + { + QString szWho; + + if(!(user.isEmpty() || host.isEmpty())) + KviQString::sprintf(szWho,"\r!n\r%Q\r [%Q@\r!h\r%Q\r]",&nick,&user,&host); + else + KviQString::sprintf(szWho,"\r!n\r%Q\r",&nick); + + QString szMsg; + + KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); + KviPointerHashTableIterator it(*d); + QString szNotify; + + while(KviRegisteredUser * u = it.current()) + { + QString prop=u->getProperty("notify"); + if (!prop.isEmpty()) + { + if(prop.split(",",QString::SkipEmptyParts).indexOf(nick)!=-1) + { + QString szComment=u->getProperty("comment"); + if(!szComment.isEmpty()) + KviQString::sprintf(szMsg,"%Q (%Q), Group \"%Q\" has left IRC as (%Q)",&(u->name()),&szComment,&(u->group()),&szWho); + else + KviQString::sprintf(szMsg,"%Q, Group \"%Q\" has left IRC as (%Q)",&(u->name()),&(u->group()),&szWho); + break; + } + } + ++it; + } + + if(szMsg.isEmpty()) + KviQString::sprintf(szMsg,__tr2qs("%Q has left IRC"),&szWho); + + if((!szReason.isEmpty()) && (_OUTPUT_VERBOSE)) + { + szMsg += "("; + szMsg += szReason; + szMsg += ")"; + } + + out->outputNoFmt(KVI_OUT_NOTIFYOFFLINE,szMsg); + } + + m_pConsole->notifyListView()->part(nick); +} + + + +// +// INTELLIGENT NOTIFY LIST MANAGER: NOTIFY PROCESS: +// +// start() stop() +// | ^ +// buildRegUserDict() | +// | | +// m_pRegUserDict->isEmpty() ? -- YES ---------->+ +// | | +// NO | +// | | +// newNotifySession()<------- TIMER ---------------- delayedNotifySession() --------------------------------+ +// | (can be stopped here) | ^ | +// | | ^ | +// buildNotifyList() | | YES +// | | | | +// m_pNotifyList->isEmpty() ? - YES ->+ | | +// | | | +// NO | | +// | | | +// newIsOnSession()<------------- TIMER -------------------- delayedIsOnSession() -- NO - m_pNotifyList->isEmpty() ? +// | (can be stopped here) | | +// | | | +// buildIsOnList() | | +// | | | +// m_pIsOnList->isEmpty() ? -- YES ---------->+ | +// | | +// NO | +// | | +// sendIsOn() - - - - - - - - - - - -> handleIsOn() | +// | | +// (build m_pOnlineList) | +// | | +// m_pOnlineList->isEmpty() ? - YES ----------------------->+ +// | | +// NO YES +// | | +// delayedUserhostSession()<--------------- NO - m_pOnlineList->isEmpty() ? +// | ^ +// TIMER (can be stopped here) | +// | | +// newUserhostSession() | +// | | +// buildUserhostList() | +// | | +// m_pUserhostList->isEmpty() ? - YES --->+ +// | ^^^ | +// | (unexpected!)||| | +// NO | +// | | +// sendUserhost() - - - - - - - - > handleUserhost() +// + + +KviIsOnNotifyListManager::KviIsOnNotifyListManager(KviIrcConnection * pConnection) +: KviNotifyListManager(pConnection) +{ + m_pRegUserDict = new KviPointerHashTable(17,false); // case insensitive, copy keys + m_pRegUserDict->setAutoDelete(true); + m_pNotifyList = new KviPointerList; + m_pNotifyList->setAutoDelete(true); + m_pIsOnList = new KviPointerList; + m_pIsOnList->setAutoDelete(true); + m_pOnlineList = new KviPointerList; + m_pOnlineList->setAutoDelete(true); + m_pUserhostList = new KviPointerList; + m_pUserhostList->setAutoDelete(true); + m_pDelayedNotifyTimer = new QTimer(); + connect(m_pDelayedNotifyTimer,SIGNAL(timeout()),this,SLOT(newNotifySession())); + m_pDelayedIsOnTimer = new QTimer(); + connect(m_pDelayedIsOnTimer,SIGNAL(timeout()),this,SLOT(newIsOnSession())); + m_pDelayedUserhostTimer = new QTimer(); + connect(m_pDelayedUserhostTimer,SIGNAL(timeout()),this,SLOT(newUserhostSession())); + m_bRunning = false; +} + + +KviIsOnNotifyListManager::~KviIsOnNotifyListManager() +{ + if(m_bRunning)stop(); + delete m_pDelayedNotifyTimer; + delete m_pDelayedIsOnTimer; + delete m_pDelayedUserhostTimer; + delete m_pRegUserDict; + delete m_pOnlineList; + delete m_pNotifyList; + delete m_pIsOnList; + delete m_pUserhostList; +} + +void KviIsOnNotifyListManager::start() +{ + if(m_bRunning)stop(); + m_bRunning = true; + m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); + + m_bExpectingIsOn = false; + m_bExpectingUserhost = false; + + buildRegUserDict(); + if(m_pRegUserDict->isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: No users to check for, quitting")); + stop(); + return; + } + newNotifySession(); +} + +void KviIsOnNotifyListManager::buildRegUserDict() +{ + m_pRegUserDict->clear(); + + const KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); + KviPointerHashTableIterator it(*d); + while(KviRegisteredUser * u = it.current()) + { + QString notify; + if(u->getProperty("notify",notify)) + { + notify.trimmed(); + while(!notify.isEmpty()) + { + int idx = notify.indexOf(' '); + if(idx > 0) + { + QString single = notify.left(idx); + m_pRegUserDict->replace(single,new QString(u->name())); + notify.remove(0,idx+1); + } else { + m_pRegUserDict->replace(notify,new QString(u->name())); + notify = ""; + } + } + } + ++it; + } +} + +void KviIsOnNotifyListManager::delayedNotifySession() +{ + unsigned int iTimeout = KVI_OPTION_UINT(KviOption_uintNotifyListCheckTimeInSecs); + if(iTimeout < 15) + { + // life first of all. + // don't allow the user to suicide + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("Notify list: Timeout (%d sec) is too short, resetting to something more reasonable (15 sec)"), + iTimeout); + iTimeout = 15; + KVI_OPTION_UINT(KviOption_uintNotifyListCheckTimeInSecs) = 15; + } + m_pDelayedNotifyTimer->setInterval(iTimeout * 1000); + m_pDelayedNotifyTimer->setSingleShot(true); + m_pDelayedNotifyTimer->start(); +} + +void KviIsOnNotifyListManager::newNotifySession() +{ + buildNotifyList(); + if(m_pNotifyList->isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Notify list empty, quitting")); + stop(); + return; + } + newIsOnSession(); +} + +void KviIsOnNotifyListManager::buildNotifyList() +{ + m_pNotifyList->clear(); + KviPointerHashTableIterator it(*m_pRegUserDict); + while(it.current()) + { + m_pNotifyList->append(new QString(it.currentKey())); + ++it; + } +} + +void KviIsOnNotifyListManager::delayedIsOnSession() +{ + unsigned int iTimeout = KVI_OPTION_UINT(KviOption_uintNotifyListIsOnDelayTimeInSecs); + if(iTimeout < 5) + { + // life first of all. + // don't allow the user to suicide + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("Notify list: ISON delay (%d sec) is too short, resetting to something more reasonable (5 sec)"), + iTimeout); + iTimeout = 5; + KVI_OPTION_UINT(KviOption_uintNotifyListIsOnDelayTimeInSecs) = 5; + } + m_pDelayedIsOnTimer->setInterval(iTimeout * 1000); + m_pDelayedIsOnTimer->setSingleShot(true); + m_pDelayedIsOnTimer->start(); +} + +void KviIsOnNotifyListManager::newIsOnSession() +{ + buildIsOnList(); + if(m_pIsOnList->isEmpty())delayedNotifySession(); + else sendIsOn(); +} + +void KviIsOnNotifyListManager::buildIsOnList() +{ + m_pIsOnList->clear(); + m_szIsOnString = ""; + m_pNotifyList->setAutoDelete(false); + while(QString * s = m_pNotifyList->first()) + { + if(((m_szIsOnString.length() + s->length()) + 1) < 504) + { + if(!m_szIsOnString.isEmpty())m_szIsOnString.append(' '); + m_szIsOnString.append(*s); + m_pIsOnList->append(s); + m_pNotifyList->removeFirst(); + } else break; + } + m_pNotifyList->setAutoDelete(true); +} + +void KviIsOnNotifyListManager::sendIsOn() +{ + if(_OUTPUT_PARANOIC) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Checking for: %Q"),&m_szIsOnString); + QByteArray szDec = m_pConnection->encodeText(m_szIsOnString); + m_pConnection->sendFmtData("ISON %s",szDec.data()); + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckRegister("@notify_ison",40); // not that reliable + m_szIsOnString = ""; + m_bExpectingIsOn = true; + // FIXME: #warning "And if can't send ?" +} + + +bool KviIsOnNotifyListManager::handleIsOn(KviIrcMessage *msg) +{ + if(!m_bExpectingIsOn)return false; + + // Check if it is our ISON + // all the nicks must be on the IsOnList + + KviPointerList tmplist; + tmplist.setAutoDelete(false); + + KviCString nk; + const char * aux = msg->trailing(); + + while(*aux) + { + nk = ""; + aux = kvi_extractToken(nk,aux,' '); + if(nk.hasData()) + { + bool bGotIt = false; + QString dnk = m_pConnection->decodeText(nk.ptr()); + for(QString * s = m_pIsOnList->first();s && (!bGotIt);s = m_pIsOnList->next()) + { + if(KviQString::equalCI(*s,dnk)) + { + tmplist.append(s); + bGotIt = true; + } + } + if(!bGotIt) + { + // ops...not my userhost! + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Hey! You've used ISON behind my back? (I might be confused now...)")); + return false; + } + } + } + + // Ok...looks to be my ison (still not sure at 100%, but can't do better) + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckComplete("@notify_ison"); + + m_bExpectingIsOn = false; + + m_pOnlineList->clear(); + + m_pIsOnList->setAutoDelete(false); + + // Ok...we have an IsOn reply here + // The nicks in the IsOnList that are also in the reply are online, and go to the OnlineList + // the remaining in the IsOnList are offline + + QString * s; + + for(s = tmplist.first();s;s = tmplist.next()) + { + m_pIsOnList->removeRef(s); + m_pOnlineList->append(s); + } + + m_pIsOnList->setAutoDelete(true); + // Ok...all the users that are online, are on the OnlineList + // the remaining users are in the m_pIsOnList, and are no longer online + + // first the easy step: remove the users that have just left irc or have never been online + // we're clearling the m_pIsOnList + while((s = m_pIsOnList->first())) + { + if(m_pConsole->notifyListView()->findEntry(*s)) + { + // has just left IRC... make him part + notifyOffLine(*s); + } // else has never been here + + m_pIsOnList->removeFirst(); // autodelete is true + } + + // ok... complex step now: the remaining users in the userhost list are online + // if they have been online before, just remove them from the list + // otherwise they must be matched for masks + // and eventually inserted in the notify view later + + KviIrcUserDataBase * db = console()->connection()->userDataBase(); + + KviPointerList l; + l.setAutoDelete(false); + + for(s = m_pOnlineList->first();s;s = m_pOnlineList->next()) + { + if(KviUserListEntry * ent = m_pConsole->notifyListView()->findEntry(*s)) + { + // the user was online from a previous notify session + // might the mask have been changed ? (heh...this is tricky, maybe too much even) + if(KVI_OPTION_BOOL(KviOption_boolNotifyListSendUserhostForOnlineUsers)) + { + // user wants to be sure about online users.... + // check if he is on some channels + if(ent->globalData()->nRefs() > 1) + { + // mmmh...we have more than one ref, so the user is at least in one query or channel + // look him up on channels, if we find his entry, we can be sure that he is + // still the right user + KviPointerList * chlist = m_pConsole->connection()->channelList(); + for(KviChannelWindow * ch = chlist->first();ch;ch = chlist->next()) + { + if(KviUserListEntry * le = ch->findEntry(*s)) + { + l.append(s); // ok...found on a channel...we don't need an userhost to match him + KviIrcMask mk(*s,le->globalData()->user(),le->globalData()->host()); + if(!doMatchUser(*s,mk))return true; // critical problems = have to restart!!! + break; + } + } + } // else Only one ref...we need an userhost to be sure (don't remove from the list) + } else { + // user wants no userhost for online users...we "hope" that everything will go ok. + l.append(s); + } + //l.append(s); // we will remove him from the list + } else { + // the user was not online! + // check if we have a cached mask + if(db) + { + if(KviIrcUserEntry * ue = db->find(*s)) + { + // already in the db... do we have a mask ? + if(ue->hasUser() && ue->hasHost()) + { + // yup! we have a complete mask to match on + KviIrcMask mk(*s,ue->user(),ue->host()); + // lookup the user's name in the m_pRegUserDict + if(!doMatchUser(*s,mk))return true; // critical problems = have to restart!!! + l.append(s); // remove anyway + } + } + } + } + } + + for(s = l.first();s;s = l.next()) + { + m_pOnlineList->removeRef(s); // autodelete is true + } + + if(m_pOnlineList->isEmpty()) + { + if(m_pNotifyList->isEmpty())delayedNotifySession(); + else delayedIsOnSession(); + } else delayedUserhostSession(); + + return true; +} + +// FIXME: #warning "Nickname escapes (links) in the notifylist messages!" + +bool KviIsOnNotifyListManager::doMatchUser(const QString ¬ifyString,const KviIrcMask & mask) +{ + QString * nam = m_pRegUserDict->find(notifyString); + if(nam) + { + // ok...find the user + if(KviRegisteredUser * u = g_pRegisteredUserDataBase->findUserByName(*nam)) + { + // ok ... match the user + if(u->matchesFixed(mask)) + { + // new user online + if(!(m_pConsole->notifyListView()->findEntry(mask.nick()))) + { + notifyOnLine(mask.nick(),mask.user(),mask.host()); + } // else already online, and matching...all ok + } else { + // not matched.... has he been online before ? + if(m_pConsole->notifyListView()->findEntry(mask.nick())) + { + // has been online just a sec ago, but now the mask does not match + // either reguserdb has changed, or the user went offline and another one got his nick + // in the meantime... (ugly situation anyway) + notifyOffLine(mask.nick(),mask.user(),mask.host(),__tr2qs("registration mask changed, or nickname is being used by someone else")); + } else { + // has never been online + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: \r!n\r%Q\r appears to be online, but the mask [%Q@\r!h\r%Q\r] does not match (registration mask does not match, or nickname is being used by someone else)"),&(mask.nick()),&(mask.user()),&(mask.host())); + } + } + } else { + // ops... unexpected inconsistency .... reguser db modified ? + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Unexpected inconsistency, registered user DB modified? (restarting)")); + stop(); + start(); + return false; // critical ... exit from the call stack + } + } else { + // ops...unexpected inconsistency + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Unexpected inconsistency, expected \r!n\r%Q\r in the registered user DB"),¬ifyString); + } + return true; +} + +void KviIsOnNotifyListManager::delayedUserhostSession() +{ + unsigned int iTimeout = KVI_OPTION_UINT(KviOption_uintNotifyListUserhostDelayTimeInSecs); + if(iTimeout < 5) + { + // life first of all. + // don't allow the user to suicide + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("Notify list: USERHOST delay (%d sec) is too short, resetting to something more reasonable (5 sec)"), + iTimeout); + iTimeout = 5; + KVI_OPTION_UINT(KviOption_uintNotifyListUserhostDelayTimeInSecs) = 5; + } + m_pDelayedUserhostTimer->setInterval(iTimeout * 1000); + m_pDelayedUserhostTimer->setSingleShot(true); + m_pDelayedUserhostTimer->start(); +} + +void KviIsOnNotifyListManager::newUserhostSession() +{ + buildUserhostList(); + if(m_pUserhostList->isEmpty()) + { + // this is unexpected! + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Unexpected inconsistency, userhost list is empty!")); + if(m_pOnlineList->isEmpty()) + { + if(m_pNotifyList->isEmpty())delayedNotifySession(); + else delayedIsOnSession(); + } else delayedUserhostSession(); + return; + } + sendUserhost(); +} + +#define MAX_USERHOST_ENTRIES 5 + +void KviIsOnNotifyListManager::buildUserhostList() +{ + m_szUserhostString = ""; + m_pUserhostList->clear(); + + m_pOnlineList->setAutoDelete(false); + int i = 0; + QString * s; + while((s = m_pOnlineList->first()) && (i < MAX_USERHOST_ENTRIES)) + { + if(!m_szUserhostString.isEmpty())m_szUserhostString.append(' '); + m_szUserhostString.append(*s); + m_pUserhostList->append(s); + m_pOnlineList->removeFirst(); + i++; + } + m_pOnlineList->setAutoDelete(true); +} + +void KviIsOnNotifyListManager::sendUserhost() +{ + if(_OUTPUT_PARANOIC) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Checking userhost for: %Q"),&m_szUserhostString); + QByteArray ccc = m_pConnection->encodeText(m_szUserhostString); + m_pConnection->sendFmtData("USERHOST %s",ccc.data()); + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckRegister("@notify_userhost",50); + m_szUserhostString = ""; + m_bExpectingUserhost = true; +// FIXME: #warning "And if can't send ?" +} + +bool KviIsOnNotifyListManager::handleUserhost(KviIrcMessage *msg) +{ + if(!m_bExpectingUserhost)return false; + // first check for consistency: all the replies must be on the USERHOST list + KviPointerList tmplist; + tmplist.setAutoDelete(true); + + KviCString nk; + const char * aux = msg->trailing(); + + while(*aux) + { + nk = ""; + aux = kvi_extractToken(nk,aux,' '); + if(nk.hasData()) + { + // split it in a mask + KviCString nick; + KviCString user; + KviCString host; + + int idx = nk.findFirstIdx('='); + if(idx != -1) + { + nick = nk.left(idx); + if(nick.lastCharIs('*'))nick.cutRight(1); + nk.cutLeft(idx + 1); + if(nk.firstCharIs('+') || nk.firstCharIs('-'))nk.cutLeft(1); + + idx = nk.findFirstIdx('@'); + if(idx != -1) + { + user = nk.left(idx); + nk.cutLeft(idx + 1); + host = nk; + } else { + user = "*"; + host = nk; + } + + bool bGotIt = false; + QString szNick = m_pConnection->decodeText(nick.ptr()); + QString szUser = m_pConnection->decodeText(user.ptr()); + QString szHost = m_pConnection->decodeText(host.ptr()); + + for(QString * s = m_pUserhostList->first();s && (!bGotIt);s = m_pUserhostList->next()) + { + if(KviQString::equalCI(*s,szNick)) + { + KviIrcMask * mk = new KviIrcMask(szNick,szUser,szHost); + tmplist.append(mk); + bGotIt = true; + m_pUserhostList->removeRef(s); + } + } + + if(!bGotIt) + { + // ops...not my userhost! + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Hey! You've used USERHOST behind my back? (I might be confused now...)")); + return false; + } + } else { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Broken USERHOST reply from the server? (%s)"),nk.ptr()); + } + } + } + + // Ok...looks to be my usershot (still not sure at 100%, but can't do better) + + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckComplete("@notify_userhost"); + + + m_bExpectingUserhost = false; + + for(KviIrcMask * mk = tmplist.first();mk;mk = tmplist.next()) + { + if(!doMatchUser(mk->nick(),*mk))return true; // have to restart!!! + } + + if(!(m_pUserhostList->isEmpty())) + { + // ops...someone is no longer online ? + while(QString * s = m_pUserhostList->first()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: \r!n\r%Q\r appears to have gone offline before USERHOST reply was received, will recheck in the next loop"),s); + m_pUserhostList->removeFirst(); + } + + } + + if(m_pOnlineList->isEmpty()) + { + if(m_pNotifyList->isEmpty())delayedNotifySession(); + else delayedIsOnSession(); + } else delayedUserhostSession(); + + return true; +} + +void KviIsOnNotifyListManager::stop() +{ + if(!m_bRunning)return; + + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckAbort("@notify_userhost"); + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckAbort("@notify_ison"); + + m_pDelayedNotifyTimer->stop(); + m_pDelayedIsOnTimer->stop(); + m_pDelayedUserhostTimer->stop(); + m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); + m_pRegUserDict->clear(); + m_pNotifyList->clear(); + m_pIsOnList->clear(); + m_pOnlineList->clear(); + m_pUserhostList->clear(); + m_szIsOnString = ""; + m_szUserhostString = ""; + m_bRunning = false; +} + + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Stupid notify list manager +// +/////////////////////////////////////////////////////////////////////////////////////////////////// + +KviStupidNotifyListManager::KviStupidNotifyListManager(KviIrcConnection * pConnection) +: KviNotifyListManager(pConnection) +{ + m_pNickList = new KviPointerList; + m_pNickList->setAutoDelete(true); + m_iRestartTimer = 0; +} + +KviStupidNotifyListManager::~KviStupidNotifyListManager() +{ + if(m_iRestartTimer) + { + killTimer(m_iRestartTimer); + m_iRestartTimer = 0; + } + delete m_pNickList; +} + +void KviStupidNotifyListManager::start() +{ + if(m_iRestartTimer) + { + killTimer(m_iRestartTimer); + m_iRestartTimer = 0; + } + if(_OUTPUT_VERBOSE) + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Starting notify list")); + buildNickList(); + if(m_pNickList->isEmpty()) + { + if(_OUTPUT_VERBOSE) + m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("No users in the notify list")); + return; // Ok...no nicknames in the list + } + m_iNextNickToCheck = 0; + m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); + sendIsOn(); +} + +void KviStupidNotifyListManager::sendIsOn() +{ + m_szLastIsOnMsg = ""; + QString * nick = m_pNickList->at(m_iNextNickToCheck); + KVI_ASSERT(nick); + + int i = 0; + while(nick && ((nick->length() + 5 + m_szLastIsOnMsg.length()) < 510)) + { + KviQString::appendFormatted(m_szLastIsOnMsg," %Q",nick); + nick = m_pNickList->next(); + i++; + } + if(_OUTPUT_PARANOIC) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Checking for: %Q"),&m_szLastIsOnMsg); + QByteArray dat = m_pConnection->encodeText(m_szLastIsOnMsg); + m_pConnection->sendFmtData("ISON%s",dat.data()); + + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckRegister("@notify_naive",20); + + m_iNextNickToCheck += i; +} + +bool KviStupidNotifyListManager::handleIsOn(KviIrcMessage * msg) +{ + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckComplete("@notify_naive"); + + KviCString nk; + const char * aux = msg->trailing(); + while(*aux) + { + nk = ""; + aux = kvi_extractToken(nk,aux,' '); + if(nk.hasData()) + { + QString nkd = m_pConnection->decodeText(nk.ptr()); + QString nksp = " " + nkd; + m_szLastIsOnMsg.replace(nksp,"",Qt::CaseInsensitive); + if(!(m_pConsole->notifyListView()->findEntry(nkd))) + { + // not yet notified + notifyOnLine(nkd); + } + } + } + // ok...check the users that have left irc now... + QStringList sl = m_szLastIsOnMsg.isEmpty()?QStringList():m_szLastIsOnMsg.split(' ',QString::SkipEmptyParts); + + for(QStringList::Iterator it = sl.begin();it != sl.end();++it) + { + if(m_pConsole->notifyListView()->findEntry(*it)) + { + // has just left irc + notifyOffLine(*it); + } // else has never been here... + } + + if(((unsigned int)m_iNextNickToCheck) >= m_pNickList->count()) + { + // have to restart + unsigned int iTimeout = KVI_OPTION_UINT(KviOption_uintNotifyListCheckTimeInSecs); + if(iTimeout < 5) + { + // life first of all. + // don't allow the user to suicide + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("Notify list: Timeout (%d sec) is too short, resetting to something more reasonable (5 sec)"), + iTimeout); + iTimeout = 5; + KVI_OPTION_UINT(KviOption_uintNotifyListCheckTimeInSecs) = 5; + } + m_iRestartTimer = startTimer(iTimeout * 1000); + } else sendIsOn(); + return true; +} + +void KviStupidNotifyListManager::timerEvent(QTimerEvent *e) +{ + if(e->timerId() == m_iRestartTimer) + { + killTimer(m_iRestartTimer); + m_iRestartTimer = 0; + m_iNextNickToCheck = 0; + sendIsOn(); + return; + } + QObject::timerEvent(e); +} + +void KviStupidNotifyListManager::stop() +{ + if(m_pConnection->lagMeter()) + m_pConnection->lagMeter()->lagCheckAbort("@notify_naive"); + + if(m_iRestartTimer) + { + killTimer(m_iRestartTimer); + m_iRestartTimer = 0; + } + m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); + + // The ISON Method needs no stopping +} + +void KviStupidNotifyListManager::buildNickList() +{ + const KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); + KviPointerHashTableIterator it(*d); + m_pNickList->clear(); + while(it.current()) + { + QString notify; + if(it.current()->getProperty("notify",notify)) + { + m_pNickList->append(new QString(notify)); + } + ++it; + } +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Watch notify list manager +// +/////////////////////////////////////////////////////////////////////////////////////////////////// + +KviWatchNotifyListManager::KviWatchNotifyListManager(KviIrcConnection * pConnection) +: KviNotifyListManager(pConnection) +{ + m_pRegUserDict = new KviPointerHashTable(17,false); + m_pRegUserDict->setAutoDelete(true); +} + +KviWatchNotifyListManager::~KviWatchNotifyListManager() +{ + delete m_pRegUserDict; +} + +void KviWatchNotifyListManager::buildRegUserDict() +{ + m_pRegUserDict->clear(); + + const KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); + KviPointerHashTableIterator it(*d); + while(KviRegisteredUser * u = it.current()) + { + QString notify; + if(u->getProperty("notify",notify)) + { + notify.trimmed(); + QStringList sl = notify.split(' ',QString::SkipEmptyParts); + for(QStringList::Iterator it = sl.begin();it != sl.end();++it) + { + m_pRegUserDict->replace(*it,new QString(u->name())); + } + } + ++it; + } +} + +void KviWatchNotifyListManager::start() +{ + m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); + + buildRegUserDict(); + + QString watchStr; + + KviPointerHashTableIterator it(*m_pRegUserDict); + while(it.current()) + { + QString nk = it.currentKey(); + if(nk.indexOf('*') == -1) + { + if((watchStr.length() + nk.length() + 2) > 501) + { + QByteArray dat = m_pConnection->encodeText(watchStr); + m_pConnection->sendFmtData("WATCH%s",dat.data()); + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Adding watch entries for %Q"),&watchStr); + watchStr = ""; + } + KviQString::appendFormatted(watchStr," +%Q",&nk); + } + ++it; + } + + if(!watchStr.isEmpty()) + { + QByteArray dat = m_pConnection->encodeText(watchStr); + m_pConnection->sendFmtData("WATCH%s",dat.data()); + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Adding watch entries for %Q"),&watchStr); + } +} +void KviWatchNotifyListManager::stop() +{ + m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); + m_pConnection->sendFmtData("WATCH clear"); + m_pRegUserDict->clear(); +} + +bool KviWatchNotifyListManager::doMatchUser(KviIrcMessage * msg,const QString ¬ifyString,const KviIrcMask & mask) +{ + QString * nam = m_pRegUserDict->find(notifyString); + + if(nam) + { + // ok...find the user + if(KviRegisteredUser * u = g_pRegisteredUserDataBase->findUserByName(*nam)) + { + // ok ... match the user + if(u->matchesFixed(mask)) + { + // new user online + if(!(m_pConsole->notifyListView()->findEntry(mask.nick()))) + { + notifyOnLine(mask.nick(),mask.user(),mask.host(),"watch"); + } else { + // else already online, and matching...all ok + if(msg->numeric() == RPL_NOWON) + { + // This is a reply to a /watch +something (should not happen, unless the user is messing) or to /watch l (user requested) + notifyOnLine(mask.nick(),mask.user(),mask.host(), + __tr2qs("watch entry listing requested by user"),false); + } else { + // This is a RPL_LOGON....we're desynched ? + notifyOnLine(mask.nick(),mask.user(),mask.host(), + __tr2qs("possible watch list desync"),false); + } + } + } else { + // not matched.... has he been online before ? + if(m_pConsole->notifyListView()->findEntry(mask.nick())) + { + // has been online just a sec ago, but now the mask does not match + // prolly the reguserdb has been changed + notifyOffLine(mask.nick(),mask.user(),mask.host(), + __tr2qs("registration mask changed or desync with the watch service")); + } else { + // has never been online + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, + __tr("Notify list: \r!n\r%Q\r appears to be online, but the mask [%Q@\r!h\r%Q\r] does not match (watch: registration mask does not match, or nickname is being used by someone else)"), + &(mask.nick()),&(mask.user()),&(mask.host())); + } + } + } else { + // ops... unexpected inconsistency .... reguser db modified ? + m_pConsole->output(KVI_OUT_SYSTEMWARNING, + __tr2qs("Notify list: Unexpected inconsistency, registered user DB modified? (watch: restarting)")); + stop(); + start(); + return false; // critical ... exit from the call stack + } + } else { + // not in our dictionary + // prolly someone used /WATCH behind our back... bad boy! + if(!(m_pConsole->notifyListView()->findEntry(mask.nick()))) + { + notifyOnLine(mask.nick(),mask.user(),mask.host(),__tr2qs("watch entry added by user")); + } + } + return true; +} + +// FIXME: #warning "DEDICATED WATCH LIST VERBOSITY FLAG ? (To allow the user to use /WATCH l and manual /WATCH)" + +bool KviWatchNotifyListManager::handleWatchReply(KviIrcMessage *msg) +{ + // 600: RPL_LOGON + // :prefix 600 :logged online + // 601: RPL_LOGON + // :prefix 601 :logged offline + // 604: PRL_NOWON + // :prefix 604 :is online + // 605: PRL_NOWOFF + // :prefix 605 0 :is offline + +// FIXME: #warning "Use the logintime in some way ?" + + const char * nk = msg->safeParam(1); + const char * us = msg->safeParam(2); + const char * ho = msg->safeParam(3); + QString dnk = m_pConnection->decodeText(nk); + QString dus = m_pConnection->decodeText(us); + QString dho = m_pConnection->decodeText(ho); + + if((msg->numeric() == RPL_LOGON) || (msg->numeric() == RPL_NOWON)) + { + KviIrcMask m(dnk,dus,dho); + doMatchUser(msg,dnk,m); + return true; + + } else if(msg->numeric() == RPL_WATCHOFF) + { + if(m_pConsole->notifyListView()->findEntry(dnk)) + { + notifyOffLine(dnk,dus,dho,__tr2qs("removed from watch list")); + } else { + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Stopped watching for \r!n\r%Q\r"),&dnk); + } + if(m_pRegUserDict->find(dnk))m_pRegUserDict->remove(dnk); // kill that + + return true; + + } else if((msg->numeric() == RPL_LOGOFF) || (msg->numeric() == RPL_NOWOFF)) + { + if(m_pConsole->notifyListView()->findEntry(dnk)) + { + notifyOffLine(dnk,dus,dho,__tr2qs("watch")); + } else { + if(msg->numeric() == RPL_NOWOFF) + { + // This is a reply to a /watch +something + if(_OUTPUT_VERBOSE) + m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: \r!n\r%Q\r is offline (watch)"),&dnk); + } else { + // This is a RPL_LOGOFF for an user that has not matched the reg-mask + notifyOffLine(dnk,dus,dho,__tr2qs("unmatched watch list entry")); + } + } + return true; + } + + return false; +} + + +#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES +#include "kvi_notifylist.moc" +#endif //!COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/KviNotifyList.h b/src/kvirc/kernel/KviNotifyList.h new file mode 100644 index 000000000..a06f99904 --- /dev/null +++ b/src/kvirc/kernel/KviNotifyList.h @@ -0,0 +1,160 @@ +#ifndef _KVI_NOTIFYLIST_H_ +#define _KVI_NOTIFYLIST_H_ + +//============================================================================= +// +// File : KviNotifyList.h +// Creation date : Fri Oct 27 2000 23:39:09 CEST by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviPointerList.h" +#include "KviPointerHashTable.h" + +#include +#include + +class KviConsole; +class KviIrcMessage; +class KviIrcMask; +class KviIrcConnection; + +class KVIRC_API KviNotifyListManager : public QObject +{ + friend class KviConsole; + friend class KviConnectionInfo; + friend class KviIrcServerParser; + friend class KviIrcConnection; + Q_OBJECT +protected: + KviNotifyListManager(KviIrcConnection * pConnection); + ~KviNotifyListManager(); +protected: + KviConsole * m_pConsole; + KviIrcConnection * m_pConnection; +protected: + virtual void start(); + virtual void stop(); + virtual bool handleUserhost(KviIrcMessage * msg); + virtual bool handleIsOn(KviIrcMessage * msg); + virtual bool handleWatchReply(KviIrcMessage *msg); + void notifyOnLine(const QString &nick,const QString &user = QString(),const QString &host = QString(),const QString &szReason = QString(),bool bJoin=true); + void notifyOffLine(const QString &nick,const QString &user = QString(),const QString &host = QString(),const QString &szReason = QString()); +public: + KviConsole * console(){ return m_pConsole; }; +}; + +class KVIRC_API KviIsOnNotifyListManager : public KviNotifyListManager +{ + friend class KviConsole; + friend class KviIrcServerParser; + friend class KviIrcConnection; + Q_OBJECT +protected: + KviIsOnNotifyListManager(KviIrcConnection * pConnection); + ~KviIsOnNotifyListManager(); +private: + KviPointerHashTable * m_pRegUserDict; // dict notifystring->reguser name + KviPointerList * m_pNotifyList; // list of notifystring (total) + KviPointerList * m_pIsOnList; // list of notifystring (one session) + QString m_szIsOnString; // m_pIsOnList in form of a string + KviPointerList * m_pOnlineList; // + KviPointerList * m_pUserhostList; + QString m_szUserhostString; + bool m_bExpectingIsOn; + bool m_bExpectingUserhost; + QTimer * m_pDelayedIsOnTimer; + QTimer * m_pDelayedNotifyTimer; + QTimer * m_pDelayedUserhostTimer; + bool m_bRunning; +protected: + virtual void start(); + virtual void stop(); + virtual bool handleUserhost(KviIrcMessage *msg); + virtual bool handleIsOn(KviIrcMessage *msg); +private: + void delayedNotifySession(); + void delayedIsOnSession(); + void delayedUserhostSession(); +private slots: + void newNotifySession(); + void newIsOnSession(); + void newUserhostSession(); + + void buildRegUserDict(); + void buildIsOnList(); + void buildUserhostList(); + void buildNotifyList(); + void sendIsOn(); + void sendUserhost(); + bool doMatchUser(const QString ¬ifyString,const KviIrcMask & mask); + +}; + + +class KVIRC_API KviStupidNotifyListManager : public KviNotifyListManager +{ + friend class KviConsole; + friend class KviIrcServerParser; + friend class KviIrcConnection; + Q_OBJECT +protected: + KviStupidNotifyListManager(KviIrcConnection * pConnection); + ~KviStupidNotifyListManager(); +protected: + KviPointerList * m_pNickList; + QString m_szLastIsOnMsg; + int m_iNextNickToCheck; + int m_iRestartTimer; +protected: + virtual void start(); + virtual void stop(); + virtual bool handleIsOn(KviIrcMessage *msg); +protected: + virtual void timerEvent(QTimerEvent *e); +private: + void buildNickList(); + void sendIsOn(); +}; + +class KVIRC_API KviWatchNotifyListManager : public KviNotifyListManager +{ + friend class KviConsole; + friend class KviIrcServerParser; + friend class KviIrcConnection; + Q_OBJECT +public: + KviWatchNotifyListManager(KviIrcConnection * pConnection); + ~KviWatchNotifyListManager(); +protected: + KviPointerHashTable * m_pRegUserDict; // dict notifystring->reguser name +protected: + void buildRegUserDict(); + virtual void start(); + virtual void stop(); + virtual bool handleWatchReply(KviIrcMessage *msg); + bool doMatchUser(KviIrcMessage *msg,const QString ¬ifyString,const KviIrcMask & mask); + +}; + +#endif //_KVI_NOTIFYLIST_H_ diff --git a/src/kvirc/kernel/KviOptions.cpp b/src/kvirc/kernel/KviOptions.cpp new file mode 100644 index 000000000..3e7d76c05 --- /dev/null +++ b/src/kvirc/kernel/KviOptions.cpp @@ -0,0 +1,1445 @@ +//============================================================================= +// +// File : KviOptions.cpp +// Creation date : Tue Jun 20 2000 11:42:00 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + + + +#define _KVI_OPTIONS_CPP_ + +#include "KviOptions.h" +#include "kvi_defaults.h" +#include "KviConfigurationFile.h" +#include "KviApplication.h" +#include "KviIconManager.h" +#include "KviMircCntrl.h" +#include "KviLocale.h" +#include "kvi_confignames.h" +#include "KviWindow.h" +#include "kvi_out.h" +#include "KviStringConversion.h" +#include "kvi_settings.h" +#include "KviSplashScreen.h" +#include "KviMainWindow.h" +#include "KviInternalCommand.h" +#include "KviTheme.h" +#include "KviFileUtils.h" +//#include "kvi_textencoding.h" + +#include +#include +#include +#include +#include + +//xml parser +//#include +//!xml parser + +#include + +// KviApplication.cpp +extern KVIRC_API int g_iIdentDaemonRunningUsers; + + +#define RECT_OPTION(_txt,_val,_flags) KviRectOption(KVI_RECT_OPTIONS_PREFIX _txt, _val, _flags) + +KviRectOption g_rectOptionsTable[KVI_NUM_RECT_OPTIONS]= +{ + RECT_OPTION("FrameGeometry",QRect(0,0,10,10),KviOption_sectFlagGeometry), + RECT_OPTION("GeneralOptionsDialogGeometry",QRect(50,50,600,450),KviOption_sectFlagGeometry), + RECT_OPTION("RegisteredUsersDialogGeometry",QRect(50,50,600,450),KviOption_sectFlagGeometry) +}; + +#define BOOL_OPTION(_txt,_val,_flags) KviBoolOption(KVI_BOOL_OPTIONS_PREFIX _txt,_val,_flags) + +KviBoolOption g_boolOptionsTable[KVI_NUM_BOOL_OPTIONS]= +{ + BOOL_OPTION("WindowsRememberProperties",true,KviOption_sectFlagWindows), + BOOL_OPTION("IrcViewShowImages",false,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("IrcViewTimestamp",true,KviOption_sectFlagIrcView), + BOOL_OPTION("IrcViewUrlHighlighting",true,KviOption_sectFlagIrcView | KviOption_groupTheme), + BOOL_OPTION("IrcViewWrapMargin",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("InputHistoryCursorAtEnd",true,KviOption_sectFlagInput), + + BOOL_OPTION("AvoidParserWarnings",false,KviOption_sectFlagUserParser), + BOOL_OPTION("UseProxyHost",false,KviOption_sectFlagConnection), + BOOL_OPTION("ShowGeneralOptionsDialogAsToplevel",true,KviOption_sectFlagFrame), + BOOL_OPTION("ForceBrutalQuit",false,KviOption_sectFlagIrcSocket), + BOOL_OPTION("ShowPingPong",true,KviOption_sectFlagConnection), + BOOL_OPTION("PopupNotifierOnNewQueryMessages",true,KviOption_sectFlagFrame), + BOOL_OPTION("ShowExtendedServerInfo",false,KviOption_sectFlagConnection), + BOOL_OPTION("EchoNumericTopic",true,KviOption_sectFlagConnection), + BOOL_OPTION("ShowOwnParts",true,KviOption_sectFlagConnection), + BOOL_OPTION("UseAntiSpamOnPrivmsg",false,KviOption_sectFlagAntiSpam), + BOOL_OPTION("UseExtendedPrivmsgView",false,KviOption_sectFlagIrcView | KviOption_groupTheme), + BOOL_OPTION("ShowUserAndHostInPrivmsgView",false,KviOption_sectFlagIrcView | KviOption_groupTheme), + BOOL_OPTION("UseWordHighlighting",true,KviOption_sectFlagIrcView), /* _ALL_ newbie users, with who i was taling asks me where can they switch on */ + BOOL_OPTION("UseBigIcons",false,KviOption_sectFlagFrame), /* Almost all users asks me "How to decrease icon size?" */ + BOOL_OPTION("CleanupUnusedModules",true,KviOption_sectFlagModules), + BOOL_OPTION("IgnoreCtcpPing",false,KviOption_sectFlagCtcp), + BOOL_OPTION("IgnoreCtcpVersion",false,KviOption_sectFlagCtcp), + BOOL_OPTION("UseCtcpFloodProtection",true,KviOption_sectFlagCtcp), + BOOL_OPTION("DisableBrokenEventHandlers",true,KviOption_sectFlagUserParser), + BOOL_OPTION("IgnoreCtcpClientinfo",false,KviOption_sectFlagCtcp), + BOOL_OPTION("IgnoreCtcpUserinfo",false,KviOption_sectFlagCtcp), + BOOL_OPTION("IgnoreCtcpFinger",false,KviOption_sectFlagCtcp), + BOOL_OPTION("IgnoreCtcpSource",false,KviOption_sectFlagCtcp), + BOOL_OPTION("IgnoreCtcpTime",false,KviOption_sectFlagCtcp), + BOOL_OPTION("RequestMissingAvatars",true,KviOption_sectFlagAvatar), + BOOL_OPTION("ShowCompactModeChanges",true,KviOption_sectFlagConnection), + BOOL_OPTION("IgnoreCtcpDcc",false,KviOption_sectFlagDcc), + BOOL_OPTION("AutoAcceptDccChat",false,KviOption_sectFlagDcc), + BOOL_OPTION("AutoAcceptDccSend",false,KviOption_sectFlagDcc), + BOOL_OPTION("SendZeroAckInDccRecv",false,KviOption_sectFlagDcc), + BOOL_OPTION("UseFastDccSend",true,KviOption_sectFlagDcc), + BOOL_OPTION("UseCompositingForTransparency",false,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), + BOOL_OPTION("UseWindowListIrcContextIndicator",false,KviOption_sectFlagWindowList | KviOption_resetUpdateGui), + BOOL_OPTION("UseGlobalApplicationFont",false,KviOption_sectFlagGui | KviOption_resetUpdateAppFont | KviOption_groupTheme), + BOOL_OPTION("AlwaysQuitKVIrcClosingLastConsole",false,KviOption_sectFlagFrame), + BOOL_OPTION("AlwaysDisconnectClosingConnectedConsole",false,KviOption_sectFlagFrame), + BOOL_OPTION("FlashWindowOnHighlightedMessages",true,KviOption_sectFlagFrame), + BOOL_OPTION("PopupNotifierOnHighlightedMessages",true,KviOption_sectFlagFrame), + BOOL_OPTION("FlashWindowOnNotifyOnLine",true,KviOption_sectFlagConnection), + BOOL_OPTION("IrcViewTimestampUTC",false,KviOption_sectFlagIrcView), + BOOL_OPTION("UseGlobalPseudoTransparency",false,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), + BOOL_OPTION("UseNotifyList",false,KviOption_sectFlagConnection | KviOption_resetRestartNotifyList), + BOOL_OPTION("NotifyListChangesToActiveWindow",true,KviOption_sectFlagConnection), + BOOL_OPTION("AutoResumeDccSendWhenAutoAccepted",false,KviOption_sectFlagDcc), + BOOL_OPTION("LimitOutgoingTraffic",false,KviOption_sectFlagIrcSocket), + BOOL_OPTION("SendUnknownCommandsAsRaw",true,KviOption_sectFlagUserParser), + BOOL_OPTION("UserListViewDrawGrid",true,KviOption_sectFlagUserListView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("ShowChannelSyncTime",true,KviOption_sectFlagConnection), + BOOL_OPTION("RejoinChannelOnKick",false,KviOption_sectFlagConnection), + BOOL_OPTION("KeepChannelOpenOnKick",true,KviOption_sectFlagConnection), + BOOL_OPTION("AutoCloseDccSendOnSuccess",false,KviOption_sectFlagDcc), + BOOL_OPTION("NotifyDccSendSuccessInConsole",false,KviOption_sectFlagDcc), + BOOL_OPTION("CreateMinimizedDccSend",false,KviOption_sectFlagDcc), + BOOL_OPTION("CreateMinimizedDccChat",false,KviOption_sectFlagDcc), + BOOL_OPTION("AutoAcceptIncomingAvatars",true,KviOption_sectFlagDcc), + BOOL_OPTION("UseNickCompletionPostfixForFirstWordOnly",true,KviOption_sectFlagInput), + BOOL_OPTION("UseWindowListIcons",true,KviOption_sectFlagWindowList | KviOption_resetUpdateGui), + BOOL_OPTION("CreateMinimizedDccSendWhenAutoAccepted",true,KviOption_sectFlagDcc), + BOOL_OPTION("CreateMinimizedDccChatWhenAutoAccepted",true,KviOption_sectFlagDcc), + BOOL_OPTION("DccGuessIpFromServerWhenLocalIsUnroutable",true,KviOption_sectFlagDcc), + BOOL_OPTION("ShowRegisteredUsersDialogAsToplevel",true,KviOption_sectFlagFrame), + BOOL_OPTION("AutoLogQueries",true,KviOption_sectFlagLogging),/* this options enabled by default in mIRC,XChat and irssi. People are confused while they want to see logs, but see empty dir*/ + BOOL_OPTION("AutoLogChannels",true,KviOption_sectFlagLogging), + BOOL_OPTION("AutoLogDccChat",false,KviOption_sectFlagLogging), + BOOL_OPTION("AutoLogConsole",false,KviOption_sectFlagLogging), + BOOL_OPTION("SilentAntiSpam",false,KviOption_sectFlagAntiSpam), + BOOL_OPTION("UseIncomingDccMediaTypeSavePath",true,KviOption_sectFlagDcc), + BOOL_OPTION("NotifyListSendUserhostForOnlineUsers",true,KviOption_sectFlagConnection), + BOOL_OPTION("UseIntelligentNotifyListManager",true,KviOption_sectFlagConnection | KviOption_resetRestartNotifyList), + BOOL_OPTION("UseWatchListIfAvailable",true,KviOption_sectFlagConnection), + BOOL_OPTION("UseTreeWindowList",true,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList | KviOption_groupTheme), + BOOL_OPTION("BindIrcIPv4ConnectionsToSpecifiedAddress",false,KviOption_sectFlagConnection), + BOOL_OPTION("BindIrcIPv6ConnectionsToSpecifiedAddress",false,KviOption_sectFlagConnection), + BOOL_OPTION("UseAntiSpamOnNotice",false,KviOption_sectFlagAntiSpam), + BOOL_OPTION("SetLastAvatarAsDefaultForRegisteredUsers",true,KviOption_sectFlagAvatar), + BOOL_OPTION("CantAcceptIncomingDccConnections",false,KviOption_sectFlagDcc), + BOOL_OPTION("IgnoreCtcpAvatar",false,KviOption_sectFlagCtcp), + BOOL_OPTION("CtcpRepliesToActiveWindow",true,KviOption_sectFlagCtcp), + BOOL_OPTION("AutoAcceptDccCanvas",false,KviOption_sectFlagDcc), + BOOL_OPTION("NotifyDccSendSuccessInNotifier",true,KviOption_sectFlagDcc), + BOOL_OPTION("KillBrokenTimers",true,KviOption_sectFlagUserParser), + BOOL_OPTION("DccVoiceVolumeSliderControlsPCM", true, KviOption_sectFlagDcc), + BOOL_OPTION("DccVoiceForceHalfDuplex", false, KviOption_sectFlagDcc), + BOOL_OPTION("AutoAcceptDccVoice", false, KviOption_sectFlagDcc), + BOOL_OPTION("CreateMinimizedDccVoice", false, KviOption_sectFlagDcc), + BOOL_OPTION("CreateMinimizedDccVoiceWhenAutoAccepted",true,KviOption_sectFlagDcc), +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + BOOL_OPTION("UseIdentService",true,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), +#else + BOOL_OPTION("UseIdentService",false,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), +#endif + BOOL_OPTION("ShowTipAtStartup",false,KviOption_sectFlagFrame), + BOOL_OPTION("IdentdEnableIPv6",false,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + BOOL_OPTION("IdentdIPv6ContainsIPv4",false,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), +#else + BOOL_OPTION("IdentdIPv6ContainsIPv4",true,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), +#endif + BOOL_OPTION("ScaleAvatars",true,KviOption_sectFlagAvatar | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("ColorNicks",false,KviOption_sectFlagIrcView | KviOption_groupTheme), + BOOL_OPTION("BoldedNicks",true,KviOption_sectFlagIrcView | KviOption_groupTheme), + BOOL_OPTION("DccListenOnSpecifiedInterfaceByDefault",false,KviOption_sectFlagDcc), + BOOL_OPTION("ChangeNickAway", false, KviOption_sectFlagConnection), + BOOL_OPTION("AutoGeneratedAwayNick",false,KviOption_sectFlagConnection), /* only ircnet uses 9-symbol nicks */ + BOOL_OPTION("ExitAwayOnInput",false,KviOption_sectFlagConnection), + BOOL_OPTION("AlwaysHighlightNick",true,KviOption_sectFlagIrcView), + BOOL_OPTION("ShowChannelsJoinOnIrc",true,KviOption_sectFlagFrame), + BOOL_OPTION("ShowChannelsJoinDialogAsToplevel",true,KviOption_sectFlagFrame), + BOOL_OPTION("UserDefinedPortRange",false,KviOption_sectFlagDcc), + BOOL_OPTION("CreateQueryOnPrivmsg",true,KviOption_sectFlagConnection), + BOOL_OPTION("CreateQueryOnNotice",false,KviOption_sectFlagConnection), + BOOL_OPTION("CreateMinimizedQuery",true,KviOption_sectFlagConnection), + BOOL_OPTION("AutoJoinOnInvite",false,KviOption_sectFlagConnection), + BOOL_OPTION("ShowServersConnectDialogOnStart",true, KviOption_sectFlagFrame), + BOOL_OPTION("ShowServersConnectDialogAsToplevel",true,KviOption_sectFlagFrame), + BOOL_OPTION("AcceptBrokenFileNameDccResumeRequests",true,KviOption_sectFlagDcc), + BOOL_OPTION("AutoReconnectOnUnexpectedDisconnect",true,KviOption_sectFlagFrame), + BOOL_OPTION("RejoinChannelsAfterReconnect",true,KviOption_sectFlagFrame), + BOOL_OPTION("ReopenQueriesAfterReconnect",true,KviOption_sectFlagFrame), + BOOL_OPTION("EnableQueryTracing",true,KviOption_sectFlagConnection), + BOOL_OPTION("OperatorMessagesToActiveWindow",false,KviOption_sectFlagConnection), + BOOL_OPTION("InviteToActiveWindow",true,KviOption_sectFlagConnection), + BOOL_OPTION("ShowChannelUserFlagInPrivmsgView",true,KviOption_sectFlagConnection), + BOOL_OPTION("DccSendFakeAddressByDefault",false,KviOption_sectFlagDcc), + BOOL_OPTION("UseWindowListActivityMeter",false,KviOption_sectFlagWindowList | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("CloseServerWidgetAfterConnect",false,KviOption_sectFlagFrame), + BOOL_OPTION("ShowIdentityDialogAsToplevel",true,KviOption_sectFlagFrame), + BOOL_OPTION("ShowUserChannelIcons",true,KviOption_sectFlagUserListView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("ShowUserChannelState",false,KviOption_sectFlagUserListView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("EnableIgnoreOnPrivMsg",true,KviOption_sectFlagConnection), + BOOL_OPTION("VerboseIgnore",false,KviOption_sectFlagConnection), + BOOL_OPTION("EnableIgnoreOnNotice",true,KviOption_sectFlagConnection), + BOOL_OPTION("NotifyFailedDccHandshakes",true,KviOption_sectFlagDcc), + BOOL_OPTION("AutoTileWindows",false,KviOption_sectFlagMdi), + BOOL_OPTION("DrawEmoticons",true,KviOption_sectFlagIrcView | KviOption_groupTheme), + BOOL_OPTION("IgnoreCtcpPage",false,KviOption_sectFlagCtcp), + BOOL_OPTION("ShowDialogOnCtcpPage",true,KviOption_sectFlagCtcp), + BOOL_OPTION("BashLikeNickCompletion",false,KviOption_sectFlagInput), + BOOL_OPTION("UseSSLCertificate",false,KviOption_sectFlagConnection), + BOOL_OPTION("UseSSLPrivateKey",false,KviOption_sectFlagConnection), + BOOL_OPTION("WarnAboutPastingMultipleLines",true,KviOption_sectFlagFrame), + BOOL_OPTION("KeepChannelsOpenOnUnexpectedDisconnect",true,KviOption_sectFlagFrame), + BOOL_OPTION("KeepQueriesOpenOnUnexpectedDisconnect",true,KviOption_sectFlagFrame), + BOOL_OPTION("UseLagMeterEngine",true,KviOption_sectFlagConnection | KviOption_resetRestartLagMeter), + BOOL_OPTION("ShowLagOnContextDisplay",true,KviOption_sectFlagFrame), + BOOL_OPTION("DisableBanListRequestOnJoin",false,KviOption_sectFlagConnection), + BOOL_OPTION("DisableBanExceptionListRequestOnJoin",true,KviOption_sectFlagConnection), + BOOL_OPTION("DisableInviteListRequestOnJoin",true,KviOption_sectFlagConnection), + BOOL_OPTION("DisableWhoRequestOnJoin",false,KviOption_sectFlagConnection), + BOOL_OPTION("ShowDockExtension",true,KviOption_sectFlagFrame), + BOOL_OPTION("DccAddressByIrcDns",false,KviOption_sectFlagFrame), + BOOL_OPTION("MinimizeConsoleAfterConnect",false,KviOption_sectFlagFrame), + BOOL_OPTION("HighlightOnlyNormalMsg",false,KviOption_sectFlagFrame), + BOOL_OPTION("HighlightOnlyNormalMsgQueryToo",false,KviOption_sectFlagFrame), + BOOL_OPTION("HighlightOnlyNormalMsgNickinChanToo",false,KviOption_sectFlagFrame), + BOOL_OPTION("HighlightOnlyAtCustomHighlightLevel",false,KviOption_sectFlagFrame), + BOOL_OPTION("MdiManagerInSdiMode",true,KviOption_sectFlagFrame), + BOOL_OPTION("DccBrokenBouncerHack",false,KviOption_sectFlagDcc), + BOOL_OPTION("ExternalMessagesToActiveWindow",true,KviOption_sectFlagConnection), + BOOL_OPTION("IgnoreChannelAvatarRequestsWhenNoAvatarSet",true,KviOption_sectFlagAvatar), + BOOL_OPTION("FlashQueryWindowOnNewMessages",true,KviOption_sectFlagFrame), + BOOL_OPTION("ConfirmCloseWhenThereAreConnections",true,KviOption_sectFlagFrame), + BOOL_OPTION("UseWindowsDesktopForTransparency",false,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), + BOOL_OPTION("CtcpRequestsToActiveWindow",false,KviOption_sectFlagConnection), + BOOL_OPTION("ServerRepliesToActiveWindow",true,KviOption_sectFlagConnection), + BOOL_OPTION("ServerNoticesToActiveWindow",false,KviOption_sectFlagConnection), + BOOL_OPTION("ServicesNoticesToActiveWindow",false,KviOption_sectFlagConnection), + BOOL_OPTION("SortWindowListItemsByName",true,KviOption_sectFlagConnection), + BOOL_OPTION("ShowWindowListToolTips",true,KviOption_sectFlagConnection), + BOOL_OPTION("ShowUserListViewToolTips",true,KviOption_sectFlagConnection), + BOOL_OPTION("WhoisRepliesToActiveWindow",true,KviOption_sectFlagConnection), + BOOL_OPTION("PopupNotifierOnNotifyOnLine",true,KviOption_sectFlagConnection), + BOOL_OPTION("EnableNotifier",true,KviOption_sectFlagConnection), + BOOL_OPTION("DccSendForceIdleStep",false,KviOption_sectFlagDcc), + BOOL_OPTION("StatusBarVisible",true,KviOption_sectFlagFrame), + BOOL_OPTION("TrackLastReadTextViewLine",true,KviOption_sectFlagFrame), + BOOL_OPTION("KeepChannelOpenOnPart",false,KviOption_sectFlagFrame), + BOOL_OPTION("StripMircColorsInUserMessages",false,KviOption_sectFlagFrame | KviOption_groupTheme), + BOOL_OPTION("DoNotSuggestRestoreDefaultScript",false,KviOption_sectFlagFrame), + BOOL_OPTION("LimitDccSendSpeed",false,KviOption_sectFlagDcc), + BOOL_OPTION("LimitDccRecvSpeed",false,KviOption_sectFlagDcc), + BOOL_OPTION("IgnoreModuleVersions",false,KviOption_sectFlagFrame), + BOOL_OPTION("EnableInputHistory",true,KviOption_sectFlagInput | KviOption_resetUpdateGui), + BOOL_OPTION("UseSpecialColorForTimestamp",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("EnableAwayListUpdates",true,KviOption_sectFlagFrame), + BOOL_OPTION("ShowAvatarsInUserlist",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("ShowUserListStatisticLabel",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("ShowIconsInPopupMenus",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("ScriptErrorsToDebugWindow",false,KviOption_sectFlagFrame), + BOOL_OPTION("ShowMinimizedDebugWindow",true,KviOption_sectFlagFrame), + BOOL_OPTION("ShowExtendedInfoInQueryLabel",true,KviOption_resetUpdateGui), + BOOL_OPTION("UseUserListColorsAsNickColors",true,KviOption_sectFlagIrcView | KviOption_groupTheme), + BOOL_OPTION("GzipLogs",false,KviOption_sectFlagLogging), + BOOL_OPTION("UseFullWordHighlighting",false,KviOption_sectFlagIrcView), + BOOL_OPTION("NotifierFlashing",true,KviOption_sectFlagFrame), + BOOL_OPTION("CommandlineInUserFriendlyModeByDefault",false,KviOption_sectFlagFrame), // this confuses existing users and is not mentioned in the docs where there are commandline examples : we need it to be off by default for now + BOOL_OPTION("EnableVisualEffects",true,KviOption_resetUpdateGui), + BOOL_OPTION("DCCFileTransferReplaceOutgoingSpacesWithUnderscores",true,KviOption_sectFlagDcc), + BOOL_OPTION("DoNotUpscaleAvatars",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui ), + BOOL_OPTION("UseDifferentColorForOwnNick",false,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("CloseInTray",false,KviOption_sectFlagFrame | KviOption_resetUpdateGui), + BOOL_OPTION("StartupMinimized",false,KviOption_sectFlagFrame), + BOOL_OPTION("SortReceivedByDccFilesByNicks",false,KviOption_sectFlagDcc), + BOOL_OPTION("LogChannelHistory",true,KviOption_sectFlagConnection), + BOOL_OPTION("ClassicWindowListSetMaximumButtonWidth",true,KviOption_groupTheme | KviOption_sectFlagGeometry | KviOption_resetUpdateGui), + BOOL_OPTION("KeepChannelsOpenOnDisconnect",true,KviOption_sectFlagFrame), + BOOL_OPTION("KeepQueriesOpenOnDisconnect",true,KviOption_sectFlagFrame), + BOOL_OPTION("HideWindowToolButtons",true,KviOption_sectFlagFrame), + BOOL_OPTION("HideInputToolButtons",true,KviOption_sectFlagFrame), + BOOL_OPTION("StripControlCodesInLogs",false,KviOption_sectFlagLogging), + BOOL_OPTION("EnableTrayIconFlashing",true,KviOption_sectFlagFrame), + BOOL_OPTION("UseFlatClassicWindowListButtons",false,KviOption_sectFlagWindowList | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("StripMsgTypeInLogs",false,KviOption_sectFlagLogging), + BOOL_OPTION("UseLevelBasedTrayNotification",false,KviOption_sectFlagFrame), + BOOL_OPTION("MuteAllSounds",false,KviOption_sectFlagFrame), + BOOL_OPTION("CreateMinimizedChannels",false,KviOption_sectFlagFrame), + BOOL_OPTION("ShowNetworkNameForConsoleWindowListEntry",true,KviOption_sectFlagFrame | KviOption_resetUpdateGui), + BOOL_OPTION("DrawGenderIcons",true,KviOption_sectFlagFrame | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("PrependGenderInfoToRealname",true,KviOption_sectFlagConnection), + BOOL_OPTION("UseIdentServiceOnlyOnConnect",true,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), + BOOL_OPTION("UseSystemUrlHandlers",true,KviOption_sectFlagUrl), + BOOL_OPTION("ScaleAvatarsOnLoad",true,KviOption_sectFlagAvatar), + BOOL_OPTION("NotifierFading",true,KviOption_sectFlagFrame), + BOOL_OPTION("PickRandomIpAddressForRoundRobinServers",true,KviOption_sectFlagConnection), + BOOL_OPTION("PrependAvatarInfoToRealname",true,KviOption_sectFlagConnection), + BOOL_OPTION("EnableAnimatedAvatars",true,KviOption_sectFlagGui | KviOption_resetUpdateGui), + BOOL_OPTION("EnableAnimatedSmiles",true,KviOption_sectFlagGui | KviOption_resetUpdateGui), + BOOL_OPTION("PlaceNickWithNonAlphaCharsAtEnd",true,KviOption_sectFlagGui | KviOption_resetUpdateGui), + BOOL_OPTION("UseStartTlsIfAvailable",true,KviOption_sectFlagConnection), + BOOL_OPTION("PasteLastLogOnChannelJoin",false,KviOption_sectFlagLogging), + BOOL_OPTION("PasteLastLogOnQueryJoin",false,KviOption_sectFlagLogging), + BOOL_OPTION("UseSpecifiedSmartColorForOwnNick",false,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("ZshLikeNickCompletion",false,KviOption_sectFlagInput), + BOOL_OPTION("AutoAcceptDccVideo", false, KviOption_sectFlagDcc), + BOOL_OPTION("CreateMinimizedDccVideo", false, KviOption_sectFlagDcc), + BOOL_OPTION("CreateMinimizedDccVideoWhenAutoAccepted",true,KviOption_sectFlagDcc), + BOOL_OPTION("ShowTreeWindowListHeader",false,KviOption_sectFlagWindowList | KviOption_resetUpdateGui | KviOption_groupTheme), + BOOL_OPTION("FlashDccChatWindowOnNewMessages",true,KviOption_sectFlagFrame), + BOOL_OPTION("PopupNotifierOnNewDccChatMessages",true,KviOption_sectFlagFrame), + BOOL_OPTION("UseAwayMessage",true,KviOption_sectFlagConnection), + BOOL_OPTION("DisableQuietBanListRequestOnJoin",true,KviOption_sectFlagConnection), + BOOL_OPTION("UseSaslIfAvailable",true,KviOption_sectFlagConnection), + BOOL_OPTION("FrameIsMaximized",false,KviOption_sectFlagGeometry), + BOOL_OPTION("PrependNickColorInfoToRealname",true,KviOption_sectFlagConnection), + BOOL_OPTION("DontShowNotifierIfActiveWindowIsFullScreen",true,KviOption_sectFlagFrame), + BOOL_OPTION("WheelScrollsWindowsList",true,KviOption_sectFlagWindowList), + BOOL_OPTION("AcceptMismatchedPortDccResumeRequests",false,KviOption_sectFlagDcc), + BOOL_OPTION("EnableUrlLinkToolTip",true,KviOption_sectFlagGui), + BOOL_OPTION("EnableHostLinkToolTip",true,KviOption_sectFlagGui), + BOOL_OPTION("EnableServerLinkToolTip",true,KviOption_sectFlagGui), + BOOL_OPTION("EnableModeLinkToolTip",true,KviOption_sectFlagGui), + BOOL_OPTION("EnableNickLinkToolTip",true,KviOption_sectFlagGui), + BOOL_OPTION("EnableChannelLinkToolTip",true,KviOption_sectFlagGui), + BOOL_OPTION("EnableEscapeLinkToolTip",true,KviOption_sectFlagGui), + BOOL_OPTION("UseDBusNotifier",false,KviOption_sectFlagConnection) +}; + +#define STRING_OPTION(_txt,_val,_flags) KviStringOption(KVI_STRING_OPTIONS_PREFIX _txt,_val,_flags) + +// FIXME: #warning "Remove the unused string options here!" + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + #define RUN_THE_BROWSER "run \"cmd.exe /c start \\\"\\\" \\\"$0\\\"\"" +#else + #ifdef COMPILE_KDE_SUPPORT + #define RUN_THE_BROWSER "run xdg-open $0" + #else + #ifdef COMPILE_ON_MAC + #define RUN_THE_BROWSER "run open $0" + #else + #define RUN_THE_BROWSER "run xdg-open $0" + #endif + #endif +#endif + +KviStringOption g_stringOptionsTable[KVI_NUM_STRING_OPTIONS]= +{ + STRING_OPTION("UNUSED:FrameCaption","",KviOption_sectFlagFrame), + STRING_OPTION("Nickname1",KVI_DEFAULT_NICKNAME1,KviOption_sectFlagUser), + STRING_OPTION("Nickname2","",KviOption_sectFlagUser), + STRING_OPTION("Nickname3","",KviOption_sectFlagUser), + STRING_OPTION("Nickname4","",KviOption_sectFlagUser), + STRING_OPTION("Username",KVI_DEFAULT_USERNAME,KviOption_sectFlagUser), + STRING_OPTION("Realname",KVI_DEFAULT_REALNAME,KviOption_sectFlagUser), + STRING_OPTION("LocalHostIp","127.0.0.1",KviOption_sectFlagIrcSocket), + STRING_OPTION("PartMessage",KVI_DEFAULT_PART_MESSAGE,KviOption_sectFlagConnection), + STRING_OPTION("QuitMessage",KVI_DEFAULT_QUIT_MESSAGE,KviOption_sectFlagConnection), + STRING_OPTION("UrlHttpCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), + STRING_OPTION("ExtendedPrivmsgPrefix","[",KviOption_sectFlagIrcView | KviOption_groupTheme), + STRING_OPTION("ExtendedPrivmsgPostfix","] ",KviOption_sectFlagIrcView | KviOption_groupTheme), + STRING_OPTION("CtcpVersionPostfix","",KviOption_sectFlagCtcp), + STRING_OPTION("CtcpUserInfoOther",KVI_DEFAULT_CTCP_USERINFO_REPLY,KviOption_sectFlagUser), + STRING_OPTION("CtcpSourcePostfix","",KviOption_sectFlagCtcp), + STRING_OPTION("UrlFtpCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), + STRING_OPTION("UrlHttpsCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), + STRING_OPTION("UrlMailtoCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), + STRING_OPTION("PreferredMediaPlayer","auto",KviOption_sectFlagFrame), + STRING_OPTION("UrlFileCommand","play $0",KviOption_sectFlagUrl), + STRING_OPTION("NickCompletionPostfix",": ",KviOption_sectFlagInput), + STRING_OPTION("UrlUnknownCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), + STRING_OPTION("IPv4ConnectionBindAddress","",KviOption_sectFlagConnection), + STRING_OPTION("IPv6ConnectionBindAddress","",KviOption_sectFlagConnection), + STRING_OPTION("DccVoiceSoundDevice", "/dev/dsp",KviOption_sectFlagDcc), + STRING_OPTION("DccVoiceMixerDevice", "/dev/mixer",KviOption_sectFlagDcc), + STRING_OPTION("AwayMessage",KVI_DEFAULT_AWAY_MESSAGE,KviOption_sectFlagConnection), + STRING_OPTION("IdentdUser","kvirc",KviOption_sectFlagConnection | KviOption_resetRestartIdentd), + STRING_OPTION("DccListenDefaultInterface","ppp0",KviOption_sectFlagDcc), + STRING_OPTION("CustomAwayNick", KVI_DEFAULT_AWAY_NICK,KviOption_sectFlagConnection), + STRING_OPTION("DefaultDccFakeAddress","",KviOption_sectFlagDcc), + STRING_OPTION("CtcpPageReply",KVI_DEFAULT_CTCP_PAGE_REPLY,KviOption_sectFlagCtcp), + STRING_OPTION("SSLCertificatePath","",KviOption_sectFlagConnection | KviOption_encodePath), + STRING_OPTION("SSLCertificatePass","",KviOption_sectFlagConnection), + STRING_OPTION("SSLPrivateKeyPath","",KviOption_sectFlagConnection | KviOption_encodePath), + STRING_OPTION("SSLPrivateKeyPass","",KviOption_sectFlagConnection), + STRING_OPTION("SoundSystem","unknown",KviOption_sectFlagFrame), + STRING_OPTION("DefaultUserMode", "", KviOption_sectFlagUser), + STRING_OPTION("LastImageDialogPath","",KviOption_sectFlagUser | KviOption_encodePath), + STRING_OPTION("IconThemeSubdir","",KviOption_sectFlagUser | KviOption_groupTheme | KviOption_resetReloadImages | KviOption_encodePath), + STRING_OPTION("IncomingPath","",KviOption_sectFlagUser | KviOption_encodePath), + STRING_OPTION("MyAvatar","",KviOption_sectFlagUser), + STRING_OPTION("DefaultTextEncoding","",KviOption_sectFlagFrame), + STRING_OPTION("WinampTextEncoding","",KviOption_sectFlagFrame), + STRING_OPTION("Mp3TagsEncoding","",KviOption_sectFlagFrame), + STRING_OPTION("CtcpUserInfoAge","",KviOption_sectFlagUser), + STRING_OPTION("CtcpUserInfoGender","",KviOption_sectFlagUser), + STRING_OPTION("CtcpUserInfoLocation","",KviOption_sectFlagUser), + STRING_OPTION("CtcpUserInfoLanguages","",KviOption_sectFlagUser), + STRING_OPTION("WordSplitters",",\"';:|.%^~!\\$#()?",KviOption_sectFlagIrcView), + STRING_OPTION("OnNewQueryOpenedSound","",KviOption_sectFlagFrame), + STRING_OPTION("OnHighlightedMessageSound","",KviOption_sectFlagFrame), + STRING_OPTION("OnMeKickedSound","",KviOption_sectFlagFrame), + STRING_OPTION("OnQueryMessageSound","",KviOption_sectFlagFrame), + STRING_OPTION("IrcViewTimestampFormat","[hh:mm:ss]",KviOption_sectFlagIrcView), + STRING_OPTION("PreferredTorrentClient","auto",KviOption_sectFlagFrame), + STRING_OPTION("DefaultSrvEncoding","",KviOption_sectFlagFrame), + STRING_OPTION("LogsPath","",KviOption_sectFlagUser | KviOption_encodePath) +}; + +#define STRINGLIST_OPTION(_txt,_flags) \ + KviStringListOption(KVI_STRINGLIST_OPTIONS_PREFIX _txt,QStringList(),_flags) + +#define STRINGLIST_OPTION_WITHDEFAULT(_txt,_flags,_def) \ + KviStringListOption(KVI_STRINGLIST_OPTIONS_PREFIX _txt,QStringList(_def),_flags) + + +KviStringListOption g_stringlistOptionsTable[KVI_NUM_STRINGLIST_OPTIONS]= +{ + STRINGLIST_OPTION("HighlightWords",KviOption_sectFlagIrcView), + STRINGLIST_OPTION("SpamWords",KviOption_sectFlagAntiSpam), + STRINGLIST_OPTION_WITHDEFAULT("RecentChannels",KviOption_sectFlagRecent,"#kvirc" KVI_RECENT_CHANNELS_SEPARATOR "freenode"), + STRINGLIST_OPTION("RecentServers",KviOption_sectFlagRecent), + STRINGLIST_OPTION("RecentNicknames",KviOption_sectFlagRecent), + STRINGLIST_OPTION("ModuleExtensionToolbars",KviOption_sectFlagFrame), + STRINGLIST_OPTION("ImageSearchPaths",KviOption_sectFlagFrame | KviOption_encodePath), + STRINGLIST_OPTION("RecentIrcUrls",KviOption_sectFlagRecent) +}; + +#define MIRC_COLOR_OPTION(_num,_red,_green,_blue) \ + KviColorOption(KVI_MIRCCOLOR_OPTIONS_PREFIX _num,QColor(_red,_green,_blue), \ + KviOption_sectFlagMircColor | KviOption_resetUpdateGui | KviOption_groupTheme) + +KviColorOption g_mirccolorOptionsTable[KVI_NUM_MIRCCOLOR_OPTIONS]= +{ + MIRC_COLOR_OPTION("0",255,255,255), + MIRC_COLOR_OPTION("1",0,0,0), + MIRC_COLOR_OPTION("2",0,0,140), + MIRC_COLOR_OPTION("3",0,100,0), + MIRC_COLOR_OPTION("4",230,0,0), + MIRC_COLOR_OPTION("5",150,0,0), + MIRC_COLOR_OPTION("6",80,0,80), + MIRC_COLOR_OPTION("7",255,90,0), + MIRC_COLOR_OPTION("8",255,255,0), + MIRC_COLOR_OPTION("9",0,255,0), + MIRC_COLOR_OPTION("10",0,150,180), + MIRC_COLOR_OPTION("11",170,170,255), + MIRC_COLOR_OPTION("12",15,15,255), + MIRC_COLOR_OPTION("13",200,0,200), + MIRC_COLOR_OPTION("14",80,80,80), + MIRC_COLOR_OPTION("15",170,170,170) +}; + +#define COLOR_OPTION(_name,_red,_green,_blue,_flags) \ + KviColorOption(KVI_COLOR_OPTIONS_PREFIX _name, \ + QColor(_red,_green,_blue), \ + _flags | KviOption_resetUpdateGui | KviOption_groupTheme | KviOption_resetUpdatePseudoTransparency) + +KviColorOption g_colorOptionsTable[KVI_NUM_COLOR_OPTIONS]= +{ + COLOR_OPTION("MdiBackground",0,0,0,KviOption_sectFlagMdi), + COLOR_OPTION("WindowListNormalText",0,0,0,KviOption_sectFlagWindowList), + COLOR_OPTION("WindowListMinimizedText",60,60,60,KviOption_sectFlagWindowList), + COLOR_OPTION("WindowListHighlight1Text",0,16,144,KviOption_sectFlagWindowList), + COLOR_OPTION("WindowListHighlight2Text",32,0,255,KviOption_sectFlagWindowList), + COLOR_OPTION("WindowListProgressBar",180,180,180,KviOption_sectFlagWindowList), + COLOR_OPTION("UserListViewAwayForeground",143,143,143,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewOwnForeground",255,255,0,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewIrcOpForeground",200,0,0,KviOption_sectFlagUserListView), + COLOR_OPTION("NotifierBackground",255,255,255,KviOption_sectFlagNotifier), + COLOR_OPTION("NotifierForeground",0,0,0,KviOption_sectFlagNotifier), + COLOR_OPTION("NotifierTitleForeground",255,255,255,KviOption_sectFlagNotifier), + COLOR_OPTION("IrcViewBackground",255,255,255,KviOption_sectFlagIrcView), + COLOR_OPTION("InputBackgroundColor",255,255,255,KviOption_sectFlagInput), + COLOR_OPTION("InputSelectionBackground",0,0,0,KviOption_sectFlagInput), + COLOR_OPTION("InputSelectionForeground",255,255,255,KviOption_sectFlagInput), + COLOR_OPTION("InputCursor",0,0,0,KviOption_sectFlagInput), + COLOR_OPTION("InputControl",200,100,0,KviOption_sectFlagInput), + COLOR_OPTION("InputForeground",0,0,0,KviOption_sectFlagInput), + COLOR_OPTION("UserListViewBackground",255,255,255,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewOpForeground",200,0,0,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewVoiceForeground",0,0,200,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewNormalForeground",0,0,0,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewSelectionBackground",0,0,0,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewSelectionForeground",255,255,255,KviOption_sectFlagUserListView), + COLOR_OPTION("LabelBackground",255,255,255,KviOption_sectFlagLabel), + COLOR_OPTION("LabelForeground",0,0,0,KviOption_sectFlagLabel), + COLOR_OPTION("GlobalTransparencyFade",255,255,255,KviOption_sectFlagGui), + COLOR_OPTION("IrcToolBarAppletBackground",255,255,255,KviOption_sectFlagIrcToolBar), + COLOR_OPTION("IrcToolBarAppletForegroundLowContrast",180,180,180,KviOption_sectFlagIrcToolBar), + COLOR_OPTION("IrcToolBarAppletForegroundMidContrast",110,110,110,KviOption_sectFlagIrcToolBar), + COLOR_OPTION("IrcToolBarAppletForegroundHighContrastInactive1",40,40,40,KviOption_sectFlagIrcToolBar), + COLOR_OPTION("IrcToolBarAppletForegroundHighContrastInactive2",40,40,40,KviOption_sectFlagIrcToolBar), + COLOR_OPTION("IrcToolBarAppletForegroundHighContrastActive1",0,0,0,KviOption_sectFlagIrcToolBar), + COLOR_OPTION("IrcToolBarAppletForegroundHighContrastActive2",0,60,0,KviOption_sectFlagIrcToolBar), + COLOR_OPTION("TreeWindowListBackground",255,255,255,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListActiveBackground",200,200,200,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListForeground",0,0,0,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListActiveForeground",0,0,0,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListHighlight1Foreground",0,16,144,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListHighlight2Foreground",32,0,255,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListProgress",150,150,150,KviOption_sectFlagWindowList), + COLOR_OPTION("UserListViewHalfOpForeground",119,0,178,KviOption_sectFlagUserListView), + COLOR_OPTION("WindowListHighlight3Text",128,20,255,KviOption_sectFlagWindowList), + COLOR_OPTION("WindowListHighlight4Text",220,0,255,KviOption_sectFlagWindowList), + COLOR_OPTION("WindowListHighlight5Text",255,0,0,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListHighlight3Foreground",128,0,255,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListHighlight4Foreground",220,0,255,KviOption_sectFlagWindowList), + COLOR_OPTION("TreeWindowListHighlight5Foreground",255,0,0,KviOption_sectFlagWindowList), + COLOR_OPTION("UserListViewChanAdminForeground",83,54,5,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewUserOpForeground",0,127,178,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewGrid",110,110,110,KviOption_sectFlagUserListView), + COLOR_OPTION("UserListViewChanOwnerForeground",81,87,111,KviOption_sectFlagUserListView), + COLOR_OPTION("IrcViewMarkLine",40,40,40,KviOption_sectFlagIrcView) +}; + + +#define IC_COLOR_OPTION(_num,_red,_green,_blue) \ + KviColorOption( \ + KVI_ICCOLOR_OPTIONS_PREFIX _num, \ + QColor(_red,_green,_blue), \ + KviOption_sectFlagWindowList | KviOption_resetUpdateGui | KviOption_groupTheme) + +KviColorOption g_iccolorOptionsTable[KVI_NUM_ICCOLOR_OPTIONS]= +{ + IC_COLOR_OPTION("0",250,250,0), + IC_COLOR_OPTION("1",0,0,0), + IC_COLOR_OPTION("2",0,0,200), + IC_COLOR_OPTION("3",200,0,0), + IC_COLOR_OPTION("4",255,255,255), + IC_COLOR_OPTION("5",0,150,190), + IC_COLOR_OPTION("6",0,130,0), + IC_COLOR_OPTION("7",150,0,170) +}; + +#define PIXMAP_OPTION(_name,_flags) \ + KviPixmapOption( \ + KVI_PIXMAP_OPTIONS_PREFIX _name, \ + KviPixmap(), \ + _flags | KviOption_resetUpdateGui) + +KviPixmapOption g_pixmapOptionsTable[KVI_NUM_PIXMAP_OPTIONS]= +{ + PIXMAP_OPTION("MdiBackground",KviOption_sectFlagMdi | KviOption_groupTheme), + PIXMAP_OPTION("IrcViewBackground",KviOption_sectFlagIrcView | KviOption_groupTheme), + PIXMAP_OPTION("InputBackground",KviOption_sectFlagInput | KviOption_groupTheme), + PIXMAP_OPTION("UserListViewBackground",KviOption_sectFlagUserListView | KviOption_groupTheme), + PIXMAP_OPTION("LabelBackground",KviOption_sectFlagLabel | KviOption_groupTheme), + PIXMAP_OPTION("MyAvatar",KviOption_sectFlagUser), + PIXMAP_OPTION("IrcToolBarAppletBackground",KviOption_sectFlagIrcToolBar | KviOption_groupTheme), + PIXMAP_OPTION("TreeWindowListBackground",KviOption_sectFlagWindowList | KviOption_groupTheme), + PIXMAP_OPTION("GlobalTransparencyBackground",KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), + PIXMAP_OPTION("NotifierBackground",KviOption_sectFlagNotifier | KviOption_groupTheme) +}; + +//#define INT_OPTION(_name,_value,_flags) +// { +// KVI_INT_OPTIONS_PREFIX _name, +// _value, +// _flags +// } +// +//KviIntOption g_intOptionsTable[KVI_NUM_INT_OPTIONS]= +//{ +// INT_OPTION("IrcViewMaxBufferSize",KVI_IRCVIEW_MAX_LINES,KviOption_sectFlagIrcView), +// INT_OPTION("IrcViewTollTipTimeoutInMsec",1800,KviOption_sectFlagIrcView), +// INT_OPTION("IrcViewToolTipHideTimeoutInMsec",10000,KviOption_sectFlagIrcView) +//}; + +#define UINT_OPTION(_name,_value,_flags) \ + KviUIntOption( \ + KVI_UINT_OPTIONS_PREFIX _name, \ + _value, \ + _flags \ + ) + +KviUIntOption g_uintOptionsTable[KVI_NUM_UINT_OPTIONS]= +{ + UINT_OPTION("IrcSocketTimeout",60,KviOption_sectFlagIrcSocket), + UINT_OPTION("ModuleCleanupTimerInterval",90,KviOption_sectFlagModules), + UINT_OPTION("ModuleCleanupTimeout",180,KviOption_sectFlagModules), + UINT_OPTION("MaxCtcpRequests",5,KviOption_sectFlagCtcp), + UINT_OPTION("CtcpFloodCheckInterval",10,KviOption_sectFlagCtcp), + UINT_OPTION("TotalConnectionTime",0,0), + UINT_OPTION("DccSocketTimeout",360,KviOption_sectFlagDcc), + UINT_OPTION("DccSendIdleStepInMSec",30,KviOption_sectFlagDcc), + UINT_OPTION("DccSendPacketSize",4096,KviOption_sectFlagDcc), + UINT_OPTION("GlobalTransparencyParentFadeFactor",10,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), + UINT_OPTION("GlobalTransparencyChildFadeFactor",50,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), + UINT_OPTION("NotifyListCheckTimeInSecs",180,KviOption_sectFlagConnection), + UINT_OPTION("SocketQueueFlushTimeout",500,KviOption_sectFlagIrcSocket), + UINT_OPTION("OutgoingTrafficLimitUSeconds",2000000,KviOption_sectFlagIrcSocket), + UINT_OPTION("NotifyListIsOnDelayTimeInSecs",6,KviOption_sectFlagConnection), + UINT_OPTION("NotifyListUserhostDelayTimeInSecs",6,KviOption_sectFlagConnection), + UINT_OPTION("TreeWindowListMinimumWidth",24,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), + UINT_OPTION("AvatarOfferTimeoutInSecs",60,KviOption_sectFlagAvatar), + UINT_OPTION("IrcViewMaxBufferSize",1024,KviOption_sectFlagIrcView), + UINT_OPTION("IrcViewToolTipTimeoutInMsec",1200,KviOption_sectFlagIrcView), + UINT_OPTION("IrcViewToolTipHideTimeoutInMsec",12000,KviOption_sectFlagIrcView), + UINT_OPTION("DccVoicePreBufferSize",32000,KviOption_sectFlagDcc), + UINT_OPTION("IdentdPort",113,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), + UINT_OPTION("AvatarScaleWidth",80,KviOption_sectFlagAvatar | KviOption_resetUpdateGui), + UINT_OPTION("AvatarScaleHeight",80,KviOption_sectFlagAvatar | KviOption_resetUpdateGui), + UINT_OPTION("DccMinPort",30000,KviOption_sectFlagDcc), + UINT_OPTION("DccMaxPort",31000,KviOption_sectFlagDcc), + UINT_OPTION("SoundOfferTimeoutInSecs",60,KviOption_sectFlagConnection), + UINT_OPTION("MaximumRequestedAvatarSize",524288,KviOption_sectFlagAvatar), + UINT_OPTION("GlobalWindowOpacityPercent",100,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), + UINT_OPTION("PasteDelay",2000,KviOption_sectFlagInput), + UINT_OPTION("MaxDccSendTransfers",10,KviOption_sectFlagDcc), + UINT_OPTION("MaxDccSlots",64,KviOption_sectFlagDcc), + UINT_OPTION("TileMethod",5,KviOption_sectFlagMdi), + UINT_OPTION("LagMeterHeartbeat",5000,KviOption_sectFlagConnection | KviOption_resetRestartLagMeter), + UINT_OPTION("LagAlarmTime",120000,KviOption_sectFlagConnection), + UINT_OPTION("UNUSED",0,KviOption_sectFlagFrame), + UINT_OPTION("WindowListButtonMinWidth",100,KviOption_sectFlagWindowList), + UINT_OPTION("OutputVerbosityLevel",KVI_VERBOSITY_LEVEL_NORMAL,KviOption_sectFlagFrame), + UINT_OPTION("IrcContextAppletWidth",160,KviOption_sectFlagFrame), + UINT_OPTION("MinHighlightLevel",0,KviOption_uintMinHighlightLevel), + UINT_OPTION("UserListViewGridType",3,KviOption_sectFlagUserListView | KviOption_resetUpdateGui | KviOption_groupTheme), + UINT_OPTION("WindowListMaximumRows",2,KviOption_sectFlagFrame), + UINT_OPTION("MaxAutoReconnectAttempts",15,KviOption_sectFlagFrame), + UINT_OPTION("AutoReconnectDelay",10,KviOption_sectFlagFrame), + UINT_OPTION("MaxDccSendSpeed",0,KviOption_sectFlagFrame), + UINT_OPTION("MaxDccRecvSpeed",0,KviOption_sectFlagFrame), + UINT_OPTION("TimeStampForeground",KVI_DARKGRAY,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + UINT_OPTION("TimeStampBackground",KVI_TRANSPARENT,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + UINT_OPTION("UserExperienceLevel",1,KviOption_sectFlagUser), + UINT_OPTION("ClassicWindowListMaximumButtonWidth",100,KviOption_sectFlagGeometry | KviOption_resetUpdateGui | KviOption_groupTheme), + UINT_OPTION("DefaultBanType",7,KviOption_sectFlagIrcSocket), + UINT_OPTION("IrcViewPixmapAlign",0,KviOption_sectFlagIrcView | KviOption_groupTheme), + UINT_OPTION("UserListPixmapAlign",0,KviOption_sectFlagFrame | KviOption_groupTheme), + UINT_OPTION("ToolBarAppletPixmapAlign",0,KviOption_sectFlagFrame | KviOption_groupTheme), + UINT_OPTION("TreeWindowListPixmapAlign",0,KviOption_sectFlagFrame | KviOption_groupTheme), + UINT_OPTION("InputPixmapAlign",0,KviOption_sectFlagFrame | KviOption_groupTheme), + UINT_OPTION("AutoFlushLogs",30,KviOption_sectFlagFrame), + UINT_OPTION("MinTrayLowLevelMessage",1,KviOption_sectFlagFrame), + UINT_OPTION("MinTrayHighLevelMessage",4,KviOption_sectFlagFrame), + UINT_OPTION("IdentdOutputMode",KviIdentdOutputMode::Quiet,KviOption_sectFlagConnection), + UINT_OPTION("ScaleAvatarsOnLoadHeight",640,KviOption_sectFlagAvatar), + UINT_OPTION("ScaleAvatarsOnLoadWidth",480,KviOption_sectFlagAvatar), + UINT_OPTION("NotifierActiveTransparency",100,KviOption_sectFlagNotifier | KviOption_groupTheme), + UINT_OPTION("NotifierInactiveTransparency",80,KviOption_sectFlagNotifier | KviOption_groupTheme), // this may be cool but it confuses the user + UINT_OPTION("IrcViewMarkerStyle",0,KviOption_sectFlagIrcView | KviOption_groupTheme), + UINT_OPTION("IrcViewMarkerSize",1,KviOption_sectFlagIrcView | KviOption_groupTheme), + UINT_OPTION("UrlMouseClickNum",2,KviOption_sectFlagUrl), + UINT_OPTION("NotifierAutoHideTime",30,KviOption_sectFlagModules), + UINT_OPTION("LinesToPasteOnChannelJoin",10,KviOption_sectFlagLogging), + UINT_OPTION("DaysIntervalToPasteOnChannelJoin",10,KviOption_sectFlagLogging), + UINT_OPTION("LinesToPasteOnQueryJoin",10,KviOption_sectFlagLogging), + UINT_OPTION("DaysIntervalToPasteOnQueryJoin",10,KviOption_sectFlagLogging), + UINT_OPTION("SpacesToExpandTabulationInput",4,KviOption_sectFlagInput), + UINT_OPTION("UserIrcViewOwnForeground",4,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + UINT_OPTION("UserIrcViewOwnBackground",8,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), + UINT_OPTION("NotifierPixmapAlign",0,KviOption_sectFlagNotifier | KviOption_groupTheme), + UINT_OPTION("OutputDatetimeFormat",0,KviOption_sectFlagIrcView), + UINT_OPTION("OnJoinRequestsDelay",1,KviOption_sectFlagConnection), // FIXME: Wouldn't this be nicer in msecs defaulting to 100-200 ? +}; + +#define FONT_OPTION(_name,_face,_size,_flags) \ + KviFontOption( \ + KVI_FONT_OPTIONS_PREFIX _name, \ + QFont(_face,_size), \ + _flags | KviOption_groupTheme \ + ) + +KviFontOption g_fontOptionsTable[KVI_NUM_FONT_OPTIONS]= +{ +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + FONT_OPTION("IrcView","Arial",9,KviOption_sectFlagIrcView | KviOption_resetUpdateGui), + FONT_OPTION("Input","Arial",12,KviOption_sectFlagInput | KviOption_resetUpdateGui), + FONT_OPTION("UserListView","Arial",9,KviOption_sectFlagUserListView | KviOption_resetUpdateGui), + FONT_OPTION("Label","Arial",9,KviOption_sectFlagLabel | KviOption_resetUpdateGui), + FONT_OPTION("Application","Arial",9,KviOption_sectFlagGui | KviOption_resetUpdateAppFont), + FONT_OPTION("IrcToolBarApplet","Arial",9,KviOption_sectFlagIrcToolBar | KviOption_resetUpdateGui), + FONT_OPTION("WindowList","Arial",9,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), + FONT_OPTION("TreeWindowList","Arial",9,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), + FONT_OPTION("Notifier","Arial",9,KviOption_sectFlagNotifier | KviOption_resetUpdateGui), + FONT_OPTION("NotifierTitle","Arial",9,KviOption_sectFlagNotifier | KviOption_resetUpdateGui) +#else + FONT_OPTION("IrcView","Monospace",10,KviOption_sectFlagIrcView | KviOption_resetUpdateGui), + FONT_OPTION("Input","Sans Serif",12,KviOption_sectFlagInput | KviOption_resetUpdateGui), + FONT_OPTION("UserListView","Sans Serif",10,KviOption_sectFlagUserListView | KviOption_resetUpdateGui), + FONT_OPTION("Label","Sans Serif",10,KviOption_sectFlagLabel | KviOption_resetUpdateGui), + FONT_OPTION("Application","Sans Serif",10,KviOption_sectFlagGui | KviOption_resetUpdateAppFont), + FONT_OPTION("IrcToolBarApplet","Sans Serif",10,KviOption_sectFlagIrcToolBar | KviOption_resetUpdateGui), + FONT_OPTION("WindowList","Sans Serif",10,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), + FONT_OPTION("TreeWindowList","Sans Serif",10,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), + FONT_OPTION("Notifier","Sans Serif",9,KviOption_sectFlagNotifier | KviOption_resetUpdateNotifier), + FONT_OPTION("NotifierTitle","Sans Serif",9,KviOption_sectFlagNotifier | KviOption_resetUpdateNotifier) +#endif +}; + +#define MSGTYPE_OPTION(_name,_text,_icon,_levl) \ + KviMessageTypeSettingsOption( \ + KVI_MSGTYPE_OPTIONS_PREFIX _name, \ + KviMessageTypeSettings(_text,_icon,KVI_BLACK,KVI_TRANSPARENT,true,_levl), \ + KviOption_sectFlagMsgType | KviOption_groupTheme \ + ) + +#define MSGTYPE_OPTION_SPEC(_name,_text,_icon,_fore,_back,_levl) \ + KviMessageTypeSettingsOption( \ + KVI_MSGTYPE_OPTIONS_PREFIX _name, \ + KviMessageTypeSettings(_text,_icon,_fore,_back,true,_levl), \ + KviOption_sectFlagMsgType | KviOption_groupTheme \ + ) + + + +// FIXME: #warning "FIX THE ICONS HERE!!!" + +KviMessageTypeSettingsOption g_msgtypeOptionsTable[KVI_NUM_MSGTYPE_OPTIONS]= +{ + MSGTYPE_OPTION("Echo",__tr_no_lookup("Normal text"),KVI_SMALLICON_NONE,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION_SPEC("Selection",__tr_no_lookup("Selection"),KVI_SMALLICON_NONE,KVI_WHITE,KVI_BLACK,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION_SPEC("Highlight",__tr_no_lookup("Highlighted text"),KVI_SMALLICON_ALERT,KVI_WHITE,KVI_BLACK,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION_SPEC("Url",__tr_no_lookup("URL foreground"),KVI_SMALLICON_NONE,KVI_BLUE,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION_SPEC("Link",__tr_no_lookup("Link overlay foreground"),KVI_SMALLICON_NONE,KVI_BLUE,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION_SPEC("ParserError",__tr_no_lookup("Parser error"),KVI_SMALLICON_PARSERERROR,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION_SPEC("ParserWarning",__tr_no_lookup("Parser warning"),KVI_SMALLICON_PARSERWARNING,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("HostLookup",__tr_no_lookup("Host lookup result"),KVI_SMALLICON_SERVER,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("SocketMessage",__tr_no_lookup("Socket message"),KVI_SMALLICON_SOCKETMESSAGE,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("SocketWarning",__tr_no_lookup("Socket warning"),KVI_SMALLICON_SOCKETWARNING,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION_SPEC("SocketError",__tr_no_lookup("Socket error"),KVI_SMALLICON_SOCKETERROR,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION_SPEC("SystemError",__tr_no_lookup("System error"),KVI_SMALLICON_SYSTEMERROR,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("Raw",__tr_no_lookup("Raw data to server"),KVI_SMALLICON_RAW,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Connection",__tr_no_lookup("Connection status"),KVI_SMALLICON_WORLD,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("SystemWarning",__tr_no_lookup("System warning"),KVI_SMALLICON_SYSTEMWARNING,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("SystemMessage",__tr_no_lookup("System message"),KVI_SMALLICON_SYSTEMMESSAGE,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("UnhandledReply",__tr_no_lookup("Unhandled server reply"),KVI_SMALLICON_UNHANDLED,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("ServerInfo",__tr_no_lookup("Server information"),KVI_SMALLICON_SERVERINFO,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Motd",__tr_no_lookup("Server Message of the Day"),KVI_SMALLICON_MOTD,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("ServerPing",__tr_no_lookup("Server ping"),KVI_SMALLICON_SERVERPING,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Join",__tr_no_lookup("Join message"),KVI_SMALLICON_JOIN,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Part",__tr_no_lookup("Part message"),KVI_SMALLICON_PART,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Unrecognized",__tr_no_lookup("Unrecognized/broken message"),KVI_SMALLICON_UNRECOGNIZED,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Topic",__tr_no_lookup("Topic message"),KVI_SMALLICON_TOPIC,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("OwnPrivateMessage",__tr_no_lookup("Own private message"),KVI_SMALLICON_OWNPRIVMSG,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("ChannelPrivateMessage",__tr_no_lookup("Channel private message"),KVI_SMALLICON_CHANPRIVMSG,KVI_MSGTYPE_LEVEL_4), + MSGTYPE_OPTION("QueryPrivateMessage",__tr_no_lookup("Query private message"),KVI_SMALLICON_QUERYPRIVMSG,KVI_MSGTYPE_LEVEL_4), + MSGTYPE_OPTION("CtcpReply",__tr_no_lookup("CTCP reply"),KVI_SMALLICON_CTCPREPLY,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("CtcpRequestReplied",__tr_no_lookup("CTCP request replied"),KVI_SMALLICON_CTCPREQUESTREPLIED,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("CtcpRequestIgnored",__tr_no_lookup("CTCP request ignored"),KVI_SMALLICON_CTCPREQUESTIGNORED,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("CtcpRequestFlood",__tr_no_lookup("CTCP request flood warning"),KVI_SMALLICON_CTCPREQUESTFLOOD,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("CtcpRequestUnknown",__tr_no_lookup("CTCP request unknown"),KVI_SMALLICON_CTCPREQUESTUNKNOWN,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("Action",__tr_no_lookup("User action"),KVI_SMALLICON_ACTION,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("AvatarChange",__tr_no_lookup("Avatar change"),KVI_SMALLICON_AVATAR,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("Quit",__tr_no_lookup("Quit message"),KVI_SMALLICON_QUIT,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Split",__tr_no_lookup("Split message"),KVI_SMALLICON_SPLIT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("QuitSplit",__tr_no_lookup("Quit on netsplit message"),KVI_SMALLICON_QUITSPLIT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Nick",__tr_no_lookup("Nick changes"),KVI_SMALLICON_NICK,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Op",__tr_no_lookup("+o mode change"),KVI_SMALLICON_OP,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Deop",__tr_no_lookup("-o mode change"),KVI_SMALLICON_DEOP,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Voice",__tr_no_lookup("+v mode change"),KVI_SMALLICON_VOICE,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Devoice",__tr_no_lookup("-v mode change"),KVI_SMALLICON_DEVOICE,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Mode",__tr_no_lookup("Multiple user mode change"),KVI_SMALLICON_MODE,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Key",__tr_no_lookup("Channel key change"),KVI_SMALLICON_KEY,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Limit",__tr_no_lookup("Channel limit change"),KVI_SMALLICON_LIMIT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Ban",__tr_no_lookup("+b mode change"),KVI_SMALLICON_BAN,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Unban",__tr_no_lookup("-b mode change"),KVI_SMALLICON_UNBAN,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("BanExcept",__tr_no_lookup("+e mode change"),KVI_SMALLICON_BANEXCEPT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("BanUnexcept",__tr_no_lookup("-e mode change"),KVI_SMALLICON_BANUNEXCEPT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("InviteExcept",__tr_no_lookup("+I mode change"),KVI_SMALLICON_INVITEEXCEPT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("InviteUnexcept",__tr_no_lookup("-I mode change"),KVI_SMALLICON_INVITEUNEXCEPT,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("ChanMode",__tr_no_lookup("Multiple channel mode change"),KVI_SMALLICON_CHANMODE,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Who",__tr_no_lookup("Who reply"),KVI_SMALLICON_WHO,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("DccRequest",__tr_no_lookup("DCC request"),KVI_SMALLICON_DCCREQUEST,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("DccMsg",__tr_no_lookup("DCC message"),KVI_SMALLICON_DCCMSG,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("DccError",__tr_no_lookup("DCC error"),KVI_SMALLICON_DCCERROR,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("NicknameProblem",__tr_no_lookup("Nickname problem"),KVI_SMALLICON_NICKNAMEPROBLEM,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("WhoisUser",__tr_no_lookup("Whois user reply"),KVI_SMALLICON_WHOISUSER,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("WhoisChannels",__tr_no_lookup("Whois channels reply"),KVI_SMALLICON_WHOISCHANNELS,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("WhoisIdle",__tr_no_lookup("Whois idle reply"),KVI_SMALLICON_WHOISIDLE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("WhoisServer",__tr_no_lookup("Whois server reply"),KVI_SMALLICON_WHOISSERVER,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("WhoisOther",__tr_no_lookup("Whois other reply"),KVI_SMALLICON_WHOISOTHER,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("CreationTime",__tr_no_lookup("Channel creation time reply"),KVI_SMALLICON_TIME,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("NotifyOnLine",__tr_no_lookup("Notify list joins"),KVI_SMALLICON_NOTIFYONLINE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("NotifyOffLine",__tr_no_lookup("Notify list leaves"),KVI_SMALLICON_NOTIFYOFFLINE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("OwnPrivmsgCrypted",__tr_no_lookup("Own encrypted private message"),KVI_SMALLICON_OWNPRIVMSGCRYPTED,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("ChanPrivmsgCrypted",__tr_no_lookup("Channel encrypted private message"),KVI_SMALLICON_CHANPRIVMSGCRYPTED,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("QueryPrivmsgCrypted",__tr_no_lookup("Query encrypted private message"),KVI_SMALLICON_QUERYPRIVMSGCRYPTED,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("DccChatMsg",__tr_no_lookup("DCC chat message"),KVI_SMALLICON_DCCCHATMSG,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("DccChatMsgCrypted",__tr_no_lookup("Encrypted DCC chat message"),KVI_SMALLICON_DCCCHATMSGCRYPTED,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("Irc",__tr_no_lookup("Login operations completed"),KVI_SMALLICON_IRC,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Kick",__tr_no_lookup("Kick action"),KVI_SMALLICON_KICK,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Links",__tr_no_lookup("Links reply"),KVI_SMALLICON_LINKS,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Spam",__tr_no_lookup("Spam report"),KVI_SMALLICON_SPAM,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("Icq",__tr_no_lookup("ICQ message"),KVI_SMALLICON_ICQ,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("IcqMessage",__tr_no_lookup("ICQ user-message"),KVI_SMALLICON_MESSAGE,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("IcqMessageSent",__tr_no_lookup("Outgoing ICQ user-message"),KVI_SMALLICON_MESSAGESENT,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("ChannelNotice",__tr_no_lookup("Channel notice"),KVI_SMALLICON_CHANNELNOTICE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("ChannelNoticeCrypted",__tr_no_lookup("Encrypted channel notice"),KVI_SMALLICON_CHANNELNOTICECRYPTED,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("QueryNotice",__tr_no_lookup("Query notice"),KVI_SMALLICON_QUERYNOTICE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("QueryNoticeCrypted",__tr_no_lookup("Encrypted query notice"),KVI_SMALLICON_QUERYNOTICECRYPTED,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("ServerNotice",__tr_no_lookup("Server notice"),KVI_SMALLICON_SERVERNOTICE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("HalfOp",__tr_no_lookup("Halfop mode change"),KVI_SMALLICON_HALFOP,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("CtcpReplyUnknown",__tr_no_lookup("Unknown CTCP reply"),KVI_SMALLICON_CTCPREPLYUNKNOWN,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("NickServ",__tr_no_lookup("NickServ message"),KVI_SMALLICON_NICKSERV,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("ChanServ",__tr_no_lookup("ChanServ message"),KVI_SMALLICON_CHANSERV,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Away",__tr_no_lookup("Away message"),KVI_SMALLICON_AWAY,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("Ident",__tr_no_lookup("Ident message"),KVI_SMALLICON_IDENT,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("List",__tr_no_lookup("Channel list message"),KVI_SMALLICON_LIST,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("HalfDeOp",__tr_no_lookup("Half-deop mode change"),KVI_SMALLICON_HALFDEOP,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("Invite",__tr_no_lookup("Invite message"),KVI_SMALLICON_INVITE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("Multimedia",__tr_no_lookup("Multimedia message"),KVI_SMALLICON_MULTIMEDIA,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("QueryTrace",__tr_no_lookup("Query trace message"),KVI_SMALLICON_QUERYTRACE,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Wallops",__tr_no_lookup("Wallops message"),KVI_SMALLICON_WALLOPS,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("JoinError",__tr_no_lookup("Join error message"),KVI_SMALLICON_NOCHANNEL,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("BroadcastPrivmsg",__tr_no_lookup("Broadcast private message"),KVI_SMALLICON_BROADCASTPRIVMSG,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("BroadcastNotice",__tr_no_lookup("Broadcast notice"),KVI_SMALLICON_BROADCASTNOTICE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("MeKick",__tr_no_lookup("Am kicked"),KVI_SMALLICON_MEKICK,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeOp",__tr_no_lookup("Am op'd"),KVI_SMALLICON_MEOP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeVoice",__tr_no_lookup("Am voiced"),KVI_SMALLICON_MEVOICE,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeDeOp",__tr_no_lookup("Am deop'd"),KVI_SMALLICON_MEDEOP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeDeVoice",__tr_no_lookup("Am devoiced"),KVI_SMALLICON_MEDEVOICE,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeHalfOp",__tr_no_lookup("Am halfop'd"),KVI_SMALLICON_MEHALFOP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeDeHalfOp",__tr_no_lookup("Am de-halfop'd"),KVI_SMALLICON_MEDEHALFOP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeBan",__tr_no_lookup("Ban matching my mask"),KVI_SMALLICON_MEBAN,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeUnban",__tr_no_lookup("Unban matching my mask"),KVI_SMALLICON_MEUNBAN,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeBanExcept",__tr_no_lookup("Ban exception matching my mask"),KVI_SMALLICON_MEBANEXCEPT,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeBanUnExcept",__tr_no_lookup("Ban unexception matching my mask"),KVI_SMALLICON_MEBANUNEXCEPT,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeInviteExcept",__tr_no_lookup("Invite exception matching my mask"),KVI_SMALLICON_MEINVITEEXCEPT,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeInviteUnexcept",__tr_no_lookup("Invite unexception matching my mask"),KVI_SMALLICON_MEINVITEUNEXCEPT,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("Ignore",__tr_no_lookup("Ignored user message"),KVI_SMALLICON_IGNORE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("Stats",__tr_no_lookup("Server statistics"),KVI_SMALLICON_STATS,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("SSL",__tr_no_lookup("SSL message"),KVI_SMALLICON_SSL,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("Search",__tr_no_lookup("Search"),KVI_SMALLICON_SEARCH,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("GenericSuccess",__tr_no_lookup("Generic success"),KVI_SMALLICON_CYANSQUARE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION("GenericStatus",__tr_no_lookup("Generic status"),KVI_SMALLICON_GREENSQUARE,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("GenericVerbose",__tr_no_lookup("Generic verbose message"),KVI_SMALLICON_DKGREENSQUARE,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("GenericWarning",__tr_no_lookup("Generic warning"),KVI_SMALLICON_YELLOWSQUARE,KVI_MSGTYPE_LEVEL_3), + MSGTYPE_OPTION_SPEC("GenericError",__tr_no_lookup("Generic error"),KVI_SMALLICON_REDSQUARE,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION_SPEC("GenericCritical",__tr_no_lookup("Generic critical error"),KVI_SMALLICON_BLACKSQUARE,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("ChanAdmin",__tr_no_lookup("Chan admin status set"),KVI_SMALLICON_CHANADMIN,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("ChanUnAdmin",__tr_no_lookup("Chan admin status unset"),KVI_SMALLICON_CHANUNADMIN,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeChanAdmin",__tr_no_lookup("Own chan admin status set"),KVI_SMALLICON_MECHANADMIN,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeChanUnAdmin",__tr_no_lookup("Own chan admin status unset"),KVI_SMALLICON_MECHANUNADMIN,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("UserOp",__tr_no_lookup("Userop mode change"),KVI_SMALLICON_USEROP,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("UserDeOp",__tr_no_lookup("User-deop mode change"),KVI_SMALLICON_DEUSEROP,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("MeUserOp",__tr_no_lookup("Am userop'd"),KVI_SMALLICON_MEUSEROP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeDeUserOp",__tr_no_lookup("Am de-userop'd"),KVI_SMALLICON_MEDEUSEROP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION_SPEC("Verbose",__tr_no_lookup("Verbose/Debug"),KVI_SMALLICON_BINARYTEXT,KVI_DARKGRAY,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("ChanOwner",__tr_no_lookup("Chan owner status set"),KVI_SMALLICON_CHANOWNER,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("ChanUnOwner",__tr_no_lookup("Chan owner status unset"),KVI_SMALLICON_CHANUNOWNER,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeChanOwner",__tr_no_lookup("Own chan owner status set"),KVI_SMALLICON_MECHANOWNER,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeChanUnOwner",__tr_no_lookup("Own chan owner status unset"),KVI_SMALLICON_MECHANUNOWNER,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION_SPEC("ServerError",__tr_no_lookup("Server error"),KVI_SMALLICON_SERVERERROR,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION_SPEC("Help",__tr_no_lookup("Help"),KVI_SMALLICON_HELP,KVI_DARKGREEN,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_1), + MSGTYPE_OPTION("TextEncoding",__tr_no_lookup("Text Encoding Server message"),KVI_SMALLICON_TEXTENCODING,KVI_MSGTYPE_LEVEL_1), + // TODO: add icon and check what level means + // Pragma: the message level is a warning level that is rendered in the WindowList + // messages with higher level are rendered with more visible color (i.e. red) + // messages with very high level might flash the tray and end up in the notifier + // level 1 or 2 for standard torrent messages is ok + MSGTYPE_OPTION("BitTorrent",__tr_no_lookup("BitTorrent message"),KVI_SMALLICON_MULTIMEDIA,KVI_MSGTYPE_LEVEL_2), + MSGTYPE_OPTION("IrcOp",__tr_no_lookup("IRC Op status set"),KVI_SMALLICON_IRCOP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("DeIrcOp",__tr_no_lookup("IRC Op status unset"),KVI_SMALLICON_DEIRCOP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeIrcOp",__tr_no_lookup("Own IRC Op status set"),KVI_SMALLICON_MEIRCOP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("MeDeIrcOp",__tr_no_lookup("Own IRC Op status unset"),KVI_SMALLICON_MEDEIRCOP,KVI_MSGTYPE_LEVEL_5), + MSGTYPE_OPTION("Cap",__tr_no_lookup("Extended capability message"),KVI_SMALLICON_SERVERINFO,KVI_MSGTYPE_LEVEL_1) +}; + +static const char * options_section_table[KVI_NUM_OPTION_SECT_FLAGS] = +{ + "None", "Frame", "Mdi", "Windows", + "WindowList", "IrcView", "MsgType", "MircColor", + "Input", "UserParser", "Connection", "IrcSocket", + "User", "UserListView","Label", "Modules", + "Ctcp", "Dcc", "Gui", "IrcToolBar", + "Logging", "AntiSpam", "Avatar", "Url", + "Recent", "Geometry" +}; + +static void config_set_section(int flag,KviConfigurationFile * cfg) +{ + int index = flag & KviOption_sectMask; + if((index < KVI_NUM_OPTION_SECT_FLAGS) && (index >= 0)) + { + cfg->setGroup(options_section_table[index]); + } else cfg->setGroup(""); // Default group +} + +void KviApplication::loadOptions() +{ + QString buffer; + if(getReadOnlyConfigPath(buffer,KVI_CONFIGFILE_MAIN)) + { + KviConfigurationFile cfg(buffer,KviConfigurationFile::Read); + + int prg = 12; + int i; + + #define READ_OPTIONS(_num,_table,_readFnc) \ + for(i=0;i<_num;i++) \ + { \ + config_set_section(_table[i].flags,&cfg); \ + _table[i].option = cfg._readFnc(_table[i].name,_table[i].option); \ + } \ + prg += 3; \ + KVI_SPLASH_SET_PROGRESS(prg) + + READ_OPTIONS(KVI_NUM_RECT_OPTIONS,g_rectOptionsTable,readRectEntry) + READ_OPTIONS(KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable,readBoolEntry) + READ_OPTIONS(KVI_NUM_STRING_OPTIONS,g_stringOptionsTable,readEntry) + READ_OPTIONS(KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable,readColorEntry) + READ_OPTIONS(KVI_NUM_PIXMAP_OPTIONS,g_pixmapOptionsTable,readPixmapEntry) + READ_OPTIONS(KVI_NUM_UINT_OPTIONS,g_uintOptionsTable,readUIntEntry) + READ_OPTIONS(KVI_NUM_FONT_OPTIONS,g_fontOptionsTable,readFontEntry) + READ_OPTIONS(KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable,readMsgTypeEntry) + READ_OPTIONS(KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable,readStringListEntry) + READ_OPTIONS(KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable,readColorEntry) + READ_OPTIONS(KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable,readColorEntry) + + for(i=0;isave(szPixPath,"PNG")) + { + cfg.writeEntry(g_pixmapOptionsTable[i].name,szPixName); + } else { + // we ignore this error for now + qDebug("failed to save %s",szPixPath.toUtf8().data()); + cfg.writeEntry(g_pixmapOptionsTable[i].name,""); + } + } else { + cfg.writeEntry(g_pixmapOptionsTable[i].name,""); + } + } + } + + cfg.writeEntry("stringIconThemeSubdir",options.subdirectory()); + + // find all the "kvi_bigicon" images that we can find in the main pics directory + QString szPicsPath; + + g_pApp->getGlobalKvircDirectory(szPicsPath,KviApplication::Pics); + QDir d(szPicsPath); + QStringList sl = d.entryList(QDir::nameFiltersFromString("kvi_bigicon_*.png"),QDir::Files); + + for(QStringList::Iterator it=sl.begin();it != sl.end();it++) + { + KviCachedPixmap * p = g_pIconManager->getPixmapWithCache(*it); + if(p) + { + QString szPixPath = options.absoluteDirectory(); + szPixPath.append(KVI_PATH_SEPARATOR_CHAR); + szPixPath += *it; + + if(!KviFileUtils::copyFile(p->path(),szPixPath)) + { + options.setLastError(__tr2qs("Failed to save one of the theme images")); + return false; + } + } + } + + + szD = options.absoluteDirectory(); + szD.append(KVI_PATH_SEPARATOR_CHAR); + szD.append(KVI_SMALLICONS_SUBDIRECTORY); + + if(!KviFileUtils::makeDir(szD)) + { + options.setLastError(__tr2qs("Failed to create the theme subdirectory")); + return false; + } + + // We actually need to *save* the small icons since + // we have a compatibility mode that can load them from + // the old format kvi_smallicon_XY.png multiimage libraries. + + for(int j=0;jgetSmallIcon(j); + + QString szPixPath = options.absoluteDirectory(); + szPixPath.append(KVI_PATH_SEPARATOR_CHAR); + szPixPath.append(KVI_SMALLICONS_SUBDIRECTORY); + szPixPath.append(KVI_PATH_SEPARATOR_CHAR); + szPixPath.append("kcs_"); + szPixPath.append(g_pIconManager->getSmallIconName(j)); + szPixPath.append(".png"); + + if(!pix->save(szPixPath,"PNG",90)) + { + options.setLastError(__tr2qs("Failed to save one of the theme images")); + return false; + } + } + + return true; + } + + bool load(const QString &themeDir,KviThemeInfo &buffer) + { + if(!buffer.loadFromDirectory(themeDir)) + return false; // makes sure that themedata exists too + + // reset the current theme subdir + KVI_OPTION_STRING(KviOption_stringIconThemeSubdir) = ""; + + // reset the splash screen pointer + QString szPointerFile; + g_pApp->getLocalKvircDirectory(szPointerFile,KviApplication::Themes,"current-splash"); + KviFileUtils::removeFile(szPointerFile); + + QString szD = themeDir; + KviQString::ensureLastCharIs(szD,KVI_PATH_SEPARATOR_CHAR); + szD.append(KVI_THEMEDATA_FILE_NAME); + + KviConfigurationFile cfg(szD,KviConfigurationFile::Read); + + cfg.setGroup(KVI_THEMEDATA_CONFIG_GROUP); + + int i; + int iResetFlags = 0; + + #undef READ_OPTIONS + + #define READ_OPTIONS(_num,_table,_readFnc) \ + for(i=0;i<_num;i++) \ + { \ + if(_table[i].flags & KviOption_groupTheme) \ + { \ + if(cfg.hasKey(_table[i].name)) \ + { \ + iResetFlags |= (_table[i].flags & KviOption_resetMask); \ + _table[i].option = cfg._readFnc(_table[i].name,_table[i].option); \ + } \ + } \ + } + + #define READ_ALL_OPTIONS(_num,_table,_readFnc) \ + for(i=0;i<_num;i++) \ + { \ + if(cfg.hasKey(_table[i].name)) \ + { \ + iResetFlags |= (_table[i].flags & KviOption_resetMask); \ + _table[i].option = cfg._readFnc(_table[i].name,_table[i].option); \ + } \ + } + + READ_OPTIONS(KVI_NUM_RECT_OPTIONS,g_rectOptionsTable,readRectEntry) + READ_OPTIONS(KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable,readBoolEntry) + READ_OPTIONS(KVI_NUM_STRING_OPTIONS,g_stringOptionsTable,readEntry) + READ_OPTIONS(KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable,readColorEntry) + READ_OPTIONS(KVI_NUM_UINT_OPTIONS,g_uintOptionsTable,readUIntEntry) + READ_OPTIONS(KVI_NUM_FONT_OPTIONS,g_fontOptionsTable,readFontEntry) + READ_ALL_OPTIONS(KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable,readMsgTypeEntry) + READ_OPTIONS(KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable,readStringListEntry) + READ_OPTIONS(KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable,readColorEntry) + READ_OPTIONS(KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable,readColorEntry) + + #undef READ_OPTIONS + #undef READ_ALL_OPTIONS + KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).trimmed(); + + + // the pixmap options need special processing + for(i=0;ifindImage(szBuffer,szVal); + } else { + szBuffer = szVal; + } + + KviStringConversion::fromString(szBuffer,g_pixmapOptionsTable[i].option); + + // reset anyway + iResetFlags |= g_pixmapOptionsTable[i].flags & KviOption_resetMask; + } + } + } + + // create the splash screen pointer if this theme has some pixmaps in it + if(!KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).isEmpty()) + KviFileUtils::writeFile(szPointerFile,KVI_OPTION_STRING(KviOption_stringIconThemeSubdir)); + + // force reloading of images anyway + g_pApp->optionResetUpdate(iResetFlags | KviOption_resetReloadImages); + + return true; + } +}; + +void KviApplication::listAvailableOptions(KviWindow *wnd) +{ + int i; + + #define LIST_OPTIONS(__txt,__num,__table) \ + wnd->output(KVI_OUT_SYSTEMMESSAGE,"%c%s%c",KVI_TEXT_BOLD,__txt,KVI_TEXT_BOLD); \ + for(i = 0;i < __num;i++)wnd->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__table[i].name); + + LIST_OPTIONS(__tr("Boolean options (1/0)"),KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable) + LIST_OPTIONS(__tr("Rectangle options (x,y,width,height)"),KVI_NUM_RECT_OPTIONS,g_rectOptionsTable) + LIST_OPTIONS(__tr("String options (string value)"),KVI_NUM_STRING_OPTIONS,g_stringOptionsTable) + LIST_OPTIONS(__tr("Color options (#RRGGBB)"),KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable) + LIST_OPTIONS(__tr("Mirccolor options (#RRGGBB)"),KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable) + LIST_OPTIONS(__tr("Irc context color options (#RRGGBB)"),KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable) + LIST_OPTIONS(__tr("Pixmap options (image path)"),KVI_NUM_PIXMAP_OPTIONS,g_pixmapOptionsTable) + LIST_OPTIONS(__tr("Unsigned integer options (unsigned integer constant)"),KVI_NUM_UINT_OPTIONS,g_uintOptionsTable) + LIST_OPTIONS(__tr("Font options (family,pointsize,style,charset,weight,flags (biusf))"),KVI_NUM_FONT_OPTIONS,g_fontOptionsTable) + LIST_OPTIONS(__tr("Message color options (image_id,foreground,background,logFlag (0/1))"),KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable) + LIST_OPTIONS(__tr("String list options (comma separated list of strings)"),KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable) + + #undef LIST_OPTIONS +} + +//using namespace KviStringConversion; +bool KviApplication::getOptionString(const QString &optName,QString &buffer) +{ + + #define GET_OPTION_STRING(__numOpt,__table,__prefix,__prefixLen) \ + if(KviQString::equalCIN(optName,__prefix,__prefixLen)) \ + { \ + for(int i=0;i < __numOpt;i++) \ + { \ + if(KviQString::equalCI(optName,__table[i].name)) \ + { \ + KviStringConversion::toString(__table[i].option,buffer); \ + return true; \ + } \ + } \ + return false; \ + } + + // WARNING : stringlist prefix must go BEFORE the string prefix (otherwise it will match) + + GET_OPTION_STRING(KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable,KVI_BOOL_OPTIONS_PREFIX,KVI_BOOL_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_RECT_OPTIONS,g_rectOptionsTable,KVI_BOOL_OPTIONS_PREFIX,KVI_BOOL_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable,KVI_STRINGLIST_OPTIONS_PREFIX,KVI_STRINGLIST_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_STRING_OPTIONS,g_stringOptionsTable,KVI_STRING_OPTIONS_PREFIX,KVI_STRING_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable,KVI_COLOR_OPTIONS_PREFIX,KVI_COLOR_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable,KVI_MIRCCOLOR_OPTIONS_PREFIX,KVI_MIRCCOLOR_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable,KVI_ICCOLOR_OPTIONS_PREFIX,KVI_ICCOLOR_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_PIXMAP_OPTIONS,g_pixmapOptionsTable,KVI_PIXMAP_OPTIONS_PREFIX,KVI_PIXMAP_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_UINT_OPTIONS,g_uintOptionsTable,KVI_UINT_OPTIONS_PREFIX,KVI_UINT_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_FONT_OPTIONS,g_fontOptionsTable,KVI_FONT_OPTIONS_PREFIX,KVI_FONT_OPTIONS_PREFIX_LEN) + GET_OPTION_STRING(KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable,KVI_MSGTYPE_OPTIONS_PREFIX,KVI_MSGTYPE_OPTIONS_PREFIX_LEN) + return false; + + #undef GET_OPTION_STRING +} + +void KviApplication::optionResetUpdate(int flags) +{ + if(flags & KviOption_resetReloadImages) + { + g_pIconManager->reloadImages(); + emit reloadImages(); + } + + if(flags & KviOption_resetUpdateAppFont) + { + updateApplicationFont(); + } + +#ifdef COMPILE_PSEUDO_TRANSPARENCY + if(flags & KviOption_resetUpdatePseudoTransparency) + { + triggerUpdatePseudoTransparency(); + } +#endif + + if(flags & KviOption_resetRestartIdentd) + { + if(g_iIdentDaemonRunningUsers) + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); + + if(KVI_OPTION_BOOL(KviOption_boolUseIdentService) && !KVI_OPTION_BOOL(KviOption_boolUseIdentServiceOnlyOnConnect)) + g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_START); + } + + if(flags & KviOption_resetUpdateGui) + { + triggerUpdateGui(); + } + + if(flags & KviOption_resetUpdateWindowList) + { + g_pFrame->recreateWindowList(); + } + + if(flags & KviOption_resetRestartNotifyList) + { + g_pApp->restartNotifyLists(); + } + + if(flags & KviOption_resetRestartLagMeter) + { + g_pApp->restartLagMeters(); + } + + if(flags & KviOption_resetRecentChannels) + { + g_pApp->buildRecentChannels(); + } + + if(flags & KviOption_resetUpdateNotifier) + { + emit updateNotifier(); + } +} +bool KviApplication::setOptionValue(const QString &optName,const QString &value) +{ + if (!setCommonOptionValue(optName,value)) + return false; + + if(KviQString::equalCI(optName,"stringlistRecentChannels")) + { + buildRecentChannels(); + return true; + } + + // The pixmap options have special treating + if(KviQString::equalCIN(optName,KVI_PIXMAP_OPTIONS_PREFIX,KVI_PIXMAP_OPTIONS_PREFIX_LEN)) + { + // We lookup the image path (so we allow also relative paths for this option type) + QString szVal = value; + szVal.trimmed(); + QString szBuffer; + if(!szVal.isEmpty()) + { + findImage(szBuffer,szVal); + } else { + szBuffer = szVal; + } + + for(int i=0;i < KVI_NUM_PIXMAP_OPTIONS;i++) + { + if(KviQString::equalCI(optName,g_pixmapOptionsTable[i].name)) + { + if(!KviStringConversion::fromString(szBuffer,g_pixmapOptionsTable[i].option))return false; + optionResetUpdate(g_pixmapOptionsTable[i].flags); + return true; + } + } + return false; + } + + return true; +} + +bool KviApplication::setCommonOptionValue(const QString &optName,const QString &value) +{ + + #define SET_OPTION_VALUE(__numOpt,__table,__prefix,__prefixLen) \ + if(KviQString::equalCIN(optName,__prefix,__prefixLen)) \ + { \ + for(int i=0;i < __numOpt;i++) \ + { \ + if(KviQString::equalCI(optName,__table[i].name)) \ + { \ + if(!KviStringConversion::fromString(value,__table[i].option))return false; \ + optionResetUpdate(__table[i].flags); \ + return true; \ + } \ + } \ + return false; \ + } + + SET_OPTION_VALUE(KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable,KVI_BOOL_OPTIONS_PREFIX,KVI_BOOL_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_RECT_OPTIONS,g_rectOptionsTable,KVI_BOOL_OPTIONS_PREFIX,KVI_BOOL_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable,KVI_STRINGLIST_OPTIONS_PREFIX,KVI_STRINGLIST_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_STRING_OPTIONS,g_stringOptionsTable,KVI_STRING_OPTIONS_PREFIX,KVI_STRING_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable,KVI_COLOR_OPTIONS_PREFIX,KVI_COLOR_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable,KVI_MIRCCOLOR_OPTIONS_PREFIX,KVI_MIRCCOLOR_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable,KVI_ICCOLOR_OPTIONS_PREFIX,KVI_ICCOLOR_OPTIONS_PREFIX_LEN) +// SET_OPTION_VALUE(KVI_NUM_PIXMAP_OPTIONS,g_pixmapOptionsTable,KVI_PIXMAP_OPTIONS_PREFIX,KVI_PIXMAP_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_UINT_OPTIONS,g_uintOptionsTable,KVI_UINT_OPTIONS_PREFIX,KVI_UINT_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_FONT_OPTIONS,g_fontOptionsTable,KVI_FONT_OPTIONS_PREFIX,KVI_FONT_OPTIONS_PREFIX_LEN) + SET_OPTION_VALUE(KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable,KVI_MSGTYPE_OPTIONS_PREFIX,KVI_MSGTYPE_OPTIONS_PREFIX_LEN) + + #undef SET_OPTION_VALUE + return true; +} diff --git a/src/kvirc/kernel/KviOptions.h b/src/kvirc/kernel/KviOptions.h new file mode 100644 index 000000000..4063db4b9 --- /dev/null +++ b/src/kvirc/kernel/KviOptions.h @@ -0,0 +1,772 @@ +#ifndef _KVI_OPTIONS_H_ +#define _KVI_OPTIONS_H_ + +//============================================================================= +// +// File : KviOptions.h +// Creation date : Tue Jun 20 2000 12:42:07 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviCString.h" +#include "KviPixmap.h" +#include "KviMessageTypeSettings.h" + +#include +#include +#include +#include +#include + +// option structures + + +#define DECLARE_OPTION_STRUCT(_cname,_type) \ + class _cname \ + { \ + public: \ + QString name; \ + _type option; \ + int flags; \ + public: \ + _cname(const QString &n,_type o,int f) \ + : name(n), option(o), flags(f) {}; \ + ~_cname() {}; \ + }; + +DECLARE_OPTION_STRUCT(KviBoolOption,bool) +DECLARE_OPTION_STRUCT(KviRectOption,QRect) +DECLARE_OPTION_STRUCT(KviStringOption,QString) +DECLARE_OPTION_STRUCT(KviColorOption,QColor) +DECLARE_OPTION_STRUCT(KviFontOption,QFont) +DECLARE_OPTION_STRUCT(KviPixmapOption,KviPixmap) +//DECLARE_OPTION_STRUCT(KviIntOption,int) +DECLARE_OPTION_STRUCT(KviUIntOption,unsigned int) +DECLARE_OPTION_STRUCT(KviMessageTypeSettingsOption,KviMessageTypeSettings) +DECLARE_OPTION_STRUCT(KviStringListOption,QStringList) + +#define KVI_COLOR_EXT_USER_OP 50 +#define KVI_COLOR_EXT_USER_HALFOP 51 +#define KVI_COLOR_EXT_USER_ADMIN 52 +#define KVI_COLOR_EXT_USER_OWNER 53 +#define KVI_COLOR_EXT_USER_VOICE 54 +#define KVI_COLOR_EXT_USER_USEROP 55 +#define KVI_COLOR_EXT_USER_NORMAL 56 +#define KVI_COLOR_CUSTOM 255 +#define KVI_COLOR_OWN 254 + +// option entry indexes + +#define KVI_RECT_OPTIONS_PREFIX "rect" +#define KVI_RECT_OPTIONS_PREFIX_LEN 4 + +#define KviOption_rectFrameGeometry 0 /* internal */ +/* FIXME: this should be in the options module (local config) ? */ +#define KviOption_rectGeneralOptionsDialogGeometry 1 /* internal */ +/* FIXME: this should be in the regusers module (local config) ? */ +#define KviOption_rectRegisteredUsersDialogGeometry 2 /* internal */ + +#define KVI_NUM_RECT_OPTIONS 3 + + + +#define KVI_BOOL_OPTIONS_PREFIX "bool" +#define KVI_BOOL_OPTIONS_PREFIX_LEN 4 + +#define KviOption_boolWindowsRememberProperties 0 /* interface::features::global */ +#define KviOption_boolIrcViewShowImages 1 /* interface::features::components::ircview */ +#define KviOption_boolIrcViewTimestamp 2 /* interface::features::components::ircview */ +#define KviOption_boolIrcViewUrlHighlighting 3 /* interface::features::components::ircview */ +#define KviOption_boolIrcViewWrapMargin 4 /* interface::features::components::ircview */ +#define KviOption_boolInputHistoryCursorAtEnd 5 /* interface::features::components::input */ +#define KviOption_boolAvoidParserWarnings 6 /* ircengine::uparser */ +#define KviOption_boolUseProxyHost 7 /* transport */ +#define KviOption_boolShowGeneralOptionsDialogAsToplevel 8 /* interface::features::global */ +#define KviOption_boolForceBrutalQuit 9 /* irc */ +#define KviOption_boolShowPingPong 10 /* ircoutput */ +#define KviOption_boolPopupNotifierOnNewQueryMessages 11 /* query */ +#define KviOption_boolShowExtendedServerInfo 12 /* ircoutput */ +#define KviOption_boolEchoNumericTopic 13 /* channel */ +#define KviOption_boolShowOwnParts 14 /* ircoutput */ +#define KviOption_boolUseAntiSpamOnPrivmsg 15 /* ircengine::outputcontrol::antispam */ +#define KviOption_boolUseExtendedPrivmsgView 16 /* ircengine::outputcontrol::privmsg */ +#define KviOption_boolShowUserAndHostInPrivmsgView 17 /* ircengine::outputcontrol::privmsg */ +#define KviOption_boolUseWordHighlighting 18 /* ircengine::outputcontrol::highlighting */ +#define KviOption_boolUseBigIcons 19 /* internal */ +#define KviOption_boolCleanupUnusedModules 20 /* uparser ? */ +#define KviOption_boolIgnoreCtcpPing 21 /* ctcp */ +#define KviOption_boolIgnoreCtcpVersion 22 /* ctcp */ +#define KviOption_boolUseCtcpFloodProtection 23 /* ctcp */ +#define KviOption_boolDisableBrokenEventHandlers 24 /* ircengine::uparser */ +#define KviOption_boolIgnoreCtcpClientinfo 25 /* ctcp */ +#define KviOption_boolIgnoreCtcpUserinfo 26 /* ctcp */ +#define KviOption_boolIgnoreCtcpFinger 27 /* ctcp */ +#define KviOption_boolIgnoreCtcpSource 28 /* ctcp */ +#define KviOption_boolIgnoreCtcpTime 29 /* ctcp */ +#define KviOption_boolRequestMissingAvatars 30 /* ctcp::avatar */ +#define KviOption_boolShowCompactModeChanges 31 /* ircoutput */ +#define KviOption_boolIgnoreCtcpDcc 32 /* ctcp */ +#define KviOption_boolAutoAcceptDccChat 33 /* dcc::chat */ +#define KviOption_boolAutoAcceptDccSend 34 /* dcc::send */ +#define KviOption_boolSendZeroAckInDccRecv 35 /* dcc::send */ +#define KviOption_boolUseFastDccSend 36 /* dcc::send */ +#define KviOption_boolUseCompositingForTransparency 37 /* interface::look::global */ +#define KviOption_boolUseWindowListIrcContextIndicator 38 /* interface::features::global */ +#define KviOption_boolUseGlobalApplicationFont 39 /* interface::look::global */ +#define KviOption_boolAlwaysQuitKVIrcClosingLastConsole 40 /* internal */ +#define KviOption_boolAlwaysDisconnectClosingConnectedConsole 41 /* internal */ +#define KviOption_boolFlashWindowOnHighlightedMessages 42 /* highlighting */ +#define KviOption_boolPopupNotifierOnHighlightedMessages 43 /* highlighting */ +#define KviOption_boolFlashWindowOnNotifyOnLine 44 /* notify */ +#define KviOption_boolIrcViewTimestampUTC 45 /* interface::features::components::ircview */ +#define KviOption_boolUseGlobalPseudoTransparency 46 /* interface::look::global */ +#define KviOption_boolUseNotifyList 47 /* ircengine::notifylist */ +#define KviOption_boolNotifyListChangesToActiveWindow 48 /* ircengine::notifylist */ +#define KviOption_boolAutoResumeDccSendWhenAutoAccepted 49 /* dcc::send */ +#define KviOption_boolLimitOutgoingTraffic 50 /* transport */ +#define KviOption_boolSendUnknownCommandsAsRaw 51 /* ircengine::uparser */ +#define KviOption_boolUserListViewDrawGrid 52 /* look & feel::interface look::userlist */ +#define KviOption_boolShowChannelSyncTime 53 /* channel */ +#define KviOption_boolRejoinChannelOnKick 54 /* channel */ +#define KviOption_boolKeepChannelOpenOnKick 55 /* channel */ +#define KviOption_boolAutoCloseDccSendOnSuccess 56 /* dcc::send */ +#define KviOption_boolNotifyDccSendSuccessInConsole 57 /* dcc::send */ +#define KviOption_boolCreateMinimizedDccSend 58 /* dcc::send */ +#define KviOption_boolCreateMinimizedDccChat 59 /* dcc::chat */ +#define KviOption_boolAutoAcceptIncomingAvatars 60 /* irc::ctcp::avatar */ +#define KviOption_boolUseNickCompletionPostfixForFirstWordOnly 61 +#define KviOption_boolUseWindowListIcons 62 /* interface::features */ +#define KviOption_boolCreateMinimizedDccSendWhenAutoAccepted 63 /* dcc::send */ +#define KviOption_boolCreateMinimizedDccChatWhenAutoAccepted 64 /* dcc::chat */ +#define KviOption_boolDccGuessIpFromServerWhenLocalIsUnroutable 65 /* dcc */ +#define KviOption_boolShowRegisteredUsersDialogAsToplevel 66 /* interface::features::global */ +#define KviOption_boolAutoLogQueries 67 /* ircengine::logging */ +#define KviOption_boolAutoLogChannels 68 /* ircendine::logging */ +#define KviOption_boolAutoLogDccChat 69 /* ircengine::logging */ +#define KviOption_boolAutoLogConsole 70 /* ircengine::logging */ +#define KviOption_boolSilentAntiSpam 71 /* ircengine::antispam */ +#define KviOption_boolUseIncomingDccMediaTypeSavePath 72 /* dcc::send */ +#define KviOption_boolNotifyListSendUserhostForOnlineUsers 73 /* ircengine::notifylist */ +#define KviOption_boolUseIntelligentNotifyListManager 74 /* ircengine::notifylist */ +#define KviOption_boolUseWatchListIfAvailable 75 /* ircengine::notifylist */ +#define KviOption_boolUseTreeWindowListWindowList 76 /* interface::features::global */ +#define KviOption_boolBindIrcIPv4ConnectionsToSpecifiedAddress 77 /* connection::transport */ +#define KviOption_boolBindIrcIPv6ConnectionsToSpecifiedAddress 78 /* connection::transport */ +#define KviOption_boolUseAntiSpamOnNotice 79 /* ircengine::antispam */ +#define KviOption_boolSetLastAvatarAsDefaultForRegisteredUsers 80 /* irc::ctcp::avatar */ +#define KviOption_boolCantAcceptIncomingDccConnections 81 /* dcc::general */ +#define KviOption_boolIgnoreCtcpAvatar 82 /* irc::ctcp::floodprotection */ +#define KviOption_boolCtcpRepliesToActiveWindow 83 /* ctcp */ +#define KviOption_boolAutoAcceptDccCanvas 84 +#define KviOption_boolNotifyDccSendSuccessInNotifier 85 /* dcc::send */ +#define KviOption_boolKillBrokenTimers 86 /* ircengine::uparser */ +#define KviOption_boolDccVoiceVolumeSliderControlsPCM 87 /* dcc::voice */ +#define KviOption_boolDccVoiceForceHalfDuplex 88 /* dcc::voice */ +#define KviOption_boolAutoAcceptDccVoice 89 /* dcc::voice */ +#define KviOption_boolCreateMinimizedDccVoice 90 /* dcc::voice */ +#define KviOption_boolCreateMinimizedDccVoiceWhenAutoAccepted 91 /* dcc::voice */ +#define KviOption_boolUseIdentService 92 /* connection::ident */ +#define KviOption_boolShowTipAtStartup 93 /* internal */ +#define KviOption_boolIdentdEnableIPv6 94 /* connection::ident */ +#define KviOption_boolIdentdIPv6ContainsIPv4 95 /* connection::ident */ +#define KviOption_boolScaleAvatars 96 /* ctcp::avatar */ +#define KviOption_boolColorNicks 97 /* interface::features::components::ircview */ +#define KviOption_boolBoldedNicks 98 /* interface::features::components::ircview */ +#define KviOption_boolDccListenOnSpecifiedInterfaceByDefault 99 /* dcc */ +#define KviOption_boolChangeNickAway 100 /* ircengine::away */ +#define KviOption_boolAutoGeneratedAwayNick 101 /* ircengine::away */ +#define KviOption_boolExitAwayOnInput 102 /* ircengine::away */ +#define KviOption_boolAlwaysHighlightNick 103 /* ircengine::outputcontrol::highlighting */ +#define KviOption_boolShowChannelsJoinOnIrc 104 /* internal */ +#define KviOption_boolShowChannelsJoinDialogAsToplevel 105 /* FIXME: internal ??? */ +#define KviOption_boolUserDefinedPortRange 106 /* dcc */ +#define KviOption_boolCreateQueryOnPrivmsg 107 /* query */ +#define KviOption_boolCreateQueryOnNotice 108 /* query */ +#define KviOption_boolCreateMinimizedQuery 109 /* query */ +#define KviOption_boolAutoJoinOnInvite 110 /* channel */ +#define KviOption_boolShowServersConnectDialogOnStart 111 /* connection::ircservers */ +#define KviOption_boolShowServersConnectDialogAsToplevel 112 /* FIXME: internal ?? */ +#define KviOption_boolAcceptBrokenFileNameDccResumeRequests 113 /* dcc::send */ +#define KviOption_boolAutoReconnectOnUnexpectedDisconnect 114 /* connection */ +#define KviOption_boolRejoinChannelsAfterReconnect 115 /* connection */ +#define KviOption_boolReopenQueriesAfterReconnect 116 /* connection */ +#define KviOption_boolEnableQueryTracing 117 /* query */ +#define KviOption_boolOperatorMessagesToActiveWindow 118 /* irc::output */ +#define KviOption_boolInvitesToActiveWindow 119 /* irc::output */ +#define KviOption_boolShowChannelUserFlagInPrivmsgView 120 /* ircengine::outputcontrol::privmsg */ +#define KviOption_boolDccSendFakeAddressByDefault 121 /* dcc::general */ +#define KviOption_boolUseWindowListActivityMeter 122 /* irc::output */ +#define KviOption_boolCloseServerWidgetAfterConnect 123 /* IMPLEMENTATION NEEDED !!! */ +#define KviOption_boolShowIdentityDialogAsToplevel 124 /* ??? */ +#define KviOption_boolShowUserChannelIcons 125 /* look & feel::interface features::userlist */ +#define KviOption_boolShowUserChannelState 126 /* look & feel::interface features::userlist */ +#define KviOption_boolEnableIgnoreOnPrivMsg 127 /* irc::ignore */ +#define KviOption_boolVerboseIgnore 128 /* irc::ignore */ +#define KviOption_boolEnableIgnoreOnNotice 129 /* irc::ignore */ +#define KviOption_boolNotifyFailedDccHandshakes 130 +#define KviOption_boolAutoTileWindows 131 /* internal ? */ +#define KviOption_boolDrawEmoticons 132 /* look::interface::features::output */ +#define KviOption_boolIgnoreCtcpPage 133 /* irc::ctcp::floodprotection */ +#define KviOption_boolShowDialogOnCtcpPage 134 +#define KviOption_boolBashLikeNickCompletion 135 +#define KviOption_boolUseSSLCertificate 136 /* ssl */ +#define KviOption_boolUseSSLPrivateKey 137 /* ssl */ +#define KviOption_boolWarnAboutPastingMultipleLines 138 /* internal */ +#define KviOption_boolKeepChannelsOpenOnUnexpectedDisconnect 139 /* connection */ +#define KviOption_boolKeepQueriesOpenOnUnexpectedDisconnect 140 /* connection */ +#define KviOption_boolUseLagMeterEngine 141 /* irc::lag */ +#define KviOption_boolShowLagOnContextDisplay 142 /* irc::lag */ +#define KviOption_boolDisableBanListRequestOnJoin 143 /* channel */ +#define KviOption_boolDisableBanExceptionListRequestOnJoin 144 /* channel */ +#define KviOption_boolDisableInviteListRequestOnJoin 145 /* channel */ +#define KviOption_boolDisableWhoRequestOnJoin 146 /* channel */ +#define KviOption_boolShowDockExtension 147 /* internal ? */ +#define KviOption_boolDccAddressByIrcDns 148 /* irc::general */ +#define KviOption_boolMinimizeConsoleAfterConnect 149 /* irc::connection */ +#define KviOption_boolHighlightOnlyNormalMsg 150 /* irc::output::highlight */ +#define KviOption_boolHighlightOnlyNormalMsgQueryToo 151 /* irc::output::highlight */ +#define KviOption_boolHighlightOnlyNormalMsgHighlightInChanToo 152 /* irc::output::highlight */ +#define KviOption_boolHighlightOnlyAtCostumHighlightLevel 153 /* irc::output::highlight */ +#define KviOption_boolMdiManagerInSdiMode 154 /* internal */ +#define KviOption_boolDccBrokenBouncerHack 155 /* dcc */ +#define KviOption_boolExternalMessagesToActiveWindow 156 /* irc::output */ +#define KviOption_boolIgnoreChannelAvatarRequestsWhenNoAvatarSet 157 /* ctcp */ +#define KviOption_boolFlashQueryWindowOnNewMessages 158 /* query */ +#define KviOption_boolConfirmCloseWhenThereAreConnections 159 /* interface features */ +#define KviOption_boolUseWindowsDesktopForTransparency 160 /* interface::features::global */ +#define KviOption_boolCtcpRequestsToActiveWindow 161 /* irc::output */ +#define KviOption_boolServerRepliesToActiveWindow 162 /* irc::output */ +#define KviOption_boolServerNoticesToActiveWindow 163 /* irc::output */ +#define KviOption_boolServicesNoticesToActiveWindow 164 /* irc::output */ +#define KviOption_boolSortWindowListItemsByName 165 /* interface::features::global */ +#define KviOption_boolShowWindowListToolTips 166 /* interface::features::global */ +#define KviOption_boolShowUserListViewToolTips 167 /* interface::features::global */ +#define KviOption_boolWhoisRepliesToActiveWindow 168 /* irc::output */ +#define KviOption_boolPopupNotifierOnNotifyOnLine 169 /* notify */ +#define KviOption_boolEnableNotifier 170 /* notifier */ +#define KviOption_boolDccSendForceIdleStep 171 /* dcc */ +#define KviOption_boolStatusBarVisible 172 /* internal */ +#define KviOption_boolTrackLastReadTextViewLine 173 /* ircview::features */ +#define KviOption_boolKeepChannelOpenOnPart 174 /* channel */ +#define KviOption_boolStripMircColorsInUserMessages 175 /* irc::output */ +#define KviOption_boolDoNotSuggestRestoreDefaultScript 176 /* internal */ +#define KviOption_boolLimitDccSendSpeed 177 /* dcc::file transfers */ +#define KviOption_boolLimitDccRecvSpeed 178 /* dcc::file transfers */ +#define KviOption_boolIgnoreModuleVersions 179 +#define KviOption_boolEnableInputHistory 180 /* interface::input */ +#define KviOption_boolUseSpecialColorForTimestamp 181 /* interface::output */ +#define KviOption_boolEnableAwayListUpdates 182 /* channel */ +#define KviOption_boolShowAvatarsInUserlist 183 /* interface::userlist */ +#define KviOption_boolShowUserListStatisticLabel 184 /* interface::userlist */ +#define KviOption_boolShowIconsInPopupMenus 185 /* themes::general */ +#define KviOption_boolScriptErrorsToDebugWindow 186 /* parser */ +#define KviOption_boolShowMinimizedDebugWindow 187 /* parser */ +#define KviOption_boolShowExtendedInfoInQueryLabel 188 /* query */ +#define KviOption_boolUseUserListColorsAsNickColors 189 /* irc::usermessages */ +#define KviOption_boolGzipLogs 190 /* ircengine::logging */ +#define KviOption_boolUseFullWordHighlighting 191 /* highlight */ +#define KviOption_boolNotifierFlashing 192 /* interface::notifier */ +#define KviOption_boolCommandlineInUserFriendlyModeByDefault 193 /* interface::input */ +#define KviOption_boolEnableVisualEffects 194 /* interface */ +#define KviOption_boolDCCFileTransferReplaceOutgoingSpacesWithUnderscores 195 +#define KviOption_boolDoNotUpscaleAvatars 196 +#define KviOption_boolUseDifferentColorForOwnNick 197 /* interface */ +#define KviOption_boolCloseInTray 198 /* interface */ +#define KviOption_boolStartupMinimized 199 /* interface */ +#define KviOption_boolSortReceivedByDccFilesByNicks 200 /* dcc */ +#define KviOption_boolLogChannelHistory 201 /* channel */ +#define KviOption_boolClassicWindowListSetMaximumButtonWidth 202 +#define KviOption_boolKeepChannelsOpenOnDisconnect 203 /* connection */ +#define KviOption_boolKeepQueriesOpenOnDisconnect 204 /* connection */ +#define KviOption_boolHideWindowToolButtons 205 /* interface */ +#define KviOption_boolHideInputToolButtons 206 /* interface */ +#define KviOption_boolStripControlCodesInLogs 207 /* log */ +#define KviOption_boolEnableTrayIconFlashing 208 +#define KviOption_boolUseFlatClassicWindowListButtons 209 +#define KviOption_boolStripMsgTypeInLogs 210 /* log */ +#define KviOption_boolUseLevelBasedTrayNotification 211 +#define KviOption_boolMuteAllSounds 212 +#define KviOption_boolCreateMinimizedChannels 213 +#define KviOption_boolShowNetworkNameForConsoleWindowListEntry 214 +#define KviOption_boolDrawGenderIcons 215 +#define KviOption_boolPrependGenderInfoToRealname 216 +#define KviOption_boolUseIdentServiceOnlyOnConnect 217 /* connection::ident */ +#define KviOption_boolUseSystemUrlHandlers 218 /* Windoze only*/ +#define KviOption_boolScaleAvatarsOnLoad 219 +#define KviOption_boolNotifierFading 220 /* interface::notifier */ +#define KviOption_boolPickRandomIpAddressForRoundRobinServers 221 +#define KviOption_boolPrependAvatarInfoToRealname 222 +#define KviOption_boolEnableAnimatedAvatars 223 +#define KviOption_boolEnableAnimatedSmiles 224 +#define KviOption_boolPlaceNickWithNonAlphaCharsAtEnd 225 +#define KviOption_boolUseStartTlsIfAvailable 226 +#define KviOption_boolPasteLastLogOnChannelJoin 227 /* channel */ +#define KviOption_boolPasteLastLogOnQueryJoin 228 /* query */ +#define KviOption_boolUseSpecifiedSmartColorForOwnNick 229 /* interface::ircview */ +#define KviOption_boolZshLikeNickCompletion 230 +#define KviOption_boolAutoAcceptDccVideo 231 /* dcc::video */ +#define KviOption_boolCreateMinimizedDccVideo 232 /* dcc::video */ +#define KviOption_boolCreateMinimizedDccVideoWhenAutoAccepted 233 /* dcc::video */ +#define KviOption_boolShowTreeWindowListHeader 234 +#define KviOption_boolFlashDccChatWindowOnNewMessages 235 /* dcc:chat */ +#define KviOption_boolPopupNotifierOnNewDccChatMessages 236 /* dcc:chat */ +#define KviOption_boolUseAwayMessage 237 /* away */ +#define KviOption_boolDisableQuietBanListRequestOnJoin 238 /* channel */ +#define KviOption_boolUseSaslIfAvailable 239 +#define KviOption_boolFrameIsMaximized 240 /* internal */ +#define KviOption_boolPrependNickColorInfoToRealname 241 +#define KviOption_boolDontShowNotifierIfActiveWindowIsFullScreen 242 /* notifier */ +#define KviOption_boolWheelScrollsWindowsList 243 +#define KviOption_boolAcceptMismatchedPortDccResumeRequests 244 /* dcc::send */ +#define KviOption_boolEnableUrlLinkToolTip 245 /* ircview output */ +#define KviOption_boolEnableHostLinkToolTip 246 /* ircview output */ +#define KviOption_boolEnableServerLinkToolTip 247 /* ircview output */ +#define KviOption_boolEnableModeLinkToolTip 248 /* ircview output */ +#define KviOption_boolEnableNickLinkToolTip 249 /* ircview output */ +#define KviOption_boolEnableChannelLinkToolTip 250 /* ircview output */ +#define KviOption_boolEnableEscapeLinkToolTip 251 /* ircview output */ +#define KviOption_boolUseDBusNotifier 252 /* notifier */ + +#define KVI_NUM_BOOL_OPTIONS 253 + + +#define KVI_STRING_OPTIONS_PREFIX "string" +#define KVI_STRING_OPTIONS_PREFIX_LEN 6 + +//UNUSED ! #define KviOption_stringFrameCaption 0 /* interfacelookglobal */ +#define KviOption_stringNickname1 1 /* identity */ +#define KviOption_stringNickname2 2 /* identity */ +#define KviOption_stringNickname3 3 /* identity */ +#define KviOption_stringNickname4 4 /* identity */ +#define KviOption_stringUsername 5 /* identity */ +#define KviOption_stringRealname 6 /* identity */ +#define KviOption_stringLocalHostIp 7 /* ?????? This is a fallback one */ +#define KviOption_stringPartMessage 8 /* ircengine::defaultmessages */ +#define KviOption_stringQuitMessage 9 /* ircengine::defaultmessages */ +#define KviOption_stringUrlHttpCommand 10 /* urlhandlers */ +#define KviOption_stringExtendedPrivmsgPrefix 11 /* ircengine::outputcontrol::privmsg */ +#define KviOption_stringExtendedPrivmsgPostfix 12 /* ircengine::outputcontrol::privmsg */ +#define KviOption_stringCtcpVersionPostfix 13 /* ircengine::ctcp::replies */ +#define KviOption_stringCtcpUserInfoOther 14 /* identity */ +#define KviOption_stringCtcpSourcePostfix 15 /* ircengine::ctcp::replies */ +#define KviOption_stringUrlFtpCommand 16 /* urlhandlers */ +#define KviOption_stringUrlHttpsCommand 17 /* urlhandlers */ +#define KviOption_stringUrlMailtoCommand 18 /* urlhandlers */ +#define KviOption_stringPreferredMediaPlayer 19 /* still missing in options ! */ +#define KviOption_stringUrlFileCommand 20 /* urlhandlers */ +#define KviOption_stringNickCompletionPostfix 21 +#define KviOption_stringUrlUnknownCommand 22 /* urlhandlers */ +#define KviOption_stringIPv4ConnectionBindAddress 23 /* connection::transport */ +#define KviOption_stringIPv6ConnectionBindAddress 24 /* connection::transport */ +#define KviOption_stringDccVoiceSoundDevice 25 /* dcc::voice */ +#define KviOption_stringDccVoiceMixerDevice 26 /* dcc::voice */ +#define KviOption_stringAwayMessage 27 /* irc::away */ +#define KviOption_stringIdentdUser 28 /* connection::ident */ +#define KviOption_stringDccListenDefaultInterface 29 /* dcc::general */ +#define KviOption_stringCustomAwayNick 30 /* ircengine::away */ +#define KviOption_stringDefaultDccFakeAddress 31 /* dcc::general */ +#define KviOption_stringCtcpPageReply 32 /* ircengine::ctcp::replies */ +#define KviOption_stringSSLCertificatePath 33 /* ssl */ +#define KviOption_stringSSLCertificatePass 34 /* ssl */ +#define KviOption_stringSSLPrivateKeyPath 35 /* ssl */ +#define KviOption_stringSSLPrivateKeyPass 36 /* ssl */ +#define KviOption_stringSoundSystem 37 /* sound */ +#define KviOption_stringDefaultUserMode 38 +#define KviOption_stringLastImageDialogPath 39 /* internal */ +#define KviOption_stringIconThemeSubdir 40 +#define KviOption_stringIncomingPath 41 /* folders */ +#define KviOption_stringMyAvatar 42 +// empty string means guess from locale +#define KviOption_stringDefaultTextEncoding 43 /* text encoding */ + +#define KviOption_stringWinampTextEncoding 44 +#define KviOption_stringMp3TagsEncoding 45 + +#define KviOption_stringCtcpUserInfoAge 46 /* identity */ +#define KviOption_stringCtcpUserInfoGender 47 /* identity */ +#define KviOption_stringCtcpUserInfoLocation 48 /* identity */ +#define KviOption_stringCtcpUserInfoLanguages 49 /* identity */ +#define KviOption_stringWordSplitters 50 /* highlight */ +#define KviOption_stringOnNewQueryOpenedSound 51 /* sounds */ +#define KviOption_stringOnHighlightedMessageSound 52 /* sounds */ +#define KviOption_stringOnMeKickedSound 53 /* sounds */ +#define KviOption_stringOnQueryMessageSound 54 /* sounds */ +#define KviOption_stringIrcViewTimestampFormat 55 +#define KviOption_stringPreferredTorrentClient 56 /* still missing in options ! */ +// empty string means guess from locale +#define KviOption_stringDefaultSrvEncoding 57 /* server encoding */ +#define KviOption_stringLogsPath 58 /* logfolder */ + +#define KVI_NUM_STRING_OPTIONS 59 + + + +#define KVI_STRINGLIST_OPTIONS_PREFIX "stringlist" +#define KVI_STRINGLIST_OPTIONS_PREFIX_LEN 10 + +#define KviOption_stringlistHighlightWords 0 /* ircengine::outputcontrol::highlighting */ +#define KviOption_stringlistSpamWords 1 /* ircengine::outputcontrol::antispam */ +#define KviOption_stringlistRecentChannels 2 /* internal */ +#define KviOption_stringlistRecentServers 3 /* internal */ +#define KviOption_stringlistRecentNicknames 4 /* internal */ +#define KviOption_stringlistModuleExtensionToolbars 5 /* internal */ +#define KviOption_stringlistImageSearchPaths 6 /* ??? */ +#define KviOption_stringlistRecentIrcUrls 7 /* internal */ + +#define KVI_NUM_STRINGLIST_OPTIONS 8 + + + +#define KVI_COLOR_OPTIONS_PREFIX "color" +#define KVI_COLOR_OPTIONS_PREFIX_LEN 5 + +#define KviOption_colorMdiBackground 0 /* ?? look & feel : gui elements : mdi manager */ +#define KviOption_colorWindowListNormalText 1 /* look & feel::interface look::WindowList::classic WindowList */ +#define KviOption_colorWindowListMinimizedText 2 /* look & feel::interface look::WindowList::classic WindowList */ +#define KviOption_colorWindowListHighlight1Text 3 /* look & feel::interface look::WindowList::classic WindowList */ +#define KviOption_colorWindowListHighlight2Text 4 /* look & feel::interface look::WindowList::classic WindowList */ +#define KviOption_colorWindowListProgressBar 5 /* look & feel::interface look::WindowList::classic WindowList */ +#define KviOption_colorUserListViewAwayForeground 6 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewOwnForeground 7 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewIrcOpForeground 8 /* look & feel::interface look::userlist */ +#define KviOption_colorNotifierBackground 9 /* look & feel::interface look::notifier */ +#define KviOption_colorNotifierForeground 10 /* look & feel::interface look::notifier */ +#define KviOption_colorNotifierTitleForeground 11 /* look & feel::interface look::notifier */ +#define KviOption_colorIrcViewBackground 12 /* look & feel::interface look::ircview */ +#define KviOption_colorInputBackground 13 /* look & feel::interface look::input */ +#define KviOption_colorInputSelectionBackground 14 /* look & feel::interface look::input */ +#define KviOption_colorInputSelectionForeground 15 /* look & feel::interface look::input */ +#define KviOption_colorInputCursor 16 /* look & feel::interface look::input */ +#define KviOption_colorInputControl 17 /* look & feel::interface look::input */ +#define KviOption_colorInputForeground 18 /* look & feel::interface look::input */ +#define KviOption_colorUserListViewBackground 19 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewOpForeground 20 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewVoiceForeground 21 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewNormalForeground 22 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewSelectionBackground 23 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewSelectionForeground 24 /* look & feel::interface look::userlist */ +#define KviOption_colorLabelBackground 25 /* look & feel::interface look::topic label */ +#define KviOption_colorLabelForeground 26 /* look & feel::interface look::topic label */ +#define KviOption_colorGlobalTransparencyFade 27 /* look & feel::interface look */ +#define KviOption_colorIrcToolBarAppletBackground 28 /* theme::tool bar applets */ +#define KviOption_colorIrcToolBarAppletForegroundLowContrast 29 /* theme::tool bar applets */ +#define KviOption_colorIrcToolBarAppletForegroundMidContrast 30 /* theme::tool bar applets */ +#define KviOption_colorIrcToolBarAppletForegroundHighContrastInactive1 31 /* theme::tool bar applets */ +#define KviOption_colorIrcToolBarAppletForegroundHighContrastInactive2 32 /* theme::tool bar applets */ +#define KviOption_colorIrcToolBarAppletForegroundHighContrastActive1 33 /* theme::tool bar applets */ +#define KviOption_colorIrcToolBarAppletForegroundHighContrastActive2 34 /* theme::tool bar applets */ +#define KviOption_colorTreeWindowListBackground 35 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorTreeWindowListActiveBackground 36 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorTreeWindowListForeground 37 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorTreeWindowListActiveForeground 38 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorTreeWindowListHighlight1Foreground 39 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorTreeWindowListHighlight2Foreground 40 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorTreeWindowListProgress 41 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorUserListViewHalfOpForeground 42 /* look & feel::interface look::userlist */ +#define KviOption_colorWindowListHighlight3Text 43 /* look & feel::interface look::WindowList::classic WindowList */ +#define KviOption_colorWindowListHighlight4Text 44 /* look & feel::interface look::WindowList::classic WindowList */ +#define KviOption_colorWindowListHighlight5Text 45 /* look & feel::interface look::WindowList::classic WindowList */ +#define KviOption_colorTreeWindowListHighlight3Foreground 46 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorTreeWindowListHighlight4Foreground 47 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorTreeWindowListHighlight5Foreground 48 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_colorUserListViewChanAdminForeground 49 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewUserOpForeground 50 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewGrid 51 /* look & feel::interface look::userlist */ +#define KviOption_colorUserListViewChanOwnerForeground 52 /* look & feel::interface look::userlist */ +#define KviOption_colorIrcViewMarkLine 53 /* look & feel::interface look::ircvew */ + +#define KVI_NUM_COLOR_OPTIONS 54 + + + +#define KVI_PIXMAP_OPTIONS_PREFIX "pixmap" +#define KVI_PIXMAP_OPTIONS_PREFIX_LEN 6 + +#define KviOption_pixmapMdiBackground 0 +#define KviOption_pixmapIrcViewBackground 1 /* interface::look::components::ircview */ +#define KviOption_pixmapInputBackground 2 /* interface::look::components::input */ +#define KviOption_pixmapUserListViewBackground 3 /* look & feel::interface look::userlist */ +#define KviOption_pixmapLabelBackground 4 /* look & feel::interface look::topic label */ +#define KviOption_pixmapMyAvatar 5 /* identity */ +#define KviOption_pixmapIrcToolBarAppletBackground 6 /* theme::tool bar applets */ +#define KviOption_pixmapTreeWindowListBackground 7 /* look & feel::interface look::WindowList::tree WindowList */ +#define KviOption_pixmapGlobalTransparencyBackground 8 /* theme::transparency */ +#define KviOption_pixmapNotifierBackground 9 /* interface::look::components::notifier */ + +#define KVI_NUM_PIXMAP_OPTIONS 10 + + + + +#define KVI_UINT_OPTIONS_PREFIX "uint" +#define KVI_UINT_OPTIONS_PREFIX_LEN 4 + +#define KviOption_uintIrcSocketTimeout 0 /* connection::transport */ +#define KviOption_uintModuleCleanupTimerInterval 1 +#define KviOption_uintModuleCleanupTimeout 2 +#define KviOption_uintMaxCtcpRequests 3 /* ircengine::ctcp */ +#define KviOption_uintCtcpFloodCheckInterval 4 /* ircengine::ctcp */ +#define KviOption_uintTotalConnectionTime 5 +#define KviOption_uintDccSocketTimeout 6 /* dcc::general */ +#define KviOption_uintDccSendIdleStepInMSec 7 /* dcc::send */ +#define KviOption_uintDccSendPacketSize 8 /* dcc::send */ +#define KviOption_uintGlobalTransparencyParentFadeFactor 9 /* interface::look::general */ +#define KviOption_uintGlobalTransparencyChildFadeFactor 10 /* interface::look::general */ +#define KviOption_uintNotifyListCheckTimeInSecs 11 /* notify */ +#define KviOption_uintSocketQueueFlushTimeout 12 /* connection::transport */ +#define KviOption_uintOutgoingTrafficLimitUSeconds 13 /* connection::transport */ +#define KviOption_uintNotifyListIsOnDelayTimeInSecs 14 /* notify */ +#define KviOption_uintNotifyListUserhostDelayTimeInSecs 15 /* notify */ +#define KviOption_uintTreeWindowListMinimumWidth 16 /* ?? interface::general ?? */ +#define KviOption_uintAvatarOfferTimeoutInSecs 17 /* irc::ctcp::avatar */ +#define KviOption_uintIrcViewMaxBufferSize 18 /* interface::features::components::ircview */ +#define KviOption_uintIrcViewToolTipTimeoutInMsec 19 /* interface::features::components::ircview */ +#define KviOption_uintIrcViewToolTipHideTimeoutInMsec 20 /* interface::features::components::ircview */ +#define KviOption_uintDccVoicePreBufferSize 21 /* dcc::voice */ +#define KviOption_uintIdentdPort 22 /* connection::ident */ +#define KviOption_uintAvatarScaleWidth 23 /* ctcp::avatar */ +#define KviOption_uintAvatarScaleHeight 24 /* ctcp::avatar */ +#define KviOption_uintDccMinPort 25 /* dcc::general */ +#define KviOption_uintDccMaxPort 26 /* dcc::general */ +#define KviOption_uintSoundOfferTimeoutInSecs 27 +#define KviOption_uintMaximumRequestedAvatarSize 28 /* ctcp::avatar */ +#define KviOption_uintGlobalWindowOpacityPercent 29 +#define KviOption_uintPasteDelay 30 +// 0 = unlimited! +#define KviOption_uintMaxDccSendTransfers 31 +// 0 = unlimited slots = windows +#define KviOption_uintMaxDccSlots 32 +#define KviOption_uintTileMethod 33 /* internal ? */ +#define KviOption_uintLagMeterHeartbeat 34 +#define KviOption_uintLagAlarmTime 35 +// KVI_TEXT_ENCODING_UNKNOWN = KviLocale::defaultTextEncoding() <-- guessed from locale +//#define KviOption_uintDefaultTextEncoding 36 /* textencoding */ +#define KviOption_uintWindowListButtonMinWidth 37 /* interface::look::WindowList::classic WindowList */ +// follows the verbosity constants defined below +#define KviOption_uintOutputVerbosityLevel 38 +#define KviOption_uintIrcContextAppletWidth 39 /* internal */ +#define KviOption_uintMinHighlightLevel 40 /* look::interface::features::output */ +#define KviOption_uintUserListViewGridType 41 /* look&feel::ircview */ +#define KviOption_uintWindowListMaximumRows 42 /* interface::look::WindowList::classic WindowList */ +// 0 = unlimited attempts +#define KviOption_uintMaxAutoReconnectAttempts 43 /* connection */ +#define KviOption_uintAutoReconnectDelay 44 /* connection */ +#define KviOption_uintMaxDccSendSpeed 45 /* dcc::file transfers */ +#define KviOption_uintMaxDccRecvSpeed 46 /* dcc::file transfers */ +#define KviOption_uintTimeStampForeground 47 +#define KviOption_uintTimeStampBackground 48 +#define KviOption_uintUserExperienceLevel 49 +#define KviOption_uintClassicWindowListMaximumButtonWidth 50 +#define KviOption_uintDefaultBanType 51 +#define KviOption_uintIrcViewPixmapAlign 52 +#define KviOption_uintUserListPixmapAlign 53 +#define KviOption_uintToolBarAppletPixmapAlign 54 +#define KviOption_uintTreeWindowListPixmapAlign 55 +#define KviOption_uintInputPixmapAlign 56 +#define KviOption_uintAutoFlushLogs 57 +#define KviOption_uintMinTrayLowLevelMessage 58 +#define KviOption_uintMinTrayHighLevelMessage 59 +#define KviOption_uintIdentdOutputMode 60 +#define KviOption_uintScaleAvatarsOnLoadHeight 61 +#define KviOption_uintScaleAvatarsOnLoadWidth 62 +#define KviOption_uintNotifierActiveTransparency 63 +#define KviOption_uintNotifierInactiveTransparency 64 +#define KviOption_uintIrcViewMarkerStyle 65 +#define KviOption_uintIrcViewMarkerSize 66 +#define KviOption_uintUrlMouseClickNum 67 +#define KviOption_uintNotifierAutoHideTime 68 +#define KviOption_uintLinesToPasteOnChannelJoin 69 /* channel */ +#define KviOption_uintDaysIntervalToPasteOnChannelJoin 70 /* channel */ +#define KviOption_uintLinesToPasteOnQueryJoin 71 /* query */ +#define KviOption_uintDaysIntervalToPasteOnQueryJoin 72 /* query */ +#define KviOption_uintSpacesToExpandTabulationInput 73 /* number of spaces used in tabulation expansion in the inputbar */ +#define KviOption_uintUserIrcViewOwnForeground 74 /* look & feel::ircview */ +#define KviOption_uintUserIrcViewOwnBackground 75 /* look & feel::ircview */ +#define KviOption_uintNotifierPixmapAlign 76 +#define KviOption_uintOutputDatetimeFormat 77 /* irc::verbosity */ +#define KviOption_uintOnJoinRequestsDelay 78 +#define KVI_NUM_UINT_OPTIONS 79 + +namespace KviIdentdOutputMode { + enum Mode { + Quiet = 0, + ToConsole = 1, + ToActiveWindow = 2 + }; +} + + +#define KVI_FONT_OPTIONS_PREFIX "font" +#define KVI_FONT_OPTIONS_PREFIX_LEN 4 + +#define KviOption_fontIrcView 0 /* interface::look::components::ircview */ +#define KviOption_fontInput 1 /* interface::look::components::input */ +#define KviOption_fontUserListView 2 /* look & feel::interface look::userlist */ +#define KviOption_fontLabel 3 /* look & feel::interface look::topic label */ +#define KviOption_fontApplication 4 /* interface::look::global */ +#define KviOption_fontIrcToolBarApplet 5 /* theme::tool bar applet */ +#define KviOption_fontWindowList 6 /* interface::look::WindowList::classic WindowList */ +#define KviOption_fontTreeWindowList 7 /* interface::look::WindowList::tree WindowList */ +#define KviOption_fontNotifier 8 /* interface::look::components::notifier */ +#define KviOption_fontNotifierTitle 9 /* interface::look::components::notifier */ + +#define KVI_NUM_FONT_OPTIONS 10 + + + + +#define KVI_ICCOLOR_OPTIONS_PREFIX "iccolor" +#define KVI_ICCOLOR_OPTIONS_PREFIX_LEN 7 + +#define KVI_NUM_ICCOLOR_OPTIONS 8 + + +// indices declared in kvi_out.h + +#define KVI_MSGTYPE_OPTIONS_PREFIX "msgtype" +#define KVI_MSGTYPE_OPTIONS_PREFIX_LEN 7 + +#define KVI_NUM_MSGTYPE_OPTIONS 142 + + + +#define KVI_MIRCCOLOR_OPTIONS_PREFIX "mirccolor" +#define KVI_MIRCCOLOR_OPTIONS_PREFIX_LEN 9 + +#define KVI_NUM_MIRCCOLOR_OPTIONS 16 + + +// external declaration of the tables +extern KVIRC_API KviBoolOption g_boolOptionsTable[KVI_NUM_BOOL_OPTIONS]; +extern KVIRC_API KviRectOption g_rectOptionsTable[KVI_NUM_RECT_OPTIONS]; +extern KVIRC_API KviStringOption g_stringOptionsTable[KVI_NUM_STRING_OPTIONS]; +extern KVIRC_API KviColorOption g_colorOptionsTable[KVI_NUM_COLOR_OPTIONS]; +extern KVIRC_API KviPixmapOption g_pixmapOptionsTable[KVI_NUM_PIXMAP_OPTIONS]; +// extern KviIntOption g_intOptionsTable[KVI_NUM_INT_OPTIONS]; +extern KVIRC_API KviUIntOption g_uintOptionsTable[KVI_NUM_UINT_OPTIONS]; +extern KVIRC_API KviFontOption g_fontOptionsTable[KVI_NUM_FONT_OPTIONS]; +extern KVIRC_API KviMessageTypeSettingsOption g_msgtypeOptionsTable[KVI_NUM_MSGTYPE_OPTIONS]; +extern KVIRC_API KviColorOption g_mirccolorOptionsTable[KVI_NUM_MIRCCOLOR_OPTIONS]; +extern KVIRC_API KviColorOption g_iccolorOptionsTable[KVI_NUM_ICCOLOR_OPTIONS]; +extern KVIRC_API KviStringListOption g_stringlistOptionsTable[KVI_NUM_STRINGLIST_OPTIONS]; + +// __this is how we access the options from outside +#define KVI_OPTION_BOOL(_idx) g_boolOptionsTable[_idx].option +#define KVI_OPTION_RECT(_idx) g_rectOptionsTable[_idx].option +#define KVI_OPTION_STRING(_idx) g_stringOptionsTable[_idx].option +#define KVI_OPTION_COLOR(_idx) g_colorOptionsTable[_idx].option +#define KVI_OPTION_PIXMAP(_idx) g_pixmapOptionsTable[_idx].option +#define KVI_OPTION_UINT(_idx) g_uintOptionsTable[_idx].option +#define KVI_OPTION_FONT(_idx) g_fontOptionsTable[_idx].option +#define KVI_OPTION_MSGTYPE(_idx) g_msgtypeOptionsTable[_idx].option +#define KVI_OPTION_MIRCCOLOR(_idx) g_mirccolorOptionsTable[_idx].option +#define KVI_OPTION_STRINGLIST(_idx) g_stringlistOptionsTable[_idx].option +#define KVI_OPTION_ICCOLOR(_idx) g_iccolorOptionsTable[_idx].option + + +// Verbosity constants + +#define KVI_VERBOSITY_LEVEL_MUTE 0 +#define KVI_VERBOSITY_LEVEL_QUIET 1 +#define KVI_VERBOSITY_LEVEL_NORMAL 2 +#define KVI_VERBOSITY_LEVEL_VERBOSE 3 +#define KVI_VERBOSITY_LEVEL_PARANOIC 4 + +#define _OUTPUT_PARANOIC (KVI_OPTION_UINT(KviOption_uintOutputVerbosityLevel) >= KVI_VERBOSITY_LEVEL_PARANOIC) +#define _OUTPUT_VERBOSE (KVI_OPTION_UINT(KviOption_uintOutputVerbosityLevel) >= KVI_VERBOSITY_LEVEL_VERBOSE) +#define _OUTPUT_QUIET (KVI_OPTION_UINT(KviOption_uintOutputVerbosityLevel) <= KVI_VERBOSITY_LEVEL_QUIET) +#define _OUTPUT_MUTE (KVI_OPTION_UINT(KviOption_uintOutputVerbosityLevel) <= KVI_VERBOSITY_LEVEL_MUTE) + + #define START_TABLE_BOLD_ROW "" + #define END_TABLE_BOLD_ROW "" + + #define START_TABLE_NORMAL_ROW "" + + #define SET_ANTI_ALIASING(p) (p).setRenderHint(QPainter::TextAntialiasing); + + +#define KVI_RECENT_CHANNELS_SEPARATOR ":" + +#if defined(_KVI_OPTIONS_CPP_) || defined(_WANT_OPTION_FLAGS_) + + // flag definitions + + // section of the config file (rightmost 8 bits) + #define KviOption_sectFlagNone 0 + #define KviOption_sectFlagFrame 1 + #define KviOption_sectFlagMdi 2 + #define KviOption_sectFlagWindowList 3 + #define KviOption_sectFlagWindows 4 + #define KviOption_sectFlagIrcView 5 + #define KviOption_sectFlagMsgType 6 + #define KviOption_sectFlagMircColor 7 + #define KviOption_sectFlagInput 8 + #define KviOption_sectFlagUserParser 9 + #define KviOption_sectFlagConnection 10 + #define KviOption_sectFlagIrcSocket 11 + #define KviOption_sectFlagUser 12 + #define KviOption_sectFlagUserListView 13 + #define KviOption_sectFlagLabel 14 + #define KviOption_sectFlagModules 15 + #define KviOption_sectFlagCtcp 16 + #define KviOption_sectFlagDcc 17 + #define KviOption_sectFlagGui 18 + #define KviOption_sectFlagIrcToolBar 19 + #define KviOption_sectFlagLogging 20 + #define KviOption_sectFlagAntiSpam 21 + #define KviOption_sectFlagAvatar 22 + #define KviOption_sectFlagUrl 23 + #define KviOption_sectFlagRecent 24 + #define KviOption_sectFlagGeometry 25 + #define KviOption_sectFlagNotifier 26 + + #define KVI_NUM_OPTION_SECT_FLAGS 27 + + #define KviOption_sectMask 255 + + // other logical groupings of options + #define KviOption_groupTheme (1 << 8) + + #define KviOption_groupMask (255 << 8) + + + + // actions to take when an option is set + #define KviOption_resetNone 0 + #define KviOption_resetUpdateNotifier (1 << 16) + #define KviOption_resetUpdateGui (1 << 17) + #define KviOption_resetUpdateWindowList (1 << 18) + #define KviOption_resetUpdateAppFont (1 << 19) + #define KviOption_resetUpdatePseudoTransparency (1 << 20) + #define KviOption_resetRestartNotifyList (1 << 21) + #define KviOption_resetRestartIdentd (1 << 22) + #define KviOption_resetReloadImages (1 << 23) + #define KviOption_resetRestartLagMeter (1 << 24) + #define KviOption_resetRecentChannels (1 << 25) + + #define KviOption_resetMask (~(KviOption_sectMask | KviOption_groupMask)) + + //for file pathes + #define KviOption_encodePath (1 << 25) + +#endif + +#endif //_KVI_OPTIONS_H_ diff --git a/src/kvirc/kernel/KviSSLMaster.cpp b/src/kvirc/kernel/KviSSLMaster.cpp new file mode 100644 index 000000000..53c6eef17 --- /dev/null +++ b/src/kvirc/kernel/KviSSLMaster.cpp @@ -0,0 +1,315 @@ +//============================================================================= +// +// File : KviSSLmanager.cpp +// Creation date : Mon Jun 17 2002 20:34:00 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviSSLMaster.h" + +#ifdef COMPILE_SSL_SUPPORT + +#include "KviWindow.h" +#include "KviOptions.h" +#include "kvi_out.h" +#include "KviMircCntrl.h" +#include "KviLocale.h" +#include "KviKvsVariant.h" + +#ifdef COMPILE_ON_WINDOWS + // + // Since OpenSSL 0.9.8 we need to link in a piece of code from the OpenSSL source. + // This is their own hack to avoid runtime problems when linking to an OpenSSL library + // that has been compiled with a different runtime (different options or compiler at all). + // This file is either installed in ${OPENSSL_INSTALL_ROOT}/include/openssl or + // in ${OPENSSL_INSTALL_ROOT}/ms/. + // + // Failing to include this file manifests itself with an abort when using a certificate. + // Just before the abort a message box complains about "no OPENSSL_Applink" which is + // implemented inside applink.c + // + #include +#endif //COMPILE_ON_WINDOWS + +namespace KviSSLMaster +{ + +KVIRC_API void printSSLCipherInfo(KviWindow * wnd,const char * description,KviSSLCipherInfo * c) +{ + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: %c%s"),KVI_TEXT_BOLD,description); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Cipher: %c%s"),KVI_TEXT_BOLD,c->name()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Version: %c%s"),KVI_TEXT_BOLD,c->version()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Bits: %c%d (%d used)"),KVI_TEXT_BOLD,c->bits(),c->bitsUsed()); +// wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Description: %c%s"),KVI_TEXT_BOLD,c->description()); +} + +KVIRC_API void printSSLCertificate(KviWindow * wnd,const char * description,KviSSLCertificate * c) +{ + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: %c%s"),KVI_TEXT_BOLD,description); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Version: %c%d"),KVI_TEXT_BOLD,c->version()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Serial number: %c%d"),KVI_TEXT_BOLD,c->serialNumber()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Subject:")); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Common name: %c%s"),KVI_TEXT_BOLD,c->subjectCommonName()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Organization: %c%s"),KVI_TEXT_BOLD,c->subjectOrganization()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Organizational unit: %c%s"),KVI_TEXT_BOLD,c->subjectOrganizationalUnit()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Country: %c%s"),KVI_TEXT_BOLD,c->subjectCountry()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: State or province: %c%s"),KVI_TEXT_BOLD,c->subjectStateOrProvince()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Locality: %c%s"),KVI_TEXT_BOLD,c->subjectLocality()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Issuer:")); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Common name: %c%s"),KVI_TEXT_BOLD,c->issuerCommonName()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Organization: %c%s"),KVI_TEXT_BOLD,c->issuerOrganization()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Organizational unit: %c%s"),KVI_TEXT_BOLD,c->issuerOrganizationalUnit()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Country: %c%s"),KVI_TEXT_BOLD,c->issuerCountry()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: State or province: %c%s"),KVI_TEXT_BOLD,c->issuerStateOrProvince()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Locality: %c%s"),KVI_TEXT_BOLD,c->issuerLocality()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Public key: %c%s (%d bits)"),KVI_TEXT_BOLD,c->publicKeyType(),c->publicKeyBits()); + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Signature type: %c%s"),KVI_TEXT_BOLD,c->signatureType()); + KviCString tmp = c->signatureContents(); + if(tmp.len() > 40) + { + tmp.cutRight(tmp.len() - 40); + tmp.append("..."); + } + wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Signature contents: %c%s"),KVI_TEXT_BOLD,tmp.ptr()); + +} + +KVIRC_API void printSSLConnectionInfo(KviWindow * wnd,KviSSL * s) +{ + KviSSLCertificate * sc = s->getPeerCertificate(); + if(sc) + { + QString tmp(__tr2qs("Peer X509 certificate")); + KviSSLMaster::printSSLCertificate(wnd,tmp.toLocal8Bit().data(),sc); + delete sc; + } else wnd->outputNoFmt(KVI_OUT_SSL,__tr2qs("[SSL]: The peer didn't provide a certificate")); + KviSSLCipherInfo * ci = s->getCurrentCipherInfo(); + if(ci) + { + QString tmp(__tr2qs("Current transmission cipher")); + KviSSLMaster::printSSLCipherInfo(wnd,tmp.toLocal8Bit().data(),ci); + delete ci; + } else wnd->outputNoFmt(KVI_OUT_SSL,__tr2qs("[SSL]: Can't find out the current cipher info")); +} + +KVIRC_API KviSSL * allocSSL(KviWindow * wnd,kvi_socket_t sock,KviSSL::Method m,const char * contextString) +{ + KviSSL * s = new KviSSL(); + if(!s->initContext(m)) + { + delete s; + return 0; + } + + if(!contextString)contextString = KviCString::emptyString().ptr(); + + if(KVI_OPTION_BOOL(KviOption_boolUseSSLCertificate)) + { + switch(s->useCertificateFile( + KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data(), + KVI_OPTION_STRING(KviOption_stringSSLCertificatePass).toUtf8().data())) + { + case KviSSL::Success: + if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL]: Using certificate file %s"),contextString,KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data()); + break; + case KviSSL::FileIoError: + if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL ERROR]: File I/O error while trying to use the certificate file %s"),contextString,KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data()); + break; + default: + { + KviCString buffer; + while(s->getLastErrorString(buffer)) + { + if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL ERROR]: %s"),contextString,buffer.ptr()); + } + } + break; + } + } + if(KVI_OPTION_BOOL(KviOption_boolUseSSLPrivateKey)) + { + switch(s->usePrivateKeyFile( + KVI_OPTION_STRING(KviOption_stringSSLPrivateKeyPath).toUtf8().data(), + KVI_OPTION_STRING(KviOption_stringSSLPrivateKeyPass).toUtf8().data())) + { + case KviSSL::Success: + if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL]: Using private key file %s"),contextString,KVI_OPTION_STRING(KviOption_stringSSLPrivateKeyPath).toUtf8().data()); + break; + case KviSSL::FileIoError: + if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL ERROR]: File I/O error while trying to use the private key file %s"),contextString,KVI_OPTION_STRING(KviOption_stringSSLPrivateKeyPath).toUtf8().data()); + break; + default: + { + KviCString buffer; + while(s->getLastErrorString(buffer)) + { + if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL ERROR]: %s"),contextString,buffer.ptr()); + } + } + break; + } + } + + if(!s->initSocket(sock)) + { + delete s; + return 0; + } + + return s; +} + +KVIRC_API void freeSSL(KviSSL * s) +{ + delete s; +} + +/** + * Used for $certificate() and $dcc.getSSLCertInfo() function + */ +KVIRC_API bool getSSLCertInfo(KviSSLCertificate * pCert, QString szQuery, QString szOptionalParam, KviKvsVariant * pRetBuffer) +{ + pRetBuffer->setString(""); + + if(szQuery.compare("signatureType")==0) + { + pRetBuffer->setString(pCert->signatureType()); + return true; + } + if(szQuery.compare("signatureContents")==0) + { + pRetBuffer->setString(pCert->signatureContents()); + return true; + } + if(szQuery.compare("subjectCountry")==0) + { + pRetBuffer->setString(pCert->subjectCountry()); + return true; + } + if(szQuery.compare("subjectStateOrProvince")==0) + { + pRetBuffer->setString(pCert->subjectStateOrProvince()); + return true; + } + if(szQuery.compare("subjectLocality")==0) + { + pRetBuffer->setString(pCert->subjectLocality()); + return true; + } + if(szQuery.compare("subjectOrganization")==0) + { + pRetBuffer->setString(pCert->subjectOrganization()); + return true; + } + if(szQuery.compare("subjectOrganizationalUnit")==0) + { + pRetBuffer->setString(pCert->subjectOrganizationalUnit()); + return true; + } + if(szQuery.compare("subjectCommonName")==0) + { + pRetBuffer->setString(pCert->subjectCommonName()); + return true; + } + if(szQuery.compare("issuerCountry")==0) + { + pRetBuffer->setString(pCert->issuerCountry()); + return true; + } + if(szQuery.compare("issuerStateOrProvince")==0) + { + pRetBuffer->setString(pCert->issuerStateOrProvince()); + return true; + } + if(szQuery.compare("issuerLocality")==0) + { + pRetBuffer->setString(pCert->issuerLocality()); + return true; + } + if(szQuery.compare("issuerOrganization")==0) + { + pRetBuffer->setString(pCert->issuerOrganization()); + return true; + } + if(szQuery.compare("issuerOrganizationalUnit")==0) + { + pRetBuffer->setString(pCert->issuerOrganizationalUnit()); + return true; + } + if(szQuery.compare("issuerCommonName")==0) + { + pRetBuffer->setString(pCert->issuerCommonName()); + return true; + } + if(szQuery.compare("publicKeyBits")==0) + { + pRetBuffer->setInteger(pCert->publicKeyBits()); + return true; + } + if(szQuery.compare("publicKeyType")==0) + { + pRetBuffer->setString(pCert->publicKeyType()); + return true; + } + if(szQuery.compare("serialNumber")==0) + { + pRetBuffer->setInteger(pCert->serialNumber()); + return true; + } + if(szQuery.compare("pemBase64")==0) + { + const char * szTmp=pCert->getX509Base64(); + QString szBase64(szTmp); + pRetBuffer->setString(szBase64); + delete szTmp; + return true; + } + if(szQuery.compare("version")==0) + { + pRetBuffer->setInteger(pCert->version()); + return true; + } + if(szQuery.compare("fingerprintIsValid")==0) + { + pRetBuffer->setBoolean(pCert->fingerprintIsValid()); + return true; + } + if(szQuery.compare("fingerprintDigestId")==0) + { + pRetBuffer->setInteger(pCert->fingerprintDigestId()); + return true; + } + if(szQuery.compare("fingerprintDigestStr")==0) + { + pRetBuffer->setString(pCert->fingerprintDigestStr()); + return true; + } + if(szQuery.compare("fingerprintContents")==0) + { + pRetBuffer->setString(pCert->fingerprintContents(szOptionalParam)); + return true; + } + + // the warning is displayed in the caller + return false; +} + +}; +#endif diff --git a/src/kvirc/kernel/KviSSLMaster.h b/src/kvirc/kernel/KviSSLMaster.h new file mode 100644 index 000000000..d726dff0d --- /dev/null +++ b/src/kvirc/kernel/KviSSLMaster.h @@ -0,0 +1,53 @@ +#ifndef _KVI_SSLMASTER_H_ +#define _KVI_SSLMASTER_H_ +//============================================================================= +// +// File : KviSSLMaster.h +// Creation date : Mon Jun 17 2002 20:34:00 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" + +#ifdef COMPILE_SSL_SUPPORT + +#include "KviSSL.h" +#include "kvi_sockettype.h" + +class KviWindow; +class KviKvsVariant; + +namespace KviSSLMaster +{ + extern KVIRC_API void printSSLCipherInfo(KviWindow * wnd,const char * description,KviSSLCipherInfo * c); + extern KVIRC_API void printSSLCertificate(KviWindow * wnd,const char * description,KviSSLCertificate * c); + + extern KVIRC_API void printSSLConnectionInfo(KviWindow * wnd,KviSSL * s); + + extern KVIRC_API KviSSL * allocSSL(KviWindow * wnd,kvi_socket_t sock,KviSSL::Method m,const char * contextString = 0); + extern KVIRC_API void freeSSL(KviSSL * s); + + extern KVIRC_API bool getSSLCertInfo(KviSSLCertificate * pCert, QString szQuery, QString szOptionalParam, KviKvsVariant * pRetBuffer); +} + +#endif + + +#endif //_KVI_SSLMASTER_H_ diff --git a/src/kvirc/kernel/KviTextIconManager.cpp b/src/kvirc/kernel/KviTextIconManager.cpp new file mode 100644 index 000000000..f31e89769 --- /dev/null +++ b/src/kvirc/kernel/KviTextIconManager.cpp @@ -0,0 +1,309 @@ +//============================================================================= +// +// File : KviTextIconManager.cpp +// Creation date : Thu 15 May 2002 12:04:12 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + +#define _KVI_TEXTICONMANAGER_CPP_ + +#include "KviIconManager.h" +#include "KviTextIconManager.h" +#include "KviCString.h" +#include "KviPointerList.h" +#include "KviConfigurationFile.h" +#include "KviApplication.h" +#include "kvi_confignames.h" +#include "KviAnimatedPixmap.h" +#include "KviOptions.h" + +#include +#include + +static KviTextIconAssocEntry default_associations[]= +{ + { ":)" , KVI_SMALLICON_SMILE }, + { ":*" , KVI_SMALLICON_KISS }, + { ":D" , KVI_SMALLICON_BIGGRIN }, + { ":(" , KVI_SMALLICON_UGLY }, + { ":/" , KVI_SMALLICON_ANGRY }, + { ":O" , KVI_SMALLICON_SURPRISED2 }, + { ":P" , KVI_SMALLICON_TONGUE }, + { ";)" , KVI_SMALLICON_EYE }, + { ":°)" , KVI_SMALLICON_TEARSMILE }, + { ":°" , KVI_SMALLICON_CRY }, + { ":S" , KVI_SMALLICON_AFRAID }, + { ":|" , KVI_SMALLICON_DEMORALIZED }, + { ":P°" , KVI_SMALLICON_SLURP }, + { 0 , 0 } +}; + +KVIRC_API KviTextIconManager * g_pTextIconManager = 0; + +KviTextIcon::KviTextIcon(int iId) +: m_iId(iId),m_pAnimatedPixmap(0) +{ +} + +KviTextIcon::KviTextIcon(QString szFile) +: m_iId(-1), m_szFileName(szFile) +{ + QString szRetPath; + + if(g_pApp->findImage(szRetPath, szFile)) + { + m_pAnimatedPixmap = new KviAnimatedPixmap(szRetPath); +#if 0 // this doesn't work anyway + if(KVI_OPTION_BOOL(KviOption_boolEnableAnimatedSmiles)) + { + m_pAnimatedPixmap->start(); + } else { + m_pAnimatedPixmap->stop(); + } +#endif + } else { + m_pAnimatedPixmap = NULL; + } +} + +KviTextIcon::KviTextIcon(KviTextIcon * pIcon) +{ + m_iId = pIcon->id(); + m_szFileName = pIcon->m_szFileName; + if(pIcon->m_pAnimatedPixmap) + { + m_pAnimatedPixmap = new KviAnimatedPixmap(*(pIcon->m_pAnimatedPixmap)); + } else { + m_pAnimatedPixmap = NULL; + } +} + +KviTextIcon::~KviTextIcon() +{ + if(m_pAnimatedPixmap) + delete m_pAnimatedPixmap; +} + +void KviTextIcon::setId(int iId) +{ + m_iId = iId; + m_szFileName=QString(); +} + +void KviTextIcon::setFilename(QString szFileName) +{ + m_iId = -1; + m_szFileName = szFileName; +} + +QPixmap * KviTextIcon::pixmap() +{ + if(m_iId >= 0) + return g_pIconManager->getSmallIcon(m_iId); + + // This is actually wrong (at least for the current implementation). + // Users of this class expect the pointer to be permanent while + // g_pIconManager returns temporary pointers. + // KviIrcView will happily crash dereferencing a hollow pointer sooner or later + return g_pIconManager->getPixmap(m_szFileName); +} + +KviTextIconManager::KviTextIconManager() +: QObject() +{ + m_pTextIconDict = new KviPointerHashTable(47,false); + m_pTextIconDict->setAutoDelete(true); +} + +KviTextIconManager::~KviTextIconManager() +{ + delete m_pTextIconDict; +} + +void KviTextIconManager::clear() +{ + m_pTextIconDict->clear(); +} + +void KviTextIconManager::insert(const QString & szName, int iId) +{ + m_pTextIconDict->replace(szName, new KviTextIcon(iId)); + emit changed(); +} + +void KviTextIconManager::insert(const QString & szName,KviTextIcon & icon) +{ + m_pTextIconDict->replace(szName, new KviTextIcon(&icon)); + emit changed(); +} + +void KviTextIconManager::checkDefaultAssociations() +{ + for(int i=0; default_associations[i].name; i++) + { + if(!m_pTextIconDict->find(default_associations[i].name)) + insert(QString::fromUtf8(default_associations[i].name),default_associations[i].iVal); + } + emit changed(); +} + +void KviTextIconManager::load() +{ + QString szTmp; + int iUpd = 0; + if(g_pApp->getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_TEXTICONS)) + { + iUpd = load(szTmp,false); + } + + if(iUpd == TEXTICONMANAGER_CURRENT_CONFIG_UPDATE) + return; + + // do a merge of the texticons if we have a new config version + g_pApp->getGlobalKvircDirectory(szTmp,KviApplication::Config,KVI_CONFIGFILE_TEXTICONS); + + if(QFile::exists(szTmp)) + load(szTmp,true); +} + +void KviTextIconManager::applyOptions() +{ + for( + KviTextIcon * pIcon = m_pTextIconDict->first(); + pIcon; + pIcon = m_pTextIconDict->next() + ) + { + if(pIcon->animatedPixmap()) + { + if(KVI_OPTION_BOOL(KviOption_boolEnableAnimatedSmiles)) + { + pIcon->animatedPixmap()->start(); + } else { + pIcon->animatedPixmap()->stop(); + } + } + } +} + +void KviTextIconManager::save() +{ + QString szTmp; + g_pApp->getLocalKvircDirectory(szTmp,KviApplication::Config,KVI_CONFIGFILE_TEXTICONS); + save(szTmp); +} + +int KviTextIconManager::load(const QString & szFileName, bool bMerge) +{ + if(!bMerge) m_pTextIconDict->clear(); + + KviConfigurationFile cfg(szFileName,KviConfigurationFile::Read); + + cfg.setGroup("Manager"); + int iUpd = cfg.readIntEntry("ConfigUpdate",0); + + KviConfigurationFileGroup * pDict = cfg.dict()->find("TextIcons"); + if(pDict) + { + KviConfigurationFileGroupIterator it(*pDict); + + KviPointerList names; + names.setAutoDelete(true); + + while(it.current()) + { + names.append(new QString(it.currentKey())); + ++it; + } + + cfg.setGroup("TextIcons"); + + for(QString * s = names.first(); s; s = names.next()) + { + int iId = cfg.readIntEntry(*s,-1); + QString szTmp; + QPixmap * pix = 0; + //qDebug("%s %s %i %i",__FILE__,__FUNCTION__,__LINE__,id); + if(iId != -1) + { + pix = g_pIconManager->getSmallIcon(iId); + } else { + szTmp = cfg.readEntry(*s); + pix=g_pIconManager->getPixmap(szTmp); + if(!pix) + { + iId = KVI_SMALLICON_HELP; + pix = g_pIconManager->getSmallIcon(iId); + } + } + + if(pix) + { + if(bMerge) + { + if(!m_pTextIconDict->find(*s)) + { + if(iId != -1) + { + m_pTextIconDict->replace(*s,new KviTextIcon(iId)); + } else { + m_pTextIconDict->replace(*s,new KviTextIcon(szTmp)); + } + } + } else { + if(iId != -1) + { + m_pTextIconDict->replace(*s,new KviTextIcon(iId)); + } else { + m_pTextIconDict->replace(*s,new KviTextIcon(szTmp)); + } + } + } + } + } + + emit changed(); + + return iUpd; +} + +void KviTextIconManager::save(const QString & szFileName) +{ + KviConfigurationFile cfg(szFileName,KviConfigurationFile::Write); + + cfg.setGroup("Manager"); + cfg.writeEntry("ConfigUpdate",TEXTICONMANAGER_CURRENT_CONFIG_UPDATE); + + cfg.setGroup("TextIcons"); + + KviPointerHashTableIterator it(*m_pTextIconDict); + while(KviTextIcon * pIcon = it.current()) + { + if(pIcon->id() != -1) + cfg.writeEntry(it.currentKey(),pIcon->id()); + else + cfg.writeEntry(it.currentKey(),pIcon->filename()); + ++it; + } +} + +#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES +#include "kvi_texticonmanager.moc" +#endif //COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/KviTextIconManager.h b/src/kvirc/kernel/KviTextIconManager.h new file mode 100644 index 000000000..e8c3bbe38 --- /dev/null +++ b/src/kvirc/kernel/KviTextIconManager.h @@ -0,0 +1,244 @@ +#ifndef _KVI_TEXTICONMANAGER_H_ +#define _KVI_TEXTICONMANAGER_H_ + +//============================================================================= +// +// File : KviTextIconManager.h +// Creation date : Thu 15 May 2002 12:04:12 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviTextIconManager.h +* \author Szymon Stefanek +* \brief +* +* \def TEXTICONMANAGER_CURRENT_CONFIG_UPDATE This MUST match the ConfigUpdate entry in the configuration file shipped with KVIrc +*/ + +#include "kvi_settings.h" +#include "KviPointerHashTable.h" +#include "KviAnimatedPixmap.h" + +#include + +#define TEXTICONMANAGER_CURRENT_CONFIG_UPDATE 4 + +/** +* \typedef KviTextIconAssocEntry +* \struct _KviTextIconAssocEntry +* \brief A struct that contains the icon association entries +*/ +typedef struct _KviTextIconAssocEntry +{ + const char * name; /**< the name of the icon */ + int iVal; /**< the id of the icon */ +} KviTextIconAssocEntry; + +/** +* \class KviTextIcon +* \brief The class that holds the icons +*/ +class KVIRC_API KviTextIcon +{ +protected: + int m_iId; + QString m_szFileName; + KviAnimatedPixmap * m_pAnimatedPixmap; +public: + /** + * \brief Constructs the icon object + * \param iId The id of the icon + * \return KviTextIcon + */ + KviTextIcon(int iId); + + /** + * \brief Constructs the icon object + * \param szFile The filename the icon + * \return KviTextIcon + */ + KviTextIcon(QString szFile); + + /** + * \brief Constructs the icon object + * \param pIcon The pointer to the icon + * \return KviTextIcon + */ + KviTextIcon(KviTextIcon * pIcon); + + /** + * \brief Destroys the icon object + */ + ~KviTextIcon(); +public: + /** + * \brief Returns the id of the icon + * \return int + */ + inline int id(){ return m_iId; }; + + /** + * \brief Sets the id of the icon + * \param iId The id of the icon + * \return void + */ + void setId(int iId); + + /** + * \brief Sets the filename of the icon + * \param szFileName The filename of the icon + * \return void + */ + void setFilename(QString szFileName); + + /** + * \brief Returns the filename of the icon + * \return QString + */ + inline QString filename(){ return m_szFileName; }; + + /** + * \brief Returns the pixmap associated to the icon + * \return QPixmap * + */ + QPixmap * pixmap(); + + /** + * \brief Returns the animated pixmap associated to the icon + * \return KviAnimatedPixmap * + */ + inline KviAnimatedPixmap * animatedPixmap(){ return m_pAnimatedPixmap; }; +}; + +/** +* \class KviTextIconManager +* \brief The class that manages the icons +*/ +class KVIRC_API KviTextIconManager : public QObject +{ + friend class KviTextIconWindow; + friend class KviTextIconsOptionsWidget; + Q_OBJECT +public: + /** + * \brief Constructs the icon manager object + * \return KviTextIconManager + */ + KviTextIconManager(); + + /** + * \brief Destroys the icon manager object + */ + ~KviTextIconManager(); +private: + KviPointerHashTable * m_pTextIconDict; +public: + /** + * \brief Returns the dictionary of the icons + * \return KviPointerHashTable * + */ + inline KviPointerHashTable * textIconDict(){ return m_pTextIconDict; }; + + /** + * \brief Checks and updates the default associations + * \return void + */ + void checkDefaultAssociations(); + + /** + * \brief Clears the dictionary + * \return void + */ + void clear(); + + /** + * \brief Inserts an icon in the dictionary + * \param szName The name of the icon + * \param iId The id of the icon + * \return void + */ + void insert(const QString & szName, int iId); + + /** + * \brief Inserts an icon in the dictionary + * \param szName The name of the icon + * \param icon The icon + * \return void + */ + void insert(const QString & szName, KviTextIcon & icon); + + /** + * \brief Returns the text of the icon + * \param szName The name of the icon + * \return KviTextIcon * + */ + inline KviTextIcon * lookupTextIcon(const QString & szName){ return m_pTextIconDict->find(szName); }; + + /** + * \brief Loads the dictionary + * \return void + */ + void load(); + + /** + * \brief Saves the dictionary + * \return void + */ + void save(); + + /** + * \brief Applies the options + * \return void + */ + void applyOptions(); +protected: + /** + * \brief Saves the dictionary to a file + * + * This is the real save() function + * \param szFileName The filename where to save + * \return void + */ + void save(const QString & szFileName); + + /** + * \brief Loads the dictionary from a file + * + * This is the real load() function + * It returns the config update + * \param szFileName The filename from where to load + * \param bMerge Whether to merge the existing dictionary with the loaded one + * \return int + */ + int load(const QString & szFileName, bool bMerge = false); +signals: + /** + * \brief Called when the default associations change + * \return void + */ + void changed(); +}; + +#ifndef _KVI_TEXTICONMANAGER_CPP_ + extern KVIRC_API KviTextIconManager * g_pTextIconManager; +#endif + +#endif //_KVI_TEXTICONMANAGER_H_ diff --git a/src/kvirc/kernel/KviTheme.cpp b/src/kvirc/kernel/KviTheme.cpp new file mode 100644 index 000000000..062af7ee2 --- /dev/null +++ b/src/kvirc/kernel/KviTheme.cpp @@ -0,0 +1,295 @@ +//============================================================================= +// +// File : kvi_themeinfo.cpp +// Creation date : Mon Jan 08 2007 03:23:00 CEST by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2007-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviTheme.h" +#include "KviFileUtils.h" +#include "KviConfigurationFile.h" +#include "KviLocale.h" +#include "KviMiscUtils.h" +#include "kvi_sourcesdate.h" + +#include + +#define KVI_THEME_SMALL_SCREENSHOT_NAME "screenshot_small.png" +#define KVI_THEME_MEDIUM_SCREENSHOT_NAME "screenshot_medium.png" +#define KVI_THEME_LARGE_SCREENSHOT_NAME "screenshot.png" + +#define QIMAGE_SCALE_MIN Qt::KeepAspectRatio + + +KviThemeInfo::KviThemeInfo() +: KviHeapObject() +{ +} + +KviThemeInfo::~KviThemeInfo() +{ +} + + + +bool KviThemeInfo::load(const QString &szThemeFileName) +{ + if(!KviFileUtils::fileExists(szThemeFileName)) + { + m_szLastError = __tr2qs("The theme information file does not exist"); + return false; + } + + KviConfigurationFile cfg(szThemeFileName,KviConfigurationFile::Read); + + cfg.setGroup(KVI_THEMEINFO_CONFIG_GROUP); + + m_szThemeEngineVersion = cfg.readEntry("ThemeEngineVersion","1.0.0"); + if(KviMiscUtils::compareVersions(m_szThemeEngineVersion,KVI_CURRENT_THEME_ENGINE_VERSION) < 0) + { + KviQString::sprintf(m_szLastError,__tr2qs("This KVIrc executable is too old for this theme (minimum theme engine version required is %Q while this theme engine has version %s)"),&m_szThemeEngineVersion,KVI_CURRENT_THEME_ENGINE_VERSION); + return false; // incompatible theme engine (will not work) + } + + // mandatory fields + m_szName = cfg.readEntry("Name",""); + + if(m_szName.isEmpty()) + { + m_szLastError = __tr2qs("Theme information file is not valid"); + return false; + } + + // optional fields + m_szVersion = cfg.readEntry("Version",""); + if(m_szVersion.isEmpty()) + m_szVersion = "?.?.?"; + m_szAuthor = cfg.readEntry("Author",""); + QString szUnknown = __tr2qs("Unknown"); + if(m_szAuthor.isEmpty()) + m_szAuthor = szUnknown; + m_szDescription = cfg.readEntry("Description",""); + m_szDate = cfg.readEntry("Date",""); + if(m_szDate.isEmpty()) + m_szDate = szUnknown; + m_szApplication = cfg.readEntry("Application",""); + if(m_szApplication.isEmpty()) + m_szApplication = szUnknown; + + return true; +} + +bool KviThemeInfo::save(const QString &szThemeFileName) +{ + KviConfigurationFile inf(szThemeFileName,KviConfigurationFile::Write); + + inf.clear(); + + inf.setGroup(KVI_THEMEINFO_CONFIG_GROUP); + + inf.writeEntry("Name",m_szName); + inf.writeEntry("Version",m_szVersion); + inf.writeEntry("Author",m_szAuthor); + inf.writeEntry("Description",m_szDescription); + inf.writeEntry("Date",m_szDate); + inf.writeEntry("ThemeEngineVersion",KVI_CURRENT_THEME_ENGINE_VERSION); + inf.writeEntry("Application","KVIrc " KVI_VERSION "." KVI_SOURCES_DATE); + + return true; +} + +bool KviThemeInfo::loadFromDirectory(const QString &szThemeDirectory,bool bIgnoreThemeData) +{ + QString szD = szThemeDirectory; + szD.append(KVI_PATH_SEPARATOR_CHAR); + szD.append(KVI_THEMEINFO_FILE_NAME); + + if(!load(szD)) + return false; // loading failed for some reason + + m_szAbsoluteDirectory = szThemeDirectory; + + if(bIgnoreThemeData) + return true; // assume success + + // check if themedata file exists + szD = szThemeDirectory; + szD.append(KVI_PATH_SEPARATOR_CHAR); + szD.append(KVI_THEMEDATA_FILE_NAME); + + return KviFileUtils::fileExists(szD); +} + +QString KviThemeInfo::smallScreenshotPath() +{ + QString ret; + if(!m_szAbsoluteDirectory.isEmpty()) + { + ret = m_szAbsoluteDirectory; + KviQString::ensureLastCharIs(ret,KVI_PATH_SEPARATOR_CHAR); + ret.append(KVI_THEME_SMALL_SCREENSHOT_NAME); + } + return ret; +} + +const QPixmap & KviThemeInfo::smallScreenshot() +{ + if(!m_pixScreenshotSmall.isNull())return m_pixScreenshotSmall; + + if(!m_szAbsoluteDirectory.isEmpty()) + { + QString szFileName = m_szAbsoluteDirectory; + KviQString::ensureLastCharIs(szFileName,KVI_PATH_SEPARATOR_CHAR); + szFileName.append(KVI_THEME_SMALL_SCREENSHOT_NAME); + QPixmap pix(szFileName); + if(!pix.isNull()) + { + m_pixScreenshotSmall = pix; + return m_pixScreenshotSmall; + } + // try to scale it from the large one (and save it by the way) + pix = mediumScreenshot(); + if(pix.isNull())return m_pixScreenshotSmall; + + if(pix.width() > 300 || pix.height() > 225) + { + QImage sbri = pix.toImage(); + pix = QPixmap::fromImage(sbri.scaled(300,225,QIMAGE_SCALE_MIN,Qt::SmoothTransformation)); + } + pix.save(szFileName,"PNG"); + + m_pixScreenshotSmall = pix; + return m_pixScreenshotSmall; + } + + return m_pixScreenshotSmall; +} + +const QPixmap & KviThemeInfo::mediumScreenshot() +{ + if(!m_pixScreenshotMedium.isNull())return m_pixScreenshotMedium; + + if(!m_szAbsoluteDirectory.isEmpty()) + { + QString szFileName = m_szAbsoluteDirectory; + KviQString::ensureLastCharIs(szFileName,KVI_PATH_SEPARATOR_CHAR); + szFileName.append(KVI_THEME_MEDIUM_SCREENSHOT_NAME); + QPixmap pix(szFileName); + if(!pix.isNull()) + { + m_pixScreenshotMedium = pix; + return m_pixScreenshotMedium; + } + // try to scale it from the large one (and save it by the way) + pix = largeScreenshot(); + if(pix.isNull())return m_pixScreenshotMedium; + + if(pix.width() > 600 || pix.height() > 450) + { + QImage sbri = pix.toImage(); + pix.fromImage(sbri.scaled(640,450,QIMAGE_SCALE_MIN,Qt::SmoothTransformation)); + } + + pix.save(szFileName,"PNG"); + + m_pixScreenshotMedium = pix; + return m_pixScreenshotMedium; + } + + return m_pixScreenshotMedium; +} + +const QPixmap & KviThemeInfo::largeScreenshot() +{ + if(!m_pixScreenshotLarge.isNull())return m_pixScreenshotLarge; + + if(!m_szAbsoluteDirectory.isEmpty()) + { + QString szFileName = m_szAbsoluteDirectory; + KviQString::ensureLastCharIs(szFileName,KVI_PATH_SEPARATOR_CHAR); + szFileName.append(KVI_THEME_LARGE_SCREENSHOT_NAME); + QPixmap pix(szFileName); + if(pix.isNull())return m_pixScreenshotLarge; + m_pixScreenshotLarge = pix; + } + return m_pixScreenshotLarge; +} + + +namespace KviTheme +{ + bool saveScreenshots(KviThemeInfo &options,const QString &szOriginalScreenshotPath) + { + QImage pix(szOriginalScreenshotPath); + if(pix.isNull()) + { + options.setLastError(__tr2qs("Failed to load the specified screenshot image")); + return false; + } + + QImage out; + + QString szScreenshotFileName = options.absoluteDirectory(); + if(szScreenshotFileName.isEmpty()) + { + options.setLastError(__tr2qs("Invalid option")); + return false; + } + + KviQString::ensureLastCharIs(szScreenshotFileName,KVI_PATH_SEPARATOR_CHAR); + szScreenshotFileName.append(KVI_THEME_LARGE_SCREENSHOT_NAME); + if(!pix.save(szScreenshotFileName,"PNG")) + { + options.setLastError(__tr2qs("Failed to save the screenshot image")); + return false; + } + + if(pix.width() > 600 || pix.height() > 450) + out = pix.scaled(640,450,QIMAGE_SCALE_MIN,Qt::SmoothTransformation); + else + out = pix; + + szScreenshotFileName = options.absoluteDirectory(); + KviQString::ensureLastCharIs(szScreenshotFileName,KVI_PATH_SEPARATOR_CHAR); + szScreenshotFileName.append(KVI_THEME_MEDIUM_SCREENSHOT_NAME); + if(!out.save(szScreenshotFileName,"PNG")) + { + options.setLastError(__tr2qs("Failed to save the screenshot image")); + return false; + } + + if(pix.width() > 300 || pix.height() > 225) + out = pix.scaled(300,225,QIMAGE_SCALE_MIN,Qt::SmoothTransformation); + else + out = pix; + + szScreenshotFileName = options.absoluteDirectory(); + KviQString::ensureLastCharIs(szScreenshotFileName,KVI_PATH_SEPARATOR_CHAR); + szScreenshotFileName.append(KVI_THEME_SMALL_SCREENSHOT_NAME); + if(!out.save(szScreenshotFileName,"PNG")) + { + options.setLastError(__tr2qs("Failed to save the screenshot image")); + return false; + } + + return true; + } +}; diff --git a/src/kvirc/kernel/KviTheme.h b/src/kvirc/kernel/KviTheme.h new file mode 100644 index 000000000..9c45df212 --- /dev/null +++ b/src/kvirc/kernel/KviTheme.h @@ -0,0 +1,170 @@ +#ifndef _KVI_THEME_H_ +#define _KVI_THEME_H_ + +//============================================================================= +// +// File : KviTheme.h +// Creation date : Mon Jan 08 2007 03:23:00 CEST by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2007-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviQString.h" +#include "KviHeapObject.h" +#include "kvi_fileextensions.h" + +#include + +#define KVI_THEMEINFO_FILE_NAME "themeinfo" KVI_FILEEXTENSION_CONFIG +#define KVI_THEMEDATA_FILE_NAME "themedata" KVI_FILEEXTENSION_CONFIG +#define KVI_THEMEINFO_CONFIG_GROUP "ThemeInfo" +#define KVI_THEMEDATA_CONFIG_GROUP "ThemeData" + +/// +/// The current theme engine version: bump up if you make INCOMPATIBLE +/// changes in the method of saving the theme. +/// +#define KVI_CURRENT_THEME_ENGINE_VERSION "1.0.0" + +/// +/// \class KviThemeInfo +/// +/// \brief A set of information about a KVIrc theme +/// +/// This object contains a set of information about +/// a theme that can be read and stored to a standard +/// KVIrc configuration file (which is usually named +/// themeinfo.kvc but this is not strictly necessary). +/// +class KVIRC_API KviThemeInfo : public KviHeapObject +{ +public: + KviThemeInfo(); + ~KviThemeInfo(); +protected: + QString m_szName; //< name of the theme + QString m_szVersion; //< version of the theme + QString m_szSubdirectory; //< subdirectory of $LOCALKVIRCDIR/themes where the theme is saved to (not always used) + QString m_szAbsoluteDirectory; //< absolute directory where the theme should be saved to (or is loaded from) + QString m_szAuthor; //< author of the theme + QString m_szDescription; //< description of the theme + QString m_szDate; //< theme creation date + QString m_szApplication; //< theme creation (KVIrc) version + QString m_szThemeEngineVersion; //< the theme engine version that saved this theme + + QString m_szLastError; //< reported when some function fails + + QPixmap m_pixScreenshotLarge; //< the large screenshot pixmap + QPixmap m_pixScreenshotMedium; //< the medium screenshot pixmap + QPixmap m_pixScreenshotSmall; //< the small screenshot pixmap +public: + /// + /// load data from a specified theme config file + /// + bool load(const QString &szThemeFileName); + /// + /// save the currently defined theme configuration in the specified file + /// + bool save(const QString &szThemeFileName); + + const QString & lastError(){ return m_szLastError; }; + void setLastError(const QString &szLastError){ m_szLastError = szLastError; }; + const QString & name(){ return m_szName; }; + void setName(const QString &szName){ m_szName = szName; }; + const QString & version(){ return m_szVersion; }; + void setVersion(const QString &szVersion){ m_szVersion = szVersion; }; + const QString & subdirectory(){ return m_szSubdirectory; }; + void setSubdirectory(const QString &szSubdirectory){ m_szSubdirectory = szSubdirectory; }; + const QString & absoluteDirectory(){ return m_szAbsoluteDirectory; }; + void setAbsoluteDirectory(const QString &szAbsoluteDirectory){ m_szAbsoluteDirectory = szAbsoluteDirectory; } + const QString & author(){ return m_szAuthor; }; + void setAuthor(const QString &szAuthor){ m_szAuthor = szAuthor; }; + const QString & description(){ return m_szDescription; }; + void setDescription(const QString &szDescription){ m_szDescription = szDescription; }; + const QString & date(){ return m_szDate; }; + void setDate(const QString &szDate){ m_szDate = szDate; }; + const QString & application(){ return m_szApplication; }; + void setApplication(const QString &szApplication){ m_szApplication = szApplication; }; + const QString & themeEngineVersion(){ return m_szThemeEngineVersion; }; + void setThemeEngineVersion(const QString &szThemeEngineVersion){ m_szThemeEngineVersion = szThemeEngineVersion; }; + + /// + /// Attempt to load a themeinfo.kvc file present in the specified directory. + /// This function will fail if the directory contains a valid themeinfo.kvc + /// file but no themedata.kvc file unless bIgnoreThemeData is set to true + /// + bool loadFromDirectory(const QString &szThemeDirectory,bool bIgnoreThemeData = false); + + /// + /// Attempt to load the theme screenshot from THEMEDIR/screenshot_*.png + /// This function will work only if the absoluteDirectory() of the theme + /// has been set, otherwise the returned pixmap will be null. + /// + const QPixmap & smallScreenshot(); + /// + /// Attempt to load the theme screenshot from THEMEDIR/screenshot_*.png + /// This function will work only if the absoluteDirectory() of the theme + /// has been set, otherwise the returned pixmap will be null. + /// + const QPixmap & mediumScreenshot(); + /// + /// Attempt to load the theme screenshot from THEMEDIR/screenshot_*.png + /// This function will work only if the absoluteDirectory() of the theme + /// has been set, otherwise the returned pixmap will be null. + /// + const QPixmap & largeScreenshot(); + /// + /// Attempt to load the theme screenshot from THEMEDIR/screenshot_*.png + /// This function will work only if the absoluteDirectory() of the theme + /// has been set, otherwise the returned pixmap will be null. + /// + QString smallScreenshotPath(); +}; + +namespace KviTheme +{ + /// + /// Attempt to load (apply) a theme in the specified directory + /// Will return true on success and false on failure. + /// On success this function will return the theme information in the buffer. + /// On failure this function will also set buffer.lastError() to a meaningful value + /// Note that for convenience this function is implemented in KviOptions.cpp + /// + bool KVIRC_API load(const QString &szThemeDir,KviThemeInfo &buffer); + /// + /// Save a theme given the specified options. + /// Will return true on success and false on failure. + /// On failure this function will also set options.lastError() to a meaningful value + /// This function requires both absoluteDirectory() and subdirectory() to be + /// set to the right values. In theory this function could save a theme + /// in a directory different than $KVIRC_LOCAL_DIR/themes/subdirectory + /// but this feature is actually unused. + /// Note that for convenience this function is implemented in KviOptions.cpp + /// + bool KVIRC_API save(KviThemeInfo &options); + /// + /// Save the theme screenshots in the given EXISTING directory and given + /// an existing screenshot on disk (usually in the tmp directory). + /// + bool KVIRC_API saveScreenshots(KviThemeInfo &options,const QString &szOriginalScreenshotPath); +} + + +#endif //_KVI_THEME_H_ diff --git a/src/kvirc/kernel/KviUserAction.cpp b/src/kvirc/kernel/KviUserAction.cpp new file mode 100644 index 000000000..1be5303cf --- /dev/null +++ b/src/kvirc/kernel/KviUserAction.cpp @@ -0,0 +1,43 @@ +//============================================================================= +// +// File : KviUserListView.cpp +// Creation date : Tue Mar 18 2003 13:36:12 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviUserAction.h" + +static int useraction_table[KVI_NUM_USERACTION_TYPES] = +{ + 25, // ACTION (typically human) + 25, // PRIVMSG + 25, // NOTICE + 20, // TOPIC + 5, // KICK + -5, // NICK + -20, // CHANMODE + -25, // JOIN + -25 // PART (this works only for channels and not for single users on channels) +}; + +int kvi_getUserActionTemperature(unsigned int uIdx) +{ + return useraction_table[uIdx]; +} diff --git a/src/kvirc/kernel/KviUserAction.h b/src/kvirc/kernel/KviUserAction.h new file mode 100644 index 000000000..c5b39f4e8 --- /dev/null +++ b/src/kvirc/kernel/KviUserAction.h @@ -0,0 +1,98 @@ +#ifndef _KVI_USERACTION_H_ +#define _KVI_USERACTION_H_ + +//============================================================================= +// +// File : KviUserAction.h +// Creation date : Tue Mar 18 2003 13:36:12 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviUserAction.h +* \author Szymon Stefanek +* \brief This file defines the user action "temperatures" +* +* The more "hot" is an action, the more humanity is in it +* +* \def KVI_USERACTION_ACTION The action 'action' +* \def KVI_USERACTION_PRIVMSG The action 'message' (channel message) +* \def KVI_USERACTION_NOTICE The action 'notice' +* \def KVI_USERACTION_TOPIC The action 'topic' +* \def KVI_USERACTION_KICK The action 'kick' +* \def KVI_USERACTION_NICK The action 'nick' +* \def KVI_USERACTION_CHANMODE The action 'mode' (channel mode) +* \def KVI_USERACTION_JOIN The action 'join' +* \def KVI_USERACTION_PART The action 'part' +* \def KVI_NUM_USERACTION_TYPES The number of actions' type +* +* These are the temperature levels for a single user on a channel +* +* \def KVI_MAX_TEMPERATURE Maximum: can't go above this +* \def KVI_HOT_TEMPERATURE Hot: human +* \def KVI_HALF_HOT_TEMPERATURE Half hot: signs of humanity +* \def KVI_MID_TEMPERATURE Mid: uncertain +* \def KVI_HALF_COLD_TEMPERATURE Half cold: automa ? +* \def KVI_COLD_TEMPERATURE Cold: bot +* \def KVI_MIN_TEMPERATURE Minimum: can't drop below this +*/ + +#include "kvi_settings.h" + +#define KVI_USERACTION_ACTION 0 +#define KVI_USERACTION_PRIVMSG 1 +#define KVI_USERACTION_NOTICE 2 +#define KVI_USERACTION_TOPIC 3 +#define KVI_USERACTION_KICK 4 +#define KVI_USERACTION_NICK 5 +#define KVI_USERACTION_CHANMODE 6 +#define KVI_USERACTION_JOIN 7 +#define KVI_USERACTION_PART 8 + +#define KVI_NUM_USERACTION_TYPES 9 + +#define KVI_MAX_TEMPERATURE 150 +#define KVI_HOT_TEMPERATURE 100 +#define KVI_HALF_HOT_TEMPERATURE 40 +#define KVI_MID_TEMPERATURE 0 +#define KVI_HALF_COLD_TEMPERATURE -40 +#define KVI_COLD_TEMPERATURE -100 +#define KVI_MIN_TEMPERATURE -150 + +// +// ACTION 30 +// NOTICE 25 +// PRIVMSG 25 +// TOPIC 20 +// KICK 10 +// OP 5 +// VOICE 5 +// DEOP -5 +// DEVOICE -5 +// UNBAN -15 +// BAN -20 +// CHANMODE -25 +// NICK -30 +// JOIN -30 +// + +extern KVIRC_API int kvi_getUserActionTemperature(unsigned int uIdx); + +#endif // _KVI_USERACTION_H_ diff --git a/src/kvirc/kernel/KviUserInput.cpp b/src/kvirc/kernel/KviUserInput.cpp new file mode 100644 index 000000000..c086990bc --- /dev/null +++ b/src/kvirc/kernel/KviUserInput.cpp @@ -0,0 +1,156 @@ +//============================================================================= +// +// File : KviUserInput.cpp +// Creation date : Sun 25 Sep 2005 05:27:57 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviUserInput.h" +#include "KviKvsVariantList.h" +#include "KviConsoleWindow.h" +#include "KviKvsScript.h" +#include "KviLocale.h" +#include "KviIrcConnection.h" +#include "KviIrcConnectionUserInfo.h" +#include "kvi_out.h" +#include "KviOptions.h" +#include "KviKvsEventTriggers.h" + +namespace KviUserInput +{ + bool parse(QString & szData, KviWindow * pWindow, const QString & szContext, bool bUserFriendlyCommandline) + { + const QChar * b = KviQString::nullTerminatedArray(szData); + const QChar * c = b; + if(!c)return true; // empty + + while(c->isSpace()) c++; + + if(!c->unicode()) + return true; // empty + + if(c->unicode() == '\\') + { + c++; + if(c->unicode() != '/') + c--; + } else { + if(c->unicode() == '/') + { + c++; + if(c->unicode() != '/') + { + szData.remove(0, c - b); + return parseCommand(szData,pWindow,szContext,bUserFriendlyCommandline); + } else { + // C++ comment, probably + c--; + } + } + } + + if(KVS_TRIGGER_EVENT_1_HALTED(KviEvent_OnTextInput,pWindow,szData)) + return true; // halted + + if(c != b) + szData.remove(0,c-b); + + parseNonCommand(szData,pWindow); + return true; + } + + bool parseCommand(const QString & szData, KviWindow * pWindow, const QString & szContext, bool bUserFriendlyCommandline) + { + if(bUserFriendlyCommandline) + { + static QString szUserFriendlyCommandlineContext(__tr2qs("commandline::userfriendly")); + + QString szCmd = szData; + KviQString::escapeKvs(&szCmd); + + KviKvsScript kvs(szContext.isEmpty() ? szUserFriendlyCommandlineContext : szContext,szCmd); + return (kvs.run(pWindow,0,0) != KviKvsScript::Error); + } else { + static QString szCommandlineContext(__tr2qs("commandline::kvs")); + + KviKvsScript kvs(szContext.isEmpty() ? szCommandlineContext : szContext,szData); + return (kvs.run(pWindow,0,0/*,KviKvsScript::AssumeLocals*/) != KviKvsScript::Error); + } + } + + void parseNonCommand(QString & szData, KviWindow * pWindow) + { + const QChar * aux = KviQString::nullTerminatedArray(szData); + const QChar * beg = aux; + + if(!beg) + return; // empty + + while(aux->unicode()) + { + while(aux->unicode() && (aux->unicode() != '\n')) + aux++; + + QString buf(beg, aux - beg); + if(aux->unicode() == '\n') + aux++; + beg = aux; + + if(buf.isEmpty()) + buf = " "; // avoid "No text to send" (d3vah) + + switch(pWindow->type()) + { + case KVI_WINDOW_TYPE_CONSOLE: + if(pWindow->connection()) + { + QByteArray data = pWindow->connection()->encodeText(buf); + + if(((KviConsole *)pWindow)->connection()->sendData(data.data())) + { + pWindow->output(KVI_OUT_RAW,"[RAW]: %Q",&buf); + return; + } + } + pWindow->output(KVI_OUT_PARSERERROR,__tr2qs("You are not connected to a server")); + break; + case KVI_WINDOW_TYPE_CHANNEL: + case KVI_WINDOW_TYPE_QUERY: + if(pWindow->connection()) + { + if(KVI_OPTION_BOOL(KviOption_boolExitAwayOnInput)) + { + if(pWindow->connection()->userInfo()->isAway()) + parseCommand("back",pWindow->console()); + } + } + pWindow->ownMessage(buf); + break; + case KVI_WINDOW_TYPE_DCCCHAT: + case KVI_WINDOW_TYPE_DCCVIDEO: + pWindow->ownMessage(buf); + break; + default: + // FIXME: Should pass the message somewhere ?.. a KviWindow handler ? + break; + } + } + } +}; diff --git a/src/kvirc/kernel/KviUserInput.h b/src/kvirc/kernel/KviUserInput.h new file mode 100644 index 000000000..bd3409a36 --- /dev/null +++ b/src/kvirc/kernel/KviUserInput.h @@ -0,0 +1,82 @@ +#ifndef _KVI_USERINPUT_H_ +#define _KVI_USERINPUT_H_ +//============================================================================= +// +// File : KviUserInput.h +// Creation date : Sun 25 Sep 2005 05:27:57 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviUserInput.h +* \author Szymon Stefanek +* \brief User input parsing +*/ + +#include "kvi_settings.h" +#include "KviQString.h" +#include "KviWindow.h" + +/** +* \namespace KviUserInput +* \brief Namespace that contains parsing function for the user input +*/ +namespace KviUserInput +{ + /** + * \brief Returns false if szData is a command and it fails to run + * \param szData The input data to parse + * \param pWindow The window associated to the input + * \param szContext The context associated to the input + * \param bUserFriendlyCommandline Whether the commandline is in user friendly mode + * \return bool + * \warning May destroy szData + */ + KVIRC_API bool parse(QString & szData, KviWindow * pWindow, const QString & szContext = KviQString::Empty, bool bUserFriendlyCommandline = false); + + /** + * \brief Returns true if the command run + * \param szData The input data to parse + * \param pWindow The window associated to the input + * \param szContext The context associated to the input + * \param bUserFriendlyCommandline Whether the commandline is in user friendly mode + * \return bool + */ + KVIRC_API bool parseCommand(const QString & szData, KviWindow * pWindow, const QString & szContext = KviQString::Empty, bool bUserFriendlyCommandline = false); + + /** + * \brief Parses the non command input data + * \param szData The input data to parse + * \param pWindow The window associated to the input + * \return void + */ + KVIRC_API void parseNonCommand(QString & szData, KviWindow * pWindow); + + /** + * \brief Escapes any kvs special character from a string + * \param szData The string to escape + * \return void + */ + KVIRC_API void escapeString(QString & szData); + + //bool parseCommandWithSingleArgument(const QString & szData, KviWindow * pWindow, const QString & szContext = KviQString::Empty); +} + +#endif //_KVI_USERINPUT_H_ diff --git a/src/kvirc/kernel/kvi_action.cpp b/src/kvirc/kernel/kvi_action.cpp deleted file mode 100644 index 37f041290..000000000 --- a/src/kvirc/kernel/kvi_action.cpp +++ /dev/null @@ -1,503 +0,0 @@ -//============================================================================= -// -// File : kvi_action.cpp -// Creation date : Sun 21 Nov 2004 03:36:34 by Szymon Stefanek -// -// This file is part of the KVIrc IRC Client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_action.h" -#include "kvi_customtoolbar.h" -#include "kvi_frame.h" -#include "kvi_irccontext.h" -#include "kvi_iconmanager.h" -#include "kvi_app.h" -#include "kvi_window.h" -#include "kvi_channel.h" -#include "kvi_query.h" -#include "KviTalPopupMenu.h" - -#include - -KviActionCategory::KviActionCategory(const QString & szName, const QString & szVisibleName, const QString & szDescription) -: m_szName(szName), m_szVisibleName(szVisibleName), m_szDescription(szDescription) -{ -} - -KviActionCategory::~KviActionCategory() -{ -} - - -KviAction::KviAction(QObject * pParent, const QString & szName, const QString & szVisibleName, const QString & szDescription, KviActionCategory * pCategory, const QString & szBigIconId, const QString & szSmallIconId, unsigned int uFlags, const QString & szKeySequence) -: QObject(pParent),m_szName(szName),m_szVisibleName(szVisibleName),m_szDescription(szDescription),m_pCategory(pCategory),m_szBigIconId(szBigIconId),m_szSmallIconId(szSmallIconId),m_pWidgetList(NULL),m_uInternalFlags(KviAction::Enabled),m_uFlags(uFlags),m_szKeySequence(szKeySequence),m_pAccel(NULL) -{ -} - -KviAction::~KviAction() -{ - if(m_pWidgetList) - { - for(QWidget * pWidget = m_pWidgetList->first(); pWidget; pWidget = m_pWidgetList->next()) - disconnect(pWidget,SIGNAL(destroyed()),this,SLOT(widgetDestroyed())); - m_pWidgetList->setAutoDelete(true); - delete m_pWidgetList; - } -} - -const QString & KviAction::visibleName() -{ - return m_szVisibleName; -} - -const QString & KviAction::description() -{ - return m_szDescription; -} - -bool KviAction::isKviUserActionNeverOverrideThis() -{ - return false; -} - -void KviAction::registerAccelerator() -{ - if(!m_szKeySequence.isEmpty()) - { - m_pAccel = new QShortcut(m_szKeySequence,g_pFrame,0,0,Qt::ApplicationShortcut); - connect(m_pAccel,SIGNAL(activated()),this,SLOT(activate())); - //no way to have Ctrl+Alt+Key events fired as no-ambiguous, probably qt bug - connect(m_pAccel,SIGNAL(activatedAmbiguously()),this,SLOT(activate())); - } -} - -void KviAction::unregisterAccelerator() -{ - if(m_pAccel != 0) - { - if(g_pFrame) - g_pFrame->releaseShortcut(m_pAccel->id()); - m_pAccel = 0; - } -} - -void KviAction::setEnabled(bool bEnabled) -{ - if(bEnabled) - m_uInternalFlags |= KviAction::Enabled; - else - m_uInternalFlags &= ~KviAction::Enabled; - - if(m_pWidgetList) - { - if(bEnabled) - { - for(QWidget * pWidget = m_pWidgetList->first(); pWidget; pWidget = m_pWidgetList->next()) - { - if(!pWidget->isEnabled()) - pWidget->setEnabled(true); - } - } else { - for(QWidget * pWidget = m_pWidgetList->first(); pWidget; pWidget = m_pWidgetList->next()) - { - if(pWidget->isEnabled()) - pWidget->setEnabled(false); - } - } - } -} - -int KviAction::validateFlags(int iFlagsToValidate) -{ - if(iFlagsToValidate & EnableAtLogin) - iFlagsToValidate |= NeedsConnection; - if(iFlagsToValidate & NeedsConnection) - iFlagsToValidate |= NeedsContext; - if(iFlagsToValidate & WindowOnlyIfUsersSelected) - { - if(!(iFlagsToValidate & InternalWindowMask)) - iFlagsToValidate &= ~WindowOnlyIfUsersSelected; - } - return iFlagsToValidate; -} - -QPixmap * KviAction::smallIcon() -{ - if(m_szSmallIconId.isEmpty()) - return NULL; - return g_pIconManager->getImage(m_szSmallIconId); -} - -QPixmap * KviAction::bigIcon() -{ - if(m_szBigIconId.isEmpty()) - return NULL; - return g_pIconManager->getImage(m_szBigIconId); -} - -void KviAction::setup() -{ - connect(g_pApp,SIGNAL(reloadImages()),this,SLOT(reloadImages())); - if(m_uFlags & InternalWindowMask) - { - connect(g_pFrame,SIGNAL(activeWindowChanged()),this,SLOT(activeWindowChanged())); - if((m_uFlags & WindowOnlyIfUsersSelected) && (m_uFlags & (WindowChannel | WindowConsole | WindowQuery))) - connect(g_pFrame,SIGNAL(activeWindowSelectionStateChanged(bool)),this,SLOT(activeWindowSelectionStateChanged(bool))); - activeWindowChanged(); - } else { - if(m_uFlags & NeedsConnection) - { - connect(g_pFrame,SIGNAL(activeContextChanged()),this,SLOT(activeContextChanged())); - connect(g_pFrame,SIGNAL(activeContextStateChanged()),this,SLOT(activeContextStateChanged())); - KviIrcContext * pContext = g_pFrame->activeContext(); - if(!pContext) - setEnabled(false); - else { - switch(pContext->state()) - { - case KviIrcContext::LoggingIn: - setEnabled(m_uFlags & EnableAtLogin); - break; - case KviIrcContext::Connected: - setEnabled(true); - break; - default: - setEnabled(false); - break; - } - } - } else { - if(m_uFlags & NeedsContext) - { - connect(g_pFrame,SIGNAL(activeContextChanged()),this,SLOT(activeContextChanged())); - if(!g_pFrame->activeContext()) - setEnabled(false); - else - setEnabled(true); - } - } - } - - m_uInternalFlags |= KviAction::SetupDone; -} - - -void KviAction::reloadImages() -{ - if(!m_pWidgetList) - return; - QPixmap * pPix = bigIcon(); - for(QWidget * pWidget = m_pWidgetList->first(); pWidget; pWidget = m_pWidgetList->next()) - { - if(pWidget->inherits("QToolButton")) - ((QToolButton *)pWidget)->setIcon(pPix ? *pPix : QPixmap()); - } -} - -void KviAction::activeWindowChanged() -{ - if(m_uFlags & NeedsContext) - { - if(!g_pFrame->activeContext()) - { - if(isEnabled()) - setEnabled(false); - return; - } - } - - if(m_uFlags & NeedsConnection) - { - switch(g_pFrame->activeContext()->state()) - { - case KviIrcContext::LoggingIn: - if(!(m_uFlags & EnableAtLogin)) - { - if(isEnabled()) - setEnabled(false); - return; - } - break; - case KviIrcContext::Connected: - // this is ok - break; - default: - if(isEnabled()) - setEnabled(false); - return; - break; - } - } - - if(!g_pActiveWindow) - { - if(isEnabled()) - setEnabled(false); - return; - } - - switch(g_pActiveWindow->type()) - { - case KVI_WINDOW_TYPE_CONSOLE: - if(m_uFlags & WindowConsole) - { - if(m_uFlags & WindowOnlyIfUsersSelected) - { - bool bEnabled = ((KviConsole *)g_pActiveWindow)->selectedCount() > 0; - if(bEnabled != isEnabled()) - setEnabled(bEnabled); - } else { - if(!isEnabled()) - setEnabled(true); - } - } else { - if(isEnabled()) - setEnabled(false); - } - break; - case KVI_WINDOW_TYPE_CHANNEL: - if(m_uFlags & WindowChannel) - { - if(m_uFlags & WindowOnlyIfUsersSelected) - { - bool bEnabled = ((KviChannel *)g_pActiveWindow)->selectedCount() > 0; - if(bEnabled != isEnabled()) - setEnabled(bEnabled); - } else { - if(!isEnabled()) - setEnabled(true); - } - } else { - if(isEnabled()) - setEnabled(false); - } - break; - case KVI_WINDOW_TYPE_QUERY: - if(m_uFlags & WindowQuery) - { - if(m_uFlags & WindowOnlyIfUsersSelected) - { - bool bEnabled = ((KviQuery *)g_pActiveWindow)->selectedCount() > 0; - if(bEnabled != isEnabled()) - setEnabled(bEnabled); - } else { - if(!isEnabled()) - setEnabled(true); - } - } else { - if(isEnabled()) - setEnabled(false); - } - break; - case KVI_WINDOW_TYPE_DCCCHAT: - if(m_uFlags & WindowDccChat) - { - if(!isEnabled()) - setEnabled(true); - } else { - if(isEnabled()) - setEnabled(false); - } - break; - default: - if(m_uFlags & InternalWindowMask) - { - if(isEnabled()) - setEnabled(false); - } else { - if(!isEnabled()) - setEnabled(true); - } - break; - } -} - -void KviAction::activeWindowSelectionStateChanged(bool bSelectedNow) -{ - // we jump here ONLY if m_uFlags & WindowOnlyIfUsersSelected - // and thus also m_uFlags & InternalWindowMask - switch(g_pActiveWindow->type()) - { - case KVI_WINDOW_TYPE_CONSOLE: - if(m_uFlags & WindowConsole) - { - if(bSelectedNow != isEnabled()) - setEnabled(bSelectedNow); - } else { - if(isEnabled()) - setEnabled(false); - } - break; - case KVI_WINDOW_TYPE_CHANNEL: - if(m_uFlags & WindowChannel) - { - if(bSelectedNow != isEnabled()) - setEnabled(bSelectedNow); - } else { - if(isEnabled()) - setEnabled(false); - } - break; - case KVI_WINDOW_TYPE_QUERY: - if(m_uFlags & WindowQuery) - { - if(bSelectedNow != isEnabled()) - setEnabled(bSelectedNow); - } else { - if(isEnabled()) - setEnabled(false); - } - break; - case KVI_WINDOW_TYPE_DCCCHAT: - if(m_uFlags & WindowDccChat) - { - if(!isEnabled()) - setEnabled(true); - } else { - if(isEnabled()) - setEnabled(false); - } - break; - default: - if(isEnabled()) - setEnabled(false); - break; - } -} - -void KviAction::activeContextChanged() -{ - // works only if NeedsContext is specified! - KviIrcContext * pContext = g_pFrame->activeContext(); - if(pContext) - { - if(m_uFlags & NeedsConnection) - activeContextStateChanged(); - else - if(!isEnabled()) - setEnabled(true); - } else { - if(isEnabled()) - setEnabled(false); - } -} - -void KviAction::activeContextStateChanged() -{ - KviIrcContext * pContext = g_pFrame->activeContext(); - if(pContext) - { - switch(pContext->state()) - { - case KviIrcContext::Idle: - case KviIrcContext::Connecting: - if(isEnabled()) - setEnabled(false); - break; - case KviIrcContext::LoggingIn: - if(m_uFlags & EnableAtLogin) - { - if(!isEnabled()) - setEnabled(true); - } else { - if(isEnabled()) - setEnabled(false); - } - break; - case KviIrcContext::Connected: - if(!isEnabled()) - setEnabled(true); - break; - default: - if(isEnabled()) - setEnabled(false); - break; - } - } else { - if(isEnabled()) - setEnabled(false); - } -} - -bool KviAction::addToPopupMenu(KviTalPopupMenu * pMenu) -{ - if(!setupDone()) - setup(); - QPixmap * pPix = smallIcon(); - int iId; - QString szTmp = visibleName(); - - if(!m_szKeySequence.isEmpty()) - szTmp += '\t' + m_szKeySequence; - - if(pPix) - iId = pMenu->insertItem(*pPix,szTmp,this,SLOT(activate())); - else - iId = pMenu->insertItem(szTmp,this,SLOT(activate())); - - if(!isEnabled()) - pMenu->setItemEnabled(iId,false); - return true; -} - -void KviAction::widgetDestroyed() -{ - if(!m_pWidgetList) - return; - QWidget * pWidget = (QWidget *)sender(); - m_pWidgetList->removeRef(pWidget); -} - -void KviAction::registerWidget(QWidget * pWidget) -{ - connect(pWidget,SIGNAL(destroyed()),this,SLOT(widgetDestroyed())); - if(!m_pWidgetList) - { - m_pWidgetList = new KviPointerList; - m_pWidgetList->setAutoDelete(false); - } - m_pWidgetList->append(pWidget); -} - -QWidget * KviAction::addToCustomToolBar(KviCustomToolBar * pParentToolBar) -{ - if(!setupDone()) - setup(); - QPixmap * pPix = bigIcon(); - QToolButton * pTool = new QToolButton(pParentToolBar); - - pTool->setIcon(pPix ? *pPix : QPixmap()); - pTool->setText(visibleName()); - pTool->setToolTip(visibleName()); - pTool->setObjectName(m_szName.toUtf8().data()); - connect(pTool,SIGNAL(clicked()),this,SLOT(activate())); - - QAction * pAction = pParentToolBar->addWidget(pTool); - pAction->setVisible(true); - if(!isEnabled()) - pTool->setEnabled(false); - registerWidget(pTool); - return pTool; -} - -void KviAction::activate() -{ - if(isEnabled()) - emit activated(); -} diff --git a/src/kvirc/kernel/kvi_action.h b/src/kvirc/kernel/kvi_action.h deleted file mode 100644 index e21af1caa..000000000 --- a/src/kvirc/kernel/kvi_action.h +++ /dev/null @@ -1,375 +0,0 @@ -#ifndef _KVI_ACTION_H_ -#define _KVI_ACTION_H_ -//============================================================================= -// -// File : kvi_action.h -// Creation date : Sun 21 Nov 2004 03:36:34 by Szymon Stefanek -// -// This file is part of the KVIrc IRC Client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_action.h -* \author Szymon Stefanek -* \brief Actions handling -*/ - -#include "kvi_settings.h" -#include "KviPointerList.h" - -#include - -class QShortcut; -class QPixmap; -class KviTalPopupMenu; -class KviCustomToolBar; - -/** -* \class KviActionCategory -* \brief Holds the categories of an action -* -* Known categories are: general (or empty), irc, script -*/ -class KVIRC_API KviActionCategory -{ -protected: - QString m_szName; - QString m_szVisibleName; - QString m_szDescription; -public: - /** - * \brief Constructs an action category object - * \param szName The name of the category - * \param szVisibleName Permanent visible name, visible at least in the action drawer - * \param szDescription Description of the category - * \return KviActionCategory - */ - KviActionCategory(const QString & szName, const QString & szVisibleName, const QString & szDescription); - - /** - * \brief Destroys an action category object - */ - ~KviActionCategory(); -public: - /** - * \brief Returns the name of the category - * \return const QString & - */ - const QString & name(){ return m_szName; }; - - /** - * \brief Returns the visible name of the category - * \return const QString & - */ - const QString & visibleName(){ return m_szVisibleName; }; - - /** - * \brief Returns the description of the category - * \return const QString & - */ - const QString & description(){ return m_szDescription; }; -}; - -/** -* \class KviAction -* \brief Defines an action inside KVIrc -*/ -class KVIRC_API KviAction : public QObject -{ - friend class KviActionManager; - Q_OBJECT -public: - /** - * \enum InternalFlags - * \brief Holds the internal flags of an action - */ - enum InternalFlags { - Enabled = 1, /**< the action is enabled */ - SetupDone = 2 /**< the setup of the action is done */ - }; - - /** - * \enum Flags - * \brief Holds the flags of an action - */ - enum Flags { - NeedsContext = 1, /**< the action needs a context */ - NeedsConnection = 2, /**< the action needs a connection; implies NeedsContext */ - WindowConsole = 4, /**< the action is bound to a console window */ - WindowChannel = 8, /**< the action is bound to a channel window */ - WindowQuery = 16, /**< the action is bound to a query window */ - WindowDccChat = 32, /**< the action is bound to a DCC Chat window */ - InternalWindowMask = WindowConsole | WindowChannel | WindowQuery | WindowDccChat, /**< the action is bound to a window */ - EnableAtLogin = 64, /**< the action is enabled at login; implies NeedsConnection */ - WindowOnlyIfUsersSelected = 128 /**< the action is bound to a window only if it's selected by the user; implies at least one of WindowConsole | WindowChannel | WindowQuery */ - }; -public: - /** - * \brief Constructs the action object - * \param pParent The parent object - * - * It can be 0, but using a QObject will help in deleting this action :) - * \param szName Internal name of this action, in form [module.]name - * - * The action name is INTERNAL: it should be never shown to the user. If it contains a dot - * then the part before the dot is considered to be a module name to be loaded when the - * module is loaded. - * \param szVisibleName Permanent visible name, visible at least in the action drawer - * \param szDescription What this action does - * \param pCategory One of KviActionManager::category*() or 0 (default category), not owned! - * \param szBigIconId The big icon associated to the action (32x32) - * \param szSmallIconId The small icon associated to the action (16x16) - * \param uFlags The flags of the action, like needs and configuration - * \param szKeySequence The shortcut to activate the action - * \return KviAction - */ - KviAction(QObject * pParent, const QString & szName, const QString & szVisibleName, const QString & szDescription, KviActionCategory * pCategory = NULL, const QString & szBigIconId = QString(), const QString & szSmallIconId = QString(), unsigned int uFlags = 0, const QString & szKeySequence = QString()); - - /** - * \brief Destroys the action object - */ - virtual ~KviAction(); -protected: - QString m_szName; - QString m_szVisibleName; - QString m_szDescription; - KviActionCategory * m_pCategory; - QString m_szBigIconId; - QString m_szSmallIconId; - KviPointerList * m_pWidgetList; - unsigned short int m_uInternalFlags; - unsigned int m_uFlags; - QString m_szKeySequence; - QShortcut * m_pAccel; -public: - /** - * \brief Validates the flags of the action - * \param iFlagsToValidate The flags to validate - * \return int - */ - static int validateFlags(int iFlagsToValidate); - - /** - * \brief Returns the name of the action - * \return const QString & - */ - const QString & name() const { return m_szName; }; - - /** - * \brief Returns the visible name of the action - * \return const QString & - */ - virtual const QString & visibleName(); - - /** - * \brief Returns the description of the action - * \return const QString & - */ - virtual const QString & description(); - - /** - * \brief Returns the shortcut of the action - * \return const QString & - */ - const QString & keySequence() const { return m_szKeySequence; }; - - /** - * \brief Returns the id of the big icon associated to the action - * \return const QString & - */ - const QString & bigIconId() const { return m_szBigIconId; }; - - /** - * \brief Returns the id of the small icon associated to the action - * \return const QString & - */ - const QString & smallIconId() const { return m_szSmallIconId; }; - - /** - * \brief Returns the category of the action - * \return const QString & - */ - KviActionCategory * category() const { return m_pCategory; }; - - /** - * \brief Returns true if the action is enabled - * \return bool - */ - bool isEnabled() const { return (m_uInternalFlags & KviAction::Enabled); }; - - /** - * \brief Returns the flag associated to the action - * \return unsigned int - */ - unsigned int flags(){ return m_uFlags; }; - - /** - * \brief Returns true if the action is user-defined - * \warning By default, this function returns always false - * \return bool - */ - virtual bool isKviUserActionNeverOverrideThis(); - - /** - * \brief Enables the action - * \param bEnabled Whether to enable the action - * \return void - */ - virtual void setEnabled(bool bEnabled); - - /** - * \brief Returns the small icon associated to the action - * \return const QString & - */ - QPixmap * smallIcon(); - - /** - * \brief Returns the big icon associated to the action - * \return const QString & - */ - QPixmap * bigIcon(); - - /** - * \brief Adds the action to the given popup - * \param pMenu The menu where to add the action - * \return bool - */ - virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); - - /** - * \brief Adds the action to the given toolbar - * \param pParentToolBar The toolbar where to add the action - * \return QWidget * - */ - virtual QWidget * addToCustomToolBar(KviCustomToolBar * pParentToolBar); - - /** - * \brief Destroys itself. Maybe the best function in the whole APIs :) - * \return void - */ - void suicide(){ delete this; }; -protected: - /** - * \brief Returns true if the setup is finished - * \note Called once before the FIRST button or menu item is created - * \return bool - */ - bool setupDone() const { return (m_uInternalFlags & KviAction::SetupDone); }; - - /** - * \brief Enables or disables the action upon starting KVIrc - * \return void - */ - virtual void setup(); - - /** - * \brief Returns the list of widgets associated to the action - * \return KviPointerList * - */ - KviPointerList * widgetList(){ return m_pWidgetList; }; - - /** - * \brief Registers the action shortcut in the application - * \return void - */ - void registerAccelerator(); - - /** - * \brief Removes the action shortcut from the application - * \return void - */ - void unregisterAccelerator(); - - /** - * \brief Adds the widget to the list - * \param pWidget The widget to add - * \return void - */ - void registerWidget(QWidget * pWidget); -public slots: - /** - * \brief Activates the action - * - * It's called when the user activates the action clicking on the toolbar, the menu or by - * hitting its shortcut. - * \return void - */ - virtual void activate(); -protected slots: - /** - * \brief Removes the widget from the list - * - * Called when the widget is being destroyed - * \return void - */ - virtual void widgetDestroyed(); - - /** - * \brief Reloads the images - * - * Called when the application wants to refresh the images in the toolbar - * \return void - */ - virtual void reloadImages(); - - /** - * \brief Enables or disables the action upon checking the active context - * - * If the context doesn't exist, the action is disabled - * - * Called when the frame changes the active context. - * \note It works only if NeedsContext is specified - * \return void - */ - virtual void activeContextChanged(); - - /** - * \brief Enables or disables the action upon checking the active context - * - * Called when the frame changes the state of the context - * \return void - */ - virtual void activeContextStateChanged(); - - /** - * \brief Enables or disables the action upon checking the active window - * - * Called when the frame changes the active window. - * \return void - */ - virtual void activeWindowChanged(); - - /** - * \brief Enables or disables the action upon checking the active window - * - * Called when the frame changes the active window. - * \note We jump here ONLY if m_uFlags & WindowOnlyIfUsersSelected and thus also - * m_uFlags & InternalWindowMask - * \return void - */ - virtual void activeWindowSelectionStateChanged(bool bSelectedNow); -signals: - /** - * \brief Emitted when the action is being activated - * \return void - */ - void activated(); -}; - -#endif // _KVI_ACTION_H_ diff --git a/src/kvirc/kernel/kvi_actionmanager.cpp b/src/kvirc/kernel/kvi_actionmanager.cpp deleted file mode 100644 index 4b6803b50..000000000 --- a/src/kvirc/kernel/kvi_actionmanager.cpp +++ /dev/null @@ -1,318 +0,0 @@ -//============================================================================= -// -// File : kvi_actionmanager.cpp -// Creation date : Sun 21 Nov 2004 03:37:57 by Szymon Stefanek -// -// This file is part of the KVIrc IRC Client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_actionmanager.h" -#include "kvi_modulemanager.h" -#include "kvi_coreactions.h" -#include "kvi_customtoolbar.h" -#include "kvi_customtoolbarmanager.h" -#include "kvi_app.h" -#include "KviLocale.h" -#include "kvi_kvs_useraction.h" -#include "KviConfigurationFile.h" -#include "KviQString.h" -#include "kvi_frame.h" - -KviActionManager * KviActionManager::m_pInstance = 0; -KviActionCategory * KviActionManager::m_pCategoryIrc = 0; -KviActionCategory * KviActionManager::m_pCategoryGeneric = 0; -KviActionCategory * KviActionManager::m_pCategorySettings = 0; -KviActionCategory * KviActionManager::m_pCategoryScripting = 0; -KviActionCategory * KviActionManager::m_pCategoryGUI = 0; -KviActionCategory * KviActionManager::m_pCategoryChannel = 0; -KviActionCategory * KviActionManager::m_pCategoryTools = 0; -bool KviActionManager::m_bCustomizingToolBars = false; -KviCustomToolBar * KviActionManager::m_pCurrentToolBar = 0; -// kvi_coreactions.cpp -extern void register_core_actions(KviActionManager *); - -KviActionManager::KviActionManager() -: QObject() -{ - m_pActions = new KviPointerHashTable(101); - m_pActions->setAutoDelete(false); - - m_pCategories = new KviPointerHashTable(17,false); - m_pCategories->setAutoDelete(true); - -#define CATEGORY(__var,__name,__vname,__descr) \ - __var = new KviActionCategory(__name,__vname,__descr); \ - m_pCategories->replace(__name,__var) - - CATEGORY(m_pCategoryIrc,"irc",__tr2qs("IRC"),__tr2qs("IRC Context related actions")); - CATEGORY(m_pCategoryGeneric,"generic",__tr2qs("Generic"),__tr2qs("Generic actions")); - CATEGORY(m_pCategorySettings,"settings",__tr2qs("Settings"),__tr2qs("Actions related to settings")); - CATEGORY(m_pCategoryScripting,"scripting",__tr2qs("Scripting"),__tr2qs("Scripting related actions")); - CATEGORY(m_pCategoryGUI,"gui",__tr2qs("GUI"),__tr2qs("Actions related to the Graphic User Interface")); - CATEGORY(m_pCategoryChannel,"channel",__tr2qs("Channel"),__tr2qs("IRC Channel related actions")); - CATEGORY(m_pCategoryTools,"tools",__tr2qs("Tools"),__tr2qs("Actions that will appear in the \"Tools\" menu")); - - m_bCustomizingToolBars = false; - m_pCurrentToolBar = 0; - m_bCoreActionsRegistered = false; -} - -KviActionManager::~KviActionManager() -{ - // the customizeToolBars dialog has been already - // destroyed since the module manager has already - // killed all the modules at this point... - //KviActionDialog::cleanup(); - - KviPointerHashTableIterator it(*m_pActions); - while(KviAction * a = it.current()) - { - disconnect(a,SIGNAL(destroyed()),this,SLOT(actionDestroyed())); - ++it; - } - delete m_pActions; - - delete m_pCategories; -} - -void KviActionManager::load(const QString &szFileName) -{ - KviConfigurationFile cfg(szFileName,KviConfigurationFile::Read); - - KviConfigurationFileIterator it(*(cfg.dict())); - while(it.current()) - { - cfg.setGroup(it.currentKey()); - KviKvsUserAction * a = new KviKvsUserAction(this); - if(a->load(&cfg))registerAction(a); - else delete a; - ++it; - } -} - -void KviActionManager::save(const QString &szFileName) -{ - KviConfigurationFile cfg(szFileName,KviConfigurationFile::Write); - cfg.clear(); - - KviPointerHashTableIterator it(*m_pActions); - while(KviAction * a = it.current()) - { - if(a->isKviUserActionNeverOverrideThis()) - { - cfg.setGroup(a->name()); - ((KviKvsUserAction *)a)->save(&cfg); - } - ++it; - } -} - -void KviActionManager::killAllKvsUserActions() -{ - KviPointerList dying; - dying.setAutoDelete(true); - - KviPointerHashTableIterator it(*m_pActions); - while(KviAction * a = it.current()) - { - if(a->isKviUserActionNeverOverrideThis()) - { - dying.append(((KviKvsUserAction *)a)); - } - ++it; - } - - dying.clear(); // bye :) -} - - -bool KviActionManager::coreActionExists(const QString &szName) -{ - KviAction *a = m_pActions->find(szName); - if(a)return (!a->isKviUserActionNeverOverrideThis()); - return false; -} - -QString KviActionManager::nameForAutomaticAction(const QString &szTemplate) -{ - QString ret; - - int i = 1; - do { - KviQString::sprintf(ret,"%Q%d",&szTemplate,i); - i++; - } while(m_pActions->find(ret)); - - return ret; -} - -void KviActionManager::emitRemoveActionsHintRequest() -{ - emit removeActionsHintRequest(); -} - -KviActionCategory * KviActionManager::category(const QString &szName) -{ - if(!szName.isEmpty()) - { - KviActionCategory * c = m_pCategories->find(szName); - if(c)return c; - } - return m_pCategoryGeneric; -} - -void KviActionManager::customizeToolBarsDialogCreated() -{ - m_bCustomizingToolBars = true; - m_pCurrentToolBar = KviCustomToolBarManager::instance()->firstExistingToolBar(); - if(m_pCurrentToolBar)m_pCurrentToolBar->update(); - emit beginCustomizeToolBars(); -} - -void KviActionManager::customizeToolBarsDialogDestroyed() -{ - m_bCustomizingToolBars = false; - emit endCustomizeToolBars(); - if(m_pCurrentToolBar) - { - m_pCurrentToolBar->update(); - m_pCurrentToolBar = 0; - } - g_pApp->saveToolBars(); -} - -void KviActionManager::setCurrentToolBar(KviCustomToolBar * t) -{ - if(m_pCurrentToolBar == t)return; - KviCustomToolBar * old = m_pCurrentToolBar; - m_pCurrentToolBar = t; - if(old)old->update(); - if(!m_pCurrentToolBar && m_bCustomizingToolBars) - m_pCurrentToolBar = KviCustomToolBarManager::instance()->firstExistingToolBar(); - if(m_pCurrentToolBar)m_pCurrentToolBar->update(); - emit currentToolBarChanged(); -} - -void KviActionManager::loadAllAvailableActions() -{ - // make sure that the core actions are registered now - if(!KviActionManager::instance()->m_bCoreActionsRegistered) - { - register_core_actions(KviActionManager::instance()); - KviActionManager::instance()->m_bCoreActionsRegistered = true; - } - g_pModuleManager->loadModulesByCaps("action"); -} - -void KviActionManager::init() -{ - if(!m_pInstance)m_pInstance = new KviActionManager(); -} - -void KviActionManager::done() -{ - if(m_pInstance) - { - delete m_pInstance; - m_pInstance = 0; - } -} - -void KviActionManager::delayedRegisterAccelerators() -{ - KviPointerHashTableIterator it(*m_pActions); - while(KviAction * a = it.current()) - { - a->registerAccelerator(); - ++it; - } -} - -bool KviActionManager::registerAction(KviAction * a) -{ - if(m_pActions->find(a->name()))return false; - connect(a,SIGNAL(destroyed()),this,SLOT(actionDestroyed())); - m_pActions->insert(a->name(),a); - if(g_pFrame)a->registerAccelerator(); // otherwise it is delayed! - return true; -} - -void KviActionManager::actionDestroyed() -{ - KviAction * a = (KviAction *)sender(); - m_pActions->remove(a->name()); -} - -bool KviActionManager::unregisterAction(const QString &szName) -{ - KviAction * a = m_pActions->find(szName); - if(!a)return false; - disconnect(a,SIGNAL(destroyed()),this,SLOT(actionDestroyed())); - a->unregisterAccelerator(); - return m_pActions->remove(szName); -} - -KviAction * KviActionManager::getAction(const QString &szName) -{ - KviAction * a = m_pActions->find(szName); - if(a)return a; - int idx = szName.indexOf('.'); - if(idx < 0) - { - // backward compatibility: try to lookup the name with the kvirc. prefix - QString s = "kvirc."; - s += szName; - return m_pActions->find(s); - } - if((idx == 5) && (!m_bCoreActionsRegistered)) - { - // the core actions are all like kvirc.name - // so the dot is at poisition 5 (6th char) - // the first requested core action will trigger this - // the nice thing is that we will probably already have a frame when - // the core actions are registered thus stuff like mdiManager() can be accessed... - if(szName.left(5) == "kvirc") - { - register_core_actions(this); - m_bCoreActionsRegistered = true; - a = m_pActions->find(szName); - return a; - } - } - // try to preload the module that might register this action... - QString szModule = szName.left(idx); - if(!g_pModuleManager->getModule(szModule))return 0; - return m_pActions->find(szName); -} - -void KviActionManager::listActionsByCategory(const QString &szCatName,KviPointerList * pBuffer) -{ - loadAllAvailableActions(); - KviActionCategory * pCat = category(szCatName); - pBuffer->setAutoDelete(false); - pBuffer->clear(); - if(!pCat)return; - KviPointerHashTableIterator it(*m_pActions); - while(KviAction * a = it.current()) - { - if(a->category() == pCat) - pBuffer->append(a); - ++it; - } -} diff --git a/src/kvirc/kernel/kvi_actionmanager.h b/src/kvirc/kernel/kvi_actionmanager.h deleted file mode 100644 index ad3dca071..000000000 --- a/src/kvirc/kernel/kvi_actionmanager.h +++ /dev/null @@ -1,118 +0,0 @@ -#ifndef _KVI_ACTIONMANAGER_H_ -#define _KVI_ACTIONMANAGER_H_ -//============================================================================= -// -// File : kvi_actionmanager.h -// Creation date : Sun 21 Nov 2004 03:37:57 by Szymon Stefanek -// -// This file is part of the KVIrc IRC Client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "kvi_action.h" -#include "KviPointerHashTable.h" - -#include - -class KviActionDrawer; -class KviCustomToolBar; - -class KVIRC_API KviActionManager : public QObject -{ - friend class KviActionDrawer; - friend class KviCustomizeToolBarsDialog; - friend class KviCustomToolBar; - friend class KviFrame; - Q_OBJECT -public: - KviActionManager(); - ~KviActionManager(); -protected: - static KviActionManager * m_pInstance; - KviPointerHashTable * m_pActions; - KviPointerHashTable * m_pCategories; - static bool m_bCustomizingToolBars; - - // action categories - static KviActionCategory * m_pCategoryIrc; - static KviActionCategory * m_pCategoryGeneric; - static KviActionCategory * m_pCategorySettings; - static KviActionCategory * m_pCategoryScripting; - static KviActionCategory * m_pCategoryGUI; - static KviActionCategory * m_pCategoryChannel; - static KviActionCategory * m_pCategoryTools; - // internal, current toolbar to be edited (only when customizing) - static KviCustomToolBar * m_pCurrentToolBar; - bool m_bCoreActionsRegistered; -public: - static void init(); - static void done(); - static KviActionManager * instance(){ return m_pInstance; }; - static void loadAllAvailableActions(); - static bool customizingToolBars(){ return m_bCustomizingToolBars; }; - static KviActionCategory * categoryIrc(){ return m_pCategoryIrc; }; - static KviActionCategory * categoryGeneric(){ return m_pCategoryGeneric; }; - static KviActionCategory * categorySettings(){ return m_pCategorySettings; }; - static KviActionCategory * categoryScripting(){ return m_pCategoryScripting; }; - static KviActionCategory * categoryGUI(){ return m_pCategoryGUI; }; - static KviActionCategory * categoryChannel(){ return m_pCategoryChannel; }; - static KviActionCategory * categoryTools(){ return m_pCategoryTools; }; - - KviPointerHashTable * actions(){ return m_pActions; }; - KviActionCategory * category(const QString &szName); - KviPointerHashTable * categories(){ return m_pCategories; }; - - void killAllKvsUserActions(); - - static KviCustomToolBar * currentToolBar(){ return m_pCurrentToolBar; }; - KviAction * getAction(const QString &szName); - void listActionsByCategory(const QString &szCatName,KviPointerList * pBuffer); - QString nameForAutomaticAction(const QString &szTemplate); - bool coreActionExists(const QString &szName); - - void load(const QString &szFileName); - void save(const QString &szFileName); - - bool registerAction(KviAction * a); - bool unregisterAction(const QString &szName); - - void emitRemoveActionsHintRequest(); -protected: - void setCurrentToolBar(KviCustomToolBar * t); - KviAction * findAction(const QString &szName){ return m_pActions->find(szName); }; - void customizeToolBarsDialogCreated(); - void customizeToolBarsDialogDestroyed(); - void tryFindCurrentToolBar(); - void delayedRegisterAccelerators(); // this is called ONCE by KviFrame, at startup -protected slots: - void actionDestroyed(); -signals: - void beginCustomizeToolBars(); - void endCustomizeToolBars(); - void currentToolBarChanged(); // emitted only when customizing! - void removeActionsHintRequest(); // connected by the KviCustomToolBarDialog to flash the trashcan - // when the user tries to remove an action from the toolbar - // and it fails to drag it on the trashcan -}; - -#define ACTION_POPUP_ITEM(__name,__popup) \ - { KviAction * a = KviActionManager::instance()->getAction(__name); if(a)a->addToPopupMenu(__popup); } - - -#endif //!_KVI_ACTIONMANAGER_H_ diff --git a/src/kvirc/kernel/kvi_app.cpp b/src/kvirc/kernel/kvi_app.cpp deleted file mode 100644 index b1ec41346..000000000 --- a/src/kvirc/kernel/kvi_app.cpp +++ /dev/null @@ -1,1999 +0,0 @@ -//============================================================================= -// -// File : kvi_app.cpp -// Creation date : Sun Jun 18 2000 12:39:45 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - -#define _KVI_APP_CPP_ - -#include "kvi_socket.h" -#include "kvi_app.h" -#include "kvi_debug.h" -#include "kvi_frame.h" -#include "kvi_msgbox.h" -#include "kvi_iconmanager.h" -#include "kvi_input.h" -#include "kvi_input_history.h" -#include "KviConfigurationFile.h" -#include "kvi_colorwin.h" -#include "kvi_window.h" -#include "KviIrcServerDataBase.h" -#include "KviProxyDataBase.h" -#include "kvi_menubar.h" -#include "kvi_options.h" -#include "kvi_sparser.h" -#include "kvi_modulemanager.h" -#include "KviMediaType.h" -#include "KviRegisteredUserDataBase.h" -#include "KviThread.h" -#include "KviSharedFilesManager.h" -#include "kvi_confignames.h" -#include "kvi_windowlist.h" -#include "kvi_defaults.h" -#include "KviLocale.h" -#include "kvi_out.h" -#include "kvi_splash.h" -#include "KviNickServRuleSet.h" -#include "KviIdentityProfile.h" -#include "kvi_defaultscript.h" -#include "KviXlib.h" -#include "kvi_texticonmanager.h" -#include "kvi_texticonwin.h" -#include "kvi_historywin.h" -#include "kvi_ctcppagedialog.h" -#include "KviRegisteredChannel.h" -#include "kvi_moduleextension.h" -#include "kvi_internalcmd.h" -#include "kvi_filetransfer.h" -#include "KviMircCntrl.h" -#include "kvi_ircurl.h" -#include "KviAvatarCache.h" -#include "kvi_actionmanager.h" -#include "kvi_customtoolbarmanager.h" -#include "KviFileUtils.h" -#include "KviTimeUtils.h" -#include "KviStringConversion.h" -#include "KviUserIdentity.h" -#include "kvi_ircview.h" -#include "KviEnvironment.h" -#include "KviAnimatedPixmapCache.h" -#include "kvi_kvs.h" -#include "kvi_kvs_script.h" -#include "kvi_kvs_popupmanager.h" -#include "kvi_kvs_kernel.h" -#include "kvi_kvs_object_controller.h" -#include "kvi_kvs_eventtriggers.h" -#include "kvi_sourcesdate.h" -#include "KviPointerHashTable.h" -#include "KviTalPopupMenu.h" - -#ifndef COMPILE_NO_IPC - #include "kvi_ipc.h" -#endif - -#ifdef COMPILE_SSL_SUPPORT - #include "KviSSL.h" -#endif - -#include -#include -#include -#include -#include -#include -#include - -#ifdef COMPILE_ON_WINDOWS - #include -#endif - -#if defined(COMPILE_KDE_SUPPORT) || defined(COMPILE_DBUS_SUPPORT) - #include -#endif - -/* -HACK These 2 hacks are defined because X11 defines Unsorted and None -which conflicts with QDir and KviApp::KvircSubdir -DO NOT REMOVE THEM EVEN IF THEY ARE DEFINED ALSO IN kvi_app.h -*/ -#ifdef Unsorted - #undef Unsorted -#endif - -#ifdef None - #undef None -#endif - -#include - -#include // rand & srand -#include // time() in srand() - -// Global application pointer -KVIRC_API KviApp * g_pApp = 0; - -KviConfigurationFile * g_pWinPropertiesConfig = 0; -KVIRC_API KviIrcServerDataBase * g_pServerDataBase = 0; -KVIRC_API KviProxyDataBase * g_pProxyDataBase = 0; - -// Global windows -KVIRC_API KviColorWindow * g_pColorWindow = 0; -KVIRC_API KviTextIconWindow * g_pTextIconWindow = 0; -KVIRC_API KviTalPopupMenu * g_pInputPopup = 0; -KVIRC_API QStringList * g_pRecentTopicList = 0; -KVIRC_API KviPointerHashTable * g_pGlobalWindowDict = 0; -KVIRC_API KviMediaManager * g_pMediaManager = 0; -KVIRC_API KviSharedFilesManager * g_pSharedFilesManager = 0; -KVIRC_API KviNickServRuleSet * g_pNickServRuleSet = 0; -KVIRC_API KviCtcpPageDialog * g_pCtcpPageDialog = 0; -KVIRC_API KviRegisteredChannelDataBase * g_pRegisteredChannelDataBase = 0; -KVIRC_API KviHistoryWindowWidget * g_pHistoryWindow = 0; - -// this is eventually set by libkviident -KVIRC_API int g_iIdentDaemonRunningUsers = 0; - -KVIRC_API KviSplashScreen * g_pSplashScreen = 0; - - -// Loaded and destroyed by KviIconManager -QPixmap * g_pUserChanStatePixmap = 0; -QPixmap * g_pActivityMeterPixmap = 0; - -#ifdef COMPILE_PSEUDO_TRANSPARENCY - - #include - - KVIRC_API QPixmap * g_pShadedParentGlobalDesktopBackground = 0; // the pixmap that we use for MdiManager - KVIRC_API QPixmap * g_pShadedChildGlobalDesktopBackground = 0; // the pixmap that we use for MdiChild - #if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - #include - #include - #endif -#endif - -#ifdef COMPILE_CRYPT_SUPPORT - #include "KviCryptEngine.h" - // global crypt engine manager - KVIRC_API KviCryptEngineManager * g_pCryptEngineManager = 0; -#endif - -#include - -KviApp::KviApp(int &argc,char ** argv) -: KviTalApplication(argc,argv) -{ - setApplicationName("KVIrc"); - setApplicationVersion(KVIRC_VERSION_RELEASE); - setOrganizationDomain("kvirc.net"); - setOrganizationName("KVIrc"); - -#ifdef COMPILE_ON_MAC - // Disable the native menubar on MacOSX as in Qt 4.6 it's quite buggy and - // *very* often crashes in QMenuBar::macUpdateMenuBar()->QAction::isVisible(). - // FIXME: Check it with later Qt versions - KviEnvironment::setVariable("QT_MAC_NO_NATIVE_MENUBAR","1"); -#endif //COMPILE_ON_MAC - - // Ok...everything begins here - g_pApp = this; - m_szConfigFile = QString(); - m_bCreateConfig = false; - m_bShowSplashScreen = true; - m_bUpdateGuiPending = false; - m_pPendingAvatarChanges = NULL; - m_pRecentChannelDict = NULL; -#ifndef COMPILE_NO_IPC - m_pIpcSentinel = NULL; -#endif - m_iHeartbeatTimerId = -1; - m_fntDefaultFont = font(); - m_bSetupDone = false; - m_bClosingDown = false; - kvi_socket_flushTrafficCounters(); -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - m_bPortable = KviFileUtils::fileExists(g_pApp->applicationDirPath()+KVI_PATH_SEPARATOR_CHAR+"portable"); - //workaround for #957 - QApplication::setEffectEnabled(Qt::UI_FadeMenu, FALSE); -#endif - // workaround for gtk+ style forcing a crappy white background (ticket #777, #964, #1009, ..) - if(QString("QGtkStyle").compare(qApp->style()->metaObject()->className())==0) - { - setStyle(new QCleanlooksStyle()); - setPalette(style()->standardPalette()); - } - -} - -void KviApp::setup() -{ - // Here we start up all the substystems. - // This is a really critical phase since in general subsystems depend - // on each other and we must activate them in the right order. - // Don't move stuff around unless you really know what you're doing. - - // Initialize the random number generator - ::srand(::time(0)); - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - // setup winsock.dll - WSADATA w; - WSAStartup(MAKELONG((unsigned short)2,(unsigned short)0),&w); -#endif - -#ifndef COMPILE_NO_IPC - // Create this very early - // FIXME: this is still not early enough... we actually HAVE race conditions (should use a file for locking this ?) - createIpcSentinel(); -#endif - - // Initialize the thread manager early - KviThreadManager::globalInit(); - -#ifdef COMPILE_SSL_SUPPORT - KviSSL::globalInit(); -#endif - - // Setup our filesystem and initalize locale - loadDirectories(); - KviStringConversion::init(m_szGlobalKvircDir,m_szLocalKvircDir); - - g_pIconManager = new KviIconManager(); - - // add KVIrc common dirs to QT searchpath - QString szPath; - getLocalKvircDirectory(szPath,None,"avatars"); - QDir::addSearchPath("avatars",szPath); - getLocalKvircDirectory(szPath,None,"pics"); - QDir::addSearchPath("pics",szPath); - getLocalKvircDirectory(szPath,None,"audio"); - QDir::addSearchPath("audio",szPath); - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - //need to load image plugins:( - QString szPluginsDir; - getGlobalKvircDirectory(szPluginsDir,None,"qt-plugins/"); - setLibraryPaths(QStringList(szPluginsDir)); - //KviMessageBox::information(libraryPaths().join(";")); - //qDebug("%1",loader.isLoaded()); -#endif - - // check if we want to permanently disable the splash screen - // we do it once for every version: the user should see the new splash screens at least once - QString szSplashDisableFile; - getLocalKvircDirectory(szSplashDisableFile,Pics,"disable-splash." KVI_VERSION); - - if(KviFileUtils::fileExists(szSplashDisableFile)) - m_bShowSplashScreen = false; - - // Now we can create the splash screen (we can locate the splash image) - if(m_bShowSplashScreen) - createSplashScreen(); - - KVI_SPLASH_SET_PROGRESS(0) - - // Make sure that the C strings are translated to utf8 - // This is a fallback solution anyway: we should use the appropriate - // encoding every time. - QTextCodec * pUTF8Codec = KviLocale::codecForName("UTF-8"); - if(pUTF8Codec) - QTextCodec::setCodecForCStrings(pUTF8Codec); - else - qDebug("Aaargh... have no UTF-8 codec?"); - - QString szTmp; - - KVI_SPLASH_SET_PROGRESS(1) - - // Initialize the scripting engine - KviKvs::init(); - - KVI_SPLASH_SET_PROGRESS(2) - - // Initialize the action manager - KviActionManager::init(); - - KVI_SPLASH_SET_PROGRESS(3) - - // Create the module manager early: so the other managers can load modules - g_pModuleExtensionManager = new KviModuleExtensionManager(); - - KVI_SPLASH_SET_PROGRESS(4); - - g_pModuleManager = new KviModuleManager(); - - KVI_SPLASH_SET_PROGRESS(5) - - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_USERACTIONS)) - KviActionManager::instance()->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(8); - - // Initialize and load the identities - KviUserIdentityManager::init(); - - KVI_SPLASH_SET_PROGRESS(9); - - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_IDENTITIES)) - KviUserIdentityManager::instance()->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(12); - - KviAnimatedPixmapCache::init(); - - KVI_SPLASH_SET_PROGRESS(13); - - // Load the remaining configuration - // Note that loadOptions() assumes that the current progress is 12 and - // will bump it up to 45 in small steps - loadOptions(); - - KVI_SPLASH_SET_PROGRESS(47) - - // set the global font if needed - updateApplicationFont(); - -#ifdef COMPILE_PSEUDO_TRANSPARENCY - updatePseudoTransparency(); -#endif - - KVI_SPLASH_SET_PROGRESS(48) - - // Load the win properties config - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_WINPROPERTIES); - g_pWinPropertiesConfig = new KviConfigurationFile(szTmp,KviConfigurationFile::ReadWrite); - - KVI_SPLASH_SET_PROGRESS(50) - - // Load the server database - g_pServerDataBase = new KviIrcServerDataBase(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_SERVERDB)) - g_pServerDataBase->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(53) - - // Load the proxy database - g_pProxyDataBase = new KviProxyDataBase(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_PROXYDB)) - g_pProxyDataBase->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(54) - - // Event manager - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_EVENTS)) - KviKvs::loadAppEvents(szTmp); - - KVI_SPLASH_SET_PROGRESS(59) - - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_RAWEVENTS)) - KviKvs::loadRawEvents(szTmp); - - KVI_SPLASH_SET_PROGRESS(62) - - // Popup manager - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_POPUPS)) - KviKvs::loadPopups(szTmp); - - KVI_SPLASH_SET_PROGRESS(67) - - KviCustomToolBarManager::init(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_CUSTOMTOOLBARS)) - KviCustomToolBarManager::instance()->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(70) - - // Alias manager - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_ALIASES)) - KviKvs::loadAliases(szTmp); - - KVI_SPLASH_SET_PROGRESS(75) - - // Script addons manager (this in fact has delayed loading, so we don't even care - // about showing up an entry in the splash screen) - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_SCRIPTADDONS)) - KviKvs::loadScriptAddons(szTmp); - - KVI_SPLASH_SET_PROGRESS(77) - - g_pTextIconManager = new KviTextIconManager(); - g_pTextIconManager->load(); - - KVI_SPLASH_SET_PROGRESS(80) - - // load the recent data lists - g_pRecentTopicList = new QStringList(); - //g_pBookmarkList = new QStringList(); - loadRecentEntries(); - - KVI_SPLASH_SET_PROGRESS(81) - - // media manager - g_pMediaManager = new KviMediaManager(); - g_pMediaManager->lock(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_MEDIATYPES)) - g_pMediaManager->load(szTmp); - g_pMediaManager->unlock(); - - KVI_SPLASH_SET_PROGRESS(82) - - // registered user data base - g_pRegisteredUserDataBase = new KviRegisteredUserDataBase(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_REGUSERDB)) - g_pRegisteredUserDataBase->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(83) - - // registered channel data base - g_pRegisteredChannelDataBase = new KviRegisteredChannelDataBase(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_REGCHANDB)) - g_pRegisteredChannelDataBase->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(84) - - // file trader - g_pSharedFilesManager = new KviSharedFilesManager(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_SHAREDFILES)) - g_pSharedFilesManager->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(85) - - // nick serv data base - g_pNickServRuleSet = new KviNickServRuleSet(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_NICKSERVDATABASE)) - g_pNickServRuleSet->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(86) - - // Identity profiles database - KviIdentityProfileSet::init(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_PROFILESDATABASE)) - KviIdentityProfileSet::instance()->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(87) - - KviAvatarCache::init(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_AVATARCACHE)) - KviAvatarCache::instance()->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(88) - - KviInputHistory::init(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_INPUTHISTORY)) - KviInputHistory::instance()->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(89) - - KviDefaultScriptManager::init(); - if(getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_DEFAULTSCRIPT)) - KviDefaultScriptManager::instance()->load(szTmp); - - KVI_SPLASH_SET_PROGRESS(90) - - // Eventually initialize the crypt engine manager -#ifdef COMPILE_CRYPT_SUPPORT - g_pCryptEngineManager = new KviCryptEngineManager(); -#endif - - //g_pGarbageCollector = new KviGarbageCollector(); - - // and the input popup - g_pInputPopup = new KviTalPopupMenu(); - - // create the server parser - g_pServerParser = new KviIrcServerParser(); - - KVI_SPLASH_SET_PROGRESS(91) - - // Global window dictionary - g_pGlobalWindowDict = new KviPointerHashTable(41); - g_pGlobalWindowDict->setAutoDelete(false); - // Script object controller - //g_pScriptObjectController = new KviScriptObjectController(); gone - - KVI_SPLASH_SET_PROGRESS(92) - - QString szStylesheetFile; - getGlobalKvircDirectory(szStylesheetFile,Config,"style.css"); - if(KviFileUtils::fileExists(szStylesheetFile)) - { - QString szStyleData; - KviFileUtils::readFile(szStylesheetFile,szStyleData); - szStyleData.replace("global://",m_szGlobalKvircDir); - szStyleData.replace("local://",m_szLocalKvircDir); - setStyleSheet(szStyleData); - } - - // create the frame window, we're almost up and running... - createFrame(); - - // ok, we also have an UI now - - // check if this is the first time this version of KVIrc runs... - if(firstTimeRun()) - { - // Finish the setup... - setupFinish(); - } - - // hello world! - m_bSetupDone = true; - - // We're REALLY up and running! - // kill the splash screen - - KVI_SPLASH_SET_PROGRESS(100) - //KVI_SPLASH_SET_TEXT(__tr2qs("Have fun! :)")) - - if(KVI_OPTION_BOOL(KviOption_boolShowServersConnectDialogOnStart)) - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_SERVERSJOIN_OPEN); - - destroySplashScreen(); - - // check if we're in trouble... - checkSuggestRestoreDefaultScript(); - - // start our heartbeat now - m_iHeartbeatTimerId = startTimer(1000); -} - -void KviApp::frameDestructorCallback() -{ - // here we should kill anything that depends on g_pFrame, g_pActiveWindow and related being non zero... - - // kill all the objects, while we have windows... - if(KviKvsKernel::instance()) - { - if(KviKvsKernel::instance()->objectController()) - { - KviKvsKernel::instance()->objectController()->clearInstances(); - } - } -} - -KviApp::~KviApp() -{ - // Another critical phase. - // We shutdown our subsystems in the right order here. - - m_bClosingDown = true; - -#ifndef COMPILE_NO_IPC - destroyIpcSentinel(); -#endif - - if(g_pSplashScreen) - delete g_pSplashScreen; - if(g_pCtcpPageDialog) - delete g_pCtcpPageDialog; - - // if we still have a frame: kill it - if(g_pFrame) - delete g_pFrame; - g_pActiveWindow = 0; // .. but it should be already 0 anyway - - // execute pending deletes (this may still contain some UI elements) - //delete g_pGarbageCollector; - - if(!m_bSetupDone) - return; // killed with IPC (nothing except the m_pFrameList was created yet) - - KviFileTransferManager::cleanup(); - - // No more events are triggered from now on and no KVS commands are executed - - // Dangerous part.... we're unloading all the modules - // We need to unload them early since they may use other subsystems - // that we are going to kill now. - delete g_pModuleManager; - delete g_pModuleExtensionManager; - // No more external modules exist: all that happens from now is generated - // from inside the kvirc core. - - // We should have almost no UI here: only certain dialogs or popup windows may - // still exist: they should be harmless tough. - saveOptions(); - saveIdentities(); - KviUserIdentityManager::done(); - if(m_pRecentChannelDict) - delete m_pRecentChannelDict; - // now kill the stuff that the frame depends on - saveIrcServerDataBase(); - delete g_pServerDataBase; - saveProxyDataBase(); - delete g_pProxyDataBase; - delete g_pWinPropertiesConfig; - saveTextIcons(); - if(g_pTextIconWindow)delete g_pTextIconWindow; - delete g_pTextIconManager; - delete g_pIconManager; - delete g_pServerParser; - saveMediaTypes(); - delete g_pMediaManager; - saveRecentEntries(); - saveAvatarCache(); - KviAvatarCache::done(); - //delete g_pBookmarkList; - delete g_pRecentTopicList; - saveRegisteredUsers(); - delete g_pRegisteredUserDataBase; - saveRegisteredChannels(); - delete g_pRegisteredChannelDataBase; - saveNickServ(); - delete g_pNickServRuleSet; - saveIdentityProfiles(); - KviIdentityProfileSet::done(); - saveDefaultScripts(); - KviDefaultScriptManager::done(); - saveSharedFiles(); - delete g_pSharedFilesManager; - saveAppEvents(); - saveRawEvents(); - saveToolBars(); - KviCustomToolBarManager::done(); - savePopups(); - saveAliases(); - delete g_pGlobalWindowDict; - saveScriptAddons(); - // kill the remaining resources - delete g_pColorWindow; - if(g_pHistoryWindow)delete g_pHistoryWindow; - saveInputHistory(); - KviInputHistory::done(); - delete g_pInputPopup; - //delete g_pScriptObjectController; -#ifdef COMPILE_CRYPT_SUPPORT - delete g_pCryptEngineManager; -#endif -#ifdef COMPILE_PSEUDO_TRANSPARENCY - destroyPseudoTransparency(); -#endif - if(m_pPendingAvatarChanges) - delete m_pPendingAvatarChanges; - KviAnimatedPixmapCache::done(); - // Kill the thread manager.... all the slave threads should have been already terminated ... -#ifdef COMPILE_SSL_SUPPORT - KviSSL::globalDestroy(); -#endif - KviThreadManager::globalDestroy(); - // kill the scripting engine - KviKvs::done(); - // shut up the action manager - saveActions(); - KviActionManager::done(); - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - WSACleanup(); -#endif - - KviLocale::done(this); - - // goodbye cruel world... -} - -static int g_iGloballyUniqueId = 0; - -int KviApp::getGloballyUniqueId() -{ - g_iGloballyUniqueId++; - return g_iGloballyUniqueId; -} - -void KviApp::notifierMessage(KviWindow * pWnd, int iIconId, const QString & szMsg, unsigned int uMessageLifetime) -{ -#if defined(COMPILE_KDE_SUPPORT) || defined(COMPILE_DBUS_SUPPORT) - if(KVI_OPTION_BOOL(KviOption_boolUseDBusNotifier)) - { - if(!pWnd) - return; - - QString szText = __tr2qs("Message arriving from %1:\n\n").arg(pWnd->target()); - szText += KviMircCntrl::stripControlBytes(szMsg); - - // org.freedesktop.Notifications.Notify - QVariantList args; - args << QString("KVIrc"); // application name - args << QVariant(QVariant::UInt); // notification id - args << QString(g_pIconManager->getSmallIconName(16)); // application icon - args << __tr2qs("KVIrc messaging system"); // summary text - args << szText; // detailed text - args << QStringList(); // actions, optional - args << QVariantMap(); // hints, optional - args << (int)uMessageLifetime*1000; // timeout in msecs - - QDBusInterface * pNotify = new QDBusInterface("org.freedesktop.Notifications","/org/freedesktop/Notifications","org.freedesktop.Notifications",QDBusConnection::sessionBus(),this); - QDBusMessage reply = pNotify->callWithArgumentList(QDBus::Block,"Notify",args); - if(reply.type() == QDBusMessage::ErrorMessage) - { - QDBusError err = reply; - qDebug("DBus notify error\nID: %u\nName: %s\nMessage: %s\n",reply.arguments().first().toUInt(),qPrintable(err.name()),qPrintable(err.message())); - } - } else { -#endif - KviModule * m = g_pModuleManager->getModule("notifier"); - if(!m) - return; - - KviNotifierMessageParam s; - s.pWindow = pWnd; - s.szIcon.sprintf("%d",iIconId); - s.szMessage = szMsg; - s.uMessageLifetime = uMessageLifetime; - - m->ctrl("notifier::message",(void *)&s); -#if defined(COMPILE_KDE_SUPPORT) || defined(COMPILE_DBUS_SUPPORT) - } -#endif -} - -QTextCodec * KviApp::defaultTextCodec() -{ - QTextCodec * pCodec = 0; - if(!KVI_OPTION_STRING(KviOption_stringDefaultTextEncoding).isEmpty()) - { - pCodec = KviLocale::codecForName(KVI_OPTION_STRING(KviOption_stringDefaultTextEncoding).toLatin1()); - if(pCodec) - return pCodec; - } - pCodec = QTextCodec::codecForLocale(); - if(pCodec) - return pCodec; - pCodec = KviLocale::codecForName("UTF-8"); - if(!pCodec) - qDebug("KviApp::defaultTextCodec(): cannot find a suitable text codec for locale :/"); - return pCodec; -} - -QTextCodec * KviApp::defaultSrvCodec() -{ - QTextCodec * pCodec = 0; - if(!KVI_OPTION_STRING(KviOption_stringDefaultSrvEncoding).isEmpty()) - { - pCodec = KviLocale::codecForName(KVI_OPTION_STRING(KviOption_stringDefaultSrvEncoding).toLatin1()); - if(pCodec) - return pCodec; - } - pCodec = QTextCodec::codecForLocale(); - if(pCodec) - return pCodec; - pCodec = KviLocale::codecForName("UTF-8"); - if(!pCodec) - qDebug("KviApp::defaultSrcCodec(): cannot find a suitable text codec for locale :/"); - return pCodec; -} - -void KviApp::loadDefaultScript(QString szItem) -{ - QString szCmd; - - if(szItem.isEmpty()) - szItem = "default"; - - getGlobalKvircDirectory(szCmd,KviApp::DefScript,QString("%1.kvs").arg(szItem)); - szCmd.prepend("parse \""); - szCmd.append("\""); -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - szCmd.replace("\\","\\\\"); -#endif - KviKvsScript::run(szCmd,g_pFrame->firstConsole()); -} - -void KviApp::checkSuggestRestoreDefaultScript() -{ - static bool bSuggestedOnce = false; - if(KVI_OPTION_BOOL(KviOption_boolDoNotSuggestRestoreDefaultScript)) - return; - if(bSuggestedOnce) - return; // already suggested in this kvirc session - - // first: check if the user configuration has ever been updated to the current version - if(!KviDefaultScriptManager::instance()->isDefscriptUpToDate()) - { - switch( - QMessageBox::question(0,__tr2qs("Update default scripts"), - __tr2qs("Hi!

" \ - "It seems that you have just upgraded KVirc from a previous version.

" \ - "The KVIrc default scripts needs to be updated too, to play nice with your fresh new KVIrc.
" \ - "You may want to avoid this update if you plan to revert to a previous KVIrc version soon," \ - "or if you have created a lot of custom scripts and want to stay safe and avoid any deletion or overwrite.
" \ - "If you want to update the default scripts, i can restore the new default script for you.
" \ - "Do you want the default script to be restored?

"), - __tr2qs("No and Don't Ask Me Again"),__tr2qs("No"),__tr2qs("Yes"),1,1) - ) - { - case 0: - KVI_OPTION_BOOL(KviOption_boolDoNotSuggestRestoreDefaultScript) = true; - return; - break; - case 1: - // we want to execute the next checks, don't return now - break; - default: - restoreDefaultScript(); - // we want to execute the next checks after the attempted restore, don't return now - break; - } - } - - //second, check for some common corruptions in scripts - int iScore = 0; - - if(KviCustomToolBarManager::instance()->descriptorCount() < 1) - iScore += 100; // straight suggest - else if(KviKvsPopupManager::instance()->popupCount() < 1) - iScore += 100; // straight suggest - else { - // other stuff is not that critical - if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnChannelNickPopupRequest)) - iScore += 80; - if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnDCCChatPopupRequest)) - iScore += 20; - if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnConsolePopupRequest)) - iScore += 20; - if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnChannelPopupRequest)) - iScore += 20; - if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnChannelNickPopupRequest)) - iScore += 20; - if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnQueryPopupRequest)) - iScore += 20; - if(!KviKvsEventManager::instance()->hasAppHandlers(KviEvent_OnQueryNickPopupRequest)) - iScore += 20; - if(KviCustomToolBarManager::instance()->descriptorCount() < 4) - iScore += 20; - if(KviKvsPopupManager::instance()->popupCount() < 3) - iScore += 20; - if(KviCustomToolBarManager::instance()->visibleToolBarCount() < 2) - { - iScore += 20; - if(KviCustomToolBarManager::instance()->visibleToolBarCount() < 1) - iScore += 20; - } - } - - if(iScore < 100) - return; - - bSuggestedOnce = true; - - switch( - QMessageBox::question(0,__tr2qs("Installation problems?"), - __tr2qs("Ooops...

" \ - "There are some reasons that make me think that your KVIrc installation is incomplete.

" \ - "I might be wrong, but you seem to miss some of the features that the default KVIrc script provides." \ - "This may happen because you have upgraded to an unstable svn version, " \ - "because you have accidentally deleted or damaged your configuration files, " \ - "because you have installed an incomplete script " \ - "or because you have hit a bug in KVIrc.

" \ - "I can repeat the installation of the default script in order " \ - "to restore the missing features.
" \ - "Do you want the default script to be restored?

" \ - "Hint: If you're a scripter and have intentionally removed some of the scripting features " \ - "then you may safely click on \"No and Don't Ask Me Again\", otherwise it might be " \ - "a good idea to click \"Yes\". If you still want to choose \"No\" you can always restore the " \ - "default script by choosing the appropriate entry from the \"Scripting\" menu."), - __tr2qs("No and Don't Ask Me Again"),__tr2qs("No"),__tr2qs("Yes"),1,1) - ) - { - case 0: - KVI_OPTION_BOOL(KviOption_boolDoNotSuggestRestoreDefaultScript) = true; - return; - break; - case 1: - return; - break; - default: - restoreDefaultScript(); - break; - } -} - -void KviApp::restoreDefaultScript() -{ - KviDefaultScriptManager::instance()->restore(); -} - -#ifndef COMPILE_NO_IPC -void KviApp::createIpcSentinel() -{ - m_pIpcSentinel = new KviIpcSentinel(); -} - -void KviApp::destroyIpcSentinel() -{ - if(m_pIpcSentinel) - delete m_pIpcSentinel; - m_pIpcSentinel = 0; -} - -void KviApp::ipcMessage(char * pcMessage) -{ - if(!g_pFrame) - return; - KviConsole * pConsole = g_pFrame->firstConsole(); - if(!pConsole) - return; - if(_OUTPUT_VERBOSE) - { - KviCString szCmd = pcMessage; - if(szCmd.len() > 30) - szCmd.cutRight(szCmd.len() - 30); - int iIdx = szCmd.findFirstIdx('\n'); - if(iIdx != -1) - szCmd.cutRight(szCmd.len() - (iIdx + 1)); - pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Remote command received (%s ...)"),szCmd.ptr()); - } - KviKvsScript::run(pcMessage,pConsole); -} -#endif // COMPILE_NO_IPC - -void KviApp::createSplashScreen() -{ - g_pSplashScreen = new KviSplashScreen(); - g_pSplashScreen->show(); -} - -void KviApp::destroySplashScreen() -{ - if(g_pSplashScreen) - g_pSplashScreen->die(); -} - -void KviApp::setAvatarFromOptions() -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) - { - ((KviConsole *)it.current())->setAvatarFromOptions(); - } - ++it; - } - -} - -void KviApp::setAvatarOnFileReceived(KviConsole * pConsole, const QString & szRemoteUrl, const QString & szNick, const QString & szUser, const QString & szHost) -{ - if(!m_pPendingAvatarChanges) - { - m_pPendingAvatarChanges = new KviPointerList; - m_pPendingAvatarChanges->setAutoDelete(true); - } - - if(m_pPendingAvatarChanges->count() >= KVI_MAX_PENDING_AVATARS) // can't be... - { - m_pPendingAvatarChanges->removeFirst(); // kill the first entry - } - - KviPendingAvatarChange * pAvatar = new KviPendingAvatarChange; - pAvatar->pConsole = pConsole; - pAvatar->szRemoteUrl = szRemoteUrl; - pAvatar->szNick = szNick; - pAvatar->szUser = szUser; - pAvatar->szHost = szHost; - - m_pPendingAvatarChanges->append(pAvatar); -} - -KviPendingAvatarChange * KviApp::findPendingAvatarChange(KviConsole * pConsole, const QString & szNick, const QString & szRemoteUrl) -{ - if(!m_pPendingAvatarChanges) - return 0; - - KviPendingAvatarChange * pAvatar; - - for(pAvatar = m_pPendingAvatarChanges->first(); pAvatar; pAvatar = m_pPendingAvatarChanges->next()) - { - if(!pConsole || (pAvatar->pConsole == pConsole)) - { - if(szNick.isNull() || (szNick == pAvatar->szNick)) - { - if(szRemoteUrl == pAvatar->szRemoteUrl) - return pAvatar; - } - } - } - - return 0; -} - -void KviApp::fileDownloadTerminated(bool bSuccess, const QString & szRemoteUrl, const QString & szLocalFileName, const QString & szNick, const QString & szError, bool bQuiet) -{ - KviPendingAvatarChange * pAvatar; - - if(m_pPendingAvatarChanges) - pAvatar = findPendingAvatarChange(0,szNick,szRemoteUrl); - else - pAvatar = 0; - - if(!pAvatar) - { - // signal dcc completion only for NON-avatars - // FIXME: This option is misnamed and misplaced in the options dialog :( - // it seems to refer only to DCC while it refers to any file transfer - if(KVI_OPTION_BOOL(KviOption_boolNotifyDccSendSuccessInNotifier) && (!bQuiet)) - { - if(!g_pActiveWindow) - return; - if(g_pActiveWindow->hasAttention()) - return; - QString szMsg; - int iIconId; - if(!bSuccess) - { - iIconId = KVI_SMALLICON_DCCERROR; - if(szNick.isEmpty()) - szMsg = __tr2qs("File download failed"); - else - szMsg = __tr2qs("File download from %1 failed").arg(szNick); - szMsg += ": "; - szMsg += szError; - szMsg += " ("; - szMsg += szLocalFileName; - szMsg += ")"; - } else { - iIconId = KVI_SMALLICON_DCCMSG; - if(szNick.isEmpty()) - szMsg = __tr2qs("File download successfully complete"); - else - szMsg = __tr2qs("File download from %1 successfully complete").arg(szNick); - szMsg += " ("; - szMsg += szLocalFileName; - szMsg += ")"; - } - notifierMessage(0,iIconId,Qt::escape(szMsg),KVI_OPTION_UINT(KviOption_uintNotifierAutoHideTime)); - } - return; - } - - if(bSuccess) - { - if(windowExists(pAvatar->pConsole)) - { - pAvatar->pConsole->setAvatar(pAvatar->szNick,pAvatar->szUser,pAvatar->szHost,szLocalFileName,KviQString::equalCIN("http://",szRemoteUrl,7) ? szRemoteUrl : QString()); - } - } else { - if((!_OUTPUT_MUTE) && (!bQuiet)) - { - pAvatar->pConsole->output(KVI_OUT_AVATAR,__tr2qs("Avatar download failed for %Q!%Q@%Q and url %Q: %Q"), - &(pAvatar->szNick),&(pAvatar->szUser),&(pAvatar->szHost),&(szRemoteUrl),&(szError)); - } - } - - m_pPendingAvatarChanges->removeRef(pAvatar); - - if(m_pPendingAvatarChanges->count() == 0) - { - delete m_pPendingAvatarChanges; - m_pPendingAvatarChanges = 0; - } -} - -#ifdef COMPILE_PSEUDO_TRANSPARENCY -void KviApp::destroyPseudoTransparency() -{ - if(g_pShadedParentGlobalDesktopBackground) - { - delete g_pShadedParentGlobalDesktopBackground; - g_pShadedParentGlobalDesktopBackground = 0; - } - if(g_pShadedChildGlobalDesktopBackground) - { - delete g_pShadedChildGlobalDesktopBackground; - g_pShadedChildGlobalDesktopBackground = 0; - } -} - -void KviApp::triggerUpdatePseudoTransparency() -{ - if(m_bUpdatePseudoTransparencyPending) - return; - m_bUpdatePseudoTransparencyPending = true; - QTimer::singleShot(0,this,SLOT(updatePseudoTransparency())); -} - -// -// This function is taken from the KDE3 kimageeffect.cpp -// The authors listed at the top of the file are :) -// Copyright (C) 1998, 1999 Christian Tibirna -// (C) 1998, 1999 Daniel M. Duley -// (C) 1998, 1999 Dirk A. Mueller -// (C) 2000 Josef Weidendorfer -// - -QImage & kimageeffect_fade(QImage &img,float val,const QColor &color) -{ - if(img.width() == 0 || img.height() == 0)return img; - - // We don't handle bitmaps - if (img.depth() == 1)return img; - - unsigned char tbl[256]; - for (int i=0; i<256; i++)tbl[i] = (int) (val * i + 0.5); - - int red = color.red(); - int green = color.green(); - int blue = color.blue(); - - QRgb col; - int r, g, b, cr, cg, cb; - - if (img.depth() <= 8) - { - // pseudo color - int c = img.numColors(); - for(int i=0; i red)r = cr - tbl[cr - red]; - else r = cr + tbl[red - cr]; - if (cg > green)g = cg - tbl[cg - green]; - else g = cg + tbl[green - cg]; - if (cb > blue)b = cb - tbl[cb - blue]; - else b = cb + tbl[blue - cb]; - img.setColor(i, qRgb(r, g, b)); - } - } else { - // truecolor - int h = img.height(); - int w = img.width(); - for(int y=0; y red)r = cr - tbl[cr - red]; - else r = cr + tbl[red - cr]; - if (cg > green)g = cg - tbl[cg - green]; - else g = cg + tbl[green - cg]; - if (cb > blue)b = cb - tbl[cb - blue]; - else b = cb + tbl[blue - cb]; - *data++ = qRgb(r, g, b); - } - } - } - return img; -} - -void KviApp::createGlobalBackgrounds(QPixmap * pix) -{ - // create shaded copies... - if(g_pShadedParentGlobalDesktopBackground) - delete g_pShadedParentGlobalDesktopBackground; - if(g_pShadedChildGlobalDesktopBackground) - delete g_pShadedChildGlobalDesktopBackground; - g_pShadedParentGlobalDesktopBackground = new QPixmap(); - g_pShadedChildGlobalDesktopBackground = new QPixmap(); - QImage img = pix->toImage(); - // play with the fade factors - KVI_OPTION_UINT(KviOption_uintGlobalTransparencyParentFadeFactor) %= 100; - if(KVI_OPTION_UINT(KviOption_uintGlobalTransparencyParentFadeFactor) > 0) - { - *g_pShadedParentGlobalDesktopBackground = QPixmap::fromImage( - kimageeffect_fade(img, - (float)((float)KVI_OPTION_UINT(KviOption_uintGlobalTransparencyParentFadeFactor) / (float)100), - KVI_OPTION_COLOR(KviOption_colorGlobalTransparencyFade))); - } - KVI_OPTION_UINT(KviOption_uintGlobalTransparencyChildFadeFactor) %= 100; - if(KVI_OPTION_UINT(KviOption_uintGlobalTransparencyChildFadeFactor) > 0) - { - *g_pShadedChildGlobalDesktopBackground = QPixmap::fromImage( - kimageeffect_fade(img, - (float)((float)KVI_OPTION_UINT(KviOption_uintGlobalTransparencyChildFadeFactor) / (float)100), - KVI_OPTION_COLOR(KviOption_colorGlobalTransparencyFade))); - } - if(g_pFrame - )g_pFrame->updatePseudoTransparency(); -} -#endif //COMPILE_PSEUDO_TRANSPARENCY - - -void KviApp::updatePseudoTransparency() -{ -#ifdef COMPILE_PSEUDO_TRANSPARENCY - m_bUpdatePseudoTransparencyPending = false; - if(KVI_OPTION_BOOL(KviOption_boolUseGlobalPseudoTransparency)) - { -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - //TODO this has been tested only under mingw! - //TODO this needs winxp: #if (_WIN32_WINNT >= 0x0501) - if(KVI_OPTION_BOOL(KviOption_boolUseWindowsDesktopForTransparency)) - { - QSize size = g_pApp->desktop()->screenGeometry(g_pApp->desktop()->primaryScreen()).size(); - // get the Program Manager - HWND hWnd = FindWindow ("Progman", "Program Manager"); - // Create and setup bitmap - HDC bitmap_dc = CreateCompatibleDC(qt_win_display_dc()); - HBITMAP bitmap = CreateCompatibleBitmap(qt_win_display_dc(), size.width(), size.height()); - HGDIOBJ null_bitmap = SelectObject(bitmap_dc, bitmap); - - PrintWindow (hWnd, bitmap_dc, 0); - - SelectObject(bitmap_dc, null_bitmap); - DeleteDC(bitmap_dc); - - QPixmap pix = QPixmap::fromWinHBITMAP(bitmap); - - DeleteObject(bitmap); - - createGlobalBackgrounds(&pix); - } else -#endif // COMPILE_ON_WINDOWS || COMPILE_ON_MINGW - - if(KVI_OPTION_PIXMAP(KviOption_pixmapGlobalTransparencyBackground).pixmap()) - { - createGlobalBackgrounds(KVI_OPTION_PIXMAP(KviOption_pixmapGlobalTransparencyBackground).pixmap()); - } else { - //destroy pseudo transparency pixmaps - destroyPseudoTransparency(); - //if we get here, no pseudo transparency method can be used / is enabled. -#ifdef COMPILE_X11_SUPPORT - //under x11, we still have to check real transparency methods - if(!KVI_OPTION_BOOL(KviOption_boolUseCompositingForTransparency)) - { - //real transparency is off => turn off transparency support at all - KVI_OPTION_BOOL(KviOption_boolUseGlobalPseudoTransparency) = false; - } -#else - // on other platforms, no way to proceed - KVI_OPTION_BOOL(KviOption_boolUseGlobalPseudoTransparency) = false; -#endif // COMPILE_X11_SUPPORT - } - } else { - //transparency is disabled - - //destroy pseudo transparency pixmaps - destroyPseudoTransparency(); - //make sure real transparency is disabled - KVI_OPTION_BOOL(KviOption_boolUseCompositingForTransparency) = false; - - //update widgets - if(g_pFrame) - g_pFrame->updatePseudoTransparency(); - } -#endif //COMPILE_PSEUDO_TRANSPARENCY -} - -void KviApp::triggerUpdateGui() -{ - if(m_bUpdateGuiPending) - return; - m_bUpdateGuiPending = true; - QTimer::singleShot(0,this,SLOT(updateGui())); -} - -void KviApp::updateGui() -{ - m_bUpdateGuiPending = false; - g_pFrame->applyOptions(); -} - -void KviApp::updateApplicationFont() -{ - if(KVI_OPTION_BOOL(KviOption_boolUseGlobalApplicationFont)) - { - setFont(KVI_OPTION_FONT(KviOption_fontApplication)); - if(g_pFrame) - g_pFrame->setFont(font()); - } else { - setFont(m_fntDefaultFont); - if(g_pFrame) - g_pFrame->setFont(m_fntDefaultFont); - } -} - -void KviApp::loadRecentEntries() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_RECENT); - KviConfigurationFile cfg(szTmp,KviConfigurationFile::Read); - *g_pRecentTopicList = cfg.readStringListEntry("RecentTopicList",QStringList()); - //*g_pBookmarkList = cfg.readStringListEntry("Bookmarks",QStringList()); -} - -void KviApp::saveRecentEntries() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_RECENT); - KviConfigurationFile cfg(szTmp,KviConfigurationFile::Write); - cfg.writeEntry("RecentTopicList",*g_pRecentTopicList); - //cfg.writeEntry("Bookmarks",*g_pBookmarkList); -} - -void KviApp::saveAvatarCache() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_AVATARCACHE); - KviAvatarCache::instance()->save(szTmp); -} - -void KviApp::saveToolBars() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_CUSTOMTOOLBARS); - KviCustomToolBarManager::instance()->save(szTmp); -} - -void KviApp::savePopups() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_POPUPS); - KviKvs::savePopups(szTmp); -} - -void KviApp::saveInputHistory() -{ - if(KVI_OPTION_BOOL(KviOption_boolEnableInputHistory)) - { - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_INPUTHISTORY); - KviInputHistory::instance()->save(szTmp); - } -} - -void KviApp::saveAliases() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_ALIASES); - KviKvs::saveAliases(szTmp); -} - -void KviApp::saveScriptAddons() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_SCRIPTADDONS); - KviKvs::saveScriptAddons(szTmp); -} - -void KviApp::saveTextIcons() -{ - g_pTextIconManager->save(); -} - -void KviApp::saveAppEvents() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_EVENTS); - KviKvs::saveAppEvents(szTmp); -} - -void KviApp::saveRawEvents() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_RAWEVENTS); - KviKvs::saveRawEvents(szTmp); -} - -void KviApp::saveMediaTypes() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_MEDIATYPES); - g_pMediaManager->lock(); - g_pMediaManager->save(szTmp); - g_pMediaManager->unlock(); -} - -void KviApp::saveIrcServerDataBase() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_SERVERDB); - g_pServerDataBase->save(szTmp); -} - -void KviApp::saveProxyDataBase() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_PROXYDB); - g_pProxyDataBase->save(szTmp); -} - -void KviApp::saveRegisteredUsers() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_REGUSERDB); - g_pRegisteredUserDataBase->save(szTmp); -} - -void KviApp::saveRegisteredChannels() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_REGCHANDB); - g_pRegisteredChannelDataBase->save(szTmp); -} - -void KviApp::saveNickServ() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_NICKSERVDATABASE); - g_pNickServRuleSet->save(szTmp); -} - -void KviApp::saveIdentityProfiles() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_PROFILESDATABASE); - KviIdentityProfileSet::instance()->save(szTmp); -} - -void KviApp::saveDefaultScripts() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_DEFAULTSCRIPT); - KviDefaultScriptManager::instance()->save(szTmp); -} - -void KviApp::saveSharedFiles() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_SHAREDFILES); - g_pSharedFilesManager->save(szTmp); -} - -void KviApp::saveActions() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_USERACTIONS); - KviActionManager::instance()->save(szTmp); -} - -void KviApp::saveIdentities() -{ - QString szTmp; - getLocalKvircDirectory(szTmp,Config,KVI_CONFIGFILE_IDENTITIES); - KviUserIdentityManager::instance()->save(szTmp); -} - -void KviApp::saveConfiguration() -{ - // this is NOT called when the application is closing down - KviCustomToolBarManager::instance()->storeVisibilityState(); - saveOptions(); - saveIdentities(); - saveActions(); - saveIrcServerDataBase(); - saveProxyDataBase(); - saveRecentEntries(); - saveAvatarCache(); - saveAppEvents(); - saveRawEvents(); - saveMediaTypes(); - saveRegisteredUsers(); - saveRegisteredChannels(); - saveNickServ(); - saveIdentityProfiles(); - saveDefaultScripts(); - saveSharedFiles(); - savePopups(); - saveToolBars(); - saveAliases(); - saveTextIcons(); - saveInputHistory(); - saveScriptAddons(); - KviKvs::flushUserClasses(); - g_pWinPropertiesConfig->sync(); -} - -void KviApp::autoConnectToServers() -{ - KviPointerList * pList = g_pServerDataBase->autoConnectOnStartupServers(); - if(pList) - { - for(KviIrcServer * pServer = pList->first(); pServer; pServer = pList->next()) - { - QString szCommand = "server -u \"id:"; - if(pServer->id().isEmpty()) - pServer->generateUniqueId(); - szCommand += pServer->id(); - szCommand += "\""; - KviKvsScript::run(szCommand,activeConsole()); - } - g_pServerDataBase->clearAutoConnectOnStartupServers(); - } - - KviPointerList * pListNet = g_pServerDataBase->autoConnectOnStartupNetworks(); - if(pListNet) - { - for(KviIrcNetwork * pNetwork = pListNet->first(); pNetwork; pNetwork = pListNet->next()) - { - QString szCommandx = "server -u \"net:"; - szCommandx += pNetwork->name(); - szCommandx += "\""; - KviKvsScript::run(szCommandx,activeConsole()); - } - g_pServerDataBase->clearAutoConnectOnStartupNetworks(); - } -} - -void KviApp::createFrame() -{ - if(g_pFrame) - qDebug("WARNING: Creating the main frame twice!"); - g_pFrame = new KviFrame(); - g_pFrame->createNewConsole(true); - - if(m_szExecAfterStartup.hasData()) - { - // FIXME, this should be a QString - KviKvsScript::run(m_szExecAfterStartup.ptr(),g_pFrame->firstConsole()); - m_szExecAfterStartup = ""; - } - - // auto connect to servers if needed - if(g_pServerDataBase->autoConnectOnStartupServers() || g_pServerDataBase->autoConnectOnStartupNetworks()) - { - autoConnectToServers(); - } - - if(KVI_OPTION_BOOL(KviOption_boolShowDockExtension)) - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_TRAYICON_SHOW); - - if(KVI_OPTION_BOOL(KviOption_boolStartupMinimized)) - g_pFrame->showMinimized(); - else - g_pFrame->show(); -} - -void KviApp::destroyFrame() -{ - m_bClosingDown=true; - if(g_pFrame) - g_pFrame->deleteLater(); - g_pActiveWindow = 0; -} - -bool KviApp::connectionExists(KviIrcConnection * pConn) -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current()->connection() == pConn) - return true; - ++it; - } - return false; -} - -bool KviApp::windowExists(KviWindow * pWnd) -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current() == pWnd) - return true; - ++it; - } - return false; -} - -unsigned int KviApp::windowCount() -{ - return g_pGlobalWindowDict->count(); -} - -KviConsole * KviApp::findConsole(QString & szServer, QString & szNick) -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) - { - if(((KviConsole *)it.current())->isConnected()) - { - if(!szServer.isEmpty()) - { - if(KviQString::equalCI(szServer, - ((KviConsole *)it.current())->connection()->currentServerName())) - { - if(!szNick.isEmpty()) - { - if(KviQString::equalCI(szNick, - ((KviConsole *)it.current())->connection()->currentNickName())) - return ((KviConsole *)it.current()); - } else return ((KviConsole *)it.current()); - } - } else { - if(!szNick.isEmpty()) - { - if(KviQString::equalCI(szNick, - ((KviConsole *)it.current())->connection()->currentNickName())) - return ((KviConsole *)it.current()); - } - } - } - } - ++it; - } - return 0; -} - -void KviApp::restartLagMeters() -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) - { - if(((KviConsole *)it.current())->connection()) - ((KviConsole *)it.current())->connection()->restartLagMeter(); - } - ++it; - } -} - -void KviApp::restartNotifyLists() -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) - { - if(((KviConsole *)it.current())->connection()) - ((KviConsole *)it.current())->connection()->restartNotifyList(); - } - ++it; - } -} - -void KviApp::resetAvatarForMatchingUsers(KviRegisteredUser * pUser) -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) - { - ((KviConsole *)it.current())->resetAvatarForMatchingUsers(pUser); - } - ++it; - } -} - -KviConsole * KviApp::findConsole(unsigned int uIrcContextId) -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) - { - if(((KviConsole *)it.current())->context()->id() == uIrcContextId) - return ((KviConsole *)it.current()); - } - ++it; - } - return 0; -} - -KviConsole * KviApp::topmostConnectedConsole() -{ - // check the foreground window console - - KviConsole * pConsole = activeConsole(); - if(!pConsole) - return 0; - if(pConsole->isConnected()) - return pConsole; - - // try ANY connected console - - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(it.current()->type() == KVI_WINDOW_TYPE_CONSOLE) - { - if(((KviConsole *)it.current())->isConnected()) - return (KviConsole *)(it.current()); - } - ++it; - } - - return 0; -} - -KviWindow * KviApp::findWindow(const QString & szWindowId) -{ - return g_pGlobalWindowDict->find(szWindowId); -} - -KviWindow * KviApp::findWindowByCaption(const QString & szWindowCaption, int iContextId) -{ - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - - while(it.current()) - { - if(KviQString::equalCI(szWindowCaption,it.current()->plainTextCaption()) && - (iContextId==-1 || it.current()->context()->id() == (uint) iContextId)) - return it.current(); - ++it; - } - return 0; -} - -void KviApp::registerWindow(KviWindow * pWnd) -{ - g_pGlobalWindowDict->insert(pWnd->id(),pWnd); -} - -void KviApp::unregisterWindow(KviWindow * pWnd) -{ - g_pGlobalWindowDict->remove(pWnd->id()); -} - -KviConsole * KviApp::activeConsole() -{ - if(!g_pFrame) - return 0; - if(g_pActiveWindow) - { - if(g_pActiveWindow->console()) - return g_pActiveWindow->console(); - } - return g_pFrame->firstConsole(); -} - - -/////////////////// RECENT STUFF LISTS & POPUPS HANDLING - -// Helper for KviApp::addRecent*() -static void merge_to_stringlist_option(const QString & szItem, int iOption, int iMaxEntries) -{ - for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(iOption).begin(); - it != KVI_OPTION_STRINGLIST(iOption).end(); ++it) - { - // Do a case-insensitive search (for nicknames, servers, and channels) - if(!QString::compare(szItem.toLower(),(*it).toLower())) - { - // In the recent list, remove and put as first so more recent items - // are always first - it = KVI_OPTION_STRINGLIST(iOption).erase(it); - --it; - } - } - while(KVI_OPTION_STRINGLIST(iOption).count() >= iMaxEntries) - { - KVI_OPTION_STRINGLIST(iOption).erase(KVI_OPTION_STRINGLIST(iOption).isEmpty() ? KVI_OPTION_STRINGLIST(iOption).end() : --KVI_OPTION_STRINGLIST(iOption).end()); - } - KVI_OPTION_STRINGLIST(iOption).prepend(szItem); -} - -void KviApp::addRecentUrl(const QString & szText) -{ - merge_to_stringlist_option(szText,KviOption_stringlistRecentIrcUrls,50); - emit(recentUrlsChanged()); -} - -void KviApp::addRecentNickname(const QString & szNewNick) -{ - merge_to_stringlist_option(szNewNick,KviOption_stringlistRecentNicknames,KVI_MAX_RECENT_NICKNAMES); -} - -void KviApp::addRecentChannel(const QString & szChan, const QString & szNet) -{ - if(!m_pRecentChannelDict) - buildRecentChannels(); - - QStringList * pList = m_pRecentChannelDict->find(szNet); - if(!pList) - { - pList = new QStringList(szChan); - m_pRecentChannelDict->insert(szNet,pList); - } - - if(!pList->contains(szChan)) - pList->append(szChan); -} - -void KviApp::buildRecentChannels() -{ - if(m_pRecentChannelDict) - delete m_pRecentChannelDict; - - m_pRecentChannelDict = new KviPointerHashTable; - m_pRecentChannelDict->setAutoDelete(true); - - QString szChan,szNet; - - for( - QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistRecentChannels).begin(); - it != KVI_OPTION_STRINGLIST(KviOption_stringlistRecentChannels).end(); - ++it - ) - { - if((*it).isEmpty()) - continue; - - szChan = (*it).section(KVI_RECENT_CHANNELS_SEPARATOR,0,0); - szNet = (*it).section(KVI_RECENT_CHANNELS_SEPARATOR,1); - - if(szNet.isEmpty()) - continue; - - QStringList * pList = m_pRecentChannelDict->find(szNet); - if(!pList) - { - pList = new QStringList(szChan); - m_pRecentChannelDict->insert(szNet,pList); - } - - if(!pList->contains(szChan)) - pList->append(szChan); - } -} - -void KviApp::saveRecentChannels() -{ - if(!m_pRecentChannelDict) - return; - - QString szTmp; - - KVI_OPTION_STRINGLIST(KviOption_stringlistRecentChannels).clear(); - - KviPointerHashTableIterator it(*m_pRecentChannelDict); - - for(; it.current(); ++it) - { - for(QStringList::Iterator it_str = it.current()->begin(); it_str != it.current()->end(); ++it_str) - { - szTmp = *it_str; - szTmp.append(KVI_RECENT_CHANNELS_SEPARATOR); - szTmp.append(it.currentKey()); - KVI_OPTION_STRINGLIST(KviOption_stringlistRecentChannels).append(szTmp); - } - } -} - -QStringList * KviApp::recentChannelsForNetwork(const QString & szNet) -{ - if(!m_pRecentChannelDict) - buildRecentChannels(); - return m_pRecentChannelDict->find(szNet); -} - -void KviApp::addRecentServer(const QString & szServer) -{ - merge_to_stringlist_option(szServer,KviOption_stringlistRecentServers,KVI_MAX_RECENT_SERVERS); -} - -void KviApp::fillRecentServersPopup(KviTalPopupMenu * pMenu) -{ - // FIXME: #warning "MAYBE DISABLE THE SERVERS THAT WE ARE ALREADY CONNECTED TO ?" - pMenu->clear(); - for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistRecentServers).begin(); it != KVI_OPTION_STRINGLIST(KviOption_stringlistRecentServers).end(); ++it) - { - if(*it == "") - continue; - pMenu->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SERVER)),*it); - } -} - -void KviApp::fillRecentNicknamesPopup(KviTalPopupMenu * pMenu, KviConsole * pConsole) -{ - pMenu->clear(); - int iId; - bool bAlreadyFound = false; - for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistRecentNicknames).begin(); it != KVI_OPTION_STRINGLIST(KviOption_stringlistRecentNicknames).end(); ++it) - { - if(*it == "") - continue; - iId = pMenu->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NICK)),*it); - if(!pConsole->isConnected()) - pMenu->setItemEnabled(iId,false); - else { - if(!bAlreadyFound) - { - bool bIsCurrent = KviQString::equalCS(pConsole->connection()->currentNickName(),*it); - pMenu->setItemEnabled(iId,!bIsCurrent); - if(bIsCurrent) - bAlreadyFound = true; - } - } - } -} - -void KviApp::fillRecentChannelsPopup(KviTalPopupMenu * pMenu, KviConsole * pConsole) -{ - pMenu->clear(); - QStringList * pList = recentChannelsForNetwork(pConsole->currentNetworkName()); - if(pList) - { - for(QStringList::Iterator it = pList->begin(); it != pList->end(); ++it) - { - if(*it == "") - continue; // ? - int iId = pMenu->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_CHANNEL)),*it); - if(!pConsole->isConnected()) - pMenu->setItemEnabled(iId,false); - else - pMenu->setItemEnabled(iId,!(pConsole->connection()->findChannel(*it))); - } - } -} - - -/* -void KviApp::fillRecentServersListBox(KviTalListBox * l) -{ - l->clear(); - for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistRecentServers).begin(); it != KVI_OPTION_STRINGLIST(KviOption_stringlistRecentServers).end(); ++it) - l->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SERVER)),*it); -} -*/ - -//#include - -void KviApp::heartbeat(kvi_time_t tNow) -{ - const struct tm * pTm = localtime(&tNow); - - if(g_pApp->topmostConnectedConsole()) - { - // FIXME: this has huge precision problems... - KVI_OPTION_UINT(KviOption_uintTotalConnectionTime)++; - } - - if(pTm && !pTm->tm_hour && !pTm->tm_min && !pTm->tm_sec) - { - KviPointerHashTableIterator it(*g_pGlobalWindowDict); - while(it.current()) - { - if(it.current()->view() && it.current()->view()->isLogging()) - it.current()->view()->startLogging(0); - ++it; - } - } - - //qDebug("Clearing Qt pixmap cache..."); - //QPixmapCache::clear(); -} - -void KviApp::timerEvent(QTimerEvent * e) -{ - if(e->timerId() != m_iHeartbeatTimerId) - { - QObject::timerEvent(e); - return; - } - - // our heartbeat - - kvi_time_t tNow = kvi_unixTime(); - - heartbeat(tNow); -} - -// qvariant.h uses this, and it is included by the qt generated moc file for Qt >= 3.0.0 -#ifdef Bool - #undef Bool -#endif - - -#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES -#include "kvi_app.moc" -#endif //!COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/kvi_app.h b/src/kvirc/kernel/kvi_app.h deleted file mode 100644 index 01f898507..000000000 --- a/src/kvirc/kernel/kvi_app.h +++ /dev/null @@ -1,383 +0,0 @@ -#ifndef _KVI_APP_H_ -#define _KVI_APP_H_ - -//============================================================================= -// -// File : kvi_app.h -// Creation date : Sun Jun 18 2000 12:40:00 CEST by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviCString.h" -#include "KviQString.h" -#include "KviTalApplication.h" -#include "KviPointerList.h" -#include "KviTimeUtils.h" -#include "KviPointerHashTable.h" // ? - -#include -#include - -#ifdef COMPILE_ON_WINDOWS - // The brain damaged MSVC compiler can't instantiate templates without this - #include "kvi_frame.h" - #include "kvi_window.h" -#else // !COMPILE_ON_WINDOWS - class KviFrame; - class KviWindow; -#endif // !COMPILE_ON_WINDOWS - -#ifndef COMPILE_NO_IPC - class KviIpcSentinel; -#endif // !COMPILE_NO_IPC - -#ifdef COMPILE_X11_SUPPORT - #include -#endif - -class KviTalPopupMenu; -class KviTalListBox; -class KviConsole; -class KviConfigurationFile; -class KviRegisteredUser; -class KviIrcConnection; -class KviIrcServerDataBase; -class QPixmap; -class QTextCodec; -class QDomElement; -class QStringList; - -typedef struct _KviPendingAvatarChange -{ - KviConsole * pConsole; - QString szRemoteUrl; - QString szNick; - QString szUser; - QString szHost; -} KviPendingAvatarChange; - -/** -* \typedef KviNotifierMessageParam -* \struct _KviNotifierMessageParam -* \brief Defines a struct which holds information about the notifier message -*/ -typedef struct _KviNotifierMessageParam -{ - KviWindow * pWindow; /**< The window where the notifier was triggered */ - QString szIcon; /**< The id of the icon (channel, query, ...) */ - QString szMessage; /**< The message which triggered the notifier */ - unsigned int uMessageLifetime; /**< The timeout of the notifier; 0 means no hide */ -} KviNotifierMessageParam; - -typedef struct _KviDBusNotifierMessageQueue -{ - QStringList lMessages; -} KviDBusNotifierMessageQueue; - - -#ifdef Unsorted - #undef Unsorted -#endif -#ifdef None - #undef None -#endif - -class KVIRC_API KviApp : public KviTalApplication -{ - friend class KviFrame; - friend class KviWindow; - friend class KviSetupWizard; // this resides in a module! - Q_OBJECT -public: - KviApp(int &argc,char ** argv); - ~KviApp(); - -protected: - // directories - QString m_szGlobalKvircDir; - QString m_szLocalKvircDir; - int m_iHeartbeatTimerId; - bool m_bFirstTimeRun; - bool m_bClosingDown; -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - bool m_bPortable; -#endif - KviWindow * m_pActiveWindow; - bool m_bUpdateGuiPending; - KviPointerList * m_pPendingAvatarChanges; - bool m_bSetupDone; - KviPointerHashTable * m_pRecentChannelDict; -#ifdef COMPILE_PSEUDO_TRANSPARENCY - bool m_bUpdatePseudoTransparencyPending; -#endif -#ifndef COMPILE_NO_IPC - KviIpcSentinel * m_pIpcSentinel; -#endif - QFont m_fntDefaultFont; -public: - // setup stuff (accessed from kvi_main.cpp: consider private othwerise) - QString m_szConfigFile; // setup - bool m_bCreateConfig; // setup - KviCString m_szExecAfterStartup; - bool m_bShowSplashScreen; -public: - // FIXME: "Plugins" and "ConfigPlugins" should become "Modules" and "ConfigModules" - enum KvircSubdir - { - None, Pics, Config, - Help, HelpEN, HelpNoIntl, - Log, Incoming, Audio, - Scripts, Plugins, ConfigPlugins, - Trash, MsgColors, Charmaps, - Avatars, DefScript, License, - Modules, ConfigScripts, Filters, - Tmp, Locale, Themes, - Classes, SmallIcons, EasyPlugins - }; - -public: - void destroyFrame(); - void setup(); // THIS SHOULD BE PRIVATE! (but is accessed from kvi_main.cpp) - -#ifndef COMPILE_NO_IPC - void ipcMessage(char * message); -#endif - - static int getGloballyUniqueId(); // returns an unique integer identifier across the application - - bool firstTimeRun() const { return m_bFirstTimeRun; }; - bool kviClosingDown() const { return m_bClosingDown; }; - - inline bool supportsCompositing() - { -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - //we need >= win2000 - return true; -#endif -#ifdef COMPILE_X11_SUPPORT - return QX11Info::isCompositingManagerRunning(); -#endif -#ifdef COMPILE_ON_MAC - return true; -#endif - return false; - }; - void setupBegin(); - void setupFinish(); - - /* - Unused - inline void emitRecentUrlsChanged() { emit(recentUrlsChanged()); }; - */ - - // kvi_app.cpp (Saving options) - void saveIrcServerDataBase(); - void saveProxyDataBase(); - void saveRecentEntries(); - void saveAppEvents(); - void saveRawEvents(); - void saveMediaTypes(); - void saveRegisteredUsers(); - void saveSharedFiles(); - void savePopups(); - void saveAliases(); - void saveNickServ(); - void saveIdentityProfiles(); - void saveDefaultScripts(); - void saveTextIcons(); - void saveRegisteredChannels(); - void saveInputHistory(); - void saveAvatarCache(); - void saveToolBars(); - void saveActions(); - void saveScriptAddons(); - void saveIdentities(); - - // kvi_options.cpp : Options saving and loading (kvi.main.conf)) - void loadOptions(); - void saveOptions(); - - void listAvailableOptions(KviWindow *wnd); - bool getOptionString(const QString &optName,QString &buffer); - bool setOptionValue(const QString &optName,const QString &value); - bool setCommonOptionValue(const QString &optName,const QString &value); - - void optionResetUpdate(int flags); - - // kvi_app_fs.cpp : Filesystem thingies - void getGlobalKvircDirectory(QString &szData,KvircSubdir dir,const QString &appendFile = QString()); - void getLocalKvircDirectory(QString &szData,KvircSubdir dir,const QString &appendFile = QString(),bool bCreateIfNeeded = true); - - void getTmpFileName(QString &szBuffer,const QString &szEndingFileName = QString()); - void getChannelDumpLogFileName(QString &str); - - static QTextCodec * defaultTextCodec(); - static QTextCodec * defaultSrvCodec(); - - bool findImageInImageSearchPath(QString &szRetPath,const QString &filename); - - bool findImage(QString &szRetPath,const QString &filename); - bool findImageThemeOnlyCompat(QString &szRetPath,const QString &filename); // temporary compat, will be removed soon (do not use) - bool findSmallIcon(QString &szRetPath,const QString &filename); - // tries to map the full path filename to one of the KVIrc's mapped directories - // if it doesn't succeed it just returns the complete filename in szRetPath - //bool mapImageFile(KviCString &szRetPath,const char * filename); - bool mapImageFile(QString &szRetPath,const QString &filename); - - //void getDefaultDccSaveFilePath(KviCString &path,const char *filename); - void completeDirectory(const QString &word,KviPointerList * matches); - // - // Returns a config path suitable for reading (at least) - // First lookups the user local config directory, - // if no config file is found, it earches in the global one - // returns false if no config file has been found - // If bNoFail is true, the buffer is filled with the file name even - // if no config file has been found: in this case the local config - // directory is used - // - bool getReadOnlyConfigPath(QString &buffer,const char *config_name,KvircSubdir sbd = Config,bool bNoFail = false); - - - /// - /// Attempts to locate the audio file specified by szFileName and put it's - /// absolute path in szRetPath. Returns true if the audio file is found and false otherwise. - /// - /// If szFileName is already an absolute path then it's returned directly - /// after testing for its existence. If szFileName is not an absolute path - /// then it's searched in the local KVIrc "audio" directory, then in the global one - /// and finally in the user's home. - /// - bool findAudioFile(QString &szRetPath,const QString &szFileName); - - // kvi_app.cpp : Window stuff - KviWindow * findWindow(const QString &windowId); - KviWindow * findWindowByCaption(const QString &windowCaption,int iContextId=-1); - KviConsole * findConsole(unsigned int ircContextId); - KviConsole * findConsole(QString & servr,QString & nick); - KviConsole * topmostConnectedConsole(); - KviConsole * activeConsole(); - bool windowExists(KviWindow *wnd); - bool connectionExists(KviIrcConnection *cnn); - unsigned int windowCount(); - - // kvi_app.cpp : Utilities - void resetAvatarForMatchingUsers(KviRegisteredUser * u); - void restartNotifyLists(); - void restartLagMeters(); - void triggerUpdateGui(); -#ifdef COMPILE_PSEUDO_TRANSPARENCY - void triggerUpdatePseudoTransparency(); -#endif - - // kvi_app.cpp : DCC (and CTCP AVATAR & SOUND) related stuff - void setAvatarOnFileReceived(KviConsole * pConsole,const QString &szRemoteUrl,const QString &szNick,const QString &szUser,const QString &szHost); - KviPendingAvatarChange * findPendingAvatarChange(KviConsole * pConsole,const QString &szNick,const QString &szRemoteUrl); - void fileDownloadTerminated(bool bSuccess,const QString &szRemoteUrl,const QString &szLocalFileName,const QString &szNick = QString(),const QString &szError = QString(),bool bQuiet = false); - - void setAvatarFromOptions(); - - // uMessageLifetime is in seconds! and 0 means "forever" - void notifierMessage(KviWindow * pWnd,int iIconId,const QString &szMsg,unsigned int uMessageLifetime); - - void addRecentNickname(const QString& newNick); - void addRecentChannel(const QString& chan,const QString& net); - - QStringList * recentChannelsForNetwork(const QString& net); - - KviPointerHashTable * recentChannels() const - { - return m_pRecentChannelDict; - } - - - void addRecentServer(const QString& server); - void fillRecentServersPopup(KviTalPopupMenu * m); - void fillRecentNicknamesPopup(KviTalPopupMenu * m,KviConsole * pConsole); - void fillRecentChannelsPopup(KviTalPopupMenu * m,KviConsole * pConsole); -// - void autoConnectToServers(); - - void checkSuggestRestoreDefaultScript(); - - void loadDefaultScript(QString szItem = QString()); - QStyle * themedStyle(); -protected: - void buildRecentChannels(); - void saveRecentChannels(); - // kvi_app.cpp : KviWindow global database - void registerWindow(KviWindow *wnd); - void unregisterWindow(KviWindow *wnd); - void frameDestructorCallback(); - void heartbeat(kvi_time_t tNow); - virtual void timerEvent(QTimerEvent *e); -public slots: - // kvi_app.cpp : Slots - void saveConfiguration(); - void updateGui(); - void updatePseudoTransparency(); - void restoreDefaultScript(); - void addRecentUrl(const QString& text); -private: - void createSplashScreen(); - void destroySplashScreen(); - - // kvi_app_setup.cpp : Setup stuff - void loadDirectories(); - void findGlobalKvircDirectory(); - bool findLocalKvircDirectory(); - bool checkGlobalKvircDirectory(const QString); - bool checkLocalKvircDirectory(const QString &szSpecificPath); - bool checkLocalKvircDirectory(); // check the m_szLocalKvircDirectory path - bool checkFileAssociations(); - void setupFileAssociations(); - - bool checkUriAssociations(const char * proto); - void setupUriAssociations(const char * proto); - - void saveKvircDirectory(); - - // kvi_app.cpp : GUI stuff - void updateApplicationFont(); - -#ifdef COMPILE_PSEUDO_TRANSPARENCY - void createGlobalBackgrounds(QPixmap * pix); - void destroyPseudoTransparency(); -#endif //COMPILE_PSEUDO_TRANSPARENCY -private: - // kvi_app.cpp : parts of setup() - void loadRecentEntries(); -#ifndef COMPILE_NO_IPC - void createIpcSentinel(); - void destroyIpcSentinel(); -#endif //!COMPILE_NO_IPC - void createFrame(); -signals: - void reloadImages(); - void updateNotifier(); - void recentUrlsChanged(); -}; - -#ifndef _KVI_APP_CPP_ - extern KVIRC_API KviApp * g_pApp; - extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; -#endif - -#endif //_KVI_APP_H_ diff --git a/src/kvirc/kernel/kvi_app_fs.cpp b/src/kvirc/kernel/kvi_app_fs.cpp deleted file mode 100644 index c312c0073..000000000 --- a/src/kvirc/kernel/kvi_app_fs.cpp +++ /dev/null @@ -1,603 +0,0 @@ -//============================================================================= -// -// File : kvi_app_fs.cpp -// Creation date : Thu Dec 24 1998 04:05:26 by Szymon Stefanek -// -// This file is part of the Kvirc irc client distribution -// Copyright (C) 1998-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_debug.h" -#include "kvi_app.h" -#include "KviLocale.h" -#include "KviFileUtils.h" -#include "KviMediaType.h" -#include "KviEnvironment.h" -#include "KviTimeUtils.h" -#include "kvi_options.h" -#include "kvi_defaults.h" -#include "kvi_iconmanager.h" - -#include -#include -#include - -extern KviMediaManager * g_pMediaManager; - -//============ getGlobalKvircDirectory ================// - -void KviApp::getGlobalKvircDirectory(QString &szData,KvircSubdir dir,const QString &appendFile) -{ - szData=m_szGlobalKvircDir; - KviQString::ensureLastCharIs(szData,KVI_PATH_SEPARATOR_CHAR); - - switch(dir) - { - case None : break; - case Pics : szData.append("pics"); break; - case Modules : - #ifdef KVIRC_MODULES_DIR - szData = KVIRC_MODULES_DIR; - #else - szData.append("modules"); - #endif - break; - case Plugins : szData.append("modules"); break; - case EasyPlugins : szData.append("easyplugins"); break; - case ConfigPlugins : KviQString::appendFormatted(szData,"config%smodules",KVI_PATH_SEPARATOR); break; - case ConfigScripts : KviQString::appendFormatted(szData,"config%sscripts",KVI_PATH_SEPARATOR); break; - case Help : - szData.append("help"); - { - // Localized help - QString tmp(KviLocale::localeName().ptr()); - tmp.prepend(KVI_PATH_SEPARATOR_CHAR); - tmp.prepend(szData); - if(KviFileUtils::directoryExists(tmp))szData = tmp; - else { - tmp = szData; KviQString::appendFormatted(tmp,"%sen",KVI_PATH_SEPARATOR); - if(KviFileUtils::directoryExists(tmp))szData = tmp; - } - } - break; - case HelpEN : KviQString::appendFormatted(szData,"help%sen",KVI_PATH_SEPARATOR); break; - case HelpNoIntl : szData.append("help"); break; - case Log : qDebug("WARNING Global log directory requested!"); break; - case Incoming : qDebug("WARNING Global incoming directory requested!"); break; - case Trash : qDebug("WARNING Global trash directory requested!"); break; - case Config : szData.append("config"); break; - case Audio : szData.append("audio"); break; - case Scripts : szData.append("scripts"); break; - case MsgColors : szData.append("msgcolors"); break; - case Charmaps : szData.append("charmaps"); break; - case Avatars : szData.append("avatars"); break; - case DefScript : szData.append("defscript"); break; - case License : szData.append("license"); break; - case Filters : szData.append("filters"); break; - case Locale : szData.append("locale"); break; - case Tmp : qDebug("WARNING Global tmp directory requested!"); break; - case Themes : szData.append("themes"); break; - case Classes : szData.append("classes"); break; - case SmallIcons : szData.append("pics"KVI_PATH_SEPARATOR KVI_SMALLICONS_SUBDIRECTORY); break; - } - - if(!appendFile.isEmpty()) - { - KviQString::ensureLastCharIs(szData,KVI_PATH_SEPARATOR_CHAR); - szData.append(appendFile); - } - - KviFileUtils::adjustFilePath(szData); -} - -void KviApp::getLocalKvircDirectory(QString &szData,KvircSubdir dir,const QString & appendFile,bool bCreateIfNeeded) -{ - szData=m_szLocalKvircDir; - KviQString::ensureLastCharIs(szData,KVI_PATH_SEPARATOR_CHAR); - - switch(dir) - { - case None : break; - case Pics : szData.append("pics"); break; - case EasyPlugins : szData.append("easyplugins"); break; - case Config : szData.append("config"); break; - case ConfigPlugins : szData.append("config"KVI_PATH_SEPARATOR"modules"); break; - case ConfigScripts : szData.append("config"KVI_PATH_SEPARATOR"scripts"); break; - case Log : - szData = KVI_OPTION_STRING(KviOption_stringLogsPath); - // we should take special care here - // the user is likely to mess the path behind our back - // try to recover from most common problems - while(szData.endsWith(KVI_PATH_SEPARATOR_CHAR)) - szData = szData.remove(szData.length()-1,1); - if(szData.isEmpty()) - { - szData = m_szLocalKvircDir; - if(!szData.endsWith(QString(QChar(KVI_PATH_SEPARATOR_CHAR)))) - szData.append(KVI_PATH_SEPARATOR_CHAR); - szData.append("log"); - KVI_OPTION_STRING(KviOption_stringLogsPath) = szData; - } - break; - case Incoming : - szData = KVI_OPTION_STRING(KviOption_stringIncomingPath); - // we should take special care here - // the user is likely to mess the path behind our back - // try to recover from most common problems - while(szData.endsWith(KVI_PATH_SEPARATOR_CHAR)) - szData = szData.remove(szData.length()-1,1); - if(szData.isEmpty()) - { -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - if(m_bPortable) - { - szData = m_szLocalKvircDir; - } else { -#endif - szData = QDir::homePath(); -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - } -#endif - if(!szData.endsWith(QString(QChar(KVI_PATH_SEPARATOR_CHAR)))) - szData.append(KVI_PATH_SEPARATOR_CHAR); - szData.append(KVI_DEFAULT_INCOMING_SUBDIRECTORY_NAME); - KVI_OPTION_STRING(KviOption_stringLogsPath) = szData; - } - break; - case Help : - szData.append("help"); - { - // Localized help - QString tmp = KviLocale::localeName().ptr(); - tmp.prepend(KVI_PATH_SEPARATOR_CHAR); - tmp.prepend(szData); - if(KviFileUtils::directoryExists(tmp))szData = tmp; - else { - tmp = szData; tmp.append(KVI_PATH_SEPARATOR"en"); - if(KviFileUtils::directoryExists(tmp))szData = tmp; - } - } - break; - case HelpEN : szData.append("help"KVI_PATH_SEPARATOR"en"); break; - case HelpNoIntl : szData.append("help"); break; - case Audio : szData.append("audio"); break; - case Scripts : szData.append("scripts"); break; - case Modules : - case Plugins : szData.append("modules"); break; - case Trash : szData.append("trash"); break; - case MsgColors : szData.append("msgcolors"); break; - case Charmaps : szData.append("charmaps"); break; - case Avatars : szData.append("avatars"); break; - case License : szData.append("license"); break; - case Filters : szData.append("filters"); break; - case Tmp : szData.append("tmp"); break; - case Locale : szData.append("locale"); break; - case Themes : szData.append("themes"); break; - case DefScript : szData.append("defscript"); /* should never happen! */ break; - case Classes : szData.append("classes"); break; - case SmallIcons : szData.append("pics"KVI_PATH_SEPARATOR KVI_SMALLICONS_SUBDIRECTORY); break; - } - if(bCreateIfNeeded)KviFileUtils::makeDir(szData); - - if(!appendFile.isEmpty()) - { - KviQString::ensureLastCharIs(szData,KVI_PATH_SEPARATOR_CHAR); - szData.append(appendFile); - } - - KviFileUtils::adjustFilePath(szData); -} - -void KviApp::getTmpFileName(QString &szBuffer,const QString &szEndingFileName) -{ - QString tmp; - getLocalKvircDirectory(tmp,Tmp); - KviQString::ensureLastCharIs(tmp,KVI_PATH_SEPARATOR_CHAR); - - struct timeval tmv; - kvi_gettimeofday(&tmv,0); - - QString szFileName = szEndingFileName.isNull() ? QString("file.tmp") : szEndingFileName; - do { - szBuffer = tmp; - KviQString::appendFormatted(szBuffer,"kvirc_%d_%Q",tmv.tv_usec,&szFileName); - tmv.tv_usec++; - } while(KviFileUtils::fileExists(szBuffer)); -} - -void KviApp::completeDirectory(const QString &word,KviPointerList * matches) -{ - QString szDir = word; - QString szFile = word; - KviQString::cutToLast(szFile,KVI_PATH_SEPARATOR_CHAR); - KviQString::cutFromLast(szDir,KVI_PATH_SEPARATOR_CHAR); - KviFileUtils::adjustFilePath(szDir); - KviQString::ensureLastCharIs(szDir,KVI_PATH_SEPARATOR_CHAR); - QDir d(szDir); - - // FIXME: maybe check timestamps ? (old modules) - QStringList sl = d.entryList(QDir::Dirs); - QStringList::Iterator it; - - for(it = sl.begin();it != sl.end();++it) - { - QString * t = new QString(*it); - if(KviQString::equalCS(*t,".") || KviQString::equalCS(*t,"..")) - { - delete t; - } else { -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - if(KviQString::equalCIN(szFile,*t,szFile.length())) -#else - if(KviQString::equalCSN(szFile,*t,szFile.length())) -#endif - { - t->prepend(szDir); - t->append(KVI_PATH_SEPARATOR_CHAR); - matches->append(t); - } else { - delete t; - } - } - } - - sl = d.entryList(QDir::Files); - - for(it = sl.begin();it != sl.end();++it) - { - QString * t = new QString(*it); -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - if(KviQString::equalCIN(szFile,*t,szFile.length())) -#else - if(KviQString::equalCSN(szFile,*t,szFile.length())) -#endif - { - t->prepend(szDir); - matches->append(t); - } else { - delete t; - } - } -} - - -//============= getChannelDumpLogFileName ==============// -// -// Returns a valid filename for the channel dump log -// - -void KviApp::getChannelDumpLogFileName(QString &str) -{ - unsigned int logN = 0; - QString fPrefix="kick_"; - do{ - QString fName; - KviQString::sprintf(fName,"%Q%u.log",&fPrefix,logN); - getLocalKvircDirectory(str,Log,fName); - logN++; - if(logN > 9999) - { - // Time to clear logs! :) - fPrefix+="x"; - logN = 0; - } - } while(KviFileUtils::fileExists(str)); - KviFileUtils::adjustFilePath(str); -} - -//========================= findImage ===========================// -// -// Find a file inside the default "Image" directories -// This should be thread safe (and in fact IS used by other threads) -// This function should be used only for finding the INTERNAL -// pixmaps... (so we expect them to be in the pics directory or -// Eventually in user's $HOME -// - -// FIXME: #warning "Check WHEN findImage is used and when findUserFile is used...we have a mess here" - -bool KviApp::findImageInImageSearchPath(QString &szRetPath,const QString &filename) -{ - // first lookup the user defined paths - for(QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).begin(); - it != KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).end();++it) - { - szRetPath = *it; - KviQString::ensureLastCharIs(szRetPath,KVI_PATH_SEPARATOR_CHAR); - szRetPath.append(filename); - //qDebug("LOOK FOR %s",szRetPath.ptr()); - if(KviFileUtils::fileExists(szRetPath))return true; - } - - return false; -} - -static KviApp::KvircSubdir pics_localsubdirs[2]={ KviApp::Pics, KviApp::Avatars }; -static KviApp::KvircSubdir pics_globalsubdirs[2]={ KviApp::Pics, KviApp::Avatars }; - -/*bool KviApp::mapImageFile(KviCString &szRetPath,const char * filename) -{ - QString buff; - bool ret=mapImageFile(buff,filename); - szRetPath=buff; - return ret; -}*/ - -bool KviApp::mapImageFile(QString &szRetPath,const QString &filename) -{ - szRetPath = filename; - // can't map non absolute paths - if(!KviFileUtils::isAbsolutePath(filename))return false; - // can't map non existing paths - if(!KviFileUtils::fileExists(filename))return false; - - QFileInfo fi = QFileInfo(filename); - - unsigned int size = fi.size(); - - QString szBestMatch; - - while(szRetPath.indexOf(KVI_PATH_SEPARATOR) != -1) - { - KviQString::cutToFirst(szRetPath,KVI_PATH_SEPARATOR); - - if(szRetPath.isEmpty())break; - - QString szBuffer; - - int i; - - for(i=0;i<2;i++) - { - getLocalKvircDirectory(szBuffer,pics_localsubdirs[i],szRetPath); - if(KviFileUtils::fileExists(szBuffer)) - { - QFileInfo fi2(szBuffer); - if(size == fi2.size()) - { - // probably the same file - szBestMatch = szRetPath; - } - } - } - - for(i=0;i<2;i++) - { - getGlobalKvircDirectory(szBuffer,pics_globalsubdirs[i],szRetPath); - //qDebug("CHECK %s",szBuffer.ptr()); - if(KviFileUtils::fileExists(szBuffer)) - { - QFileInfo fi2(szBuffer); - if(size == fi2.size()) - { - // probably the same file - szBestMatch = szRetPath; - } - } - } - - // Last resort - szBuffer = QDir::homePath(); - KviQString::ensureLastCharIs(szBuffer,KVI_PATH_SEPARATOR_CHAR); - szBuffer.append(szRetPath); - if(KviFileUtils::fileExists(szBuffer)) - { - QFileInfo fi2(szBuffer); - if(size == fi2.size()) - { - // prolly the same file - szBestMatch = szRetPath; - } - } - } - - if(!szBestMatch.isEmpty()) - { - szRetPath = szBestMatch; - return true; - } - - - // no way to map it :/ - szRetPath = filename; - return false; -} - -bool KviApp::findImage(QString &szRetPath,const QString &filename) -{ - // Find an user file... - if(KviFileUtils::isAbsolutePath(filename)) - { - szRetPath=filename; - return KviFileUtils::fileExists(filename); - } - - // if we have a theme, look it up as first - if(!KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).isEmpty()) - { - QString szTmp = KVI_OPTION_STRING(KviOption_stringIconThemeSubdir); - szTmp.append(KVI_PATH_SEPARATOR_CHAR); - szTmp.append(filename); - - getLocalKvircDirectory(szRetPath,KviApp::Themes,szTmp); - if(KviFileUtils::fileExists(szRetPath))return true; - - getGlobalKvircDirectory(szRetPath,KviApp::Themes,szTmp); - if(KviFileUtils::fileExists(szRetPath))return true; - } - - int i; - - for(i=0;i<2;i++) - { - getLocalKvircDirectory(szRetPath,pics_localsubdirs[i],filename); - if(KviFileUtils::fileExists(szRetPath))return true; - } - - for(i=0;i<2;i++) - { - getGlobalKvircDirectory(szRetPath,pics_globalsubdirs[i],filename); - if(KviFileUtils::fileExists(szRetPath))return true; - } - - if(findImageInImageSearchPath(szRetPath,filename))return true; - - // Last resort - szRetPath = QDir::homePath(); - KviQString::ensureLastCharIs(szRetPath,KVI_PATH_SEPARATOR_CHAR); - szRetPath.append(filename); - if(KviFileUtils::fileExists(szRetPath))return true; - - szRetPath = filename; - - return false; -} - -bool KviApp::findImageThemeOnlyCompat(QString &szRetPath,const QString &filename) -{ - // if we have a theme, look it up as first - if(!KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).isEmpty()) - { - QString szTmp = KVI_OPTION_STRING(KviOption_stringIconThemeSubdir); - szTmp.append(KVI_PATH_SEPARATOR_CHAR); - szTmp.append(filename); - - getLocalKvircDirectory(szRetPath,KviApp::Themes,szTmp); - if(KviFileUtils::fileExists(szRetPath))return true; - - getGlobalKvircDirectory(szRetPath,KviApp::Themes,szTmp); - if(KviFileUtils::fileExists(szRetPath))return true; - } - - getLocalKvircDirectory(szRetPath,KviApp::Pics,filename); - if(KviFileUtils::fileExists(szRetPath))return true; - - - if(findImageInImageSearchPath(szRetPath,filename))return true; - - szRetPath = filename; - - return false; -} - -bool KviApp::findSmallIcon(QString &szRetPath,const QString &filename) -{ - // this is a bit optimized for the small builtin icons - // looks up less places. - - //if(kvi_isAbsolutePath(filename)) - //{ - // BUG!.. we should never - //szRetPath=filename; - //return KviFileUtils::fileExists(filename); - //} - - // if we have a theme, look it up as first - if(!KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).isEmpty()) - { - QString szTmp = KVI_OPTION_STRING(KviOption_stringIconThemeSubdir); - szTmp.append(KVI_PATH_SEPARATOR_CHAR); - szTmp.append(KVI_SMALLICONS_SUBDIRECTORY); - szTmp.append(KVI_PATH_SEPARATOR_CHAR); - szTmp.append(filename); - - getLocalKvircDirectory(szRetPath,KviApp::Themes,szTmp); - if(KviFileUtils::fileExists(szRetPath))return true; - - getGlobalKvircDirectory(szRetPath,KviApp::Themes,szTmp); - if(KviFileUtils::fileExists(szRetPath))return true; - } - - // unlikely - getLocalKvircDirectory(szRetPath,KviApp::SmallIcons,filename); - if(KviFileUtils::fileExists(szRetPath))return true; - - getLocalKvircDirectory(szRetPath,KviApp::Pics,filename); - if(KviFileUtils::fileExists(szRetPath))return true; - - // likely - getGlobalKvircDirectory(szRetPath,KviApp::SmallIcons,filename); - if(KviFileUtils::fileExists(szRetPath))return true; - - if(findImageInImageSearchPath(szRetPath,filename))return true; - - // Last resort... bleah :/ - szRetPath = QDir::homePath(); - KviQString::ensureLastCharIs(szRetPath,KVI_PATH_SEPARATOR_CHAR); - szRetPath.append(filename); - if(KviFileUtils::fileExists(szRetPath))return true; - - szRetPath = filename; - - return false; -} - -bool KviApp::findAudioFile(QString &szRetPath,const QString &szFileName) -{ - if(KviFileUtils::isAbsolutePath(szFileName)) - { - szRetPath = szFileName; - return KviFileUtils::fileExists(szFileName); - } - - getLocalKvircDirectory(szRetPath,KviApp::Audio,szFileName); - if(KviFileUtils::fileExists(szRetPath)) - return true; - - getGlobalKvircDirectory(szRetPath,KviApp::Audio,szFileName); - if(KviFileUtils::fileExists(szRetPath)) - return true; - - // Last resort - szRetPath = QDir::homePath(); - KviQString::ensureLastCharIs(szRetPath,KVI_PATH_SEPARATOR_CHAR); - szRetPath.append(szFileName); - if(KviFileUtils::fileExists(szRetPath)) - return true; - - szRetPath = szFileName; - - return false; -} - - -//================== getReadOnlyConfigPath ====================// -// -// We want to READ a config file...find it -// - -bool KviApp::getReadOnlyConfigPath(QString &buffer,const char *config_name,KvircSubdir sbd,bool bNoFail) -{ - // Take a look in the local directory.... - getLocalKvircDirectory(buffer,sbd,config_name); - //qDebug("%s %s %i |%s| %i",__FILE__,__FUNCTION__,__LINE__,buffer.ptr(),KviFileUtils::fileExists(buffer.ptr())); - if(!KviFileUtils::fileExists(buffer)) - { - // No saved config yet... check for defaults - QString tmp; - getGlobalKvircDirectory(tmp,sbd,config_name); - if(!KviFileUtils::fileExists(tmp)) - { - // No defaults...no such config file at all. - if(bNoFail)getLocalKvircDirectory(buffer,sbd,config_name); - return false; - } else buffer = tmp; // get the defaults this time - } // else file exists... - return true; -} diff --git a/src/kvirc/kernel/kvi_app_setup.cpp b/src/kvirc/kernel/kvi_app_setup.cpp deleted file mode 100644 index d0889f62b..000000000 --- a/src/kvirc/kernel/kvi_app_setup.cpp +++ /dev/null @@ -1,856 +0,0 @@ -//============================================================================= -// -// File : kvi_app_setup.cpp -// Creation date : Fri Apr 2 1999 02:38:05 by Szymon Stefanek -// -// This file is part of the Kvirc irc client distribution -// Copyright (C) 1999-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - - - -//#define _KVI_DEBUG_CHECK_RANGE_ -//#include "kvi_debug.h" - -#include "kvi_settings.h" -#include "kvi_defaults.h" -#include "kvi_window.h" -#include "kvi_frame.h" -#include "kvi_app.h" -#include "KviFileUtils.h" -#include "KviLocale.h" -#include "kvi_msgbox.h" -#include "kvi_sourcesdate.h" -#include "kvi_iconmanager.h" -#include "KviConfigurationFile.h" - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - #include - #include // at least for GetModuleFileName and *PrivateProfileString -#else - #include // for getenv() - #include // for symlink() <-- unused ? - - #ifdef COMPILE_KDE_SUPPORT - #include - #include -// #include - #endif -#endif - -#include -#include -#include -#include -#include - -static QLibrary * g_pSetupLibrary = 0; - -// -// Things launched at startup: -// - Attempt to find the global Kvirc directory -// - Attempt to find the local Kvirc directory -// and if it is not found, ask the user to choose one -// - -bool KviApp::checkGlobalKvircDirectory(const QString szDir) -{ - //First check if the help subdir exists - QString szHelpDir = szDir; - szHelpDir += KVI_PATH_SEPARATOR"help"; - if(!KviFileUtils::directoryExists(szHelpDir)) - return false; - //Then check if the pics subdir exists - QString szPicsDir = szDir; - szPicsDir += KVI_PATH_SEPARATOR"pics"; - if(!KviFileUtils::directoryExists(szPicsDir)) - return false; - //Now make sure that it is the dir that we're looking for. - //Check for an image file that we need. - szPicsDir.append(KVI_PATH_SEPARATOR); - szPicsDir.append(KVI_ACTIVITYMETER_IMAGE_NAME); - return KviFileUtils::isReadable(szPicsDir); -} - -bool KviApp::checkLocalKvircDirectory(const QString &szSpecificPath) -{ - QString szSavedLocalKvircDir = m_szLocalKvircDir; - m_szLocalKvircDir = szSpecificPath; - bool bRet = checkLocalKvircDirectory(); - m_szLocalKvircDir = szSavedLocalKvircDir; - return bRet; -} - -bool KviApp::checkLocalKvircDirectory() -{ - //First check if the dir exists - if(!KviFileUtils::directoryExists(m_szLocalKvircDir)) - return false; - if(!QFileInfo(m_szLocalKvircDir).isWritable()) - return false; - - QString szBuff; - getLocalKvircDirectory(szBuff,Config); - if(!KviFileUtils::directoryExists(szBuff)) - return false; - - return true; -} - -bool KviApp::checkFileAssociations() -{ -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) -#define QUERY_BUFFER 2048 - char * pcBuffer; - DWORD len = QUERY_BUFFER; - DWORD err; - pcBuffer = (char*)malloc(len*sizeof(char)); - HKEY hKey; - - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,".kvs",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if((err=RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - if(!kvi_strEqualCIN("KVIrcScript",pcBuffer,11)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if((err=RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - if(!kvi_strEqualCI(__tr2qs("KVIrc KVS Script").toLocal8Bit().data(),pcBuffer)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\DefaultIcon",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if(RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - QString szIcon = applicationFilePath()+",1"; - szIcon.replace('/',"\\"); - if(!kvi_strEqualCI(szIcon.toLocal8Bit().data(),pcBuffer)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\Shell\\Parse",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if(RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - if(!kvi_strEqualCI(__tr2qs("Run KVS Script").toLocal8Bit().data(),pcBuffer)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\Shell\\Parse\\command",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if(RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - QString szCmd = applicationFilePath()+" \"%1\""; - szCmd.replace('/',"\\"); - if(!kvi_strEqualCI(szCmd.toLocal8Bit().data(),pcBuffer)) - { - free(pcBuffer); - return false; - } - } - - //Config - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,".kvc",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if( (err=RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - if(!kvi_strEqualCIN("KVIrcConfig",pcBuffer,11)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcConfig",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - //Addon - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,".kva",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if((err=RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - if(!kvi_strEqualCIN("KVIrcAddon",pcBuffer,11)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - //Theme - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,".kvt",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if((err=RegQueryValueEx( hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - if(!kvi_strEqualCIN("KVIrcTheme",pcBuffer,11)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme",0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - free(pcBuffer); -#endif - return true; - -} - - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) -bool KviApp::checkUriAssociations(const char * pcProto) -{ -#define QUERY_BUFFER 2048 - char * pcBuffer; - DWORD len = QUERY_BUFFER; - DWORD err; - pcBuffer = (char*)malloc(len*sizeof(char)); - HKEY hKey; - - KviCString szStoredKey = pcProto; - KviCString szKey = szStoredKey; - - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,szKey,0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if((err=RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - if(!kvi_strEqualCI(__tr2qs("URL:IRC Protocol").toLocal8Bit().data(),pcBuffer)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - if((err=RegQueryValueEx(hKey,"URL Protocol",0,0,(LPBYTE)pcBuffer,&len)) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - szKey = szStoredKey + "\\DefaultIcon"; - len = QUERY_BUFFER; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,szKey,0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if(RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - QString szIcon = applicationFilePath() + ",0"; - szIcon.replace('/',"\\"); - if(!kvi_strEqualCI(szIcon.toLocal8Bit().data(),pcBuffer)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - szKey = szStoredKey + "\\Shell\\open"; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,szKey,0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if(RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - if(!kvi_strEqualCI(__tr2qs("Open with KVIrc").toLocal8Bit().data(),pcBuffer)) - { - free(pcBuffer); - return false; - } - } - - len = QUERY_BUFFER; - szKey = szStoredKey + "\\Shell\\open\\command"; - if(RegOpenKeyEx(HKEY_CLASSES_ROOT,szKey,0,KEY_READ,&hKey) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } - - if(RegQueryValueEx(hKey,0,0,0,(LPBYTE)pcBuffer,&len) != ERROR_SUCCESS) - { - free(pcBuffer); - return false; - } else { - QString szCmd = applicationFilePath() + " \"%1\""; - szCmd.replace('/',"\\"); - if(!kvi_strEqualCI(szCmd.toLocal8Bit().data(),pcBuffer)) - { - free(pcBuffer); - return false; - } - } - - free(pcBuffer); -#else -bool KviApp::checkUriAssociations(const char *) -{ -#endif - return true; -} - - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) -void KviApp::setupUriAssociations(const char * pcProto) -{ - HKEY hKey; - DWORD err; - - KviCString szStoredKey = pcProto; - KviCString szKey = szStoredKey; - - QByteArray tmp; - QString szAppPath = applicationFilePath(); - szAppPath.replace('/',"\\"); - - SHDeleteKey(HKEY_CLASSES_ROOT,szKey); - - err = RegCreateKeyEx(HKEY_CLASSES_ROOT,szKey,0,0,0,KEY_WRITE,0,&hKey,0); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"URL:IRC Protocol",16); - RegSetValueEx(hKey,"URL Protocol",0,REG_SZ,(LPBYTE)"",0); - - szKey = szStoredKey + "\\DefaultIcon"; - RegCreateKeyEx(HKEY_CLASSES_ROOT,szKey,0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + ",0").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - szKey = szStoredKey + "\\Shell\\open"; - RegCreateKeyEx(HKEY_CLASSES_ROOT,szKey,0,0,0,KEY_WRITE,0,&hKey,0); - tmp = __tr2qs("Open with KVIrc").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - szKey = szStoredKey + "\\Shell\\open\\command"; - RegCreateKeyEx(HKEY_CLASSES_ROOT,szKey,0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + " --external \"%1\"").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); -#else -void KviApp::setupUriAssociations(const char *) -{ -#endif -} - -void KviApp::setupFileAssociations() -{ -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - HKEY hKey; - DWORD err; - - QByteArray tmp; - QString szAppPath = applicationFilePath(); - szAppPath.replace('/',"\\"); - - SHDeleteKey(HKEY_CLASSES_ROOT,".kvs"); - - err = RegCreateKeyEx(HKEY_CLASSES_ROOT,".kvs",0,0,0,KEY_WRITE,0,&hKey,0); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"KVIrcScript",11); - - SHDeleteKey(HKEY_CLASSES_ROOT,"KVIrcScript"); - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = __tr2qs("KVIrc KVS Script").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\DefaultIcon",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + ",1").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\Shell\\Parse",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = __tr2qs("Run KVS Script").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcScript\\Shell\\Parse\\command",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + " \"%1\"").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - //Configs - SHDeleteKey(HKEY_CLASSES_ROOT,".kvc"); - - err = RegCreateKeyEx(HKEY_CLASSES_ROOT,".kvc",0,0,0,KEY_WRITE,0,&hKey,0); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"KVIrcConfig",11); - - SHDeleteKey(HKEY_CLASSES_ROOT,"KVIrcConfig"); - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcConfig",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = __tr2qs("KVIrc Configuration File").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcConfig\\DefaultIcon",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + ",2").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - // Themes - SHDeleteKey(HKEY_CLASSES_ROOT,".kvt"); - - err = RegCreateKeyEx(HKEY_CLASSES_ROOT,".kvt",0,0,0,KEY_WRITE,0,&hKey,0); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"KVIrcTheme",11); - - SHDeleteKey(HKEY_CLASSES_ROOT,"KVIrcTheme"); - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = __tr2qs("KVIrc Theme Package").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme\\DefaultIcon",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + ",3").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme\\Shell\\Install",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = __tr2qs("Install Theme Package").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcTheme\\Shell\\Install\\command",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + " \"%1\"").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - //Addons - SHDeleteKey(HKEY_CLASSES_ROOT,".kva"); - - err = RegCreateKeyEx(HKEY_CLASSES_ROOT,".kva",0,0,0,KEY_WRITE,0,&hKey,0); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)"KVIrcAddon",11); - - SHDeleteKey(HKEY_CLASSES_ROOT,"KVIrcAddon"); - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = __tr2qs("KVIrc Addon Package").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon\\DefaultIcon",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + ",4").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon\\Shell\\Install",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = __tr2qs("Install Package").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - - RegCreateKeyEx(HKEY_CLASSES_ROOT,"KVIrcAddon\\Shell\\Install\\command",0,0,0,KEY_WRITE,0,&hKey,0); - tmp = QString(szAppPath + " \"%1\"").toLocal8Bit(); - RegSetValueEx(hKey,0,0,REG_SZ,(LPBYTE)tmp.data(),tmp.length()); - -#endif -} - -void KviApp::findGlobalKvircDirectory() -{ - // Look for the installation directory - // with the image and help files inside -#ifdef GLOBAL_KVIRC_DIR - m_szGlobalKvircDir = GLOBAL_KVIRC_DIR; - KviFileUtils::adjustFilePath(m_szGlobalKvircDir); - if(checkGlobalKvircDirectory(m_szGlobalKvircDir)) - return; -#endif //GLOBAL_KVIRC_DIR - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - - m_szGlobalKvircDir = applicationDirPath(); - KviFileUtils::adjustFilePath(m_szGlobalKvircDir); - if(checkGlobalKvircDirectory(m_szGlobalKvircDir)) - return; - - KviMessageBox::warning("Unable to find the shared Kvirc directory.\n"\ - "I have tried %Q, but it seemed to fail\n" \ - "Trying to run anyway...\n",&m_szGlobalKvircDir); -#else - - // Check for MacOS X Bundle compilation - #ifdef COMPILE_ON_MAC - m_szGlobalKvircDir = applicationDirPath(); - m_szGlobalKvircDir += "/../Resources/"; - #else - m_szGlobalKvircDir = KVIRC_RESOURCES_DIR; - #endif //COMPILE_ON_MAC - - if(checkGlobalKvircDirectory(m_szGlobalKvircDir)) - return; - - m_szGlobalKvircDir = ""; - - // DO NOT TRANSLATE THIS - // THE TRANSLATION DIRECTORY WAS NOT FOUND YET - // AND THE LOCALE IS NOT INITIALIZED AT ALL - - #ifdef COMPILE_KDE_SUPPORT - KviMessageBox::warning("Unable to find the shared Kvirc directory.\n"\ - "The usual path for this directory is $KDEDIR/share/apps/kvirc.\n"\ - "Are you sure that 'make install' worked correctly ?\n"\ - "Please make sure that you have the read permission to that directory\n"\ - "and you have set KDEDIR correctly. You may also try to rerun 'make install'.\n"\ - "A detailed explaination of the Kvirc directory system is in the INSTALL document\n"\ - "shipped with the kvirc source dirstribution.\n"\ - "Trying to run anyway..."); - #elif defined(COMPILE_ON_MAC) - KviMessageBox::warning("Unable to find the shared KVIrc directory.\n"\ - "The usual path for this directory is ./Contents/Resources/kvirc within your application bundle.\n"\ - "Something went wrong during the bundle creation.\n"\ - "Please read the documentation and make sure to set proper paths for --prefix, -bindir, -libdir and --datadir during the configure run.\n"\ - "Trying to run anyway...\n"); - #else //!defined(COMPILE_KDE_SUPPORT) && !defined(COMPILE_ON_MAC) - KviMessageBox::warning("Unable to find the shared KVIrc directory.\n"\ - "The usual path for this directory is /usr/local/share/kvirc.\n"\ - "Are you sure that 'make install' worked correctly ?\n"\ - "Please make sure that you have the read permission to that directory.\n"\ - "You may also need to rerun 'make install'.\n"\ - "A detailed explaination of the KVIrc directory system is in the INSTALL document\n"\ - "shipped with the kvirc source dirstribution.\n"\ - "Trying to run anyway...\n"); - #endif //!COMPILE_ON_MAC -#endif -} - - -bool KviApp::findLocalKvircDirectory() -{ - // Here we check if we already did the setup - // and we have the kvirc local directory saved somewhere -#ifdef COMPILE_KDE_SUPPORT - if(m_szConfigFile.isEmpty()) - { - // don't do that if user supplied a config file :) - KConfig oKCfg("kvirc"); - KConfigGroup oKCfgMainGroup(&oKCfg, "Main"); - - m_szLocalKvircDir = oKCfgMainGroup.readEntry("LocalKvircDirectory"); - - unsigned int uSourcesDate = oKCfgMainGroup.readEntry("SourcesDate").toInt(); - if(uSourcesDate < KVI_SOURCES_DATE_NUMERIC_FORCE_SETUP) - return false; // we force a setup anyway - - // If we have it, ok...done - if(checkLocalKvircDirectory()) - return true; - } -#endif //COMPILE_KDE_SUPPORT - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - if(m_bPortable) - { - m_szLocalKvircDir = g_pApp->applicationDirPath() + KVI_PATH_SEPARATOR_CHAR + "Settings"; - if(checkLocalKvircDirectory()) - return true; - } -#endif - //Check if we have a special .kvirc.rc in $HOME - QString szF = QDir::homePath(); - - if(!m_szConfigFile.isEmpty()) - { - QString szConfig = m_szConfigFile; - if(QDir::isRelativePath(szConfig)) - { - szF += KVI_PATH_SEPARATOR; - szF += szConfig; - } else { - szF = szConfig; - } - } else { - szF += KVI_PATH_SEPARATOR; - szF += KVI_HOME_CONFIG_FILE_NAME; - } - - //If the file exists, read the first non empty line. - KviConfigurationFile cfgx(szF,KviConfigurationFile::Read); - - cfgx.setGroup("Main"); - m_szLocalKvircDir = cfgx.readEntry("LocalKvircDirectory",""); - - unsigned int uSourcesDate = cfgx.readUIntEntry("SourcesDate",0); - if(uSourcesDate < KVI_SOURCES_DATE_NUMERIC_FORCE_SETUP) - return false; // we force a setup anyway - - // If we have it, ok...done - return checkLocalKvircDirectory(); -} - -void KviApp::loadDirectories() -{ - // First find the global (readable) one... - findGlobalKvircDirectory(); - // Init locale - QString szLocalePath = m_szGlobalKvircDir; - szLocalePath.append(KVI_PATH_SEPARATOR); - szLocalePath.append("locale"); - szLocalePath.append(KVI_PATH_SEPARATOR); - - KviLocale::init(this,szLocalePath); - - //__debug_1arg("Global Kvirc directory is %s",m_szGlobalKvircDir.ptr()); - // Now look for the local (writable) one - m_bFirstTimeRun = !findLocalKvircDirectory(); - - if(m_bFirstTimeRun) - setupBegin(); - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - if(m_bPortable) return; -#endif - if(!checkFileAssociations()) setupFileAssociations(); - if(!checkUriAssociations("irc")) setupUriAssociations("irc"); - if(!checkUriAssociations("ircs")) setupUriAssociations("ircs"); - if(!checkUriAssociations("irc6")) setupUriAssociations("irc6"); - if(!checkUriAssociations("ircs6")) setupUriAssociations("ircs6"); -} - -void KviApp::setupBegin() -{ - //We must do the setup...ask the user.. - QString szSetupLib; - -#ifdef KVIRC_MODULES_DIR - szSetupLib = KVIRC_MODULES_DIR; -#else - getGlobalKvircDirectory(szSetupLib,KviApp::Modules); -#endif - - KviQString::ensureLastCharIs(szSetupLib, KVI_PATH_SEPARATOR_CHAR); - -#if defined(COMPILE_ON_WINDOWS) - szSetupLib.append("kvisetup.dll"); -#elif defined(COMPILE_ON_MINGW) - szSetupLib.append("libkvisetup.dll"); -#else - szSetupLib.append("libkvisetup.so"); -#endif - g_pSetupLibrary = new QLibrary(szSetupLib); - if(!g_pSetupLibrary->load()) - { - KviMessageBox::warning(__tr2qs("Ops...it looks like I can't load modules on this sytem.\n" \ - "I have been looking for the %s library but I haven't been able to load it\n" \ - "due to the following error: \"%s\"\nAborting."),szSetupLib.toUtf8().data(),g_pSetupLibrary->errorString().toUtf8().data()); -#if defined(COMPILE_ON_WINDOWS) - ExitProcess(-1); -#elif defined(COMPILE_ON_MINGW) - ExitProcess(1); -#else - ::exit(-1); -#endif - } - - bool (*sfunc)() = (bool(*)())g_pSetupLibrary->resolve("setup_begin"); - if(!sfunc) - { - KviMessageBox::warning(__tr2qs("Ops...it looks like you have a broken distribution.\n" \ - "The setup module does not export the \"setup_begin\" function.\n" \ - "Aborting!")); -#if defined(COMPILE_ON_WINDOWS) - ExitProcess(-1); -#elif defined(COMPILE_ON_MINGW) - ExitProcess(1); -#else - ::exit(-1); -#endif - } - - bool bRet = sfunc(); - - if(!bRet) - { - KviMessageBox::warning(__tr2qs("Setup aborted")); -#if defined(COMPILE_ON_WINDOWS) - ExitProcess(-1); -#elif defined(COMPILE_ON_MINGW) - ExitProcess(1); -#else - ::exit(-1); -#endif - } - - // Now save it - //Let it be done by setup function -// saveKvircDirectory(); -} - -void KviApp::setupFinish() -{ - if(!g_pSetupLibrary) - { - qDebug("Oops... lost the setup library ?"); - return; - } - - void (*sfunc)() = (void(*)())g_pSetupLibrary->resolve("setup_finish"); - if(!sfunc) - { - KviMessageBox::warning(__tr2qs("Ops...it looks like you have a broken distribution.\n" \ - "The setup module does not export the \"setup_finish\" function.\n" \ - "Trying to continue anyway...")); - } - - sfunc(); - - g_pSetupLibrary->unload(); - delete g_pSetupLibrary; - g_pSetupLibrary = 0; -} - -void KviApp::saveKvircDirectory() -{ - // Here we save the local directory path -#ifdef COMPILE_KDE_SUPPORT - // In KDE we use the application config file - if(m_szConfigFile.isEmpty()) - { - // not if user supplied a config file - KConfig * pCfg = new KConfig("kvirc"); - KConfigGroup * pCfgMainGroup = new KConfigGroup(pCfg,"Main"); - if(pCfg) - { - if(pCfg->accessMode() == KConfig::ReadWrite) - { - pCfgMainGroup->writeEntry("LocalKvircDirectory",m_szLocalKvircDir); - pCfgMainGroup->writeEntry("SourcesDate",KVI_SOURCES_DATE_NUMERIC); - pCfg->sync(); - delete pCfgMainGroup; - pCfgMainGroup = 0; - return; - } - } - } -#endif //COMPILE_KDE_SUPPORT - // In NON-KDE we use $HOME/.kvirc.rc or $HOME/kvirc.ini - QString szF = QDir::homePath(); - if(!m_szConfigFile.isEmpty()) - { - //Must be changed from QString::fromLocal8Bit to QTextCodec::codecForLocale() - QString szConfig = m_szConfigFile; - if(QDir::isRelativePath(szConfig)) - { - szF += KVI_PATH_SEPARATOR; - szF += szConfig; - } else { - szF = szConfig; - } - } else { - szF += KVI_PATH_SEPARATOR; - szF += KVI_HOME_CONFIG_FILE_NAME; - } - //FIXME: LOCALE BROKEN!!! - - KviConfigurationFile cfgx(szF,KviConfigurationFile::Write); - - cfgx.setGroup("Main"); - cfgx.writeEntry("LocalKvircDirectory",m_szLocalKvircDir); - cfgx.writeEntry("SourcesDate",KVI_SOURCES_DATE_NUMERIC); -} diff --git a/src/kvirc/kernel/kvi_asynchronousconnectiondata.cpp b/src/kvirc/kernel/kvi_asynchronousconnectiondata.cpp deleted file mode 100644 index 9a208fd23..000000000 --- a/src/kvirc/kernel/kvi_asynchronousconnectiondata.cpp +++ /dev/null @@ -1,41 +0,0 @@ -//============================================================================= -// -// File : kvi_asynchronousconnectiondata.cpp -// Creation date : Sun 04 Jul 2004 16:22:25 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_asynchronousconnectiondata.h" - -KviAsynchronousConnectionData::KviAsynchronousConnectionData() -: KviHeapObject() -{ - m_pReconnectInfo=0; - bUseLastServerInContext = false; -} - -KviAsynchronousConnectionData::~KviAsynchronousConnectionData() -{ - if(m_pReconnectInfo) - delete m_pReconnectInfo; -} - diff --git a/src/kvirc/kernel/kvi_asynchronousconnectiondata.h b/src/kvirc/kernel/kvi_asynchronousconnectiondata.h deleted file mode 100644 index a863f2679..000000000 --- a/src/kvirc/kernel/kvi_asynchronousconnectiondata.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef _KVI_ASYNCHRONOUSCONNECTIONDATA_H_ -#define _KVI_ASYNCHRONOUSCONNECTIONDATA_H_ -//============================================================================= -// -// File : kvi_asynchronousconnectiondata.h -// Creation date : Sun 04 Jul 2004 16:22:25 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviHeapObject.h" -#include "KviIrcServer.h" - -class KviAsynchronousConnectionData : public KviHeapObject -{ -public: - KviAsynchronousConnectionData(); - ~KviAsynchronousConnectionData(); -public: - QString szServer; - bool bUseLastServerInContext; // this is checked ONLY if szServer is empty - kvi_u32_t uPort; - bool bPortIsOk; - bool bUseIPv6; - bool bUseSSL; - bool bSTARTTLS; - QString szBindAddress; // ip address (or interface name) to bind the connection to - QString szCommandToExecAfterConnect; - QString szLinkFilter; - QString szPass; - QString szNick; - QString szInitUMode; - QString szServerId; - KviIrcServerReconnectInfo * m_pReconnectInfo; -}; - -#endif //!_KVI_ASYNCHRONOUSCONNECTIONDATA_H_ diff --git a/src/kvirc/kernel/kvi_coreactions.cpp b/src/kvirc/kernel/kvi_coreactions.cpp deleted file mode 100644 index 231098808..000000000 --- a/src/kvirc/kernel/kvi_coreactions.cpp +++ /dev/null @@ -1,1179 +0,0 @@ -//============================================================================= -// -// File : kvi_coreactions.cpp -// Creation date : Mon 22 Nov 2004 02:30:47 by Szymon Stefanek -// -// This file is part of the KVIrc IRC Client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_coreactions.h" -#include "kvi_shortcuts.h" -#include "kvi_frame.h" -#include "KviLocale.h" -#include "kvi_irccontext.h" -#include "kvi_iconmanager.h" -#include "kvi_app.h" -#include "kvi_customtoolbar.h" -#include "kvi_actiondrawer.h" -#include "kvi_actionmanager.h" -#include "kvi_kvs_action.h" -#include "kvi_mdimanager.h" -#include "kvi_irctoolbar.h" -#include "KviLocale.h" -#include "kvi_ircurl.h" -#include "kvi_ircconnection.h" -#include "kvi_ircconnectionuserinfo.h" -#include "kvi_coreactionnames.h" -#include "kvi_ircconnectionserverinfo.h" -#include "kvi_kvs_script.h" -#include "KviTalPopupMenu.h" - -#include - -void register_core_actions(KviActionManager * m) -{ - m->registerAction(new KviConnectAction(m)); // this as parent will destroy it on exit! - m->registerAction(new KviSeparatorAction(m)); - m->registerAction(new KviIrcContextDisplayAction(m)); - m->registerAction(new KviJoinChannelAction(m)); - m->registerAction(new KviChangeNickAction(m)); - m->registerAction(new KviConnectToServerAction(m)); - m->registerAction(new KviChangeUserModeAction(m)); - m->registerAction(new KviGoAwayAction(m)); - m->registerAction(new KviIrcToolsAction(m)); - m->registerAction(new KviIrcOperationsAction(m)); - - KviAction * a; - -#define SCRIPT_ACTION(__name,__code,__visible,__description,__category,__icon,__smallicon,__flags,__accel) \ - a = new KviKvsAction(m, \ - QString(__name), \ - QString(__code), \ - QString(__visible), \ - QString(__description), \ - __category, \ - QString(__icon), \ - QString("%1").arg(__smallicon), \ - __flags, \ - __accel); \ - m->registerAction(a) - -#define SLOT_ACTION(__name,__object,__slot,__visible,__description,__category,__icon,__smallicon,__flags,__accel) \ - a = new KviAction(m, \ - QString(__name), \ - QString(__visible), \ - QString(__description), \ - __category, \ - QString(__icon), \ - QString("%1").arg(__smallicon), \ - __flags, \ - __accel); \ - QObject::connect(a,SIGNAL(activated()),__object,__slot); \ - m->registerAction(a) - - SCRIPT_ACTION( - KVI_COREACTION_SERVEROPTIONS, - "options.edit -t KviIrcServerOptionsWidget", - __tr2qs("Configure Servers..."), - __tr2qs("Allows you to configure the servers and eventually to connect to them"), - KviActionManager::categorySettings(), - "kvi_bigicon_servers.png", - KVI_SMALLICON_SERVER, - 0, - KVI_SHORTCUTS_SERVERS); - - SCRIPT_ACTION( - KVI_COREACTION_MANAGEADDONS, - "addon.dialog -t", - __tr2qs("Manage Addons..."), - __tr2qs("Allows you to manage the script-based addons"), - KviActionManager::categorySettings(), - "kvi_bigicon_addons.png", - KVI_SMALLICON_ADDONS, - 0, - KVI_SHORTCUTS_MANAGE_ADDONS); - - SCRIPT_ACTION( - KVI_COREACTION_EDITREGUSERS, - "reguser.edit -t", - __tr2qs("Configure Registered Users..."), - __tr2qs("Shows a dialog that allows editing the registered user entries"), - KviActionManager::categorySettings(), - "kvi_bigicon_regusers.png", - KVI_SMALLICON_REGUSERS, - 0, - KVI_SHORTCUTS_USERS); - - SCRIPT_ACTION( - KVI_COREACTION_IDENTITYOPTIONS, - "options.edit -t KviIdentityOptionsWidget", - __tr2qs("Configure Identity..."), - __tr2qs("Allows you to configure nickname, username, avatar etc..."), - KviActionManager::categorySettings(), - "kvi_bigicon_identity.png", - KVI_SMALLICON_WHO, - 0, - KVI_SHORTCUTS_IDENTITY); - - SCRIPT_ACTION( - KVI_COREACTION_SOCKETSPY, - "socketspy.open", - __tr2qs("Show SocketSpy..."), - __tr2qs("Shows a window that allows monitoring the socket traffic"), - KviActionManager::categoryScripting(), - "kvi_bigicon_socketspy.png", - KVI_SMALLICON_SPY, - KviAction::NeedsContext, - QString()); - - SCRIPT_ACTION( - KVI_COREACTION_NETWORKLINKS, - "links.open", - __tr2qs("Get Network Links"), - __tr2qs("Shows a window that allows viewing the network links"), - KviActionManager::categoryIrc(), - "kvi_bigicon_networklinks.png", - KVI_SMALLICON_LINKS, - KviAction::NeedsContext, - QString()); - - SCRIPT_ACTION( - KVI_COREACTION_CHANNELLIST, - "list.open", - __tr2qs("Get Channel List"), - __tr2qs("Shows a window that allows listing the network channels"), - KviActionManager::categoryIrc(), - "kvi_bigicon_channellist.png", - KVI_SMALLICON_LIST, - KviAction::NeedsContext, - QString()); - - SCRIPT_ACTION( - KVI_COREACTION_GENERALOPTIONS, - "options.dialog -t", - __tr2qs("Configure KVIrc..."), - __tr2qs("Shows the general options dialog"), - KviActionManager::categorySettings(), - "kvi_bigicon_settings.png", - KVI_SMALLICON_OPTIONS, - 0, - KVI_SHORTCUTS_OPTIONS); - - SCRIPT_ACTION( - KVI_COREACTION_THEMEOPTIONS, - "options.dialog -t theme", - __tr2qs("Configure Theme..."), - __tr2qs("Shows the theme options dialog"), - KviActionManager::categorySettings(), - "kvi_bigicon_themeoptions.png", - KVI_SMALLICON_THEMEOPTIONS, - 0, - KVI_SHORTCUTS_THEME); - - SCRIPT_ACTION( - KVI_COREACTION_MANAGETHEMES, - "theme.dialog -t", - __tr2qs("Manage Themes..."), - __tr2qs("Allows you to manage the themes"), - KviActionManager::categorySettings(), - "kvi_bigicon_theme.png", - KVI_SMALLICON_THEME, - 0, - KVI_SHORTCUTS_MANAGE_THEMES); - - SCRIPT_ACTION( - KVI_COREACTION_TOOLBAREDITOR, - "toolbareditor.open -t", - __tr2qs("Customize Toolbars..."), - __tr2qs("Shows a window that allows editing script toolbars"), - KviActionManager::categorySettings(), - "kvi_bigicon_toolbareditor.png", - KVI_SMALLICON_TOOLBAR, - 0, - KVI_SHORTCUTS_EDITORS_TOOLBAR); - - SCRIPT_ACTION( - KVI_COREACTION_JOINCHANNELS, - "channelsjoin.open", - __tr2qs("Join Channels..."), - __tr2qs("Shows a dialog that allows you join channels"), - KviActionManager::categoryIrc(), - "kvi_bigicon_channels.png", - KVI_SMALLICON_CHANNEL, - KviKvsAction::NeedsConnection | KviKvsAction::NeedsContext, - KVI_SHORTCUTS_JOIN); - - SCRIPT_ACTION( - KVI_COREACTION_ACTIONEDITOR, - "actioneditor.open", - __tr2qs("Edit Actions..."), - __tr2qs("Shows a window that allows editing actions"), - KviActionManager::categoryScripting(), - "kvi_bigicon_actioneditor.png", - KVI_SMALLICON_SCRIPTACTION, - 0, - KVI_SHORTCUTS_EDITORS_ACTION); - - SCRIPT_ACTION( - KVI_COREACTION_ALIASEDITOR, - "aliaseditor.open", - __tr2qs("Edit Aliases..."), - __tr2qs("Shows a window that allows editing aliases"), - KviActionManager::categoryScripting(), - "kvi_bigicon_aliaseditor.png", - KVI_SMALLICON_ALIAS, - 0, - KVI_SHORTCUTS_EDITORS_ALIAS); - - SCRIPT_ACTION( - KVI_COREACTION_CLASSEDITOR, - "classeditor.open", - __tr2qs("Edit Classes..."), - __tr2qs("Shows a window that allows editing classes"), - KviActionManager::categoryScripting(), - "kvi_bigicon_classeditor.png", - KVI_SMALLICON_CLASSEDITOR, - 0, - KVI_SHORTCUTS_EDITORS_CLASS); - - SCRIPT_ACTION( - KVI_COREACTION_EVENTEDITOR, - "eventeditor.open", - __tr2qs("Edit Events..."), - __tr2qs("Shows a window that allows editing script events"), - KviActionManager::categoryScripting(), - "kvi_bigicon_eventeditor.png", - KVI_SMALLICON_EVENT, - 0, - KVI_SHORTCUTS_EDITORS_EVENT); - - SCRIPT_ACTION( - KVI_COREACTION_POPUPEDITOR, - "popupeditor.open", - __tr2qs("Edit Popups..."), - __tr2qs("Shows a window that allows editing popup menus"), - KviActionManager::categoryScripting(), - "kvi_bigicon_popupeditor.png", - KVI_SMALLICON_POPUP, - 0, - KVI_SHORTCUTS_EDITORS_POPUP); - - SCRIPT_ACTION( - KVI_COREACTION_RAWEDITOR, - "raweditor.open", - __tr2qs("Edit Raw Events..."), - __tr2qs("Shows a window that allows editing raw scripting events"), - KviActionManager::categoryScripting(), - "kvi_bigicon_raweditor.png", - KVI_SMALLICON_RAWEVENT, - 0, - KVI_SHORTCUTS_EDITORS_RAW); - - SCRIPT_ACTION( - KVI_COREACTION_CODETESTER, - "codetester.open", - __tr2qs("Script Tester"), - __tr2qs("Creates an embedded editor for long scripts"), - KviActionManager::categoryScripting(), - "kvi_bigicon_codetester.png", - KVI_SMALLICON_BOMB, - 0, - KVI_SHORTCUTS_EDITORS_TESTER); - - SCRIPT_ACTION( - KVI_COREACTION_EXECUTEKVS, - "dialog.file(open,$tr(\"Select a Script File\")){ if(!$str.isEmpty($0))parse $0; }", - __tr2qs("Execute Script..."), - __tr2qs("Allows executing a KVS script from file"), - KviActionManager::categoryScripting(), - "kvi_bigicon_folder.png", - KVI_SMALLICON_FOLDER, - 0, - KVI_SHORTCUTS_EXEC); - - SCRIPT_ACTION( - KVI_COREACTION_HELPINDEX, - "help -m", - __tr2qs("Help Index"), - __tr2qs("Shows the documentation index"), - KviActionManager::categoryGeneric(), - "kvi_bigicon_help.png", - KVI_SMALLICON_HELP, - 0, - KVI_SHORTCUTS_HELP); - - SCRIPT_ACTION( - KVI_COREACTION_KVIRCMAILINGLIST, - "openurl http://www.kvirc.net/?id=mailinglist", - __tr2qs("Subscribe to the Mailing List"), - __tr2qs("Allows subscribing to the KVIrc mailing list"), - KviActionManager::categoryGeneric(), - "kvi_bigicon_mailinglist.png", - KVI_SMALLICON_MESSAGE, - 0, - QString()); - - SCRIPT_ACTION( - KVI_COREACTION_KVIRCHOMEPAGE, - "openurl http://www.kvirc.net", - __tr2qs("KVIrc WWW"), - __tr2qs("Opens the KVIrc homepage"), - KviActionManager::categoryGeneric(), - "kvi_bigicon_kvircwww.png", - KVI_SMALLICON_KVIRC, - 0, - QString()); - - SCRIPT_ACTION( - KVI_COREACTION_KVIRCRUHOMEPAGE, - "openurl http://www.kvirc.ru", - __tr2qs("KVIrc Russian WWW"), - __tr2qs("Opens the KVIrc homepage in russian"), - KviActionManager::categoryGeneric(), - "kvi_bigicon_kvircwww.png", - KVI_SMALLICON_KVIRC, - 0, - QString()); - - SCRIPT_ACTION( - KVI_COREACTION_SCREENSHOT, - "theme.screenshot", - __tr2qs("Acquire Screenshot"), - __tr2qs("Acquires a Screenshot of the KVIrc main window"), - KviActionManager::categoryGeneric(), - "kvi_bigicon_screenshot.png", - KVI_SMALLICON_SCREENSHOT, - 0, - QString()); - - - SLOT_ACTION( - KVI_COREACTION_CASCADEWINDOWS, - g_pFrame->mdiManager(), - SLOT(cascadeMaximized()), - __tr2qs("Cascade windows"), - __tr2qs("Arranges the MDI windows in a maximized-cascade fashion"), - KviActionManager::categoryGUI(), - "kvi_bigicon_cascadewindows.png", - KVI_SMALLICON_CASCADEWINDOWS, - 0, - QString()); - - SLOT_ACTION( - KVI_COREACTION_TILEWINDOWS, - g_pFrame->mdiManager(), - SLOT(tile()), - __tr2qs("Tile windows"), - __tr2qs("Tiles the MDI windows with the currently selected tile method"), - KviActionManager::categoryGUI(), - "kvi_bigicon_tilewindows.png", - KVI_SMALLICON_TILEWINDOWS, - 0, - QString()); - - SLOT_ACTION( - KVI_COREACTION_MINIMIZEALLWINDOWS, - g_pFrame->mdiManager(), - SLOT(minimizeAll()), - __tr2qs("Minimize all windows"), - __tr2qs("Minimized all the currently visible MDI windows"), - KviActionManager::categoryGUI(), - "kvi_bigicon_minimizeallwindows.png", - KVI_SMALLICON_MINIMIZE, - 0, - QString()); - - SLOT_ACTION( - KVI_COREACTION_NEWIRCCONTEXT, - g_pFrame, - SLOT(newConsole()), - __tr2qs("New IRC Context"), - __tr2qs("Creates a new IRC context console"), - KviActionManager::categoryIrc(), - "kvi_bigicon_newirccontext.png", - KVI_SMALLICON_CONSOLE, - 0, - KVI_SHORTCUTS_CONTEXT); - - SLOT_ACTION( - KVI_COREACTION_QUITKVIRC, - g_pApp, - SLOT(quit()), - __tr2qs("Quit KVIrc"), - __tr2qs("Quits KVIrc closing all the current connections"), - KviActionManager::categoryGeneric(), - "kvi_bigicon_quit.png", - KVI_SMALLICON_QUITAPP, - 0, - QString()); -} - - -KviIrcContextDisplayAction::KviIrcContextDisplayAction(QObject * pParent) -: KviAction(pParent, - QString(KVI_COREACTION_IRCCONTEXTDISPLAY), - __tr2qs("IRC Context Display"), - __tr2qs("Shows a small display with IRC context information"), - KviActionManager::categoryIrc(), - "kvi_bigicon_irccontextdisplay.png", - KVI_SMALLICON_NONE, - NeedsContext | NeedsConnection) -{ -} - -void KviIrcContextDisplayAction::setup() -{ - KviAction::setup(); - connect(g_pFrame,SIGNAL(activeConnectionServerInfoChanged()),this,SLOT(activeContextStateChanged())); - connect(g_pFrame,SIGNAL(activeConnectionNickNameChanged()),this,SLOT(activeContextStateChanged())); - connect(g_pFrame,SIGNAL(activeConnectionUserModeChanged()),this,SLOT(activeContextStateChanged())); - connect(g_pFrame,SIGNAL(activeConnectionAwayStateChanged()),this,SLOT(activeContextStateChanged())); - connect(g_pFrame,SIGNAL(activeConnectionLagChanged()),this,SLOT(activeContextStateChanged())); -} - -bool KviIrcContextDisplayAction::addToPopupMenu(KviTalPopupMenu *) -{ - // QT4SUX: Widgets can be no longer added to popup menus.. what about labels ? - return true; -} - -QWidget * KviIrcContextDisplayAction::addToCustomToolBar(KviCustomToolBar *t) -{ - if(!setupDone()) setup(); - KviIrcContextDisplay * w = new KviIrcContextDisplay(t,"kvirc.irccontextdisplay"); - t->addWidget(w); - registerWidget(w); - return w; -} - -void KviIrcContextDisplayAction::activeContextChanged() -{ - if(m_pWidgetList) - { - for(QWidget * w = m_pWidgetList->first();w;w = m_pWidgetList->next()) - w->update(); - } -} - -void KviIrcContextDisplayAction::activeContextStateChanged() -{ - if(m_pWidgetList) - { - for(QWidget * w = m_pWidgetList->first();w;w = m_pWidgetList->next()) - w->update(); - } -} - -void KviIrcContextDisplayAction::setEnabled(bool) -{ - // does nothing here : always enabled! -} - - - - -KviSeparatorAction::KviSeparatorAction(QObject * pParent) -: KviAction(pParent, - QString(KVI_COREACTION_SEPARATOR), - __tr2qs("Separator"), - __tr2qs("Acts as a separator for other items: performs no action"), - KviActionManager::categoryGeneric(), - KVI_BIGICON_SEPARATOR, - KVI_SMALLICON_NONE, - 0) -{ -} - - -bool KviSeparatorAction::addToPopupMenu(KviTalPopupMenu * p) -{ - if(!setupDone()) setup(); - p->insertSeparator(); - return true; -} - -QWidget * KviSeparatorAction::addToCustomToolBar(KviCustomToolBar * t) -{ - if(!setupDone()) setup(); - QWidget * w = new KviCustomToolBarSeparator(t,"kvirc.separator"); - registerWidget(w); - t->addWidget(w); - return w; -} - - -KviConnectAction::KviConnectAction(QObject * pParent) -: KviAction(pParent, - QString(KVI_COREACTION_CONNECT), - __tr2qs("Connect/Disconnect"), - __tr2qs("Allows you to connect to a server or to terminate the current connection"), - KviActionManager::categoryIrc(), - KVI_BIGICON_CONNECTED, - KVI_SMALLICON_NONE, // no small icon for now - NeedsContext | NeedsConnection, - QString(KVI_SHORTCUTS_CONNECT)) -{ -} - - -void KviConnectAction::reloadImages() -{ - activeContextStateChanged(); -} - -void KviConnectAction::activeContextChanged() -{ - activeContextStateChanged(); -} - -void KviConnectAction::activeContextStateChanged() -{ - - KviPointerList * bl = widgetList(); - if(!bl)return; - - QPixmap * p; - QString txt; - KviIrcContext * c = g_pFrame->activeContext(); - if(c) - { - switch(c->state()) - { - case KviIrcContext::Idle: - p = g_pIconManager->getBigIcon(KVI_BIGICON_DISCONNECTED); - txt = m_szConnectString; - break; - case KviIrcContext::Connecting: - case KviIrcContext::LoggingIn: - p = g_pIconManager->getBigIcon(KVI_BIGICON_CONNECTING); - txt = m_szAbortConnectionString; - break; - case KviIrcContext::Connected: - p = g_pIconManager->getBigIcon(KVI_BIGICON_CONNECTED); - txt = m_szDisconnectString; - break; - default: - p = 0; - break; - } - } else { - p = 0; - } - - if(p) - { - for(QToolButton * b = (QToolButton *)bl->first();b;b =(QToolButton *)bl->next()) - { - if(!b->isEnabled())b->setEnabled(true); - b->setIcon(QIcon(*p)); - b->setText(txt); - } - } else { - for(QToolButton * b = (QToolButton *)bl->first();b;b = (QToolButton *)bl->next()) - { - if(b->isEnabled())b->setEnabled(false); - } - } -} - -void KviConnectAction::setup() -{ - KviAction::setup(); - m_szConnectString = __tr2qs("Connect"); - m_szAbortConnectionString = __tr2qs("Abort Connection"); - m_szDisconnectString = __tr2qs("Disconnect"); -} - -void KviConnectAction::activate() -{ - KviIrcContext * c = g_pFrame->activeContext(); - if(c)c->connectOrDisconnect(); -} - -bool KviConnectAction::addToPopupMenu(KviTalPopupMenu *p) -{ - if(!setupDone())setup(); - KviIrcContext * c = g_pFrame->activeContext(); - int id; - - - QString t; - if(c) - { - switch(c->state()) - { - case KviIrcContext::Idle: - t = m_szConnectString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - p->insertItem(t,this,SLOT(activate())); - break; - case KviIrcContext::Connecting: - case KviIrcContext::LoggingIn: - t = m_szAbortConnectionString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - p->insertItem(t,this,SLOT(activate())); - break; - case KviIrcContext::Connected: - t = m_szDisconnectString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - p->insertItem(t,this,SLOT(activate())); - break; - default: - t = m_szConnectString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - id = p->insertItem(t,this,SLOT(activate())); - p->setItemEnabled(id,false); - break; - } - } else { - t = m_szConnectString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - id = p->insertItem(t,this,SLOT(activate())); - p->setItemEnabled(id,false); - } - return true; -} - -QWidget * KviConnectAction::addToCustomToolBar(KviCustomToolBar *t) -{ - if(!setupDone())setup(); - QToolButton * b = new QToolButton(t); - b->setIcon(*(g_pIconManager->getBigIcon(KVI_BIGICON_DISCONNECTED))); - b->setText(m_szConnectString); - b->setStatusTip(m_szConnectString); - b->setObjectName(name()); - connect(b, SIGNAL(clicked()), this, SLOT(activate())); - registerWidget(b); - t->addWidget(b); - activeContextStateChanged(); - return b; -} - - -KviSubmenuAction::KviSubmenuAction( - QObject * pParent, - const QString &szName, - const QString &szScriptCode, - const QString &szVisibleName, - const QString &szDescription, - KviActionCategory * pCategory, - const QString &szBigIconId, - const QString &szSmallIconId, - unsigned int uFlags - ) -: KviKvsAction( - pParent, - szName, - szScriptCode, - szVisibleName, - szDescription, - pCategory, - szBigIconId, - szSmallIconId, - uFlags - ) -{ - m_pPopup = 0; -} - -KviSubmenuAction::~KviSubmenuAction() -{ - if(m_pPopup)delete m_pPopup; -} - -void KviSubmenuAction::setup() -{ - KviKvsAction::setup(); - if(!m_pPopup) - { - m_pPopup = new KviTalPopupMenu(); - connect(m_pPopup,SIGNAL(aboutToShow()),this,SLOT(popupAboutToShow())); - connect(m_pPopup,SIGNAL(activated(int)),this,SLOT(popupActivated(int))); - } -} - -void KviSubmenuAction::popupAboutToShow() -{ -} - -void KviSubmenuAction::popupActivated(int) -{ -} - -bool KviSubmenuAction::addToPopupMenu(KviTalPopupMenu *p) -{ - if(!setupDone()) setup(); - int id = p->insertItem(*(smallIcon()),visibleName(),m_pPopup); - if(!isEnabled()) p->setItemEnabled(id,false); - return true; -} - -QWidget * KviSubmenuAction::addToCustomToolBar(KviCustomToolBar *t) -{ - if(!setupDone()) setup(); - QToolButton * b = new QToolButton(t); - QPixmap * p = bigIcon(); - b->setIcon(p ? *p : QPixmap()); - b->setText(visibleName()); - b->setStatusTip(visibleName()); - b->setObjectName(name()); - connect(b, SIGNAL(clicked()), this, SLOT(activate())); - - b->setMenu(m_pPopup); - - b->setPopupMode( scriptCode().isEmpty() ? QToolButton::InstantPopup : QToolButton::MenuButtonPopup); - t->addWidget(b); - registerWidget(b); - if(!isEnabled()) b->setEnabled(false); - return b; -} - - -KviJoinChannelAction::KviJoinChannelAction(QObject * pParent) -: KviSubmenuAction(pParent, - QString(KVI_COREACTION_CHANNELMENU), - QString("channelsjoin.open"), - __tr2qs("Join Channel"), - __tr2qs("Shows a popup menu that allows quickly selecting a channel to join"), - KviActionManager::categoryIrc(), - "kvi_bigicon_channelspopup.png", - QString("%1").arg(KVI_SMALLICON_CHANNEL), - NeedsConnection | NeedsContext) -{ -} - -void KviJoinChannelAction::popupAboutToShow() -{ - KviConsole * c = g_pActiveWindow->console(); - if(!c) return; - - g_pApp->fillRecentChannelsPopup(m_pPopup,c); - - m_pPopup->insertSeparator(); - m_pPopup->insertItem(*(smallIcon()),__tr2qs("Other...")); - m_pPopup->insertSeparator(); - m_pPopup->insertItem(__tr2qs("Clear Recent Channels List")); -} - -void KviJoinChannelAction::popupActivated(int id) -{ - KviConsole * c = g_pActiveWindow->console(); - if(!c)return; - - QString szItemText = m_pPopup->text(id); - if(!szItemText.isEmpty()) - { - QString szText; - if(szItemText == __tr2qs("Other...")) - { - szText = "channelsjoin.open"; - } else if(szItemText == __tr2qs("Clear Recent Channels List")) - { - szText = "option stringlistRecentChannels"; - } else { - szText = szItemText; - szText.prepend("join "); - } - KviKvsScript::run(szText,c); - } -} - - - -KviChangeNickAction::KviChangeNickAction(QObject * pParent) -: KviSubmenuAction( - pParent, - QString(KVI_COREACTION_NICKNAMEMENU), - QString("dialog.textinput(\"" + __tr2qs("Change Nickname") + "\",\"" + - __tr2qs("Please enter the new nickname") + "\",\"" + - __tr2qs("OK") + "\",\"" + - __tr2qs("Cancel") + "\"){ if($0 == 0 && $1 != \"\")nick $1; }"), - __tr2qs("Change Nickname"), - __tr2qs("Shows a popup menu that allows quickly changing the nickname"), - KviActionManager::categoryIrc(), - "kvi_bigicon_nickpopup.png", - QString("%1").arg(KVI_SMALLICON_NICK), - NeedsConnection | NeedsContext) -{ -} - -void KviChangeNickAction::popupAboutToShow() -{ - KviConsole * c = g_pActiveWindow->console(); - if(!c)return; - - g_pApp->fillRecentNicknamesPopup(m_pPopup,c); - - m_pPopup->insertSeparator(); - m_pPopup->insertItem(*(smallIcon()),__tr2qs("Other...")); - - m_pPopup->insertSeparator(); - m_pPopup->insertItem(*(smallIcon()),__tr2qs("Clear Recent Nicks List")); -} - -void KviChangeNickAction::popupActivated(int id) -{ - KviConsole * c = g_pActiveWindow->console(); - if(!c)return; - - QString text = m_pPopup->text(id); - if(!text.isEmpty()) - { - QString szText; - if(__tr2qs("Other...") == text) - { - activate(); - } else if(__tr2qs("Clear Recent Nicks List") == text) - { - KviKvsScript::run("option stringlistRecentNicknames",c); - } else { - szText = text; - szText.prepend("nick "); - KviKvsScript::run(szText,c); - } - } -} - - -KviConnectToServerAction::KviConnectToServerAction(QObject * pParent) -: KviSubmenuAction( - pParent, - QString(KVI_COREACTION_SERVERMENU), - QString("options.edit KviIrcServerOptionsWidget"), - __tr2qs("Connect To"), - __tr2qs("Shows a popup menu that allows quickly connecting to a server"), - KviActionManager::categoryIrc(), - "kvi_bigicon_server.png", - QString("%1").arg(KVI_SMALLICON_SERVER), - NeedsContext) -{ -} - -void KviConnectToServerAction::popupAboutToShow() -{ - g_pApp->fillRecentServersPopup(m_pPopup); - m_pPopup->insertSeparator(); - m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SERVER)),__tr2qs("Other...")); - m_pPopup->insertSeparator(); - m_pPopup->insertItem(__tr2qs("Clear Recent Servers List")); -} - -void KviConnectToServerAction::popupActivated(int id) -{ - KviConsole * c = g_pActiveWindow->console(); - if(!c)return; - - QString szItemText = m_pPopup->text(id); - if(!szItemText.isEmpty()) - { - if(szItemText == __tr2qs("Other...")) - { - activate(); - } else if(szItemText == __tr2qs("Clear Recent Servers List")) - { - KviKvsScript::run("option stringlistRecentServers",c); - } else { - KviCString szCommand; - QString szText = szItemText; - if(KviIrcUrl::parse(szText.toUtf8().data(),szCommand,KVI_IRCURL_CONTEXT_FIRSTFREE)) - { - KviKvsScript::run(szCommand.ptr(),c); - } - } - } -} - - -KviChangeUserModeAction::KviChangeUserModeAction(QObject * pParent) -: KviSubmenuAction( - pParent, - QString(KVI_COREACTION_USERMODEMENU), - QString(""), - __tr2qs("User Mode"), - __tr2qs("Shows a popup menu that allows quickly changing user modes"), - KviActionManager::categoryIrc(), - "kvi_bigicon_usermode.png", - QString("%1").arg(KVI_SMALLICON_MODE), - NeedsContext | NeedsConnection) -{ -} - -void KviChangeUserModeAction::popupAboutToShow() -{ - KviConsole * c = g_pActiveWindow->console(); - if(!c)return; - - m_pPopup->clear(); - int id; - QString szModes = g_pActiveWindow->connection()->serverInfo()->supportedUserModes(); - - id = m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_WALLOPS)),__tr2qs("Wallops (+w)")); - m_pPopup->setItemChecked(id,c->connection()->userInfo()->hasUserMode('w')); - id = m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_SERVERNOTICE)),__tr2qs("Server Notices (+s)")); - m_pPopup->setItemChecked(id,c->connection()->userInfo()->hasUserMode('s')); - id = m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_INVISIBLE)),__tr2qs("Invisible (+i)")); - m_pPopup->setItemChecked(id,c->connection()->userInfo()->hasUserMode('i')); - - szModes.replace("w",""); - szModes.replace("s",""); - szModes.replace("i",""); - while(!szModes.isEmpty()) - { - QChar ccc = szModes[0]; - szModes.remove(0,1); - id = m_pPopup->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_MODE)),QString("+%1 Mode").arg(ccc)); - m_pPopup->setItemChecked(id,c->connection()->userInfo()->hasUserMode(ccc.toLatin1())); - } -} - -void KviChangeUserModeAction::popupActivated(int id) -{ - KviConsole * c = g_pActiveWindow->console(); - if(!c)return; - - QString text = m_pPopup->text(id); - if(!c->isConnected())return; - if(!text.isEmpty()) - { - int idx = text.indexOf('+'); - if(idx != -1) - { - idx++; - if(idx < text.length()) - { - QChar m = text[idx]; - QString szNick = c->connection()->userInfo()->nickName(); - KviQString::escapeKvs(&szNick); - QString command = "mode "; - command.append(szNick); - command.append(c->connection()->userInfo()->hasUserMode(m) ? " -" : " +"); - command.append(m); - KviKvsScript::run(command,c); - } - } - } -} - - -KviGoAwayAction::KviGoAwayAction(QObject * pParent) -: KviKvsAction( - pParent, - QString(KVI_COREACTION_AWAYBACK), - QString("if($away())back; else away;"), - __tr2qs("Away/Back"), - __tr2qs("Allows entering and leaving away state"), - KviActionManager::categoryIrc(), - "kvi_bigicon_nokeyboard.png", - QString("%1").arg(KVI_SMALLICON_NOTAWAY), - KviKvsAction::NeedsContext | KviKvsAction::NeedsConnection, - KVI_SHORTCUTS_AWAY - ) -{ -} - -void KviGoAwayAction::reloadImages() -{ - activeContextStateChanged(); -} - -void KviGoAwayAction::activeContextChanged() -{ - activeContextStateChanged(); -} - -void KviGoAwayAction::activeContextStateChanged() -{ - KviPointerList * bl = widgetList(); - if(!bl)return; - - QPixmap * p; - QString txt; - KviIrcContext * c = g_pFrame->activeContext(); - if(c) - { - if(c->state() == KviIrcContext::Connected) - { - if(c->connection()->userInfo()->isAway()) - { - p = g_pIconManager->getBigIcon("kvi_bigicon_keyboard.png"); - txt = m_szBackString; - } else { - p = g_pIconManager->getBigIcon("kvi_bigicon_nokeyboard.png"); - txt = m_szAwayString; - } - } else { - p = 0; - } - } else { - p = 0; - } - - if(p) - { - for(QToolButton * b = (QToolButton *)bl->first();b;b =(QToolButton *)bl->next()) - { - if(!b->isEnabled())b->setEnabled(true); - b->setIcon(QIcon(*p)); - b->setText(txt); - } - m_uInternalFlags |= KviAction::Enabled; - setEnabled(true); - } else { - for(QToolButton * b = (QToolButton *)bl->first();b;b = (QToolButton *)bl->next()) - { - if(b->isEnabled())b->setEnabled(false); - } - m_uInternalFlags &= ~KviAction::Enabled; - setEnabled(true); - } -} - -void KviGoAwayAction::setup() -{ - KviKvsAction::setup(); - m_szAwayString = __tr2qs("Enter Away Mode"); - m_szBackString = __tr2qs("Leave Away Mode"); - connect(g_pFrame,SIGNAL(activeConnectionAwayStateChanged()),this,SLOT(activeContextStateChanged())); -} - -bool KviGoAwayAction::addToPopupMenu(KviTalPopupMenu *p) -{ - if(!setupDone())setup(); - KviIrcContext * c = g_pFrame->activeContext(); - int id; - QString t; - if(c) - { - if(c->state() == KviIrcContext::Connected) - { - if(c->connection()->userInfo()->isAway()) - { - t = m_szBackString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - p->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_AWAY)),t,this,SLOT(activate())); - } else { - t = m_szAwayString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - p->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NOTAWAY)),t,this,SLOT(activate())); - } - } else { - t = m_szAwayString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - id = p->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NOTAWAY)),t,this,SLOT(activate())); - p->setItemEnabled(id,false); - } - } else { - t = m_szAwayString; - if(!m_szKeySequence.isEmpty())t += '\t' + m_szKeySequence; - id = p->insertItem(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_NOTAWAY)),t,this,SLOT(activate())); - p->setItemEnabled(id,false); - } - return true; -} - -QWidget * KviGoAwayAction::addToCustomToolBar(KviCustomToolBar *t) -{ - if(!setupDone())setup(); - - QToolButton * b = new QToolButton(t); - b->setIcon(*(g_pIconManager->getBigIcon("kvi_bigicon_nokeyboard.png"))); - b->setText(m_szAwayString); - b->setStatusTip(m_szAwayString); - b->setObjectName(name()); - connect(b, SIGNAL(clicked()), this, SLOT(activate())); - - registerWidget(b); - t->addWidget(b); - activeContextStateChanged(); - return b; -} - - -KviIrcToolsAction::KviIrcToolsAction(QObject * pParent) -: KviSubmenuAction( - pParent, - QString(KVI_COREACTION_IRCTOOLS), - QString(""), - __tr2qs("Irc Tools"), - __tr2qs("Shows a popup menu with some IRC Tools"), - KviActionManager::categoryIrc(), - "kvi_bigicon_tools.png", - QString("%1").arg(KVI_SMALLICON_NONE), - NeedsConnection | NeedsContext) -{ -} - -void KviIrcToolsAction::popupAboutToShow() -{ - m_pPopup->clear(); - KviAction * a; - a = KviActionManager::instance()->getAction(KVI_COREACTION_SOCKETSPY); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_SEPARATOR); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_CHANNELLIST); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_NETWORKLINKS); - if(a)a->addToPopupMenu(m_pPopup); -} - -void KviIrcToolsAction::popupActivated(int) -{ -} - - -KviIrcOperationsAction::KviIrcOperationsAction(QObject * pParent) -: KviSubmenuAction( - pParent, - QString(KVI_COREACTION_IRCACTIONS), - QString(""), - __tr2qs("Irc Actions"), - __tr2qs("Shows a popup menu with some IRC Actions"), - KviActionManager::categoryIrc(), - "kvi_bigicon_actions.png", - QString("%1").arg(KVI_SMALLICON_NONE), - NeedsConnection | NeedsContext) -{ -} - -void KviIrcOperationsAction::popupAboutToShow() -{ - m_pPopup->clear(); - KviAction * a; - a = KviActionManager::instance()->getAction(KVI_COREACTION_AWAYBACK); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_USERMODEMENU); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_SEPARATOR); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_CHANNELMENU); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_NICKNAMEMENU); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_SEPARATOR); - if(a)a->addToPopupMenu(m_pPopup); - a = KviActionManager::instance()->getAction(KVI_COREACTION_SERVERMENU); - if(a)a->addToPopupMenu(m_pPopup); -} - -void KviIrcOperationsAction::popupActivated(int) -{ -} diff --git a/src/kvirc/kernel/kvi_coreactions.h b/src/kvirc/kernel/kvi_coreactions.h deleted file mode 100644 index 9fc78b40d..000000000 --- a/src/kvirc/kernel/kvi_coreactions.h +++ /dev/null @@ -1,188 +0,0 @@ -#ifndef _KVI_COREACTIONS_H_ -#define _KVI_COREACTIONS_H_ -//============================================================================= -// -// File : kvi_coreactions.h -// Creation date : Mon 22 Nov 2004 02:30:47 by Szymon Stefanek -// -// This file is part of the KVIrc IRC Client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "kvi_action.h" -#include "kvi_kvs_action.h" -#include "KviPointerList.h" - -class KviConnectAction : public KviAction -{ - Q_OBJECT -public: - KviConnectAction(QObject * pParent); -protected: - QString m_szConnectString; - QString m_szAbortConnectionString; - QString m_szDisconnectString; -public: - virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); - virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); -protected: - virtual void setup(); - virtual void reloadImages(); - virtual void activate(); - virtual void activeContextChanged(); - virtual void activeContextStateChanged(); -}; - -class KviSeparatorAction : public KviAction -{ - Q_OBJECT -public: - KviSeparatorAction(QObject * pParent); -public: - virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); - virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); -}; - -class KviTalPopupMenu; - -class KviSubmenuAction : public KviKvsAction -{ - Q_OBJECT -public: - KviSubmenuAction( - QObject * pParent, - const QString & szName, - const QString & szScriptCode, - const QString & szVisibleName, - const QString & szDescription, - KviActionCategory * pCategory = NULL, - const QString & szBigIconId = QString(), - const QString & szSmallIcoNId = QString(), - unsigned int uFlags = 0 - ); - ~KviSubmenuAction(); -protected: - KviTalPopupMenu * m_pPopup; -protected: - virtual void setup(); -public: - virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); - virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); -protected slots: - virtual void popupAboutToShow(); - virtual void popupActivated(int iId); -}; - -class KviJoinChannelAction : public KviSubmenuAction -{ - Q_OBJECT -public: - KviJoinChannelAction(QObject * pParent); -protected slots: - virtual void popupAboutToShow(); - virtual void popupActivated(int); -}; - -class KviChangeNickAction : public KviSubmenuAction -{ - Q_OBJECT -public: - KviChangeNickAction(QObject * pParent); -protected slots: - void popupAboutToShow(); - void popupActivated(int); -}; - -class KviConnectToServerAction : public KviSubmenuAction -{ - Q_OBJECT -public: - KviConnectToServerAction(QObject * pParent); -protected slots: - void popupAboutToShow(); - void popupActivated(int); -}; - -class KviChangeUserModeAction : public KviSubmenuAction -{ - Q_OBJECT -public: - KviChangeUserModeAction(QObject * pParent); -protected slots: - void popupAboutToShow(); - void popupActivated(int); -}; - -class KviIrcToolsAction : public KviSubmenuAction -{ - Q_OBJECT -public: - KviIrcToolsAction(QObject * pParent); -protected slots: - void popupAboutToShow(); - void popupActivated(int); -}; - - -class KviIrcOperationsAction : public KviSubmenuAction -{ - Q_OBJECT -public: - KviIrcOperationsAction(QObject * pParent); -protected slots: - void popupAboutToShow(); - void popupActivated(int); -}; - -#include "kvi_irctoolbar.h" - -class KviIrcContextDisplayAction : public KviAction -{ - Q_OBJECT -public: - KviIrcContextDisplayAction(QObject * pParent); -public: - virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); - virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); - virtual void activeContextStateChanged(); - virtual void activeContextChanged(); - virtual void setEnabled(bool); - virtual void setup(); -}; - - -class KviGoAwayAction : public KviKvsAction -{ - Q_OBJECT -public: - KviGoAwayAction(QObject * pParent); -protected: - QString m_szAwayString; - QString m_szBackString; -public: - virtual bool addToPopupMenu(KviTalPopupMenu * pMenu); - virtual QWidget * addToCustomToolBar(KviCustomToolBar * pTool); -protected: - virtual void setup(); - virtual void reloadImages(); - virtual void activeContextChanged(); - virtual void activeContextStateChanged(); -}; - -#endif //_KVI_COREACTIONS_H_ diff --git a/src/kvirc/kernel/kvi_customtoolbardescriptor.cpp b/src/kvirc/kernel/kvi_customtoolbardescriptor.cpp deleted file mode 100644 index 0d6245d1b..000000000 --- a/src/kvirc/kernel/kvi_customtoolbardescriptor.cpp +++ /dev/null @@ -1,220 +0,0 @@ -//============================================================================= -// -// File : kvi_customtoolbardescriptor.cpp -// Creation date : Sun 05 Dec 2004 18:20:58 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_customtoolbardescriptor.h" -#include "kvi_customtoolbar.h" -#include "KviConfigurationFile.h" -#include "kvi_action.h" -#include "kvi_actionmanager.h" -#include "kvi_app.h" -#include "KviLocale.h" -#include "kvi_kvs_script.h" -#include "kvi_window.h" - -KviCustomToolBarDescriptor::KviCustomToolBarDescriptor(const QString &szId,const QString &szLabelCode) -{ - m_iInternalId = g_pApp->getGloballyUniqueId(); - m_szId = szId; - m_pActions = new KviPointerList; - m_pActions->setAutoDelete(true); - m_pToolBar = 0; - m_bVisibleAtStartup = false; - createLabelScript(szLabelCode); -} - -KviCustomToolBarDescriptor::~KviCustomToolBarDescriptor() -{ - if(m_pToolBar)delete m_pToolBar; // first kill the toolbar (so eventually leave it sync the actions) - delete m_pActions; // THEN kill the actions - delete m_pLabelScript; -} - -void KviCustomToolBarDescriptor::createLabelScript(const QString &szLabelCode) -{ - QString szTmp = "toolbar::"; - szTmp += m_szId; - szTmp += "::label"; - m_pLabelScript = new KviKvsScript(szTmp,szLabelCode,KviKvsScript::Parameter); -} - -const QString & KviCustomToolBarDescriptor::label() -{ - if(!m_pLabelScript->run(g_pActiveWindow,0,m_szParsedLabel))m_szParsedLabel = m_pLabelScript->code(); - return m_szParsedLabel; -} - -const QString & KviCustomToolBarDescriptor::labelCode() -{ - return m_pLabelScript->code(); -} - -bool KviCustomToolBarDescriptor::addAction(const QString &szAction) -{ - KviAction *a = KviActionManager::instance()->getAction(szAction); - if(a) - { - m_pActions->append(new QString(szAction)); - if(m_pToolBar)a->addToCustomToolBar(m_pToolBar); - return true; - } - return false; -} - -bool KviCustomToolBarDescriptor::removeAction(unsigned int iAction) -{ - if(iAction >= m_pActions->count())return false; - if(!m_pActions->remove(iAction))return false; - if(m_pToolBar) - { - // need to refill it :/ - m_pToolBar->clear(); - fillToolBar(); - } - return true; -} - -bool KviCustomToolBarDescriptor::removeAction(const QString &szAction) -{ - for(QString *s = m_pActions->first();s;s = m_pActions->next()) - { - if(*s == szAction) - { - m_pActions->removeRef(s); - if(m_pToolBar) - { - // need to refill it :/ - m_pToolBar->clear(); - fillToolBar(); - } - return true; - } - } - return false; -} - -void KviCustomToolBarDescriptor::updateToolBar() -{ - if(!m_pToolBar)return; - m_pToolBar->clear(); - fillToolBar(); -} - - -void KviCustomToolBarDescriptor::fillToolBar() -{ - if(m_pActions->count() == 0) - { - // force layout of the toolbar - QApplication::postEvent(m_pToolBar,new QEvent(QEvent::LayoutRequest)); - } else { - KviPointerList dying; - dying.setAutoDelete(false); - for(QString *p = m_pActions->first();p;p = m_pActions->next()) - { - KviAction *a = KviActionManager::instance()->getAction(*p); - if(a)a->addToCustomToolBar(m_pToolBar); - else dying.append(p); - } - for(QString *d = dying.first();d;d = dying.next()) - m_pActions->removeRef(d); - } -} - -KviCustomToolBar * KviCustomToolBarDescriptor::createToolBar() -{ - if(!m_pToolBar) - { - QByteArray dd = id().toUtf8(); - m_pToolBar = new KviCustomToolBar(this,label(),Qt::TopToolBarArea,false,dd.data()); - fillToolBar(); - } - return m_pToolBar; -} - -void KviCustomToolBarDescriptor::registerToolBar(KviCustomToolBar * t) -{ - m_pToolBar = t; -} - -void KviCustomToolBarDescriptor::unregisterToolBar(KviCustomToolBar *) -{ - m_pToolBar = 0; -} - -void KviCustomToolBarDescriptor::rename(const QString &szNewLabelCode) -{ - delete m_pLabelScript; - createLabelScript(szNewLabelCode); - if(m_pToolBar)m_pToolBar->setWindowTitle(label()); -} - -void KviCustomToolBarDescriptor::clear() -{ - m_pActions->clear(); - if(m_pToolBar) - { - delete m_pToolBar; - m_pToolBar = 0; - } -} - -bool KviCustomToolBarDescriptor::load(KviConfigurationFile * cfg) -{ - m_pActions->clear(); - m_szId = cfg->group(); - QString szLabelCode = cfg->readEntry("Label"); - if(szLabelCode.isEmpty())szLabelCode = "$tr(Unnamed)"; - delete m_pLabelScript; - createLabelScript(szLabelCode); - m_szIconId = cfg->readEntry("IconId",""); - unsigned int n = cfg->readUIntEntry("Count",0); - QString tmp; - for(unsigned int i=0;ireadEntry(tmp)); - if(p->isEmpty())delete p; - else m_pActions->append(p); - } - return true; -} - -void KviCustomToolBarDescriptor::save(KviConfigurationFile * cfg) -{ - cfg->setGroup(m_szId); - cfg->writeEntry("Label",m_pLabelScript->code()); - cfg->writeEntry("Count",m_pActions->count()); - if(!m_szIconId.isEmpty())cfg->writeEntry("IconId",m_szIconId); - int i = 0; - QString tmp; - for(QString * p = m_pActions->first();p;p = m_pActions->next()) - { - tmp.setNum(i); - cfg->writeEntry(tmp,*p); - i++; - } -} - diff --git a/src/kvirc/kernel/kvi_customtoolbardescriptor.h b/src/kvirc/kernel/kvi_customtoolbardescriptor.h deleted file mode 100644 index a10545402..000000000 --- a/src/kvirc/kernel/kvi_customtoolbardescriptor.h +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef _KVI_CUSTOMTOOLBARDESCRIPTOR_H_ -#define _KVI_CUSTOMTOOLBARDESCRIPTOR_H_ -//============================================================================= -// -// File : kvi_customtoolbardescriptor.h -// Creation date : Sun 05 Dec 2004 18:20:58 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviPointerList.h" - -class KviCustomToolBar; -class KviConfigurationFile; -class KviKvsScript; - - -class KVIRC_API KviCustomToolBarDescriptor -{ - friend class KviCustomToolBar; - friend class KviCustomToolBarManager; -protected: - KviCustomToolBarDescriptor(const QString & szId, const QString & szLabelCode); -public: - ~KviCustomToolBarDescriptor(); -protected: - QString m_szId; - QString m_szIconId; - QString m_szParsedLabel; - KviPointerList * m_pActions; - KviCustomToolBar * m_pToolBar; - int m_iInternalId; - bool m_bVisibleAtStartup; - KviKvsScript * m_pLabelScript; -public: - const QString & iconId(){ return m_szIconId; }; - const QString & label(); - const QString & labelCode(); - const QString & id(){ return m_szId; }; - int internalId(){ return m_iInternalId; }; // useful only for KviFrame - KviCustomToolBar * toolBar(){ return m_pToolBar; }; - KviCustomToolBar * createToolBar(); - void setIconId(const QString &szIconId){ m_szIconId = szIconId; }; - bool addAction(const QString &szAction); - bool removeAction(const QString &szAction); - bool removeAction(unsigned int iAction); - void clear(); - void rename(const QString &szNewName); - KviPointerList * actions(){ return m_pActions; }; - void updateToolBar(); -protected: - void createLabelScript(const QString &szNewLabelCode); - void fillToolBar(); - bool load(KviConfigurationFile * cfg); - void save(KviConfigurationFile * cfg); - void registerToolBar(KviCustomToolBar * t); - void unregisterToolBar(KviCustomToolBar * t); -}; - -#endif //_KVI_CUSTOMTOOLBARDESCRIPTOR_H_ diff --git a/src/kvirc/kernel/kvi_customtoolbarmanager.cpp b/src/kvirc/kernel/kvi_customtoolbarmanager.cpp deleted file mode 100644 index e827ec9d8..000000000 --- a/src/kvirc/kernel/kvi_customtoolbarmanager.cpp +++ /dev/null @@ -1,212 +0,0 @@ -//============================================================================= -// -// File : kvi_customtoolbarmanager.cpp -// Creation date : Sun 05 Dec 2004 18:20:18 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_customtoolbarmanager.h" -#include "kvi_customtoolbardescriptor.h" -#include "KviConfigurationFile.h" -#include "KviLocale.h" - -KviCustomToolBarManager * KviCustomToolBarManager::m_pInstance = 0; - -KviCustomToolBarManager::KviCustomToolBarManager() -{ - m_pDescriptors = new KviPointerHashTable(17,false); - m_pDescriptors->setAutoDelete(true); -} - -KviCustomToolBarManager::~KviCustomToolBarManager() -{ - delete m_pDescriptors; -} - -KviCustomToolBar * KviCustomToolBarManager::firstExistingToolBar() -{ - KviPointerHashTableIterator it(*m_pDescriptors); - while(KviCustomToolBarDescriptor * d = it.current()) - { - if(d->toolBar())return d->toolBar(); - ++it; - } - return 0; -} - -void KviCustomToolBarManager::init() -{ - if(!m_pInstance)m_pInstance = new KviCustomToolBarManager(); -} - -void KviCustomToolBarManager::done() -{ - if(m_pInstance) - { - delete m_pInstance; - m_pInstance = 0; - } -} - -QString KviCustomToolBarManager::idForNewToolBar(const QString &szTemplate) -{ - QString s; - QString szTT = szTemplate.toLower(); - szTT.remove(" "); - szTT.remove("$tr"); - szTT.remove("("); - szTT.remove(")"); - szTT.remove("\""); - int idx = 0; - for(;;) - { - s = szTT; - if(idx > 0) - { - QString tmp; - tmp.setNum(idx); - s += tmp; - } - if(!m_pDescriptors->find(s))return s; - idx++; - } - return s; -} - -KviCustomToolBarDescriptor * KviCustomToolBarManager::findDescriptorByInternalId(int id) -{ - KviPointerHashTableIterator it(*m_pDescriptors); - while(KviCustomToolBarDescriptor * d = it.current()) - { - if(d->internalId() == id)return d; - ++it; - } - return 0; -} - -bool KviCustomToolBarManager::renameDescriptor(const QString &szId,const QString &szNewId,const QString &szNewLabelCode) -{ - KviCustomToolBarDescriptor * d = m_pDescriptors->find(szId); - if(!d)return false; - d->rename(szNewLabelCode); - if(szId == szNewId)return true; // already done - m_pDescriptors->setAutoDelete(false); - m_pDescriptors->remove(szId); - m_pDescriptors->replace(szNewId,d); - m_pDescriptors->setAutoDelete(true); - return true; -} - -bool KviCustomToolBarManager::destroyDescriptor(const QString &szId) -{ - KviCustomToolBarDescriptor * d = m_pDescriptors->find(szId); - if(!d)return false; - m_pDescriptors->remove(szId); // will delete it too! - return true; -} - -void KviCustomToolBarManager::clear() -{ - m_pDescriptors->clear(); // bye! -} - -KviCustomToolBarDescriptor * KviCustomToolBarManager::create(const QString &szId,const QString &szLabelCode) -{ - KviCustomToolBarDescriptor * d = m_pDescriptors->find(szId); - if(d)return d; - d = new KviCustomToolBarDescriptor(szId,szLabelCode); - m_pDescriptors->replace(szId,d); - return d; -} - -void KviCustomToolBarManager::storeVisibilityState() -{ - KviPointerHashTableIterator it(*m_pDescriptors); - while(KviCustomToolBarDescriptor * d = it.current()) - { - d->m_bVisibleAtStartup = d->toolBar() != 0; - ++it; - } - -} - -int KviCustomToolBarManager::visibleToolBarCount() -{ - int cnt = 0; - KviPointerHashTableIterator it(*m_pDescriptors); - while(KviCustomToolBarDescriptor * d = it.current()) - { - if(d->toolBar() != 0)cnt++; - ++it; - } - return cnt; -} - -void KviCustomToolBarManager::createToolBarsVisibleAtStartup() -{ - KviPointerHashTableIterator it(*m_pDescriptors); - while(KviCustomToolBarDescriptor * d = it.current()) - { - if(d->m_bVisibleAtStartup && (!d->toolBar())) - d->createToolBar(); - ++it; - } -} - -void KviCustomToolBarManager::updateVisibleToolBars() -{ - KviPointerHashTableIterator it(*m_pDescriptors); - while(KviCustomToolBarDescriptor * d = it.current()) - { - if(d->toolBar())d->updateToolBar(); - ++it; - } -} - -void KviCustomToolBarManager::load(const QString &szFileName) -{ - KviConfigurationFile cfg(szFileName,KviConfigurationFile::Read); - - KviConfigurationFileIterator it(*(cfg.dict())); - while(it.current()) - { - cfg.setGroup(it.currentKey()); - KviCustomToolBarDescriptor * d = new KviCustomToolBarDescriptor(it.currentKey(),QString()); - d->m_bVisibleAtStartup = (cfg.readIntEntry("Visible",0) > 0); - if(!d->load(&cfg))delete d; - else m_pDescriptors->replace(it.currentKey(),d); - ++it; - } -} - -void KviCustomToolBarManager::save(const QString &szFileName) -{ - KviConfigurationFile cfg(szFileName,KviConfigurationFile::Write); - KviPointerHashTableIterator it(*m_pDescriptors); - while(KviCustomToolBarDescriptor * d = it.current()) - { - cfg.setGroup(d->id()); - cfg.writeEntry("Visible",d->m_bVisibleAtStartup ? 1 : 0); - d->save(&cfg); - ++it; - } -} diff --git a/src/kvirc/kernel/kvi_customtoolbarmanager.h b/src/kvirc/kernel/kvi_customtoolbarmanager.h deleted file mode 100644 index bc3c76c46..000000000 --- a/src/kvirc/kernel/kvi_customtoolbarmanager.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef _KVI_CUSTOMTOOLBARMANAGER_H_ -#define _KVI_CUSTOMTOOLBARMANAGER_H_ -//============================================================================= -// -// File : kvi_customtoolbarmanager.h -// Creation date : Sun 05 Dec 2004 18:20:18 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviPointerHashTable.h" - -#ifdef COMPILE_ON_WINDOWS - #include "kvi_customtoolbardescriptor.h" -#else - class KviCustomToolBarDescriptor; -#endif - -class KviCustomToolBar; - -class KVIRC_API KviCustomToolBarManager -{ -protected: - KviCustomToolBarManager(); - ~KviCustomToolBarManager(); -protected: - static KviCustomToolBarManager * m_pInstance; - KviPointerHashTable * m_pDescriptors; -public: - static KviCustomToolBarManager * instance(){ return m_pInstance; }; - static void init(); - static void done(); - void clear(); - int descriptorCount(){ return m_pDescriptors->count(); }; - int visibleToolBarCount(); - QString idForNewToolBar(const QString &szTemplate); - KviPointerHashTable * descriptors(){ return m_pDescriptors; }; - KviCustomToolBar * firstExistingToolBar(); - KviCustomToolBarDescriptor * create(const QString &szId,const QString &szLabelCode); - KviCustomToolBarDescriptor * find(const QString &szId){ return m_pDescriptors->find(szId); }; - KviCustomToolBarDescriptor * findDescriptorByInternalId(int id); - void updateVisibleToolBars(); - void createToolBarsVisibleAtStartup(); - void storeVisibilityState(); - bool renameDescriptor(const QString &szId,const QString &szNewId,const QString &szNewLabelCode); - bool destroyDescriptor(const QString &szId); - void load(const QString &szFileName); - void save(const QString &szFileName); -}; - -#endif //_KVI_CUSTOMTOOLBARMANAGER_H_ diff --git a/src/kvirc/kernel/kvi_defaultscript.cpp b/src/kvirc/kernel/kvi_defaultscript.cpp deleted file mode 100644 index 38cd1bd1b..000000000 --- a/src/kvirc/kernel/kvi_defaultscript.cpp +++ /dev/null @@ -1,489 +0,0 @@ -//============================================================================= -// -// File : kvi_defaultscript.cpp -// Creation date : Fri Oct 01 2010 19:14:48 by Elvio Basello -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2010 Elvio Basello (hell at hellvis69 dot netsons dot org) -// -// 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 opinion) 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 "kvi_defaultscript.h" - -#include "kvi_app.h" -#include "kvi_kvs.h" -#include "KviConfigurationFile.h" -#include "KviLocale.h" -#include "KviMiscUtils.h" -#include "kvi_actionmanager.h" -#include "kvi_iconmanager.h" -#include "kvi_customtoolbarmanager.h" - -#include -#include -#include -#include -#include -#include - -KviDefaultScriptManager * KviDefaultScriptManager::m_pSelf = NULL; -unsigned int KviDefaultScriptManager::m_uCount = 0; - -KviDefaultScriptManager::KviDefaultScriptManager() -: QObject() -{ - m_bNoNeedToRestore = false; - - // Check if versions' file exists in personal settings - QString szLocal; - g_pApp->getLocalKvircDirectory(szLocal,KviApp::Config,"default.kvc"); - - if(!QFile::exists(szLocal)) - { - QString szGlobal; - g_pApp->getGlobalKvircDirectory(szGlobal,KviApp::DefScript,"default.kvc"); - QFile::copy(szGlobal,szLocal); - } -} - -KviDefaultScriptManager::~KviDefaultScriptManager() -{ -} - -void KviDefaultScriptManager::init() -{ - if((!m_pSelf) && (m_pSelf->count() == 0)) - { - m_pSelf = new KviDefaultScriptManager(); - m_uCount++; - } -} - -void KviDefaultScriptManager::done() -{ - m_uCount--; - if(m_pSelf->count() == 0) - delete m_pSelf; -} - -bool KviDefaultScriptManager::isDefscriptUpToDate() -{ - QString szConfig, szTmp; - g_pApp->getGlobalKvircDirectory(szConfig,KviApp::DefScript,"default.kvc"); - KviConfigurationFile * pCfg = new KviConfigurationFile(szConfig,KviConfigurationFile::Read); - - szTmp = pCfg->readEntry("Date"); - QDate cfgDate = QDate::fromString(szTmp,"yyyy-MM-dd"); - QDate userDate = QDate::fromString(m_szDate,"yyyy-MM-dd"); - - return (cfgDate == userDate); -} - -void KviDefaultScriptManager::restore() -{ - QString szGlobal, szError, szLocal; - g_pApp->getGlobalKvircDirectory(szGlobal,KviApp::DefScript,"default.kvc"); - - m_pDialog = new KviDefaultScriptDialog(); - if(m_pDialog->exec() == QDialog::Rejected) - { - delete m_pDialog; - return; - } - - // Check data - if(!compareVersions(szGlobal,&szError)) - { - QMessageBox::warning(0,__tr2qs("Restore Default Script - Error"),szError,QMessageBox::Ok,QMessageBox::NoButton,QMessageBox::NoButton); - return; - } - - if(m_bNoNeedToRestore) - { - if(QMessageBox::warning(0,__tr2qs("Restore Default Script - Warning"),szError,QMessageBox::Yes, QMessageBox::No,QMessageBox::Cancel) != QMessageBox::Yes) - return; - } - - restoreInternal(); -} - -void KviDefaultScriptManager::restoreInternal() -{ - QString szConfig, szTmp; - g_pApp->getGlobalKvircDirectory(szConfig,KviApp::DefScript,"default.kvc"); - KviConfigurationFile * pCfg = new KviConfigurationFile(szConfig,KviConfigurationFile::Read); - - m_szDate = pCfg->readEntry("Date"); - - // Select elements to restore - if((m_pDialog->m_pAction->isEnabled() && m_pDialog->m_pAction->isChecked()) || m_pDialog->m_pAll->isChecked()) - { - if(m_pDialog->m_pData->isChecked()) - KviActionManager::instance()->killAllKvsUserActions(); - // No need to load here since we haven't a default actions script yet - //g_pApp->loadDefaultScript("action"); - m_szAction = pCfg->readEntry("ActionVersion"); - } - - if((m_pDialog->m_pAddon->isEnabled() && m_pDialog->m_pAddon->isChecked()) || m_pDialog->m_pAll->isChecked()) - { - if(m_pDialog->m_pData->isChecked()) - KviKvs::clearScriptAddons(); - // No need to load here since we haven't a default actions script yet - //g_pApp->loadDefaultScript("addons"); - m_szAddon = pCfg->readEntry("AddonVersion"); - } - - if((m_pDialog->m_pAlias->isEnabled() && m_pDialog->m_pAlias->isChecked()) || m_pDialog->m_pAll->isChecked()) - { - if(m_pDialog->m_pData->isChecked()) - KviKvs::clearAliases(); - g_pApp->loadDefaultScript("aliases"); - m_szAlias = pCfg->readEntry("AliasVersion"); - } - - if((m_pDialog->m_pClass->isEnabled() && m_pDialog->m_pClass->isChecked()) || m_pDialog->m_pAll->isChecked()) - { - // TODO: clear classes - g_pApp->loadDefaultScript("classes"); - m_szClass = pCfg->readEntry("ClassVersion"); - } - - if((m_pDialog->m_pEvent->isEnabled() && m_pDialog->m_pEvent->isChecked()) || m_pDialog->m_pAll->isChecked()) - { - if(m_pDialog->m_pData->isChecked()) - KviKvs::clearAppEvents(); - g_pApp->loadDefaultScript("events"); - m_szEvent = pCfg->readEntry("EventVersion"); - } - - if((m_pDialog->m_pPopup->isEnabled() && m_pDialog->m_pPopup->isChecked()) || m_pDialog->m_pAll->isChecked()) - { - if(m_pDialog->m_pData->isChecked()) - KviKvs::clearPopups(); - g_pApp->loadDefaultScript("popups"); - m_szPopup = pCfg->readEntry("PopupVersion"); - } - - if((m_pDialog->m_pRaw->isEnabled() && m_pDialog->m_pRaw->isChecked()) || m_pDialog->m_pAll->isChecked()) - { - if(m_pDialog->m_pData->isChecked()) - KviKvs::clearRawEvents(); - // No need to load here since we haven't a default raw events script yet - //g_pApp->loadDefaultScript("raws"); - m_szRaw = pCfg->readEntry("RawVersion"); - } - - if((m_pDialog->m_pToolbar->isEnabled() && m_pDialog->m_pToolbar->isChecked()) || m_pDialog->m_pAll->isChecked()) - { - if(m_pDialog->m_pData->isChecked()) - KviCustomToolBarManager::instance()->clear(); - g_pApp->loadDefaultScript("toolbars"); - m_szToolbar = pCfg->readEntry("ToolbarVersion"); - } -} - -#define CHECK(__name,__global,__local) \ - if(KviMiscUtils::compareVersions(__global,__local) == 1) \ - { \ - *pszError = __tr2qs("There's something wrong in your personal data: my '%1' is %2, while yours is %3").arg(__name,__global,__local); \ - return false; \ - } - -bool KviDefaultScriptManager::compareVersions(QString & szConfig, QString * pszError) -{ - QString szTmp, szTmp2; - - if(pszError) - *pszError = ""; - - KviConfigurationFile * pCfg = new KviConfigurationFile(szConfig,KviConfigurationFile::Read); - - szTmp = "Date"; - szTmp2 = pCfg->readEntry(szTmp); - QDate cfgDate = QDate::fromString(szTmp2,"yyyy-MM-dd"); - QDate userDate = QDate::fromString(m_szDate,"yyyy-MM-dd"); - - if(cfgDate <= userDate) - { - m_bNoNeedToRestore = true; - *pszError = __tr2qs("Your default script is up to date.\nDo you want to restore it anyway?"); - return true; - } - - szTmp = "Version"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szVersion) - - szTmp = "ActionVersion"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szAction) - - szTmp = "AddonVersion"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szAction) - - szTmp = "AliasVersion"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szAlias) - - szTmp = "ClassVersion"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szClass) - - szTmp = "EventVersion"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szEvent) - - szTmp = "PopupVersion"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szPopup) - - szTmp = "RawVersion"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szRaw) - - szTmp = "ToolbarVersion"; - szTmp2 = pCfg->readEntry(szTmp); - CHECK(szTmp,szTmp2,m_szToolbar) - - return true; -} - -void KviDefaultScriptManager::load(const QString & szConfigFile) -{ - KviConfigurationFile cfg(szConfigFile,KviConfigurationFile::Read); - loadInternal(&cfg); -} - -#define IS_EMPTY(__var,__default) \ - if(__var.isEmpty()) \ - __var = __default; - -void KviDefaultScriptManager::loadInternal(KviConfigurationFile * pCfg) -{ - QString szTmp; - QString szDate = QDate::currentDate().toString("yyyy-MM-dd"); - - szTmp = "Version"; - m_szVersion = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szVersion,KVI_VERSION) - - szTmp = "Date"; - m_szDate = pCfg->readEntry(szTmp,szDate); - IS_EMPTY(m_szDate,szDate) - - szTmp = "ActionVersion"; - m_szAction = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szAction,KVI_VERSION) - - szTmp = "AddonVersion"; - m_szAddon = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szAddon,KVI_VERSION) - - szTmp = "AliasVersion"; - m_szAlias = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szAlias,KVI_VERSION) - - szTmp = "ClassVersion"; - m_szClass = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szClass,KVI_VERSION) - - szTmp = "EventVersion"; - m_szEvent = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szEvent,KVI_VERSION) - - szTmp = "PopupVersion"; - m_szPopup = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szPopup,KVI_VERSION) - - szTmp = "RawVersion"; - m_szRaw = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szRaw,KVI_VERSION) - - szTmp = "ToolbarVersion"; - m_szToolbar = pCfg->readEntry(szTmp,KVI_VERSION); - IS_EMPTY(m_szToolbar,KVI_VERSION) -} - -void KviDefaultScriptManager::save(const QString & szConfigFile) -{ - KviConfigurationFile cfg(szConfigFile,KviConfigurationFile::Write); - cfg.clear(); - saveInternal(&cfg); -} - -void KviDefaultScriptManager::saveInternal(KviConfigurationFile * pCfg) -{ - QString szTmp; - - szTmp = "Version"; - pCfg->writeEntry(szTmp,m_szVersion); - - szTmp = "Date"; - pCfg->writeEntry(szTmp,m_szDate); - - szTmp = "ActionVersion"; - pCfg->writeEntry(szTmp,m_szAction); - - szTmp = "AddonVersion"; - pCfg->writeEntry(szTmp,m_szAddon); - - szTmp = "AliasVersion"; - pCfg->writeEntry(szTmp,m_szAlias); - - szTmp = "ClassVersion"; - pCfg->writeEntry(szTmp,m_szClass); - - szTmp = "EventVersion"; - pCfg->writeEntry(szTmp,m_szEvent); - - szTmp = "PopupVersion"; - pCfg->writeEntry(szTmp,m_szPopup); - - szTmp = "RawVersion"; - pCfg->writeEntry(szTmp,m_szRaw); - - szTmp = "ToolbarVersion"; - pCfg->writeEntry(szTmp,m_szToolbar); -} - - -KviDefaultScriptDialog::KviDefaultScriptDialog() -: QDialog() -{ - setObjectName("restore_default_script"); - setWindowTitle(__tr2qs("Restore Default Script - KVIrc")); - setWindowModality(Qt::WindowModal); - setModal(true); - - QGridLayout * pLayout = new QGridLayout(this); - - QLabel * pLabel = new QLabel(this); - pLabel->setText(__tr2qs("You are about to restore the default script.\nAny script changes you have made will be erased if you\nrestore all stuff or \"Clear personal data\" is selected.\n\nDo you wish to proceed?\n")); - pLayout->addWidget(pLabel,0,0,1,4); - - // Construct the advanced widget - m_pAdvanced = new QGroupBox(__tr2qs("Select default script's elements to restore"),this); - m_pAdvanced->hide(); - - QGridLayout * pAdvLayout = new QGridLayout(m_pAdvanced); - pAdvLayout->setContentsMargins(0,10,0,0); - pLayout->addWidget(m_pAdvanced,1,0,1,4); - - m_pAll = new QCheckBox(__tr2qs("All"),m_pAdvanced); - m_pAll->setChecked(true); - pAdvLayout->addWidget(m_pAll,0,0); - connect(m_pAll,SIGNAL(clicked(bool)),this,SLOT(toggleAll(bool))); - - m_pData = new QCheckBox(__tr2qs("Clear custom scripts"),m_pAdvanced); - m_pData->setChecked(false); - m_pData->setEnabled(true); - pAdvLayout->addWidget(m_pData,0,1); - - pLabel = new QLabel(m_pAdvanced); - pAdvLayout->addWidget(pLabel,1,1,1,2); - - m_pAction = new QCheckBox(__tr2qs("Actions"),m_pAdvanced); - m_pAction->setChecked(true); - m_pAction->setEnabled(false); - pAdvLayout->addWidget(m_pAction,2,0); - - m_pAddon = new QCheckBox(__tr2qs("Addons"),m_pAdvanced); - m_pAddon->setChecked(true); - m_pAddon->setEnabled(false); - pAdvLayout->addWidget(m_pAddon,2,1); - - m_pAlias = new QCheckBox(__tr2qs("Aliases"),m_pAdvanced); - m_pAlias->setChecked(true); - m_pAlias->setEnabled(false); - pAdvLayout->addWidget(m_pAlias,3,0); - - m_pClass = new QCheckBox(__tr2qs("Classes"),m_pAdvanced); - m_pClass->setChecked(true); - m_pClass->setEnabled(false); - pAdvLayout->addWidget(m_pClass,3,1); - - m_pEvent = new QCheckBox(__tr2qs("Events"),m_pAdvanced); - m_pEvent->setChecked(true); - m_pEvent->setEnabled(false); - pAdvLayout->addWidget(m_pEvent,4,0); - - m_pPopup = new QCheckBox(__tr2qs("Popups"),m_pAdvanced); - m_pPopup->setChecked(true); - m_pPopup->setEnabled(false); - pAdvLayout->addWidget(m_pPopup,4,1); - - m_pRaw = new QCheckBox(__tr2qs("Raw Events"),m_pAdvanced); - m_pRaw->setChecked(true); - m_pRaw->setEnabled(false); - pAdvLayout->addWidget(m_pRaw,5,0); - - m_pToolbar = new QCheckBox(__tr2qs("Toolbars"),m_pAdvanced); - m_pToolbar->setChecked(true); - m_pToolbar->setEnabled(false); - pAdvLayout->addWidget(m_pToolbar,5,1); - - m_pAdvanced->setLayout(pAdvLayout); - - QPixmap * pImage = g_pIconManager->getSmallIcon(262); - QPushButton * pAdvanced = new QPushButton(*pImage,__tr2qs("Advanced..."),this); - connect(pAdvanced,SIGNAL(clicked()),this,SLOT(advanced())); - pLayout->addWidget(pAdvanced,2,0,1,1); - - pImage = g_pIconManager->getSmallIcon(44); - QPushButton * pCancel = new QPushButton(*pImage,__tr2qs("Cancel"),this); - pCancel->setDefault(true); - connect(pCancel,SIGNAL(clicked()),this,SLOT(reject())); - pLayout->addWidget(pCancel,2,2,1,1); - - pImage = g_pIconManager->getSmallIcon(43); - QPushButton * pAccept = new QPushButton(*pImage,__tr2qs("Restore"),this); - connect(pAccept,SIGNAL(clicked()),this,SLOT(accept())); - pLayout->addWidget(pAccept,2,3,1,1); -} - -KviDefaultScriptDialog::~KviDefaultScriptDialog() -{ -} - -void KviDefaultScriptDialog::toggleAll(bool) -{ - m_pAction->setEnabled(!m_pAction->isEnabled()); - m_pAddon->setEnabled(!m_pAddon->isEnabled()); - m_pAlias->setEnabled(!m_pAlias->isEnabled()); - m_pClass->setEnabled(!m_pClass->isEnabled()); - m_pEvent->setEnabled(!m_pEvent->isEnabled()); - m_pPopup->setEnabled(!m_pPopup->isEnabled()); - m_pRaw->setEnabled(!m_pRaw->isEnabled()); - m_pToolbar->setEnabled(!m_pToolbar->isEnabled()); -} - -void KviDefaultScriptDialog::advanced() -{ - m_pAdvanced->isVisible() ? m_pAdvanced->hide() : m_pAdvanced->show(); -} - -void KviDefaultScriptDialog::accept() -{ - QDialog::accept(); -} - -void KviDefaultScriptDialog::reject() -{ - QDialog::reject(); -} diff --git a/src/kvirc/kernel/kvi_defaultscript.h b/src/kvirc/kernel/kvi_defaultscript.h deleted file mode 100644 index c7c59aaee..000000000 --- a/src/kvirc/kernel/kvi_defaultscript.h +++ /dev/null @@ -1,239 +0,0 @@ -#ifndef _KVI_DEFAULTSCRIPT_H_ -#define _KVI_DEFAULTSCRIPT_H_ -//============================================================================= -// -// File : kvi_defaultscript.h -// Creation date : Fri Oct 01 2010 19:14:48 by Elvio Basello -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2010 Elvio Basello (hell at hellvis69 dot netsons dot org) -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_defaultscript.h -* \author Elvio Basello -* \brief Default script handling -*/ - -#include "kvi_settings.h" - -#include -#include - -class QGroupBox; -class QCheckBox; -class KviConfigurationFile; -class KviDefaultScriptDialog; - -/** -* \class KviDefaultScriptManager -* \brief The manager who handles the restoring of the default script -*/ -class KVIRC_API KviDefaultScriptManager : public QObject -{ - Q_OBJECT -public: - /** - * \brief Constructs the default script manager - * \return KviDefaultScriptManager - */ - KviDefaultScriptManager(); - - /** - * \brief Destroys the default script manager - */ - ~KviDefaultScriptManager(); -private: - static KviDefaultScriptManager * m_pSelf; - static unsigned int m_uCount; - bool m_bNoNeedToRestore; - KviDefaultScriptDialog * m_pDialog; - QString m_szVersion; - QString m_szDate; - QString m_szAction; - QString m_szAddon; - QString m_szAlias; - QString m_szClass; - QString m_szEvent; - QString m_szPopup; - QString m_szRaw; - QString m_szToolbar; -public: - /** - * \brief Initializes the class instance - * \return void - */ - static void init(); - - /** - * \brief Destroys the class instance - * \return void - */ - static void done(); - - /** - * \brief Returns the instance of the class - * \return KviDefaultScriptManager * - */ - static inline KviDefaultScriptManager * instance(){ return m_pSelf; } - - /** - * \brief Returns the number of instances of the class - * \return unsigned int - */ - unsigned int count(){ return m_uCount; }; - - /** - * \brief Checks if the local defscript is up to date - * \return bool - */ - bool isDefscriptUpToDate(); - - /** - * \brief Restores the default script - * - * If this function is suggested by KVIrc, the default script will be wiped out and then - * it will be reloaded. Otherwise, when the user wants to restore it, he can choose which - * part of the default script have to be restored - * - * This is an external helper to the real function - * \return void - */ - void restore(); - - /** - * \brief Loads the configuration of the default script - * - * This is an external helper to the real function - * \param szConfigFile The file where to load - * \return void - */ - void load(const QString & szConfigFile); - - /** - * \brief Saves the configuration of the default script - * - * This is an external helper to the real function - * \param szConfigFile The file to save - * \return void - */ - void save(const QString & szConfigFile); -private: - /** - * \brief Restores the default script - * - * This is the real function - * \return void - * \todo This function still misses class clearing due to a missing function in class editor - */ - void restoreInternal(); - - /** - * \brief Loads the configuration of the default script - * - * This is the real function - * \param pCfg The configuration file - * \return void - */ - void loadInternal(KviConfigurationFile * pCfg); - - /** - * \brief Saves the configuration of the default script - * - * This is the real function - * \param pCfg The configuration file - * \return void - */ - void saveInternal(KviConfigurationFile * pCfg); - - /** - * \brief Compares versions between global and personal data - * \param szConfig The global configuration file - * \param pszError The buffer containing errors - * \return bool - */ - bool compareVersions(QString & szConfig, QString * pszError); -}; - -/** -* \class KviDefaultScriptDialog -* \brief A dialog which allow the user to choose which elements to restore -*/ -class KVIRC_API KviDefaultScriptDialog : public QDialog -{ - Q_OBJECT - friend class KviDefaultScriptManager; -public: - /** - * \brief Constructs the default script dialog - * \return KviDefaultScriptDialog - */ - KviDefaultScriptDialog(); - - /** - * \brief Destroys the default script dialog - */ - ~KviDefaultScriptDialog(); -protected: - QGroupBox * m_pAdvanced; - QCheckBox * m_pAll; - QCheckBox * m_pData; - QCheckBox * m_pAction; - QCheckBox * m_pAddon; - QCheckBox * m_pAlias; - QCheckBox * m_pClass; - QCheckBox * m_pEvent; - QCheckBox * m_pPopup; - QCheckBox * m_pRaw; - QCheckBox * m_pToolbar; -protected slots: - /** - * \brief Enables or disables all checkboxes - * - * Called when the user (de)selects the 'All' one - * \return void - */ - void toggleAll(bool); - - /** - * \brief Open/close the advanced widget - * - * Called when the user clicks on 'Advanced...' - * \return void - */ - void advanced(); - - /** - * \brief Accepts the dialog - * - * Called when the user clicks on 'Ok' - * \return void - */ - virtual void accept(); - - /** - * \brief Rejects the dialog - * - * Called when the user clicks on 'Cancel' or closes the dialog using the window - * decoration or pressing ESC - * \return void - */ - virtual void reject(); -}; - -#endif // _KVI_DEFAULTSCRIPT_H_ \ No newline at end of file diff --git a/src/kvirc/kernel/kvi_filetransfer.cpp b/src/kvirc/kernel/kvi_filetransfer.cpp deleted file mode 100644 index b3860b658..000000000 --- a/src/kvirc/kernel/kvi_filetransfer.cpp +++ /dev/null @@ -1,202 +0,0 @@ -//============================================================================= -// -// File : kvi_filetransfer.cpp -// Creation date : Mon Apr 21 22:14:31 2003 GMT by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_filetransfer.h" -#include "kvi_moduleextension.h" -#include "kvi_window.h" - -#include "kvi_app.h" - -#include "KviTalPopupMenu.h" - -static KviFileTransferManager * g_pFileTransferManager = 0; - - -KviFileTransferManager::KviFileTransferManager() -: QObject() -{ - m_pTransferList = 0; - m_pTransferWindow = 0; -} - -KviFileTransferManager::~KviFileTransferManager() -{ - killAllTransfers(); -} - -KviFileTransferManager * KviFileTransferManager::instance() -{ - if(!g_pFileTransferManager) { - g_pFileTransferManager = new KviFileTransferManager(); - } - return g_pFileTransferManager; -} - -void KviFileTransferManager::cleanup() -{ - if(g_pFileTransferManager) { - delete g_pFileTransferManager; - g_pFileTransferManager = 0; - } -} - -void KviFileTransferManager::killAllTransfers() -{ - while(m_pTransferList) - { - KviFileTransfer * t = m_pTransferList->first(); - t->die(); - } -} - -void KviFileTransferManager::killTerminatedTransfers() -{ - if(m_pTransferList) - { - KviPointerList l; - l.setAutoDelete(false); - - for(KviFileTransfer * f = m_pTransferList->first();f;f = m_pTransferList->next()) - { - if(f->terminated()) { - l.append(f); - } - } - - for(KviFileTransfer * d = l.first();d;d = l.next()) - d->die(); - } -} - -void KviFileTransferManager::invokeTransferWindow(KviWindow * pWnd,bool bCreateMinimized,bool bNoRaise) -{ - if(!m_pTransferWindow) - { - KviPointerHashTable d(7,false); - d.setAutoDelete(true); - d.replace("bCreateMinimized",new QVariant(bCreateMinimized)); - d.replace("bNoRaise",new QVariant(bNoRaise)); - - KviModuleExtensionManager::instance()->allocateExtension( - "tool", - KVI_FILE_TRANSFER_WINDOW_EXTENSION_NAME, - pWnd,&d,0, - "filetransferwindow"); - } -} - -void KviFileTransferManager::registerTransfer(KviFileTransfer * t) -{ - if(!m_pTransferList) - { - m_pTransferList = new KviPointerList; - m_pTransferList->setAutoDelete(false); - } - - m_pTransferList->append(t); - - emit transferRegistered(t); -} - -void KviFileTransferManager::unregisterTransfer(KviFileTransfer * t) -{ - if(!m_pTransferList) - { - qDebug("Ops: unregistering transfer with no transfer list!"); - return; - } - - emit transferUnregistering(t); - - m_pTransferList->removeRef(t); - if(m_pTransferList->isEmpty()) - { - delete m_pTransferList; - m_pTransferList = 0; - } -} - - - -KviFileTransfer::KviFileTransfer() -: QObject() -{ - m_pDisplayItem = 0; - m_iId = g_pApp->getGloballyUniqueId(); - manager()->registerTransfer(this); -} - -KviFileTransfer::~KviFileTransfer() -{ - manager()->unregisterTransfer(this); -} - -KviWindow * KviFileTransfer::outputWindow() -{ - KviWindow * o = transferWindow(); - if(o)return o; - return g_pActiveWindow; -} - -void KviFileTransfer::invokeTransferWindow(KviWindow * pWnd,bool bCreateMinimized,bool bNoRaise) -{ - manager()->invokeTransferWindow(pWnd,bCreateMinimized,bNoRaise); -} - -QString KviFileTransfer::localFileName() -{ - return QString(); -} - -QString KviFileTransfer::retryCommand() -{ - return QString(); -} - -bool KviFileTransfer::terminated() -{ - return !active(); -} - -QString KviFileTransfer::tipText() -{ - return QString(); -} - -int KviFileTransfer::displayHeight(int iLineSpacing) -{ - return iLineSpacing * 2; -} - -void KviFileTransfer::displayUpdate() -{ - if(m_pDisplayItem)m_pDisplayItem->displayUpdate(); -} - -void KviFileTransfer::die() -{ - if(m_pDisplayItem) - m_pDisplayItem->tableWidget()->removeRow(m_pDisplayItem->row()); - delete this; -} diff --git a/src/kvirc/kernel/kvi_filetransfer.h b/src/kvirc/kernel/kvi_filetransfer.h deleted file mode 100644 index 45f64cddb..000000000 --- a/src/kvirc/kernel/kvi_filetransfer.h +++ /dev/null @@ -1,114 +0,0 @@ -#ifndef _KVI_FILETRANSFER_H_ -#define _KVI_FILETRANSFER_H_ - -//============================================================================= -// -// File : kvi_filetransfer.h -// Creation date : Mon Apr 21 22:14:31 2003 GMT by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviPointerList.h" -#include "KviTalTableWidget.h" - -#include - -class KviFileTransfer; -class KviWindow; -class KviTalPopupMenu; -class QPainter; - -// This is for the external extension -#define KVI_FILE_TRANSFER_WINDOW_EXTENSION_NAME "File transfer extension" - - -class KVIRC_API KviFileTransferManager : public QObject -{ - friend class KviApp; - friend class KviFileTransfer; - friend class KviFileTransferWindow; - Q_OBJECT -public: - KviFileTransferManager(); - ~KviFileTransferManager(); -protected: - KviPointerList * m_pTransferList; - KviWindow * m_pTransferWindow; -protected: - static void cleanup(); - void registerTransfer(KviFileTransfer * t); - void unregisterTransfer(KviFileTransfer * t); - void setTransferWindow(KviWindow * wnd){ m_pTransferWindow = wnd; }; -public: - // might be zero! - KviWindow * transferWindow(){ return m_pTransferWindow; }; - static KviFileTransferManager * instance(); - KviPointerList * transferList(){ return m_pTransferList; }; - void invokeTransferWindow(KviWindow * pWnd = 0,bool bCreateMinimized = false,bool bNoRaise = false); - void killAllTransfers(); - void killTerminatedTransfers(); -signals: - void transferRegistered(KviFileTransfer *t); - void transferUnregistering(KviFileTransfer *t); -}; - -#define COLUMN_TRANSFERTYPE 0 -#define COLUMN_FILEINFO 1 -#define COLUMN_PROGRESS 2 - -class KVIRC_API KviFileTransfer : public QObject -{ - Q_OBJECT -public: - KviFileTransfer(); - ~KviFileTransfer(); -protected: - int m_iId; - KviTalTableWidgetItemEx * m_pDisplayItem; -public: - // This is called by KviFileTransferItem at any time - void setDisplayItem(KviTalTableWidgetItemEx * i){ m_pDisplayItem = i; }; - int id(){ return m_iId; }; - // this is just a convenience function : it's equivalent to !active() - bool terminated(); - // This may be used to invoke the transfer window - void invokeTransferWindow(KviWindow * pWnd = 0,bool bCreateMinimized = false,bool bNoRaise = false); - KviFileTransferManager * manager(){ return KviFileTransferManager::instance(); }; - // this returns the pointer to the transfer window : may be 0! - KviWindow * transferWindow(){ return manager()->transferWindow(); }; - // this returns transferWindow() if not 0, otherwise the application's active window - KviWindow * outputWindow(); - - // this may be called by the transfers to update the display when the state changes - void displayUpdate(); - - // this must be implemented by the transfer - virtual bool active() = 0; - virtual void displayPaint(QPainter * p,int column, QRect rect) = 0; - virtual QString tipText(); - virtual QString localFileName(); - virtual QString retryCommand(); - virtual int displayHeight(int iLineSpacing); - virtual void fillContextPopup(KviTalPopupMenu * m) = 0; - virtual void die(); -}; - -#endif //! _KVI_FILETRANSFER_H_ diff --git a/src/kvirc/kernel/kvi_htmlgenerator.cpp b/src/kvirc/kernel/kvi_htmlgenerator.cpp deleted file mode 100644 index ee66f0a81..000000000 --- a/src/kvirc/kernel/kvi_htmlgenerator.cpp +++ /dev/null @@ -1,304 +0,0 @@ -//============================================================================= -// -// File : kvi_htmlgenerator.cpp -// Creation date : Mon 04 Jan 2010 22:09:18 by Fabio Bas -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2010 Fabio Bas < ctrlaltca at gmail dot 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 opinion) 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 "kvi_htmlgenerator.h" - -#include "kvi_iconmanager.h" -#include "KviMircCntrl.h" -#include "kvi_options.h" -#include "kvi_texticonmanager.h" - -#define KVI_LABEL_DEF_BACK 100 -#define KVI_LABEL_DEF_FORE 101 - -namespace KviHtmlGenerator -{ - - QString convertToHtml(const QString &szText) - { - QString szResult=""; - bool bCurBold = false; - bool bCurUnderline = false; - bool bIgnoreIcons = false; - bool bShowIcons = KVI_OPTION_BOOL(KviOption_boolDrawEmoticons); - - unsigned char uCurFore = KVI_LABEL_DEF_FORE; //default fore - unsigned char uCurBack = KVI_LABEL_DEF_BACK; //default back - - unsigned int uIdx = 0; - - while(uIdx < (unsigned int)szText.length()) - { - unsigned short c = szText[(int)uIdx].unicode(); - unsigned int uStart = uIdx; - - while( - (c != KVI_TEXT_COLOR) && - (c != KVI_TEXT_BOLD) && - (c != KVI_TEXT_UNDERLINE) && - (c != KVI_TEXT_REVERSE) && - (c != KVI_TEXT_RESET) && - (c != KVI_TEXT_ICON) && - ((c != ':') || bIgnoreIcons) && - ((c != ';') || bIgnoreIcons) && - ((c != '=') || bIgnoreIcons) - ) - { - bIgnoreIcons=FALSE; - if(c == '&') - { - //look for an html entity - QString szEntity = szText.mid((int)uIdx,6); - if(szEntity==""") - { - uIdx+=5; - } else { - szEntity.truncate(5); - if(szEntity=="&") - { - uIdx+=4; - } else { - szEntity.truncate(4); - if(szEntity=="<" || szEntity==">") uIdx+=3; - } - } - } - - uIdx++; - if(uIdx >= (unsigned int)szText.length()) break; - else c = szText[(int)uIdx].unicode(); - } - - bIgnoreIcons=FALSE; - int iLen = uIdx - uStart; - - if(iLen > 0) - { - bool bOpened = FALSE; - - if(uCurFore != KVI_LABEL_DEF_FORE) - { - szResult.append(""); - - szResult.append(szText.mid(uStart,iLen)); - - if( bOpened ) - szResult.append(""); - } - - switch(c) - { - case KVI_TEXT_BOLD: bCurBold = !bCurBold; ++uIdx; break; - case KVI_TEXT_UNDERLINE: bCurUnderline = !bCurUnderline; ++uIdx; break; - case KVI_TEXT_REVERSE: - { - char auxBack = uCurBack; - uCurBack = uCurFore; - uCurFore = auxBack; - } - ++uIdx; - break; - case KVI_TEXT_RESET: - uCurFore = KVI_LABEL_DEF_FORE; - uCurBack = KVI_LABEL_DEF_BACK; - bCurBold = false; - bCurUnderline = false; - ++uIdx; - break; - case KVI_TEXT_COLOR: - { - ++uIdx; - unsigned char fore; - unsigned char back; - uIdx = getUnicodeColorBytes(szText,uIdx,&fore,&back); - if(fore != KVI_NOCHANGE) - { - uCurFore = fore; - if(back != KVI_NOCHANGE)uCurBack = back; - } else { - // only a CTRL+K - uCurBack = KVI_LABEL_DEF_BACK; - uCurFore = KVI_LABEL_DEF_FORE; - } - } - break; - case ':': - case ';': - case '=': - { - //potential emoticon, got eyes - if(bShowIcons) - { - ++uIdx; - QString szLookup; - szLookup.append(QChar(c)); - unsigned short uIsEmoticon=0; - unsigned int uIcoStart = uIdx; - - if(uIdx < (unsigned int)szText.length()) - { - //look up for a nose - if(szText[(int)uIdx] == '-') - { - szLookup.append('-'); - uIdx++; - } - } - - if(uIdx < (unsigned int)szText.length()) - { - //look up for a mouth - unsigned short m = szText[(int)uIdx].unicode(); - switch(m) - { - case ')': - case '(': - case '/': - case 'D': - case 'P': - case 'S': - case 'O': - case '*': - case '|': - szLookup+=QChar(m); - uIsEmoticon++; - uIdx++; - break; - default: - break; - } - } - - if(uIdx < (unsigned int)szText.length()) - { - //look up for a space - if(szText[(int)uIdx]== ' ') - { - uIsEmoticon++; - } - } else { - //got a smile at the end of the szText - uIsEmoticon++; - } - - if(uIsEmoticon>1) - { - KviTextIcon * pIcon = g_pTextIconManager->lookupTextIcon(szLookup); - // do we have that emoticon-icon association ? - if(pIcon) - { - szResult.append("getSmallIconResourceName(pIcon->id())); - if(uCurBack != KVI_LABEL_DEF_BACK) - { - szResult.append("\" style=\"background-color:"); - szResult.append(KVI_OPTION_MIRCCOLOR(uCurBack).name()); - } - szResult.append("\">"); - } else { - bIgnoreIcons=TRUE; - uIdx = uIcoStart-1; - } - } else { - bIgnoreIcons=TRUE; - uIdx = uIcoStart-1; - } - } else { - bIgnoreIcons=TRUE; - } - } - break; - case KVI_TEXT_ICON: - { - ++uIdx; - if(bShowIcons) - { - unsigned int uIcoStart = uIdx; - while((uIdx < (unsigned int)szText.length()) && (szText[(int)uIdx].unicode() > 32))uIdx++; - - QString szLookup = szText.mid(uIcoStart,uIdx - uIcoStart); - - KviTextIcon * pIcon = g_pTextIconManager->lookupTextIcon(szLookup); - if(pIcon) - { - szResult.append("getSmallIconResourceName(pIcon->id())); - if(uCurBack != KVI_LABEL_DEF_BACK) - { - szResult.append("\" style=\"background-color:"); - szResult.append(KVI_OPTION_MIRCCOLOR(uCurBack).name()); - } - szResult.append("\">"); - } else { - uIdx = uIcoStart; - } - } - } - break; - } - } - szResult.append(""); - //qDebug("%s",szResult.toUtf8().data()); - return szResult; - } -} diff --git a/src/kvirc/kernel/kvi_htmlgenerator.h b/src/kvirc/kernel/kvi_htmlgenerator.h deleted file mode 100644 index 0d4d47cfe..000000000 --- a/src/kvirc/kernel/kvi_htmlgenerator.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef _KVI_HTMLGENERATOR_H_ -#define _KVI_HTMLGENERATOR_H_ -//============================================================================= -// -// File : kvi_htmlgenerator.h -// Creation date : Mon 04 Jan 2010 22:09:18 by Fabio Bas -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2010 Fabio Bas < ctrlaltca at gmail dot 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_htmlgenerator.h -* \author Fabio Bas -* \brief Irc => Html format converter; this should better live in kdelibs, but uses kvirc options -*/ - -#include "kvi_settings.h" - -/** -* \namespace KviHtmlGenerator -* \brief A namespace to handle html-related functions -*/ -namespace KviHtmlGenerator -{ - /** - * \brief Converts a raw irc message to its html equivalent text - * \param szText const reference to a message text - * \return QString - */ - extern KVIRC_API QString convertToHtml(const QString &szText); -}; - -#endif //_KVI_HTMLGENERATOR_H_ \ No newline at end of file diff --git a/src/kvirc/kernel/kvi_iconmanager.cpp b/src/kvirc/kernel/kvi_iconmanager.cpp deleted file mode 100644 index 85202719e..000000000 --- a/src/kvirc/kernel/kvi_iconmanager.cpp +++ /dev/null @@ -1,956 +0,0 @@ -//============================================================================= -// -// File : kvi_iconmanager.cpp -// Creation date : Sat Jun 24 2000 14:50:11 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - - -#define _KVI_ICONMANAGER_CPP_ - -#include "kvi_iconmanager.h" -#include "kvi_app.h" -#include "kvi_settings.h" -#include "kvi_defaults.h" -#include "KviLocale.h" -#include "KviFileUtils.h" -#include "kvi_options.h" - -#include -#include -#include -#include -#include -#include -#include - -// kvi_app.cpp -extern QPixmap * g_pUserChanStatePixmap; -extern QPixmap * g_pActivityMeterPixmap; - -KviIconManager * g_pIconManager = 0; - -static const char * g_szIconNames[KVI_NUM_SMALL_ICONS]= -{ - "none", // 0 - "close", // 1 - "maximize", // 2 - "minimize", // 3 - "restore", // 4 - "default", // 5 - "dock", // 6 - "undock", // 7 - "quitapp", // 8 - "console", // 9 - "floppy", // 10 - "parsererror", // 11 - "parserwarning", // 12 - "server", // 13 - "world", // 14 - "proxy", // 15 - "kvirc", // 16 - "cut", // 17 - "copy", // 18 - "paste", // 19 - "options", // 20 - "socketmessage", // 21 - "socketwarning", // 22 - "socketerror", // 23 - "systemerror", // 24 - "raw", // 25 - "systemwarning", // 26 - "systemmessage", // 27 - "unhandled", // 28 - "serverinfo", // 29 - "motd", // 30 - "channel", // 31 - "hidedoubleview", // 32 - "showdoubleview", // 33 - "op", // 34 - "voice", // 35 - "serverping", // 36 - "showlistview", // 37 - "hidelistview", // 38 - "join", // 39 - "part", // 40 - "unrecognized", // 41 - "topic", // 42 - "accept", // 43 - "discard", // 44 - "ownprivmsg", // 45 - "chanprivmsg", // 46 - "query", // 48 - "queryprivmsg", // 49 - "help", // 49 - "mdihelp", // 50 - "ctcpreply", // 51 - "ctcprequestreplied", // 52 - "ctcprequestignored", // 53 - "ctcprequestflood", // 54 - "ctcprequestunknown", // 55 - "action", // 56 - "avatar", // 57 - "quit", // 58 - "split", // 59 - "quitsplit", // 60 - "nick", // 61 - "deop", // 62 - "devoice", // 63 - "mode", // 64 - "key", // 65 - "limit", // 66 - "ban", // 67 - "unban", // 68 - "banexcept", // 69 - "banunexcept", // 70 - "inviteexcept", // 71 - "inviteunexcept", // 72 - "chanmode", // 73 - "chanmodehide", // 74 - "who", // 75 - "editor", // 76 - "dccrequest", // 77 - "dccmsg", // 78 - "dccerror", // 79 - "iconmanager", // 80 - "scriptcenter", // 81 - "bomb", // 82 - "event", // 83 - "eventnohandlers", // 84 - "handler", // 85 - "handlerdisabled", // 86 - "nicknameproblem", // 87 - "whoisuser", // 88 - "whoischannels", // 89 - "whoisidle", // 90 - "whoisserver", // 91 - "whoisother", // 92 - "time", // 93 - "notifyonline", // 94 - "notifyoffline", // 95 - "locked", // 96 - "unlocked", // 97 - "lockedoff", // 98 - "unlockedoff", // 99 - "ownprivmsgcrypted", // 100 - "chanprivmsgcrypted", // 101 - "queryprivmsgcrypted", // 102 - "dccchatmsg", // 103 - "dccchatmsgcrypted", // 104 - "irc", // 105 - "folder", // 106 - "home", // 107 - "bookmarks", // 108 - "spy", // 109 - "kick", // 110 - "linux", // 111 - "links", // 112 - "regusers", // 113 - "dockwidget", // 114 - "cascadewindows", // 115 - "maxvertical", // 116 - "maxhorizontal", // 117 - "tilewindows", // 118 - "log", // 119 - "spam", // 120 - "file", // 121 - "icq", // 122 - "icqyellow", // 123 - "icqred", // 124 - "icqblue", // 125 - "icqlightgreen", // 126 - "icqlightyellow", // 127 - "message", // 128 - "messagesent", // 129 - "bluesquare", // 130 - "violetsquare", // 131 - "yellowsquare", // 132 - "greensquare", // 133 - "blacksquare", // 134 - "redsquare", // 135 - "cyansquare", // 136 - "dkgreensquare", // 137 - "terminal", // 138 - "wallops", // 139 - "invisible", // 140 - "servernotice", // 141 - "gnutella", // 142 - "search", // 143 - "files", // 144 - "transfer", // 145 - "package", // 146 - "retry", // 147 - "idea", // 148 - "colors", // 149 - "gui", // 150 - "ircview", // 151 - "alias", // 152 - "channelnotice",// 153 - "channelnoticecrypted", // 154 - "querynotice", // 155 - "querynoticecrypted", // 156 - "servnotice", // 157 - "popup", // 158 - "prologue", // 159 - "epilogue", // 160 - "sharedfiles", // 161 - "ctcpreplyunknown", // 162 - "canvas", // 163 - "nickserv", // 164 - "chanserv", // 165 - "dccvoice", // 166 - "play", // 167 - "record", // 168 - "autotilewindows", // 169 - "away", // 170 - "ident", // 171 - "homepage", // 172 - "list", // 173 - "halfop", // 174 - "halfdeop", // 175 - "invite", // 176 - "multimedia", // 177 - "look", // 178 - "input", // 179 - "messages", // 180 - "querytrace", // 181 - "nochannel", // 182 - "broadcastprivmsg", // 183 - "broadcastnotice", // 184 - "url", // 185 - "rawevent", // 186 - "raweventnohandlers", // 187 - "mekick", // 188 - "meop", // 189 - "mevoice", // 190 - "medeop", // 191 - "medevoice", // 192 - "mehalfop", // 193 - "medehalfop", // 194 - "meban", // 195 - "meunban", // 196 - "mebanexcept", // 197 - "mebanunexcept", // 198 - "meinviteexcept", // 199 - "meinviteunexcept", // 200 - "classicwindowlist", // 201 - "treewindowlist", // 202 - "ignore", // 203 - "userlist",// 204 - "stats", // 205 - "popupmenu", // 206 - "xy", // 207 - "irc0", // 208 - "irc1", // 209 - "irc2", // 210 - "irc3", // 211 - "irc4", // 212 - "irc5", // 213 - "heart", // 214 - "heartbroken", // 215 - "rose", // 215 - "biggrin", // 217 - "biggringlasses", // 218 - "biggrineyes", // 219 - "textexclamative", // 220 - "textpoints", // 221 - "kiss", // 222 - "surprised1", // 223 - "ugly", // 224 - "angry", // 225 - "surprised2", // 226 - "smile", // 227 - "tongue", // 228 - "ssl", // 229 - "cry", // 230 - "eye", // 231 - "deadchannel", // 232 - "deadquery", // 233 - "sound", // 234 - "toolbar", // 235 - "textencoding",// 236 - "newitem", // 237 - "newitembywizard", // 238 - "deleteitem", // 239 - "edititem", // 240 - "filetransfer", // 241 - "chanadmin", // 242 - "chanunadmin", // 243 - "mechanadmin", // 244 - "mechanunadmin", // 245 - "userop", // 246 - "deuserop", // 247 - "meuserop", // 248 - "medeuserop", // 249 - "applet", // 250 - "caption", // 251 - "transparent", // 252 - "alert", // 253 - "userwindow", // 254 - "statusbar", // 255 - "notaway", // 256 - "plus", // 257 - "minus", // 258 - "binarytext", // 259 - "chanowner", // 260 - "chanunowner", // 261 - "mechanowner", // 262 - "mechanunowner", // 263 - "afraid", // 264 - "tongue2", // 265 - "sayicon", // 266 - "saycolors", // 267 - "finger", // 268 - "scriptaction", // 269 - "tearsmile", // 270 - "shy", // 271 - "servererror", // 272 - "cafe", // 273 - "addons", // 274 - "chanowneraway", // 275 - "opaway", // 276 - "voiceaway", // 277 - "chanadminaway", // 278 - "useropaway", // 279 - "halfopaway", // 280 - "classeditor", // 281 - "demoralized", // 282 - "slurp", // 283 - "namespace", // 284 - "saysmile", // 285 - "saykvs", // 286 - "themeoptions", // 287 - "bug", // 288 - "refresh", //289 - "theme", // 290 - "screenshot", // 291 - "update", // 292 - "notupdate", // 293 - "failupdate", // 294 - "unreadtext", // 295 - "ircop", // 296 - "ircopaway", // 297 - "deircop", // 298 - "meircop", // 299 - "medeircop", // 300 - "angel", // 301 - "clown", // 302 - "devil", // 303 - "inlove", // 304 - "ninja", // 305 - "pirate", // 306 - "puke", // 307 - "rage", // 308 - "class", // 309 - "classnotbuilt", // 310 - "function", // 311 - "sexmale", // 312 - "sexfemale", // 313 - "sexbot", // 314 - "sexircop" // 315 -}; - -KviIconWidget::KviIconWidget() -: QWidget(0 /*,WType_TopLevel | WStyle_Customize | WStyle_Title | WStyle_StaysOnTop | WStyle_DialogBorder | WStyle_SysMenu | WStyle_Minimize*/) -{ - setObjectName("global_icon_widget"); - init(); -} - -KviIconWidget::KviIconWidget(QWidget * par) -: QWidget(par) -{ - setObjectName("global_icon_widget"); - init(); -} - -void KviIconWidget::init() -{ - setWindowTitle(__tr2qs("Icon Table")); - setWindowIcon(QIcon(*(g_pIconManager->getSmallIcon(KVI_SMALLICON_ICONMANAGER)))); - - int rows = KVI_NUM_SMALL_ICONS / 20; - if((rows * 20) < KVI_NUM_SMALL_ICONS)rows++; - QGridLayout * g = new QGridLayout(this); - int i; - for(i = 0;i < 20;i++) - { - KviCString tmp(KviCString::Format,"%d",i); - QLabel * l = new QLabel(tmp.ptr(),this); - g->addWidget(l,0,i + 1); - } - for(i = 0;i < rows;i++) - { - KviCString tmp(KviCString::Format,"%d",i * 20); - QLabel * l = new QLabel(tmp.ptr(),this); - g->addWidget(l,i + 1,0); - } - for(i = 0;i < KVI_NUM_SMALL_ICONS;i++) - { - KviCString tmp(KviCString::Format,"%d",i); - QLabel * l = new QLabel(this); - l->setObjectName(tmp.ptr()); - l->setPixmap(*(g_pIconManager->getSmallIcon(i))); - g->addWidget(l,(i / 20) + 1,(i % 20) + 1); - l->installEventFilter(this); - l->setAcceptDrops(true); - } -} - -KviIconWidget::~KviIconWidget() -{ -} - -void KviIconWidget::closeEvent(QCloseEvent * e) -{ - e->ignore(); - emit closed(); -} - -bool KviIconWidget::eventFilter(QObject * o,QEvent *e) -{ - if(e->type() == QEvent::MouseButtonPress) - { - if(o->inherits("QLabel")) - { - KviCString szName = ((QLabel *)o)->objectName(); - bool bOk; - int iVal = szName.toInt(&bOk); - if(bOk)emit selected(iVal); - - if(parentWidget() && isVisible() && parentWidget()->inherits("KviTalPopupMenu")) - { - parentWidget()->close(); - return true; - } else { - if(const QPixmap * pix = ((QLabel *)o)->pixmap()) - { - QDrag *drobj = new QDrag(this); - QMimeData *mimeData = new QMimeData; - - mimeData->setText(o->objectName()); - mimeData->setImageData(*pix); - drobj->setMimeData(mimeData); - drobj->setPixmap(*pix); - } - } - } - } else if(e->type() == QEvent::DragEnter) - { - ((QDragEnterEvent *)e)->setAccepted(true); - return true; - } - return QWidget::eventFilter(o,e); -} - - -KviCachedPixmap::KviCachedPixmap(QPixmap * ptr,const QString &szPath) -{ - m_szPath = szPath; - m_tLastAccess = kvi_unixTime(); - m_pPixmap = ptr; - m_uSize = m_pPixmap->width() * m_pPixmap->height() * (m_pPixmap->depth() / 8); -} - -KviCachedPixmap::~KviCachedPixmap() -{ - delete m_pPixmap; -} - -void KviCachedPixmap::updateLastAccessTime() -{ - m_tLastAccess = kvi_unixTime(); -} - - -KviIconManager::KviIconManager() -{ - int i=0; - for(i=0;i(21,true); - m_pCachedImages->setAutoDelete(true); - - m_uCacheTotalSize = 0; - m_uCacheMaxSize = 1024 * 1024; // 1 MB - - m_pIconWidget = 0; - - QString buffer; - - // Load the userchanstate image - g_pApp->findImage(buffer,KVI_USERCHANSTATE_IMAGE_NAME); - g_pUserChanStatePixmap = new QPixmap(buffer); - - g_pApp->findImage(buffer,KVI_ACTIVITYMETER_IMAGE_NAME); - g_pActivityMeterPixmap = new QPixmap(buffer); - - m_pIconNames = 0; -} - -KviIconManager::~KviIconManager() -{ - delete g_pUserChanStatePixmap; - delete g_pActivityMeterPixmap; - - if(m_pIconWidget)delete m_pIconWidget; - int i; - - for(i=0;igetLocalKvircDirectory(szPath,KviApp::Pics); - QDir::addSearchPath("icons", szPath); - - g_pApp->getGlobalKvircDirectory(szPath,KviApp::Pics); - QDir::addSearchPath("icons", szPath); - - g_pApp->getLocalKvircDirectory(szPath,KviApp::SmallIcons); - QDir::addSearchPath("smallicons", szPath); - - g_pApp->getGlobalKvircDirectory(szPath,KviApp::SmallIcons); - QDir::addSearchPath("smallicons", szPath); - -} - -QString KviIconManager::getSmallIconResourceName(int idx) -{ - QString szName("smallicons:kcs_"); - szName.append(g_szIconNames[idx]); - szName.append(".png"); - return szName; -} - -const char * KviIconManager::getSmallIconName(int idx) -{ - return g_szIconNames[idx]; -} - -int KviIconManager::getSmallIconIdFromName(const QString &szName) -{ - if(!m_pIconNames) - { - m_pIconNames = new KviPointerHashTable(257,false); - m_pIconNames->setAutoDelete(true); - - for(int i=0;ireplace(QString(g_szIconNames[i]),pInt); - } - } - int * pInt = m_pIconNames->find(szName); - if(!pInt)return 0; - return *pInt; -} - -void KviIconManager::showIconWidget() -{ - if(!m_pIconWidget) - { - m_pIconWidget = new KviIconWidget(); - connect(m_pIconWidget,SIGNAL(closed()),this,SLOT(iconWidgetClosed())); - } - m_pIconWidget->show(); - m_pIconWidget->raise(); - m_pIconWidget->setFocus(); -} - -void KviIconManager::iconWidgetClosed() -{ - delete m_pIconWidget; - m_pIconWidget = 0; -} - -/* - @doc: image_id - @title: - The image identifier - @keyterms: - image identifier, using builtin images, how kvirc locates image files - @type: - language - @short: - Semantics of the parameter - @body: - Some KVIrc commands and functions accept - the as a parameter. - The indicates an image to be displayed - by some gui element. Since KVIrc has a set of - builtin icons, we want the user to be able to use it :).[br] - The can be either a signed integer number - or a filename.[br] - If it is a signed integer it is interpreted as - index of the internal KVIrc image to use: - positive integers (starting at 0) indicate - small (16x16) icons (the ones used in the view widget).[br] - If is anything else than a signed integer, - it is interpreted as a filename. - The filename can be an absolute file path or a relative one. - In this last case KVIrc will look for the file in a predefined set - of directories: First in the local "pics" directory (usually - in ~/kvirc-version/pics/), then in the local "incoming" directory, - then in the global "pics" directory, then in the user home (~) - and in the current directory.[br] -*/ - -KviCachedPixmap * KviIconManager::getPixmapWithCache(const QString &szName) -{ - if(szName.isEmpty())return 0; - - KviCachedPixmap * p = m_pCachedImages->find(szName); - - if(p) - { - p->updateLastAccessTime(); - return p; - } - - QPixmap * pix = 0; - - QString szRetPath; - - if(g_pApp->findImage(szRetPath,szName)) - { - pix = new QPixmap(szRetPath); - if(pix->isNull()) - { - delete pix; // it is not an valid image!!! (really bad situation...) - pix = 0; - return 0; - } - } else { - return 0; - } - - p = new KviCachedPixmap(pix,QString(szRetPath)); - addToCache(szName,p); - - return p; -} - -KviCachedPixmap * KviIconManager::getPixmapWithCacheScaleOnLoad(const QString &szName,int iMaxWidth,int iMaxHeight) -{ - if(szName.isEmpty())return 0; - - KviCachedPixmap * p = m_pCachedImages->find(szName); - - if(p) - { - p->updateLastAccessTime(); - return p; - } - - QPixmap * pix = 0; - - QString szRetPath; - - if(g_pApp->findImage(szRetPath,szName)) - { - pix = new QPixmap(szRetPath); - if(pix->isNull()) - { - delete pix; // it is not an valid image!!! (really bad situation...) - pix = 0; - return 0; - } - if((pix->width() > iMaxWidth) || (pix->height() > iMaxHeight)) - { - // scale to fit - int scaleW = iMaxWidth; - int scaleH; - scaleH = (pix->height() * iMaxWidth) / pix->width(); - if(scaleH > iMaxHeight) - { - scaleH = iMaxHeight; - scaleW = (scaleH * pix->width()) / pix->height(); - } - - QImage img = pix->toImage(); - *pix = QPixmap::fromImage(img.scaled(scaleW,scaleH,Qt::IgnoreAspectRatio,Qt::SmoothTransformation)); - } - } else { - return 0; - } - - p = new KviCachedPixmap(pix,QString(szRetPath)); - addToCache(szName,p); - - return p; -} - -void KviIconManager::addToCache(const QString &szName,KviCachedPixmap * p) -{ - if((m_uCacheTotalSize + p->size()) >= m_uCacheMaxSize)cacheCleanup(); - - m_pCachedImages->insert(szName,p); - m_uCacheTotalSize += p->size(); -} - -QPixmap * KviIconManager::getImage(const QString &id,bool bCanBeNumber,QString* pRetPath) -{ - if(id.isEmpty()) - return NULL; - - if(bCanBeNumber) - { - bool bOk; - int idx = id.toInt(&bOk); - if(bOk) - { - // was a number : this is not a filename - if(idx >= 0) - return getSmallIcon(idx % KVI_NUM_SMALL_ICONS); - } else { - if(id.startsWith("$icon")) - { - QString szTmp = id.trimmed(); - szTmp.replace("$icon(",""); - szTmp.replace(")",""); - szTmp = szTmp.trimmed(); - szTmp.replace("\"",""); - idx = getSmallIconIdFromName(szTmp.trimmed()); - if(idx >= 0) - return getSmallIcon(idx % KVI_NUM_SMALL_ICONS); - - } - } - } - - KviCachedPixmap * p = getPixmapWithCache(id); - if(!p) - return NULL; - - if(pRetPath) - *pRetPath = p->path(); - - return p->pixmap(); -} - - -QPixmap * KviIconManager::getBigIcon(const QString &szName) -{ - QPixmap * p = getPixmap(szName); - if(p)return p; - - bool bOk; - int idx = szName.toInt(&bOk); - if(bOk && (idx >= 0)) - { - // was a number : this is not a filename - // it was a small icon: scale it and cache it - QString tmpName = szName; - tmpName += ".scaled16to32"; - p = getPixmap(tmpName); - if(p)return p; - p = getSmallIcon(idx % KVI_NUM_SMALL_ICONS); - if(p) - { - QImage tmpi = p->toImage(); - QImage tmp2 = tmpi.scaled(32,32,Qt::IgnoreAspectRatio,Qt::SmoothTransformation); - QPixmap *pix=new QPixmap(); - *pix = QPixmap::fromImage(tmp2); - KviCachedPixmap * cp = new KviCachedPixmap(pix,QString()); - addToCache(tmpName,cp); - return cp->pixmap(); - } - } - - p = getPixmap("kvi_bigicon_unknown.png"); - if(p)return p; - KviCachedPixmap * cp = new KviCachedPixmap(new QPixmap(32,32),QString()); - addToCache(szName,cp); - return cp->pixmap(); -} - -void KviIconManager::urlToCachedFileName(QString &szFName) -{ - szFName.replace(":","_"); - szFName.replace(";","_"); - szFName.replace("/","_"); - szFName.replace("\\","_"); - szFName.replace("\"","_"); - szFName.replace("\'","_"); - szFName.replace("(","_"); - szFName.replace(")","_"); - szFName.replace("?","_"); - szFName.replace("___","."); - //cut filenames to 255 chars, trying to preserve file name/extension (bug #616) - if(szFName.size()>255) - { - QString ext = szFName.right(55); - szFName.truncate(200); - szFName.append(ext); - } -} - -KviAvatar * KviIconManager::getAvatar(const QString &szLocalPath,const QString &szName) -{ - QString szP,szN; - - if(szLocalPath.isEmpty()) - { - //both path and name empty => fail - if(szName.isEmpty()) - return 0; - if(KviQString::equalCIN("http://",szName,7)) - { - // it's an url, cache it locally - szN = szName; - urlToCachedFileName(szN); - g_pApp->getLocalKvircDirectory(szP,KviApp::Avatars,szN); - szN = szName; // keep the remote url as name - } else { - //locally cached avatar, called only by its szName - szN = KviFileUtils::extractFileName(szName); - g_pApp->getLocalKvircDirectory(szP,KviApp::Avatars,szN); - } - } else if(szName.isEmpty()) - { - if(szLocalPath.isEmpty()) - return 0; - szP = szLocalPath; - szN = KviFileUtils::extractFileName(szLocalPath); - } else { - szP = szLocalPath; - szN = szName; - } - - // avatars bigger than 1024x768 just sux: they can't be seen on tooltips anyway - //KviCachedPixmap * p = KVI_OPTION_BOOL(KviOption_boolScaleAvatarsOnLoad) ? getPixmapWithCacheScaleOnLoad(szP, - // KVI_OPTION_UINT(KviOption_uintScaleAvatarsOnLoadWidth) - // ,KVI_OPTION_UINT(KviOption_uintScaleAvatarsOnLoadHeight)) : getPixmapWithCache(szP); - //if(!p)return 0; - - - KviAvatar* result = 0; - - if(KviFileUtils::fileExists(szP)) - { - if(KVI_OPTION_BOOL(KviOption_boolScaleAvatarsOnLoad)) - { - result = new KviAvatar(szP,szN, - QSize( - KVI_OPTION_UINT(KviOption_uintScaleAvatarsOnLoadWidth), - KVI_OPTION_UINT(KviOption_uintScaleAvatarsOnLoadHeight) - ) - ); - } else { - result = new KviAvatar(szP,szN); - } - } - - //Can't load it - if(result && !result->isValid()) - { - delete result; - result = 0; - } - - return result; -} - -void KviIconManager::clearCache() -{ - m_pCachedImages->clear(); -} - -void KviIconManager::reloadImages() -{ - clearCache(); - for(int i=0;i= KVI_NUM_SMALL_ICONS)return 0; - if(idx < 0)return 0; - - QString szPath; - QString buffer; - KviQString::sprintf(szPath,KVI_SMALLICONS_PREFIX "%s.png",g_szIconNames[idx]); - - g_pApp->findSmallIcon(buffer,szPath); - m_smallIcons[idx] = new QPixmap(buffer); - - //if(m_smallIcon[idx]->isNull()) - //{ - // // load an "unknown" image ?.. but should never happen - //} - return m_smallIcons[idx]; -} - -void KviIconManager::cacheCleanup() -{ - QStringList l; - - KviPointerHashTableIterator it(*m_pCachedImages); - - -//#warning "IMPLEMENT CLEANUP" -/* - while(it.current()) - { - kvi_time_t curTime = kvi_unixTime(); - - if((((unsigned int)it.current()->timestamp) - ((unsigned int)curTime)) > 120) - { - // unused since 2 minutes - // time to cleanup it... - l.append(new KviCString(it.currentKey())); - } - ++it; - } - - for(QStringList::Iterator it = l.begin();it != l.end();++it) - { - m_pCachedImages->remove(*it); - } -*/ -/* - for(KviCString * p =l.first();p;p = l.next()) - { - m_pCachedImages->remove(p->ptr()); - } - if(m_pCachedImages->isEmpty())m_pCleanupTimer->stop(); -*/ -} - -#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES -#include "kvi_iconmanager.moc" -#endif //!COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/kvi_iconmanager.h b/src/kvirc/kernel/kvi_iconmanager.h deleted file mode 100644 index 35d9f5b07..000000000 --- a/src/kvirc/kernel/kvi_iconmanager.h +++ /dev/null @@ -1,528 +0,0 @@ -#ifndef _KVI_ICONMANAGER_H_ -#define _KVI_ICONMANAGER_H_ - -//============================================================================= -// -// File : kvi_iconmanager.h -// Creation date : Sat Jun 24 2000 14:49:24 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviCString.h" -#include "KviAvatar.h" -#include "KviTimeUtils.h" -#include "KviPointerHashTable.h" - -#include -#include -#include - -#define KVI_SMALLICON_NONE 0 -#define KVI_SMALLICON_CLOSE 1 -#define KVI_SMALLICON_MAXIMIZE 2 -#define KVI_SMALLICON_MINIMIZE 3 -#define KVI_SMALLICON_RESTORE 4 -#define KVI_SMALLICON_DEFAULTICON 5 -#define KVI_SMALLICON_DOCK 6 -#define KVI_SMALLICON_UNDOCK 7 -#define KVI_SMALLICON_QUITAPP 8 -#define KVI_SMALLICON_CONSOLE 9 -#define KVI_SMALLICON_FLOPPY 10 -#define KVI_SMALLICON_PARSERERROR 11 -#define KVI_SMALLICON_PARSERWARNING 12 -#define KVI_SMALLICON_SERVER 13 -#define KVI_SMALLICON_WORLD 14 -#define KVI_SMALLICON_PROXY 15 -#define KVI_SMALLICON_KVIRC 16 -#define KVI_SMALLICON_CUT 17 -#define KVI_SMALLICON_COPY 18 -#define KVI_SMALLICON_PASTE 19 -#define KVI_SMALLICON_OPTIONS 20 -#define KVI_SMALLICON_SOCKETMESSAGE 21 -#define KVI_SMALLICON_SOCKETWARNING 22 -#define KVI_SMALLICON_SOCKETERROR 23 -#define KVI_SMALLICON_SYSTEMERROR 24 -#define KVI_SMALLICON_RAW 25 -#define KVI_SMALLICON_SYSTEMWARNING 26 -#define KVI_SMALLICON_SYSTEMMESSAGE 27 -#define KVI_SMALLICON_UNHANDLED 28 -#define KVI_SMALLICON_SERVERINFO 29 -#define KVI_SMALLICON_MOTD 30 -#define KVI_SMALLICON_CHANNEL 31 -#define KVI_SMALLICON_HIDEDOUBLEVIEW 32 -#define KVI_SMALLICON_SHOWDOUBLEVIEW 33 -#define KVI_SMALLICON_OP 34 -#define KVI_SMALLICON_VOICE 35 -#define KVI_SMALLICON_SERVERPING 36 -#define KVI_SMALLICON_SHOWLISTVIEW 37 -#define KVI_SMALLICON_HIDELISTVIEW 38 -#define KVI_SMALLICON_JOIN 39 -#define KVI_SMALLICON_PART 40 -#define KVI_SMALLICON_UNRECOGNIZED 41 -#define KVI_SMALLICON_TOPIC 42 -#define KVI_SMALLICON_ACCEPT 43 -#define KVI_SMALLICON_DISCARD 44 -#define KVI_SMALLICON_OWNPRIVMSG 45 -#define KVI_SMALLICON_CHANPRIVMSG 46 -#define KVI_SMALLICON_QUERY 47 -#define KVI_SMALLICON_QUERYPRIVMSG 48 -#define KVI_SMALLICON_HELP 49 -#define KVI_SMALLICON_MDIHELP 50 -#define KVI_SMALLICON_CTCPREPLY 51 -#define KVI_SMALLICON_CTCPREQUESTREPLIED 52 -#define KVI_SMALLICON_CTCPREQUESTIGNORED 53 -#define KVI_SMALLICON_CTCPREQUESTFLOOD 54 -#define KVI_SMALLICON_CTCPREQUESTUNKNOWN 55 -#define KVI_SMALLICON_ACTION 56 -#define KVI_SMALLICON_AVATAR 57 -#define KVI_SMALLICON_QUIT 58 -#define KVI_SMALLICON_SPLIT 59 -#define KVI_SMALLICON_QUITSPLIT 60 -#define KVI_SMALLICON_NICK 61 -#define KVI_SMALLICON_DEOP 62 -#define KVI_SMALLICON_DEVOICE 63 -#define KVI_SMALLICON_MODE 64 -#define KVI_SMALLICON_KEY 65 -#define KVI_SMALLICON_LIMIT 66 -#define KVI_SMALLICON_BAN 67 -#define KVI_SMALLICON_UNBAN 68 -#define KVI_SMALLICON_BANEXCEPT 69 -#define KVI_SMALLICON_BANUNEXCEPT 70 -#define KVI_SMALLICON_INVITEEXCEPT 71 -#define KVI_SMALLICON_INVITEUNEXCEPT 72 -#define KVI_SMALLICON_CHANMODE 73 -#define KVI_SMALLICON_CHANMODEHIDE 74 -#define KVI_SMALLICON_WHO 75 -#define KVI_SMALLICON_EDITOR 76 -#define KVI_SMALLICON_DCCREQUEST 77 -#define KVI_SMALLICON_DCCMSG 78 -#define KVI_SMALLICON_DCCERROR 79 -#define KVI_SMALLICON_ICONMANAGER 80 -#define KVI_SMALLICON_SCRIPTCENTER 81 -#define KVI_SMALLICON_BOMB 82 -#define KVI_SMALLICON_EVENT 83 -#define KVI_SMALLICON_EVENTNOHANDLERS 84 -#define KVI_SMALLICON_HANDLER 85 -#define KVI_SMALLICON_HANDLERDISABLED 86 -#define KVI_SMALLICON_NICKNAMEPROBLEM 87 -#define KVI_SMALLICON_WHOISUSER 88 -#define KVI_SMALLICON_WHOISCHANNELS 89 -#define KVI_SMALLICON_WHOISIDLE 90 -#define KVI_SMALLICON_WHOISSERVER 91 -#define KVI_SMALLICON_WHOISOTHER 92 -#define KVI_SMALLICON_TIME 93 -#define KVI_SMALLICON_NOTIFYONLINE 94 -#define KVI_SMALLICON_NOTIFYOFFLINE 95 -#define KVI_SMALLICON_LOCKED 96 -#define KVI_SMALLICON_UNLOCKED 97 -#define KVI_SMALLICON_LOCKEDOFF 98 -#define KVI_SMALLICON_UNLOCKEDOFF 99 -#define KVI_SMALLICON_OWNPRIVMSGCRYPTED 100 -#define KVI_SMALLICON_CHANPRIVMSGCRYPTED 101 -#define KVI_SMALLICON_QUERYPRIVMSGCRYPTED 102 -#define KVI_SMALLICON_DCCCHATMSG 103 -#define KVI_SMALLICON_DCCCHATMSGCRYPTED 104 -#define KVI_SMALLICON_IRC 105 -#define KVI_SMALLICON_FOLDER 106 -#define KVI_SMALLICON_HOME 107 -#define KVI_SMALLICON_BOOKMARKS 108 -#define KVI_SMALLICON_SPY 109 -#define KVI_SMALLICON_KICK 110 -#define KVI_SMALLICON_LINUX 111 -#define KVI_SMALLICON_LINKS 112 -#define KVI_SMALLICON_REGUSERS 113 -#define KVI_SMALLICON_TRAYICON 114 -#define KVI_SMALLICON_CASCADEWINDOWS 115 -#define KVI_SMALLICON_MAXVERTICAL 116 -#define KVI_SMALLICON_MAXHORIZONTAL 117 -#define KVI_SMALLICON_TILEWINDOWS 118 -#define KVI_SMALLICON_LOG 119 -#define KVI_SMALLICON_SPAM 120 -#define KVI_SMALLICON_FILE 121 -#define KVI_SMALLICON_ICQ 122 -#define KVI_SMALLICON_ICQYELLOW 123 -#define KVI_SMALLICON_ICQRED 124 -#define KVI_SMALLICON_ICQBLUE 125 -#define KVI_SMALLICON_ICQLIGHTGREEN 126 -#define KVI_SMALLICON_ICQLIGHTYELLOW 127 -#define KVI_SMALLICON_MESSAGE 128 -#define KVI_SMALLICON_MESSAGESENT 129 -#define KVI_SMALLICON_BLUESQUARE 130 -#define KVI_SMALLICON_VIOLETSQUARE 131 -#define KVI_SMALLICON_YELLOWSQUARE 132 -#define KVI_SMALLICON_GREENSQUARE 133 -#define KVI_SMALLICON_BLACKSQUARE 134 -#define KVI_SMALLICON_REDSQUARE 135 -#define KVI_SMALLICON_CYANSQUARE 136 -#define KVI_SMALLICON_DKGREENSQUARE 137 -#define KVI_SMALLICON_TERMINAL 138 -#define KVI_SMALLICON_WALLOPS 139 -#define KVI_SMALLICON_INVISIBLE 140 -#define KVI_SMALLICON_SERVERNOTICE 141 -#define KVI_SMALLICON_GNUTELLA 142 -#define KVI_SMALLICON_SEARCH 143 -#define KVI_SMALLICON_FILES 144 -#define KVI_SMALLICON_TRANSFER 145 -#define KVI_SMALLICON_PACKAGE 146 -#define KVI_SMALLICON_RETRY 147 -#define KVI_SMALLICON_IDEA 148 -#define KVI_SMALLICON_COLORS 149 -#define KVI_SMALLICON_GUI 150 -#define KVI_SMALLICON_IRCVIEW 151 -#define KVI_SMALLICON_ALIAS 152 -#define KVI_SMALLICON_CHANNELNOTICE 153 -#define KVI_SMALLICON_CHANNELNOTICECRYPTED 154 -#define KVI_SMALLICON_QUERYNOTICE 155 -#define KVI_SMALLICON_QUERYNOTICECRYPTED 156 -#define KVI_SMALLICON_SERVNOTICE 157 -#define KVI_SMALLICON_POPUP 158 -#define KVI_SMALLICON_PROLOGUE 159 -#define KVI_SMALLICON_EPILOGUE 160 -#define KVI_SMALLICON_SHAREDFILES 161 -#define KVI_SMALLICON_CTCPREPLYUNKNOWN 162 -#define KVI_SMALLICON_CANVAS 163 -#define KVI_SMALLICON_NICKSERV 164 -#define KVI_SMALLICON_CHANSERV 165 -#define KVI_SMALLICON_DCCVOICE 166 -#define KVI_SMALLICON_PLAY 167 -#define KVI_SMALLICON_RECORD 168 -#define KVI_SMALLICON_AUTOTILEWINDOWS 169 -#define KVI_SMALLICON_AWAY 170 -#define KVI_SMALLICON_IDENT 171 -#define KVI_SMALLICON_HOMEPAGE 172 -#define KVI_SMALLICON_LIST 173 -#define KVI_SMALLICON_HALFOP 174 -#define KVI_SMALLICON_HALFDEOP 175 -#define KVI_SMALLICON_INVITE 176 -#define KVI_SMALLICON_MULTIMEDIA 177 -#define KVI_SMALLICON_LOOK 178 -#define KVI_SMALLICON_INPUT 179 -#define KVI_SMALLICON_MESSAGES 180 -#define KVI_SMALLICON_QUERYTRACE 181 -#define KVI_SMALLICON_NOCHANNEL 182 -#define KVI_SMALLICON_BROADCASTPRIVMSG 183 -#define KVI_SMALLICON_BROADCASTNOTICE 184 -#define KVI_SMALLICON_URL 185 -#define KVI_SMALLICON_RAWEVENT 186 -#define KVI_SMALLICON_RAWEVENTNOHANDLERS 187 -#define KVI_SMALLICON_MEKICK 188 -#define KVI_SMALLICON_MEOP 189 -#define KVI_SMALLICON_MEVOICE 190 -#define KVI_SMALLICON_MEDEOP 191 -#define KVI_SMALLICON_MEDEVOICE 192 -#define KVI_SMALLICON_MEHALFOP 193 -#define KVI_SMALLICON_MEDEHALFOP 194 -#define KVI_SMALLICON_MEBAN 195 -#define KVI_SMALLICON_MEUNBAN 196 -#define KVI_SMALLICON_MEBANEXCEPT 197 -#define KVI_SMALLICON_MEBANUNEXCEPT 198 -#define KVI_SMALLICON_MEINVITEEXCEPT 199 -#define KVI_SMALLICON_MEINVITEUNEXCEPT 200 -#define KVI_SMALLICON_CLASSICWINDOWLIST 201 -#define KVI_SMALLICON_TREEWINDOWLIST 202 -#define KVI_SMALLICON_IGNORE 203 -#define KVI_SMALLICON_USERLIST 204 -#define KVI_SMALLICON_STATS 205 -#define KVI_SMALLICON_POPUPMENU 206 -#define KVI_SMALLICON_XY 207 -#define KVI_SMALLICON_IRC0 208 -#define KVI_SMALLICON_IRC1 209 -#define KVI_SMALLICON_IRC2 210 -#define KVI_SMALLICON_IRC3 211 -#define KVI_SMALLICON_IRC4 212 -#define KVI_SMALLICON_IRC5 213 -#define KVI_SMALLICON_HEART 214 -#define KVI_SMALLICON_HEARTBROKEN 215 -#define KVI_SMALLICON_ROSE 216 -#define KVI_SMALLICON_BIGGRIN 217 -#define KVI_SMALLICON_BIGGRINGLASSES 218 -#define KVI_SMALLICON_BIGGRINEYES 219 -#define KVI_SMALLICON_TEXTEXCLAMATIVE 220 -#define KVI_SMALLICON_TEXTPOINTS 221 -#define KVI_SMALLICON_KISS 222 -#define KVI_SMALLICON_SURPRISED1 223 -#define KVI_SMALLICON_UGLY 224 -#define KVI_SMALLICON_ANGRY 225 -#define KVI_SMALLICON_SURPRISED2 226 -#define KVI_SMALLICON_SMILE 227 -#define KVI_SMALLICON_TONGUE 228 -#define KVI_SMALLICON_SSL 229 -#define KVI_SMALLICON_CRY 230 -#define KVI_SMALLICON_EYE 231 -#define KVI_SMALLICON_DEADCHANNEL 232 -#define KVI_SMALLICON_DEADQUERY 233 -#define KVI_SMALLICON_SOUND 234 -#define KVI_SMALLICON_TOOLBAR 235 -#define KVI_SMALLICON_TEXTENCODING 236 -#define KVI_SMALLICON_NEWITEM 237 -#define KVI_SMALLICON_NEWITEMBYWIZARD 238 -#define KVI_SMALLICON_DELETEITEM 239 -#define KVI_SMALLICON_EDITITEM 240 -#define KVI_SMALLICON_FILETRANSFER 241 -#define KVI_SMALLICON_CHANADMIN 242 -#define KVI_SMALLICON_CHANUNADMIN 243 -#define KVI_SMALLICON_MECHANADMIN 244 -#define KVI_SMALLICON_MECHANUNADMIN 245 -#define KVI_SMALLICON_USEROP 246 -#define KVI_SMALLICON_DEUSEROP 247 -#define KVI_SMALLICON_MEUSEROP 248 -#define KVI_SMALLICON_MEDEUSEROP 249 -#define KVI_SMALLICON_APPLET 250 -#define KVI_SMALLICON_CAPTION 251 -#define KVI_SMALLICON_TRANSPARENT 252 -#define KVI_SMALLICON_ALERT 253 -#define KVI_SMALLICON_USERWINDOW 254 -#define KVI_SMALLICON_STATUSBAR 255 -#define KVI_SMALLICON_NOTAWAY 256 -#define KVI_SMALLICON_PLUS 257 -#define KVI_SMALLICON_MINUS 258 -#define KVI_SMALLICON_BINARYTEXT 259 -#define KVI_SMALLICON_CHANOWNER 260 -#define KVI_SMALLICON_CHANUNOWNER 261 -#define KVI_SMALLICON_MECHANOWNER 262 -#define KVI_SMALLICON_MECHANUNOWNER 263 -#define KVI_SMALLICON_AFRAID 264 -#define KVI_SMALLICON_TONGUE2 265 -#define KVI_SMALLICON_SAYICON 266 -#define KVI_SMALLICON_SAYCOLORS 267 -#define KVI_SMALLICON_FINGER 268 -#define KVI_SMALLICON_SCRIPTACTION 269 -#define KVI_SMALLICON_TEARSMILE 270 -#define KVI_SMALLICON_SHY 271 -#define KVI_SMALLICON_SERVERERROR 272 -#define KVI_SMALLICON_CAFE 273 -#define KVI_SMALLICON_ADDONS 274 -#define KVI_SMALLICON_CHANOWNERAWAY 275 -#define KVI_SMALLICON_OPAWAY 276 -#define KVI_SMALLICON_VOICEAWAY 277 -#define KVI_SMALLICON_CHANADMINAWAY 278 -#define KVI_SMALLICON_USEROPAWAY 279 -#define KVI_SMALLICON_HALFOPAWAY 280 -#define KVI_SMALLICON_CLASSEDITOR 281 -#define KVI_SMALLICON_DEMORALIZED 282 -#define KVI_SMALLICON_SLURP 283 -#define KVI_SMALLICON_NAMESPACE 284 -#define KVI_SMALLICON_SAYSMILE 285 -#define KVI_SMALLICON_SAYKVS 286 -#define KVI_SMALLICON_THEMEOPTIONS 287 -#define KVI_SMALLICON_BUG 288 -#define KVI_SMALLICON_REFRESH 289 -#define KVI_SMALLICON_THEME 290 -#define KVI_SMALLICON_SCREENSHOT 291 -#define KVI_SMALLICON_UPDATE 292 -#define KVI_SMALLICON_NOTUPDATE 293 -#define KVI_SMALLICON_FAILUPDATE 294 -#define KVI_SMALLICON_UNREADTEXT 295 -#define KVI_SMALLICON_IRCOP 296 -#define KVI_SMALLICON_IRCOPAWAY 297 -#define KVI_SMALLICON_DEIRCOP 298 -#define KVI_SMALLICON_MEIRCOP 299 -#define KVI_SMALLICON_MEDEIRCOP 300 -#define KVI_SMALLICON_ANGEL 301 -#define KVI_SMALLICON_CLOWN 302 -#define KVI_SMALLICON_DEVIL 303 -#define KVI_SMALLICON_INLOVE 304 -#define KVI_SMALLICON_NINJA 305 -#define KVI_SMALLICON_PIRATE 306 -#define KVI_SMALLICON_PUKE 307 -#define KVI_SMALLICON_RAGE 308 -#define KVI_SMALLICON_CLASS 309 -#define KVI_SMALLICON_CLASSNOTBUILT 310 -#define KVI_SMALLICON_FUNCTION 311 -#define KVI_SMALLICON_SEXMALE 312 -#define KVI_SMALLICON_SEXFEMALE 313 -#define KVI_SMALLICON_SEXBOT 314 -#define KVI_SMALLICON_SEXIRCOP 315 - -#define KVI_NUM_SMALL_ICONS 316 - - -#define KVI_BIGICON_DISCONNECTED "kvi_bigicon_disconnected.png" -#define KVI_BIGICON_CONNECTING "kvi_bigicon_connecting.png" -#define KVI_BIGICON_CONNECTED "kvi_bigicon_connected.png" -#define KVI_BIGICON_TOOLS "kvi_bigicon_tools.png" -#define KVI_BIGICON_ACTIONS "kvi_bigicon_actions.png" -#define KVI_BIGICON_FOLDER "kvi_bigicon_folder.png" -#define KVI_BIGICON_UNKNOWN "kvi_bigicon_unknown.png" -#define KVI_BIGICON_SEPARATOR "kvi_bigicon_separator.png" -#define KVI_BIGICON_KVS "kvi_bigicon_kvs.png" -#define KVI_BIGICON_THEME "kvi_bigicon_theme.png" -#define KVI_BIGICON_ADDONS "kvi_bigicon_addons.png" - -#define KVI_BIGICON_HELP "kvi_bigicon_help.png" -#define KVI_BIGICON_HELPINDEX "kvi_bigicon_helpindex.png" -#define KVI_BIGICON_HELPBACK "kvi_bigicon_helpback.png" -#define KVI_BIGICON_HELPFORWARD "kvi_bigicon_helpforward.png" -#define KVI_BIGICON_HELPCLOSE "kvi_bigicon_helpclose.png" -#define KVI_BIGICON_HELPSEARCH "kvi_bigicon_helpsearch.png" - -#define KVI_BIGICON_OPEN "kvi_bigicon_open.png" -#define KVI_BIGICON_SAVE "kvi_bigicon_save.png" -#define KVI_BIGICON_REMOVE "kvi_bigicon_remove.png" -#define KVI_BIGICON_WWW "kvi_bigicon_www.png" -#define KVI_BIGICON_PACK "kvi_bigicon_pack.png" -#define KVI_BIGICON_SCREENSHOT "kvi_bigicon_screenshot.png" -#define KVI_BIGICON_REGUSERS "kvi_bigicon_regusers.png" - -#define KVI_SMALLICONS_SUBDIRECTORY "coresmall" -#define KVI_SMALLICONS_PREFIX "kcs_" - -// FIXME: this should be removed -#define KVI_SMALLICONS_IMAGELIB_PREFIX "kvi_smallicon_" - -#define KVI_USERCHANSTATE_IMAGE_NAME "kvi_userchanstate.png" -#define KVI_ACTIVITYMETER_IMAGE_NAME "kvi_activitymeter.png" - -#define KVI_REFRESH_IMAGE_NAME "kvi_icon_refresh.png" - -class KviIconManager; - -class KVIRC_API KviCachedPixmap -{ -public: - // the pixmap MUST be allocated with new QPixmap() - // this calss takes the ownership - KviCachedPixmap(QPixmap * ptr,const QString &szPath); - ~KviCachedPixmap(); -private: - QString m_szPath; - kvi_time_t m_tLastAccess; - QPixmap * m_pPixmap; - unsigned int m_uSize; -public: - QPixmap * pixmap(){ return m_pPixmap; }; - const QString & path(){ return m_szPath; }; - unsigned int size(){ return m_uSize; }; - kvi_time_t lastAccessTime(){ return m_tLastAccess; }; - void updateLastAccessTime(); -}; - -class KVIRC_API KviIconWidget : public QWidget -{ - Q_OBJECT -public: - KviIconWidget(); - KviIconWidget(QWidget * par); - ~KviIconWidget(); -protected: - void init(); - virtual void closeEvent(QCloseEvent *e); - virtual bool eventFilter(QObject * o,QEvent *e); -signals: - void closed(); - void selected(int iIcon); -}; - - - -// -// This class manages the images used by KVIrc. -// -// We handle three types of images: builtin small icons, builtin big icons and generic images. -// -// The builtin small icons are in the pics/coresmall directory (this is to optimize the directory size -// since it's a linear search...), are 16x16 in size and are indexed by numbers in a way that their -// access is really fast. The icons used here are used mostly in KviIrcView (but not exclusively). -// -// The generic images are just "any" image that the underlying Qt engine -// is able to load. They are loaded by (relative) path and -// cached by name. -// -// The builtin big icons are (actually) just generic images -// that are eventually scaled to 32x32 if needed. One can request -// a builtin small icon indexed by number to be scaled -// to the size of 32x32 as a big icon too. -// - -class KVIRC_API KviIconManager : public QObject -{ - Q_OBJECT -public: - KviIconManager(); - ~KviIconManager(); -private: - QPixmap * m_smallIcons[KVI_NUM_SMALL_ICONS]; - KviIconWidget * m_pIconWidget; - - KviPointerHashTable * m_pCachedImages; - KviPointerHashTable * m_pIconNames; - unsigned int m_uCacheTotalSize; - unsigned int m_uCacheMaxSize; -public: - // WARNING: Don't store this pointer! - // id == filename | number that indicates an internal pixmap - // 0 stands for "any" - QPixmap * getImage(const QString &id,bool bCanBeNumber = true,QString* pRetPath = 0); - - // The returned pointer is owned by the icon manager - // and can be deleted at any time : so don't store it - KviCachedPixmap * getPixmapWithCache(const QString &szName); - - // The returned pointer is owned by the icon manager - // and can be deleted at any time : so don't store it - KviCachedPixmap * getPixmapWithCacheScaleOnLoad(const QString &szName,int iMaxWidth,int iMaxHeight); - - // The returned pointer is owned by the icon manager - // and can be deleted at any time : so don't store it - QPixmap * getPixmap(const QString &szName) - { KviCachedPixmap * p = getPixmapWithCache(szName); return p ? p->pixmap() : 0; }; - - // this one never fails... if the image can't be found - // a default 32x32 image is returned - QPixmap * getBigIcon(const QString &szName); - - // this one never fails... if the icon isn't there - // then a default 16x16 image is returned - QPixmap * getSmallIcon(int idx){ return idx < KVI_NUM_SMALL_ICONS ? (m_smallIcons[idx] ? m_smallIcons[idx] : loadSmallIcon(idx) ) : 0; }; - - const char * getSmallIconName(int idx); - - QString getSmallIconResourceName(int idx); - - int getSmallIconIdFromName(const QString &szName); - - // if szLocalPath is empty then szName can be the identification - // string for the avatar - // if szName is empty then it is found from szLocalPath - KviAvatar * getAvatar(const QString &szLocalPath,const QString &szName); - - void urlToCachedFileName(QString &szFName); - - void clearCache(); - void reloadImages(); - - void cacheCleanup(); - -protected: - void addToCache(const QString &szName,KviCachedPixmap * p); - //void loadSmallIcons(); - QPixmap * loadSmallIcon(int idx); - - void initQResourceBackend(); -public slots: - void showIconWidget(); -protected slots: - void iconWidgetClosed(); -}; - -extern KVIRC_API KviIconManager * g_pIconManager; - -#endif //_KVI_ICONMANAGER_H_ diff --git a/src/kvirc/kernel/kvi_internalcmd.cpp b/src/kvirc/kernel/kvi_internalcmd.cpp deleted file mode 100644 index 548c75bdc..000000000 --- a/src/kvirc/kernel/kvi_internalcmd.cpp +++ /dev/null @@ -1,83 +0,0 @@ -//============================================================================= -// -// File : kvi_internalcmd.cpp -// Creation date : Sun Aug 13 2000 19:22:45 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - -#define _KVI_INTERNALCMD_CPP_ - -#include "kvi_internalcmd.h" - -// FIXME: #warning "LOCALIZE THIS!" - -static const char * internalCommandTable[KVI_NUM_INTERNAL_COMMANDS]= -{ - "echo INTERNAL COMMAND ERROR: INDEX OUT OF RANGE", - "help.open -n -m", - "help.open -n", - "about.kvirc", - "if($option(boolShowGeneralOptionsDialogAsToplevel))options.dialog -t; else options.dialog", - "codetester.open", - "socketspy.open", - "links.open", - "if($option(boolShowRegisteredUsersDialogAsToplevel))reguser.edit -t; else reguser.edit", - "trayicon.show", - "trayicon.hide", - "toolbareditor.open", - "aliaseditor.open", - "term.open -m", - "eventeditor.open", - "dirbrowser.open -m", - "dirbrowser.open", - "ident.start", - "ident.stop", - "tip.open", - "openurl http://www.kvirc.net", - "list.open", - "if($option(boolShowChannelsJoinDialogAsToplevel))channelsjoin.open -t;else channelsjoin.open", - "if($option(boolShowServersConnectDialogAsToplevel))options.edit -t KviIrcServerOptionsWidget;else options.edit KviIrcServerOptionsWidget", - "url.list", - "openurl http://www.kvirc.net/?id=themes", - "openurl http://www.kvirc.net/?id=mailinglist", - "openurl https://svn.kvirc.de/kvirc/wiki#Bugreportticket", - "raweditor.open", - "popupeditor.open", - "dialog.file(open,\"Select a Script File\"){ if(!$str.isEmpty($0))parse $0; }", - "actioneditor.open", - "quit", - "openurl http://www.kvirc.ru", - "openurl irc://freenode/kvirc", - "openurl irc://ircnet/kvirc", - "openurl irc://azzurra/kvirc.net", - "openurl http://kvirc-fr.info", - "openurl irc://freenode/kvirc-fr", - "openurl irc://irc.europnet.org/kvirc" -}; - - -const char * kvi_getInternalCommandBuffer(int idx) -{ - if(idx > 0 && idx < KVI_NUM_INTERNAL_COMMANDS) - { - return internalCommandTable[idx]; - } - return internalCommandTable[0]; -} diff --git a/src/kvirc/kernel/kvi_internalcmd.h b/src/kvirc/kernel/kvi_internalcmd.h deleted file mode 100644 index 0fa1639fd..000000000 --- a/src/kvirc/kernel/kvi_internalcmd.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef _KVI_INTERNALCMD_H_ -#define _KVI_INTERNALCMD_H_ -//============================================================================= -// -// File : kvi_internalcmd.h -// Creation date : Sun Aug 13 2000 19:21:12 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" - -#define KVI_INTERNALCOMMAND_ECHO_INTERNALERROR 0 -#define KVI_INTERNALCOMMAND_HELP_NEWMDIWINDOW 1 -#define KVI_INTERNALCOMMAND_HELP_NEWSTATICWINDOW 2 -#define KVI_INTERNALCOMMAND_ABOUT_ABOUTKVIRC 3 -#define KVI_INTERNALCOMMAND_OPTIONS_DIALOG 4 -#define KVI_INTERNALCOMMAND_CODETESTER_OPEN 5 -#define KVI_INTERNALCOMMAND_SOCKETSPY_OPEN 6 -#define KVI_INTERNALCOMMAND_LINKS_OPEN 7 -#define KVI_INTERNALCOMMAND_REGUSER_EDIT 8 -#define KVI_INTERNALCOMMAND_TRAYICON_SHOW 9 -#define KVI_INTERNALCOMMAND_TRAYICON_HIDE 10 -#define KVI_INTERNALCOMMAND_TOOLBAREDITOR_OPEN 11 -#define KVI_INTERNALCOMMAND_ALIASEDITOR_OPEN 12 -#define KVI_INTERNALCOMMAND_TERM_OPEN 13 -#define KVI_INTERNALCOMMAND_EVENTEDITOR_OPEN 14 -#define KVI_INTERNALCOMMAND_BROWSER_OPEN_MDI 15 -#define KVI_INTERNALCOMMAND_BROWSER_OPEN 16 -#define KVI_INTERNALCOMMAND_IDENT_START 17 -#define KVI_INTERNALCOMMAND_IDENT_STOP 18 -#define KVI_INTERNALCOMMAND_TIP_OPEN 19 -#define KVI_INTERNALCOMMAND_KVIRC_HOMEPAGE 20 -#define KVI_INTERNALCOMMAND_LIST_OPEN 21 -#define KVI_INTERNALCOMMAND_CHANNELSJOIN_OPEN 22 -#define KVI_INTERNALCOMMAND_SERVERSJOIN_OPEN 23 -#define KVI_INTERNALCOMMAND_URL_OPEN 24 -#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_THEMES 25 -#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_MAILINGLIST 26 -#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_BUGTRACK 27 -#define KVI_INTERNALCOMMAND_RAWEDITOR_OPEN 28 -#define KVI_INTERNALCOMMAND_POPUPEDITOR_OPEN 29 -#define KVI_INTERNALCOMMAND_EXECUTE_SCRIPT_FROM_DISK 30 -#define KVI_INTERNALCOMMAND_ACTIONEDITOR_OPEN 31 -#define KVI_INTERNALCOMMAND_QUIT 32 -#define KVI_INTERNALCOMMAND_KVIRC_HOMEPAGE_RU 33 -#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_ON_FREENODE 34 -#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_ON_IRCNET 35 -#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_IT_ON_AZZURRA 36 -#define KVI_INTERNALCOMMAND_KVIRC_HOMEPAGE_FR 37 -#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_FR_ON_FREENODE 38 -#define KVI_INTERNALCOMMAND_OPENURL_KVIRC_FR_ON_EUROPNET 39 - -#define KVI_NUM_INTERNAL_COMMANDS 40 - -extern KVIRC_API const char * kvi_getInternalCommandBuffer(int idx); - -#endif //_KVI_INTERNALCMD_H_ diff --git a/src/kvirc/kernel/kvi_ipc.cpp b/src/kvirc/kernel/kvi_ipc.cpp deleted file mode 100644 index 01dc8cf87..000000000 --- a/src/kvirc/kernel/kvi_ipc.cpp +++ /dev/null @@ -1,284 +0,0 @@ -//============================================================================= -// -// File : kvi_ipc.hcpp -// Creation date : Tue Apr 10 2001 15:04:45 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2001-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 -#include "kvi_ipc.h" - - -#ifndef COMPILE_NO_IPC - - #include "KviMemory.h" - #include "kvi_app.h" - #include "KviQString.h" - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - - static HWND kvi_win_findIpcSentinel() - { - HWND hWnd = ::FindWindow("QWidget","[Non-Commercial] - kvirc4_ipc_sentinel"); - if(hWnd)return hWnd; - hWnd = ::FindWindow("QWidget","[Freeware] - kvirc4_ipc_sentinel"); - if(hWnd)return hWnd; - hWnd = ::FindWindow("QWidget","kvirc4_ipc_sentinel"); - return hWnd; - } - -#else - - #ifdef COMPILE_X11_SUPPORT - #include - - #include // for getuid - #include // for getuid - - //#include - #include - #define kvi_ipc_get_xdisplay QX11Info::display - #define kvi_ipc_get_xrootwin QX11Info::appRootWindow - - static Atom kvi_atom_ipc_sentinel_window; - static Atom kvi_atom_ipc_remote_command; - static Atom kvi_atom_ipc_remote_message; - static KviCString kvi_sentinel_id; - static bool g_bIpcAtomsLoaded = false; - - static void kvi_ipcLoadAtoms() - { - if(g_bIpcAtomsLoaded)return; - g_bIpcAtomsLoaded = true; - kvi_sentinel_id.sprintf("pane tonno e mistero - %d",getuid()); - kvi_atom_ipc_sentinel_window = XInternAtom(kvi_ipc_get_xdisplay(),"XA_KVI4_IPC_SENTINEL_WINDOW",False); - kvi_atom_ipc_remote_command = XInternAtom(kvi_ipc_get_xdisplay(),"XA_KVI4_IPC_REMOTE_COMMAND",False); - kvi_atom_ipc_remote_message = XInternAtom(kvi_ipc_get_xdisplay(),"XA_KVI4_IPC_REMOTE_MESSAGE",False); - } - - static void kvi_ipcSetRemoteCommand(Window w,const char * command) - { - XChangeProperty(kvi_ipc_get_xdisplay(),w,kvi_atom_ipc_remote_command, - XA_STRING,8,PropModeReplace,(const unsigned char *)command,kvi_strLen(command) + 1); - } - - static Window kvi_x11_findIpcSentinel(Window win) - { - Atom type; - int format; - unsigned long nItems,after; - unsigned char * data = 0; - if(XGetWindowProperty(kvi_ipc_get_xdisplay(),win,kvi_atom_ipc_sentinel_window,0,32,FALSE,XA_STRING, - &type,&format,&nItems,&after,&data) == Success) - { - if((type == XA_STRING) && (format == 8)) - { - if((nItems == ((unsigned long)(kvi_sentinel_id.len()))) && data) - { - if(kvi_strEqualCSN((const char *)data,kvi_sentinel_id.ptr(),kvi_sentinel_id.len())) - { - XFree((char *)data); - return win; - } - } - } - } - - Window root,parent; - Window * children; - unsigned int nChildren; - - if(!XQueryTree(kvi_ipc_get_xdisplay(),win,&root,&parent,&children,&nChildren)) - { - if(children)XFree((char *)children); - return 0; - } - - Window found = 0; - - for(int i=nChildren-1;(!found) && (i >= 0);i--) - found = kvi_x11_findIpcSentinel(children[i]); - - if(children)XFree((char *)children); - - return found; - } - #endif //!COMPILE_NO_X - -#endif - - - #define KVI_WINDOWS_IPC_MESSAGE 0x2FACE5 - - bool kvi_sendIpcMessage(const char * message) - { -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - - HWND hSentinel = kvi_win_findIpcSentinel(); - if(hSentinel != NULL) - { - COPYDATASTRUCT cpd; - cpd.cbData = strlen(message)+1; - cpd.dwData = KVI_WINDOWS_IPC_MESSAGE; - cpd.lpData = (void *)message; - DWORD dwResult; - //qDebug(message); -#if defined(COMPILE_ON_WINDOWS) && !(defined(MINGW)) - if(!::SendMessageTimeout(hSentinel,WM_COPYDATA,(WPARAM)NULL,(LPARAM)&cpd,SMTO_BLOCK,1000,(PDWORD_PTR)&dwResult)) -#else - if(!::SendMessageTimeout(hSentinel,WM_COPYDATA,(WPARAM)NULL,(LPARAM)&cpd,SMTO_BLOCK,1000,&dwResult)) -#endif - { - qDebug("Failed to send IPC message: error code 0x%x",::GetLastError()); - } - return true; - } -#else - #ifdef COMPILE_X11_SUPPORT - - kvi_ipcLoadAtoms(); - - Window sentinel = kvi_x11_findIpcSentinel(kvi_ipc_get_xrootwin()); - if(sentinel != 0) - { -// XChangeProperty(kvi_ipc_get_xdisplay(),sentinel,kvi_atom_ipc_remote_command,XA_STRING,8, -// PropModeReplace,(const unsigned char *)message,kvi_strLen(message)); - kvi_ipcSetRemoteCommand(sentinel,message); - - XEvent e; - KviMemory::set(&e,0,sizeof(XEvent)); - e.type = ClientMessage; - e.xclient.display = kvi_ipc_get_xdisplay(); - e.xclient.window = sentinel; - e.xclient.message_type = kvi_atom_ipc_remote_message; - e.xclient.format = 8; - - XSendEvent(kvi_ipc_get_xdisplay(),sentinel,False,0,&e); - - return true; - } - #endif //!COMPILE_NO_X -#endif - return false; - } - - - ////////////////////////////////////////////////////////////////////// - // class KviIpcSentinel - // - // hidden sentinel of ipc messages - // - ////////////////////////////////////////////////////////////////////// - - KviIpcSentinel::KviIpcSentinel() - : QWidget(0) - { - setObjectName("kvirc4_ipc_sentinel"); -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - setWindowTitle("kvirc4_ipc_sentinel"); - setWindowFlags(Qt::FramelessWindowHint); -#else - #ifdef COMPILE_X11_SUPPORT - kvi_ipcLoadAtoms(); - - XChangeProperty(kvi_ipc_get_xdisplay(),winId(),kvi_atom_ipc_sentinel_window,XA_STRING,8, - PropModeReplace,(const unsigned char *)kvi_sentinel_id.ptr(),kvi_sentinel_id.len()); - - kvi_ipcSetRemoteCommand(winId(),""); - #endif //!COMPILE_NO_X -#endif - - move(-50,-50); - resize(1,1); -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - // we need to show the window once otherwise it will never get "realized" - // and we will not be able to find it via FindWindow() - show(); -#endif - hide(); - - } - - KviIpcSentinel::~KviIpcSentinel() - { - } - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - - bool KviIpcSentinel::winEvent(MSG * msg, long * result) - { - if(msg->message == WM_COPYDATA) - { - COPYDATASTRUCT * cpd = (COPYDATASTRUCT *)msg->lParam; - if(cpd) - { - if(cpd->dwData == KVI_WINDOWS_IPC_MESSAGE) - { - qDebug((char *)(cpd->lpData)); - if(g_pApp) - g_pApp->ipcMessage((char *)(cpd->lpData)); - if(result) - *result = 0; - return true; - } - } - } - return false; - } - -#else - #ifdef COMPILE_X11_SUPPORT - bool KviIpcSentinel::x11Event(XEvent *e) - { - if(e->type == ClientMessage) - { - if((e->xclient.message_type = kvi_atom_ipc_remote_message) && (e->xclient.format == 8)) - { - Atom type; - int format; - unsigned long nItems,after; - unsigned char * data = 0; - KviCString szData; - if(XGetWindowProperty(kvi_ipc_get_xdisplay(),winId(),kvi_atom_ipc_remote_command,0,1024,FALSE,XA_STRING, - &type,&format,&nItems,&after,&data) == Success) - { - if((type == XA_STRING) && (format == 8) && (nItems > 0) && data) - { - szData = (char *)data; - XFree((char *)data); - } - } - kvi_ipcSetRemoteCommand(winId(),""); - - if(g_pApp)g_pApp->ipcMessage(szData.ptr()); - return true; - } - } - return false; - } - #endif //!COMPILE_NO_X -#endif - #ifndef COMPILE_USE_STANDALONE_MOC_SOURCES - #include "kvi_ipc.moc" - #endif //!COMPILE_USE_STANDALONE_MOC_SOURCES - -#endif diff --git a/src/kvirc/kernel/kvi_ipc.h b/src/kvirc/kernel/kvi_ipc.h deleted file mode 100644 index e3d68071e..000000000 --- a/src/kvirc/kernel/kvi_ipc.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef _KVI_IPC_H_ -#define _KVI_IPC_H_ -//============================================================================= -// -// File : kvi_ipc.h -// Creation date : Tue Apr 10 2001 15:04:45 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2001-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" - - -#ifndef COMPILE_NO_IPC - - #include "KviCString.h" - - #include - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - #include - #include -#else - #ifdef COMPILE_X11_SUPPORT - #include - #include "KviXlib.h" // for XEvent - #endif //!COMPILE_X11_SUPPORT -#endif - - ////////////////////////////////////////////////////////////////////// - // class KviIpcSentinel - // - ////////////////////////////////////////////////////////////////////// - - class KVIRC_API KviIpcSentinel : public QWidget - { - Q_OBJECT - public: - KviIpcSentinel(); - ~KviIpcSentinel(); - protected: // protected members -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - virtual bool winEvent(MSG * msg, long * result); -#else - #ifdef COMPILE_X11_SUPPORT - virtual bool x11Event(XEvent *e); - #endif //!COMPILE_X11_SUPPORT -#endif - }; -#endif //!COMPILE_NO_IPC - -#endif //_KVI_IPC_H_ diff --git a/src/kvirc/kernel/kvi_ircconnection.cpp b/src/kvirc/kernel/kvi_ircconnection.cpp deleted file mode 100644 index f3e25eecc..000000000 --- a/src/kvirc/kernel/kvi_ircconnection.cpp +++ /dev/null @@ -1,1745 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnection.cpp -// Creation date : Mon 03 May 2004 01:45:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnection.h" -#include "kvi_ircconnectiontarget.h" -#include "kvi_ircconnectionuserinfo.h" -#include "kvi_ircconnectionserverinfo.h" -#include "kvi_ircconnectionstatedata.h" -#include "kvi_ircconnectionantictcpflooddata.h" -#include "kvi_ircconnectionnetsplitdetectordata.h" -#include "kvi_ircconnectionasyncwhoisdata.h" -#include "kvi_ircconnectionrequestqueue.h" -#include "kvi_ircconnectionstatistics.h" -#include "kvi_ircconnectionuserinfo.h" -#include "kvi_ircconnectionserverinfo.h" -#include "kvi_irclink.h" -#include "kvi_ircsocket.h" -#include "KviLocale.h" -#include "KviIrcServerDataBase.h" -#include "KviProxyDataBase.h" -#include "KviError.h" -#include "kvi_out.h" -#include "kvi_options.h" -#include "kvi_console.h" -#include "KviNetUtils.h" -#include "kvi_internalcmd.h" -#include "kvi_frame.h" -#include "kvi_mexlinkfilter.h" -#include "KviMemory.h" -#include "KviMemory.h" -#include "kvi_debug.h" -#include "kvi_channel.h" -#include "kvi_query.h" -#include "kvi_app.h" -#include "KviDataBuffer.h" -#include "kvi_notifylist.h" -#include "KviDnsResolver.h" -#include "kvi_defaults.h" -#include "kvi_sparser.h" -#include "kvi_ircdatastreammonitor.h" -#include "KviDataBuffer.h" -#include "kvi_lagmeter.h" -#include "kvi_kvs_eventtriggers.h" -#include "kvi_kvs_script.h" -#include "KviMircCntrl.h" -#include "KviUserIdentity.h" -#include "KviIdentityProfile.h" -#include "KviSASL.h" -#include "KviNickColors.h" - -#include -#include - -extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; -extern KVIRC_API KviProxyDataBase * g_pProxyDataBase; - -KviIrcConnection::KviIrcConnection(KviIrcContext * pContext,KviIrcConnectionTarget * pTarget,KviUserIdentity * pIdentity) -: QObject() -{ - m_bIdentdAttached = false; - m_pContext = pContext; - m_pConsole = pContext->console(); - m_pTarget = pTarget; - m_pUserIdentity = pIdentity; - m_pChannelList = new KviPointerList; - m_pChannelList->setAutoDelete(false); - m_pQueryList = new KviPointerList; - m_pQueryList->setAutoDelete(false); - m_pLink = new KviIrcLink(this); - m_pUserDataBase = new KviIrcUserDataBase(); - m_pUserInfo = new KviIrcConnectionUserInfo(); - m_pServerInfo = new KviIrcConnectionServerInfo(); - m_pStateData = new KviIrcConnectionStateData(); - m_pAntiCtcpFloodData = new KviIrcConnectionAntiCtcpFloodData(); - m_pNetsplitDetectorData = new KviIrcConnectionNetsplitDetectorData(); - m_pAsyncWhoisData = new KviIrcConnectionAsyncWhoisData(); - m_pStatistics = new KviIrcConnectionStatistics(); - m_pNotifyListTimer = 0; - m_pNotifyListManager = 0; - m_pLocalhostDns = 0; - m_pLagMeter = 0; - m_eState = Idle; - m_pRequestQueue = new KviRequestQueue(); - setupSrvCodec(); - setupTextCodec(); -} - -KviIrcConnection::~KviIrcConnection() -{ - if(m_bIdentdAttached) - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); - - m_bIdentdAttached = false; - if(m_pLocalhostDns) - { - QObject::disconnect(m_pLocalhostDns,SIGNAL(lookupDone(KviDnsResolver *)),0,0); - if(m_pLocalhostDns->isRunning()) - { - m_pLocalhostDns->deleteLater(); - } else { - delete m_pLocalhostDns; - } - } - - - if(m_pNotifyListTimer) - { - delete m_pNotifyListTimer; - m_pNotifyListTimer = 0; - } - - if(m_pNotifyListManager) - { - delete m_pNotifyListManager; // destroy this before the userDb - m_pNotifyListManager = 0; - } - - if(m_pLagMeter) - { - delete m_pLagMeter; - m_pLagMeter = 0; - } - - delete m_pLink; // <-- this MAY trigger a linkTerminated() or something like this! - delete m_pChannelList; - delete m_pQueryList; - delete m_pTarget; - delete m_pUserDataBase; - delete m_pUserInfo; - delete m_pServerInfo; - delete m_pStateData; - delete m_pAntiCtcpFloodData; - delete m_pNetsplitDetectorData; - delete m_pAsyncWhoisData; - delete m_pStatistics; - delete m_pUserIdentity; - m_pRequestQueue->deleteLater(); -} - -void KviIrcConnection::clearOutputQueue(bool bPrivateMessagesOnly) -{ - m_pLink->clearOutputQueue(bPrivateMessagesOnly); -} - -void KviIrcConnection::setEncoding(const QString & szEncoding) -{ - QTextCodec * c = KviLocale::codecForName(szEncoding.toLatin1()); - if(c == m_pTextCodec) - return; - if(!c) - { - m_pConsole->output(KVI_OUT_SYSTEMERROR,__tr2qs("Failed to set the encoding to %Q: mapping not available."),&szEncoding); - return; - } - - QString szTmp = c->name(); - for(KviChannel * ch = m_pChannelList->first(); ch; ch = m_pChannelList->next()) - { - if((ch->textCodec() != c) && (ch->textCodec() != ch->defaultTextCodec())) // actually not using the default! - { - ch->forceTextCodec(c); - if(_OUTPUT_VERBOSE) - ch->output(KVI_OUT_VERBOSE,__tr2qs("Changed text encoding to %Q"),&szTmp); - } - } - - for(KviQuery * q = m_pQueryList->first(); q; q = m_pQueryList->next()) - { - if((q->textCodec() != c) && (q->textCodec() != q->defaultTextCodec())) // actually not using the default! - { - q->forceTextCodec(c); - if(_OUTPUT_VERBOSE) - q->output(KVI_OUT_VERBOSE,__tr2qs("Changed text encoding to %Q"),&szTmp); - } - } - m_pTextCodec = c; - m_pConsole->setTextEncoding(szEncoding); -} - -void KviIrcConnection::setupSrvCodec() -{ - // grab the codec: first look it up in the server data - m_pSrvCodec = 0; - if(!m_pTarget->server()->encoding().isEmpty()) - { - m_pSrvCodec = KviLocale::codecForName(m_pTarget->server()->encoding().toLatin1()); - if(!m_pSrvCodec) - qDebug("KviIrcConnection: can't find QTextCodec for encoding %s",m_pTarget->server()->encoding().toUtf8().data()); - } - - if(!m_pSrvCodec) - { - // try the network - if(!m_pTarget->network()->encoding().isEmpty()) - { - m_pSrvCodec = KviLocale::codecForName(m_pTarget->network()->encoding().toLatin1()); - if(!m_pSrvCodec) - qDebug("KviIrcConnection: can't find QTextCodec for encoding %s",m_pTarget->network()->encoding().toUtf8().data()); - } - } - - if(!m_pSrvCodec) - { - m_pSrvCodec = KviApp::defaultSrvCodec(); - } - m_pConsole->setTextEncoding(QString(m_pSrvCodec->name())); -} - -void KviIrcConnection::setupTextCodec() -{ - // grab the codec: first look it up in the server data - m_pTextCodec = 0; - if(!m_pTarget->server()->textEncoding().isEmpty()) - { - m_pTextCodec = KviLocale::codecForName(m_pTarget->server()->textEncoding().toLatin1()); - if(!m_pTextCodec)qDebug("KviIrcConnection: can't find QTextCodec for encoding %s",m_pTarget->server()->textEncoding().toUtf8().data()); - } - - if(!m_pTextCodec) - { - // try the network - if(!m_pTarget->network()->textEncoding().isEmpty()) - { - m_pTextCodec = KviLocale::codecForName(m_pTarget->network()->textEncoding().toLatin1()); - if(!m_pTextCodec)qDebug("KviIrcConnection: can't find QTextCodec for encoding %s",m_pTarget->network()->textEncoding().toUtf8().data()); - } - } - - if(!m_pTextCodec) - { - m_pTextCodec = KviApp::defaultTextCodec(); - } -} - -/* - * We're asking the connection itself to encode/decode text: use server specific encoding, - * instead of the "user text" encoding used in channels - */ -QByteArray KviIrcConnection::encodeText(const QString & szText) -{ - if(!m_pSrvCodec) - return szText.toUtf8(); - return m_pSrvCodec->fromUnicode(szText); -} - -QString KviIrcConnection::decodeText(const char * pcText) -{ - if(!m_pSrvCodec) - return QString(pcText); - return m_pSrvCodec->toUnicode(pcText); -} - -void KviIrcConnection::serverInfoReceived(const QString & szServerName, const QString & szUserModes, const QString & szChanModes) -{ - serverInfo()->setName(szServerName); - serverInfo()->setSupportedUserModes(szUserModes); - serverInfo()->setSupportedChannelModes(szChanModes); - m_pConsole->updateCaption(); // for server name - m_pConsole->frame()->childConnectionServerInfoChange(this); -} - -const QString & KviIrcConnection::currentNetworkName() -{ - //return m_pTarget->networkName(); - return m_pServerInfo->networkName(); -} - -void KviIrcConnection::abort() -{ - // this WILL trigger linkAttemptFailed() or linkTerminated() - m_pLink->abort(); -} - -void KviIrcConnection::start() -{ - m_eState = Connecting; - if(KVI_OPTION_BOOL(KviOption_boolUseIdentService) && KVI_OPTION_BOOL(KviOption_boolUseIdentServiceOnlyOnConnect)) - { - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_START); - m_bIdentdAttached=true; - } - m_pLink->start(); -} - -void KviIrcConnection::linkEstabilished() -{ - m_eState = Connected; - - // setup reasonable defaults before notifying anyone - m_pStatistics->setConnectionStartTime(kvi_unixTime()); - m_pStatistics->setLastMessageTime(kvi_unixTime()); - m_pServerInfo->setName(target()->server()->hostName()); - m_pServerInfo->setNetworkName(target()->network()->name()); - - // FIXME: With STARTTLS this is called TWICE! - if(KviPointerList * l = context()->monitorList()) - { - for(KviIrcDataStreamMonitor *m =l->first();m;m =l->next()) - m->connectionInitiated(); - } - - // FIXME: With STARTTLS this is called TWICE! - context()->connectionEstabilished(); - - // Ok...we're loggin in now - resolveLocalHost(); - - if(target()->server()->enabledCAP()) - { - /* - * HACK: this is needed to avoid timeouts connecting to server that does not - * support thye CAP extension (yet). Adding a somewhat broken message to a - * CAP LS request will force the server to output an error message. - * - * I'm currently aware of 2 methods: - * 1) using a broken nick (NICK -) to force a 437: ERR_UNAVAILRESOURCE - * 2) ping the server before registration to get a // 451: ERR_NOTREGISTERED - * - * Both method works, but the first method could compromise STARTTLS on some - * server that won't allow you to use tsl if the registration has already started - * - * Please note that irc bouncers are currently broken for this setup: eg. psyBNC - * will let the user login with a "-" (single dash) nickname or executing any - * invalid command without throwing any error at all. - * - * This MUST go as one network packet to avoid possible handshake problems - * on slow connections. - */ - - m_pStateData->setInsideInitialCapLs(true); - m_pStateData->setIgnoreOneYouHaveNotRegisteredError(true); - - // FIXME: The PING method does NOT work with bouncers. We need a timeout here. - - sendFmtData("CAP LS\r\nPING :%Q",&(target()->server()->hostName())); - } else { - loginToIrcServer(); - } -} - -void KviIrcConnection::handleInitialCapLs() -{ - if(!m_pStateData->isInsideInitialCapLs()) - return; // We shouldn't be here... - - m_pStateData->setInsideInitialCapLs(false); - - // STARTTLS support: this has to be checked first because it could imply - // a full cap renegotiation -#ifdef COMPILE_SSL_SUPPORT - if( - KVI_OPTION_BOOL(KviOption_boolUseStartTlsIfAvailable) && - (!link()->socket()->usingSSL()) && - target()->server()->enabledSTARTTLS() && - serverInfo()->supportedCaps().contains("tls",Qt::CaseInsensitive) - ) - { - trySTARTTLS(); // FIXME: Shouldn't we be able to STARTTLS even without CAP support ? - return; - } -#endif - - QString szRequests; - - //SASL - if(KVI_OPTION_BOOL(KviOption_boolUseSaslIfAvailable) && - target()->server()->enabledSASL() && - serverInfo()->supportedCaps().contains("sasl",Qt::CaseInsensitive) - ) - { - szRequests.append("sasl "); - } - -#if 0 - if(serverInfo()->supportedCaps().contains("multi-prefix",Qt::CaseInsensitive)) - { - szRequest.append("multi-prefix"); // NAMES supports this, WHO probably not yet - } -#endif - - //TODO MULTI-PREFIX, others goes here - - if(szRequests.isEmpty()) - { - endInitialCapNegotiation(); - } else { - sendFmtData("CAP REQ :%s",szRequests.trimmed().toUtf8().data()); - m_pStateData->setInsideInitialCapReq(true); - } -} - -void KviIrcConnection::handleInitialCapAck() -{ - if(!m_pStateData->isInsideInitialCapReq()) - return; // We shouldn't be here - - m_pStateData->setInsideInitialCapReq(false); - - bool bUsed=false; - - //SASL - if(KVI_OPTION_BOOL(KviOption_boolUseSaslIfAvailable) && - target()->server()->enabledSASL() && - m_pStateData->enabledCaps().contains("sasl",Qt::CaseInsensitive) - ) - { - m_pStateData->setInsideAuthenticate(true); - bUsed=true; - -#ifdef COMPILE_SSL_SUPPORT - sendFmtData("AUTHENTICATE DH-BLOWFISH"); -#else - sendFmtData("AUTHENTICATE PLAIN"); -#endif - } - - if(!bUsed) - endInitialCapNegotiation(); -} - -void KviIrcConnection::handleAuthenticate(KviCString & szAuth) -{ - //SASL - if(!m_pStateData->isInsideAuthenticate()) - return; - - QByteArray szNick = encodeText(target()->server()->saslNick()); - QByteArray szPass = encodeText(target()->server()->saslPass()); - if(szAuth=="+") - { - //PLAIN - KviCString szOut; - if(KviSASL::plainMethod(szAuth, - szOut, - szNick, - szPass - )) - { - sendFmtData("AUTHENTICATE %s",szOut.ptr()); - } else { - sendFmtData("AUTHENTICATE *"); - } - } else { - //DH-BLOWFISH sasl auth - KviCString szOut; - if(KviSASL::dh_blowfishMethod(szAuth, - szOut, - szNick, - szPass - )) - { - sendFmtData("AUTHENTICATE %s",szOut.ptr()); - } else { - sendFmtData("AUTHENTICATE *"); - } - } -} - -void KviIrcConnection::handleInitialCapNak() -{ - endInitialCapNegotiation(); -} - -void KviIrcConnection::endInitialCapNegotiation() -{ - m_pStateData->setInsideAuthenticate(false); - sendFmtData("CAP END"); - loginToIrcServer(); -} - -void KviIrcConnection::handleFailedInitialCapLs() -{ - m_pStateData->setInsideInitialCapLs(false); - loginToIrcServer(); -} - -void KviIrcConnection::linkTerminated() -{ - if(m_bIdentdAttached) - { - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); - m_bIdentdAttached=false; - } - m_eState = Idle; - - if(m_pNotifyListManager) - { - delete m_pNotifyListManager; - m_pNotifyListManager = 0; - } - - if(m_pLagMeter) - { - delete m_pLagMeter; - m_pLagMeter = 0; - } - - if(KviPointerList * l = context()->monitorList()) - { - for(KviIrcDataStreamMonitor *m =l->first();m;m =l->next()) - m->connectionTerminated(); - } - - // Prepare data for an eventual reconnect - context()->connectionTerminated(); -} - -void KviIrcConnection::linkAttemptFailed(int iError) -{ - if(m_bIdentdAttached) - { - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); - m_bIdentdAttached=false; - } - m_eState = Idle; - context()->connectionFailed(iError); -} - -KviChannel * KviIrcConnection::findChannel(const QString & szName) -{ - for(KviChannel * c = m_pChannelList->first(); c; c = m_pChannelList->next()) - { - if(KviQString::equalCI(szName,c->windowName())) - return c; - } - return 0; -} - -int KviIrcConnection::getCommonChannels(const QString & szNick, QString & szChansBuffer, bool bAddEscapeSequences) -{ - int iCount = 0; - for(KviChannel * c = m_pChannelList->first(); c; c = m_pChannelList->next()) - { - if(c->isOn(szNick)) - { - if(!szChansBuffer.isEmpty()) - szChansBuffer.append(", "); - - char uFlag = c->getUserFlag(szNick); - if(uFlag) - { - KviQString::appendFormatted(szChansBuffer,bAddEscapeSequences ? "%c\r!c\r%Q\r" : "%c%Q",uFlag,&(c->windowName())); - } else { - if(bAddEscapeSequences) - KviQString::appendFormatted(szChansBuffer,"\r!c\r%Q\r",&(c->windowName())); - else szChansBuffer.append(c->windowName()); - } - iCount++; - } - } - return iCount; -} - -void KviIrcConnection::unhighlightAllChannels() -{ - for(KviChannel * c = m_pChannelList->first(); c; c = m_pChannelList->next()) - c->unhighlight(); -} - -void KviIrcConnection::unhighlightAllQueries() -{ - for(KviQuery * c = m_pQueryList->first(); c; c = m_pQueryList->next()) - c->unhighlight(); -} - -void KviIrcConnection::closeAllChannels() -{ - while(m_pChannelList->first()) - { - m_pChannelList->first()->close(); - QApplication::processEvents(QEventLoop::ExcludeSocketNotifiers & QEventLoop::ExcludeUserInputEvents); - } -} - -void KviIrcConnection::closeAllQueries() -{ - while(m_pQueryList->first()) - { - m_pQueryList->first()->close(); - QApplication::processEvents(QEventLoop::ExcludeSocketNotifiers & QEventLoop::ExcludeUserInputEvents); - } -} - -KviChannel * KviIrcConnection::createChannel(const QString & szName) -{ - KviChannel * c = m_pContext->findDeadChannel(szName); - if(c) - { - c->setAliveChan(); - if(!KVI_OPTION_BOOL(KviOption_boolCreateMinimizedChannels)) - { - c->raise(); - c->setFocus(); - } - } else { - c = new KviChannel(m_pConsole->frame(),m_pConsole,szName); - m_pConsole->frame()->addWindow(c,!KVI_OPTION_BOOL(KviOption_boolCreateMinimizedChannels)); - - if(KVI_OPTION_BOOL(KviOption_boolPasteLastLogOnChannelJoin)) - c->pasteLastLog(); - } - return c; -} - -KviQuery * KviIrcConnection::createQuery(const QString & szNick) -{ - KviQuery * q = m_pContext->findDeadQuery(szNick); - if(!q) - { - q = findQuery(szNick); - if(q) - return q; // hm ? - } - if(q) - { - q->setAliveQuery(); - if(!KVI_OPTION_BOOL(KviOption_boolCreateMinimizedQuery)) - { - q->raise(); - q->setFocus(); - } - } else { - q = new KviQuery(m_pConsole->frame(),m_pConsole,szNick); - m_pConsole->frame()->addWindow(q,!KVI_OPTION_BOOL(KviOption_boolCreateMinimizedQuery)); - } - return q; -} - -KviQuery * KviIrcConnection::findQuery(const QString & szName) -{ - for(KviQuery * c = m_pQueryList->first(); c; c = m_pQueryList->next()) - { - if(KviQString::equalCI(szName,c->windowName())) - return c; - } - return 0; -} - -void KviIrcConnection::registerChannel(KviChannel * c) -{ - m_pChannelList->append(c); - if(KVI_OPTION_BOOL(KviOption_boolLogChannelHistory)) - g_pApp->addRecentChannel(c->windowName(),m_pServerInfo->networkName()); - emit(channelRegistered(c)); - emit(chanListChanged()); -} - -void KviIrcConnection::unregisterChannel(KviChannel * c) -{ - m_pChannelList->removeRef(c); - requestQueue()->dequeueChannel(c); - emit(channelUnregistered(c)); - emit(chanListChanged()); -} - -void KviIrcConnection::registerQuery(KviQuery * q) -{ - m_pQueryList->append(q); -} - -void KviIrcConnection::unregisterQuery(KviQuery * q) -{ - if(m_pQueryList->removeRef(q)) - return; -} - -void KviIrcConnection::keepChannelsOpenAfterDisconnect() -{ - while(KviChannel * c = m_pChannelList->first()) - { - c->outputNoFmt(KVI_OUT_SOCKETERROR,__tr2qs("Connection to server lost")); - c->setDeadChan(); - } -} - -void KviIrcConnection::keepQueriesOpenAfterDisconnect() -{ - while(KviQuery * q = m_pQueryList->first()) - { - q->outputNoFmt(KVI_OUT_SOCKETERROR,__tr2qs("Connection to server lost")); - q->setDeadQuery(); - } -} - -void KviIrcConnection::resurrectDeadQueries() -{ - while(KviQuery * q = m_pContext->firstDeadQuery()) - { - q->outputNoFmt(KVI_OUT_SOCKETMESSAGE,__tr2qs("Connection to server established")); - q->setAliveQuery(); - } -} - - -//=== Message send stuff ====================================================// -// Max buffer that can be sent to an IRC server is 512 bytes -// including CRLF. (ircd simply 'cuts' messages to 512 bytes -// and discards the remainig part) -// Note that 510 bytes of data is a reasonably long message :) -// -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 01234567890123456789012345678901234567890123456789 -// 0123456789\r\n -// -// We keep a list of data to send, and flush it as soon as we can. -// - -bool KviIrcConnection::sendFmtData(const char * pcFmt, ...) -{ - KviDataBuffer * pData = new KviDataBuffer(512); - kvi_va_list(list); - kvi_va_start(list,pcFmt); - bool bTruncated; - //sprintf the buffer up to 512 chars (adds a CRLF too) - int iLen = kvi_irc_vsnprintf((char *)(pData->data()),pcFmt,list,&bTruncated); - kvi_va_end(list); - - //adjust the buffer size - if(iLen < 512) - pData->resize(iLen); - - if(bTruncated) - { - if(!_OUTPUT_MUTE) - m_pConsole->outputNoFmt(KVI_OUT_SOCKETWARNING,__tr2qs("[LINK WARNING]: Socket message truncated to 512 bytes.")); - } - - QString szMsg = QString::fromLatin1((const char *)(pData->data()), iLen-2); - - // notify the monitors - if(KviPointerList * l = context()->monitorList()) - { - for(KviIrcDataStreamMonitor * m = l->first(); m; m = l->next()) - { - if(m->outgoingMessage(szMsg.toLatin1().data())) - return true; - } - } - - // Trigger OnOutboundTraffic event - KVS_TRIGGER_EVENT_1(KviEvent_OnOutboundTraffic,m_pConsole->activeWindow(),szMsg); - - return m_pLink->sendPacket(pData); -} - -bool KviIrcConnection::sendData(const char * pcBuffer, int iBuflen) -{ - if(iBuflen < 0) - iBuflen = (int)strlen(pcBuffer); - if(iBuflen > 510) - { - iBuflen = 510; - if(!_OUTPUT_MUTE) - m_pConsole->outputNoFmt(KVI_OUT_SOCKETWARNING,__tr2qs("[LINK WARNING]: Socket message truncated to 512 bytes.")); - } - - KviDataBuffer * pData = new KviDataBuffer(iBuflen + 2); - KviMemory::move(pData->data(),pcBuffer,iBuflen); - *(pData->data() + iBuflen) = '\r'; - *(pData->data() + iBuflen + 1) = '\n'; - - QString szMsg = (const char *)(pData->data()); - szMsg.truncate(iBuflen); - - // notify the monitors - if(KviPointerList * l = context()->monitorList()) - { - for(KviIrcDataStreamMonitor * m = l->first(); m; m = l->next()) - { - if(m->outgoingMessage(szMsg.toUtf8().data())) - return true; - } - } - - // Trigger OnOutboundTraffic event - KVS_TRIGGER_EVENT_1(KviEvent_OnOutboundTraffic,m_pConsole->activeWindow(),szMsg); - - return m_pLink->sendPacket(pData); -} - -//============================================================================================== -// notify list management -//============================================================================================== - -void KviIrcConnection::delayedStartNotifyList() -{ - KVI_ASSERT(!m_pNotifyListTimer); - - if(m_pNotifyListTimer) - delete m_pNotifyListTimer; - - m_pNotifyListTimer = new QTimer(); - m_pNotifyListTimer->setInterval(15000); - m_pNotifyListTimer->setSingleShot(true); - m_pNotifyListTimer->start(); - connect(m_pNotifyListTimer,SIGNAL(timeout()),this,SLOT(restartNotifyList())); - - // This delay is large enough to fire after the MOTD has been sent, - // even on the weirdest network. - // If there is no MOTD, this timer will fire after 15 secs, - // If there is a MOTD, restartNotifyList() will be triggered by RPL_ENDOFMOTD and - // will kill the timer before it has fired. -} - -void KviIrcConnection::endOfMotdReceived() -{ - // if the timer is still there running then just - if(m_pNotifyListTimer) - restartNotifyList(); -} - -void KviIrcConnection::restartNotifyList() -{ - if(m_pNotifyListTimer) - { - delete m_pNotifyListTimer; - m_pNotifyListTimer = 0; - } - - // clear it - if(m_pNotifyListManager) - { - m_pNotifyListManager->stop(); // may need to remove watch entries - delete m_pNotifyListManager; - m_pNotifyListManager = 0; - } - - if(!KVI_OPTION_BOOL(KviOption_boolUseNotifyList)) - return; - - if(serverInfo()->supportsWatchList() && KVI_OPTION_BOOL(KviOption_boolUseWatchListIfAvailable)) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("The server seems to support the WATCH notify list method, will try to use it")); - m_pNotifyListManager = new KviWatchNotifyListManager(this); - } else { - if(KVI_OPTION_BOOL(KviOption_boolUseIntelligentNotifyListManager)) - { - m_pNotifyListManager = new KviIsOnNotifyListManager(this); - } else { - m_pNotifyListManager = new KviStupidNotifyListManager(this); - } - } - m_pNotifyListManager->start(); -} - -void KviIrcConnection::restartLagMeter() -{ - if(m_pLagMeter) - { - delete m_pLagMeter; - m_pLagMeter = 0; - } - if(!KVI_OPTION_BOOL(KviOption_boolUseLagMeterEngine)) - return; - m_pLagMeter = new KviLagMeter(this); -} - -void KviIrcConnection::resolveLocalHost() -{ - QString szIp; - - if(!link()->socket()->getLocalHostIp(szIp,target()->server()->isIPv6())) - { - bool bGotIp = false; - if(!KVI_OPTION_STRING(KviOption_stringLocalHostIp).isEmpty()) - { -#ifdef COMPILE_IPV6_SUPPORT - if(target()->server()->isIPv6()) - { - if(KviNetUtils::isValidStringIPv6(KVI_OPTION_STRING(KviOption_stringLocalHostIp))) - bGotIp = true; - } else { -#endif - if(KviNetUtils::isValidStringIp(KVI_OPTION_STRING(KviOption_stringLocalHostIp))) - bGotIp = true; -#ifdef COMPILE_IPV6_SUPPORT - } -#endif - } - - if(bGotIp) - { - m_pUserInfo->setLocalHostIp(KVI_OPTION_STRING(KviOption_stringLocalHostIp)); - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Can't resolve local host address, using user supplied one (%Q)"), - &(m_pUserInfo->localHostIp())); - - } else { - // FIXME : Maybe check for IPv6 here too ? - m_pUserInfo->setLocalHostIp("127.0.0.1"); - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Can't resolve local host address, using default 127.0.0.1"), - &(m_pUserInfo->localHostIp())); - } - } else { - m_pUserInfo->setLocalHostIp(szIp); - if(!_OUTPUT_QUIET) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Local host address is %Q"), - &(m_pUserInfo->localHostIp())); - } - - // For now this is the only we know - m_pUserInfo->setHostName(m_pUserInfo->localHostIp()); - m_pUserInfo->setHostIp(m_pUserInfo->localHostIp()); -} - -void KviIrcConnection::changeAwayState(bool bAway) -{ - if(bAway) - m_pUserInfo->setAway(); - else m_pUserInfo->setBack(); - - m_pConsole->updateCaption(); - m_pConsole->frame()->childConnectionAwayStateChange(this); - - emit awayStateChanged(); -} - -void KviIrcConnection::userInfoReceived(const QString & szUserName, const QString & szHostName) -{ - userInfo()->setUserName(szUserName); - QString szUnmaskedHost = m_pUserInfo->unmaskedHostName(); - // Update the user entry - KviIrcUserEntry * e = userDataBase()->find(userInfo()->nickName()); - if(e) // should be there! (we have the permanent entry in the notify list view) - { - e->setUser(szUserName); - if(!szHostName.isEmpty())e->setHost(szHostName); - } // else buuug - - if(szHostName.isEmpty()) - return; // nothing to do anyway - - if(KviQString::equalCS(m_pUserInfo->hostName(),szHostName)) - return; // again nothing to do - - static bool warned_once = false; - - if(!warned_once) - { - if(!(m_pUserInfo->hostName().isEmpty() || KviQString::equalCS(m_pUserInfo->hostName(),m_pUserInfo->localHostIp()))) - { - // ok, something weird is probably going on - // is is non-empty and it is NOT the IP address we have set - // at connection startup... - // ...the server (or more likely the bouncer) must have changed his mind... - if(!_OUTPUT_MUTE) - { - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("The server reports a hostname differing from what KVIrc set for the local hostname.")); - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("This can happen if you use a broken bouncer, the IRC server masks your IP/Hostname or something weird is happening on the IRC server.")); - } - warned_once = true; - } - } - - // set it - m_pUserInfo->setHostName(szHostName); - - bool bChangeIp = true; - - // if we don't have any routable IP yet, then it is worth to lookup the new hostname - -#ifdef COMPILE_IPV6_SUPPORT - if((KviNetUtils::isValidStringIp(m_pUserInfo->hostIp()) && - KviNetUtils::isRoutableIpString(m_pUserInfo->hostIp())) || - KviNetUtils::isValidStringIPv6(m_pUserInfo->hostIp())) -#else - if((KviNetUtils::isValidStringIp(m_pUserInfo->hostIp()) && - KviNetUtils::isRoutableIpString(m_pUserInfo->hostIp()))) -#endif - { - if(KVI_OPTION_BOOL(KviOption_boolDccGuessIpFromServerWhenLocalIsUnroutable) && - KVI_OPTION_BOOL(KviOption_boolDccBrokenBouncerHack)) - { - if(!_OUTPUT_MUTE) - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Here goes your \"broken bouncer hack\": The server has changed the hostname but I'll ignore the IP address change")); - bChangeIp = false; - } - } - - if(bChangeIp) - { - // lookup the new hostname then... -#ifdef COMPILE_IPV6_SUPPORT - if(KviNetUtils::isValidStringIp(szHostName) || KviNetUtils::isValidStringIPv6(szHostName)) -#else - if(KviNetUtils::isValidStringIp(szHostName)) -#endif - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("The local IP address as seen by the IRC server is %Q"),&szHostName); - m_pUserInfo->setHostIp(szHostName); - } else -#ifdef COMPILE_IPV6_SUPPORT - if(KviNetUtils::isValidStringIp(szUnmaskedHost) || KviNetUtils::isValidStringIPv6(szUnmaskedHost)) -#else - if(KviNetUtils::isValidStringIp(szUnmaskedHost)) -#endif - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("The local IP address as seen by the IRC server is %Q"),&szUnmaskedHost); - m_pUserInfo->setHostIp(szUnmaskedHost); - - } else { - // look it up too - if(m_pLocalhostDns) - delete m_pLocalhostDns; // it could be only another local host lookup - m_pLocalhostDns = new KviDnsResolver(); - connect(m_pLocalhostDns,SIGNAL(lookupDone(KviDnsResolver *)),this,SLOT(hostNameLookupTerminated(KviDnsResolver *))); - - if(!m_pLocalhostDns->lookup(szHostName,KviDnsResolver::Any)) - { - if(!_OUTPUT_MUTE) - { - // don't change the string to aid the translators - QString szTmp = __tr2qs("Can't start the DNS slave thread"); - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Unable to resolve the local hostname as seen by the IRC server: %Q"),&szTmp); - } - delete m_pLocalhostDns; - m_pLocalhostDns = 0; - } else { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Looking up the local hostname as seen by the IRC server (%Q)"),&szHostName); - } - } - } -} - -void KviIrcConnection::hostNameLookupTerminated(KviDnsResolver *) -{ - if(!m_pLocalhostDns) - { - qDebug("Something weird is happening: pDns != 0 but m_pLocalhostDns == 0 :/"); - return; - } - - if(m_pLocalhostDns->state() != KviDnsResolver::Success) - { - QString szErr = KviError::getDescription(m_pLocalhostDns->error()); - if(!m_pUserInfo->hostIp().isEmpty()) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Unable to resolve the local hostname as seen by the IRC server: %Q, using previously resolved %Q"), - &szErr,&(m_pUserInfo->hostIp())); - else - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Unable to resolve the local hostname as seen by the IRC server: %Q"), - &szErr); - } else { - QString szIpAddr = m_pLocalhostDns->firstIpAddress(); - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Local hostname as seen by the IRC server resolved to %Q"),&szIpAddr); - m_pUserInfo->setHostIp(m_pLocalhostDns->firstIpAddress()); - } - - delete m_pLocalhostDns; - m_pLocalhostDns = 0; -} - -#ifdef COMPILE_SSL_SUPPORT -void KviIrcConnection::trySTARTTLS() -{ - // Check if the server supports STARTTLS protocol and we want to - // connect through it - //qDebug("Sending STARTTLS command..."); - if(!sendFmtData("STARTTLS")) - { - // Cannot send command - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Impossible to send STARTTLS command to the IRC server. Your connection will NOT be encrypted")); - return; - } - m_pStateData->setSentStartTls(); -} - -void KviIrcConnection::enableStartTlsSupport(bool bEnable) -{ - if(bEnable) - { - // Ok, the server supports STARTTLS protocol - // ssl handshake e switch del socket - //qDebug("Starting SSL handshake..."); - link()->socket()->enterSSLMode(); // FIXME: this should be forwarded through KviIrcLink, probably - } else { - // The server does not support STARTTLS - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("The server does not support STARTTLS command. Your connection will NOT be encrypted")); - } -} -#endif // COMPILE_SSL_SUPPORT - -void KviIrcConnection::useRealName(const QString &szRealName) -{ - // Evaluate functions in the real name (so we can have $version() inside) - - QString szRealNameBuffer = szRealName; - - if(!szRealNameBuffer.isEmpty()) - { - KviQString::escapeKvs(&szRealNameBuffer, KviQString::PermitVariables | KviQString::PermitFunctions); - - KviKvsVariant vRet; - if(KviKvsScript::evaluate(szRealNameBuffer,console(),0,&vRet)) - vRet.asString(szRealNameBuffer); - } - - m_pUserInfo->setRealName(szRealNameBuffer); -} - -void KviIrcConnection::useProfileData(KviIdentityProfileSet * pSet, const QString & szNetwork) -{ - KviIdentityProfile * pProfile = pSet->findNetwork(szNetwork); - if(!pProfile) return; - - // Update connection data - m_pUserInfo->setNickName(pProfile->nick()); - m_pUserInfo->setUserName(pProfile->userName()); - useRealName(pProfile->realName()); -} - -void KviIrcConnection::loginToIrcServer() -{ - KviIrcServer * pServer = target()->server(); - KviIrcNetwork * pNet = target()->network(); - - // For now this is the only we know - m_pServerInfo->setName(pServer->m_szHostname); - - QString szTmpNick, szTmpUser, szTmpPass, szTmpName; - // Username - szTmpUser = pServer->m_szUser.trimmed(); - if(!szTmpUser.isEmpty()) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using server specific username (%Q)"),&(szTmpUser)); - } else { - szTmpUser = pNet->userName().trimmed(); - if(!szTmpUser.isEmpty()) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using network specific username (%Q)"),&(szTmpUser)); - } else { - szTmpUser = KVI_OPTION_STRING(KviOption_stringUsername).trimmed(); - if(szTmpUser.isEmpty()) - szTmpUser = KVI_DEFAULT_USERNAME; - } - } - - m_pUserInfo->setUserName(szTmpUser); - - // Nick - if(pServer->m_pReconnectInfo) - { - szTmpNick=pServer->m_pReconnectInfo->m_szNick; - } - - if(!szTmpNick.isEmpty()) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using connection specific nickname (%Q)"),&(szTmpNick)); - m_pStateData->setLoginNickIndex(0); - } else { - szTmpNick = pServer->m_szNick.trimmed(); - if(!szTmpNick.isEmpty()) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using server specific nickname (%Q)"),&(szTmpNick)); - m_pStateData->setLoginNickIndex(0); - } else { - szTmpNick = pNet->nickName().trimmed(); - if(!szTmpNick.isEmpty()) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using network specific nickname (%Q)"),&(szTmpNick)); - m_pStateData->setLoginNickIndex(0); - } else { - szTmpNick = KVI_OPTION_STRING(KviOption_stringNickname1).trimmed(); - if(szTmpNick.isEmpty()) - { - szTmpNick = KVI_OPTION_STRING(KviOption_stringNickname1) = KVI_DEFAULT_NICKNAME1; - } - m_pStateData->setLoginNickIndex(1); - } - } - } - - m_pUserInfo->setNickName(szTmpNick); - - // Real name - szTmpName=pServer->m_szRealName.trimmed(); - if(!szTmpName.isEmpty()) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using server specific real name (%Q)"),&(szTmpName)); - } else { - szTmpName=pNet->realName().trimmed(); - if(!szTmpName.isEmpty()) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using network specific real name (%Q)"),&(szTmpName)); - } else { - szTmpName=KVI_OPTION_STRING(KviOption_stringRealname); - } - } - - useRealName(szTmpName); - - // Pass - if(pServer->m_pReconnectInfo) - { - szTmpPass=pServer->m_pReconnectInfo->m_szPass; - } - - if(!szTmpPass.isEmpty()) - { - if(!_OUTPUT_MUTE) - { - QString szHidden = QString(szTmpPass.length(), QChar('*')); - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using connection specific password (%Q)"),&(szHidden)); - } - } else { - szTmpPass = pServer->m_szPass.trimmed(); - if(!szTmpPass.isEmpty()) - { - if(!_OUTPUT_MUTE) - { - QString szHidden = QString(szTmpPass.length(), QChar('*')); - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using server specific password (%Q)"),&(szHidden)); - } - } else { - szTmpPass = pNet->password().trimmed(); - if(!szTmpPass.isEmpty()) - { - if(!_OUTPUT_MUTE) - { - QString szHidden = QString(szTmpPass.length(), QChar('*')); - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Using network specific password (%Q)"),&(szHidden)); - } - } - } - } - - m_pUserInfo->setPassword(szTmpPass); - - // Check for identity profiles - KviIdentityProfileSet * pSet = KviIdentityProfileSet::instance(); - bool bProfilesEnabled = pSet ? (pSet->isEnabled() && !pSet->isEmpty()) : false; - if(bProfilesEnabled) useProfileData(pSet,pNet->name()); - - // FIXME: The server's encoding! - setupTextCodec(); - QByteArray szNick = encodeText(m_pUserInfo->nickName()); // never empty - QByteArray szUser = encodeText(m_pUserInfo->userName()); // never empty - QByteArray szReal = encodeText(m_pUserInfo->realName()); // may be empty - QByteArray szPass = encodeText(m_pUserInfo->password()); // may be empty - - if(!szReal.data())szReal = ""; - if(!szPass.data())szReal = ""; - - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Logging in as %Q!%Q :%Q"), - &(m_pUserInfo->nickName()),&(m_pUserInfo->userName()),&(m_pUserInfo->realName())); - - // spity, 27.03.2005: follow the RFC2812 suggested order for connection registration - // first the PASS, then NICK and then USER - - // The pass ? - if(!m_pUserInfo->password().isEmpty()) - { - if(!sendFmtData("PASS :%s",szPass.data())) - { - // disconnected in the meantime - return; - } - } - - if(!sendFmtData("NICK %s",szNick.data())) - { - // disconnected :( - return; - } - - unsigned int iGenderAvatarTag=0; - - if(KVI_OPTION_BOOL(KviOption_boolPrependGenderInfoToRealname) && !KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).isEmpty()) - { - if(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).startsWith("m",Qt::CaseInsensitive)) - { - iGenderAvatarTag|=1; - } else if(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).startsWith("f",Qt::CaseInsensitive)) - { - iGenderAvatarTag|=2; - } - } - - if(KVI_OPTION_BOOL(KviOption_boolPrependAvatarInfoToRealname) && !KVI_OPTION_STRING(KviOption_stringMyAvatar).isEmpty()) - { - iGenderAvatarTag|=4; - } - - if(KVI_OPTION_BOOL(KviOption_boolPrependNickColorInfoToRealname) && - KVI_OPTION_BOOL(KviOption_boolUseSpecifiedSmartColorForOwnNick)) - { - QString szTags; - szTags.sprintf("%c%d,%d%c", - KVI_TEXT_COLOR, - KVI_OPTION_UINT(KviOption_uintUserIrcViewOwnForeground), - KVI_OPTION_UINT(KviOption_uintUserIrcViewOwnBackground), - KVI_TEXT_RESET); - szReal.prepend(KviQString::toUtf8(szTags)); - } - - if(iGenderAvatarTag!=0) - { - QString szTags; - szTags.sprintf("%c%d%c", - KVI_TEXT_COLOR, - iGenderAvatarTag, - KVI_TEXT_RESET); - szReal.prepend(KviQString::toUtf8(szTags)); - } - - if(!sendFmtData("USER %s 0 %s :%s",szUser.data(), - KviQString::toUtf8(pServer->m_szHostname).data(),szReal.data())) - { - // disconnected in the meantime! - return; - } - - // permanent info in the user database - m_pConsole->notifyListView()->join(m_pUserInfo->nickName(),"*","*"); - - // set own avatar if we have it - KviIrcUserEntry * e = userDataBase()->find(userInfo()->nickName()); - if(e) // should be there! - { - if(!e->avatar()) - { - KviAvatar * av = m_pConsole->defaultAvatarFromOptions(); - if(av) - { - e->setAvatar(av); - m_pConsole->notifyListView()->avatarChanged(userInfo()->nickName()); - } - } - } // else buuug - - if(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).startsWith("m",Qt::CaseInsensitive)){ - e->setGender(KviIrcUserEntry::Male); - } else if(KVI_OPTION_STRING(KviOption_stringCtcpUserInfoGender).startsWith("f",Qt::CaseInsensitive)){ - e->setGender(KviIrcUserEntry::Female); - } - - // on connect stuff ? - - QString szTmp = pNet->onConnectCommand().trimmed(); - if(!szTmp.isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled network specific \"on connect\" commands")); - KviKvsScript::run(szTmp,m_pConsole); - } - - szTmp = pServer->onConnectCommand().trimmed(); - if(!szTmp.isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled server specific \"on connect\" commands")); - KviKvsScript::run(szTmp,m_pConsole); - } - - szTmp = m_pUserIdentity->onConnectCommand().trimmed(); - if(!szTmp.isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled identity specific \"on connect\" commands")); - KviKvsScript::run(szTmp,m_pConsole); - } - - // and wait for the server to agree... -} - -void KviIrcConnection::nickChange(const QString & szNewNick) -{ - // FIXME: should the new nickname be decoded in some way ? - m_pConsole->notifyListView()->nickChange(m_pUserInfo->nickName(),szNewNick); - m_pUserInfo->setNickName(szNewNick); - m_pConsole->output(KVI_OUT_NICK,__tr2qs("You have changed your nickname to %Q"),&szNewNick); - m_pConsole->updateCaption(); - m_pConsole->frame()->childConnectionNickNameChange(this); - emit nickNameChanged(); - g_pApp->addRecentNickname(szNewNick); -} - -bool KviIrcConnection::changeUserMode(char cMode, bool bSet) -{ - if(bSet) - { - if(m_pUserInfo->hasUserMode(cMode)) - return false; - m_pUserInfo->addUserMode(cMode); - } else { - if(!m_pUserInfo->hasUserMode(cMode)) - return false; - m_pUserInfo->removeUserMode(cMode); - } - m_pConsole->updateCaption(); - console()->frame()->childConnectionUserModeChange(this); - emit userModeChanged(); - return true; -} - -void KviIrcConnection::loginComplete(const QString & szNickName) -{ - if(context()->state() == KviIrcContext::Connected) - return; - - // Stop ignoring ERR_NOTREGISTERED errors. This is related to the initial CAP LS message. - // Well.. we should already have stopped ignoring the errors as we should have received - // the one we expected (because of the PING after CAP LS). Moreover the server shouldn't - // be sending these messages after the login has been completed. - // ...but to be on the safe side we just disable the special handling here. - m_pStateData->setIgnoreOneYouHaveNotRegisteredError(false); - - context()->loginComplete(); - - if(m_bIdentdAttached) - { - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); - m_bIdentdAttached = false; - } - - if(szNickName != m_pUserInfo->nickName()) - { - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("The server refused the suggested nickname (%s) and named you %s instead"),m_pUserInfo->nickName().toUtf8().data(),szNickName.toUtf8().data()); - m_pConsole->notifyListView()->nickChange(m_pUserInfo->nickName(),szNickName); - m_pUserInfo->setNickName(szNickName); - } - - g_pApp->addRecentNickname(szNickName); - - bool bHaltOutput = false; - bHaltOutput = KVS_TRIGGER_EVENT_0_HALTED(KviEvent_OnIRC,m_pConsole); - - if(!bHaltOutput) - m_pConsole->outputNoFmt(KVI_OUT_IRC,__tr2qs("Login operations complete, happy ircing!")); - - resurrectDeadQueries(); - - // on connect stuff ? - QString szTmp = target()->network()->onLoginCommand().trimmed(); - if(!szTmp.isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled network specific \"on login\" commands")); - KviKvsScript::run(szTmp,m_pConsole); - } - - szTmp = target()->server()->onLoginCommand().trimmed(); - if(!szTmp.isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled server specific \"on login\" commands")); - KviKvsScript::run(szTmp,m_pConsole); - } - - szTmp = m_pUserIdentity->onLoginCommand().trimmed(); - if(!szTmp.isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Executing scheduled identity specific \"on login\" commands")); - KviKvsScript::run(szTmp,m_pConsole); - } - - // Set the configured umode - QString szModeStr = target()->server()->initUMode(); - - if(szModeStr.isEmpty()) - szModeStr = KVI_OPTION_STRING(KviOption_stringDefaultUserMode); - - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Setting configured user mode")); - sendFmtData("MODE %s +%s",encodeText(m_pUserInfo->nickName()).data(),encodeText(szModeStr).data()); - - delayedStartNotifyList(); - restartLagMeter(); - - if(KVI_OPTION_BOOL(KviOption_boolShowChannelsJoinOnIrc)) - m_pConsole->frame()->executeInternalCommand(KVI_INTERNALCOMMAND_CHANNELSJOIN_OPEN); - - - // join saved channels - - // FIXME: It should be possible to delay the channel join process after identification - // (or maybe just delay by a fixed amount ?) - // (or maybe retry joining after a while ?) - - QString szChannels,szProtectedChannels,szPasswords,szCurPass,szCurChan; - - if(!(m_pStateData->commandToExecAfterConnect().isEmpty())) - { - KviCString tmp = m_pStateData->commandToExecAfterConnect(); - KviKvsScript::run(tmp.ptr(),m_pConsole); - } - - bool bJoinStdChannels=true; - - if(target()->server()->m_pReconnectInfo) - { - if(!target()->server()->m_pReconnectInfo->m_szJoinChannels.isEmpty()) - { - bJoinStdChannels=false; - sendFmtData("JOIN %s",encodeText(target()->server()->m_pReconnectInfo->m_szJoinChannels).data()); - } - - KviQuery * pQuery; - - for(QStringList::Iterator it = target()->server()->m_pReconnectInfo->m_szOpenQueryes.begin(); - it != target()->server()->m_pReconnectInfo->m_szOpenQueryes.end();it++) - { - QString szNick = *it; - pQuery = findQuery(szNick); - if(!pQuery) - { - pQuery = createQuery(szNick); - QString szUser; - QString szHost; - - KviIrcUserDataBase * db = userDataBase(); - if(db) - { - KviIrcUserEntry * e = db->find(szNick); - if(e) - { - szUser = e->user(); - szHost = e->host(); - } - } - pQuery->setTarget(szNick,szUser,szHost); - } - pQuery->autoRaise(); - pQuery->setFocus(); - } - delete target()->server()->m_pReconnectInfo; - target()->server()->m_pReconnectInfo=0; - } - - if(bJoinStdChannels) - { - if(target()->network()->autoJoinChannelList()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Auto-joining network specific channels")); - - QStringList * l = target()->network()->autoJoinChannelList(); - for(QStringList::Iterator it = l->begin(); it != l->end(); ++it) - { - szCurPass=(*it).section(':',1); - szCurChan = (*it).section(':',0,0); - if(szCurChan.isEmpty()) - continue; - if(szCurPass.isEmpty()) - { - if(!szChannels.isEmpty()) - szChannels.append(","); - if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!' || szCurChan[0]=='+')) - szCurChan.prepend('#'); - szChannels.append(szCurChan); - } else { - if(!szProtectedChannels.isEmpty()) - szProtectedChannels.append(","); - if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!' || szCurChan[0]=='+')) - szCurChan.prepend('#'); - szProtectedChannels.append(szCurChan); - if(!szPasswords.isEmpty()) - szPasswords.append(","); - szPasswords.append(szCurPass); - } - } - } - - if(target()->server()->autoJoinChannelList()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_VERBOSE,__tr2qs("Auto-joining server specific channels")); - - QStringList * l = target()->server()->autoJoinChannelList(); - for(QStringList::Iterator it = l->begin(); it != l->end(); ++it) - { - szCurPass=(*it).section(':',1); - szCurChan = (*it).section(':',0,0); - if(szCurChan.isEmpty()) - continue; - if(szCurPass.isEmpty()) - { - if(!szChannels.isEmpty()) - szChannels.append(","); - if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!' || szCurChan[0]=='+')) - szCurChan.prepend('#'); - szChannels.append(szCurChan); - } else { - if(!szProtectedChannels.isEmpty()) - szProtectedChannels.append(","); - if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!' || szCurChan[0]=='+')) - szCurChan.prepend('#'); - szProtectedChannels.append(szCurChan); - if(!szPasswords.isEmpty()) - szPasswords.append(","); - szPasswords.append(szCurPass); - } - } - } - - QString szCommand; - if( (!szChannels.isEmpty()) || (!szProtectedChannels.isEmpty()) ) - { - szCommand.append(szProtectedChannels); - if(!szProtectedChannels.isEmpty() && !szChannels.isEmpty()) - szCommand.append(','); - szCommand.append(szChannels); - szCommand.append(" "); - szCommand.append(szPasswords); - - sendFmtData("JOIN %s",encodeText(szCommand).data()); - } - } - // minimize after connect - if(KVI_OPTION_BOOL(KviOption_boolMinimizeConsoleAfterConnect)) - m_pConsole->minimize(); -} - -void KviIrcConnection::incomingMessage(const char * pcMessage) -{ - // A message has arrived from the current server - // First of all, notify the monitors - if(KviPointerList * l = context()->monitorList()) - { - for(KviIrcDataStreamMonitor * m = l->first(); m; m = l->next()) - { - if(m->incomingMessage(pcMessage)) - return; - } - } - // set the last message time - m_pStatistics->setLastMessageTime(kvi_unixTime()); - // and pass it to the server parser for processing - g_pServerParser->parseMessage(pcMessage,this); -} - -void KviIrcConnection::incomingMessageNoFilter(const char * pcMessage) -{ - // set the last message time - m_pStatistics->setLastMessageTime(kvi_unixTime()); - // and pass it to the server parser for processing - g_pServerParser->parseMessage(pcMessage,this); -} - -void KviIrcConnection::heartbeat(kvi_time_t tNow) -{ - if(m_eState == Connected) - { - if(KVI_OPTION_BOOL(KviOption_boolEnableAwayListUpdates)) - { - // update the channel WHO lists (fixes users away state) - // first of all, we send our request not more often than every 50 secs - if((tNow - stateData()->lastSentChannelWhoRequest()) > 50) - { - // we also make sure that the last sent request is older than - // the last received reply - if(stateData()->lastSentChannelWhoRequest() <= stateData()->lastReceivedChannelWhoReply()) - { - // find the channel that has the older list now - kvi_time_t tOldest = tNow; - KviChannel * pOldest = 0; - for(KviChannel * pChan = m_pChannelList->first();pChan;pChan = m_pChannelList->next()) - { - if(pChan->lastReceivedWhoReply() < tOldest) - { - pOldest = pChan; - tOldest = pChan->lastReceivedWhoReply(); - } - } - // if the oldest chan who list is older than 150 secs, update it - if((tNow - tOldest) > 150) - { - // ok, sent the request for this channel - stateData()->setLastSentChannelWhoRequest(tNow); - QString szChanName = encodeText(pOldest->windowName()).data(); - if(_OUTPUT_PARANOIC) - console()->output(KVI_OUT_VERBOSE,__tr2qs("Updating away state for channel %Q"),&szChanName); - if(lagMeter()) - { - KviCString tmp(KviCString::Format,"WHO %s",encodeText(pOldest->windowName()).data()); - lagMeter()->lagCheckRegister(tmp.ptr(),70); - } - pOldest->setSentSyncWhoRequest(); - if(!sendFmtData("WHO %s",encodeText(pOldest->windowName()).data())) - return; - } - } - } - } - } -} - -const QString & KviIrcConnection::currentServerName() -{ - return serverInfo()->name(); -} - -const QString & KviIrcConnection::currentNickName() -{ - return userInfo()->nickName(); -} - -const QString & KviIrcConnection::currentUserName() -{ - return userInfo()->userName(); -} \ No newline at end of file diff --git a/src/kvirc/kernel/kvi_ircconnection.h b/src/kvirc/kernel/kvi_ircconnection.h deleted file mode 100644 index 19f6e3111..000000000 --- a/src/kvirc/kernel/kvi_ircconnection.h +++ /dev/null @@ -1,947 +0,0 @@ -#ifndef _KVI_IRCCONNECTION_H_ -#define _KVI_IRCCONNECTION_H_ -//============================================================================= -// -// File : kvi_ircconnection.h -// Creation date : Mon 03 May 2004 01:45:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_ircconnection.h -* \author Szymon Stefanek -* \brief An abstraction of a connection to an IRC server -*/ - -#include "kvi_settings.h" -#include "KviQString.h" -#include "KviPointerList.h" -#include "KviTimeUtils.h" - -#include -#include - -class QTimer; -class QTextCodec; -class KviConsole; -class KviIrcNetworkData; -class KviIrcServer; -class KviProxy; -class KviIrcSocket; -class KviIrcLink; -class KviDataBuffer; -class KviIrcContext; -class KviFrame; -class KviChannel; -class KviQuery; -class KviIrcConnectionTarget; -class KviIrcUserDataBase; -class KviIrcConnectionUserInfo; -class KviIrcConnectionServerInfo; -class KviIrcConnectionStateData; -class KviIrcConnectionAntiCtcpFloodData; -class KviIrcConnectionNetsplitDetectorData; -class KviIrcConnectionAsyncWhoisData; -class KviIrcConnectionStatistics; -class KviRequestQueue; -class KviLagMeter; -class KviNotifyListManager; -class KviDnsResolver; -class KviUserIdentity; -class KviIdentityProfileSet; -class KviCString; - - -/** -* \class KviIrcConnection -* \brief An abstraction of a connection to an IRC server -* -* This class deals with the high-level logic of a connection to an IRC server. -* It's always attached to a KviIrcContext and thus to a KviConsole window. -* The connection has a KviIrcConnectionTarget object which specifies the -* data of the server that needs to be contacted and a KviUserIdentity object -* which specifies the user data to use. -* -* The connection is the upper layer of the KVIrc networking stack. It owns -* KviIrcLink which is the layer immediately below and which in turn contains -* a KviIrcSocket. -* -* The connection creates and manages a lot of objects that handle -* runtime information. These objects include a KviIrcConnectionUserInfo which -* contains the ACTUAL user information, KviIrcConnectionServerInfo which -* contains the ACTUAL server information, KviIrcUserDataBase which is -* substantially a big hash table containing all the users visible to KVIrc in -* this connection, a list of channels, a list of queries etc... -*/ -class KVIRC_API KviIrcConnection : public QObject -{ - friend class KviConsole; - friend class KviIrcContext; - friend class KviIrcLink; - friend class KviIrcServerParser; - Q_OBJECT -protected: - /** - * \brief Creates a KviIrcConnection object. - * - * This is actually used only by KviConsole. - * - * pContext must not be NULL and is kept as shallow pointer (that is, it's - * not owned and must persists for the entire life of KviIrcConnection: - * caller is responsable for that). - * - * pTarget must not be NULL and must be allocated with new as this class - * takes the ownership. - * - * pIdentity must not be NULL and must be allocated with new as this class - * takes the ownership. - * \param pContext The KviIrcContext we're attacched to - * \param pTarget The server data - * \param pIdentity User information to use in ths connection - * \return KviIrcConnection - */ - KviIrcConnection(KviIrcContext * pContext,KviIrcConnectionTarget * pTarget,KviUserIdentity * pIdentity); - - /** - * \brief Destroys a KviIrcConnection object. KviConsole uses this. - */ - ~KviIrcConnection(); -public: - /** - * \enum State - * \brief The possible "high level" states of this connection. - */ - enum State - { - Idle, /**< The connection is doing nothing */ - Connecting, /**< A connection attempt is in progress */ - Connected /**< We're connected to an IRC server */ - }; -private: - KviConsole * m_pConsole; // shallow, never null - KviIrcContext * m_pContext; // shallow, never null - - State m_eState; - bool m_bIdentdAttached; - - KviIrcConnectionTarget * m_pTarget; // owned, never null - - KviIrcLink * m_pLink; // owned, never null - - // The initial information about the user we'll send out to the server - // Note that the ACTUAL user information are in m_pUserInfo instead - KviUserIdentity * m_pUserIdentity; // owned, never null - - // The ACTUAL user information - KviIrcConnectionUserInfo * m_pUserInfo; // owned, never null - // The ACTUAL server information - KviIrcConnectionServerInfo * m_pServerInfo; // owned, never null - - KviIrcConnectionStateData * m_pStateData; // owned, never null - - KviPointerList * m_pChannelList; // owned, never null, elements shallow - KviPointerList * m_pQueryList; // owned, never null, elements shallow - - KviIrcUserDataBase * m_pUserDataBase; // owned, never null - - KviNotifyListManager * m_pNotifyListManager; // owned, see restartNotifyList() - QTimer * m_pNotifyListTimer; // delayed startup timer for the notify lists - - KviLagMeter * m_pLagMeter; // owned, may be null (when not running) - - KviIrcConnectionAntiCtcpFloodData * m_pAntiCtcpFloodData; // owned, never null - KviIrcConnectionNetsplitDetectorData * m_pNetsplitDetectorData; // owned, never null - KviIrcConnectionAsyncWhoisData * m_pAsyncWhoisData; // owned, never null - - KviIrcConnectionStatistics * m_pStatistics; // owned, never null - - KviDnsResolver * m_pLocalhostDns; // FIXME: this should go to an aux structure - - QTextCodec * m_pSrvCodec; // connection codec: never null - QTextCodec * m_pTextCodec; // connection codec: never null - KviRequestQueue * m_pRequestQueue; // owned, never null -public: - /** - * \brief Returns a pointer to the owning console - * - * The pointer is never NULL - * \return KviConsole * - */ - inline KviConsole * console(){ return m_pConsole; }; - - /** - * \brief Returns a pointer to the owning KviIrcContext. - * - * The returned value is never NULL - * \return KviIrcContext * - */ - inline KviIrcContext * context(){ return m_pContext; }; - - /** - * \brief Returns the target of this connection. - * - * Please note that the target doesn't necessairly contain up-to-date data. - * You might want to look at serverInfo() instead. - * The returned pointer is never NULL. - * \return KviIrcConnectionTarget * - */ - inline KviIrcConnectionTarget * target(){ return m_pTarget; }; - - /** - * \brief Returns the underlying KviIrcLink object - * - * The returned pointer is never NULL. - * \return KviIrcLink * - */ - inline KviIrcLink * link(){ return m_pLink; }; - - /** - * \brief Returns the current state of the connection - * \return State - */ - inline State state(){ return m_eState; }; - - /** - * \brief Returns a pointer to the big connection user database. - * - * The database contains ALL the users KVIrc can "see" in this connection. - * The returned pointer is never NULL. - * \return KviIrcUserDataBase * - */ - inline KviIrcUserDataBase * userDataBase(){ return m_pUserDataBase; }; - - /** - * \brief Returns a pointer to the KviIrcConnectionUserInfo object - * - * It contains runtime information about the user. This includes the - * current nickname, username, flags and other stuff that KviUserIdentity - * actually doesn't contain (or has only "default" values for). - * The returned pointer is never NULL. - * Include "kvi_ircconnectionuserinfo.h" as the class is only - * forwarded here. - * \return KviIrcConnectionUserInfo * - */ - inline KviIrcConnectionUserInfo * userInfo(){ return m_pUserInfo; }; - - /** - * \brief Returns a pointer to the KviIrcConnectionServerInfo object - * - * It contains runtime information about the current server. This includes - * the current servername, the server capabilities and other stuff that - * KviConnectionTarget actually doesn't contain (or has only "default" - * values for). - * The returned pointer is never NULL. - * Include "kvi_ircconnectionserverinfo.h" as the class is only - * forwarded here. - * \return KviIrcConnectionServerInfo * - */ - inline KviIrcConnectionServerInfo * serverInfo(){ return m_pServerInfo; }; - - /** - * \brief Returns a pointer to the KviIrcConnectionStateData object - * - * It contains _generic_ connection state data. This includes the current - * nickname index at login time, flags that signal "micro-states" etc... - * This data *could* be part of KviIrcConnection itself but we prefer to - * keep it in a separate class in order to cleanup the implementation. - * The returned pointer is never NULL. - * Include "kvi_ircconnectionstatedata.h" as the class is only - * forwarded here. - * \return KviIrcConnectionStateData * - */ - inline KviIrcConnectionStateData * stateData(){ return m_pStateData; }; - - /** - * \brief Returns a pointer to the KviIrcConnectionAntiCtcpFloodData object - * - * It contains data private to the Anti CTCP Flood engine. Very similar - * to KviIrcConnectionStateData but dedicated to Ctcp flood. - * The returned pointer is never NULL. - * Include "kvi_ircconnectionantictcpflooddata.h" as the class is - * only forwarded here. - * \return KviIrcConnectionAntiCtcpFloodData * - */ - inline KviIrcConnectionAntiCtcpFloodData * antiCtcpFloodData() - { return m_pAntiCtcpFloodData; }; - - /** - * \brief Returns a pointer to the KviIrcConnectionNetsplitDetectorData object - * - * It contains data private to the netsplit detector engine. Very similar - * to KviIrcConnectionStateData but dedicated to netsplit detection. - * The returned pointer is never NULL. - * Include "kvi_ircconnectionnetsplitdetectordata.h" as the class is - * only forwarded here. - * \return KviIrcConnectionNetsplitDetectorData * - */ - inline KviIrcConnectionNetsplitDetectorData * netsplitDetectorData() - { return m_pNetsplitDetectorData; }; - - /** - * \brief Returns a pointer to the KviIrcConnectionAsyncWhoisData object - * - * It contains data private to the async whois engine. Very similar to - * KviIrcConnectionStateData but dedicated to async whois. - * The returned pointer is never NULL. - * Include "kvi_ircconnectionasyncwhoisdata.h" as the class is only - * forwarded here. - * \return KviIrcConnectionAsyncWhoisData * - */ - inline KviIrcConnectionAsyncWhoisData * asyncWhoisData() - { return m_pAsyncWhoisData; }; - - /** - * \brief Returns a pointer to the KviIrcConnectionStatistics object - * - * It contains runtime statistics about the connection. Very similar to - * KviIrcConnectionStateData but dedicated to statistics. - * The returned pointer is never NULL. - * Include "kvi_ircconnectionstatistics.h" as the class is only - * forwarded here. - * \return KviIrcConnectionStatistics * - */ - inline KviIrcConnectionStatistics * statistics(){ return m_pStatistics; }; - - /** - * \brief Returns a pointer to the current KviNotifyListManager. - * - * The returned pointer is NULL if notify list management is disabled for - * the current connection. - * \return KviNotifyListManager * - */ - inline KviNotifyListManager * notifyListManager() - { return m_pNotifyListManager; }; - - /** - * \brief Returns a pointer to the current KviLagMeter. - * - * The returned pointer is NULL if lag measurement is disabled for the - * current connection. - * \return KviLagMeter * - */ - inline KviLagMeter * lagMeter(){ return m_pLagMeter; }; - - /** - * \brief Returns a pointer to the current KviRequestQueue. - * \return KviRequestQueue * - */ - inline KviRequestQueue * requestQueue(){ return m_pRequestQueue; }; - - /** - * \brief Returns the list of the channels bound to the current connection. - * - * The pointer itself is never null (though the list may be empty). - * \return KviPointerList * - */ - inline KviPointerList * channelList(){ return m_pChannelList; }; - - /** - * \brief Helper that provides a shortcut for really common access to serverInfo()->networkName() - * \return const QString & - */ - const QString & currentNetworkName(); - - /** - * \brief Helper that provides a shortcut for really common access to userInfo()->nickName() - * \return const QString & - */ - const QString & currentNickName(); - - /** - * \brief Helper that provides a shortcut for really common access to userInfo()->userName() - * \return const QString & - */ - const QString & currentUserName(); - - /** - * \brief Helper that provides a shortcut for really common access to serverInfo()->name() - * \return const QString & - */ - const QString & currentServerName(); - - // - // Channel management - // - // FIXME: Delegate to a KviChannelManager - // - - /** - * \brief Finds the channel with the specified unicode name. - * - * Returns the pointer to the channel found or NULL if there is no such - * channel. - * \param szName The name of the channel - * \return KviChannel * - */ - KviChannel * findChannel(const QString & szName); - - /** - * \brief Returns a list of channels bound to the current connection - * - * This is actually the list of channels that the local user has in common - * with the specified user. - * The list is returned as a comma separated string. If bAddEscapeSequences - * is true, then the string includes special escape sequences for - * KviIrcView that will make the channel names clickable. - * - * Returns the number of channels found. - * \param szNick The nickname of the user - * \param szChansBuffer The buffer where to store data - * \param bAddEscapeSequences Whether to include escape sequences - * \return int - */ - int getCommonChannels(const QString & szNick, QString & szChansBuffer, bool bAddEscapeSequences = true); - - /** - * \brief Creates a new channel with the specified name. - * - * This should be called in response to a JOIN message. - * This function _assumes_ that such a channel doesn't exist yet (or if it - * exists then it's actually in DEAD state). You can assume that channel - * creation never fails: if the returned pointer is NULL then we're screwed - * anyway as virtual memory is exausted. - * \param szName The name of the channel - * \return KviChannel * - */ - KviChannel * createChannel(const QString & szName); - - /// - /// This is called by KviChannel upon creation. You shouldn't need to call it. - /// - /// FIXME: Could be made protected. - /// - void registerChannel(KviChannel *c); - - /// - /// This is called by KviChannel just before destruction. You shouldn't need to call it. - /// - /// FIXME: Could be made protected. - /// - void unregisterChannel(KviChannel *c); - - /** - * \brief Marks all the currently existing channels as DEAD - * - * They are preserved across connections. Marking a channel as dead - * actually removes the ownership of KviChannel from KviIrcConnection and - * moves it to KviIrcContext (as the contex is preserved across - * connections). - * \return void - */ - void keepChannelsOpenAfterDisconnect(); - - /** - * \brief Closes all the currently open channels not marked as dead. - * \return void - */ - void closeAllChannels(); - - /** - * \brief Closes all the currently open queries not marked as dead. - * \return void - */ - void closeAllQueries(); - - // - // Query management - // - // FIXME: Delegate to a KviQueryManager ? - // - - /** - * \brief Finds the query with the specified nick. - * - * Returns the pointer to the query found or NULL if there is no such - * query. - * \param szNick The nickname of the user - * \return KviQuery * - */ - KviQuery * findQuery(const QString & szNick); - - /** - * \brief Returns the list of the currently open queries. - * - * The returned pointer is never NULL (the list may be empty though). - * \return KviPointerList * - */ - inline KviPointerList * queryList(){ return m_pQueryList; }; - - /** - * \brief Creates a query with the specified nick as target. - * - * This function assumes that such a query doesn't exist yet (or if it - * exists it's actually marked as dead and needs to be resurrected). - * \param szNick The nickname of the user - * \return KviQuery * - */ - KviQuery * createQuery(const QString & szNick); - - /// - /// This is called by KviQuery upon creation, you shouldn't need to use it. - /// - /// FIXME: Could be made protected. - /// - void registerQuery(KviQuery *q); - - /// - /// This is called by KviQuery just before destruction, you shouldn't need to use it. - /// - /// FIXME: Could be made protected. - /// - void unregisterQuery(KviQuery *q); - - /** - * \brief Marks all the currently open queries as DEAD - * - * They are kept open after a disconnect. Marking a query as dead removes - * ownership from this class and gives it to KviIrcContext (which survives - * disconnects). - * \return void - */ - void keepQueriesOpenAfterDisconnect(); - - /** - * \brief This is the inverse of keepQueriesOpenAfterDisconnect(). - * - * It's meant to be called upon reconnection (as queries don't need a JOIN - * message to be opened). - * \return void - */ - void resurrectDeadQueries(); - - /// - /// This function actually restarts the lag meter. - /// - /// FIXME: Why ? - /// - void restartLagMeter(); - - // - // Networking stack public stuff - // - - /** - * \brief Sends the specified text on the connected link (and thus socket). - * - * This function basically works like sprintf(). Please note that you - * should send only ENCODED text to the server. This is why the accepted - * parameter is a const char *. IRC is an 8 (I'd say even 7 sometimes) bit - * protocol. - * - * Please note that you don't actually need to append a CRLF pair to your - * buffer: - * the implementation of the networking stack will do it for you. Hovewer - * you can send multiple IRC commands by separating them by CRLF pairs. - * Just take care of avoiding a CRLF after the last command you specify. - * - * Returns true on success or false if the data can't be actually - * enqueued/sent (and this usually means that there is no connection at - * the moment). Please note that it MAY happen that a send attempt on a - * correctly connected link causes the link to actually disconnect (or - * rather "discover" the fact that it's disconnected at OS level). - * \param pcBuffer The _encoded_ text data to send - * \param iBuflen The length of the data: if -1 the length is determined via strlen(). - * \return bool - */ - bool sendData(const char * pcBuffer, int iBuflen = -1); - - /** - * \brief Sends the specified text on the connected link (and thus socket). - * - * This function basically works like sprintf(). Please note that you - * should send only ENCODED text to the server. This is why the accepted - * parameter is a const char *. IRC is an 8 (I'd say even 7 sometimes) bit - * protocol. - * - * Please note that you don't actually need to append a CRLF pair to your - * buffer: - * the implementation of the networking stack will do it for you. Hovewer - * you can send multiple IRC commands by separating them by CRLF pairs. - * Just take care of avoiding a CRLF after the last command you specify. - * - * Returns true on success or false if the data can't be actually - * enqueued/sent (and this usually means that there is no connection at - * the moment). Please note that it MAY happen that a send attempt on a - * correctly connected link causes the link to actually disconnect (or - * rather "discover" the fact that it's disconnected at OS level). - * \param pcFmt The format string to be first sprintf'ed with the variadic params and then sent - * \param ... The variadic arguments (see man sprintf for an explaination) - * \return bool - * - * FIXME: change name to sendFormattedData() ? - */ - bool sendFmtData(const char * pcFmt, ...); - - /** - * Clears the underlying output queue. - * Exposed basically for /context.clearQueue - * You shouldn't need it for any other reason :) - */ - void clearOutputQueue(bool bPrivateMessagesOnly); - - /** - * \brief This function is part of the networking stack. - * - * It's called by KviIrcLink OR KviMexLinkFilter when a message is arriving - * from the server. Needs to be public because subclasses of - * KviMexLinkFilter may call it. - * \param pcMessage The message :) - * \return void - */ - void incomingMessage(const char * pcMessage); - - /** - * \brief This function is part of the networking stack. - * - * It's called by KviIrcDataStreamMonitor subclasses when they want to - * inject some message without getting it filtered again - * \param pcMessage The message :) - * \return void - */ - void incomingMessageNoFilter(const char * pcMessage); - - // - // Encoding related stuff - // - - /** - * \brief Returns a pointer to the current global codec for outbound text. - * - * This codec is a global setting and may be overridden by specific - * windows. The returned pointer may be null if things really went wrong. - * \return QTextCodec * - */ - inline QTextCodec * textCodec(){ return m_pTextCodec; }; - - /** - * \brief Returns a pointer to the current global codec for inbound data. - * - * This codec is a global setting and may be overridden by specific - * windows. The returned pointer may be null if things really went wrong. - * \return QTextCodec * - */ - inline QTextCodec * serverCodec(){ return m_pSrvCodec; }; - - /** - * \brief Sets the global encoding for this connection. - * - * This is a default value and can be overridden by specific windows. - * \param szEncoding The encoding to use - * \return void - * - * FIXME: This is quite unclear (why it forces encoding to all the windows?) - */ - void setEncoding(const QString & szEncoding); - - /** - * \brief Decodes the specified text by using the server codec. - * - * You should first attempt to decode the text by using the window codec - * (if you belong to a window). - * \param szText The text to decode - * \return QString - */ - QString decodeText(const char * szText); - - /** - * \brief Encodes the specified text by using the local text codec. - * - * You should first attempt to encode the text by using the window codec - * (if you belong to a window). - * \param szText The text to encode - * \return QByteArray - */ - QByteArray encodeText(const QString & szText); -protected: - // - // Notify list management - // - - /** - * \brief Starts the notify list in 15 seconds - * - * We have this delay to wait an eventual RPL_PROTOCTL from the server - * telling us that the WATCH notify list method is supported - * \return void - */ - void delayedStartNotifyList(); - - // - // Login operations - // - - /** - * \brief Resolves the localhost into an IP address - * \return void - */ - void resolveLocalHost(); - -#ifdef COMPILE_SSL_SUPPORT - void trySTARTTLS(); - void enableStartTlsSupport(bool bEnable); -#endif - - /** - * \brief Uses the profiles' data as connection data - * - * It checks if the identity profiles are enabled and updates the data - * of the connection if a profile rule matches the network name - * \param pSet The instance of the network identity profile set - * \param szNetwork The name of the network - * \return void - */ - void useProfileData(KviIdentityProfileSet * pSet, const QString & szNetwork); - - /** - * Sets the specified real name in the user information set after - * evaluating it via KVS engine (so identifiers are substituted). - * Call this function instead of m_pUserInfo->setRealName(). - */ - void useRealName(const QString &szRealName); - - /** - * \brief Logins to the irc server - * \return void - */ - void loginToIrcServer(); - - // - // KviIrcServerParser interface - // - - /** - * \brief Called to start the notify lists when RPL_ENDOFMOTD is received - * \return void - */ - void endOfMotdReceived(); - - /** - * \brief Called when RPL_SERVINFO (004) is received and sets the info - * \param szServerName The name of the server - * \param szUserModes The user modes supported by the server - * \param szChanModes The chan modes supported by the server - * \return void - */ - void serverInfoReceived(const QString & szServerName, const QString & szUserModes, const QString & szChanModes); - - /** - * \brief Called when AUTHENTICATE answer is received - * \return void - */ - void handleAuthenticate(KviCString & szResponse); - - /** - * \brief Called when CAP LS answer is received - * \return void - */ - void handleInitialCapLs(); - - /** - * \brief Called when CAP LS negotiation fails - * \return void - */ - void handleFailedInitialCapLs(); - - /** - * \brief Called when CAP ACK answer is received - * \return void - */ - void handleInitialCapAck(); - - /** - * \brief Called when CAP NAK answer is received - * \return void - */ - void handleInitialCapNak(); - - /** - * \brief Called when we want to end CAP negotiation and go on wi the login - * \return void - */ - void endInitialCapNegotiation(); - - /** - * \brief Called to update the away state - * \param bAway Whether we enter the away mode - * \return void - */ - void changeAwayState(bool bAway); - - /** - * \brief Called on each JOIN and sets the info - * - * It's called meaningful almost only on the first time - * \param szUserName The username - * \param szHostName The hostname - * \return void - * FIXME: call it also on other messages ? - */ - void userInfoReceived(const QString & szUserName, const QString & szHostName); - - /** - * \brief Called when NICK is received - * \param szNewNick The new nickname for the user - * \return void - */ - void nickChange(const QString & szNewNick); - - /** - * \brief Called when MODE is received for each mode character - * \param cMode The mode flag :) - * \param bSet Whether to set the mode - * \return bool - */ - bool changeUserMode(char cMode, bool bSet); - - /** - * \brief Called on the first numeric received from server - * \param szNickName The nickname to use - * \return void - */ - void loginComplete(const QString & szNickName); - - // - // KviIrcContext interface - // - - /** - * \brief This starts an asynchronous connection attempt - * - * You must return control to the Qt core for the connection operations to - * be initiated - * \return void - */ - void start(); - - /** - * \brief Kills any running connection or attempt - * \return void - */ - void abort(); - - /** - * \brief Called once in a while (every 5 secs at the moment) - * \param tNow The current time - * \return void - */ - void heartbeat(kvi_time_t tNow); - - // - // KviIrcLink interface (down) - // - - /** - * \brief This signals that the connection attempt has failed - * \param iError The error code - * \return void - */ - void linkAttemptFailed(int iError); - - /** - * \brief Called by KviIrcLink when the socket state changes to Connected - * \return void - */ - void linkEstabilished(); - - /** - * \brief Called by KviIrcLink when the socket state changes to Ready - * \return void - */ - void linkTerminated(); -private: - /** - * \brief Setups the codec for the text - * \return void - */ - void setupTextCodec(); - - /** - * \brief Setups the codec for the server - * \return void - */ - void setupSrvCodec(); -public slots: - /** - * \brief Called when we unhighlight all channels - * \return void - */ - void unhighlightAllChannels(); - - /** - * \brief Called when we unhighlight all queries - * \return void - */ - void unhighlightAllQueries(); - - /** - * \brief Called to restart the notify list - * \return void - */ - void restartNotifyList(); -private slots: - /** - * \brief Called when the hostname lookup is finished - * \return void - */ - void hostNameLookupTerminated(KviDnsResolver * pDns); -signals: - /** - * \brief Emitted when the away state changes - * \return void - */ - void awayStateChanged(); - - /** - * \brief Emitted when the user modes change - * \return void - */ - void userModeChanged(); - - /** - * \brief Emitted when the nickname changes - * \return void - */ - void nickNameChanged(); - - /** - * \brief Emitted when we register a channel - * \param pChan The channel :) - * \return void - */ - void channelRegistered(KviChannel * pChan); - - /** - * \brief Emitted when we unregister a channel - * \param pChan The channel :) - * \return void - */ - void channelUnregistered(KviChannel * pChan); - - /** - * \brief Emitted when the channels list change - * \return void - */ - void chanListChanged(); -}; - - -// TODO: KviIdentity - -#endif //_KVI_IRCCONNECTION_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectionantictcpflooddata.cpp b/src/kvirc/kernel/kvi_ircconnectionantictcpflooddata.cpp deleted file mode 100644 index b71d97b65..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionantictcpflooddata.cpp +++ /dev/null @@ -1,38 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectionantictcpflooddata.cpp -// Creation date : Sat 26 Jun 2004 18:09:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnectionantictcpflooddata.h" - -KviIrcConnectionAntiCtcpFloodData::KviIrcConnectionAntiCtcpFloodData() -{ - m_tLastCtcp = 0; - m_uCtcpCount = 0; -} - -KviIrcConnectionAntiCtcpFloodData::~KviIrcConnectionAntiCtcpFloodData() -{ -} - diff --git a/src/kvirc/kernel/kvi_ircconnectionantictcpflooddata.h b/src/kvirc/kernel/kvi_ircconnectionantictcpflooddata.h deleted file mode 100644 index 7a54e7d7d..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionantictcpflooddata.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONANTICTCPFLOODDATA_H_ -#define _KVI_IRCCONNECTIONANTICTCPFLOODDATA_H_ -//============================================================================= -// -// File : kvi_ircconnectionantictcpflooddata.h -// Creation date : Sat 26 Jun 2004 18:09:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviTimeUtils.h" - -class KVIRC_API KviIrcConnectionAntiCtcpFloodData -{ -public: - KviIrcConnectionAntiCtcpFloodData(); - ~KviIrcConnectionAntiCtcpFloodData(); -protected: - // ctcp antiflood mechanism - kvi_time_t m_tLastCtcp; // the time we have received the last "may flood" ctcp request - unsigned int m_uCtcpCount; // the ctcp counter for the antiflooder -public: - kvi_time_t lastCtcpTime(){ return m_tLastCtcp; }; - unsigned int ctcpCount(){ return m_uCtcpCount; }; - void setLastCtcpTime(kvi_time_t tLastCtcp){ m_tLastCtcp = tLastCtcp; }; - void increaseCtcpCount(){ m_uCtcpCount++; }; - void setCtcpCount(unsigned int uCtcpCount){ m_uCtcpCount = uCtcpCount; }; -}; - - -#endif //!_KVI_IRCCONNECTIONANTICTCPFLOODDATA_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectionasynctemplatedata.h b/src/kvirc/kernel/kvi_ircconnectionasynctemplatedata.h deleted file mode 100644 index 83985ad98..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionasynctemplatedata.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONASYNCTEMPLATEDATA_H_ -#define _KVI_IRCCONNECTIONASYNCTEMPLATEDATA_H_ -//============================================================================= -// -// File : kvi_ircconnectionasyncwhoisdata.h -// Creation date : Sat 26 Jun 2004 19:40:20 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 template class will be used to create some other classes for future commands -// KviIrcConnectionAsyncWhoData for creating an awho command -// KviIrcConnectionAsyncWhowasData for creating an awhowas command -// It is now also used by KviIrcConnectionAsyncWhoisData - -template -class KVIRC_API KviIrcConnectionAsyncTemplateData -{ -public: - KviIrcConnectionAsyncTemplateData() - { - m_pInfoList = 0; - } - - ~KviIrcConnectionAsyncTemplateData() - { - if(m_pInfoList)delete m_pInfoList; - } - -protected: - KviPointerList * m_pInfoList; // awhois pending stuff -public: - void add(T * i) - { - if(!m_pInfoList) - { - m_pInfoList = new KviPointerList; - m_pInfoList->setAutoDelete(true); - } - m_pInfoList->append(i); - } - - T * lookup(const QString &nick) - { - if(!m_pInfoList)return 0; - for(T * i = m_pInfoList->first();i;i = m_pInfoList->next()) - { - if(KviQString::equalCI(nick,i->szNick))return i; - } - return 0; - } - - void remove(T * i) - { - if(!m_pInfoList)return; - m_pInfoList->removeRef(i); - if(m_pInfoList->isEmpty()) - { - delete m_pInfoList; - m_pInfoList = 0; - } - } -}; - -#endif - diff --git a/src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.cpp b/src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.cpp deleted file mode 100644 index 7c3a89864..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.cpp +++ /dev/null @@ -1,42 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectionasyncwhoisdata.cpp -// Creation date : Sat 26 Jun 2004 19:40:20 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnectionasyncwhoisdata.h" -#include "kvi_kvs_script.h" - -KviAsyncWhoisInfo::KviAsyncWhoisInfo() -{ - pCallback = 0; - pMagic = 0; -} - -KviAsyncWhoisInfo::~KviAsyncWhoisInfo() -{ - if(pCallback)delete pCallback; - if(pMagic)delete pMagic; -} - - diff --git a/src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.h b/src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.h deleted file mode 100644 index 91e6b4e01..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionasyncwhoisdata.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONASYNCWHOISDATA_H_ -#define _KVI_IRCCONNECTIONASYNCWHOISDATA_H_ -//============================================================================= -// -// File : kvi_ircconnectionasyncwhoisdata.h -// Creation date : Sat 26 Jun 2004 19:40:20 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviPointerList.h" -#include "kvi_ircconnectionasynctemplatedata.h" - -class KviWindow; -class KviKvsScript; -class KviKvsVariant; - -class KVIRC_API KviAsyncWhoisInfo -{ -public: - QString szNick; - QString szUser; - QString szHost; - QString szReal; - QString szServer; - QString szIdle; - QString szSignon; - QString szChannels; - QString szAway; // The szSpecial member is renamed szAway as its sole purpose is to tell whether the user is away or not - QString szAuth; - QString szAdditional; - KviKvsScript * pCallback; - KviKvsVariant * pMagic; - KviWindow * pWindow; -public: - KviAsyncWhoisInfo(); - ~KviAsyncWhoisInfo(); -}; - - - -// KviIrcConnectionAsyncWhoisData is now recreated using a template -// I'm using inheritance as i haven't been able to use a typedef -// This line didn't build -// typedef KviIrcConnectionAsyncTemplateData KviIrcConnectionAsyncWhoisData -class KVIRC_API KviIrcConnectionAsyncWhoisData : public KviIrcConnectionAsyncTemplateData -{ -}; - -#endif //!_KVI_IRCCONNECTIONASYNCWHOISDATA_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectionnetsplitdetectordata.cpp b/src/kvirc/kernel/kvi_ircconnectionnetsplitdetectordata.cpp deleted file mode 100644 index 388b33384..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionnetsplitdetectordata.cpp +++ /dev/null @@ -1,37 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectionnetsplitdetectordata.cpp -// Creation date : Sat 26 Jun 2004 18:20:58 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnectionnetsplitdetectordata.h" - -KviIrcConnectionNetsplitDetectorData::KviIrcConnectionNetsplitDetectorData() -{ - m_tLastNetsplitOnQuit = 0; -} - -KviIrcConnectionNetsplitDetectorData::~KviIrcConnectionNetsplitDetectorData() -{ -} - diff --git a/src/kvirc/kernel/kvi_ircconnectionnetsplitdetectordata.h b/src/kvirc/kernel/kvi_ircconnectionnetsplitdetectordata.h deleted file mode 100644 index 8ac238828..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionnetsplitdetectordata.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONNETSPLITDETECTORDATA_H_ -#define _KVI_IRCCONNECTIONNETSPLITDETECTORDATA_H_ -//============================================================================= -// -// File : kvi_ircconnectionnetsplitdetectordata.h -// Creation date : Sat 26 Jun 2004 18:20:58 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviTimeUtils.h" - -class KVIRC_API KviIrcConnectionNetsplitDetectorData -{ -public: - KviIrcConnectionNetsplitDetectorData(); - ~KviIrcConnectionNetsplitDetectorData(); -protected: - QString m_szLastNetsplitOnQuitReason; - kvi_time_t m_tLastNetsplitOnQuit; -public: - const QString & lastNetsplitOnQuitReason(){ return m_szLastNetsplitOnQuitReason; }; - void setLastNetsplitOnQuitReason(const QString &szReason){ m_szLastNetsplitOnQuitReason = szReason; }; - kvi_time_t lastNetsplitOnQuitTime(){ return m_tLastNetsplitOnQuit; }; - void setLastNetsplitOnQuitTime(kvi_time_t t){ m_tLastNetsplitOnQuit = t; }; -}; - -#endif //!_KVI_IRCCONNECTIONNETSPLITDETECTORDATA_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectionrequestqueue.cpp b/src/kvirc/kernel/kvi_ircconnectionrequestqueue.cpp deleted file mode 100644 index 365f8d2c4..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionrequestqueue.cpp +++ /dev/null @@ -1,175 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectionrequestqueue.h -// Creation date : Tue 09 Feb 2010 10:24:32 by Fabio Bas -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2010 Fabio Bas -// -// 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 opinion) 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 "kvi_ircconnectionrequestqueue.h" - -#include "kvi_channel.h" -#include "kvi_options.h" -#include "kvi_lagmeter.h" -#include "kvi_ircconnectionstatedata.h" -#include "kvi_ircconnectionserverinfo.h" - -#include - -KviRequestQueue::KviRequestQueue() -{ - m_curType = Mode; - connect(&m_timer, SIGNAL(timeout()), this, SLOT(timerSlot())); -} - -KviRequestQueue::~KviRequestQueue() -{ - disconnect(&m_timer, SIGNAL(timeout()), this, SLOT(timerSlot())); -} - -void KviRequestQueue::enqueueChannel(KviChannel * pChan) -{ - if(!m_channels.contains(pChan)) - { - m_channels.enqueue(pChan); - if(!m_timer.isActive()) - { - m_timer.start(KVI_OPTION_UINT(KviOption_uintOnJoinRequestsDelay)*1000); - } - } -} - -void KviRequestQueue::dequeueChannel(KviChannel * pChan) -{ - if(m_channels.contains(pChan)) - { - m_channels.removeOne(pChan); - if(m_channels.isEmpty()) - m_timer.stop(); - } -} - -void KviRequestQueue::clearAll() -{ - m_timer.stop(); - m_channels.clear(); - m_curType = Mode; -} - -void KviRequestQueue::timerSlot() -{ - if(m_channels.isEmpty()) - { - m_timer.stop(); - } else { - KviChannel * pChan = m_channels.head(); - QByteArray encodedChan = pChan->connection()->encodeText(pChan->target()).data(); - /* The following switch will let the execution flow pass-trought if any request type - * is currently disabled (or not available on the server). Channel's "MODE" request is - * the only mandatory request. - */ - switch(m_curType) - { - case BanException: - if(pChan->serverInfo()->supportedListModes().contains('e') && - !KVI_OPTION_BOOL(KviOption_boolDisableBanExceptionListRequestOnJoin) && - !( pChan->serverInfo()->getNeedsOpToListModeseI() && - !pChan->isMeOp() - ) - ) - { - if(!pChan->connection()->sendFmtData("MODE %s e",encodedChan.data())) - clearAll(); // disconnected - else pChan->setSentListRequest('e'); - m_curType = Invite; - break; - } - case Invite: - if(pChan->serverInfo()->supportedListModes().contains('I') && - !KVI_OPTION_BOOL(KviOption_boolDisableInviteListRequestOnJoin) && - !( pChan->serverInfo()->getNeedsOpToListModeseI() && - !pChan->isMeOp() - ) - ) - { - if(!pChan->connection()->sendFmtData("MODE %s I",encodedChan.data())) - clearAll(); // disconnected - else pChan->setSentListRequest('I'); - m_curType = QuietBan; - break; - } - case QuietBan: - if(pChan->serverInfo()->supportedListModes().contains('q') && - !KVI_OPTION_BOOL(KviOption_boolDisableQuietBanListRequestOnJoin)) - { - if(!pChan->connection()->sendFmtData("MODE %s q",encodedChan.data())) - clearAll(); // disconnected - else pChan->setSentListRequest('q'); - m_curType = Who; - break; - } - case Who: - if(!KVI_OPTION_BOOL(KviOption_boolDisableWhoRequestOnJoin)) - { - pChan->connection()->stateData()->setLastSentChannelWhoRequest(kvi_unixTime()); - if(pChan->connection()->lagMeter()) - { - KviCString tmp; - tmp.sprintf("WHO %s",encodedChan.data()); - pChan->connection()->lagMeter()->lagCheckRegister(tmp.ptr(),60); - } - if(!pChan->connection()->sendFmtData("WHO %s",encodedChan.data())) - clearAll(); // disconnected - else pChan->setSentWhoRequest(); - m_curType = Ban; - break; - } - case Ban: - if(!KVI_OPTION_BOOL(KviOption_boolDisableBanListRequestOnJoin)) - { - if(!pChan->connection()->sendFmtData("MODE %s b",encodedChan.data())) - clearAll(); // disconnected - else pChan->setSentListRequest('b'); - m_channels.dequeue(); - m_curType = Mode; - break; - } - default: - // we're at the end of the list - m_channels.dequeue(); - pChan->checkChannelSync(); - m_curType = Mode; - if(m_channels.isEmpty()) - { - m_timer.stop(); - return; - } - pChan = m_channels.head(); - encodedChan = pChan->connection()->encodeText(pChan->target()); - case Mode: - if(!pChan->connection()->sendFmtData("MODE %s",encodedChan.data())) - { - clearAll(); // disconnected - break; - } - m_curType = BanException; - break; - } - } -} \ No newline at end of file diff --git a/src/kvirc/kernel/kvi_ircconnectionrequestqueue.h b/src/kvirc/kernel/kvi_ircconnectionrequestqueue.h deleted file mode 100644 index 1e4a06070..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionrequestqueue.h +++ /dev/null @@ -1,115 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONREQUESTQUEUE_H_ -#define _KVI_IRCCONNECTIONREQUESTQUEUE_H_ -//============================================================================= -// -// File : kvi_ircconnectionrequestqueue.h -// Creation date : Tue 09 Feb 2010 10:24:32 by Fabio Bas -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2010 Fabio Bas -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_ircconnectionrequestqueue.h -* \author Fabio Bas -* \brief IRC connection request queue -*/ - -#include "kvi_settings.h" - -#include -#include - -class KviChannel; - -/** -* \class KviRequestQueue -* \brief Class to enqueue commands to IRC server -* -* This class is designed to delay channel requests like MODE and WHO to avoid -* excess floods on some servers -*/ -class KVIRC_API KviRequestQueue: public QObject -{ - Q_OBJECT -public: - /** - * \brief Constructs the request queue objects - * \return KviRequestQueue - */ - KviRequestQueue(); - - /** - * \brief Destroys the request queue objects - */ - virtual ~KviRequestQueue(); -protected: - /** - * \enum RequestTypes - * - * \warning MODE %s b MUST BE THE LAST AUTOMATIC CHANNEL QUERY so we get - * RPL_ENDOFBANLIST as the last reply and we know that the channel is in sync - */ - enum RequestTypes { - Mode = 0, /**< Channel modes request */ - BanException = 1, /**< Ban exceptions request */ - Invite = 2, /**< Invites request */ - Who = 3, /**< Who request */ - QuietBan = 4, /**< Quiet ban request */ - Ban = 5 /**< Ban request */ - }; - - QQueue m_channels; - QTimer m_timer; - RequestTypes m_curType; -public: - /** - * \brief Enqueues the channel in the queue stack - * \param pChan The channel to enqueue - * \return void - */ - void enqueueChannel(KviChannel * pChan); - - /** - * \brief Removes the channel from the queue stack - * \param pChan The channel to dequeue - * \return void - */ - void dequeueChannel(KviChannel * pChan); - - /** - * \brief Checks if a channel is in the queue stack - * \param pChan The channel to check - * \return bool - */ - bool isQueued(KviChannel * pChan) { return m_channels.contains(pChan); }; - - /** - * \brief Clears the queue stack - * \return void - */ - void clearAll(); -private slots: - /** - * \brief Performs time based requests - * \return void - */ - void timerSlot(); -}; - -#endif //!_KVI_IRCCONNECTIONREQUESTQUEUE_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectionserverinfo.cpp b/src/kvirc/kernel/kvi_ircconnectionserverinfo.cpp deleted file mode 100644 index 4b30916b8..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionserverinfo.cpp +++ /dev/null @@ -1,488 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectionserverinfo.cpp -// Creation date : Tue 22 Jun 2004 03:57:32 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnectionserverinfo.h" -#include "KviLocale.h" -#include "KviMemory.h" -#include "KviIrcUserDataBase.h" - -KviIrcConnectionServerInfo::KviIrcConnectionServerInfo() -{ - // default assumptions - m_szSupportedChannelTypes = "#&!+"; - m_szSupportedModePrefixes = "@+"; - m_szSupportedModeFlags = "ov"; - m_pModePrefixTable = 0; - buildModePrefixTable(); - m_bSupportsWatchList = false; - m_bSupportsCodePages = false; - m_bSupportsCap = false; - m_iMaxTopicLen = -1; - m_iMaxModeChanges = 3; - m_szListModes = "b"; - m_szParameterModes = "k"; - m_szParameterWhenSetModes = "l"; - m_szPlainModes = "pstnmi"; - m_szSupportedChannelModes = "pstnmiklb"; - m_pServInfo = new KviBasicIrcServerInfo(this); -} - -KviIrcConnectionServerInfo::~KviIrcConnectionServerInfo() -{ - if(m_pServInfo) - delete m_pServInfo; - if(m_pModePrefixTable) - KviMemory::free(m_pModePrefixTable); -} - -void KviIrcConnectionServerInfo::addSupportedCaps(const QString &szCapList) -{ - m_bSupportsCap = true; - - QStringList lTmp = szCapList.split(' ',QString::SkipEmptyParts); - foreach(QString szCap,lTmp) - { - // cap modifiers are: - // '-' : disable a capability (should not be present in a LS message...) - // '=' : sticky (can't be disabled once enabled) - // '~' : needs ack for modification - - if(szCap.length() < 1) - continue; // shouldn't happen - - switch(szCap[0].unicode()) - { - case '-': - case '~': - case '=': - szCap.remove(0,1); - break; - default: - // ok - break; - } - - szCap = szCap.toLower(); - - if(!m_lSupportedCaps.contains(szCap)) - m_lSupportedCaps.append(szCap); - } -} - -void KviIrcConnectionServerInfo::setSupportedChannelModes(const QString &szSupportedChannelModes) -{ - QStringList szAllModes = szSupportedChannelModes.split(',', QString::KeepEmptyParts); - - if(szAllModes.count() != 4) - { - // in this situation, better not to make assumptions about which modes needs a parameter - return; - } - - m_szListModes = szAllModes.at(0); - m_szParameterModes = szAllModes.at(1); - m_szParameterWhenSetModes = szAllModes.at(2); - m_szPlainModes = szAllModes.at(3); - - m_szSupportedChannelModes = szSupportedChannelModes; -} - -void KviIrcConnectionServerInfo::setSupportedModePrefixes(const QString &szSupportedModePrefixes,const QString &szSupportedModeFlags) -{ - m_szSupportedModeFlags = szSupportedModeFlags; - m_szSupportedModePrefixes = szSupportedModePrefixes; - buildModePrefixTable(); -} - -void KviIrcConnectionServerInfo::buildModePrefixTable() -{ - if(m_pModePrefixTable) KviMemory::free(m_pModePrefixTable); - const QChar * cPrefix = KviQString::nullTerminatedArray(m_szSupportedModePrefixes); - const QChar * cFlag = KviQString::nullTerminatedArray(m_szSupportedModeFlags); - if(!cPrefix || !cFlag)return; // eh ? - - m_uPrefixes=qMin(m_szSupportedModePrefixes.length(),m_szSupportedModePrefixes.length()); - m_pModePrefixTable=(kvi_u32_t*)KviMemory::allocate(sizeof(kvi_u32_t)*3*m_uPrefixes); - - unsigned short uPrefix,uFlag; - - // Pragma: FIXME: The whole mode handling needs rethinking! - // Alexey: FIXED: rethinked:) - // Pragma: LOL :DDDD - unsigned int i=0; - while( (uPrefix = cPrefix->unicode()) && (uFlag = cFlag->unicode()) && i:)"); break; - case 'h': return __tr2qs("Half-operators");break; - case 'j': return __tr2qs("Join throttling (:)"); break; - case 'q': return __tr2qs("Channel owners"); break; - case 'r': return __tr2qs("Registered"); break; - case 'u': return __tr2qs("Auditorium: /NAMES and /WHO show only ops"); break; - case 'z': return __tr2qs("Need SSL connection to join"); break; - } - return KviBasicIrcServerInfo::getChannelModeDescription(mode); -} - - -const QString & KviIrcdSevenIrcServerInfo::getChannelModeDescription(char mode) -{ - switch(mode) - { - case 'C': return __tr2qs("Forbid channel CTCPs"); break; - case 'F': return __tr2qs("Enable forwarding"); break; - case 'L': return __tr2qs("Large ban/exempt/invex lists (staff only)"); break; - case 'M': return __tr2qs("Disallow kicking opers (staff only)"); break; - case 'P': return __tr2qs("Persistent (staff only)"); break; - case 'Q': return __tr2qs("Block forwarded users"); break; - case 'R': return __tr2qs("Only registered nicks can join"); break; - case 'S': return __tr2qs("Strip colors"); break; - case 'T': return __tr2qs("Forbid channel NOTICEs"); break; - case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; - case 'f': return __tr2qs("Forward to another channel on uninvited"); break; - case 'g': return __tr2qs("Allow anybody to invite");break; - case 'j': return __tr2qs("Join throttling (:)"); break; - case 'p': return __tr2qs("Paranoid (disable KNOCK)"); break; - case 'q': return __tr2qs("Quiet Ban Editor"); break; - case 'r': return __tr2qs("Need auth to join channel"); break; - case 'z': return __tr2qs("Reduced moderation for ops"); break; - } - return KviBasicIrcServerInfo::getChannelModeDescription(mode); -} - -const QString & KviBahamutIrcServerInfo::getChannelModeDescription(char mode) -{ - switch(mode) - { - case 'L': return __tr2qs("Channel visible in LIST"); break; - case 'M': return __tr2qs("Need auth to speak and change nick"); break; - case 'O': return __tr2qs("IRC-Op only channel"); break; - case 'R': return __tr2qs("Only registered nicks can join"); break; - case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; - case 'j': - if(m_pParent) - { - if(m_pParent->supportedPlainModes().contains('j')) - { - // Azzurra (bahamut 1.4) similar to 'R' - return __tr2qs("Only registered nicks can join"); - } - } - - // Dalnet (bahamut 1.8) - return __tr2qs("Join throttling (:)"); - break; - // azzurra (bahamuth 1.4) specific addition: - case 'S': return __tr2qs("Need SSL connection to join"); break; - case 'U': return __tr2qs("Permit foreign users without auth to JOIN"); break; - case 'd': return __tr2qs("Need op/voice to change nick"); break; - case 'h': return __tr2qs("Half-operators");break; - case 'r': return __tr2qs("Registered"); break; - case 'u': return __tr2qs("Hide QUIT and PART messages"); break; - } - return KviBasicIrcServerInfo::getChannelModeDescription(mode); -} - -const QString & KviInspIRCdIrcServerInfo::getChannelModeDescription(char mode) -{ - switch(mode) - { - case 'A': return __tr2qs("Allow anybody to invite");break; - case 'B': return __tr2qs("Block messages with too many CAPS");break; - case 'C': return __tr2qs("Forbid channel CTCPs"); break; - case 'D': return __tr2qs("Delay users join to first message"); break; - case 'F': return __tr2qs("Limit nick changes (:)"); break; - case 'G': return __tr2qs("Censor bad words"); break; - case 'J': return __tr2qs("Disable join after kick ()"); break; - case 'K': return __tr2qs("Forbid /KNOCK"); break; - case 'L': return __tr2qs("Redirect on channel full (mode +l)"); break; - case 'M': return __tr2qs("Need auth to speak and change nick"); break; - case 'N': return __tr2qs("Need auth to change nick"); break; - case 'O': return __tr2qs("IRC-Op only channel"); break; - case 'P': return __tr2qs("Persistent (staff only)"); break; - case 'Q': return __tr2qs("Disallow KICK (unless U-Line)"); break; - case 'R': return __tr2qs("Only registered nicks can join"); break; - case 'S': return __tr2qs("Strip colors"); break; - case 'T': return __tr2qs("Forbid channel NOTICEs"); break; - case 'a': return __tr2qs("Protected/admin nicks"); break; - case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; - case 'f': return __tr2qs("Kick/[*]ban on message flood ([*]:)"); break; - case 'g': return __tr2qs("Block message matching"); break; - case 'j': return __tr2qs("Join throttling (:)"); break; - case 'q': return __tr2qs("Channel owners"); break; - case 'u': return __tr2qs("Auditorium: /NAMES and /WHO show only ops"); break; - case 'y': return __tr2qs("Channel IRC op"); break; - case 'z': return __tr2qs("Need SSL connection to join"); break; - } - return KviBasicIrcServerInfo::getChannelModeDescription(mode); -} - -const QString & KviIrcdRatboxIrcServerInfo::getChannelModeDescription(char mode) -{ - switch(mode) - { - // not present of efnet, but supported by ratbox - case 'r': return __tr2qs("Only registered nicks can join"); break; - case 'S': return __tr2qs("Need SSL connection to join"); break; - } - return KviBasicIrcServerInfo::getChannelModeDescription(mode); -} - -const QString & KviSnircdIrcServerInfo::getChannelModeDescription(char mode) -{ - switch(mode) - { - case 'C': return __tr2qs("Forbid channel CTCPs"); break; - case 'D': return __tr2qs("Delay users join to first message"); break; - case 'M': return __tr2qs("Moderate non auth users"); break; - case 'N': return __tr2qs("Forbid channel NOTICEs"); break; - case 'R': return __tr2qs("Registered"); break; - case 'T': return __tr2qs("No multitarget messages"); break; - case 'd': return __tr2qs("Contains hidden users (previously +D)"); break; - case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; - case 'r': return __tr2qs("Only registered nicks can join"); break; - case 'u': return __tr2qs("Hide QUIT and PART messages"); break; - } - return KviBasicIrcServerInfo::getChannelModeDescription(mode); -} - -const QString & KviIrcuIrcServerInfo::getChannelModeDescription(char mode) -{ - switch(mode) - { - case 'D': return __tr2qs("Delay users join to first message"); break; - case 'R': return __tr2qs("Registered"); break; - case 'd': return __tr2qs("Contains hidden users (previously +D)"); break; - case 'r': return __tr2qs("Only registered nicks can join"); break; - } - return KviBasicIrcServerInfo::getChannelModeDescription(mode); -} - -const QString & KviPlexusIrcServerInfo::getChannelModeDescription(char mode) -{ - switch(mode) - { - case 'B': return __tr2qs("Bandwidth Saver"); break; - case 'M': return __tr2qs("Moderate non auth users"); break; - case 'N': return __tr2qs("Forbid channel NOTICEs"); break; - case 'O': return __tr2qs("IRC-Op only channel"); break; - case 'R': return __tr2qs("Only registered nicks can join"); break; - case 'S': return __tr2qs("Need SSL connection to join"); break; - case 'a': return __tr2qs("Protected/admin nicks"); break; - case 'c': return __tr2qs("No control codes (colors, bold, ..)"); break; - case 'h': return __tr2qs("Half-operators");break; - case 'p': return __tr2qs("Paranoia"); break; - case 'q': return __tr2qs("Channel owners"); break; - case 'z': return __tr2qs("Persistent (staff only)"); break; - } - return KviBasicIrcServerInfo::getChannelModeDescription(mode); -} diff --git a/src/kvirc/kernel/kvi_ircconnectionserverinfo.h b/src/kvirc/kernel/kvi_ircconnectionserverinfo.h deleted file mode 100644 index e61841155..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionserverinfo.h +++ /dev/null @@ -1,241 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONSERVERINFO_H_ -#define _KVI_IRCCONNECTIONSERVERINFO_H_ -//============================================================================= -// -// File : kvi_ircconnectionserverinfo.h -// Creation date : Tue 22 Jun 2004 03:57:32 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "kvi_inttypes.h" - -#include - -class KviIrcConnectionServerInfo; - -class KVIRC_API KviBasicIrcServerInfo -{ - //ircnet -protected: - QString m_szServerVersion; - KviIrcConnectionServerInfo * m_pParent; -public: - KviBasicIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty); - virtual ~KviBasicIrcServerInfo(); -public: - virtual const QString & getChannelModeDescription(char mode); - virtual const QString & getUserModeDescription(QChar mode); - virtual char getRegisterModeChar() { return 0; }; - virtual const char * getSoftware() { return "Ircd"; }; - virtual bool getNeedsOpToListModeseI() { return false; }; -}; - -class KVIRC_API KviUnrealIrcServerInfo : public KviBasicIrcServerInfo -{ -public: - KviUnrealIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 'r'; }; - virtual const char * getSoftware() { return "Unreal"; }; - virtual bool getNeedsOpToListModeseI() { return false; }; - virtual const QString & getChannelModeDescription(char mode); -}; - -class KVIRC_API KviBahamutIrcServerInfo : public KviBasicIrcServerInfo -{ - //dalnet, azzurranet -public: - KviBahamutIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 'r'; }; - virtual const char * getSoftware() { return "Bahamut"; }; - virtual bool getNeedsOpToListModeseI() { return false; }; - virtual const QString & getChannelModeDescription(char mode); -}; - -class KVIRC_API KviHyperionIrcServerInfo : public KviBasicIrcServerInfo -{ - // legacy freenode : no longer mantained -public: - KviHyperionIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 'e'; }; - virtual const char * getSoftware() { return "Hyperion"; }; - virtual bool getNeedsOpToListModeseI() { return true; }; -}; - -class KVIRC_API KviIrcdSevenIrcServerInfo : public KviBasicIrcServerInfo -{ - //freenode -public: - KviIrcdSevenIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 0; }; - virtual const char * getSoftware() { return "Ircd-seven"; }; - virtual bool getNeedsOpToListModeseI() { return true; }; - virtual const QString & getChannelModeDescription(char mode); -}; - -class KVIRC_API KviIrcdRatboxIrcServerInfo : public KviBasicIrcServerInfo -{ - //efnet -public: - KviIrcdRatboxIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 0; }; - virtual const char * getSoftware() { return "Ircd-ratbox"; }; - virtual bool getNeedsOpToListModeseI() { return true; }; - virtual const QString & getChannelModeDescription(char mode); -}; - -class KVIRC_API KviInspIRCdIrcServerInfo : public KviBasicIrcServerInfo -{ - //chatspike -public: - KviInspIRCdIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 'r'; }; - virtual const char * getSoftware() { return "InspIRCd"; }; - virtual bool getNeedsOpToListModeseI() { return true; }; - virtual const QString & getChannelModeDescription(char mode); -}; - -class KVIRC_API KviSnircdIrcServerInfo : public KviBasicIrcServerInfo -{ - //quakenet; note: snird is an extension to ircu -public: - KviSnircdIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 0; }; - virtual const char * getSoftware() { return "Snircd"; }; - virtual bool getNeedsOpToListModeseI() { return false; }; //modes eI doesn't exists - virtual const QString & getChannelModeDescription(char mode); -}; - -class KVIRC_API KviIrcuIrcServerInfo : public KviBasicIrcServerInfo -{ - //undernet -public: - KviIrcuIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 0; }; - virtual const char * getSoftware() { return "Ircu"; }; - virtual bool getNeedsOpToListModeseI() { return true; }; - virtual const QString & getChannelModeDescription(char mode); -}; - -class KVIRC_API KviPlexusIrcServerInfo : public KviBasicIrcServerInfo -{ - //rizon; note: plexus is an extension to hybrid -public: - KviPlexusIrcServerInfo(KviIrcConnectionServerInfo * pParent = 0, const QString & version = KviQString::Empty) - :KviBasicIrcServerInfo(pParent, version) {;}; - virtual char getRegisterModeChar() { return 'r'; }; - virtual const char * getSoftware() { return "Plexus"; }; - virtual bool getNeedsOpToListModeseI() { return true; }; - virtual const QString & getChannelModeDescription(char mode); -}; - -class KVIRC_API KviIrcConnectionServerInfo -{ - friend class KviConsole; // for now - friend class KviIrcServerParser; - friend class KviIrcConnection; -protected: - KviIrcConnectionServerInfo(); - ~KviIrcConnectionServerInfo(); -private: - KviBasicIrcServerInfo * m_pServInfo; - QString m_szNetworkName; // the most actual network name (may be the one we specify or the one that the server reports) - QString m_szName; // the most actual server name (may be the one we specify or the one that the server wants to be known as) - QString m_szSupportedUserModes; // the supported user modes - QString m_szSupportedChannelModes; // the supported channel modes (all of them) - QString m_szSupportedModePrefixes; // the actually used mode prefixes @+ - kvi_u32_t * m_pModePrefixTable; // the mode prefixes above in a table - unsigned int m_uPrefixes; - QString m_szSupportedModeFlags; // the actually used mode flags ov - QString m_szSupportedChannelTypes; // the supported channel types - bool m_bSupportsWatchList; // supports the watch list ? - bool m_bSupportsCodePages; // supports the /CODEPAGE command ? - int m_iMaxTopicLen; - int m_iMaxModeChanges; - // Mode that adds or removes a nick or address to a list. Always has a parameter (eg: "b" as ban) - QString m_szListModes; - // Mode that changes a setting and always has a parameter (eg: "k" as channel key) - QString m_szParameterModes; - // Mode that changes a setting and only has a parameter when set (eg: "l" as channel limit) - QString m_szParameterWhenSetModes; - // Mode that changes a setting and never has a parameter (eg: "m" as channel moderated) - QString m_szPlainModes; - bool m_bSupportsCap; - QStringList m_lSupportedCaps; -public: - char registerModeChar() { return m_pServInfo ? m_pServInfo->getRegisterModeChar() : 0; }; - const char * software() { return m_pServInfo ? m_pServInfo->getSoftware() : 0; }; - bool getNeedsOpToListModeseI() { return m_pServInfo ? m_pServInfo->getNeedsOpToListModeseI() : false; }; - const QString & name() { return m_szName; }; - const QString & networkName() { return m_szNetworkName; }; - const QString & supportedUserModes() { return m_szSupportedUserModes; }; - const QString & supportedChannelModes() { return m_szSupportedChannelModes; }; - const QString & supportedChannelTypes() { return m_szSupportedChannelTypes; }; - const QString & supportedModePrefixes() { return m_szSupportedModePrefixes; }; - const QString & supportedModeFlags() { return m_szSupportedModeFlags; }; - const QString & supportedListModes() { return m_szListModes; }; - const QString & supportedParameterModes() { return m_szParameterModes; }; - const QString & supportedParameterWhenSetModes() { return m_szParameterWhenSetModes; }; - const QString & supportedPlainModes() { return m_szPlainModes; }; - bool supportsCap() { return m_bSupportsCap; }; - const QStringList & supportedCaps() { return m_lSupportedCaps; }; - bool supportsWatchList() { return m_bSupportsWatchList; }; - bool supportsCodePages() { return m_bSupportsCodePages; }; - - int maxTopicLen() { return m_iMaxTopicLen; }; - int maxModeChanges() { return m_iMaxModeChanges; }; - - void setServerVersion(const QString & version); - - const QString & getChannelModeDescription(char mode) { return m_pServInfo->getChannelModeDescription(mode); }; - const QString & getUserModeDescription(QChar mode) { return m_pServInfo->getUserModeDescription(mode); }; - - bool isSupportedModePrefix(QChar c); - bool isSupportedModeFlag(QChar c); - QChar modePrefixChar(kvi_u32_t flag); - QChar modeFlagChar(kvi_u32_t flag); - kvi_u32_t modeFlagFromPrefixChar(QChar c); - kvi_u32_t modeFlagFromModeChar(QChar c); -protected: - void setNetworkName(const QString &szName){ m_szNetworkName = szName; }; - void setName(const QString &szName) { m_szName = szName; }; - void setSupportedUserModes(const QString &szSupportedUserModes) { m_szSupportedUserModes = szSupportedUserModes; }; - void setSupportedChannelModes(const QString &szSupportedChannelModes); - void setSupportedModePrefixes(const QString &szSupportedModePrefixes,const QString &szSupportedModeFlags); - void setSupportedChannelTypes(const QString &szSupportedChannelTypes) { m_szSupportedChannelTypes = szSupportedChannelTypes; }; - void setSupportsWatchList(bool bSupportsWatchList) { m_bSupportsWatchList = bSupportsWatchList; }; - void setSupportsCodePages(bool bSupportsCodePages) { m_bSupportsCodePages = bSupportsCodePages; }; - void addSupportedCaps(const QString &szCapList); - void setMaxTopicLen(int iTopLen) { m_iMaxTopicLen=iTopLen; }; - void setMaxModeChanges(int iModes) { m_iMaxModeChanges=iModes; }; -private: - void buildModePrefixTable(); -}; - -#endif //!_KVI_IRCCONNECTIONSERVERINFO_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectionstatedata.cpp b/src/kvirc/kernel/kvi_ircconnectionstatedata.cpp deleted file mode 100644 index 23a172298..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionstatedata.cpp +++ /dev/null @@ -1,91 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectionstatedata.cpp -// Creation date : Sat 26 Jun 2004 09:31:52 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnectionstatedata.h" - -KviIrcConnectionStateData::KviIrcConnectionStateData() -{ - m_bSentStartTls = false; - m_bSentQuit = false; - m_bInsideInitialCapLs = false; - m_bInsideInitialCapReq = false; - m_bIgnoreOneYouHaveNotRegisteredError = false; - m_uLoginNickIndex = 0; - m_bSimulateUnexpectedDisconnect = false; - m_tLastReceivedChannelWhoReply = kvi_unixTime(); - m_tLastSentChannelWhoRequest = m_tLastReceivedChannelWhoReply; - m_tLastReceivedWhoisReply = 0; - m_bIdentifyMsgCapabilityEnabled = false; -} - -KviIrcConnectionStateData::~KviIrcConnectionStateData() -{ -} - -void KviIrcConnectionStateData::changeEnabledCapList(const QString &szCapList) -{ - QStringList lTmp = szCapList.split(' ',QString::SkipEmptyParts); - foreach(QString szCap,lTmp) - { - // cap modifiers are: - // '-' : disable a capability (should not be present in a LS message...) - // '=' : sticky (can't be disabled once enabled) - // '~' : needs ack for modification - - if(szCap.length() < 1) - continue; // shouldn't happen - - bool bRemove = false; - - switch(szCap[0].unicode()) - { - case '-': - bRemove = true; - // fall through - case '~': - case '=': - szCap.remove(0,1); - break; - default: - // ok - break; - } - - szCap = szCap.toLower(); - - if(szCap == "identify-msg") - m_bIdentifyMsgCapabilityEnabled = !bRemove; - - if(bRemove) - { - m_lEnabledCaps.removeAll(szCap); - } else { - if(!m_lEnabledCaps.contains(szCap)) - m_lEnabledCaps.append(szCap); - } - } -} - diff --git a/src/kvirc/kernel/kvi_ircconnectionstatedata.h b/src/kvirc/kernel/kvi_ircconnectionstatedata.h deleted file mode 100644 index 3a8f6507a..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionstatedata.h +++ /dev/null @@ -1,109 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONSTATEDATA_H_ -#define _KVI_IRCCONNECTIONSTATEDATA_H_ -//============================================================================= -// -// File : kvi_ircconnectionstatedata.h -// Creation date : Sat 26 Jun 2004 09:31:52 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviTimeUtils.h" -#include "KviQString.h" - -#include - -// -// This class is used as container for miscelaneous connection state variables -// that do not have a class for their own. -// If you need to add some "minor" variable to the connection state then -// this is the right place for it. -// - -class KVIRC_API KviIrcConnectionStateData -{ - friend class KviIrcConnection; - friend class KviIrcServerParser; - friend class KviUserParser; -public: - KviIrcConnectionStateData(); - ~KviIrcConnectionStateData(); -protected: - bool m_bInsideInitialCapLs; // true if there's a CAP LS request pending - bool m_bIgnoreOneYouHaveNotRegisteredError; // true if we have sent a CAP LS request followed by a PING which will generate an error (and we need to ignore it) - bool m_bInsideInitialCapReq; // true if there's a CAP REQ request pending - bool m_bInsideAuthenticate; // true if there's a AUTHENTICATE request pending - bool m_bSentStartTls; // the state of STARTTLS protocol - bool m_bSentQuit; // have we sent the quit message for this connection ? - unsigned int m_uLoginNickIndex; // the index of the identity nicknames used until now (see KviIrcConnection::loginToIrcServer()) - QString m_szCommandToExecAfterConnect; // yes.. this is a special command to execute after connection - bool m_bSimulateUnexpectedDisconnect; // this is set to true if we have to simulate an unexpected disconnect even if we have sent a normal quit message - kvi_time_t m_tLastReceivedChannelWhoReply; // the time that we have received our last channel who reply - kvi_time_t m_tLastSentChannelWhoRequest; // the time that we have sent our last channel who request - kvi_time_t m_tLastReceivedWhoisReply; // the time that we have received the last whois reply, reset to 0 when we receive an /END OF WHOIS - QStringList m_lEnabledCaps; // the CAPs currently enabled - bool m_bIdentifyMsgCapabilityEnabled; // do we have the msg-identity CAP enabled ? -public: - const QStringList & enabledCaps(){ return m_lEnabledCaps; }; - void changeEnabledCapList(const QString &szCapList); - - bool identifyMsgCapabilityEnabled() const - { return m_bIdentifyMsgCapabilityEnabled; }; - - bool sentStartTls(){ return m_bSentStartTls; }; - void setSentStartTls(){ m_bSentStartTls = true; }; - - bool isInsideAuthenticate(){ return m_bInsideAuthenticate; }; - void setInsideAuthenticate(bool bInside){ m_bInsideAuthenticate = bInside; }; - - bool isInsideInitialCapLs(){ return m_bInsideInitialCapLs; }; - void setInsideInitialCapLs(bool bInside){ m_bInsideInitialCapLs = bInside; }; - - void setIgnoreOneYouHaveNotRegisteredError(bool bIgnore) - { m_bIgnoreOneYouHaveNotRegisteredError = bIgnore; }; - bool ignoreOneYouHaveNotRegisteredError() const - { return m_bIgnoreOneYouHaveNotRegisteredError; }; - - bool isInsideInitialCapReq(){ return m_bInsideInitialCapReq; }; - void setInsideInitialCapReq(bool bInside){ m_bInsideInitialCapReq = bInside; }; - - bool sentQuit(){ return m_bSentQuit; }; - void setSentQuit(){ m_bSentQuit = true; }; - - kvi_time_t lastReceivedChannelWhoReply(){ return m_tLastReceivedChannelWhoReply; }; - void setLastReceivedChannelWhoReply(kvi_time_t tTime){ m_tLastReceivedChannelWhoReply = tTime; }; - - kvi_time_t lastSentChannelWhoRequest(){ return m_tLastSentChannelWhoRequest; }; - void setLastSentChannelWhoRequest(kvi_time_t tTime){ m_tLastSentChannelWhoRequest = tTime; }; - - kvi_time_t lastReceivedWhoisReply(){ return m_tLastReceivedWhoisReply; }; - void setLastReceivedWhoisReply(kvi_time_t tTime){ m_tLastReceivedWhoisReply = tTime; }; - - bool simulateUnexpectedDisconnect(){ return m_bSimulateUnexpectedDisconnect; }; - void setSimulateUnexpectedDisconnect(bool bSimulate){ m_bSimulateUnexpectedDisconnect = bSimulate; }; - - unsigned int loginNickIndex(){ return m_uLoginNickIndex; }; - void setLoginNickIndex(unsigned int uNickIdx){ m_uLoginNickIndex = uNickIdx; }; - - const QString & commandToExecAfterConnect(){ return m_szCommandToExecAfterConnect; }; - void setCommandToExecAfterConnect(const QString &szCmd){ m_szCommandToExecAfterConnect = szCmd; }; -}; - -#endif //!_KVI_IRCCONNECTIONSTATEDATA_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectionstatistics.cpp b/src/kvirc/kernel/kvi_ircconnectionstatistics.cpp deleted file mode 100644 index d3d2bc94f..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionstatistics.cpp +++ /dev/null @@ -1,38 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectionstatistics.cpp -// Creation date : Sun 27 Jun 2004 21:13:48 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnectionstatistics.h" - -KviIrcConnectionStatistics::KviIrcConnectionStatistics() -{ - m_tConnectionStart = 0; - m_tLastMessage = 0; -} - -KviIrcConnectionStatistics::~KviIrcConnectionStatistics() -{ -} - diff --git a/src/kvirc/kernel/kvi_ircconnectionstatistics.h b/src/kvirc/kernel/kvi_ircconnectionstatistics.h deleted file mode 100644 index dad53abe2..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionstatistics.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONSTATISTICS_H_ -#define _KVI_IRCCONNECTIONSTATISTICS_H_ -//============================================================================= -// -// File : kvi_ircconnectionstatistics.h -// Creation date : Sun 27 Jun 2004 21:13:48 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviTimeUtils.h" - - -class KVIRC_API KviIrcConnectionStatistics -{ - friend class KviConsole; // to be removed - friend class KviIrcConnection; -public: - KviIrcConnectionStatistics(); - ~KviIrcConnectionStatistics(); -protected: - kvi_time_t m_tConnectionStart; // (valid only when Connected or LoggingIn) - kvi_time_t m_tLastMessage; // last message received from server -public: - kvi_time_t connectionStartTime(){ return m_tConnectionStart; }; - kvi_time_t lastMessageTime(){ return m_tLastMessage; }; -protected: - void setLastMessageTime(kvi_time_t t){ m_tLastMessage = t; }; - void setConnectionStartTime(kvi_time_t t){ m_tConnectionStart = t; }; -}; - -#endif //!_KVI_IRCCONNECTIONSTATISTICS_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectiontarget.cpp b/src/kvirc/kernel/kvi_ircconnectiontarget.cpp deleted file mode 100644 index 344ba1b37..000000000 --- a/src/kvirc/kernel/kvi_ircconnectiontarget.cpp +++ /dev/null @@ -1,72 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectiontarget.cpp -// Creation date : Tue 08 Jun 2004 14:11:59 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnectiontarget.h" -#include "KviIrcServer.h" -#include "KviIrcNetwork.h" -#include "KviProxyDataBase.h" - -KviIrcConnectionTarget::KviIrcConnectionTarget( - const KviIrcNetwork * pNetwork, - const KviIrcServer * pServer, - const KviProxy * pProxy, - const QString &szBindAddress - ) -{ - m_pNetwork = new KviIrcNetwork(*pNetwork); - m_pServer = new KviIrcServer(*pServer); - m_pProxy = pProxy ? new KviProxy(*pProxy) : NULL; - m_szBindAddress = szBindAddress; -} - -KviIrcConnectionTarget::~KviIrcConnectionTarget() -{ - delete m_pNetwork; - delete m_pServer; - if(m_pProxy) - delete m_pProxy; -} - -#if 0 -const QString & KviIrcConnectionTarget::networkName() -{ - return m_pNetwork->name(); -} - -void KviIrcConnectionTarget::setNetworkName(const QString &szNetName) -{ - m_pNetwork->setName(szNetName); -} -#endif - - -void KviIrcConnectionTarget::clearProxy() -{ - if(!m_pProxy)return; - delete m_pProxy; - m_pProxy = 0; -} - diff --git a/src/kvirc/kernel/kvi_ircconnectiontarget.h b/src/kvirc/kernel/kvi_ircconnectiontarget.h deleted file mode 100644 index bc9b537b0..000000000 --- a/src/kvirc/kernel/kvi_ircconnectiontarget.h +++ /dev/null @@ -1,100 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONTARGET_H_ -#define _KVI_IRCCONNECTIONTARGET_H_ -//============================================================================= -// -// File : kvi_ircconnectiontarget.h -// Creation date : Tue 08 Jun 2004 14:11:59 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviHeapObject.h" - -class KviIrcNetwork; -class KviIrcServer; -class KviProxy; - -class KVIRC_API KviIrcConnectionTarget : public KviHeapObject -{ - friend class KviIrcConnectionTargetResolver; -public: - // pServer is a shallow pointer: this class makes a copy of it internally, must NOT be null - // pProxy may be null if a proxy is not desired. this class makes a copy of it internally - KviIrcConnectionTarget( - const KviIrcNetwork * pNetwork, - const KviIrcServer * pServer, - const KviProxy * pProxy = 0, - const QString &szBindAddress = QString() - ); - ~KviIrcConnectionTarget(); -private: - KviIrcNetwork * m_pNetwork; // owned, never null, it's a COPY of the entry in the db - KviIrcServer * m_pServer; // owned, never null, it's a COPY of the entry in the db - KviProxy * m_pProxy; // owned, may be null, it's a COPY of the entry in the db - QString m_szBindAddress; // forced bind address - -public: - - KviIrcServer * server() - { - return m_pServer; - } - - KviIrcNetwork * network() - { - return m_pNetwork; - } - - KviProxy * proxy() - { - return m_pProxy; - } - - const QString & bindAddress() - { - return m_szBindAddress; - } - - bool hasBindAddress() - { - return (!m_szBindAddress.isEmpty()); - } - -#if 0 - const QString & networkName(); - - // this allows to force the network name: it should be used only by KviConsole - // but it's KviIrcServerParser (kvi_sp_numeric.cpp) that first - // gets the new network name... thus we make it public - // to remove one level of indirection. - void setNetworkName(const QString &szNetName); -#endif - -protected: - // this is for KviIrcConnectionTargetResolver only - void clearProxy(); - void setBindAddress(const QString &szBindAddress) - { - m_szBindAddress = szBindAddress; - } -}; - -#endif //!_KVI_IRCCONNECTIONTARGET_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectiontargetresolver.cpp b/src/kvirc/kernel/kvi_ircconnectiontargetresolver.cpp deleted file mode 100644 index 438f6d471..000000000 --- a/src/kvirc/kernel/kvi_ircconnectiontargetresolver.cpp +++ /dev/null @@ -1,583 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectiontargetresolver.cpp -// Creation date : Fri May 11 23:24:18 2002 GMT by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_ircconnectiontargetresolver.h" -#include "KviDnsResolver.h" -#include "KviLocale.h" -#include "KviIrcServerDataBase.h" -#include "KviProxyDataBase.h" -#include "KviError.h" -#include "kvi_out.h" -#include "kvi_options.h" -#include "kvi_ircsocket.h" -#include "kvi_console.h" -#include "KviNetUtils.h" -#include "kvi_internalcmd.h" -#include "kvi_frame.h" -#include "kvi_mexlinkfilter.h" -//#include "kvi_garbage.h" -#include "KviMemory.h" -#include "KviMemory.h" -#include "kvi_debug.h" -#include "kvi_ircconnection.h" -#include "kvi_ircconnectiontarget.h" -#include "kvi_ircsocket.h" -#include "KviError.h" -#include "kvi_debug.h" - -#include - -#include - -extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; -extern KVIRC_API KviProxyDataBase * g_pProxyDataBase; -//extern KVIRC_API KviGarbageCollector * g_pGarbageCollector; - - - -KviIrcConnectionTargetResolver::KviIrcConnectionTargetResolver(KviIrcConnection * pConnection) -: QObject() -{ - m_pConnection = pConnection; - m_pTarget = 0; - m_pConsole = m_pConnection->console(); - - m_pStartTimer = 0; - m_pProxyDns = 0; - m_pServerDns = 0; - - m_eState = Idle; - m_eStatus = Success; - - m_iLastError = KviError_success; -} - -KviIrcConnectionTargetResolver::~KviIrcConnectionTargetResolver() -{ - cleanup(); -} - -void KviIrcConnectionTargetResolver::cleanup() -{ - if(m_pProxyDns) - { - if(m_pProxyDns->isRunning()) - { - // deleting a running dns may block - // thus garbage-collect it and delete later - //g_pGarbageCollector->collect(m_pProxyDns); - m_pProxyDns->deleteLater(); - } else { - // can't block : just delete it - delete m_pProxyDns; - } - m_pProxyDns = 0; - } - if(m_pServerDns) - { - if(m_pServerDns->isRunning()) - { - // deleting a running dns may block - // thus garbage-collect it and delete later - //g_pGarbageCollector->collect(m_pServerDns); - m_pServerDns->deleteLater(); - } else { - // can't block : just delete it - delete m_pServerDns; - } - m_pServerDns = 0; - } - if(m_pStartTimer) - { - delete m_pStartTimer; - m_pStartTimer = 0; - } -} - -void KviIrcConnectionTargetResolver::start(KviIrcConnectionTarget * t) -{ - KVI_ASSERT(m_eState == Idle); - - m_eState = Running; - - if(m_pStartTimer) // this should never happen I guess - { - delete m_pStartTimer; - m_pStartTimer = 0; - } - m_pStartTimer = new QTimer(this); - connect(m_pStartTimer,SIGNAL(timeout()),this,SLOT(asyncStartResolve())); - - m_pTarget = t; - - m_pStartTimer->start(0); -} - -void KviIrcConnectionTargetResolver::abort() -{ - cleanup(); // do a cleanup to kill the timers and dns slaves - - if(m_eState == Terminated)return; - - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR,__tr2qs("Hostname resolution aborted")); - terminate(Error,KviError_operationAborted); -} - -void KviIrcConnectionTargetResolver::asyncStartResolve() -{ - if(m_pStartTimer) - { - delete m_pStartTimer; - m_pStartTimer = 0; - } - - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Attempting %Q to %Q (%Q) on port %u"), - m_pTarget->server()->useSSL() ? &(__tr2qs("secure connection")) : &(__tr2qs("connection")), - &(m_pTarget->server()->m_szHostname), - &(m_pTarget->network()->name()), - m_pTarget->server()->m_uPort); - - if(m_pTarget->proxy()) - { - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Attempting to 'bounce' on proxy %s on port %u (protocol %s)"), - m_pTarget->proxy()->m_szHostname.toUtf8().data(), - m_pTarget->proxy()->m_uPort, - m_pTarget->proxy()->protocolName().toUtf8().data()); - - lookupProxyHostname(); - } else { - lookupServerHostname(); - } -} - -void KviIrcConnectionTargetResolver::lookupProxyHostname() -{ - bool bValidIp; -#ifdef COMPILE_IPV6_SUPPORT - if(m_pTarget->proxy()->isIPv6()) - { - bValidIp = KviNetUtils::isValidStringIPv6(m_pTarget->proxy()->m_szIp); - } else { -#endif - bValidIp = KviNetUtils::isValidStringIp(m_pTarget->proxy()->m_szIp); -#ifdef COMPILE_IPV6_SUPPORT - } -#endif - - if(bValidIp) - { - if(!_OUTPUT_QUIET) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Using cached proxy IP address (%s)"), - m_pTarget->proxy()->m_szIp.toUtf8().data()); - if(m_pTarget->proxy()->protocol() != KviProxy::Http - && m_pTarget->proxy()->protocol() != KviProxy::Socks5) - lookupServerHostname(); - else terminate(Success,KviError_success); - } else { -#ifdef COMPILE_IPV6_SUPPORT - if(m_pTarget->proxy()->isIPv6()) - { - bValidIp = KviNetUtils::isValidStringIPv6(m_pTarget->proxy()->m_szHostname); - } else { -#endif - bValidIp = KviNetUtils::isValidStringIp(m_pTarget->proxy()->m_szHostname); -#ifdef COMPILE_IPV6_SUPPORT - } -#endif - if(bValidIp) - { - m_pTarget->proxy()->m_szIp=m_pTarget->proxy()->m_szHostname; - if(m_pTarget->proxy()->protocol() != KviProxy::Http && - m_pTarget->proxy()->protocol() != KviProxy::Socks5) - { - lookupServerHostname(); - } else { - terminate(Success,KviError_success); - } - } else { - - if(m_pProxyDns) - { - qDebug("Something weird is happening, m_pProxyDns is non-zero in lookupProxyHostname()"); - delete m_pProxyDns; - m_pProxyDns = 0; - } - - m_pProxyDns = new KviDnsResolver(); - connect(m_pProxyDns,SIGNAL(lookupDone(KviDnsResolver *)),this,SLOT(proxyLookupTerminated(KviDnsResolver *))); - - if(!m_pProxyDns->lookup(m_pTarget->proxy()->m_szHostname, - m_pTarget->proxy()->isIPv6() ? KviDnsResolver::IPv6 : KviDnsResolver::IPv4)) - { - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMWARNING, - __tr2qs("Unable to look up the IRC proxy hostname: Can't start the DNS slave")); - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMWARNING, - __tr2qs("Resuming direct server connection")); - // FIXME: #warning "Option for resuming direct connection or not ?" - delete m_pProxyDns; - m_pProxyDns = 0; - m_pTarget->clearProxy(); - lookupServerHostname(); - } else { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Looking up the proxy hostname (%s)..."), - m_pTarget->proxy()->m_szHostname.toUtf8().data()); - } - } - } -} - -void KviIrcConnectionTargetResolver::proxyLookupTerminated(KviDnsResolver *) -{ - if(m_pProxyDns->state() != KviDnsResolver::Success) - { - QString szErr = KviError::getDescription(m_pProxyDns->error()); - m_pConsole->output(KVI_OUT_SYSTEMERROR, - __tr2qs("Can't find the proxy IP address: %Q"), - &szErr); - // FIXME: #warning "Option to resume the direct connection if proxy failed ?" - m_pConsole->output(KVI_OUT_SYSTEMERROR, - __tr2qs("Resuming direct server connection")); - m_pTarget->clearProxy(); - } else { - QString szFirstIpAddress = m_pProxyDns->firstIpAddress(); - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Proxy hostname resolved to %Q"),&szFirstIpAddress); - - m_pTarget->proxy()->m_szIp = m_pProxyDns->firstIpAddress(); - g_pProxyDataBase->updateProxyIp(m_pTarget->proxy()->m_szIp.toUtf8().data(),szFirstIpAddress.toUtf8().data()); - - if(m_pProxyDns->hostnameCount() > 1) - { - QString szFirstHostname = m_pProxyDns->firstHostname(); - - for(QString * addr = m_pProxyDns->hostnameList()->next();addr;addr = m_pProxyDns->hostnameList()->next()) - { - if(!_OUTPUT_QUIET) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Proxy %Q has a nickname: %Q"),&szFirstHostname,addr); - } - } - } - - delete m_pProxyDns; - m_pProxyDns = 0; - if(m_pTarget->proxy()) - { - if(m_pTarget->proxy()->protocol() == KviProxy::Http - || m_pTarget->proxy()->protocol() == KviProxy::Socks5) - { - terminate(Success,KviError_success); - return; - } - } - lookupServerHostname(); -} - -void KviIrcConnectionTargetResolver::lookupServerHostname() -{ - bool bValidIp; - -#ifdef COMPILE_IPV6_SUPPORT - if(m_pTarget->server()->isIPv6()) - { - bValidIp = KviNetUtils::isValidStringIPv6(m_pTarget->server()->m_szIp); - } else { -#endif - bValidIp = KviNetUtils::isValidStringIp(m_pTarget->server()->m_szIp); -#ifdef COMPILE_IPV6_SUPPORT - } -#endif - - if(bValidIp && m_pTarget->server()->cacheIp()) - { - if(!_OUTPUT_QUIET) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Using cached server IP address (%s)"), - m_pTarget->server()->m_szIp.toUtf8().data()); - haveServerIp(); - } else { -#ifdef COMPILE_IPV6_SUPPORT - if(m_pTarget->server()->isIPv6()) - { - bValidIp = KviNetUtils::isValidStringIPv6(m_pTarget->server()->m_szHostname); - } else { -#endif - bValidIp = KviNetUtils::isValidStringIp(m_pTarget->server()->m_szHostname); -#ifdef COMPILE_IPV6_SUPPORT - } -#endif - if(bValidIp) - { - m_pTarget->server()->m_szIp=m_pTarget->server()->m_szHostname; - haveServerIp(); - } else { - if(m_pServerDns) - { - qDebug("Something weird is happening, m_pServerDns is non-zero in lookupServerHostname()"); - delete m_pServerDns; - m_pServerDns = 0; - } - m_pServerDns = new KviDnsResolver(); - connect(m_pServerDns,SIGNAL(lookupDone(KviDnsResolver *)),this, - SLOT(serverLookupTerminated(KviDnsResolver *))); - if(!m_pServerDns->lookup(m_pTarget->server()->m_szHostname, - m_pTarget->server()->isIPv6() ? KviDnsResolver::IPv6 : KviDnsResolver::IPv4)) - { - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR, - __tr2qs("Unable to look up the server hostname: Can't start the DNS slave")); - terminate(Error,KviError_internalError); - } else { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Looking up the server hostname (%s)..."), - m_pTarget->server()->m_szHostname.toUtf8().data()); - } - } - } -} - - -void KviIrcConnectionTargetResolver::serverLookupTerminated(KviDnsResolver *) -{ - if(m_pServerDns->state() != KviDnsResolver::Success) - { - QString szErr = KviError::getDescription(m_pServerDns->error()); - m_pConsole->output(KVI_OUT_SYSTEMERROR, - __tr2qs("Can't find the server IP address: %Q"), - &szErr); - -#ifdef COMPILE_IPV6_SUPPORT - if(!(m_pTarget->server()->isIPv6())) - { - m_pConsole->output(KVI_OUT_SYSTEMERROR, - __tr2qs("If this server is an IPv6 one, try /server -i %Q"), - &(m_pTarget->server()->m_szHostname)); - } -#endif - terminate(Error,m_pServerDns->error()); - return; - } - - QString szIpAddress; - - if(m_pServerDns->ipAddressCount() > 1) - { - if(KVI_OPTION_BOOL(KviOption_boolPickRandomIpAddressForRoundRobinServers)) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Server has %d IP addresses, picking a random one"), - m_pServerDns->ipAddressCount() - ); - - int r = ::rand() % m_pServerDns->ipAddressCount(); - szIpAddress = *(m_pServerDns->ipAddressList()->at(r)); - } else { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Server has %d IP addresses, using the first one"), - m_pServerDns->ipAddressCount() - ); - szIpAddress = m_pServerDns->firstIpAddress(); - } - } else { - szIpAddress = m_pServerDns->firstIpAddress(); - } - - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Server hostname resolved to %Q"), - &szIpAddress); - m_pTarget->server()->setIp(szIpAddress); - - QString szFirstHostname = m_pServerDns->firstHostname(); - - if(!KviQString::equalCI(m_pTarget->server()->m_szHostname,m_pServerDns->firstHostname())) - { - if(!_OUTPUT_QUIET) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Real hostname for %Q is %Q"), - &(m_pTarget->server()->m_szHostname), - &szFirstHostname); - m_pTarget->server()->m_szHostname = szFirstHostname; - } - - m_pTarget->server()->m_szIp = szIpAddress; - - if(m_pServerDns->hostnameCount() > 1) - { - for(QString * addr = m_pServerDns->hostnameList()->next();addr;addr = m_pServerDns->hostnameList()->next()) - { - if(!_OUTPUT_QUIET) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Server %Q has a nickname: %Q"), - &szFirstHostname,addr); - } - } - - delete m_pServerDns; - m_pServerDns = 0; - haveServerIp(); -} - -bool KviIrcConnectionTargetResolver::validateLocalAddress(const QString &szAddress,QString &szBuffer) -{ - // szAddress may be an ip address or an interface name -#ifdef COMPILE_IPV6_SUPPORT - if(m_pTarget->server()->isIPv6()) - { - if(KviNetUtils::isValidStringIPv6(szAddress)) - { - szBuffer = szAddress; - return true; - } - } else { -#endif - if(KviNetUtils::isValidStringIp(szAddress)) - { - szBuffer = szAddress; - return true; - } -#ifdef COMPILE_IPV6_SUPPORT - } -#endif - - // is it an interface name ? - return KviNetUtils::getInterfaceAddress(szAddress,szBuffer); -} - - -void KviIrcConnectionTargetResolver::haveServerIp() -{ - if(KVI_OPTION_BOOL(KviOption_boolUseIdentService) && !KVI_OPTION_BOOL(KviOption_boolUseIdentServiceOnlyOnConnect)) - m_pConsole->frame()->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_START); - - QString bindAddress; - - if(m_pTarget->hasBindAddress()) - { - if(!validateLocalAddress(m_pTarget->bindAddress(),bindAddress)) - { - QString szBindAddress = m_pTarget->bindAddress(); - if((szBindAddress.indexOf('.') != -1) || - (szBindAddress.indexOf(':') != -1)) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("The specified bind address (%Q) is not valid"), - &szBindAddress); - } else { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("The specified bind address (%Q) is not valid (the interface it refers to might be down)"), - &(szBindAddress)); - } - } - } else { - // the options specify a bind address ? -#ifdef COMPILE_IPV6_SUPPORT - if(m_pTarget->server()->isIPv6()) - { - if(KVI_OPTION_BOOL(KviOption_boolBindIrcIPv6ConnectionsToSpecifiedAddress)) - { - if(!KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress).isEmpty()) - { - if(!validateLocalAddress(KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress),bindAddress)) - { - // if it is not an interface name, kill it for now and let the user correct the address - if(KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress).indexOf(':') != -1) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("The system-wide IPv6 bind address (%s) is not valid"), - KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress).toUtf8().data()); - KVI_OPTION_BOOL(KviOption_boolBindIrcIPv6ConnectionsToSpecifiedAddress) = false; - } else { - // this is an interface address: might be down - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("The system-wide IPv6 bind address (%s) is not valid (the interface it refers to might be down)"), - KVI_OPTION_STRING(KviOption_stringIPv6ConnectionBindAddress).toUtf8().data()); - } - } - } else { - // empty address....kill it - KVI_OPTION_BOOL(KviOption_boolBindIrcIPv6ConnectionsToSpecifiedAddress) = false; - } - } - } else { -#endif - if(KVI_OPTION_BOOL(KviOption_boolBindIrcIPv4ConnectionsToSpecifiedAddress)) - { - if(!KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress).isEmpty()) - { - if(!validateLocalAddress(KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress),bindAddress)) - { - // if it is not an interface name, kill it for now and let the user correct the address - if(KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress).indexOf(':') != -1) - { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("The system-wide IPv4 bind address (%s) is not valid"), - KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress).toUtf8().data()); - KVI_OPTION_BOOL(KviOption_boolBindIrcIPv4ConnectionsToSpecifiedAddress) = false; - } else { - // this is an interface address: might be down - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("The system-wide IPv4 bind address (%s) is not valid (the interface it refers to might be down)"), - KVI_OPTION_STRING(KviOption_stringIPv4ConnectionBindAddress).toUtf8().data()); - } - } - } else { - // empty address....kill it - KVI_OPTION_BOOL(KviOption_boolBindIrcIPv4ConnectionsToSpecifiedAddress) = false; - } - } -#ifdef COMPILE_IPV6_SUPPORT - } -#endif - } - - m_pTarget->setBindAddress(bindAddress); - terminate(Success,KviError_success); -} - -void KviIrcConnectionTargetResolver::terminate(Status s,int iLastError) -{ - KVI_ASSERT(m_eState != Terminated); - cleanup(); // do a cleanup anyway - m_eState = Terminated; - m_eStatus = s; - m_iLastError = iLastError; - emit terminated(); -} diff --git a/src/kvirc/kernel/kvi_ircconnectiontargetresolver.h b/src/kvirc/kernel/kvi_ircconnectiontargetresolver.h deleted file mode 100644 index ee5021880..000000000 --- a/src/kvirc/kernel/kvi_ircconnectiontargetresolver.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONTARGETRESOLVER_H_ -#define _KVI_IRCCONNECTIONTARGETRESOLVER_H_ -//============================================================================= -// -// File : kvi_ircconnectiontargetresolver.h -// Creation date : Fri 11 May 2004 23:17:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" - -#include - -class KviConsole; -class KviDnsResolver; -class KviIrcConnection; -class KviIrcConnectionTarget; - -class QTimer; - -class KVIRC_API KviIrcConnectionTargetResolver : public QObject -{ - friend class KviIrcLink; // upper protocol in the stack - Q_OBJECT -protected: - KviIrcConnectionTargetResolver(KviIrcConnection * pConnection); - ~KviIrcConnectionTargetResolver(); -public: - enum Status { Success, Error }; - enum State { Idle, Running, Terminated }; -private: - KviIrcConnection * m_pConnection; // shallow, never null - KviIrcConnectionTarget * m_pTarget; // shallow, never null - KviConsole * m_pConsole; // shallow, never null - Status m_eStatus; - State m_eState; - - // Auxiliary stuff - QTimer * m_pStartTimer; // timer used to start the connection - KviDnsResolver * m_pProxyDns; // the dns object for the proxy hostnames - KviDnsResolver * m_pServerDns; // the dns object for the server hostnames - - char * m_pReadBuffer; - unsigned int m_uReadBufferLen; - unsigned int m_uReadPackets; - - int m_iLastError; -public: - void start(KviIrcConnectionTarget * t); - // valid only after the terminated() signal - Status status(){ return m_eStatus; }; - int lastError(){ return m_iLastError; }; - // causes the resolver to terminate with iLastError == KviError_operationAborted - // the terminated() signal is emitted. - void abort(); -protected slots: - void asyncStartResolve(); - void serverLookupTerminated(KviDnsResolver *); - void proxyLookupTerminated(KviDnsResolver *); -private: - void cleanup(); - void lookupProxyHostname(); - void lookupServerHostname(); - void haveServerIp(); - bool validateLocalAddress(const QString &szAddress,QString &szBuffer); - void terminate(Status s,int iLastError); -signals: - void terminated(); -}; - -#endif //!_KVI_IRCCONNECTIONTARGETRESOLVER_H_ diff --git a/src/kvirc/kernel/kvi_ircconnectionuserinfo.cpp b/src/kvirc/kernel/kvi_ircconnectionuserinfo.cpp deleted file mode 100644 index 1732225f8..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionuserinfo.cpp +++ /dev/null @@ -1,65 +0,0 @@ -//============================================================================= -// -// File : kvi_ircconnectionuserinfo.cpp -// Creation date : Sun 20 Jun 2004 01:45:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircconnectionuserinfo.h" - -KviIrcConnectionUserInfo::KviIrcConnectionUserInfo() -{ - m_bAway = false; -} - -bool KviIrcConnectionUserInfo::hasUserMode(const QChar &m) -{ - return m_szUserMode.contains(m) > 0; -} - -bool KviIrcConnectionUserInfo::addUserMode(const QChar &m) -{ - if(hasUserMode(m))return false; - m_szUserMode.append(m); - return true; -} - -bool KviIrcConnectionUserInfo::removeUserMode(const QChar &m) -{ - int idx = m_szUserMode.indexOf(m,0); - if(idx == -1)return false; - m_szUserMode.replace(m,QString("")); - return true; -} - -void KviIrcConnectionUserInfo::setAway() -{ - m_szNickBeforeAway = m_szNickName; - m_tAway = kvi_unixTime(); - m_bAway = true; -} - -void KviIrcConnectionUserInfo::setBack() -{ - m_szNickBeforeAway = ""; - m_bAway = false; -} diff --git a/src/kvirc/kernel/kvi_ircconnectionuserinfo.h b/src/kvirc/kernel/kvi_ircconnectionuserinfo.h deleted file mode 100644 index ab4a707f2..000000000 --- a/src/kvirc/kernel/kvi_ircconnectionuserinfo.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef _KVI_IRCCONNECTIONUSERINFO_H_ -#define _KVI_IRCCONNECTIONUSERINFO_H_ -//============================================================================= -// -// File : kvi_ircconnectionuserinfo.h -// Creation date : Sun 20 Jun 2004 01:45:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviTimeUtils.h" - -class KVIRC_API KviIrcConnectionUserInfo -{ - friend class KviIrcConnection; - friend class KviIrcServerParser; - friend class KviConsole; -protected: - KviIrcConnectionUserInfo(); - ~KviIrcConnectionUserInfo(){}; -private: - QString m_szRealName; // the actual real name sent from the server - QString m_szNickName; // the actual nick name acknowledged by the server - QString m_szPassword; // the password used connecting to the server - QString m_szUserMode; // the actual user mode - QString m_szUserName; // user name with ident char - QString m_szLocalHostIp; // the local host ip as found by resolveLocalHost() at connection startup - QString m_szHostName; // the local host name that the server reports - QString m_szHostIp; // the host name above resolved, if possible - QString m_szAwayReason; - bool m_bAway; // is the user away ? - kvi_time_t m_tAway; // time at that the user went away - QString m_szNickBeforeAway; // the nickname that the user had just before going away - // From bugtrack: - // On many IRC networks the host is masked or hashed, and if one also is connected through a LAN, - // it is basically impossible to initiate DCC transfers, as 192.168.0.13 or similar will be sent as IP. - // But IRC servers usually (at least in my experience) send the unmasked host in the 001 raw event - // with something like ":Welcome to the Internet Relay Chat network, nick!ident@host". I think - // it'd be a good idea to just grab the IP from that event and use it for DCC transfers by default. - QString m_szUnmaskedHostName; -public: - const QString & realName(){ return m_szRealName; }; - const QString & nickName(){ return m_szNickName; }; - const QString & userMode(){ return m_szUserMode; }; - const QString & userName(){ return m_szUserName; }; - const QString & password(){ return m_szPassword; }; - const QString & localHostIp(){ return m_szLocalHostIp; }; - const QString & hostName(){ return m_szHostName; }; - const QString & unmaskedHostName(){ return m_szUnmaskedHostName; }; - const QString & hostIp(){ return m_szHostIp; }; - const QString & awayReason() { return m_szAwayReason; }; - bool hasUserMode(const QChar & m); - bool isAway(){ return m_bAway; }; - time_t awayTime(){ return m_tAway; }; - const QString & nickNameBeforeAway(){ return m_szNickBeforeAway; }; -protected: - void setRealName(const QString &szRealName){ m_szRealName = szRealName; }; - void setNickName(const QString &szNickName){ m_szNickName = szNickName; }; - void setUserMode(const QString &szUserMode){ m_szUserMode = szUserMode; }; - void setUserName(const QString &szUserName){ m_szUserName = szUserName; }; - void setPassword(const QString &szPassword){ m_szPassword = szPassword; }; - void setHostName(const QString &szHostName){ m_szHostName = szHostName; }; - void setUnmaskedHostName(const QString &szHostName){ m_szUnmaskedHostName = szHostName; }; - void setHostIp(const QString &szHostIp){ m_szHostIp = szHostIp; }; - void setLocalHostIp(const QString &szLocalHostIp){ m_szLocalHostIp = szLocalHostIp; }; - bool addUserMode(const QChar &m); // returns false if the mode was already there - bool removeUserMode(const QChar &m); // returns fales if the mode was not there - void setAwayReason(const QString& szReazon) { m_szAwayReason=szReazon; }; - void setAway(); - void setBack(); -}; - -#endif //!_KVI_IRCCONNECTIONUSERINFO_H_ diff --git a/src/kvirc/kernel/kvi_irccontext.cpp b/src/kvirc/kernel/kvi_irccontext.cpp deleted file mode 100644 index ca69c1c1c..000000000 --- a/src/kvirc/kernel/kvi_irccontext.cpp +++ /dev/null @@ -1,926 +0,0 @@ -//============================================================================= -// -// File : kvi_irccontext.cpp -// Creation date : Sun 09 May 2004 20:37:46 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_irccontext.h" -#include "kvi_console.h" -#include "kvi_channel.h" -#include "kvi_query.h" -#include "kvi_frame.h" -#include "kvi_debug.h" -#include "kvi_sparser.h" -#include "kvi_irclink.h" -#include "kvi_ircconnection.h" -#include "kvi_ircconnectiontarget.h" -#include "kvi_asynchronousconnectiondata.h" -#include "kvi_ircconnectionstatedata.h" -#include "kvi_ircconnectionuserinfo.h" -#include "kvi_ircconnectionrequestqueue.h" -#include "kvi_irctoolbar.h" -#include "kvi_out.h" -#include "KviIrcServerDataBase.h" -#include "KviProxyDataBase.h" -#include "kvi_options.h" -#include "KviLocale.h" -#include "kvi_ircdatastreammonitor.h" -#include "KviError.h" -#include "KviThread.h" // for KviThread::msleep() -#include "kvi_app.h" -#include "kvi_kvs_eventtriggers.h" -#include "kvi_kvs_script.h" -#include "KviNetUtils.h" -#include "kvi_ircurl.h" -#include "KviUserIdentity.h" - -#define __KVI_DEBUG__ -#include "kvi_debug.h" - -#include -#include - -// the irc context identifiers start from 1 -static unsigned int g_uNextIrcContextId = 1; - -extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; -extern KVIRC_API KviProxyDataBase * g_pProxyDataBase; - - -KviIrcContext::KviIrcContext(KviConsole * pConsole) -: QObject(0) -{ - m_uId = g_uNextIrcContextId; - g_uNextIrcContextId++; - - m_pConsole = pConsole; - - m_pConnection = 0; - - m_pFrame = m_pConsole->frame(); - - m_pDeadChannels = 0; - m_pDeadQueries = 0; - m_pContextWindows = 0; - - m_pLinksWindow = 0; - m_pListWindow = 0; - - m_eState = Idle; - - m_pAsynchronousConnectionData = 0; - m_pSavedAsynchronousConnectionData = 0; - m_uConnectAttemptCount = 0; - m_pMonitorList = 0; - m_pReconnectTimer = 0; - - m_uConnectAttemptCount = 1; - - m_iHeartbeatTimerId = startTimer(5000); -} - -KviIrcContext::~KviIrcContext() -{ - killTimer(m_iHeartbeatTimerId); - - while(m_pMonitorList) - { - KviIrcDataStreamMonitor * m = m_pMonitorList->first(); - if(m)m->die(); - else { - delete m_pMonitorList; - m_pMonitorList = 0; - } - } - - if(m_pReconnectTimer)delete m_pReconnectTimer; - - if(m_pLinksWindow)m_pLinksWindow->die(); - if(m_pListWindow)m_pListWindow->die(); - - closeAllDeadChannels(); - closeAllDeadQueries(); - closeAllContextWindows(); - - destroyConnection(); - if(m_pAsynchronousConnectionData)delete m_pAsynchronousConnectionData; - if(m_pSavedAsynchronousConnectionData)delete m_pSavedAsynchronousConnectionData; -} - -void KviIrcContext::registerDataStreamMonitor(KviIrcDataStreamMonitor * m) -{ - if(!m_pMonitorList) - { - m_pMonitorList = new KviPointerList; - m_pMonitorList->setAutoDelete(false); - } - m_pMonitorList->append(m); -} - -void KviIrcContext::unregisterDataStreamMonitor(KviIrcDataStreamMonitor *m) -{ - if(!m_pMonitorList)return; - m_pMonitorList->removeRef(m); - if(m_pMonitorList->isEmpty()) - { - delete m_pMonitorList; - m_pMonitorList = 0; - } -} - -void KviIrcContext::closeAllDeadChannels() -{ - while(m_pDeadChannels) - { - KviChannel * c = m_pDeadChannels->first(); - if(c) - { - m_pFrame->closeWindow(c); - } else { - // ops.... - delete m_pDeadChannels; - m_pDeadChannels = 0; - } - } -} - -void KviIrcContext::closeAllDeadQueries() -{ - while(m_pDeadQueries) - { - KviQuery * q = m_pDeadQueries->first(); - if(q) - { - m_pFrame->closeWindow(q); - } else { - // ops.... - delete m_pDeadQueries; - m_pDeadQueries = 0; - } - } -} - -void KviIrcContext::closeAllContextWindows() -{ - while(m_pContextWindows) - { - KviWindow * w = m_pContextWindows->first(); - if(w) - { - m_pFrame->closeWindow(w); - } else { - // ops... - delete m_pContextWindows; - m_pContextWindows = 0; - } - } -} - -KviChannel * KviIrcContext::findDeadChannel(const QString &name) -{ - if(!m_pDeadChannels)return 0; - for(KviChannel * c = m_pDeadChannels->first();c;c = m_pDeadChannels->next()) - { - KVI_ASSERT(c->isDeadChan()); - if(KviQString::equalCI(name,c->windowName()))return c; - } - return 0; -} - -KviQuery * KviIrcContext::findDeadQuery(const QString &name) -{ - if(!m_pDeadQueries)return 0; - for(KviQuery * c = m_pDeadQueries->first();c;c = m_pDeadQueries->next()) - { - KVI_ASSERT(c->isDeadQuery()); - if(KviQString::equalCI(name,c->windowName()))return c; - } - return 0; -} - -KviQuery * KviIrcContext::firstDeadQuery() -{ - if(!m_pDeadQueries) - return 0; - return m_pDeadQueries->first(); -} - -KviChannel * KviIrcContext::firstDeadChannel() -{ - if(!m_pDeadChannels) - return 0; - return m_pDeadChannels->first(); -} - -void KviIrcContext::registerContextWindow(KviWindow * pWnd) -{ - if(!m_pContextWindows) - { - m_pContextWindows = new KviPointerList; - m_pContextWindows->setAutoDelete(false); - } - m_pContextWindows->append(pWnd); -} - -void KviIrcContext::registerDeadChannel(KviChannel * c) -{ - if(!m_pDeadChannels) - { - m_pDeadChannels = new KviPointerList; - m_pDeadChannels->setAutoDelete(false); - } - m_pDeadChannels->append(c); -} - -void KviIrcContext::registerDeadQuery(KviQuery * q) -{ - if(!m_pDeadQueries) - { - m_pDeadQueries = new KviPointerList; - m_pDeadQueries->setAutoDelete(false); - } - m_pDeadQueries->append(q); -} - -bool KviIrcContext::unregisterDeadChannel(KviChannel * c) -{ - // was a dead channel ? - if(!m_pDeadChannels)return false; - if(!m_pDeadChannels->removeRef(c)) - { - return false; - } - if(m_pDeadChannels->isEmpty()) - { - delete m_pDeadChannels; - m_pDeadChannels = 0; - } - return true; -} - -bool KviIrcContext::unregisterContextWindow(KviWindow * pWnd) -{ - if(!m_pContextWindows)return false; - if(!m_pContextWindows->removeRef(pWnd)) - { - return false; - } - if(m_pContextWindows->isEmpty()) - { - delete m_pContextWindows; - m_pContextWindows = 0; - } - return true; -} - -bool KviIrcContext::unregisterDeadQuery(KviQuery * q) -{ - if(!m_pDeadQueries)return false; - if(!m_pDeadQueries->removeRef(q)) - { - return false; - } - if(m_pDeadQueries->isEmpty()) - { - delete m_pDeadQueries; - m_pDeadQueries = 0; - } - return true; -} - -void KviIrcContext::createLinksWindow() -{ - if(m_pLinksWindow)return; - KviKvsScript::run("links.open",m_pConsole); -} - -void KviIrcContext::createListWindow() -{ - if(m_pListWindow)return; - KviKvsScript::run("list.open",m_pConsole); -} - -void KviIrcContext::destroyConnection() -{ - if(!m_pConnection)return; - m_pConnection->closeAllChannels(); - m_pConnection->closeAllQueries(); - - if(m_pLinksWindow)m_pLinksWindow->control(EXTERNAL_SERVER_DATA_PARSER_CONTROL_RESET); - if(m_pListWindow)m_pListWindow->control(EXTERNAL_SERVER_DATA_PARSER_CONTROL_RESET); - - m_pConsole->connectionDetached(); - - // make sure that m_pConnection is already 0 in any - // event triggered by KviIrcConnection destructor - KviIrcConnection * pTmp = m_pConnection; - m_pConnection = 0; - delete pTmp; -} - -void KviIrcContext::setState(State eState) -{ - if(m_eState == eState)return; - m_eState = eState; - - m_pFrame->childContextStateChange(this); - - emit stateChanged(); - - if(eState == KviIrcContext::Idle)destroyConnection(); - - m_pConsole->updateCaption(); -} - -void KviIrcContext::setAsynchronousConnectionData(KviAsynchronousConnectionData * d) -{ - if(m_pAsynchronousConnectionData)delete m_pAsynchronousConnectionData; - m_pAsynchronousConnectionData = d; -} - -void KviIrcContext::destroyAsynchronousConnectionData() -{ - if(!m_pAsynchronousConnectionData)return; - delete m_pAsynchronousConnectionData; - m_pAsynchronousConnectionData = 0; -} - -void KviIrcContext::loginComplete() -{ - setState(Connected); -} - -void KviIrcContext::connectButtonClicked() -{ - if(!connection()) - { - if(m_pReconnectTimer) - { - // reconnection was in progress... - delete m_pReconnectTimer; - m_pReconnectTimer = 0; - destroyAsynchronousConnectionData(); - - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR, - __tr2qs("Reconnect attempt aborted")); - - return; - } - - // No connections in progress - m_uConnectAttemptCount = 1; - connectToCurrentServer(); - } else { - // Sth is going on - terminateConnectionRequest(false); - } -} - -void KviIrcContext::connectToCurrentServer() -{ - if(m_pReconnectTimer) - { - delete m_pReconnectTimer; - m_pReconnectTimer = 0; - } - - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE," "); // spacer - - // No connection target specified. - // If we have a saved target, reuse it - if(!m_pAsynchronousConnectionData && m_pSavedAsynchronousConnectionData) - { - m_pAsynchronousConnectionData = m_pSavedAsynchronousConnectionData; - m_pSavedAsynchronousConnectionData = 0; - } - - if(m_pAsynchronousConnectionData) - { - // we have a specified connection target (either from outside or saved) - if(m_pAsynchronousConnectionData->szServer.isEmpty()) - { - // an empty server might mean "reuse the last server in context" - if( - m_pAsynchronousConnectionData->bUseLastServerInContext && - m_pSavedAsynchronousConnectionData - ) - { - // reuse the saved connection data - // the server for sure - m_pAsynchronousConnectionData->szServer = m_pSavedAsynchronousConnectionData->szServer; - m_pAsynchronousConnectionData->szServerId = m_pSavedAsynchronousConnectionData->szServerId; - m_pAsynchronousConnectionData->uPort = m_pSavedAsynchronousConnectionData->uPort; - m_pAsynchronousConnectionData->bPortIsOk = true; - m_pAsynchronousConnectionData->bUseIPv6 = m_pSavedAsynchronousConnectionData->bUseIPv6; - m_pAsynchronousConnectionData->bUseSSL = m_pSavedAsynchronousConnectionData->bUseSSL; - m_pAsynchronousConnectionData->bSTARTTLS = m_pSavedAsynchronousConnectionData->bSTARTTLS; - if(m_pSavedAsynchronousConnectionData->m_pReconnectInfo) - m_pAsynchronousConnectionData->m_pReconnectInfo = new KviIrcServerReconnectInfo(*(m_pSavedAsynchronousConnectionData->m_pReconnectInfo)); - else m_pAsynchronousConnectionData->m_pReconnectInfo = 0; - - // and the other info, only if not overridden by the user - if(m_pAsynchronousConnectionData->szBindAddress.isEmpty()) - m_pAsynchronousConnectionData->szBindAddress = m_pSavedAsynchronousConnectionData->szBindAddress; - if(m_pAsynchronousConnectionData->szCommandToExecAfterConnect.isEmpty()) - m_pAsynchronousConnectionData->szCommandToExecAfterConnect = m_pSavedAsynchronousConnectionData->szCommandToExecAfterConnect; - if(m_pAsynchronousConnectionData->szLinkFilter.isEmpty()) - m_pAsynchronousConnectionData->szLinkFilter = m_pSavedAsynchronousConnectionData->szLinkFilter; - if(m_pAsynchronousConnectionData->szPass.isEmpty()) - m_pAsynchronousConnectionData->szPass = m_pSavedAsynchronousConnectionData->szPass; - if(m_pAsynchronousConnectionData->szNick.isEmpty()) - m_pAsynchronousConnectionData->szNick = m_pSavedAsynchronousConnectionData->szNick; - if(m_pAsynchronousConnectionData->szInitUMode.isEmpty()) - m_pAsynchronousConnectionData->szInitUMode = m_pSavedAsynchronousConnectionData->szInitUMode; - } else { - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMWARNING,__tr2qs("This is the first connection in this IRC context: using the global server setting")); - } - } else { - // !m_pAsynchronousConnectionData->szServer.isEmpty() - // ok, have a server to look for in the db - // FIXME: this is a bit ugly... could it be managed in some completly different and nicer way ? - KviIrcServerDefinition d; - d.szServer = m_pAsynchronousConnectionData->szServer; - d.bPortIsValid = m_pAsynchronousConnectionData->bPortIsOk; - d.uPort = m_pAsynchronousConnectionData->uPort; - d.bIPv6 = m_pAsynchronousConnectionData->bUseIPv6; - d.bSSL = m_pAsynchronousConnectionData->bUseSSL; - d.bSTARTTLS = m_pAsynchronousConnectionData->bSTARTTLS; - d.szLinkFilter = m_pAsynchronousConnectionData->szLinkFilter; - d.szPass = m_pAsynchronousConnectionData->szPass; - d.szNick = m_pAsynchronousConnectionData->szNick; - d.szInitUMode = m_pAsynchronousConnectionData->szInitUMode; - d.szId = m_pAsynchronousConnectionData->szServerId; - QString szError; - if(!g_pServerDataBase->makeCurrentServer(&d,szError)) - { - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR,szError); - destroyAsynchronousConnectionData(); - return; - } - } // else we just connect to the globally selected irc server in the options dialog - } - - KviIrcNetwork * net = g_pServerDataBase->currentNetwork(); - KviIrcServer * srv = net ? net->currentServer() : 0; - - KviProxy * prx = 0; - - if(!srv) - { - if(g_pServerDataBase->networkCount()) - KviKvsScript::run("options.edit KviIrcServerOptionsWidget",m_pConsole); - else - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR,__tr2qs("No servers available. Check the options dialog or use the /SERVER command")); - destroyAsynchronousConnectionData(); - return; - } - - if(!net) - { - // BUG - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMERROR,__tr2qs("Ooops.. you've hit a bug in the servers database... I have found a server but not a network...")); - destroyAsynchronousConnectionData(); - return; - } - - - prx = srv->proxyServer(g_pProxyDataBase); - - if(!prx && (srv->proxy()!=-1) && KVI_OPTION_BOOL(KviOption_boolUseProxyHost)) - { - prx = g_pProxyDataBase->currentProxy(); - if(!prx) - { - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMWARNING,__tr2qs("No proxy hosts available, resuming direct connection")); - } - } - - QString szBindAddress; - - srv->m_pReconnectInfo = 0; - if(m_pAsynchronousConnectionData) - { - szBindAddress = m_pAsynchronousConnectionData->szBindAddress; - if(m_pAsynchronousConnectionData->m_pReconnectInfo) - srv->m_pReconnectInfo = new KviIrcServerReconnectInfo(*(m_pAsynchronousConnectionData->m_pReconnectInfo)); - } - - // Find out the identity we'll be using in this connection - // First check the server for one - - const KviUserIdentity * pIdentity = 0; - - QString szUserIdentityId = srv->userIdentityId(); - if(!szUserIdentityId.isEmpty()) - pIdentity = KviUserIdentityManager::instance()->findIdentity(szUserIdentityId); - - // If not found, look in the network instead - if(!pIdentity) - szUserIdentityId = net->userIdentityId(); - - if(!szUserIdentityId.isEmpty()) - pIdentity = KviUserIdentityManager::instance()->findIdentity(szUserIdentityId); - - // If not found, get the default identity (this is GRANTED to be never null, eventually filled up with defaults) - pIdentity = KviUserIdentityManager::instance()->defaultIdentity(); - - if(m_pConnection) delete m_pConnection; - m_pConnection = new KviIrcConnection( - this, - new KviIrcConnectionTarget( - net, - srv, - prx, - szBindAddress - ), - new KviUserIdentity(*pIdentity) - ); - - setState(Connecting); - - if(m_pAsynchronousConnectionData) - { - m_pConnection->stateData()->setCommandToExecAfterConnect(m_pAsynchronousConnectionData->szCommandToExecAfterConnect); - destroyAsynchronousConnectionData(); - } - - m_pConsole->connectionAttached(); - - // save stuff for later - - // FIXME: this management of "next" connection should be reviewed a bit anyway - if(m_pSavedAsynchronousConnectionData) delete m_pSavedAsynchronousConnectionData; - m_pSavedAsynchronousConnectionData = new KviAsynchronousConnectionData(); - m_pSavedAsynchronousConnectionData->szServer = srv->m_szHostname; - m_pSavedAsynchronousConnectionData->uPort = srv->port(); - m_pSavedAsynchronousConnectionData->bPortIsOk = true; - m_pSavedAsynchronousConnectionData->bUseIPv6 = srv->isIPv6(); - m_pSavedAsynchronousConnectionData->bUseSSL = srv->useSSL(); - m_pSavedAsynchronousConnectionData->bSTARTTLS = srv->enabledSTARTTLS(); - m_pSavedAsynchronousConnectionData->szPass = srv->password(); - m_pSavedAsynchronousConnectionData->szServerId = srv->id(); - m_pSavedAsynchronousConnectionData->szInitUMode = srv->m_szInitUMode; - if(srv->m_pReconnectInfo) - m_pSavedAsynchronousConnectionData->m_pReconnectInfo = new KviIrcServerReconnectInfo(*(srv->m_pReconnectInfo)); - else m_pSavedAsynchronousConnectionData->m_pReconnectInfo = 0; - - // this never fails! - m_pConnection->start(); -} - -void KviIrcContext::connectionFailed(int iError) -{ - if(!m_pConnection)return; // this may happen in the destructor! - - m_pConsole->output(KVI_OUT_SYSTEMERROR, - __tr2qs("Connection attempt failed [%s]"), - m_pConnection->target()->server()->m_szHostname.toUtf8().data()); - - // if the connection has been aborted by the user then just go idle - if(iError == KviError_operationAborted) - goto enter_idle_state; - - // FIXME: this should stop on critical errors ! - if(KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) - { - if((!KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts) || - (m_uConnectAttemptCount < KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)))) - { - m_uConnectAttemptCount++; - //FIXME: Multiply the delay by (m_uConnectAttemptCount / 2) so later connects are less frequent. - if(!_OUTPUT_MUTE) - { - QString tmp; - KviQString::sprintf(tmp,__tr2qs("Will attempt to reconnect in %d seconds"),KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); - QString num; - - if(!KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)) - KviQString::sprintf(num,__tr2qs("%d"),m_uConnectAttemptCount); - else - KviQString::sprintf(num,__tr2qs("%d of %d"), - m_uConnectAttemptCount,KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)); - tmp += " [" + num + "]"; - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,tmp); - } - - KviIrcServer oldServer(*(connection()->target()->server())); - QString oldNickname = connection()->userInfo()->isAway() ? connection()->userInfo()->nickNameBeforeAway() : connection()->userInfo()->nickName(); - - KviAsynchronousConnectionData * d = new KviAsynchronousConnectionData(); - d->szServer = oldServer.m_szHostname; - d->szServerId = oldServer.id(); - d->uPort = oldServer.port(); - d->bPortIsOk = true; - d->bUseIPv6 = oldServer.isIPv6(); - d->bUseSSL = oldServer.useSSL(); - d->bSTARTTLS = oldServer.enabledSTARTTLS(); - d->szPass = oldServer.password(); - d->szNick = oldNickname; - d->szInitUMode = oldServer.m_szInitUMode; - d->szCommandToExecAfterConnect = ""; - setAsynchronousConnectionData(d); - beginAsynchronousConnect(1000 * KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); - - setState(Idle); // destroy the actual connection - - return; - } else { - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_SYSTEMERROR,__tr2qs("Maximum number of reconnect attempts reached (%d): giving up"),KVI_OPTION_UINT(KviOption_uintMaxAutoReconnectAttempts)); - } - } - - // reset the attempt count - m_uConnectAttemptCount = 1; - - if(connection()->target()->server()->cacheIp()) - { - if((((int)iError) == KviError_connectionTimedOut) || - (((int)iError) == KviError_connectionRefused) || - (((int)iError) == KviError_networkUnreachable) || - (((int)iError) == KviError_hostUnreachable)) - { - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("The connection attempt failed while using a cached IP address for the current server")); - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("The problem *might* be caused by an updated DNS entry")); - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Try reconnecting with caching disabled")); - } - } - -enter_idle_state: - setState(Idle); -} - -void KviIrcContext::connectionEstabilished() -{ - //qDebug("context::connectionEstabilished"); - // - // The connection has been estabilished, the - // KviIrcConnection will attempt to login now - // - m_uConnectAttemptCount = 1; - - bool bStopOutput = false; - - setState(LoggingIn); // this must be set in order for $server and other functions to return the correct values - - bStopOutput = KVS_TRIGGER_EVENT_0_HALTED(KviEvent_OnIRCConnectionEstabilished,m_pConsole); - - if(!bStopOutput) - { - m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("%Q established [%s (%s:%u)]"), - connection()->link()->socket()->usingSSL() ? &(__tr2qs("Secure connection")) : &(__tr2qs("Connection")), - connection()->target()->server()->m_szHostname.toUtf8().data(), - connection()->target()->server()->m_szIp.toUtf8().data(), - connection()->target()->server()->m_uPort); - } - - // Add to recent server list (build the url of type irc[6]://: - QString url; - KviIrcUrl::join(url,connection()->target()->server()); - g_pApp->addRecentServer(url); - - // save the last server this console used - //if(m_pLastIrcServer)delete m_pLastIrcServer; - //m_pLastIrcServer = new KviIrcServer(*(connection()->server())); -} - -void KviIrcContext::connectionTerminated() -{ - if(!m_pConnection)return; // this may happen in the destructor! - - KviIrcServer oldServer(*(connection()->target()->server())); - if(oldServer.m_pReconnectInfo) - { - KviIrcServerReconnectInfo *pOldInfo = oldServer.m_pReconnectInfo; - oldServer.m_pReconnectInfo = 0; - delete pOldInfo; - } - - KviIrcServerReconnectInfo info, *pInfo(&info); - pInfo->m_szNick = connection()->userInfo()->isAway() ? connection()->userInfo()->nickNameBeforeAway() : connection()->userInfo()->nickName(); - pInfo->m_szPass = connection()->userInfo()->password(); - pInfo->m_bIsAway = connection()->userInfo()->isAway(); - pInfo->m_szAwayReason = connection()->userInfo()->awayReason(); - - connection()->requestQueue()->clearAll(); - - // we consider it unexpected when we haven't sent a QUIT message and we're connected - // or alternatively when a simulation of such a termination is requested (this is used to keep the queries open etc..) - bool bUnexpectedDisconnect = ((!(connection()->stateData()->sentQuit())) && ((m_eState == KviIrcContext::Connected) || (m_eState == KviIrcContext::Connecting))) || connection()->stateData()->simulateUnexpectedDisconnect(); - - if(bUnexpectedDisconnect) - { - if(KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) - { - if(KVI_OPTION_BOOL(KviOption_boolRejoinChannelsAfterReconnect)) - { - // FIXME: THIS SHOULD BE A KviIrcConnection FUNCTION - KviChannel * c; - QString szChannels, szProtectedChannels, szPasswords, szCurPass, szCurChan; - // first only chans without key, in groups of 4 - for(c = connection()->channelList()->first(); c; c = connection()->channelList()->next()) - { - szCurPass = c->hasChannelMode('k') ? c->channelModeParam('k') : ""; - szCurChan = c->windowName(); - if(szCurPass.isEmpty()) - { - if(!szChannels.isEmpty()) - szChannels.append(","); - szChannels.append(szCurChan); - } else { - if(!szProtectedChannels.isEmpty()) - szProtectedChannels.append(","); - szProtectedChannels.append(szCurChan); - if(!szPasswords.isEmpty()) - szPasswords.append(","); - szPasswords.append(szCurPass); - } - } - if((!szChannels.isEmpty()) || (!szProtectedChannels.isEmpty())) - { - pInfo->m_szJoinChannels.append(szProtectedChannels); - if(!szProtectedChannels.isEmpty() && !szChannels.isEmpty()) - pInfo->m_szJoinChannels.append(','); - pInfo->m_szJoinChannels.append(szChannels); - pInfo->m_szJoinChannels.append(" "); - pInfo->m_szJoinChannels.append(szPasswords); - } - } - - - if(KVI_OPTION_BOOL(KviOption_boolReopenQueriesAfterReconnect)) - { - for(KviQuery * q = connection()->queryList()->first(); q; q = connection()->queryList()->next()) - { - pInfo->m_szOpenQueryes.append(q->target()); - } - } - } - - if(KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnUnexpectedDisconnect) || KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnDisconnect)) - connection()->keepChannelsOpenAfterDisconnect(); - - if(KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnUnexpectedDisconnect) || KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnDisconnect)) - connection()->keepQueriesOpenAfterDisconnect(); - } else { - if(KVI_OPTION_BOOL(KviOption_boolKeepChannelsOpenOnDisconnect)) - connection()->keepChannelsOpenAfterDisconnect(); - - if(KVI_OPTION_BOOL(KviOption_boolKeepQueriesOpenOnDisconnect)) - connection()->keepQueriesOpenAfterDisconnect(); - } - - setState(Idle); - - bool bStopOutput = false; - - bStopOutput = KVS_TRIGGER_EVENT_0_HALTED(KviEvent_OnIRCConnectionTerminated,m_pConsole); - - if(!bStopOutput) - { - m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("Connection terminated [%s (%s:%u)]"), - oldServer.hostName().toUtf8().data(), - oldServer.ip().toUtf8().data(), - oldServer.port()); - } - - // do reconnect - - if(bUnexpectedDisconnect && KVI_OPTION_BOOL(KviOption_boolAutoReconnectOnUnexpectedDisconnect)) - { - //m_uConnectAttemptCount = 1; - if(!_OUTPUT_MUTE) - m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("The connection terminated unexpectedly. Trying to reconnect...")); - KviAsynchronousConnectionData * d = new KviAsynchronousConnectionData(); - d->szServerId = oldServer.id(); - d->szServer = oldServer.m_szHostname; - d->uPort = oldServer.port(); - d->bPortIsOk = true; - d->bUseIPv6 = oldServer.isIPv6(); - d->bUseSSL = oldServer.useSSL(); - d->bSTARTTLS = oldServer.enabledSTARTTLS(); - d->szPass = oldServer.password(); - d->szInitUMode = oldServer.m_szInitUMode; - d->m_pReconnectInfo = new KviIrcServerReconnectInfo(*(pInfo)); - setAsynchronousConnectionData(d); - - beginAsynchronousConnect(1000 * KVI_OPTION_UINT(KviOption_uintAutoReconnectDelay)); - } -} - -void KviIrcContext::beginAsynchronousConnect(unsigned int uDelayInMSecs) -{ - if(m_pReconnectTimer) delete m_pReconnectTimer; - m_pReconnectTimer = new QTimer(this); - connect(m_pReconnectTimer,SIGNAL(timeout()),this,SLOT(asynchronousConnect())); - m_pReconnectTimer->start(uDelayInMSecs); -} - -void KviIrcContext::asynchronousConnect() -{ - if(m_pReconnectTimer) - { - delete m_pReconnectTimer; - m_pReconnectTimer = 0; - } - - if(state() != Idle) // need a brutal disconnect here - terminateConnectionRequest(true,"Changing server..."); - - connectToCurrentServer(); -} - -void KviIrcContext::terminateConnectionRequest(bool bForce, const QString & szQuitMsg, bool bSimulateUnexpectedDisconnect) -{ - if(!connection())return; // hm ? - - connection()->stateData()->setSimulateUnexpectedDisconnect(bSimulateUnexpectedDisconnect); - - switch(m_eState) - { - case Connected: - { - // was connected : send a quit and abort the connection - bool bWasSentQuit = true; - if(!connection()->stateData()->sentQuit()) - { - KVS_TRIGGER_EVENT_0(KviEvent_OnDisconnectRequest,m_pConsole); - QString szQuit = szQuitMsg; - if(szQuit.isEmpty()) - szQuit = KVI_OPTION_STRING(KviOption_stringQuitMessage); - KviQString::escapeKvs(&szQuit, KviQString::PermitVariables | KviQString::PermitFunctions); - QString buffer; - KviKvsVariant ret; - if(KviKvsScript::evaluate(szQuit,console(),0,&ret)) - ret.asString(buffer); - else - buffer = szQuit; - QByteArray dat = connection()->encodeText(buffer); - bWasSentQuit = false; - connection()->stateData()->setSentQuit(); - connection()->sendFmtData("QUIT :%s",dat.data() ? dat.data() : ""); // here theoretically we COULD get disconnected - } // else it was already sent anyway - - if(KVI_OPTION_BOOL(KviOption_boolForceBrutalQuit) || bWasSentQuit || bForce) - { - if(!bWasSentQuit) - { - // idle for some milliseconds in order to allow the quit message to reach - // the remote end without breaking the connection - KviThread::msleep(100); - } - // and brutally abort the connection (if it still exists!!!) - if(connection())connection()->abort(); - } else { - if(!bWasSentQuit) - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Sent QUIT, waiting for the server to close the connection...")); - // else it was already sent anyway - } - } - break; - case Connecting: - case LoggingIn: - // was waiting for connection or login, just abort it: it will trigger an error anyway - connection()->abort(); - break; - default: - // should never end here! - KVI_ASSERT(false); - break; - } -} - -void KviIrcContext::timerEvent(QTimerEvent * e) -{ - if(e->timerId() != m_iHeartbeatTimerId) - { - QObject::timerEvent(e); - return; - } - - // our heartbeat - kvi_time_t tNow = kvi_unixTime(); - - if(m_pConnection) - m_pConnection->heartbeat(tNow); -} diff --git a/src/kvirc/kernel/kvi_irccontext.h b/src/kvirc/kernel/kvi_irccontext.h deleted file mode 100644 index 581b02d16..000000000 --- a/src/kvirc/kernel/kvi_irccontext.h +++ /dev/null @@ -1,189 +0,0 @@ -#ifndef _KVI_IRCCONTEXT_H_ -#define _KVI_IRCCONTEXT_H_ -//============================================================================= -// -// File : kvi_irccontext.h -// Creation date : Sun 09 May 2004 20:37:46 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviPointerList.h" -#include - -class KviChannel; -class KviQuery; -class KviQuery; -class KviFrame; -class KviIrcConnection; -class KviExternalServerDataParser; -class KviAsynchronousConnectionData; -class KviIrcDataStreamMonitor; -class KviWindow; -class QTimer; -class KviConsole; -class KviIrcNetwork; -class KviIrcServer; -/* - KviIrcContext is the structure that groups the objects and resources - usable for a single irc connection: a console, a set of channels and queries, - and a KviIrcConnection object. - - The objects grouped here are mostly permanent across connections. - - Each irc context has its own unique numeric identifier. The identifiers start - from 1 so 0 is an invalid irc context id (this is useful in the scripting engine). - - The irc context is created in the KviConsole constructor and destroyed - in the KviConsole destructor. No other class can allocate KviIrcContext objects. -*/ - -class KVIRC_API KviIrcContext : public QObject -{ - friend class KviConsole; - friend class KviChannel; - friend class KviQuery; - friend class KviIrcConnection; - friend class KviIrcContextToolBar; - Q_OBJECT -protected: - KviIrcContext(KviConsole * pConsole); // only KviConsole can create this -public: - ~KviIrcContext(); -public: - enum State - { - Idle, // connection() == 0 - Connecting, // connection() != 0 - LoggingIn, // connection() != 0 - Connected // connection() != 0 - }; -protected: - KviConsole * m_pConsole; // shallow, never null - KviIrcConnection * m_pConnection; - - unsigned int m_uId; // this irc context id - - State m_eState; // this context state - - // helper pointers - KviFrame * m_pFrame; // the owning frame, shallow, never null - - // permanent links and list window - KviExternalServerDataParser * m_pLinksWindow; - KviExternalServerDataParser * m_pListWindow; - - KviAsynchronousConnectionData * m_pAsynchronousConnectionData; // owned, may be null - KviAsynchronousConnectionData * m_pSavedAsynchronousConnectionData; // owned, may be null, this is used to reconnect to the last server in this context - - unsigned int m_uConnectAttemptCount; - QTimer * m_pReconnectTimer; - - KviPointerList * m_pMonitorList; // owned, may be null - - // dead channels and queries - KviPointerList * m_pDeadChannels; - KviPointerList * m_pDeadQueries; - // other context bound windows - KviPointerList * m_pContextWindows; - - int m_iHeartbeatTimerId; -public: - inline unsigned int id(){ return m_uId; }; - // never null and always the same! - inline KviConsole * console(){ return m_pConsole; }; - // never null and always the same - inline KviFrame * frame(){ return m_pFrame; }; - // may be null and may change! - inline KviIrcConnection * connection(){ return m_pConnection; }; - // state - inline State state(){ return m_eState; }; - inline bool isConnected(){ return m_eState == Connected; }; - inline bool isLoggingIn(){ return m_eState == LoggingIn; }; - // dead channels and queries - bool unregisterDeadChannel(KviChannel * c); - bool unregisterDeadQuery(KviQuery * q); - void registerDeadChannel(KviChannel * c); - void registerDeadQuery(KviQuery * q); - KviChannel * findDeadChannel(const QString &name); - KviQuery * findDeadQuery(const QString &nick); - KviQuery * firstDeadQuery(); - KviChannel * firstDeadChannel(); - // other windows bound to the context - void closeAllContextWindows(); - void registerContextWindow(KviWindow * pWnd); - bool unregisterContextWindow(KviWindow * pWnd); - - inline KviPointerList * monitorList(){ return m_pMonitorList; }; - - // links window - void createLinksWindow(); - inline void setLinksWindowPointer(KviExternalServerDataParser * l){ m_pLinksWindow = l; }; - inline KviExternalServerDataParser * linksWindow(){ return m_pLinksWindow; }; - - // list window - void createListWindow(); - inline void setListWindowPointer(KviExternalServerDataParser * l){ m_pListWindow = l; }; - inline KviExternalServerDataParser * listWindow(){ return m_pListWindow; }; - - void setAsynchronousConnectionData(KviAsynchronousConnectionData * d); - inline KviAsynchronousConnectionData * asynchronousConnectionData(){ return m_pAsynchronousConnectionData; }; - void destroyAsynchronousConnectionData(); - // used by KviConsole (for now) and KviUserParser - void connectToCurrentServer(); - - void beginAsynchronousConnect(unsigned int uDelayInMSecs); - - void registerDataStreamMonitor(KviIrcDataStreamMonitor * m); - void unregisterDataStreamMonitor(KviIrcDataStreamMonitor *m); - - void terminateConnectionRequest(bool bForce,const QString &szQuitMessage = QString(),bool bSimulateUnexpectedDisconnect = false); -public slots: - void closeAllDeadChannels(); - void closeAllDeadQueries(); - -protected: - // called by KviIrcContextToolBar: this will DIE in favor of connectOrDisconnect() - void connectButtonClicked(); - // used by KviConsole (for now) - void destroyConnection(); - // for KviConsole (for now) . later will be used only internally - void setState(State eState); - // called by KviIrcConnection - void loginComplete(); - // our heartbeat timer event - virtual void timerEvent(QTimerEvent *e); -public: - void connectOrDisconnect(){ connectButtonClicked(); }; -protected: - // - // KviIrcConnection interface - // - void connectionFailed(int iError); - void connectionEstabilished(); - void connectionTerminated(); -signals: - void stateChanged(); -protected slots: - void asynchronousConnect(); -}; - - -#endif //!_KVI_IRCCONTEXT_H_ diff --git a/src/kvirc/kernel/kvi_ircdatastreammonitor.cpp b/src/kvirc/kernel/kvi_ircdatastreammonitor.cpp deleted file mode 100644 index 2b126ad84..000000000 --- a/src/kvirc/kernel/kvi_ircdatastreammonitor.cpp +++ /dev/null @@ -1,41 +0,0 @@ -//============================================================================= -// -// File : kvi_ircdatastreammonitor.cpp -// Creation date : Sun 04 Jul 2004 21:27:22 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_ircdatastreammonitor.h" -#include "kvi_irccontext.h" - -KviIrcDataStreamMonitor::KviIrcDataStreamMonitor(KviIrcContext * pContext) -: KviHeapObject() -{ - m_pMyContext = pContext; - m_pMyContext->registerDataStreamMonitor(this); -} - -KviIrcDataStreamMonitor::~KviIrcDataStreamMonitor() -{ - m_pMyContext->unregisterDataStreamMonitor(this); -} - diff --git a/src/kvirc/kernel/kvi_ircdatastreammonitor.h b/src/kvirc/kernel/kvi_ircdatastreammonitor.h deleted file mode 100644 index ebe0df397..000000000 --- a/src/kvirc/kernel/kvi_ircdatastreammonitor.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef _KVI_IRCDATASTREAMMONITOR_H_ -#define _KVI_IRCDATASTREAMMONITOR_H_ -//============================================================================= -// -// File : kvi_ircdatastreammonitor.h -// Creation date : Sun 04 Jul 2004 21:27:22 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviHeapObject.h" - -class KviIrcContext; - -class KVIRC_API KviIrcDataStreamMonitor : public KviHeapObject -{ -public: - KviIrcDataStreamMonitor(KviIrcContext * pContext); - virtual ~KviIrcDataStreamMonitor(); -protected: - KviIrcContext * m_pMyContext; -public: - virtual bool incomingMessage(const char *) = 0; - // For proxy connections it might spit out binary data! - virtual bool outgoingMessage(const char *) = 0; - virtual void connectionInitiated(){}; - virtual void connectionTerminated(){}; - virtual void die(){ delete this; }; -}; - - -#endif //!_KVI_IRCDATASTREAMMONITOR_H_ diff --git a/src/kvirc/kernel/kvi_irclink.cpp b/src/kvirc/kernel/kvi_irclink.cpp deleted file mode 100644 index 4c7b77d63..000000000 --- a/src/kvirc/kernel/kvi_irclink.cpp +++ /dev/null @@ -1,424 +0,0 @@ -//============================================================================= -// -// File : kvi_irclink.cpp -// Creation date : Mon 03 May 2004 01:45:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_irclink.h" -#include "KviDnsResolver.h" -#include "KviLocale.h" -#include "KviIrcServerDataBase.h" -#include "KviProxyDataBase.h" -#include "KviError.h" -#include "kvi_out.h" -#include "kvi_options.h" -#include "kvi_ircsocket.h" -#include "kvi_console.h" -#include "KviNetUtils.h" -#include "kvi_internalcmd.h" -#include "kvi_frame.h" -#include "kvi_mexlinkfilter.h" -//#include "kvi_garbage.h" -#include "KviMemory.h" -#include "KviMemory.h" -#include "kvi_ircconnection.h" -#include "kvi_ircconnectiontarget.h" -#include "kvi_ircconnectiontargetresolver.h" -#include "kvi_ircsocket.h" -#include "KviDataBuffer.h" -#include "kvi_debug.h" - -#include - -extern KVIRC_API KviIrcServerDataBase * g_pServerDataBase; -extern KVIRC_API KviProxyDataBase * g_pProxyDataBase; -//extern KVIRC_API KviGarbageCollector * g_pGarbageCollector; - - -KviIrcLink::KviIrcLink(KviIrcConnection * pConnection) -: QObject() -{ - m_pConnection = pConnection; - m_pTarget = pConnection->target(); - m_pConsole = m_pConnection->console(); - - m_pSocket = 0; - m_pLinkFilter = 0; - m_pResolver = 0; - - m_pReadBuffer = 0; // incoming data buffer - m_uReadBufferLen = 0; // incoming data buffer length - m_uReadPackets = 0; // total packets read per session - - m_eState = Idle; -} - -KviIrcLink::~KviIrcLink() -{ - if(m_pResolver) - delete m_pResolver; - - destroySocket(); - - if(m_pReadBuffer) - KviMemory::free(m_pReadBuffer); -} - - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// KviIrcSocket management -// - -void KviIrcLink::linkFilterDestroyed() -{ - m_pLinkFilter = 0; - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("Ops... for some reason the link filter object has been destroyed")); -} - -void KviIrcLink::destroySocket() -{ - if(m_pLinkFilter) - { - QObject::disconnect(m_pLinkFilter,0,this,0); - // the module extension server links must be destroyed in the module that provided it - m_pLinkFilter->die(); - m_pLinkFilter = 0; - } - - if(m_pSocket) - { - // We use deleteLater() here, since we could actually be inside an event - // related to the QSocketNotifier that the socket is attached to... - m_pSocket->deleteLater(); - m_pSocket = 0; - } -} - -void KviIrcLink::createSocket(const QString & szLinkFilterName) -{ - destroySocket(); // make sure we do not leak memory - - m_pSocket = new KviIrcSocket(this); - - if(szLinkFilterName.isEmpty()) - return; - - if(KviQString::equalCI(szLinkFilterName,"irc")) - return; - - m_pLinkFilter = (KviMexLinkFilter *)g_pModuleExtensionManager->allocateExtension("linkfilter", - szLinkFilterName.toUtf8().data(),m_pConsole,0,this,szLinkFilterName.toUtf8().data()); - - if(m_pLinkFilter) - { - connect(m_pLinkFilter,SIGNAL(destroyed()),this,SLOT(linkFilterDestroyed())); - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr2qs("Using filtered IRC protocol: Link filter is \"%Q\""),&szLinkFilterName); - return; - } - - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("Failed to set up the link filter \"%Q\", will try with plain IRC"),&szLinkFilterName); -} - -////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Connection related operations -// - -void KviIrcLink::abort() -{ - if(m_pSocket) - { - m_pSocket->abort(); - return; - } - - if(m_pResolver) - { - m_pResolver->abort(); - return; - } -} - -void KviIrcLink::start() -{ - m_eState = Connecting; - if(m_pResolver) - delete m_pResolver; // this should never happen - - m_pResolver = new KviIrcConnectionTargetResolver(m_pConnection); - connect(m_pResolver,SIGNAL(terminated()),this,SLOT(resolverTerminated())); - m_pResolver->start(m_pTarget); -} - -void KviIrcLink::resolverTerminated() -{ - if(!m_pResolver) - { - qDebug("Oops... resoverTerminated() triggered without a resolver ?"); - return; - } - - if(m_pResolver->status() != KviIrcConnectionTargetResolver::Success) - { - m_eState = Idle; - m_pConnection->linkAttemptFailed(m_pResolver->lastError()); - return; - } - - // resolver terminated successfully - delete m_pResolver; - m_pResolver = 0; - - createSocket(m_pTarget->server()->linkFilter()); - - int iErr = m_pSocket->startConnection(m_pTarget->server(),m_pTarget->proxy(), - m_pTarget->bindAddress().isEmpty() ? 0 : m_pTarget->bindAddress().toUtf8().data()); - - if(iErr != KviError_success) - { - QString szStrDescription(KviError::getDescription(iErr)); - m_pConsole->output(KVI_OUT_SYSTEMERROR, - __tr2qs("Failed to start the connection: %Q"), - &szStrDescription); -// &(KviError::getDescription(iErr))); - - m_eState = Idle; - m_pConnection->linkAttemptFailed(iErr); - } -} - - -///////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Incoming data processing -// - -void KviIrcLink::processData(char * buffer, int iLen) -{ - if(m_pLinkFilter) - { - m_pLinkFilter->processData(buffer,iLen); - return; - } - - register char * p = buffer; - char * cBeginOfCurData = buffer; - int iBufLen = 0; - char * cMessageBuffer = (char *)KviMemory::allocate(1); - - while(*p) - { - if((*p == '\r' )||(*p == '\n')) - { - //found a CR or LF... - //prepare a message buffer - iBufLen = p - cBeginOfCurData; - //check for previous unterminated data - if(m_uReadBufferLen > 0) - { - KVI_ASSERT(m_pReadBuffer); - cMessageBuffer = (char *)KviMemory::reallocate(cMessageBuffer,iBufLen + m_uReadBufferLen + 1); - KviMemory::move(cMessageBuffer,m_pReadBuffer,m_uReadBufferLen); - KviMemory::move((void *)(cMessageBuffer + m_uReadBufferLen),cBeginOfCurData,iBufLen); - *(cMessageBuffer + iBufLen + m_uReadBufferLen) = '\0'; - m_uReadBufferLen = 0; - KviMemory::free(m_pReadBuffer); - m_pReadBuffer = 0; - } else { - KVI_ASSERT(!m_pReadBuffer); - cMessageBuffer = (char *)KviMemory::reallocate(cMessageBuffer,iBufLen + 1); - KviMemory::move(cMessageBuffer,cBeginOfCurData,iBufLen); - *(cMessageBuffer + iBufLen) = '\0'; - } - m_uReadPackets++; - - // FIXME: actually it can happen that the socket gets disconnected - // in a incomingMessage() call. - // The problem might be that some other parts of kvirc assume - // that the irc context still exists after a failed write to the socket - // (some parts don't even check the return value!) - // If the problem presents itself again then the solution is: - // disable queue flushing for the "incomingMessage" call - // and just call queue_insertMessage() - // then after the call terminates flush the queue (eventually detecting - // the disconnect and thus destroying the irc context). - // For now we try to rely on the remaining parts to handle correctly - // such conditions. Let's see... - if(*cMessageBuffer != 0) - m_pConnection->incomingMessage(cMessageBuffer); - - if(m_pSocket->state() != KviIrcSocket::Connected) - { - // Disconnected in KviConsole::incomingMessage() call. - // This may happen for several reasons (local event loop - // with the user hitting the disconnect button, a scripting - // handler event that disconnects explicitly) - // - // We handle it by simply returning control to readData() which - // will return immediately (and safely) control to Qt - KviMemory::free(cMessageBuffer); - return; - } - - while(*p && ((*p=='\r')||(*p=='\n')) )p++; - cBeginOfCurData = p; - - } else p++; - } - - //now *p == '\0' - //beginOfCurData points to '\0' if we have - //no more stuff to parse, or points to something - //different than '\r' or '\n'... - if(*cBeginOfCurData) - { - //Have remaining data...in the local buffer - iBufLen = p - cBeginOfCurData; - if(m_uReadBufferLen > 0) - { - //and there was more stuff saved... (really slow connection) - KVI_ASSERT(m_pReadBuffer); - m_pReadBuffer =(char *)KviMemory::reallocate(m_pReadBuffer,m_uReadBufferLen + iBufLen); - KviMemory::move((void *)(m_pReadBuffer+m_uReadBufferLen),cBeginOfCurData,iBufLen); - m_uReadBufferLen += iBufLen; - } else { - // - KVI_ASSERT(!m_pReadBuffer); - m_uReadBufferLen = iBufLen; - m_pReadBuffer =(char *)KviMemory::allocate(m_uReadBufferLen); - KviMemory::move(m_pReadBuffer,cBeginOfCurData,m_uReadBufferLen); - } - //The m_pReadBuffer contains at max 1 irc message... - //that can not be longer than 510 bytes (the message is not CRLF terminated) - // FIXME: Is this limit *really* valid on all servers ? - if(m_uReadBufferLen > 510) qDebug("WARNING: Receiving an invalid irc message from server."); - } - KviMemory::free(cMessageBuffer); -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Outgoing data processing -// - -void KviIrcLink::clearOutputQueue(bool bPrivateMessagesOnly) -{ - if(!m_pSocket) - return; // we have no queue at all - - if(m_pLinkFilter) - { - m_pLinkFilter->clearOutputQueue(bPrivateMessagesOnly); - return; - } - - m_pSocket->clearOutputQueue(bPrivateMessagesOnly); -} - - -bool KviIrcLink::sendPacket(KviDataBuffer * pData) -{ - if(!m_pSocket) - { - delete pData; - pData = 0; - return false; - } - - // if we have a filter, let it do its job - if(m_pLinkFilter) - return m_pLinkFilter->sendPacket(pData); - - return m_pSocket->sendPacket(pData); -} - -void KviIrcLink::socketStateChange() -{ - switch(m_pSocket->state()) - { - case KviIrcSocket::Connected: - m_eState = Connected; - m_pConnection->linkEstabilished(); - break; - case KviIrcSocket::Idle: - { - State old = m_eState; - m_eState = Idle; - switch(old) - { - case Connecting: - m_pConnection->linkAttemptFailed(m_pSocket->lastError()); - break; - case Connected: - m_pConnection->linkTerminated(); - break; - default: // currently can be only Idle - qDebug("Ooops... got a KviIrcSocket::Idle state change when KviIrcLink::m_eState was Idle"); - break; - } - } - break; - case KviIrcSocket::Connecting: - m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("Contacting %Q %s (%s) on port %u"), - connection()->target()->proxy() ? &(__tr2qs("proxy host")) : &(__tr2qs("IRC server")), - connection()->target()->proxy() ? connection()->target()->proxy()->m_szHostname.toUtf8().data() : connection()->target()->server()->m_szHostname.toUtf8().data(), - connection()->target()->proxy() ? connection()->target()->proxy()->m_szIp.toUtf8().data() : connection()->target()->server()->m_szIp.toUtf8().data(), - connection()->target()->proxy() ? connection()->target()->proxy()->m_uPort : connection()->target()->server()->m_uPort); - break; - case KviIrcSocket::SSLHandshake: - m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("Low-level transport connection established [%s (%s:%u)]"), - connection()->target()->proxy() ? connection()->target()->proxy()->m_szHostname.toUtf8().data() : connection()->target()->server()->m_szHostname.toUtf8().data(), - connection()->target()->proxy() ? connection()->target()->proxy()->m_szIp.toUtf8().data() : connection()->target()->server()->m_szIp.toUtf8().data(), - connection()->target()->proxy() ? connection()->target()->proxy()->m_uPort : connection()->target()->server()->m_uPort); - m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Starting Secure Socket Layer handshake")); - break; - case KviIrcSocket::ProxyLogin: - m_pConsole->output(KVI_OUT_CONNECTION,__tr2qs("%Q established [%s (%s:%u)]"), - connection()->link()->socket()->usingSSL() ? &(__tr2qs("Secure proxy connection")) : &(__tr2qs("Proxy connection")), - connection()->target()->proxy()->m_szHostname.toUtf8().data(), - connection()->target()->proxy()->m_szIp.toUtf8().data(), - connection()->target()->proxy()->m_uPort); - m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Negotiating relay information")); - break; - case KviIrcSocket::ProxyFinalV4: - m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent connection request, waiting for acknowledgement")); - break; - case KviIrcSocket::ProxyFinalV5: - m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent target host data, waiting for acknowledgement")); - break; - case KviIrcSocket::ProxySelectAuthMethodV5: - m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent auth method request, waiting for acknowledgement")); - break; - case KviIrcSocket::ProxyUserPassV5: - m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent username and password, waiting for acknowledgement")); - break; - case KviIrcSocket::ProxyFinalHttp: - m_pConsole->outputNoFmt(KVI_OUT_CONNECTION,__tr2qs("Sent connection request, waiting for \"HTTP 200\" acknowledgement")); - break; - default: - break; - } -} diff --git a/src/kvirc/kernel/kvi_irclink.h b/src/kvirc/kernel/kvi_irclink.h deleted file mode 100644 index 719006778..000000000 --- a/src/kvirc/kernel/kvi_irclink.h +++ /dev/null @@ -1,222 +0,0 @@ -#ifndef _KVI_IRCLINK_H_ -#define _KVI_IRCLINK_H_ -//============================================================================= -// -// File : kvi_irclink.h -// Creation date : Mon 03 May 2004 01:45:42 by Szymon Stefanek -// -// This file is part of the KVIrc IRC client distribution -// Copyright (C) 2004-2010 Szymon Stefanek -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_irclink.h -* \author Szymon Stefanek -* \brief Middle stack protocol for IRC connection -*/ - -#include "kvi_settings.h" -#include "KviQString.h" - -#include - -class KviConsole; -class KviIrcServer; -class KviProxy; -class KviIrcSocket; -class KviDnsResolver; -class KviIrcConnection; -class KviIrcConnectionTarget; -class KviIrcConnectionTargetResolver; -class KviDataBuffer; -class KviMexLinkFilter; - -/** -* \class KviIrcLink -* \brief Middle stack class for IRC connection -* -* This class gets data from KviIrcSocket and pass it to KviIrcConnection -*/ -class KVIRC_API KviIrcLink : public QObject -{ - friend class KviIrcConnection; // upper protocol in the stack - friend class KviIrcSocket; // lower protocol in the stack - Q_OBJECT -public: - /** - * \enum State - */ - enum State { - Idle, /**< Socket idling */ - Connecting, /**< Socket connecting */ - Connected /**< Socket connected */ - }; -protected: - /** - * \brief Constructs the IrcLink object - * - * Only KviConsole can create this. - * pConsole must NOT be null; - * pServer is a shallow pointer: Connection makes a copy of it internally, - * must NOT be null; - * pProxy may be null if a proxy is not desired. Connection makes a copy - * of it internally; - * \param pConnection The pointer to the KviIrcConnection class - * \return KviIrcLink - */ - KviIrcLink(KviIrcConnection * pConnection); - - /** - * \brief Destroys the IrcLink object - */ - ~KviIrcLink(); -private: - KviIrcConnection * m_pConnection; // shallow, never null - KviIrcConnectionTarget * m_pTarget; // shallow, never null - KviConsole * m_pConsole; // shallow, never null - KviIrcSocket * m_pSocket; // owned, may be null! - KviMexLinkFilter * m_pLinkFilter; // owned, may be null! - - State m_eState; - - char * m_pReadBuffer; - unsigned int m_uReadBufferLen; - unsigned int m_uReadPackets; - - KviIrcConnectionTargetResolver * m_pResolver; // owned -public: - /** - * \brief Returns the socket - * - * May be null! - * \return KviIrcSocket * - */ - KviIrcSocket * socket(){ return m_pSocket; }; - - /** - * \brief Returns the connection object - * - * Never null - * \return KviIrcConnection * - */ - KviIrcConnection * connection(){ return m_pConnection; }; - - /** - * \brief Returns the console - * - * Never null - * \return KviConsole * - */ - KviConsole * console(){ return m_pConsole; }; - - /** - * \brief Returns the state of the socket - * \return State - */ - State state(){ return m_eState; }; -protected: - /** - * \brief Sends a data packet - * - * This is used by KviIrcConnection::send*() - * This should be used to intercept the outgoing packets when implementing - * a new protocol. - * It's an interface for KviIrcConnection (upper protocol in stack) - * \param pData The pointer to the data packet - * \return bool - */ - virtual bool sendPacket(KviDataBuffer * pData); - - /** - * \brief Clears the output queue - * - * Requests to clear the underlying packet queue. - */ - virtual void clearOutputQueue(bool bPrivateMessagesOnly); - - /** - * \brief Aborts any connection or attempt - * \return void - */ - void abort(); -protected: - /** - * \brief Starts a connection attempt. - * - * It starts the server or proxy DNS lookup. - * The function MUST be asynchronous: it must return successfully and - * report any error by using m_pConnection->linkAttemptFailed() - * It's called internally and it's overridable - * \return void - */ - void start(); -protected: - /** - * \brief Process a packet of raw data from the server - * - * This is called by KviIrcSocket. - * The buffer is iLength+1 bytes long and contains a null terminator - * It's an interface for KviIrcSocket (lower protocol in stack) - * \param buffer The buffer :) - * \param iLength The length of the buffer - * \return void - */ - void processData(char * buffer, int iLength); - - /** - * \brief Called at each state change - * \return void - */ - void socketStateChange(); -protected slots: - /** - * \brief Called when the link filter has been destroyed without permission :D - * - * This should NEVER happen (?) - * This is part of the KviIrcSocket management - * \return void - */ - void linkFilterDestroyed(); -private: - /** - * \brief Destroys the socket - * \return void - */ - void destroySocket(); - - /** - * \brief Creates the socket - * \param szLinkFilterName The source linkfilter name - * \return void - */ - void createSocket(const QString & szLinkFilterName); -signals: - /** - * \brief Emitted when the connection attempt has failed - * \return void - */ - void connectionFailed(); -private slots: - /** - * \brief Called when the DNS lookup has terminated - * \return void - */ - void resolverTerminated(); -}; - -#endif //_KVI_IRCLINK_H_ diff --git a/src/kvirc/kernel/kvi_ircsocket.cpp b/src/kvirc/kernel/kvi_ircsocket.cpp deleted file mode 100644 index 55ab56cf1..000000000 --- a/src/kvirc/kernel/kvi_ircsocket.cpp +++ /dev/null @@ -1,2014 +0,0 @@ -//============================================================================= -// -// File : kvi_ircsocket.cpp -// Creation date : Tue Jul 30 19:25:18 2002 GMT by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_ircsocket.h" -#include "KviIrcServer.h" -#include "KviProxyDataBase.h" -#include "KviNetUtils.h" -#include "kvi_settings.h" -#include "KviError.h" -#include "KviLocale.h" -#include "KviMemory.h" -#include "kvi_debug.h" -#include "KviCString.h" -#include "kvi_options.h" -#include "KviMemory.h" -#include "kvi_socket.h" -#include "kvi_console.h" -#include "kvi_out.h" -#include "kvi_irclink.h" -#include "kvi_ircconnection.h" -#include "KviDataBuffer.h" - -#ifdef COMPILE_SSL_SUPPORT - #include "kvi_sslmaster.h" -#endif - -#include -#include - -#if !defined(COMPILE_ON_WINDOWS) && !defined(COMPILE_ON_MINGW) - #include //for gettimeofday() -#endif -//#include -//#include - -// FIXME: #warning "Lag-o-meter" - -unsigned int g_uNextIrcLinkId = 1; - -KviIrcSocket::KviIrcSocket(KviIrcLink * pLink) -: QObject() -{ - m_uId = g_uNextIrcLinkId; - g_uNextIrcLinkId++; - - m_pLink = pLink; - m_pConsole = m_pLink->console(); - - m_state = Idle; // current socket state - - m_pRsn = 0; // read socket notifier - m_pWsn = 0; // write socket notifier - m_sock = KVI_INVALID_SOCKET; // socket - - m_pIrcServer = 0; // current server data - m_pProxy = 0; // current proxy data - - m_pTimeoutTimer = 0; // timeout for connect() - - m_uReadBytes = 0; // total read bytes per session - m_uSentBytes = 0; // total sent bytes per session - m_uSentPackets = 0; // total packets sent per session - - m_pSendQueueHead = 0; // data queue - m_pSendQueueTail = 0; // - - m_iLastError = KviError_success; - -#ifdef COMPILE_SSL_SUPPORT - m_pSSL = 0; -#endif - - m_tAntiFloodLastMessageTime.tv_sec = 0; - m_tAntiFloodLastMessageTime.tv_usec = 0; - - if(KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout) < 100) - KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout) = 100; // this is our minimum, we don't want to lag the app - - m_bInProcessData = false; - - m_pFlushTimer = new QTimer(); // queue flush timer - connect(m_pFlushTimer,SIGNAL(timeout()),this,SLOT(flushSendQueue())); -} - -KviIrcSocket::~KviIrcSocket() -{ - reset(); - delete m_pFlushTimer; -} - -void KviIrcSocket::reset() -{ -#ifdef COMPILE_SSL_SUPPORT - if(m_pSSL) - { - KviSSLMaster::freeSSL(m_pSSL); - m_pSSL = 0; - } -#endif - if(m_pIrcServer) - { - delete m_pIrcServer; - m_pIrcServer = 0; - } - - if(m_pProxy) - { - delete m_pProxy; - m_pProxy = 0; - } - - if(m_pRsn) - { - delete m_pRsn; - m_pRsn = 0; - } - - if(m_pWsn) - { - delete m_pWsn; - m_pWsn = 0; - } - - if(kvi_socket_isValid(m_sock)) - { - kvi_socket_destroy(m_sock); - m_sock = KVI_INVALID_SOCKET; - } - - if(m_pTimeoutTimer) - { - m_pTimeoutTimer->stop(); - delete m_pTimeoutTimer; - m_pTimeoutTimer = 0; - } - - m_bInProcessData = false; - - m_uReadBytes = 0; - m_uSentBytes = 0; - m_uSentPackets = 0; - m_tAntiFloodLastMessageTime.tv_sec = 0; - m_tAntiFloodLastMessageTime.tv_usec = 0; - - m_bInProcessData = false; - - if(m_pFlushTimer->isActive()) - m_pFlushTimer->stop(); - - queue_removeAllMessages(); - - setState(Idle); -} - -void KviIrcSocket::clearOutputQueue(bool bPrivateMessagesOnly) -{ - if(bPrivateMessagesOnly) - queue_removePrivateMessages(); - else - queue_removeAllMessages(); -} - - -void KviIrcSocket::outputSSLMessage(const QString & szMsg) -{ - m_pConsole->output(KVI_OUT_SSL,__tr2qs("[SSL]: %Q"),&szMsg); -} - -void KviIrcSocket::outputSSLError(const QString & szMsg) -{ - m_pConsole->output(KVI_OUT_SSL,__tr2qs("[SSL ERROR]: %Q"),&szMsg); -} - -void KviIrcSocket::outputProxyMessage(const QString & szMsg) -{ - QStringList list = szMsg.isEmpty() ? QStringList() : szMsg.split("\n",QString::SkipEmptyParts); - - for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) - { - QString szTemporary = (*it).trimmed(); - m_pConsole->output(KVI_OUT_SOCKETMESSAGE,__tr2qs("[PROXY]: %Q"),&(szTemporary)); - } -} - -void KviIrcSocket::outputProxyError(const QString & szMsg) -{ - QStringList list = szMsg.isEmpty() ? QStringList() : szMsg.split("\n",QString::SkipEmptyParts); - - for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) - { - QString szTemporary = (*it).trimmed(); - m_pConsole->output(KVI_OUT_SOCKETERROR,__tr2qs("[PROXY ERROR]: %Q"),&(szTemporary)); - } - -} - -void KviIrcSocket::outputSocketMessage(const QString & szMsg) -{ - m_pConsole->output(KVI_OUT_SOCKETMESSAGE,__tr2qs("[SOCKET]: %Q"),&szMsg); -} - -void KviIrcSocket::outputSocketError(const QString & szMsg) -{ - m_pConsole->output(KVI_OUT_SOCKETERROR,__tr2qs("[SOCKET ERROR]: %Q"),&szMsg); -} - -void KviIrcSocket::outputSocketWarning(const QString & szMsg) -{ - m_pConsole->output(KVI_OUT_SOCKETWARNING,__tr2qs("[SOCKET WARNING]: %Q"),&szMsg); -} - -void KviIrcSocket::setState(SocketState state) -{ - if(state != m_state) - { - m_state = state; - m_pLink->socketStateChange(); - } -} - -void KviIrcSocket::raiseError(int iError) -{ - m_iLastError = iError; - //m_pConsole->socketError(iError); - if((m_iLastError == KviError_remoteEndClosedConnection) && - ( m_state == ProxyHttpError)) - outputSocketMessage(KviError::getDescription(iError)); - else - outputSocketError(KviError::getDescription(iError)); -} - -int KviIrcSocket::startConnection(KviIrcServer * pServer, KviProxy * pProxy, const char * pcBindAddress) -{ - // Attempts to estabilish an IRC connection - // to the server specified by *srv. - // Uses the proxy *prx if not 0 - if(m_state != Idle) - return KviError_anotherConnectionInProgress; - - // Coherent state, thnx. - reset(); - - if(pServer->useSSL()) - { -#ifndef COMPILE_SSL_SUPPORT - return KviError_noSSLSupport; -#endif //COMPILE_SSL_SUPPORT - } - - // Copy the server - m_pIrcServer = new KviIrcServer(*pServer); - - bool bTargetIPv6 = false; - bool bNeedServerIp = !pProxy; - if(pProxy) - bNeedServerIp = ( - (pProxy->protocol() != KviProxy::Http) && (pProxy->protocol() != KviProxy::Socks5) - ); - - // We're going to check the addresses now - - // check the proxy stuff... - if(pProxy) - { - // Yeah...here comes the proxy - m_pProxy = new KviProxy(*pProxy); - // check the proxy IP address - if(m_pProxy->isIPv6()) - { - // IPv6 proxy :) (STILL QUITE UNTESTED ?) -#ifdef COMPILE_IPV6_SUPPORT - bTargetIPv6 = true; - if(!KviNetUtils::isValidStringIPv6(m_pProxy->ip())) - return KviError_invalidProxyAddress; - // SOCKSv4 does not support IPv6 addresses - if(m_pProxy->protocol() == KviProxy::Socks4) - return KviError_socksV4LacksIPv6Support; -#else - return KviError_noIPv6Support; -#endif - } else { - // IPv4 proxy - if(!KviNetUtils::isValidStringIp(m_pProxy->ip())) - return KviError_invalidProxyAddress; - } - } - - if(bNeedServerIp) - { - // check the irc host ip -#ifdef COMPILE_IPV6_SUPPORT - if(m_pIrcServer->isIPv6()) - { - // We have an IPv6 server host (Interesting if proxy is IPv4) - if( !KviNetUtils::isValidStringIPv6(m_pIrcServer->ip()) ) - return KviError_invalidIpAddress; - if(!m_pProxy) - bTargetIPv6 = true; // otherwise the proxy rules - } else { -#endif - // We have an IPv4 server host - if(!KviNetUtils::isValidStringIp(m_pIrcServer->ip())) - return KviError_invalidIpAddress; -#ifdef COMPILE_IPV6_SUPPORT - } -#endif - } - - KviSockaddr sa(pProxy ? m_pProxy->ip().toUtf8().data() : m_pIrcServer->ip().toUtf8().data(), pProxy ? m_pProxy->port() : m_pIrcServer->port(),bTargetIPv6); - - if(!sa.socketAddress()) - return KviError_invalidIpAddress; - - // create the socket -#ifdef COMPILE_IPV6_SUPPORT - m_sock = kvi_socket_create(bTargetIPv6 ? KVI_SOCKET_PF_INET6 : KVI_SOCKET_PF_INET,KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP); -#else - m_sock = kvi_socket_create(KVI_SOCKET_PF_INET,KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP); -#endif - - if(m_sock < 0) - return KviError_socketCreationFailed; - - if(pcBindAddress) - { - // we have to bind the socket to a local address - KviSockaddr localSa(pcBindAddress,0,bTargetIPv6); - bool bBindOk = localSa.socketAddress(); - - if(bBindOk) - { - bBindOk = kvi_socket_bind(m_sock,localSa.socketAddress(),((int)(localSa.addressLength()))); - } - - QString szTmp; - if(bBindOk) - { - if(_OUTPUT_VERBOSE) - KviQString::sprintf(szTmp,__tr2qs("Binding to local address %s"),pcBindAddress); - outputSocketMessage(szTmp); - } else { - if(_OUTPUT_VERBOSE) - KviQString::sprintf(szTmp,__tr2qs("Binding to local address %s failed: the kernel will choose the correct interface"),pcBindAddress); - outputSocketWarning(szTmp); - } - } - - // make it non blocking - if(!kvi_socket_setNonBlocking(m_sock)) - { - reset(); - return KviError_asyncSocketFailed; - } - - if(!kvi_socket_connect(m_sock,sa.socketAddress(),((int)(sa.addressLength())))) - { - // ops... - int iErr = kvi_socket_error(); - - if(!kvi_socket_recoverableConnectError(iErr)) - { - // Ops... - int iSockError = iErr; - if(iSockError == 0) - { - // Zero error ?...let's look closer - int iSize = sizeof(int); - if(!kvi_socket_getsockopt(m_sock,SOL_SOCKET,SO_ERROR,(void *)&iSockError,&iSize)) - iSockError = 0; - } - // die :( - reset(); - // And declare problems :) - if(iSockError) - return KviError::translateSystemError(iSockError); - else return KviError_unknownError; //Error 0 ? - } - } - - // and setup the WRITE notifier... - m_pWsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Write); - QObject::connect(m_pWsn,SIGNAL(activated(int)),this,SLOT(writeNotifierFired(int))); - m_pWsn->setEnabled(true); - - // set the timer - if(KVI_OPTION_UINT(KviOption_uintIrcSocketTimeout) < 5) - KVI_OPTION_UINT(KviOption_uintIrcSocketTimeout) = 5; - - m_pTimeoutTimer = new QTimer(); - QObject::connect(m_pTimeoutTimer,SIGNAL(timeout()),this,SLOT(connectionTimedOut())); - m_pTimeoutTimer->setSingleShot(true); - m_pTimeoutTimer->setInterval(KVI_OPTION_UINT(KviOption_uintIrcSocketTimeout) * 1000); - m_pTimeoutTimer->start(); - - // and wait for connect - setState(Connecting); - - return KviError_success; -} - -void KviIrcSocket::connectionTimedOut() -{ - // the m_pTimeoutTimer fired :( - raiseError(KviError_connectionTimedOut); - reset(); -} - -void KviIrcSocket::writeNotifierFired(int) -{ - // kill the timeout timer - if(m_pTimeoutTimer) - { - delete m_pTimeoutTimer; - m_pTimeoutTimer = 0; - } - - // Check for errors... - int iSockError; - int iSize = sizeof(int); - if(!kvi_socket_getsockopt(m_sock,SOL_SOCKET,SO_ERROR,(void *)&iSockError,&iSize)) - iSockError = -1; - - //sockError = 0; - if(iSockError != 0) - { - //failed - if(iSockError > 0) - iSockError = KviError::translateSystemError(iSockError); - else iSockError = KviError_unknownError; //Error 0 ? - - raiseError(iSockError); - reset(); - return; - } - - // kill the write notifier - delete m_pWsn; - m_pWsn = 0; - - //Succesfully connected... - connectionEstabilished(); -} - -void KviIrcSocket::connectionEstabilished() -{ - if(m_sock == KVI_INVALID_SOCKET) - return; // ops...disconnected in setState() ???? - - if(m_pProxy) - connectedToProxy(); - else connectedToIrcServer(); -} - -void KviIrcSocket::connectedToProxy() -{ - if(!m_pProxy) - qDebug("WARNING: connectedToProxy() without a m_pProxy!"); - - // FIXME: Do we want to support SSL proxies ? - // it would be just a matter of SSL handshaking - // with the proxy - - setState(ProxyLogin); - - if(m_pRsn) - { - delete m_pRsn; - m_pRsn = 0; - } - - m_pRsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); - - QObject::connect(m_pRsn,SIGNAL(activated(int)),this,SLOT(readProxyData(int))); - - switch(m_pProxy->protocol()) - { - case KviProxy::Http: - proxyLoginHttp(); - break; - case KviProxy::Socks5: - proxyLoginV5(); - break; - default: - proxyLoginV4(); - break; - } -} - -void KviIrcSocket::readHttpProxyErrorData(int) -{ - char cBuffer[256]; - int iReadLength; - - iReadLength = kvi_socket_recv(m_sock,cBuffer,255); - if(iReadLength <= 0) - { - handleInvalidSocketRead(iReadLength); - return; - } - - outputProxyMessage(m_pConsole->decodeText(cBuffer)); -} - -void KviIrcSocket::connectedToIrcServer() -{ -#ifdef COMPILE_SSL_SUPPORT - if(m_pIrcServer->useSSL()) - { - enterSSLMode(); - return; - } -#endif //COMPILE_SSL_SUPPORT - linkUp(); -} - -#ifdef COMPILE_SSL_SUPPORT -void KviIrcSocket::enterSSLMode() -{ - Q_ASSERT(!m_pSSL); // Don't call this function twice in a session - - m_pSSL = KviSSLMaster::allocSSL(m_pConsole,m_sock,KviSSL::Client); - if(!m_pSSL) - { - raiseSSLError(); - raiseError(KviError_SSLError); - reset(); - return; - } - setState(SSLHandshake); - doSSLHandshake(0); -} -#endif //COMPILE_SSL_SUPPORT - -void KviIrcSocket::readProxyData(int) -{ - char cBuffer[256]; - int iReadLength; -/* - // THIS IS WORKING CODE THAT SUPPORTS SSL PROXIES! -#ifdef COMPILE_SSL_SUPPORT - if(m_pSSL) - { - readLength = m_pSSL->read(buffer,256); - if(readLength <= 0) - { - // ssl error....? - switch(m_pSSL->getProtocolError(readLength)) - { - case KviSSL::ZeroReturn: - readLength = 0; - break; - case KviSSL::WantRead: - case KviSSL::WantWrite: - // hmmm... - return; - break; - case KviSSL::SyscallError: - { - int iE = m_pSSL->getLastError(true); - if(iE != 0) - { - raiseSSLError(); - raiseError(KviError_SSLError); - reset(); - return; - } - } - break; - case KviSSL::SSLError: - raiseSSLError(); - raiseError(KviError_SSLError); - reset(); - return; - break; - default: - raiseError(KviError_SSLError); - reset(); - return; - break; - - } - handleInvalidSocketRead(readLength); - return; - } - } else { -#endif -*/ - iReadLength = kvi_socket_recv(m_sock,cBuffer,255); - if(iReadLength <= 0) - { - handleInvalidSocketRead(iReadLength); - return; - } -/* -#ifdef COMPILE_SSL_SUPPORT - } -#endif -*/ - // we need at least two bytes... - if(iReadLength < 2) - { - // a single byte of reply means: - // - connection through a 1 bps modem - // - a totally blocked network - // - remote host is not a SOCKS/HTTP server - // Anyway....it is always a meaningless reply - // better to try again later :) - raiseError(KviError_unrecognizedProxyReply); - reset(); - return; - } - - // handle the reply - switch(m_state) - { - case ProxyFinalV4: - //V4 final reply - proxyHandleV4FinalReply((unsigned char)cBuffer[1]); - break; - case ProxySelectAuthMethodV5: - //V5 method selection reply - proxyHandleV5MethodReply((unsigned char)cBuffer[1]); - break; - case ProxyUserPassV5: - //V5 user and pass reply - proxyHandleV5AuthReply((unsigned char)cBuffer[1]); - break; - case ProxyFinalV5: - //V5 final reply - proxyHandleV5FinalReply((unsigned char)cBuffer[1]); - break; - case ProxyFinalHttp: - //Http final reply - cBuffer[iReadLength] = '\0'; - proxyHandleHttpFinalReply(cBuffer,iReadLength); - break; - default: - // what ? - raiseError(KviError_unrecognizedProxyReply); - reset(); - break; - } -} - -void KviIrcSocket::proxyLoginHttp() -{ - // Well..this is just plain and easy: connect to the proxy machine - // and say "CONNECT : HTTP/\n\n" - // if it requires auth then say Proxy-Authorization: Basic user:passwd - // Then expect a server reply header (2 newlines) - // HTTP 200 = Success - // HTTP Anything else = Failure - - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("Using HTTP protocol.")); - - setState(ProxyFinalHttp); - KviCString szTmp(KviCString::Format,"CONNECT %s:%u HTTP/1.0\r\n",m_pIrcServer->hostName().toUtf8().data(),(unsigned int)(m_pIrcServer->port())); - - szTmp.append(KviCString::Format,"User-Agent: KVIrc-ProxyClient/4.0\r\n"); - - if(m_pProxy->hasUser()) - { - KviCString szAuth(KviCString::Format,"%s:%s",m_pProxy->user().toUtf8().data(),m_pProxy->pass().toUtf8().data()); - KviCString szEncoded; - szEncoded.bufferToBase64(szAuth.ptr(),szAuth.len()); - szTmp.append(KviCString::Format,"Proxy-Authorization: Basic %s\r\n\r\n",szEncoded.ptr()); - } else { - szTmp.append("\r\n"); - } - - sendRawData(szTmp.ptr(),szTmp.len()); -} - -void KviIrcSocket::proxyLoginV4() -{ - // SOCKSv4 protocol - // - // 1) CONNECT - // - // The client connects to the SOCKS server and sends a CONNECT request when - // it wants to establish a connection to an application server. The client - // includes in the request packet the IP address and the port number of the - // destination host, and userid, in the following format. - // - // +----+----+----+----+----+----+----+----+----+----+....+----+ - // | VN | CD | DSTPORT | DSTIP | USERID |NULL| - // +----+----+----+----+----+----+----+----+----+----+....+----+ - // # of bytes: 1 1 2 4 variable 1 - // - // VN is the SOCKS protocol version number and should be 4. CD is the - // SOCKS command code and should be 1 for CONNECT request. NULL is a byte - // of all zero bits. - // - // The SOCKS server checks to see whether such a request should be granted - // based on any combination of source IP address, destination IP address, - // destination port number, the userid, and information it may obtain by - // consulting IDENT, cf. RFC 1413. If the request is granted, the SOCKS - // server makes a connection to the specified port of the destination host. - // A reply packet is sent to the client when this connection is established, - // or when the request is rejected or the operation fails. - // - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("Using SOCKSv4 protocol.")); - - m_pProxy->normalizeUserAndPass(); - // the protocol does not specify the "userid" format... - // so build an userid from the pass and/or username... - - KviCString szUserAndPass = m_pProxy->user(); - if(m_pProxy->hasPass()){ - if(szUserAndPass.hasData()) - szUserAndPass.append(' '); - szUserAndPass.append(m_pProxy->pass()); - } - - int iLen = szUserAndPass.len() + 9; - - // build the request packet - char * pcBufToSend = new char[iLen]; - pcBufToSend[0] = (unsigned char)4; //Version 4 - pcBufToSend[1] = (unsigned char)1; //Connect - - quint16 port = (quint16)htons(m_pIrcServer->port()); - KviMemory::move((void *)(pcBufToSend + 2),(void *)&port,2); - - struct in_addr ircInAddr; - - if(!KviNetUtils::stringIpToBinaryIp(m_pIrcServer->ip(),&ircInAddr)) - qDebug("SOCKET INTERNAL ERROR IN IPV4 (SOCKS4) ADDR CONVERSION"); - - quint32 host = (quint32)ircInAddr.s_addr; - KviMemory::move((void *)(pcBufToSend + 4),(void *)&host,4); - KviMemory::move((void *)(pcBufToSend + 8),(void *)(szUserAndPass.ptr()),szUserAndPass.len()); - - pcBufToSend[iLen-1] = 0; //NULL - - // send it into hyperspace... - setState(ProxyFinalV4); - sendRawData(pcBufToSend,iLen); - delete[] pcBufToSend; - // and wait for reply... -} - -void KviIrcSocket::proxyLoginV5() -{ - // SOCKSv5 protocol. - // - // When a TCP-based client wishes to establish a connection to an object - // that is reachable only via a firewall (such determination is left up - // to the implementation), it must open a TCP connection to the - // appropriate SOCKS port on the SOCKS server system. The SOCKS service - // is conventionally located on TCP port 1080. If the connection - // request succeeds, the client enters a negotiation for the - // authentication method to be used, authenticates with the chosen - // method, then sends a relay request. The SOCKS server evaluates the - // request, and either establishes the appropriate connection or denies - // it. - // - // The client connects to the server, and sends a version - // identifier/method selection message: - // - // +----+----------+----------+ - // |VER | NMETHODS | METHODS | - // +----+----------+----------+ - // | 1 | 1 | 1 to 255 | - // +----+----------+----------+ - // - // The VER field is set to X'05' for this version of the protocol. The - // NMETHODS field contains the number of method identifier octets that - // appear in the METHODS field. - // The values currently defined for METHOD are: - // - // o X'00' NO AUTHENTICATION REQUIRED - // o X'01' GSSAPI - // o X'02' USERNAME/PASSWORD - // o X'03' CHAP - // o X'04' to X'7F' IANA ASSIGNED - // o X'80' to X'FE' RESERVED FOR PRIVATE METHODS - // o X'FF' NO ACCEPTABLE METHODS - // - - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("Using SOCKSv5 protocol.")); - - m_pProxy->normalizeUserAndPass(); - // the protocol does not specify the "userid" format... - // so build an userid from the pass and/or username... - - char cBufToSend[4]; - cBufToSend[0] = (unsigned char)5; //use version 5 - int iSendLen = 3; - - if(!(m_pProxy->hasUser() || m_pProxy->hasPass())) - { - // no auth needed. - cBufToSend[1] = (unsigned char)1; //select one method - cBufToSend[2] = (unsigned char)0; //select method 0 : no auth - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("We can accept auth method 0 (no auth)")); - } else { - // we can provide a password and username if needed... - cBufToSend[1] = (unsigned char)2; //select from two methods - cBufToSend[2] = (unsigned char)0; //method 0 or - cBufToSend[3] = (unsigned char)2; //method 2 username/pass auth - iSendLen = 4; - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("We can accept auth method 0 (no auth) or 2 (user/pass)")); - } - - // notify the user before sending...since we may get disconnected - setState(ProxySelectAuthMethodV5); - sendRawData(cBufToSend,iSendLen); - // and wait for response -} - -void KviIrcSocket::proxyAuthUserPassV5() -{ - // Once the SOCKS V5 server has started, and the client has selected the - // Username/Password Authentication protocol, the Username/Password - // subnegotiation begins. This begins with the client producing a - // Username/Password request: - // - // +----+------+----------+------+----------+ - // |VER | ULEN | UNAME | PLEN | PASSWD | - // +----+------+----------+------+----------+ - // | 1 | 1 | 1 to 255 | 1 | 1 to 255 | - // +----+------+----------+------+----------+ - // - // The VER field contains the current version of the subnegotiation, - // which is X'01'. The ULEN field contains the length of the UNAME field - // that follows. The UNAME field contains the username as known to the - // source operating system. The PLEN field contains the length of the - // PASSWD field that follows. The PASSWD field contains the password - // association with the given UNAME. - // - unsigned int uPass = (unsigned int)m_pProxy->passLen(); - unsigned int uUser = (unsigned int)m_pProxy->userLen(); - - if(uPass > 255) - uPass = 255; - - if(uUser > 255) - uUser = 255; - - int iLen = uPass + uUser + 3; - char * pcBufToSend = new char[iLen]; - - //version x'01' - pcBufToSend[0] = (unsigned char)1; - - //length of the username - pcBufToSend[1] = (unsigned char)uUser; - - //username - KviMemory::move((void *)(pcBufToSend + 2),(void *)m_pProxy->user().toUtf8().data(),uUser); - - //length of the password - pcBufToSend[2 + uUser] = (unsigned char)uPass; - KviMemory::move((void *)(pcBufToSend + 3 + uUser),(void *)m_pProxy->pass().toUtf8().data(),uPass); - - // spit out the buffer and wait - setState(ProxyUserPassV5); - sendRawData(pcBufToSend,iLen); - delete[] pcBufToSend; - // and wait for response... -} - -void KviIrcSocket::proxySendTargetDataV5() -{ - // Once the method-dependent subnegotiation has completed, the client - // sends the request details. If the negotiated method includes - // encapsulation for purposes of integrity checking and/or - // confidentiality, these requests MUST be encapsulated in the method- - // dependent encapsulation. - // - // The SOCKS request is formed as follows: - // - // +----+-----+------+------+----------+----------+ - // |VER | CMD | FLAG | ATYP | DST.ADDR | DST.PORT | - // +----+-----+------+------+----------+----------+ - // | 1 | 1 | 1 | 1 | Variable | 2 | - // +----+-----+------+------+----------+----------+ - // - // Where: - // - // o VER protocol version: X'05' - // o CMD - // o CONNECT X'01' - // o BIND X'02' - // o UDP ASSOCIATE X'03' - // o X'04' to X'7F' IANA ASSIGNED - // o X'80' to X'FF' RESERVED FOR PRIVATE METHODS - // o FLAG command dependent flag (defaults to X'00') - // o ATYP address type of following address - // o IP V4 address: X'01' - // o DOMAINNAME: X'03' - // o IP V6 address: X'04' - // o DST.ADDR desired destination address - // o DST.PORT desired destination port in network octet - // order - // - // The SOCKS server will typically evaluate the request based on - // source and destination addresses, and return one or more reply - // messages, as appropriate for the request type. - // - // In an address field (DST.ADDR, BND.ADDR), the ATYP field specifies - // the type of address contained within the field: - // - // o X'01' - // - // The address is a version-4 IP address, with a length of 4 octets. - // - // o X'03' - // - // The address field contains a fully-qualified domain name. The first - // octet of the address field contains the number of octets of name that - // follow, there is no terminating NUL octet. - // - // o X'04' - // - // The address is a version-6 IP address, with a length of 16 octets. - bool bRemoteDns=!( - ( - KviNetUtils::isValidStringIp(m_pIrcServer->ip()) - #ifdef COMPILE_IPV6_SUPPORT - || KviNetUtils::isValidStringIPv6(m_pIrcServer->ip()) - #endif - ) - - && m_pIrcServer->cacheIp() - ); - int iBufLen = bRemoteDns ? 4 + 1 + m_pIrcServer->hostName().toUtf8().length() + 2 - : (m_pIrcServer->isIPv6() ? 22 : 10); - char * pcBufToSend = (char *)KviMemory::allocate(sizeof(char) * iBufLen); - pcBufToSend[0] = (unsigned char)5; //Proto 5 - pcBufToSend[1] = (unsigned char)1; //CONNECT - pcBufToSend[2] = (unsigned char)0; //RSV - - if(bRemoteDns) - { - bRemoteDns = true; - pcBufToSend[3] = 3; - pcBufToSend[4] = m_pIrcServer->hostName().toUtf8().length(); - } else { - pcBufToSend[3] = (unsigned char)m_pIrcServer->isIPv6() ? 4 : 1; // IPv6 : IPv4 - } - - if(bRemoteDns) - { - KviMemory::move((void *)(pcBufToSend + 5), - (void *)(m_pIrcServer->hostName().toUtf8().data()), - m_pIrcServer->hostName().toUtf8().length()); - quint16 port = (quint16)htons(m_pIrcServer->port()); - KviMemory::move((void *)(pcBufToSend + 4 + 1 + m_pIrcServer->hostName().toUtf8().length()),(void *)&port,2); - } else if(m_pIrcServer->isIPv6()) { -#ifdef COMPILE_IPV6_SUPPORT - struct in6_addr ircInAddr; - - if(!KviNetUtils::stringIpToBinaryIp_V6(m_pIrcServer->ip(),&ircInAddr)) - qDebug("SOCKET INTERNAL ERROR IN IPV6 ADDR CONVERSION"); - KviMemory::move((void *)(pcBufToSend + 4),(void *)(&ircInAddr),4); - quint16 port = (quint16)htons(m_pIrcServer->port()); - KviMemory::move((void *)(pcBufToSend + 20),(void *)&port,2); -#endif - } else { - struct in_addr ircInAddr; - - if(!KviNetUtils::stringIpToBinaryIp(m_pIrcServer->ip(),&ircInAddr)) - qDebug("SOCKET INTERNAL ERROR IN IPV4 ADDR CONVERSION"); - quint32 host = (quint32)ircInAddr.s_addr; - KviMemory::move((void *)(pcBufToSend + 4),(void *)&host,4); - quint16 port = (quint16)htons(m_pIrcServer->port()); - KviMemory::move((void *)(pcBufToSend + 8),(void *)&port,2); - } - - // send it into hyperspace... - setState(ProxyFinalV5); - sendRawData(pcBufToSend,iBufLen); - KviMemory::free(pcBufToSend); - // and wait for reply... -} - -void KviIrcSocket::proxyHandleV5AuthReply(unsigned char cReply) -{ - // The server verifies the supplied UNAME and PASSWD, and sends the - // following response: - // - // +----+--------+ - // |VER | STATUS | - // +----+--------+ - // | 1 | 1 | - // +----+--------+ - // - // A STATUS field of X'00' indicates success. If the server returns a - // `failure' (STATUS value other than X'00') status, it MUST close the - // connection. - // - if(cReply == 0) - { - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("Proxy response: auth OK: access granted")); - proxySendTargetDataV5(); - return; - } - raiseError(KviError_proxyAuthFailed); - reset(); -} - -void KviIrcSocket::proxyHandleV5MethodReply(unsigned char cReply) -{ - // The server selects from one of the methods given in METHODS, and - // sends a METHOD selection message: - // - // +----+--------+ - // |VER | METHOD | - // +----+--------+ - // | 1 | 1 | - // +----+--------+ - // - // If the selected METHOD is X'FF', none of the methods listed by the - // client are acceptable, and the client MUST close the connection. - // - // The values currently defined for METHOD are: - // - // o X'00' NO AUTHENTICATION REQUIRED - // o X'01' GSSAPI - // o X'02' USERNAME/PASSWORD - // o X'03' CHAP - // o X'04' to X'7F' IANA ASSIGNED - // o X'80' to X'FE' RESERVED FOR PRIVATE METHODS - // o X'FF' NO ACCEPTABLE METHODS - // - if(cReply == 0) - { - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("Proxy response: Auth method OK: using method 0 (no auth)")); - proxySendTargetDataV5(); - return; - } - - if(cReply == 2) - { - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("Proxy response: Auth method OK: using method 2 (user/pass)")); - proxyAuthUserPassV5(); - return; - } - - //Request rejected - if(cReply == 0xFF) - { - raiseError(KviError_proxyNoAcceptableAuthMethod); - reset(); - } else { - // unrecognized... - raiseError(KviError_unrecognizedProxyReply); - reset(); - } -} - -void KviIrcSocket::proxyHandleV5FinalReply(unsigned char cReply) -{ - // - // The SOCKS request information is sent by the client as soon as it has - // established a connection to the SOCKS server, and completed the - // authentication negotiations. The server evaluates the request, and - // returns a reply formed as follows: - // - // +----+-----+------+------+----------+----------+ - // |VER | REP | FLAG | ATYP | BND.ADDR | BND.PORT | - // +----+-----+------+------+----------+----------+ - // | 1 | 1 | 1 | 1 | Variable | 2 | - // +----+-----+------+------+----------+----------+ - // - // Where: - // o VER protocol version: X'05' - // o REP Reply field: - // o X'00' succeeded - // o X'01' general SOCKS server failure - // o X'02' connection not allowed by ruleset - // o X'03' Network unreachable - // o X'04' Host unreachable - // o X'05' Connection refused - // o X'06' TTL expired - // o X'07' Command not supported - // o X'08' Address type not supported - // o X'09' Invalid address - // o X'0A' to X'FF' unassigned - // o FLAG command dependent flag - // o ATYP address type of following address - // o IP V4 address: X'01' - // o DOMAINNAME: X'03' - // o IP V6 address: X'04' - // o BND.ADDR server bound address - // o BND.PORT server bound port in network octet order - // - if(cReply == 0) - { - // Request granted - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("Proxy response: target data OK: request granted")); - connectedToIrcServer(); - } else { - //Request rejected - int iErr; - switch(cReply) - { - case 1: iErr = KviError_proxyReply01GeneralSOCKSFailure; break; - case 2: iErr = KviError_proxyReply02ConnectionNotAllowed; break; - case 3: iErr = KviError_proxyReply03NetworkUnreachable; break; - case 4: iErr = KviError_proxyReply04HostUnreachable; break; - case 5: iErr = KviError_proxyReply05ConnectionRefused; break; - case 6: iErr = KviError_proxyReply06TTLExpired; break; - case 7: iErr = KviError_proxyReply07CommandNotSupported; break; - case 8: iErr = KviError_proxyReply08AddressTypeNotSupported; break; - case 9: iErr = KviError_proxyReply09InvalidAddress; break; - default: iErr = KviError_unrecognizedProxyReply; break; - } - raiseError(iErr); - reset(); - } -} - -void KviIrcSocket::proxyHandleV4FinalReply(unsigned char cReply) -{ - // If the request is granted, the SOCKS - // server makes a connection to the specified port of the destination host. - // A reply packet is sent to the client when this connection is established, - // or when the request is rejected or the operation fails. - // - // - // +----+----+----+----+----+----+----+----+ - // | VN | CD | DSTPORT | DSTIP | - // +----+----+----+----+----+----+----+----+ - // # of bytes: 1 1 2 4 - // - // VN is the version of the reply code and should be 0. CD is the result - // code with one of the following values: - // - // 90: request granted - // 91: request rejected or failed - // 92: request rejected becasue SOCKS server cannot connect to - // identd on the client - // 93: request rejected because the client program and identd - // report different user-ids - // - // The remaining fields are ignored. - // - // The SOCKS server closes its connection immediately after notifying - // the client of a failed or rejected request. For a successful request, - // the SOCKS server gets ready to relay traffic on both directions. This - // enables the client to do I/O on its connection as if it were directly - // connected to the application server. - if(cReply == 90) - { - // Request granted - if(_OUTPUT_VERBOSE) - outputProxyMessage(__tr2qs("Proxy response: target data OK: request granted")); - connectedToIrcServer(); - } else { - //Request rejected - int iErr; - switch(cReply) - { - case 91: iErr = KviError_proxyReply91RequestFailed; break; - case 92: iErr = KviError_proxyReply92IdentFailed; break; - case 93: iErr = KviError_proxyReply93IdentNotMatching; break; - default: iErr = KviError_unrecognizedProxyReply; break; - } - raiseError(iErr); - reset(); - } - // Just looked out of the window... - // Hmmmm...strange light outside... - // Looked at the clock...6:34 ! - // I think I'll go sleep.... :) -} - -void KviIrcSocket::proxyHandleHttpFinalReply(const char * pcBuffer, int) -{ - // Escape character is '^]'. - // CONNECT warszawa.irc.pl:6667 HTTP/1.0 - // - // HTTP/1.0 200 Connection established - - KviCString szTmp = pcBuffer; - // FIXME: #warning "We could even show the proxy output here...!" - szTmp.cutFromFirst('\n'); - szTmp.trimmed(); - - if(kvi_strEqualCIN(szTmp.ptr(),"HTTP",4)) - { - int iIdx = szTmp.findFirstIdx(" 200 "); - if(iIdx != -1) - { - if(iIdx == szTmp.findFirstIdx(' ')) - { - QString szMsg = __tr2qs("Proxy response: "); - szMsg += szTmp.ptr(); - if(_OUTPUT_VERBOSE) - outputProxyMessage(szMsg); - connectedToIrcServer(); - return; - } - } - } - - outputProxyError(__tr2qs("Proxy said something about: \n")); - outputProxyMessage(m_pConsole->decodeText(pcBuffer)); - - //Read HTTP error page and show it - - if(m_pWsn) - { - delete m_pWsn; - m_pWsn = 0; - } - - if(m_pRsn) - { - delete m_pRsn; - m_pRsn = 0; - } - - m_pRsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); - QObject::connect(m_pRsn,SIGNAL(activated(int)),this,SLOT(readHttpProxyErrorData(int))); - m_pRsn->setEnabled(true); - - setState(ProxyHttpError); - - //raiseError(KviError_proxyHttpFailure); - //reset(); -} - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// SSL HANDSHAKE -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - - -#ifdef COMPILE_SSL_SUPPORT -void KviIrcSocket::printSSLPeerCertificate() -{ - KviSSLCertificate * c = m_pSSL->getPeerCertificate(); - if(c) - { - //m_pConsole->socketEvent(SSLCertificate,(void *)c); - if(_OUTPUT_VERBOSE) - KviSSLMaster::printSSLCertificate(m_pConsole,__tr("Server X509 certificate"),c); - delete c; - } else { - if(_OUTPUT_VERBOSE) - outputSSLMessage(__tr2qs("The server didn't provide a certificate")); - } -} - -void KviIrcSocket::printSSLCipherInfo() -{ - KviSSLCipherInfo * ci = m_pSSL->getCurrentCipherInfo(); - if(ci) - { - //m_pConsole->socketEvent(SSLCipherInfo,(void *)ci); - KviSSLMaster::printSSLCipherInfo(m_pConsole,__tr("Current transmission cipher"),ci); - delete ci; - } else { - if(_OUTPUT_VERBOSE) - outputSSLMessage(__tr2qs("Unable to determine the current cipher")); - } -} - -void KviIrcSocket::raiseSSLError() -{ - KviCString szBuffer; - while(m_pSSL->getLastErrorString(szBuffer)) - { - outputSSLError(szBuffer.ptr()); - } -} -#endif // COMPILE_SSL_SUPPORT - -void KviIrcSocket::doSSLHandshake(int) -{ -#ifdef COMPILE_SSL_SUPPORT - KVI_ASSERT(m_pSSL); - - if(m_pRsn) - { - delete m_pRsn; - m_pRsn = 0; - } - - if(m_pWsn) - { - delete m_pWsn; - m_pWsn = 0; - } - - if(!m_pSSL) - { - qDebug("Ops... Have I lost the SSL class ?"); - reset(); - return; // ops ? - } - - // We avoid to reset() the socket while in a processData() call (see bug #600) - switch(m_pSSL->connect()) - { - case KviSSL::Success: - // done! - printSSLCipherInfo(); - printSSLPeerCertificate(); - linkUp(); - break; - case KviSSL::WantRead: - m_pRsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); - QObject::connect(m_pRsn,SIGNAL(activated(int)),this,SLOT(doSSLHandshake(int))); - m_pRsn->setEnabled(true); - break; - case KviSSL::WantWrite: - m_pWsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Write); - QObject::connect(m_pWsn,SIGNAL(activated(int)),this,SLOT(doSSLHandshake(int))); - m_pWsn->setEnabled(true); - break; - case KviSSL::RemoteEndClosedConnection: - raiseError(KviError_remoteEndClosedConnection); -// reset(); - break; - case KviSSL::SSLError: - raiseSSLError(); - raiseError(KviError_SSLError); -// reset(); - break; - case KviSSL::SyscallError: - { - // syscall problem - int iErr = kvi_socket_error(); - if(!kvi_socket_recoverableError(iErr)) - { - // Declare problems :) - raiseError((iErr ? KviError::translateSystemError(iErr) : KviError_unknownError)); - } else { - // can recover ? (EAGAIN, EINTR ?) - m_pWsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Write); - QObject::connect(m_pWsn,SIGNAL(activated(int)),this,SLOT(doSSLHandshake(int))); - m_pWsn->setEnabled(true); - return; - } -// reset(); - } - break; - default: - raiseError(KviError_SSLError); -// reset(); - break; - } - -#else //COMPILE_SSL_SUPPORT - qDebug("Ops.. SSL handshake without SSL support! Aborting!"); - exit(-1); -#endif //COMPILE_SSL_SUPPORT -} - -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// LINK UP -////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -void KviIrcSocket::linkUp() -{ - setState(Connected); - - // the last check - if(m_sock == KVI_INVALID_SOCKET) - return; // ops...disconnected in setState() ???? - - // ok.. it seems that we're really up and running now! - if(m_pWsn) - { - delete m_pWsn; - m_pWsn = 0; - } - - if(m_pRsn) - { - delete m_pRsn; - m_pRsn = 0; - } - - m_pRsn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); - QObject::connect(m_pRsn,SIGNAL(activated(int)),this,SLOT(readData(int))); - m_pRsn->setEnabled(true); - - // yahoo! -} - -void KviIrcSocket::readData(int) -{ - //read data - char cBuffer[1025]; - int iReadLength; -#ifdef COMPILE_SSL_SUPPORT - if(m_pSSL) - { - iReadLength = m_pSSL->read(cBuffer,1024); - if(iReadLength <= 0) - { - // ssl error....? - switch(m_pSSL->getProtocolError(iReadLength)) - { - case KviSSL::ZeroReturn: - iReadLength = 0; - break; - case KviSSL::WantRead: - case KviSSL::WantWrite: - // hmmm... - return; - break; - case KviSSL::SyscallError: - { - int iE = m_pSSL->getLastError(true); - if(iE != 0) - { - raiseSSLError(); - raiseError(KviError_SSLError); - reset(); - return; - } - } - break; - case KviSSL::SSLError: - raiseSSLError(); - raiseError(KviError_SSLError); - reset(); - return; - break; - default: - raiseError(KviError_SSLError); - reset(); - return; - break; - - } - handleInvalidSocketRead(iReadLength); - return; - } - } else { -#endif - iReadLength = kvi_socket_recv(m_sock,cBuffer,1024); - if(iReadLength <= 0) - { - handleInvalidSocketRead(iReadLength); - return; - } -#ifdef COMPILE_SSL_SUPPORT - } -#endif - - - //terminate our buffer - (*(cBuffer + iReadLength))='\0'; - - m_uReadBytes += iReadLength; - - // Shut up the socket notifier - // in case that we enter in a local loop somewhere - // while processing data... - m_pRsn->setEnabled(false); - // shut also the flushing of the message queue - // in this way we prevent disconnect detection - // during the processing of a message effectively - // making it always an asynchronous event. - m_bInProcessData = true; - - m_pLink->processData(cBuffer,iReadLength); - // after this line there should be nothing that relies - // on the "connected" state of this socket. - // It may happen that it has been reset() in the middle of the processData() call - // and (unverified) it might have been even deleted. - - // re-enable the socket notifier... (if it's still there) - if(m_pRsn) - m_pRsn->setEnabled(true); - // and the message queue flushing - m_bInProcessData = false; - // and flush the queue too! - if(m_pSendQueueHead) - flushSendQueue(); -} - -/* -void KviIrcSocket::processData(char * buffer,int) -{ - register char *p=buffer; - char *beginOfCurData = buffer; - int bufLen = 0; - char *messageBuffer = (char *)KviMemory::allocate(1); - - // Shut up the socket notifier - // in case that we enter in a local loop somewhere - // while processing data... - m_pRsn->setEnabled(false); - // shut also the flushing of the message queue - // in this way we prevent disconnect detection - // during the processing of a message effectively - // making it always an asynchronous event. - m_bInProcessData = true; - - while(*p) - { - if((*p == '\r' )||(*p == '\n')) - { - //found a CR or LF... - //prepare a message buffer - bufLen = p - beginOfCurData; - //check for previous unterminated data - if(m_uReadBufferLen > 0){ - KVI_ASSERT(m_pReadBuffer); - messageBuffer = (char *)KviMemory::reallocate(messageBuffer,bufLen + m_uReadBufferLen + 1); - KviMemory::move(messageBuffer,m_pReadBuffer,m_uReadBufferLen); - KviMemory::move((void *)(messageBuffer + m_uReadBufferLen),beginOfCurData,bufLen); - *(messageBuffer + bufLen + m_uReadBufferLen) = '\0'; - m_uReadBufferLen = 0; - KviMemory::free(m_pReadBuffer); - m_pReadBuffer = 0; - } else { - __range_invalid(m_pReadBuffer); - messageBuffer = (char *)KviMemory::reallocate(messageBuffer,bufLen + 1); - KviMemory::move(messageBuffer,beginOfCurData,bufLen); - *(messageBuffer + bufLen) = '\0'; - } - m_uReadPackets++; - - // FIXME: actually it can happen that the socket gets disconnected - // in a incomingMessage() call. - // The problem might be that some other parts of kvirc assume - // that the irc context still exists after a failed write to the socket - // (some parts don't even check the return value!) - // If the problem presents itself again then the solution is: - // disable queue flushing for the "incomingMessage" call - // and just call queue_insertMessage() - // then after the call terminates flush the queue (eventually detecting - // the disconnect and thus destroying the irc context). - // For now we try to rely on the remaining parts to handle correctly - // such conditions. Let's see... - - m_pConsole->incomingMessage(messageBuffer); - - if(m_state != Connected) - { - // Disconnected in KviConsole::incomingMessage() call. - // This may happen for several reasons (local event loop - // with the user hitting the disconnect button, a scripting - // handler event that disconnects explicitly) - // - // We handle it by simply returning control to readData() which - // will return immediately (and safely) control to Qt - KviMemory::free(messageBuffer); - m_bInProcessData = false; - return; - } - - while(*p && ((*p=='\r')||(*p=='\n')) )p++; - beginOfCurData = p; - - } else p++; - } - - //now *p == '\0' - //beginOfCurData points to '\0' if we have - //no more stuff to parse, or points to something - //different than '\r' or '\n'... - if(*beginOfCurData) - { - //Have remaining data...in the local buffer - bufLen = p - beginOfCurData; - if(m_uReadBufferLen > 0){ - //and there was more stuff saved... (really slow connection) - KVI_ASSERT(m_pReadBuffer); - m_pReadBuffer =(char *)KviMemory::reallocate(m_pReadBuffer,m_uReadBufferLen + bufLen); - KviMemory::move((void *)(m_pReadBuffer+m_uReadBufferLen),beginOfCurData,bufLen); - m_uReadBufferLen += bufLen; - } else { - // - __range_invalid(m_pReadBuffer); - m_uReadBufferLen = bufLen; - m_pReadBuffer =(char *)KviMemory::allocate(m_uReadBufferLen); - KviMemory::move(m_pReadBuffer,beginOfCurData,m_uReadBufferLen); - } - //The m_pReadBuffer contains at max 1 irc message... - //that can not be longer than 510 bytes (the message is not CRLF terminated) - // FIXME: Is this limit *really* valid on all servers ? - if(m_uReadBufferLen > 510)qDebug("WARNING : Receiving an invalid irc message from server."); - } - KviMemory::free(messageBuffer); - - // re-enable the socket notifier... - m_pRsn->setEnabled(true); - // and the message queue flushing - m_bInProcessData = false; - // and flush the queue too! - if(m_pSendQueueHead)flushSendQueue(); -} -*/ - -void KviIrcSocket::abort() -{ - // flush the send queue if possible (and if not yet disconnected in fact) - if(m_state == Connected) - flushSendQueue(); - if(m_state != Idle) - raiseError(KviError_operationAborted); - // and reset - reset(); -} - -void KviIrcSocket::handleInvalidSocketRead(int iReadLength) -{ - KVI_ASSERT(iReadLength <= 0); - if(iReadLength == 0) - { - raiseError(KviError_remoteEndClosedConnection); - reset(); - } else { - //check for transmission errors - int iErr = kvi_socket_error(); -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - if((iErr != EAGAIN) && (iErr != EINTR) && (iErr != WSAEWOULDBLOCK)) -#else - if((iErr != EAGAIN) && (iErr != EINTR)) -#endif - { - if(iErr > 0) - raiseError((KviError::translateSystemError(iErr))); - else - raiseError(KviError_remoteEndClosedConnection); - reset(); - } //else transient error...wait again... - } -} - -void KviIrcSocket::queue_insertMessage(KviIrcSocketMsgEntry * pMsg) -{ - KVI_ASSERT(pMsg); - - pMsg->next_ptr = 0; - - if(m_pSendQueueHead) - { - m_pSendQueueTail->next_ptr = pMsg; - m_pSendQueueTail = pMsg; - } else { - m_pSendQueueHead = pMsg; - m_pSendQueueTail = pMsg; - } -} - -void KviIrcSocket::free_msgEntry(KviIrcSocketMsgEntry * e) -{ - if(e->pData) - delete e->pData; - - e->pData = 0; - KviMemory::free(e); -} - -bool KviIrcSocket::queue_removeMessage() -{ - KVI_ASSERT(m_pSendQueueTail); - KVI_ASSERT(m_pSendQueueHead); - - if(m_pSendQueueHead->pData) - delete m_pSendQueueHead->pData; - - KviIrcSocketMsgEntry * pEntry = m_pSendQueueHead; - m_pSendQueueHead = pEntry->next_ptr; - KviMemory::free((void *)pEntry); - - if(m_pSendQueueHead == 0) - { - m_pSendQueueTail = 0; - return false; - } else return true; -} - -void KviIrcSocket::queue_removeAllMessages() -{ - if(m_pSendQueueHead) - while(queue_removeMessage()) {} -} - -void KviIrcSocket::queue_removePrivateMessages() -{ - KviIrcSocketMsgEntry * pPrevEntry = 0; - KviIrcSocketMsgEntry * pEntry = m_pSendQueueHead; - while(pEntry) - { - if(pEntry->pData->size() > 7) - { - if(kvi_strEqualCIN((char *)(pEntry->pData->data()),"PRIVMSG",7)) - { - // remove it - if(pPrevEntry) - { - pPrevEntry->next_ptr = pEntry->next_ptr; - if(!pPrevEntry->next_ptr) - m_pSendQueueTail = 0; - free_msgEntry(pEntry); - pEntry = pPrevEntry->next_ptr; - } else { - m_pSendQueueHead = pEntry->next_ptr; - if(!m_pSendQueueHead) - m_pSendQueueTail = 0; - free_msgEntry(pEntry); - pEntry = m_pSendQueueHead; - } - continue; - } - } - pPrevEntry = pEntry; - pEntry = pEntry->next_ptr; - } -} - -void KviIrcSocket::flushSendQueue() -{ - // If we're called from the flush timer, stop it - if(m_pFlushTimer->isActive()) - m_pFlushTimer->stop(); - - // Ok...have something to send... - KVI_ASSERT(m_state != Idle); - - struct timeval curTime; - - while(m_pSendQueueHead) - { - if(KVI_OPTION_BOOL(KviOption_boolLimitOutgoingTraffic)) - { - kvi_gettimeofday(&curTime,0); - - int iTimeDiff = curTime.tv_usec - m_tAntiFloodLastMessageTime.tv_usec; - iTimeDiff += (curTime.tv_sec - m_tAntiFloodLastMessageTime.tv_sec) * 1000000; - - if(((unsigned int)iTimeDiff) < KVI_OPTION_UINT(KviOption_uintOutgoingTrafficLimitUSeconds)) - { - // need to wait for a while.... - m_pFlushTimer->start(((KVI_OPTION_UINT(KviOption_uintOutgoingTrafficLimitUSeconds) - iTimeDiff) / 1000) + 1); - return; - } // else can send - } - // Write one data buffer... - int iResult; -#ifdef COMPILE_SSL_SUPPORT - if(m_pSSL) - { - iResult = m_pSSL->write((char *)(m_pSendQueueHead->pData->data()),m_pSendQueueHead->pData->size()); - } else { -#endif - iResult = kvi_socket_send(m_sock,(char *)(m_pSendQueueHead->pData->data()),m_pSendQueueHead->pData->size()); -#ifdef COMPILE_SSL_SUPPORT - } -#endif - if(iResult == (int)m_pSendQueueHead->pData->size()) - { - // Succesfull send...remove this data buffer - m_uSentPackets++; - m_uSentBytes += iResult; - //if(m_pConsole->hasMonitors())outgoingMessageNotifyMonitors((char *)(m_pSendQueueHead->pData->data()),result); - queue_removeMessage(); - if(KVI_OPTION_BOOL(KviOption_boolLimitOutgoingTraffic)) - { - m_tAntiFloodLastMessageTime.tv_sec = curTime.tv_sec; - m_tAntiFloodLastMessageTime.tv_usec = curTime.tv_usec; - } - // And try next buffer... - continue; - } else { - // Something wrong ? -#ifdef COMPILE_SSL_SUPPORT - if(iResult <= 0) - { - if(m_pSSL) - { - // ops...might be an SSL error - switch(m_pSSL->getProtocolError(iResult)) - { - case KviSSL::WantWrite: - case KviSSL::WantRead: - // Async continue... - m_pFlushTimer->start(KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout)); - return; - break; - case KviSSL::SyscallError: - if(iResult == 0) - { - raiseSSLError(); - raiseError(KviError_remoteEndClosedConnection); - reset(); - return; - } else { - int iSSLErr = m_pSSL->getLastError(true); - if(iSSLErr != 0) - { - raiseSSLError(); - raiseError(KviError_SSLError); - reset(); - return; - } else { - goto handle_system_error; - } - } - break; - case KviSSL::SSLError: - raiseSSLError(); - raiseError(KviError_SSLError); - reset(); - return; - break; - default: - raiseError(KviError_SSLError); - reset(); - return; - break; - } - } - } else { -#else // COMPILE_SSL_SUPPORT - if(iResult >= 0) - { - if(iResult > 0) - { -#endif // COMPILE_SSL_SUPPORT - - // Partial send...need to finish it later - m_pSendQueueHead->pData->remove(iResult); - - m_uSentBytes += iResult; - if(_OUTPUT_VERBOSE) - outputSocketWarning(__tr2qs("Partial socket write: packet broken into smaller pieces.")); -#ifndef COMPILE_SSL_SUPPORT - } -#endif // COMPILE_SSL_SUPPORT - // Async continue... - m_pFlushTimer->start(KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout)); - return; - } - -handle_system_error: - // Oops...error ? - int iErr = kvi_socket_error(); -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - if((iErr == EAGAIN) || (iErr == EINTR) || (iErr == WSAEWOULDBLOCK)) -#else - if((iErr == EAGAIN)||(iErr == EINTR)) -#endif - { - // Transient error...partial send as before... - if(_OUTPUT_VERBOSE) - outputSocketWarning(__tr2qs("Partial socket write: packet broken into smaller pieces.")); - // Async continue... - m_pFlushTimer->start(KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout)); - return; - } else { - // Disconnected... :( - raiseError((KviError::translateSystemError(iErr))); - reset(); - return; - } - } - } - //flushed completely ... -} - -bool KviIrcSocket::getLocalHostIp(QString & szIp, bool bIPv6) -{ - if(m_state != Connected) - return false; - - if(bIPv6) - { -#ifdef COMPILE_IPV6_SUPPORT - struct sockaddr_in6 name; - int iLen = sizeof(name); - if(!kvi_socket_getsockname(m_sock, (struct sockaddr *)&name,&iLen))return false; - //I assume that getsockname returns data in Network byte order... - //The man page misses to specify that... - if(!KviNetUtils::binaryIpToStringIp_V6(name.sin6_addr,szIp)) - return false; - - return true; -#else - return false; // no support -#endif - } - - struct sockaddr_in name; - int iLen = sizeof(name); - if(!kvi_socket_getsockname(m_sock, (struct sockaddr *)&name,&iLen)) - return false; - //I assume that getsockname returns data in Network byte order... - //The man page misses to specify that... - if(!KviNetUtils::binaryIpToStringIp(name.sin_addr,szIp)) - return false; - - return true; -} - -/* -bool KviIrcSocket::sendFmtData(const char *fmt,...) -{ - if(m_state != Connected)return false; - //new buffer - KviIrcSocketMsgEntry *ptr = (KviIrcSocketMsgEntry *)KviMemory::allocate(sizeof(KviIrcSocketMsgEntry)); - ptr->pData = new KviDataBuffer(512); - kvi_va_list(list); - kvi_va_start(list,fmt); - bool bTruncated; - //sprintf the buffer up to 512 chars (adds a CRLF too) - int iLen = kvi_irc_vsnprintf((char *)(ptr->pData->data()),fmt,list,&bTruncated); - kvi_va_end(list); - //adjust the buffer size - if(iLen < 512)ptr->pData->resize(iLen); - if(bTruncated) - { - if(_OUTPUT_VERBOSE) - outputSocketWarning(__tr2qs("Socket message truncated to 512 bytes.")); - } - - queue_insertMessage(ptr); - if(!m_bInProcessData)flushSendQueue(); - return (m_state != Idle); -} -*/ -/* -bool KviIrcSocket::sendData(const char *buffer,int buflen) -{ - if(m_state != Connected)return false; - //new buffer - KviIrcSocketMsgEntry *ptr = (KviIrcSocketMsgEntry *)KviMemory::allocate(sizeof(KviIrcSocketMsgEntry)); - if(buflen < 0)buflen = strlen(buffer); - if(buflen > 510) - { - buflen = 510; - if(_OUTPUT_VERBOSE) - outputSocketWarning(__tr2qs("Socket message truncated to 512 bytes.")); - } - ptr->pData = new KviDataBuffer(buflen + 2); - KviMemory::move(ptr->pData->data(),buffer,buflen); - *(ptr->pData->data()+buflen)='\r'; - *(ptr->pData->data()+buflen+1)='\n'; - - queue_insertMessage(ptr); - if(!m_bInProcessData)flushSendQueue(); - return (m_state != Idle); -} -*/ - -bool KviIrcSocket::sendRawData(const char * pcBuffer, int iBuflen) -{ - if((m_state == Idle) || (m_state == Connecting)) - return false; - - //new buffer - KviIrcSocketMsgEntry * pEntry = (KviIrcSocketMsgEntry *)KviMemory::allocate(sizeof(KviIrcSocketMsgEntry)); - pEntry->pData = new KviDataBuffer(iBuflen); - - KviMemory::move(pEntry->pData->data(),pcBuffer,iBuflen); - queue_insertMessage(pEntry); - - if(!m_bInProcessData) - flushSendQueue(); - - return (m_state != Idle); -} - -bool KviIrcSocket::sendPacket(KviDataBuffer * pData) -{ - if(m_state != Connected) - { - delete pData; - pData = 0; - return false; - } - - KviIrcSocketMsgEntry * pEntry = (KviIrcSocketMsgEntry *)KviMemory::allocate(sizeof(KviIrcSocketMsgEntry)); - pEntry->pData = pData; - queue_insertMessage(pEntry); - - if(!m_bInProcessData) - flushSendQueue(); - - return (m_state != Idle); -} diff --git a/src/kvirc/kernel/kvi_ircsocket.h b/src/kvirc/kernel/kvi_ircsocket.h deleted file mode 100644 index face64d84..000000000 --- a/src/kvirc/kernel/kvi_ircsocket.h +++ /dev/null @@ -1,520 +0,0 @@ -#ifndef _KVI_IRCSOCKET_H_ -#define _KVI_IRCSOCKET_H_ -//============================================================================= -// -// File : kvi_ircsocket.h -// Creation date : Tue Jul 30 19:25:17 2002 GMT by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_ircsocket.h -* \author Szymon Stefanek -* \brief Lower stack protocol for IRC connection -*/ - -#include "kvi_settings.h" -#include "KviCString.h" -#include "kvi_sockettype.h" -#include "KviTimeUtils.h" -#include "KviPointerList.h" - -#include - -class QTimer; -class QSocketNotifier; -class KviIrcServer; -class KviProxy; -class KviIrcConnection; -class KviIrcConnectionTarget; -class KviIrcLink; -class KviSSL; -class KviConsole; -class KviDataBuffer; - -/** -* \typedef KviIrcSocketMsgEntry -* \struct _KviIrcSocketMsgEntry -* \brief Holds the messages entries -*/ -typedef struct _KviIrcSocketMsgEntry -{ - KviDataBuffer * pData; - struct _KviIrcSocketMsgEntry * next_ptr; -} KviIrcSocketMsgEntry; - -/** -* \class KviIrcSocket -* \brief This class is the lowest level of the KVIrc networking stack -* -* It sends and receives raw data packets from the underlying system socket. -* It should output only verbose "progress" messages. -*/ -class KVIRC_API KviIrcSocket : public QObject -{ - Q_OBJECT -public: - /** - * \brief Constructs the IRC socket object - * \param pLink The middle networking stack class - * \return KviIrcSocket - */ - KviIrcSocket(KviIrcLink * pLink); - - /** - * \brief Destroys the IRC socket object - */ - ~KviIrcSocket(); -public: - /** - * \enum SocketState - */ - enum SocketState { - Idle, /**< Socket idling */ - Connecting, /**< Socket connecting */ - ProxyLogin, /**< Socket loggin in to a proxy */ - ProxyHttpError, /**< Socket error on http proxy */ - Connected, /**< Socket connected */ - ProxyFinalV4, /**< Socket received the final proxy v4 reply */ - ProxyFinalV5, /**< Socket received the final proxy v5 reply */ - ProxyFinalHttp, /**< Socket received the final proxy http reply */ - ProxySelectAuthMethodV5, /**< Socket received v5 method select reply */ - ProxyUserPassV5, /**< Socket received user/pass reply */ - SSLHandshake /**< Socket is doing the SSL handshake */ - }; -protected: - unsigned int m_uId; - KviIrcLink * m_pLink; - KviConsole * m_pConsole; - kvi_socket_t m_sock; - SocketState m_state; - QSocketNotifier * m_pWsn; - QSocketNotifier * m_pRsn; - KviIrcServer * m_pIrcServer; - KviProxy * m_pProxy; - QTimer * m_pTimeoutTimer; - unsigned int m_uReadBytes; - unsigned int m_uSentBytes; - int m_iLastError; - unsigned int m_uSentPackets; - KviIrcSocketMsgEntry * m_pSendQueueHead; - KviIrcSocketMsgEntry * m_pSendQueueTail; - QTimer * m_pFlushTimer; - struct timeval m_tAntiFloodLastMessageTime; - bool m_bInProcessData; -#ifdef COMPILE_SSL_SUPPORT - KviSSL * m_pSSL; -#endif -public: - /** - * \brief Returns the console - * \return KviConsole * - */ - KviConsole * console(){ return m_pConsole; }; - - /** - * \brief Returns the link - * \return KviIrcLink * - */ - KviIrcLink * link(){ return m_pLink; }; - - /** - * \brief Returns the state of the socket - * \return SocketState - */ - SocketState state(){ return m_state; }; - - /** - * \brief Returns the last error - * \return int - */ - int lastError(){ return m_iLastError; }; - - /** - * \brief Returns the id of the socket - * \return unsigned int - */ - unsigned int id(){ return m_uId; }; - - /** - * \brief Returns true if the socket is a Secure Socket Layer (SSL) - * \return bool - */ -#ifdef COMPILE_SSL_SUPPORT - bool usingSSL(){ return m_pSSL; }; -#else - bool usingSSL(){ return false; }; -#endif - - /** - * \brief Returns the number of bytes read - * \return unsigned int - */ - unsigned int readBytes(){ return m_uReadBytes; }; - - /** - * \brief Returns the number of bytes sent - * \return unsigned int - */ - unsigned int sentBytes(){ return m_uSentBytes; }; - - /** - * \brief Returns the number of packets sent - * \return unsigned int - */ - unsigned int sentPackets(){ return m_uSentPackets; }; - //unsigned int readPackets(){ return m_uReadPackets; }; - - /** - * \brief Returns true if the socket is connected - * \return bool - */ - bool isConnected(){ return m_state == Connected; }; - - /** - * \brief Starts the connection - * \param pServer The server where to connect to - * \param pProxy The proxy to use during connection - * \param pcBindAddress The address to bind the connection to - * \return int - */ - int startConnection(KviIrcServer * pServer, KviProxy * pProxy = 0, const char * pcBindAddress = 0); - -#ifdef COMPILE_SSL_SUPPORT - /** - * \brief Called to enter SSL connection mode. - * - * It can be called either internally or from outside - * \return void - */ - void enterSSLMode(); -#endif // COMPILE_SSL_SUPPORT - - /** - * \brief Returns true if the packet is sent to the socket - * \param pData The source data packet - * \return bool - */ - bool sendPacket(KviDataBuffer * pData); - - /** - * \brief Aborts the connection - * \return void - */ - void abort(); - - /** - * \brief Gets the localhost IP - * \param szIp The source IP address - * \param bIPv6 Whether to use IPv6 sockets - * \return bool - */ - bool getLocalHostIp(QString & szIp, bool bIPv6); - - /** - * Clears the output queue - */ - void clearOutputQueue(bool bPrivateMessagesOnly); - -protected: - -#ifdef COMPILE_SSL_SUPPORT - /** - * \brief Raises an SSL error - * \return void - */ - void raiseSSLError(); - - /** - * \brief Prints the SSL certificate of the peer - * \return void - */ - void printSSLPeerCertificate(); - - /** - * \brief Prints the SSL cipher used - * \return void - */ - void printSSLCipherInfo(); -#endif // COMPILE_SSL_SUPPORT - - /** - * \brief Sends raw data to the socket - * \param pcBuffer The data buffer - * \param iBufLen The size of the buffer - * \return bool - */ - bool sendRawData(const char * pcBuffer, int iBufLen); - - /** - * \brief Raises an error - * \param iError The error to raise - * \return void - */ - void raiseError(int iError); - - /** - * \brief Called when the connection has been estabilished - * - * If it's a proxy we need to perform the login operations, otherwise - * we're connected to the irc server - * \return void - */ - void connectionEstabilished(); - - /** - * \brief Called when the connection to the proxy has been established - * \return void - */ - void connectedToProxy(); - - /** - * \brief Called when the connection to the irc server has been established - * \return void - */ - void connectedToIrcServer(); - - /** - * \brief Called to login to an HTTP proxy - * \return void - */ - void proxyLoginHttp(); - - /** - * \brief Called to login to a SOCKSv4 proxy - * \return void - */ - void proxyLoginV4(); - - /** - * \brief Called to login to a SOCKSv5 proxy - * \return void - */ - void proxyLoginV5(); - - /** - * \brief Starts the negotiation of user/pass for the proxy - * \return void - */ - void proxyAuthUserPassV5(); - - /** - * \brief Sends the request details - * \return void - */ - void proxySendTargetDataV5(); - - /** - * \brief Gets the authentication reply and handles it - * \param cReply The proxy reply - * \return void - */ - void proxyHandleV5AuthReply(unsigned char cReply); - - /** - * \brief Gets the method selection reply and handles it - * \param cReply The proxy reply - * \return void - */ - void proxyHandleV5MethodReply(unsigned char cReply); - - /** - * \brief Gets the final SOCKSv5 reply and handles it - * \param cReply The proxy reply - * \return void - */ - void proxyHandleV5FinalReply(unsigned char cReply); - - /** - * \brief Gets the final SOCKSv4 reply and handles it - * \param cReply The proxy reply - * \return void - */ - void proxyHandleV4FinalReply(unsigned char cReply); - - /** - * \brief Gets the final HTTP reply and handles it - * \param pcBuffer The buffer containing the proxy reply - * \param iBufLen Size of the buffer containing the proxy reply - * \return void - */ - void proxyHandleHttpFinalReply(const char * pcBuffer, int iBufLen); - - /** - * \brief Connection established. Sets the link up - * \return void - */ - void linkUp(); - - /** - * \brief Checks if the socket error is a transient error - * - * If it is not a transient error it resets the socket and fires the - * appropriate event. - * Otherwise it does nothing. - * \param iReadLength The number of bytes read - * \return void - */ - void handleInvalidSocketRead(int iReadLength); - - /** - * \brief Resets the connection - * \return void - */ - virtual void reset(); - - /** - * \brief Removes the message entry - * \param e The entry - * \return void - */ - void free_msgEntry(KviIrcSocketMsgEntry * e); - - /** - * \brief Appends a KviIrcSocketMsgEntry to the tail of the message queue. - * - * The pMsg for this message is set to 0. - * \param pMsg The message to append to the queue - * \return void - */ - virtual void queue_insertMessage(KviIrcSocketMsgEntry * pMsg); - - /** - * \brief Removes a message from the head of the queue. - * \return bool - */ - bool queue_removeMessage(); - - /** - * \brief Removes all messages from the queue. - * \return void - */ - void queue_removeAllMessages(); - - /** - * \brief Removes private messages from the queue. - * \return void - */ - void queue_removePrivateMessages(); - - /** - * \brief Sets the state of the socket - * \param state The state :) - * \return void - */ - virtual void setState(SocketState state); -private: - /** - * \brief Outputs a SSL message - * \param szMsg The message :) - * \return void - */ - void outputSSLMessage(const QString & szMsg); - - /** - * \brief Outputs a SSL error - * \param szMsg The message :) - * \return void - */ - void outputSSLError(const QString & szMsg); - - /** - * \brief Outputs a proxy message - * \param szMsg The message :) - * \return void - */ - void outputProxyMessage(const QString & szMsg); - - /** - * \brief Outputs a proxy error - * \param szMsg The message :) - * \return void - */ - void outputProxyError(const QString & szMsg); - - /** - * \brief Outputs a socket message - * \param szMsg The message :) - * \return void - */ - void outputSocketMessage(const QString & szMsg); - - /** - * \brief Outputs a socket warning - * \param szMsg The message :) - * \return void - */ - void outputSocketWarning(const QString & szMsg); - - /** - * \brief Outputs a socket error - * \param szMsg The message :) - * \return void - */ - void outputSocketError(const QString & szMsg); -protected slots: - /** - * \brief Called when the connection timeouts - * \return void - */ - void connectionTimedOut(); - - /** - * \brief Called when the write notifier is enabled - * \return void - */ - void writeNotifierFired(int); - - /** - * \brief Called when the read notifier is enabled - * \return void - */ - void readData(int); - - /** - * \brief Called when the proxy read notifier is enabled - * \return void - */ - void readProxyData(int); - - /** - * \brief Called when the proxy read notifier encounters an error - * \return void - */ - void readHttpProxyErrorData(int); - - /** - * \brief Attempts to send as much as possible to the server - * - * If fails (happens only on really lagged servers) calls itself with a - * QTimer shot after KVI_OPTION_UINT(KviOption_uintSocketQueueFlushTimeout) - * ms to retry again... - * \return void - */ - void flushSendQueue(); - - /** - * \brief Starts the SSL handshake - * \return void - */ - void doSSLHandshake(int); -}; - -#endif //_KVI_IRCSOCKET_H_ diff --git a/src/kvirc/kernel/kvi_ircurl.cpp b/src/kvirc/kernel/kvi_ircurl.cpp deleted file mode 100644 index f227f4b09..000000000 --- a/src/kvirc/kernel/kvi_ircurl.cpp +++ /dev/null @@ -1,365 +0,0 @@ -//============================================================================= -// -// File : kvi_ircurl.cpp -// Creation date : Sun Mar 04 2001 14:20:12 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2001-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "KviCString.h" -#include "kvi_inttypes.h" -#include "KviQString.h" -#include "KviIrcServer.h" -#include "kvi_kvs_script.h" -#include "kvi_msgbox.h" -#include "kvi_channel.h" -#include "kvi_app.h" -#include "KviLocale.h" -#include "kvi_ircconnectiontarget.h" -#include "kvi_ircconnection.h" -#include "kvi_irccontext.h" -#include "kvi_console.h" -#include "kvi_frame.h" - -#define _KVI_IRCURL_CPP_ -#include "kvi_ircurl.h" - - -bool KviIrcUrl::parse(const char * url,KviCString &cmdBuffer,int contextSpec) -{ - // irc[6]://[:][/[?]] - KviCString szUrl = url; - //szUrl.replaceAll("$","\\$"); - //szUrl.replaceAll(";","\\;"); - bool bIPv6 = false; - bool bSSL = false; - KviCString szServer; - kvi_u32_t uPort = 0; - bool bGotPort = false; - if(kvi_strEqualCIN(szUrl.ptr(),"irc://",6)) - { - szUrl.cutLeft(6); - } else if(kvi_strEqualCIN(szUrl.ptr(),"irc6://",7)) - { - bIPv6 = true; - szUrl.cutLeft(7); - } else if(kvi_strEqualCIN(szUrl.ptr(),"ircs://",7)) - { - bSSL = true; - szUrl.cutLeft(7); - } else if(kvi_strEqualCIN(szUrl.ptr(),"ircs6://",8)) - { - bIPv6 = true; - bSSL = true; - szUrl.cutLeft(8); - } else return false; - - KviCString szServerAndPort; - - int idx = szUrl.findFirstIdx('/'); - if(idx != -1) - { - szServerAndPort = szUrl.left(idx); - szUrl.cutLeft(idx + 1); - } else { - szServerAndPort = szUrl; - szUrl = ""; - } - - if(szServerAndPort.isEmpty())return false; - - idx = szServerAndPort.findFirstIdx(':'); - - if(idx != -1) - { - szServer = szServerAndPort.left(idx); - szServerAndPort.cutLeft(idx + 1); - bool bOk; - uPort = szServerAndPort.toUInt(&bOk); - if(!bOk)uPort = 6667; - bGotPort = true; - } else { - szServer = szServerAndPort; - } - - cmdBuffer = "server "; - switch(contextSpec) - { - case KVI_IRCURL_CONTEXT_FIRSTFREE: - cmdBuffer.append("-u "); - break; - case KVI_IRCURL_CONTEXT_NEW: - cmdBuffer.append("-n "); - break; - } - if(bIPv6)cmdBuffer.append(" -i "); - if(bSSL)cmdBuffer.append(" -s "); - - if(szUrl.hasData()) - { - KviCString szChannel; - KviCString szPass; - - idx = szUrl.findFirstIdx('?'); - if(idx != -1) - { - szChannel = szUrl.left(idx); - szUrl.cutLeft(idx + 1); - szPass = szUrl; - } else { - szChannel = szUrl; - szPass = ""; - } - - if(!(szChannel.firstCharIs('#') || szChannel.firstCharIs('!') || szChannel.firstCharIs('&'))) - szChannel.prepend('#'); - - if(szPass.isEmpty())cmdBuffer.append(KviCString::Format," -c=\"join %s\" ",szChannel.ptr()); - else cmdBuffer.append(KviCString::Format," -c=\"join %s %s\" ",szChannel.ptr(),szPass.ptr()); - - } - - cmdBuffer.append(szServer); - if(bGotPort)cmdBuffer.append(KviCString::Format," %d",uPort); - - cmdBuffer.append(';'); - - return true; -} - -void KviIrcUrl::split(QString url, KviIrcUrlParts& result) -{ - // irc[s][6]://[:][/[?]][[,[?]] - - //defaults - result.bSsl=false; - result.bIPv6=false; - result.iPort = 6667; - result.iError=0; - - int iProtoLen = url.indexOf("://"); - if(iProtoLen!=-1) { - if(KviQString::equalCIN(url,"irc",3)) { - // OK, seems to be a valid proto; - url = url.right(url.length()-3); - if(KviQString::equalCIN(url,"s",1)) { - result.bSsl=true; - url = url.right(url.length()-1); - } - if(KviQString::equalCIN(url,"6",1)) { - result.bIPv6=true; - url = url.right(url.length()-1); - } - if(!KviQString::equalCIN(url,"://",3)) { - //irc(???):// proto?? - result.iError |= InvalidProtocol; - } - iProtoLen = url.indexOf("://"); - url = url.right(url.length()-iProtoLen-3); - } else { - result.iError |= InvalidProtocol; - } - } - //Ok, we understand a protocol.. Now we shuld find a server name:) - int iTmp; - iTmp = url.indexOf(':'); - if(iTmp!=-1) { - result.szHost = url.left(iTmp); - url = url.right(url.length()-iTmp-1); - // Accepted, now the time for the port:) - bool bOk; - if( (iTmp = url.indexOf('/')) != -1) { // any channels pending? - result.iPort = url.left(iTmp).toUInt(&bOk); - if(!bOk) { - result.iPort = 6667; - result.iError |= InvalidPort; - } - url = url.right(url.length()-iTmp-1); - } else { - result.iPort = url.toUInt(&bOk); - if(!bOk) { - result.iPort = 6667; - result.iError |= InvalidPort; - } - url = ""; - } - } else if( (iTmp = url.indexOf('/')) != -1) { // have channels?? - result.szHost = url.left(iTmp); - url = url.right(url.length()-iTmp-1); - } else { - result.szHost = url; - url = ""; - } - - //and, finally, channels:D - result.chanList = url.isEmpty()?QStringList():url.split(',',QString::SkipEmptyParts); - -} - -void KviIrcUrl::join(QString &uri, KviIrcServer* server) -{ - if(server) - { - uri="irc"; - - if(server->useSSL()) uri.append("s"); - if(server->isIPv6()) uri.append("6"); - - uri.append("://"); - uri.append(server->hostName()); - if(server->port()!=6667) uri.append(QString(":%1").arg(server->port())); - uri.append("/"); - } -} - -void KviIrcUrl::makeJoinCmd(const QStringList& chans, QString& szJoinCommand) -{ - QString szChannels,szProtectedChannels,szPasswords,szCurPass,szCurChan; - if(chans.count()!=0) - { - - for ( QStringList::ConstIterator it = chans.begin(); it != chans.end(); ++it ) { - - szCurPass=(*it).section('?',1); - if(szCurPass.isEmpty()) - { - if(!szChannels.isEmpty()) - szChannels.append(","); - szCurChan = (*it).section('?',0,0); - if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!')) - szCurChan.prepend('#'); - szChannels.append(szCurChan); - } else { - if(!szProtectedChannels.isEmpty()) - szProtectedChannels.append(","); - szCurChan = (*it).section('?',0,0); - if(!(szCurChan[0]=='#' || szCurChan[0]=='&' || szCurChan[0]=='!')) - szCurChan.prepend('#'); - szProtectedChannels.append(szCurChan); - if(!szPasswords.isEmpty()) - szPasswords.append(","); - szPasswords.append(szCurPass); - } - } - szJoinCommand = "JOIN "; - szJoinCommand.append(szProtectedChannels); - if(!szProtectedChannels.isEmpty() && !szChannels.isEmpty()) - szJoinCommand.append(','); - szJoinCommand.append(szChannels); - szJoinCommand.append(" "); - szJoinCommand.append(szPasswords); - } -} - -int KviIrcUrl::run(const QString& text,int contextSpec,KviConsole* pConsole) -{ - KviIrcUrlParts parts; - KviIrcUrl::split(text,parts); - QString cmdBuffer; - - if( (contextSpec & CurrentContext) && !pConsole) { - contextSpec = FirstFreeContext; - } - - if( (contextSpec & TryCurrentContext) && !pConsole) { - contextSpec = FirstFreeContext; - } - - if(contextSpec & FirstFreeContext) { - if(pConsole) { - if(pConsole->connectionInProgress()) - { - pConsole = g_pFrame->firstNotConnectedConsole(); - if(!pConsole) { - pConsole = g_pFrame->createNewConsole(); - } - } - } else { - pConsole = g_pFrame->firstNotConnectedConsole(); - if(!pConsole) { - pConsole = g_pFrame->createNewConsole(); - } - } - } - - if(!(parts.iError & KviIrcUrl::InvalidProtocol)) { - g_pApp->addRecentUrl(text); - - QString szJoinCommand; - makeJoinCmd(parts.chanList,szJoinCommand); - QString szCommand("server "); - if(parts.bSsl) szCommand.append("-s "); - if(parts.bIPv6) szCommand.append("-i "); - if(!szJoinCommand.isEmpty()){ - szCommand.append("-c=\""); - szCommand.append(szJoinCommand); - szCommand.append("\" "); - } - szCommand.append(QString("%1 %2 ").arg(parts.szHost).arg(parts.iPort)); - - if(pConsole->connection()) { - KviIrcServer* server = pConsole->connection()->target()->server(); - if( - ( server->hostName() != parts.szHost ) || - ( server->port() != parts.iPort ) || - ( server->useSSL() != parts.bSsl ) || - ( server->isIPv6() != parts.bIPv6) ) - { // New server, try to reconnect - KviKvsScript::run(szCommand,(contextSpec & TryCurrentContext) ? g_pFrame->createNewConsole() : pConsole); - return parts.iError; - } else { - // the same server, but probably new chanlist - QString tmp; - QString toPart; - for(KviChannel * c = pConsole->connection()->channelList()->first();c;c = pConsole->connection()->channelList()->next()) - { - tmp=c->target(); - if(c->hasChannelMode('k')) - { - tmp.append("?"); - tmp.append(c->channelModeParam('k')); - } - if(!parts.chanList.removeAll(tmp)) - { - toPart.append(c->target()); - toPart.append(","); - } - } - if(!(contextSpec & DoNotPartChans)) - { - makeJoinCmd(parts.chanList,szJoinCommand); - if(!toPart.isEmpty()) - { - toPart.prepend("part "); - KviKvsScript::run(toPart,pConsole); - } - } - if(!szJoinCommand.isEmpty()) - { - pConsole->connection()->sendData(pConsole->connection()->encodeText(szJoinCommand).data()); - } - return parts.iError; - } - } - // New server - KviKvsScript::run(szCommand,pConsole); - } - //!invalid proto - return parts.iError; -} diff --git a/src/kvirc/kernel/kvi_ircurl.h b/src/kvirc/kernel/kvi_ircurl.h deleted file mode 100644 index ddf281134..000000000 --- a/src/kvirc/kernel/kvi_ircurl.h +++ /dev/null @@ -1,79 +0,0 @@ -#ifndef _KVI_IRCURL_H_ -#define _KVI_IRCURL_H_ -//============================================================================= -// -// File : kvi_ircurl.h -// Creation date : Sun Mar 04 2001 14:22:55 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2001-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviCString.h" -#include "kvi_inttypes.h" - -class KviIrcServer; -class KviConsole; - -#include - -// Create /server -u commands (first free context) -#define KVI_IRCURL_CONTEXT_FIRSTFREE 0 -// Create /server -n commands (new irc context) -#define KVI_IRCURL_CONTEXT_NEW 1 -// Create /server commands (this irc context) -#define KVI_IRCURL_CONTEXT_THIS 2 - -typedef struct _KviIrcUrlParts { - QString szHost; - kvi_u32_t iPort; - bool bIPv6; - bool bSsl; - QStringList chanList; - int iError; - } KviIrcUrlParts; - -namespace KviIrcUrl -{ - - enum KviIrcUrlParserError { - InvalidProtocol = 1, - InvalidPort = 2, - NeedNewContext = 4 - }; - - enum KviIrcUrlContextSpec { - FirstFreeContext = 1, - NewContext = 2, - CurrentContext = 4, - TryCurrentContext = 8, - - DoNotPartChans = 16 - }; - - extern KVIRC_API bool parse(const char * url,KviCString &cmdBuffer,int contextSpec = KVI_IRCURL_CONTEXT_FIRSTFREE); - - extern KVIRC_API int run(const QString& url,int contextSpec = FirstFreeContext,KviConsole* pConsole = 0); - - extern KVIRC_API void split(QString url, KviIrcUrlParts& parts); - extern KVIRC_API void join(QString &url, KviIrcServer* server); - extern KVIRC_API void makeJoinCmd(const QStringList& chans, QString& szJoinCommand); -} - -#endif // _KVI_IRCURL_H_ diff --git a/src/kvirc/kernel/kvi_lagmeter.cpp b/src/kvirc/kernel/kvi_lagmeter.cpp deleted file mode 100644 index 053a77cf6..000000000 --- a/src/kvirc/kernel/kvi_lagmeter.cpp +++ /dev/null @@ -1,266 +0,0 @@ -//============================================================================= -// -// File : kvi_lagmeter.cpp -// Creation date : Fri Oct 18 13:31:36 CEST 1999 by Juanjo Álvarez -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 1999 Juanjo Álvarez -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_lagmeter.h" -#include "kvi_options.h" -#include "kvi_kvs_eventtriggers.h" -#include "KviParameterList.h" -#include "kvi_ircconnection.h" -#include "kvi_irccontext.h" -#include "kvi_frame.h" -#include "kvi_console.h" -#include "KviTimeUtils.h" -#include "kvi_ircconnectionuserinfo.h" -#include "kvi_ircconnectionserverinfo.h" -#include "kvi_out.h" -#include "KviLocale.h" - -KviLagMeter::KviLagMeter(KviIrcConnection * c) -: QObject() -{ - m_pConnection = c; - m_pCheckList = new KviPointerList; - m_pCheckList->setAutoDelete(true); - m_uLag = 0; - m_uLastEmittedLag = 0; - m_uLastReliability = 0; - m_tLastCompleted = 0; - m_tLastOwnCheck = 0; - m_tFirstOwnCheck = 0; - m_bOnAlarm = false; - m_pDeletionSignal = 0; - - // FIXME: We could use the KviIrcConnection::heartbeat() here! - if(KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) < 2000) - KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) = 2000; // kinda absurd - - if(KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) > 10000) - KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) = 10000; // kinda absurd - - startTimer(KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat)); // 5 seconds by default -} - -KviLagMeter::~KviLagMeter() -{ - if(m_pDeletionSignal)*m_pDeletionSignal = true; - delete m_pCheckList; -} - -unsigned int KviLagMeter::secondsSinceLastCompleted() -{ - struct timeval tv; - kvi_gettimeofday(&tv,0); - return tv.tv_sec - m_tLastCompleted; -} - -void KviLagMeter::timerEvent(QTimerEvent *) -{ - if(m_pConnection->state() != KviIrcConnection::Connected)return; // do nothing atm - - // If the lag has changed emit our signals - if((m_uLag / 10) != (m_uLastEmittedLag / 10)) - { - m_uLastEmittedLag = m_uLag; - g_pFrame->childConnectionLagChange(m_pConnection); - - KviCString szLag(KviCString::Format,"%u",m_uLag); - - bool bDeletionSignal = false; - m_pDeletionSignal = &bDeletionSignal; - - if((!m_bOnAlarm) && (m_uLag > KVI_OPTION_UINT(KviOption_uintLagAlarmTime))) - { - KVS_TRIGGER_EVENT_2_HALTED(KviEvent_OnLagAlarmTimeUp, - m_pConnection->console(),m_pConnection->serverInfo()->name(),QString(szLag.ptr())); - if(bDeletionSignal)return; // killed, probably by a quit -f -u - m_bOnAlarm = true; - } else if(m_bOnAlarm) - { - KVS_TRIGGER_EVENT_2_HALTED(KviEvent_OnLagAlarmTimeDown, - m_pConnection->console(),m_pConnection->serverInfo()->name(),QString(szLag.ptr())); - if(bDeletionSignal)return; // killed, probably by a quit -f -u - m_bOnAlarm = false; - } - - KVS_TRIGGER_EVENT_2_HALTED(KviEvent_OnLagCheck, - m_pConnection->console(),m_pConnection->serverInfo()->name(),QString(szLag.ptr())); - if(bDeletionSignal)return; // killed, probably by a quit -f -u - - m_pDeletionSignal = 0; - } - - // get current time - struct timeval tv; - kvi_gettimeofday(&tv,0); - unsigned int uDiff = tv.tv_sec - m_tLastCompleted; - unsigned int uHeartbeat = KVI_OPTION_UINT(KviOption_uintLagMeterHeartbeat) / 1000; - if(uHeartbeat < 2)uHeartbeat = 2; - // we keep the last lag value for an amount of time - // depending on its reliability. - // Since reliability ranges from 10 to 100 we keep the lags - // for (hrtbt * 4) + (reliability / 2) seconds (which means from 25 to 70 seconds by default) - if(uDiff <= ((uHeartbeat * 4) + (m_uLastReliability / 2)))return; // nothing to do, the actual value is accurate - - // the last completed check has been completed a lot of time ago - // do we have some checks on the queue ? - if(m_pCheckList->count() > 0) - { - // if the first registered check is not too outdated - // we wait a little more for it to return - KviLagCheck * c = m_pCheckList->first(); - if(c) - { - if((tv.tv_sec - c->lSecs) <= 10)return; - } - // the first check was registered more than 10 secs before - if(m_tLastOwnCheck > 0) - { - // hm.. we have already sent our own (reliable) check after the last completed - // make the lag grow (we're pretty sure it's growing) - uDiff = (tv.tv_sec - m_tFirstOwnCheck) * 1000; - if(m_uLag < uDiff)m_uLag = uDiff; // the lag grows for sure - uDiff = tv.tv_sec - m_tLastOwnCheck; - if(uDiff < (uHeartbeat * 4))return; // wait a bit...send own checks only every 20 secs (by default) at this point - } - } - // or we have no checks in the queue at all - // or it's really time to do something... - if(m_tFirstOwnCheck == 0) - { - if(_OUTPUT_PARANOIC) - m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Sending out PING based lag probe")); - - // this is the first our own lag check since the last succesfull one: use the ping - lagCheckRegister("@ping@",70); // the ping may be fooled easily - m_pConnection->sendFmtData("PING %s %s", - m_pConnection->encodeText( m_pConnection->userInfo()->nickName() ).data(), - m_pConnection->encodeText( m_pConnection->serverInfo()->name() ).data() ); - m_tFirstOwnCheck = tv.tv_sec; - } else { - if(_OUTPUT_PARANOIC) - m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Sending out CTCP based lag probe")); - - // we have already sent a ping but we got no reply - // try with another method... even if this will reset our idle time - KviCString tmp(KviCString::Format,"%d%d-yeah-:)",tv.tv_sec,tv.tv_usec); - lagCheckRegister(tmp.ptr(),100); // almost impossible to fool - m_pConnection->sendFmtData("NOTICE %s :%cLAGCHECK %s%c", - m_pConnection->encodeText( m_pConnection->userInfo()->nickName() ).data(), - 0x01, - tmp.ptr(), - 0x01); - } - m_tLastOwnCheck = tv.tv_sec; -} - -void KviLagMeter::lagCheckRegister(const char * key,unsigned int uReliability) -{ - if(uReliability < 10)return; // what the heck of a lag check is this ? - // store the lagcheck structure and just return - - if(_OUTPUT_PARANOIC) - m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Registered lag check with reliability %u (%s)"),uReliability,key); - - KviLagCheck * c = new KviLagCheck; - c->szKey = key; - struct timeval tv; - kvi_gettimeofday(&tv,0); - c->lSecs = tv.tv_sec; - c->lUSecs = tv.tv_usec; - c->uReliability = uReliability <= 100 ? uReliability : 100; - m_pCheckList->append(c); - while(m_pCheckList->count() > 30) - { - // we're fried :/ - // either our ping mechanism is not working - // or the server is stoned... - m_pCheckList->removeFirst(); - } -} - -bool KviLagMeter::lagCheckComplete(const char * key) -{ - // find this lag check - KviLagCheck * c; - for(c = m_pCheckList->first();c;c = m_pCheckList->next()) - { - if(kvi_strEqualCS(c->szKey.ptr(),key))break; - } - if(!c)return false; // not found - // kill any earlier lag checks (IRC is a sequential proto) - while(m_pCheckList->first() != c)m_pCheckList->removeFirst(); - - if(_OUTPUT_PARANOIC) - m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Lag check completed (%s)"),key); - - struct timeval tv; - kvi_gettimeofday(&tv,0); - - unsigned int uLag = ((tv.tv_sec - c->lSecs) * 1000); - if(tv.tv_usec < c->lUSecs)uLag -= ((c->lUSecs - tv.tv_usec) / 1000); - else uLag += ((tv.tv_usec - c->lUSecs) / 1000); - - // now check the reliability - - if(m_uLastReliability > c->uReliability) - { - // the actual data is more reliable than the new one :/ - // change the real lag only by a certain amount - // c->uRel : 100 = uLag : m_uLag - m_uLag = ((uLag * c->uReliability) + (m_uLag * m_uLastReliability)) / (c->uReliability + m_uLastReliability); - } else { - // the actual data is less reliable than the new one - m_uLag = uLag; - } - - m_tLastCompleted = tv.tv_sec; // now - m_tLastOwnCheck = 0; - m_tFirstOwnCheck = 0; - m_uLastReliability = c->uReliability; - - m_pCheckList->removeFirst(); - - return true; -} - -void KviLagMeter::lagCheckAbort(const char * key) -{ - KviPointerList l; - l.setAutoDelete(false); - KviLagCheck * c; - - if(_OUTPUT_PARANOIC) - m_pConnection->console()->output(KVI_OUT_VERBOSE,__tr2qs("Lag check aborted (%s)"),key); - - for(c = m_pCheckList->first();c;c = m_pCheckList->next()) - if(kvi_strEqualCS(c->szKey.ptr(),key))l.append(c); - for(c = l.first();c;c = l.next())m_pCheckList->removeRef(c); -} - -#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES -#include "kvi_lagmeter.moc" -#endif //!COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/kvi_lagmeter.h b/src/kvirc/kernel/kvi_lagmeter.h deleted file mode 100644 index 9bd87de7a..000000000 --- a/src/kvirc/kernel/kvi_lagmeter.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef _KVI_LAGMETER_H_ -#define _KVI_LAGMETER_H_ -//============================================================================= -// -// File : kvi_lagmeter.h -// Creation date : Fri Oct 18 13:30:26 CEST 1999 by Juanjo Álvarez -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 1999 Juanjo Álvarez -// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviCString.h" -#include "KviPointerList.h" - -#include - -class KviIrcConnection; - -class KviLagCheck -{ -public: - KviCString szKey; - long lSecs; // since epoch - long lUSecs; - unsigned int uReliability; // [0-100] -}; - -class KVIRC_API KviLagMeter : public QObject -{ - Q_OBJECT - friend class KviIrcConnection; -protected: - KviLagMeter(KviIrcConnection * c); - ~KviLagMeter(); -protected: - KviIrcConnection * m_pConnection; - unsigned int m_uLag; // last computed lag - unsigned int m_uLastEmittedLag; // last emitted lag - long m_tLastCompleted; // time when the last lag was completed (gettimeofday!) - unsigned int m_uLastReliability; // how much reliable was the last completed check ? - KviPointerList * m_pCheckList; - long m_tFirstOwnCheck; // time when the first ping after a completed check was sent - long m_tLastOwnCheck; // time when the last ping was sent - bool m_bOnAlarm; - bool * m_pDeletionSignal; // we use this to signal our own delete -public: - // lag checks should be done only against the user's server - // please make SURE that the key is unique! - void lagCheckRegister(const char * key,unsigned int uReliability = 50); - bool lagCheckComplete(const char * key); - void lagCheckAbort(const char * key); - unsigned int lag(){ return m_uLag; }; - unsigned int secondsSinceLastCompleted(); -protected: - virtual void timerEvent(QTimerEvent * e); -}; - -#endif // _KVI_LAGMETER_H_ diff --git a/src/kvirc/kernel/kvi_main.cpp b/src/kvirc/kernel/kvi_main.cpp deleted file mode 100644 index 03bcc75c1..000000000 --- a/src/kvirc/kernel/kvi_main.cpp +++ /dev/null @@ -1,462 +0,0 @@ -//============================================================================= -// -// File : kvi_main.cpp -// Creation date : Sun Jun 18 2000 12:38:45 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_app.h" -#include "KviCString.h" -#include "kvi_settings.h" -#include "kvi_ircurl.h" -#include "kvi_defaults.h" -#include "kvi_sourcesdate.h" -#include "kvi_msgbox.h" -#include "KviBuildInfo.h" -#ifdef COMPILE_DBUS_SUPPORT - #ifndef COMPILE_KDE_SUPPORT // 'cause kde adds an interface itself - #include "KviDbusAdaptor.h" - #endif -#endif -#ifndef COMPILE_NO_IPC - extern bool kvi_sendIpcMessage(const char * message); // kvi_ipc.cpp -#endif - -#include //for qDebug() -#include - -#ifdef COMPILE_KDE_SUPPORT - #include - #include -#endif - -#define KVI_ARGS_RETCODE_OK 0 -#define KVI_ARGS_RETCODE_ERROR 1 -#define KVI_ARGS_RETCODE_STOP 2 - -typedef struct _ParseArgs -{ - int argc; - char ** argv; - char * configFile; - bool createFile; - bool bForceNewSession; - bool bShowPopup; - bool bShowSplashScreen; - bool bExecuteCommandAndClose; - KviCString szExecCommand; - KviCString szExecRemoteCommand; -} ParseArgs; - -int parseArgs(ParseArgs * a) -{ - KviCString szServer; - KviCString szPort; - int idx; - - if(a->argc < 2)return KVI_ARGS_RETCODE_OK; - - for(idx = 1;idx < a->argc;idx++) - { - QString szMessage; - char * p = a->argv[idx]; - - if((kvi_strLen(p) > 3) && (*p == '-') && (*(p+1) == '-'))p++; - - if(kvi_strEqualCI("-v",p) || kvi_strEqualCI("-version",p)) - { - KviQString::appendFormatted(szMessage,"KVIrc %s '%s'\n",KVI_VERSION,KVI_RELEASE_NAME); - KviQString::appendFormatted(szMessage,"Sources date: %s\n",KVI_SOURCES_DATE); - szMessage += "Build date: "; - szMessage += KviBuildInfo::buildDate(); - szMessage += "\n"; - - KviQString::appendFormatted(szMessage,"Home page: http://www.kvirc.net/\n"); - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - MessageBox(0,szMessage.toLocal8Bit().data(),"KVIrc",0); -#else - qDebug("%s",szMessage.toLocal8Bit().data()); -#endif - - return KVI_ARGS_RETCODE_STOP; - } - - if(kvi_strEqualCI("-h",p) || kvi_strEqualCI("-help",p)) - { - KviQString::appendFormatted(szMessage,"Usage:\n"); - KviQString::appendFormatted(szMessage," %s [options] [server [port]] [ircurl [ircurl [...]]]\n",a->argv[0]); - KviQString::appendFormatted(szMessage," \n"); - KviQString::appendFormatted(szMessage,"Available options:\n"); - KviQString::appendFormatted(szMessage," -h, --help : Print this help and exit\n"); - KviQString::appendFormatted(szMessage," -v, --version: Print version information and exit\n"); - KviQString::appendFormatted(szMessage," -c : Use as config file instead of ~/%s\n",KVI_HOME_CONFIG_FILE_NAME); - KviQString::appendFormatted(szMessage," (defaults to $HOME/%s if does not exist)\n",KVI_HOME_CONFIG_FILE_NAME); - KviQString::appendFormatted(szMessage," -n : Use as config file instead of $HOME/%s\n",KVI_HOME_CONFIG_FILE_NAME); - KviQString::appendFormatted(szMessage," (create if it does not exist)\n"); -#ifdef COMPILE_NO_IPC - KviQString::appendFormatted(szMessage," -f : Accepted but ignored (for compatibility)\n"); -#else - KviQString::appendFormatted(szMessage," -f : Force a new KVIrc session, even if there is already\n"); - KviQString::appendFormatted(szMessage," a running one.\n"); -#endif - KviQString::appendFormatted(szMessage," -e : If a KVIrc session is already running, execute\n"); - KviQString::appendFormatted(szMessage," the in that session, otherwise start up\n"); - KviQString::appendFormatted(szMessage," normally and execute \n"); - KviQString::appendFormatted(szMessage," must be a single shell token.\n"); - KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); - KviQString::appendFormatted(szMessage," -x : If a KVIrc session is already running, execute\n"); - KviQString::appendFormatted(szMessage," the in that session, otherwise exit from application without doing anything/\n"); - KviQString::appendFormatted(szMessage," must be a single shell token.\n"); - KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); - KviQString::appendFormatted(szMessage," -r : If a KVIrc session is already running, execute the \n"); - KviQString::appendFormatted(szMessage," in that session, otherwise start up normally (do not execute).\n"); - KviQString::appendFormatted(szMessage," must be a single shell token.\n"); - KviQString::appendFormatted(szMessage," You can eventually use this switch more than once\n"); - KviQString::appendFormatted(szMessage," -m : If a KVIrc session is already running, show an informational\n"); - KviQString::appendFormatted(szMessage," popup dialog instead of writing to the console\n"); - KviQString::appendFormatted(szMessage," --nosplash : Do not show the splash screen at startup\n"); - KviQString::appendFormatted(szMessage," [server] : Connect to this server after startup\n"); - KviQString::appendFormatted(szMessage," [port] : Use this port for connection\n"); - KviQString::appendFormatted(szMessage," [ircurl] : URL in the following form:\n"); - KviQString::appendFormatted(szMessage," irc[6]://[:][/[?]]\n"); - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - MessageBox(0,szMessage.toLocal8Bit().data(),"KVIrc",0); -#else - qDebug("%s",szMessage.toLocal8Bit().data()); -#endif - return KVI_ARGS_RETCODE_STOP; - } - - if(kvi_strEqualCI("-c",p)) - { - idx++; - if(idx >= a->argc) - { - qDebug("Option -c requires a config file name"); - return KVI_ARGS_RETCODE_ERROR; - } - p = a->argv[idx]; - a->configFile = p; - qDebug("Using file %s as config",p); - continue; - } - - if(kvi_strEqualCI("-e",p)) - { - idx++; - if(idx >= a->argc) - { - qDebug("Option -e requires a command"); - return KVI_ARGS_RETCODE_ERROR; - } - p = a->argv[idx]; - if(a->szExecCommand.hasData())a->szExecCommand.append("\n"); - a->szExecCommand.append(p); - continue; - } - - if(kvi_strEqualCI("-x",p)) - { - idx++; - if(idx >= a->argc) - { - qDebug("Option -x requires a command"); - return KVI_ARGS_RETCODE_ERROR; - } - p = a->argv[idx]; - if(a->szExecCommand.hasData())a->szExecCommand.append("\n"); - a->szExecCommand.append(p); - a->bExecuteCommandAndClose=true; - continue; - } - - if(kvi_strEqualCI("-r",p)) - { - idx++; - if(idx >= a->argc) - { - qDebug("Option -r requires a command"); - return KVI_ARGS_RETCODE_ERROR; - } - p = a->argv[idx]; - if(a->szExecRemoteCommand.hasData())a->szExecRemoteCommand.append("\n"); - a->szExecRemoteCommand.append(p); - continue; - } - - if(kvi_strEqualCI("-m",p)) - { - a->bShowPopup = true; - continue; - } - - if(kvi_strEqualCI("-n",p)) - { - idx++; - if(idx >= a->argc) - { - qDebug("Option -n requires a config file name"); - return KVI_ARGS_RETCODE_ERROR; - } - p = a->argv[idx]; - a->configFile = p; - a->createFile=true; - qDebug("Using file %s as config",p); - continue; - } - - if(kvi_strEqualCI("-nosplash",p)) - { - a->bShowSplashScreen = false; - continue; - } - - if(kvi_strEqualCI("-f",p)) - { - a->bForceNewSession = true; - continue; - } - - if(kvi_strEqualCI("-session",p)||kvi_strEqualCI("-display",p)||kvi_strEqualCI("-name",p)) - { - // Qt apps are supposed to handle the params to these switches, but we'll skip arg for now - idx++; - continue; - } - - if(kvi_strEqualCI("-external",p)) - { - idx++; - if(idx >= a->argc) - { - qDebug("Option --external requires n irc:// url"); - return KVI_ARGS_RETCODE_ERROR; - } - p = a->argv[idx]; - if(kvi_strEqualCIN(p,"irc://",6) || kvi_strEqualCIN(p,"irc6://",7) || kvi_strEqualCIN(p,"ircs://",7) || kvi_strEqualCIN(p,"ircs6://",8)) - { - KviCString tmp = QString::fromLocal8Bit(p); - a->szExecCommand ="openurl "; - tmp.replaceAll("$",""); // the urls can't contain $ signs - tmp.replaceAll(";",""); // the urls can't contain ; signs - tmp.replaceAll("%",""); // the urls can't contain % signs - a->szExecCommand.append(tmp); - return KVI_ARGS_RETCODE_OK; - } - return KVI_ARGS_RETCODE_ERROR; - } - - if(*p != '-') - { - // no dash - if(kvi_strEqualCIN(p,"irc://",6) || kvi_strEqualCIN(p,"irc6://",7) || kvi_strEqualCIN(p,"ircs://",7) || kvi_strEqualCIN(p,"ircs6://",8)) - { - KviCString szTmp = QString::fromLocal8Bit(p); - if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); - a->szExecCommand.append("openurl "); - szTmp.replaceAll("$",""); // the urls can't contain $ signs - szTmp.replaceAll(";",""); // the urls can't contain ; signs - szTmp.replaceAll("%",""); // the urls can't contain % signs - a->szExecCommand.append(szTmp); - } else { - QString szTmp = QString::fromLocal8Bit(p); - bool bOk; - szTmp.toUInt(&bOk); - if(bOk) - { - szPort = szTmp; - } else { - QString ri = szTmp.right(4); - if(KviQString::equalCI(ri,".kvs")) - { - if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); - a->szExecCommand.append("parse \""); - szTmp.replace('$',"\\$"); - szTmp.replace('\\',"\\\\"); - a->szExecCommand.append(szTmp); - a->szExecCommand.append('"'); - } else if(KviQString::equalCI(ri,".kvt")) - { - if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); - a->szExecCommand.append("theme.install \""); - szTmp.replace('$',"\\$"); - szTmp.replace('\\',"\\\\"); - a->szExecCommand.append(szTmp); - a->szExecCommand.append('"'); - } else if(KviQString::equalCI(ri,".kva")) - { - if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); - a->szExecCommand.append("addon.install \""); - szTmp.replace('$',"\\$"); - szTmp.replace('\\',"\\\\"); - a->szExecCommand.append(szTmp); - a->szExecCommand.append('"'); - } else { - szServer = szTmp; // assume a plain server name - } - } - } - } - } - - if(szServer.hasData()) - { - if(a->szExecCommand.hasData())a->szExecCommand.append('\n'); - a->szExecCommand.append("server -u "); - a->szExecCommand.append(szServer); - if(szPort.hasData()) - { - a->szExecCommand.append(' '); - a->szExecCommand.append(szPort); - } - } - - return KVI_ARGS_RETCODE_OK; -} - -int main(int argc, char ** argv) -{ - ParseArgs a; - a.argc = argc; - a.argv = argv; - a.configFile = 0; - a.createFile = false; - a.bForceNewSession = false; - a.bShowPopup = false, - a.bShowSplashScreen = true; - a.bExecuteCommandAndClose = false; - - int iRetCode = parseArgs(&a); - - if(iRetCode != KVI_ARGS_RETCODE_OK) - { - return ((iRetCode == KVI_ARGS_RETCODE_ERROR) ? (-1) : 0); - } - -#ifdef COMPILE_KDE_SUPPORT - - KAboutData oAboutData( - "kvirc", // internal program name - "kvirc", // message catalogue name - ki18n("KVIrc"), // user-visible program name - KVI_VERSION, // program version - ki18n("Visual IRC Client"), // description - KAboutData::License_GPL, // license - ki18n("(c) 1998-2010 The KVIrc Development Team"), - ki18n("???"), // *some other text* ???? - "http://www.kvirc.net", // homepage - "https://svn.kvirc.de/kvirc/" // bug address (FIXME: this would be an E-MAIL address...) - ); - - //fake argc/argv initialization: kde will use argv[0] as out appName in some dialogs - // (eg: kdebase/workspace/kwin/killer/killer.cpp) - KCmdLineArgs::init(1, &argv[0], &oAboutData); - -#endif - - KviApp * pTheApp = new KviApp(argc,argv); - -#ifdef COMPILE_DBUS_SUPPORT - #ifndef COMPILE_KDE_SUPPORT - new KviDbusAdaptor(pTheApp); // FIXME: shouldn't this be deleted by someone ? - QDBusConnection::sessionBus().registerObject("/MainApplication", pTheApp); - #endif -#endif - - KviCString szRemoteCommand = a.szExecCommand; - if(a.szExecRemoteCommand.hasData()) - { - if(szRemoteCommand.hasData()) - { - szRemoteCommand.append('\n'); - } - szRemoteCommand.append(a.szExecRemoteCommand); - } - - /* - FIXME: There is a race condition in the IPC mechanism. - If one starts two instances of kvirc one immediately after another - then both instances may run through kvi_sendIpcMessage - without finding the sentinel window and thus both may decide - to start. - A weak file locking mechanism should be used too... - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - QString szLock = convertSeparators(cleanDirPath(QDir::homePath() + "/.kvirc.lock")); -#else - QString szLock = convertSeparators(cleanDirPath(QDir::homePath() + "/.kvirc.lock")); -#endif - - QFileInfo inf(szLock); - bool bLocked = false; - if(inf.exists()) - { - iLocked = inf.lastModified().secsTo(QDateTime::currentDateTime()); - } - */ - -#ifndef COMPILE_NO_IPC - if(!a.bForceNewSession) - { - // here we could use CreateMutex on win and semget() on linux - // in order to get a shared semaphore to ensure instance unicity. - - if(kvi_sendIpcMessage(szRemoteCommand.ptr())) - { - if(szRemoteCommand.isEmpty()) - { - KviCString szTmp(KviCString::Format,"Another KVIrc session is already running on this display and with this user id.\nUse %s -f if you want to force a new session.",argv[0]); - if(a.bShowPopup) - { - QMessageBox::information(0,"Session - KVIrc",szTmp.ptr(),QMessageBox::Ok); - } else { - qDebug("%s",szTmp.ptr()); - } - } - delete pTheApp; - return 0; - } - - if(a.bExecuteCommandAndClose) - { - delete pTheApp; - return 0; - } - } -#endif - - pTheApp->m_bCreateConfig = a.createFile; - pTheApp->m_szConfigFile = a.configFile; - pTheApp->m_szExecAfterStartup = a.szExecCommand; - pTheApp->m_bShowSplashScreen = a.bShowSplashScreen; - pTheApp->setup(); - - // YEAH! - int iRetVal = pTheApp->exec(); - // :) - - delete pTheApp; - - return iRetVal; -} diff --git a/src/kvirc/kernel/kvi_notifylist.cpp b/src/kvirc/kernel/kvi_notifylist.cpp deleted file mode 100644 index 1012f5b60..000000000 --- a/src/kvirc/kernel/kvi_notifylist.cpp +++ /dev/null @@ -1,1294 +0,0 @@ -//============================================================================= -// -// File : kvi_notifylist.cpp -// Creation date : Fri Oct 27 2000 23:41:01 CEST by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_debug.h" -#include "kvi_notifylist.h" -#include "kvi_console.h" -#include "kvi_ircsocket.h" -#include "KviRegisteredUserDataBase.h" -#include "kvi_userlistview.h" -#include "kvi_channel.h" -#include "kvi_options.h" -#include "kvi_window.h" -#include "KviLocale.h" -#include "kvi_out.h" -#include "kvi_sparser.h" -#include "KviIrcMask.h" -#include "kvi_numeric.h" -#include "KviParameterList.h" -#include "kvi_ircconnection.h" -#include "kvi_app.h" -#include "KviQString.h" -#include "kvi_lagmeter.h" -#include "kvi_kvs_eventtriggers.h" - -#include -#include - -// FIXME: #warning "Finish this doc!" - -/* - @doc: notify_list - @title: - Notify lists - @short: - Tracking users on IRC - @keyterms: - notify property, watch property, notify lists - @body: - The notify list is a means of keeping track of users on IRC.[br] - Once connected to an IRC server, you can tell KVIrc to check - periodically if your friends are online.[br] - This is basically achieved by setting a property in the [doc:registered_users]registered users database[/doc] - entry.[br] - The property is called "notify", and you have to set it to the nickname - that you want to look for.[br] - So for example, assume to register a frend of yours like Szymon:[br] - [example] - [cmd:reguser.add]reguser.add[/cmd] Szymon - [cmd:reguser.addmask]reguser.addmask[/cmd] Szymon Pragma!*@*.it - [/example] - And then want it in the notify list; nothing easier, just set - hist "notify" property to the nickname that you want him to be "looked for":[br] - [example] - [cmd:reguser.setproperty]reguser.setproperty[/cmd] Szymon notify Pragma - [/example] - In this way, once in a while, KVIrc will send to the server an ISON message - with the nickname Pragma. If Szymon is online, you will be notified with a message:[br] - "Pragma [someuser@somehost.it] is on IRC".[br] - If Szymon uses often "[Pragma]" as his secondary nickname, you can do the following:[br] - [example] - [cmd:reguser.addmask]reguser.addmask[/cmd] Szymon [Pragma]*@*.it - [cmd:reguser.setproperty]reguser.setproperty[/cmd] Szymon notify "Pragma [Pragma]" - [/example] - KVIrc will then look for both nicknames getting online.[br] - KVIrc supports three notify lists management methods:[br] - The "stupid ISON method", the "intelligent ISON method" and the "WATCH method".[br] - The "stupid ISON method" will assume that Szymon is online if any user with nickname - Pragma (or [Pragma] in the second example) gets online; this means that also Pragma!someuser@somehost.com will be - assumed to be "Szymon" and will be shown in the notify list.[br] - This might be a false assumption (since somehod.com does not even match *.it), - but it is the best result that the "stupid ISON method" can achieve.[br] - The "intelligent ISON method" will also check the Pragma's username and hostname - and match it in the registered masks; so in the example above, you will be notified if - any user that matches Pragma!*@*.it gets online; (but you will NOT be notified if - (for example) Pragma!someuser@somehost.com gets online).[br] - So what's the point in including a stupid method? :) Well...the intelligent - method "eats" some of your IRC bandwidth; it has to send USERHOST messages - for every group of 5 users in the notify list. If you have a lot of users - in the notify list, it might become slow and eventually cause a - client to server flood.[br] - So finally, the intelligent method is the default. If you have "flood" problems, - or if you think that the notify list is quite slow, try the "stupid" method: - it is not that bad after all.[br] - The third notify list management method is the "WATCH method".[br] - It uses a totally different (and better) approach to the notify lists management, - and can be used only on the networks that support the WATCH notify method (DALnet, WebNet, etc.).[br] - KVIrc will attempt to guess if the server you're currently using supports the WATCH command - and eventually use this last method.[br] - The WATCH method uses the "notify" property to get the nicknames that have to be - sent to the server in the /WATCH commands. -*/ - -// Basic NotifyListManager: this does completely nothing - -KviNotifyListManager::KviNotifyListManager(KviIrcConnection * pConnection) -: QObject(0) -{ - setObjectName("notify_list_manager"); - m_pConnection = pConnection; - m_pConsole = pConnection->console(); -} - -KviNotifyListManager::~KviNotifyListManager() -{ -} - -void KviNotifyListManager::start() -{ -} - -void KviNotifyListManager::stop() -{ -} - -bool KviNotifyListManager::handleUserhost(KviIrcMessage *) -{ - return false; -} - -bool KviNotifyListManager::handleIsOn(KviIrcMessage *) -{ - return false; -} - -bool KviNotifyListManager::handleWatchReply(KviIrcMessage *) -{ - return false; -} - -void KviNotifyListManager::notifyOnLine(const QString &nick,const QString &user,const QString &host,const QString &szReason,bool bJoin) -{ - if(bJoin) - m_pConsole->notifyListView()->join(nick,user,host); - - KviWindow * out = KVI_OPTION_BOOL(KviOption_boolNotifyListChangesToActiveWindow) ? m_pConsole->activeWindow() : m_pConsole; - if(KVS_TRIGGER_EVENT_1_HALTED(KviEvent_OnNotifyOnLine,out,nick))return; - - QString szWho; - QString szMsg; - - if(!(user.isEmpty() || host.isEmpty())) - KviQString::sprintf(szWho,"\r!n\r%Q\r [%Q@\r!h\r%Q\r]",&nick,&user,&host); - else - KviQString::sprintf(szWho,"\r!n\r%Q\r",&nick); - - KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); - KviPointerHashTableIterator it(*d); - QString szNotify; - - while(KviRegisteredUser * u = it.current()) - { - QString prop=u->getProperty("notify"); - if (!prop.isEmpty()) - { - if(prop.split(",",QString::SkipEmptyParts).indexOf(nick)!=-1) - { - QString szComment=u->getProperty("comment"); - if(!szComment.isEmpty()) - KviQString::sprintf(szMsg,"%Q (%Q), Group \"%Q\" is on IRC as (%Q)",&(u->name()),&szComment,&(u->group()),&szWho); - else - KviQString::sprintf(szMsg,"%Q, Group \"%Q\" is on IRC as (%Q)",&(u->name()),&(u->group()),&szWho); - break; - } - } - ++it; - } - QString szFmt = __tr2qs("%Q is on IRC"); - - if(szMsg.isEmpty()) - KviQString::sprintf(szMsg,szFmt,&szWho); - - if((!szReason.isEmpty()) && (_OUTPUT_VERBOSE)) - { - szMsg += "("; - szMsg += szReason; - szMsg += ")"; - } - - out->outputNoFmt(KVI_OUT_NOTIFYONLINE,szMsg); - - if(!(out->hasAttention())) - { - if(KVI_OPTION_BOOL(KviOption_boolFlashWindowOnNotifyOnLine)) - out->demandAttention(); - if(KVI_OPTION_BOOL(KviOption_boolPopupNotifierOnNotifyOnLine)) - { - szWho = ""; - szWho += nick; - szWho += ""; - KviQString::sprintf(szMsg,szFmt,&szWho); - g_pApp->notifierMessage(0,KVI_OPTION_MSGTYPE(KVI_OUT_NOTIFYONLINE).pixId(),szMsg,KVI_OPTION_UINT(KviOption_uintNotifierAutoHideTime)); - } - } -} - -void KviNotifyListManager::notifyOffLine(const QString &nick,const QString &user,const QString &host,const QString &szReason) -{ - KviWindow * out = KVI_OPTION_BOOL(KviOption_boolNotifyListChangesToActiveWindow) ? m_pConsole->activeWindow() : m_pConsole; - if(!KVS_TRIGGER_EVENT_1_HALTED(KviEvent_OnNotifyOffLine,out,nick)) - { - QString szWho; - - if(!(user.isEmpty() || host.isEmpty())) - KviQString::sprintf(szWho,"\r!n\r%Q\r [%Q@\r!h\r%Q\r]",&nick,&user,&host); - else - KviQString::sprintf(szWho,"\r!n\r%Q\r",&nick); - - QString szMsg; - - KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); - KviPointerHashTableIterator it(*d); - QString szNotify; - - while(KviRegisteredUser * u = it.current()) - { - QString prop=u->getProperty("notify"); - if (!prop.isEmpty()) - { - if(prop.split(",",QString::SkipEmptyParts).indexOf(nick)!=-1) - { - QString szComment=u->getProperty("comment"); - if(!szComment.isEmpty()) - KviQString::sprintf(szMsg,"%Q (%Q), Group \"%Q\" has left IRC as (%Q)",&(u->name()),&szComment,&(u->group()),&szWho); - else - KviQString::sprintf(szMsg,"%Q, Group \"%Q\" has left IRC as (%Q)",&(u->name()),&(u->group()),&szWho); - break; - } - } - ++it; - } - - if(szMsg.isEmpty()) - KviQString::sprintf(szMsg,__tr2qs("%Q has left IRC"),&szWho); - - if((!szReason.isEmpty()) && (_OUTPUT_VERBOSE)) - { - szMsg += "("; - szMsg += szReason; - szMsg += ")"; - } - - out->outputNoFmt(KVI_OUT_NOTIFYOFFLINE,szMsg); - } - - m_pConsole->notifyListView()->part(nick); -} - - - -// -// INTELLIGENT NOTIFY LIST MANAGER: NOTIFY PROCESS: -// -// start() stop() -// | ^ -// buildRegUserDict() | -// | | -// m_pRegUserDict->isEmpty() ? -- YES ---------->+ -// | | -// NO | -// | | -// newNotifySession()<------- TIMER ---------------- delayedNotifySession() --------------------------------+ -// | (can be stopped here) | ^ | -// | | ^ | -// buildNotifyList() | | YES -// | | | | -// m_pNotifyList->isEmpty() ? - YES ->+ | | -// | | | -// NO | | -// | | | -// newIsOnSession()<------------- TIMER -------------------- delayedIsOnSession() -- NO - m_pNotifyList->isEmpty() ? -// | (can be stopped here) | | -// | | | -// buildIsOnList() | | -// | | | -// m_pIsOnList->isEmpty() ? -- YES ---------->+ | -// | | -// NO | -// | | -// sendIsOn() - - - - - - - - - - - -> handleIsOn() | -// | | -// (build m_pOnlineList) | -// | | -// m_pOnlineList->isEmpty() ? - YES ----------------------->+ -// | | -// NO YES -// | | -// delayedUserhostSession()<--------------- NO - m_pOnlineList->isEmpty() ? -// | ^ -// TIMER (can be stopped here) | -// | | -// newUserhostSession() | -// | | -// buildUserhostList() | -// | | -// m_pUserhostList->isEmpty() ? - YES --->+ -// | ^^^ | -// | (unexpected!)||| | -// NO | -// | | -// sendUserhost() - - - - - - - - > handleUserhost() -// - - -KviIsOnNotifyListManager::KviIsOnNotifyListManager(KviIrcConnection * pConnection) -: KviNotifyListManager(pConnection) -{ - m_pRegUserDict = new KviPointerHashTable(17,false); // case insensitive, copy keys - m_pRegUserDict->setAutoDelete(true); - m_pNotifyList = new KviPointerList; - m_pNotifyList->setAutoDelete(true); - m_pIsOnList = new KviPointerList; - m_pIsOnList->setAutoDelete(true); - m_pOnlineList = new KviPointerList; - m_pOnlineList->setAutoDelete(true); - m_pUserhostList = new KviPointerList; - m_pUserhostList->setAutoDelete(true); - m_pDelayedNotifyTimer = new QTimer(); - connect(m_pDelayedNotifyTimer,SIGNAL(timeout()),this,SLOT(newNotifySession())); - m_pDelayedIsOnTimer = new QTimer(); - connect(m_pDelayedIsOnTimer,SIGNAL(timeout()),this,SLOT(newIsOnSession())); - m_pDelayedUserhostTimer = new QTimer(); - connect(m_pDelayedUserhostTimer,SIGNAL(timeout()),this,SLOT(newUserhostSession())); - m_bRunning = false; -} - - -KviIsOnNotifyListManager::~KviIsOnNotifyListManager() -{ - if(m_bRunning)stop(); - delete m_pDelayedNotifyTimer; - delete m_pDelayedIsOnTimer; - delete m_pDelayedUserhostTimer; - delete m_pRegUserDict; - delete m_pOnlineList; - delete m_pNotifyList; - delete m_pIsOnList; - delete m_pUserhostList; -} - -void KviIsOnNotifyListManager::start() -{ - if(m_bRunning)stop(); - m_bRunning = true; - m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); - - m_bExpectingIsOn = false; - m_bExpectingUserhost = false; - - buildRegUserDict(); - if(m_pRegUserDict->isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: No users to check for, quitting")); - stop(); - return; - } - newNotifySession(); -} - -void KviIsOnNotifyListManager::buildRegUserDict() -{ - m_pRegUserDict->clear(); - - const KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); - KviPointerHashTableIterator it(*d); - while(KviRegisteredUser * u = it.current()) - { - QString notify; - if(u->getProperty("notify",notify)) - { - notify.trimmed(); - while(!notify.isEmpty()) - { - int idx = notify.indexOf(' '); - if(idx > 0) - { - QString single = notify.left(idx); - m_pRegUserDict->replace(single,new QString(u->name())); - notify.remove(0,idx+1); - } else { - m_pRegUserDict->replace(notify,new QString(u->name())); - notify = ""; - } - } - } - ++it; - } -} - -void KviIsOnNotifyListManager::delayedNotifySession() -{ - unsigned int iTimeout = KVI_OPTION_UINT(KviOption_uintNotifyListCheckTimeInSecs); - if(iTimeout < 15) - { - // life first of all. - // don't allow the user to suicide - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("Notify list: Timeout (%d sec) is too short, resetting to something more reasonable (15 sec)"), - iTimeout); - iTimeout = 15; - KVI_OPTION_UINT(KviOption_uintNotifyListCheckTimeInSecs) = 15; - } - m_pDelayedNotifyTimer->setInterval(iTimeout * 1000); - m_pDelayedNotifyTimer->setSingleShot(true); - m_pDelayedNotifyTimer->start(); -} - -void KviIsOnNotifyListManager::newNotifySession() -{ - buildNotifyList(); - if(m_pNotifyList->isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Notify list empty, quitting")); - stop(); - return; - } - newIsOnSession(); -} - -void KviIsOnNotifyListManager::buildNotifyList() -{ - m_pNotifyList->clear(); - KviPointerHashTableIterator it(*m_pRegUserDict); - while(it.current()) - { - m_pNotifyList->append(new QString(it.currentKey())); - ++it; - } -} - -void KviIsOnNotifyListManager::delayedIsOnSession() -{ - unsigned int iTimeout = KVI_OPTION_UINT(KviOption_uintNotifyListIsOnDelayTimeInSecs); - if(iTimeout < 5) - { - // life first of all. - // don't allow the user to suicide - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("Notify list: ISON delay (%d sec) is too short, resetting to something more reasonable (5 sec)"), - iTimeout); - iTimeout = 5; - KVI_OPTION_UINT(KviOption_uintNotifyListIsOnDelayTimeInSecs) = 5; - } - m_pDelayedIsOnTimer->setInterval(iTimeout * 1000); - m_pDelayedIsOnTimer->setSingleShot(true); - m_pDelayedIsOnTimer->start(); -} - -void KviIsOnNotifyListManager::newIsOnSession() -{ - buildIsOnList(); - if(m_pIsOnList->isEmpty())delayedNotifySession(); - else sendIsOn(); -} - -void KviIsOnNotifyListManager::buildIsOnList() -{ - m_pIsOnList->clear(); - m_szIsOnString = ""; - m_pNotifyList->setAutoDelete(false); - while(QString * s = m_pNotifyList->first()) - { - if(((m_szIsOnString.length() + s->length()) + 1) < 504) - { - if(!m_szIsOnString.isEmpty())m_szIsOnString.append(' '); - m_szIsOnString.append(*s); - m_pIsOnList->append(s); - m_pNotifyList->removeFirst(); - } else break; - } - m_pNotifyList->setAutoDelete(true); -} - -void KviIsOnNotifyListManager::sendIsOn() -{ - if(_OUTPUT_PARANOIC) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Checking for: %Q"),&m_szIsOnString); - QByteArray szDec = m_pConnection->encodeText(m_szIsOnString); - m_pConnection->sendFmtData("ISON %s",szDec.data()); - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckRegister("@notify_ison",40); // not that reliable - m_szIsOnString = ""; - m_bExpectingIsOn = true; - // FIXME: #warning "And if can't send ?" -} - - -bool KviIsOnNotifyListManager::handleIsOn(KviIrcMessage *msg) -{ - if(!m_bExpectingIsOn)return false; - - // Check if it is our ISON - // all the nicks must be on the IsOnList - - KviPointerList tmplist; - tmplist.setAutoDelete(false); - - KviCString nk; - const char * aux = msg->trailing(); - - while(*aux) - { - nk = ""; - aux = kvi_extractToken(nk,aux,' '); - if(nk.hasData()) - { - bool bGotIt = false; - QString dnk = m_pConnection->decodeText(nk.ptr()); - for(QString * s = m_pIsOnList->first();s && (!bGotIt);s = m_pIsOnList->next()) - { - if(KviQString::equalCI(*s,dnk)) - { - tmplist.append(s); - bGotIt = true; - } - } - if(!bGotIt) - { - // ops...not my userhost! - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Hey! You've used ISON behind my back? (I might be confused now...)")); - return false; - } - } - } - - // Ok...looks to be my ison (still not sure at 100%, but can't do better) - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckComplete("@notify_ison"); - - m_bExpectingIsOn = false; - - m_pOnlineList->clear(); - - m_pIsOnList->setAutoDelete(false); - - // Ok...we have an IsOn reply here - // The nicks in the IsOnList that are also in the reply are online, and go to the OnlineList - // the remaining in the IsOnList are offline - - QString * s; - - for(s = tmplist.first();s;s = tmplist.next()) - { - m_pIsOnList->removeRef(s); - m_pOnlineList->append(s); - } - - m_pIsOnList->setAutoDelete(true); - // Ok...all the users that are online, are on the OnlineList - // the remaining users are in the m_pIsOnList, and are no longer online - - // first the easy step: remove the users that have just left irc or have never been online - // we're clearling the m_pIsOnList - while((s = m_pIsOnList->first())) - { - if(m_pConsole->notifyListView()->findEntry(*s)) - { - // has just left IRC... make him part - notifyOffLine(*s); - } // else has never been here - - m_pIsOnList->removeFirst(); // autodelete is true - } - - // ok... complex step now: the remaining users in the userhost list are online - // if they have been online before, just remove them from the list - // otherwise they must be matched for masks - // and eventually inserted in the notify view later - - KviIrcUserDataBase * db = console()->connection()->userDataBase(); - - KviPointerList l; - l.setAutoDelete(false); - - for(s = m_pOnlineList->first();s;s = m_pOnlineList->next()) - { - if(KviUserListEntry * ent = m_pConsole->notifyListView()->findEntry(*s)) - { - // the user was online from a previous notify session - // might the mask have been changed ? (heh...this is tricky, maybe too much even) - if(KVI_OPTION_BOOL(KviOption_boolNotifyListSendUserhostForOnlineUsers)) - { - // user wants to be sure about online users.... - // check if he is on some channels - if(ent->globalData()->nRefs() > 1) - { - // mmmh...we have more than one ref, so the user is at least in one query or channel - // look him up on channels, if we find his entry, we can be sure that he is - // still the right user - KviPointerList * chlist = m_pConsole->connection()->channelList(); - for(KviChannel * ch = chlist->first();ch;ch = chlist->next()) - { - if(KviUserListEntry * le = ch->findEntry(*s)) - { - l.append(s); // ok...found on a channel...we don't need an userhost to match him - KviIrcMask mk(*s,le->globalData()->user(),le->globalData()->host()); - if(!doMatchUser(*s,mk))return true; // critical problems = have to restart!!! - break; - } - } - } // else Only one ref...we need an userhost to be sure (don't remove from the list) - } else { - // user wants no userhost for online users...we "hope" that everything will go ok. - l.append(s); - } - //l.append(s); // we will remove him from the list - } else { - // the user was not online! - // check if we have a cached mask - if(db) - { - if(KviIrcUserEntry * ue = db->find(*s)) - { - // already in the db... do we have a mask ? - if(ue->hasUser() && ue->hasHost()) - { - // yup! we have a complete mask to match on - KviIrcMask mk(*s,ue->user(),ue->host()); - // lookup the user's name in the m_pRegUserDict - if(!doMatchUser(*s,mk))return true; // critical problems = have to restart!!! - l.append(s); // remove anyway - } - } - } - } - } - - for(s = l.first();s;s = l.next()) - { - m_pOnlineList->removeRef(s); // autodelete is true - } - - if(m_pOnlineList->isEmpty()) - { - if(m_pNotifyList->isEmpty())delayedNotifySession(); - else delayedIsOnSession(); - } else delayedUserhostSession(); - - return true; -} - -// FIXME: #warning "Nickname escapes (links) in the notifylist messages!" - -bool KviIsOnNotifyListManager::doMatchUser(const QString ¬ifyString,const KviIrcMask & mask) -{ - QString * nam = m_pRegUserDict->find(notifyString); - if(nam) - { - // ok...find the user - if(KviRegisteredUser * u = g_pRegisteredUserDataBase->findUserByName(*nam)) - { - // ok ... match the user - if(u->matchesFixed(mask)) - { - // new user online - if(!(m_pConsole->notifyListView()->findEntry(mask.nick()))) - { - notifyOnLine(mask.nick(),mask.user(),mask.host()); - } // else already online, and matching...all ok - } else { - // not matched.... has he been online before ? - if(m_pConsole->notifyListView()->findEntry(mask.nick())) - { - // has been online just a sec ago, but now the mask does not match - // either reguserdb has changed, or the user went offline and another one got his nick - // in the meantime... (ugly situation anyway) - notifyOffLine(mask.nick(),mask.user(),mask.host(),__tr2qs("registration mask changed, or nickname is being used by someone else")); - } else { - // has never been online - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: \r!n\r%Q\r appears to be online, but the mask [%Q@\r!h\r%Q\r] does not match (registration mask does not match, or nickname is being used by someone else)"),&(mask.nick()),&(mask.user()),&(mask.host())); - } - } - } else { - // ops... unexpected inconsistency .... reguser db modified ? - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Unexpected inconsistency, registered user DB modified? (restarting)")); - stop(); - start(); - return false; // critical ... exit from the call stack - } - } else { - // ops...unexpected inconsistency - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Unexpected inconsistency, expected \r!n\r%Q\r in the registered user DB"),¬ifyString); - } - return true; -} - -void KviIsOnNotifyListManager::delayedUserhostSession() -{ - unsigned int iTimeout = KVI_OPTION_UINT(KviOption_uintNotifyListUserhostDelayTimeInSecs); - if(iTimeout < 5) - { - // life first of all. - // don't allow the user to suicide - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("Notify list: USERHOST delay (%d sec) is too short, resetting to something more reasonable (5 sec)"), - iTimeout); - iTimeout = 5; - KVI_OPTION_UINT(KviOption_uintNotifyListUserhostDelayTimeInSecs) = 5; - } - m_pDelayedUserhostTimer->setInterval(iTimeout * 1000); - m_pDelayedUserhostTimer->setSingleShot(true); - m_pDelayedUserhostTimer->start(); -} - -void KviIsOnNotifyListManager::newUserhostSession() -{ - buildUserhostList(); - if(m_pUserhostList->isEmpty()) - { - // this is unexpected! - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Unexpected inconsistency, userhost list is empty!")); - if(m_pOnlineList->isEmpty()) - { - if(m_pNotifyList->isEmpty())delayedNotifySession(); - else delayedIsOnSession(); - } else delayedUserhostSession(); - return; - } - sendUserhost(); -} - -#define MAX_USERHOST_ENTRIES 5 - -void KviIsOnNotifyListManager::buildUserhostList() -{ - m_szUserhostString = ""; - m_pUserhostList->clear(); - - m_pOnlineList->setAutoDelete(false); - int i = 0; - QString * s; - while((s = m_pOnlineList->first()) && (i < MAX_USERHOST_ENTRIES)) - { - if(!m_szUserhostString.isEmpty())m_szUserhostString.append(' '); - m_szUserhostString.append(*s); - m_pUserhostList->append(s); - m_pOnlineList->removeFirst(); - i++; - } - m_pOnlineList->setAutoDelete(true); -} - -void KviIsOnNotifyListManager::sendUserhost() -{ - if(_OUTPUT_PARANOIC) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Checking userhost for: %Q"),&m_szUserhostString); - QByteArray ccc = m_pConnection->encodeText(m_szUserhostString); - m_pConnection->sendFmtData("USERHOST %s",ccc.data()); - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckRegister("@notify_userhost",50); - m_szUserhostString = ""; - m_bExpectingUserhost = true; -// FIXME: #warning "And if can't send ?" -} - -bool KviIsOnNotifyListManager::handleUserhost(KviIrcMessage *msg) -{ - if(!m_bExpectingUserhost)return false; - // first check for consistency: all the replies must be on the USERHOST list - KviPointerList tmplist; - tmplist.setAutoDelete(true); - - KviCString nk; - const char * aux = msg->trailing(); - - while(*aux) - { - nk = ""; - aux = kvi_extractToken(nk,aux,' '); - if(nk.hasData()) - { - // split it in a mask - KviCString nick; - KviCString user; - KviCString host; - - int idx = nk.findFirstIdx('='); - if(idx != -1) - { - nick = nk.left(idx); - if(nick.lastCharIs('*'))nick.cutRight(1); - nk.cutLeft(idx + 1); - if(nk.firstCharIs('+') || nk.firstCharIs('-'))nk.cutLeft(1); - - idx = nk.findFirstIdx('@'); - if(idx != -1) - { - user = nk.left(idx); - nk.cutLeft(idx + 1); - host = nk; - } else { - user = "*"; - host = nk; - } - - bool bGotIt = false; - QString szNick = m_pConnection->decodeText(nick.ptr()); - QString szUser = m_pConnection->decodeText(user.ptr()); - QString szHost = m_pConnection->decodeText(host.ptr()); - - for(QString * s = m_pUserhostList->first();s && (!bGotIt);s = m_pUserhostList->next()) - { - if(KviQString::equalCI(*s,szNick)) - { - KviIrcMask * mk = new KviIrcMask(szNick,szUser,szHost); - tmplist.append(mk); - bGotIt = true; - m_pUserhostList->removeRef(s); - } - } - - if(!bGotIt) - { - // ops...not my userhost! - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Hey! You've used USERHOST behind my back? (I might be confused now...)")); - return false; - } - } else { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING,__tr2qs("Notify list: Broken USERHOST reply from the server? (%s)"),nk.ptr()); - } - } - } - - // Ok...looks to be my usershot (still not sure at 100%, but can't do better) - - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckComplete("@notify_userhost"); - - - m_bExpectingUserhost = false; - - for(KviIrcMask * mk = tmplist.first();mk;mk = tmplist.next()) - { - if(!doMatchUser(mk->nick(),*mk))return true; // have to restart!!! - } - - if(!(m_pUserhostList->isEmpty())) - { - // ops...someone is no longer online ? - while(QString * s = m_pUserhostList->first()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: \r!n\r%Q\r appears to have gone offline before USERHOST reply was received, will recheck in the next loop"),s); - m_pUserhostList->removeFirst(); - } - - } - - if(m_pOnlineList->isEmpty()) - { - if(m_pNotifyList->isEmpty())delayedNotifySession(); - else delayedIsOnSession(); - } else delayedUserhostSession(); - - return true; -} - -void KviIsOnNotifyListManager::stop() -{ - if(!m_bRunning)return; - - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckAbort("@notify_userhost"); - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckAbort("@notify_ison"); - - m_pDelayedNotifyTimer->stop(); - m_pDelayedIsOnTimer->stop(); - m_pDelayedUserhostTimer->stop(); - m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); - m_pRegUserDict->clear(); - m_pNotifyList->clear(); - m_pIsOnList->clear(); - m_pOnlineList->clear(); - m_pUserhostList->clear(); - m_szIsOnString = ""; - m_szUserhostString = ""; - m_bRunning = false; -} - - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Stupid notify list manager -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -KviStupidNotifyListManager::KviStupidNotifyListManager(KviIrcConnection * pConnection) -: KviNotifyListManager(pConnection) -{ - m_pNickList = new KviPointerList; - m_pNickList->setAutoDelete(true); - m_iRestartTimer = 0; -} - -KviStupidNotifyListManager::~KviStupidNotifyListManager() -{ - if(m_iRestartTimer) - { - killTimer(m_iRestartTimer); - m_iRestartTimer = 0; - } - delete m_pNickList; -} - -void KviStupidNotifyListManager::start() -{ - if(m_iRestartTimer) - { - killTimer(m_iRestartTimer); - m_iRestartTimer = 0; - } - if(_OUTPUT_VERBOSE) - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Starting notify list")); - buildNickList(); - if(m_pNickList->isEmpty()) - { - if(_OUTPUT_VERBOSE) - m_pConsole->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__tr2qs("No users in the notify list")); - return; // Ok...no nicknames in the list - } - m_iNextNickToCheck = 0; - m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); - sendIsOn(); -} - -void KviStupidNotifyListManager::sendIsOn() -{ - m_szLastIsOnMsg = ""; - QString * nick = m_pNickList->at(m_iNextNickToCheck); - KVI_ASSERT(nick); - - int i = 0; - while(nick && ((nick->length() + 5 + m_szLastIsOnMsg.length()) < 510)) - { - KviQString::appendFormatted(m_szLastIsOnMsg," %Q",nick); - nick = m_pNickList->next(); - i++; - } - if(_OUTPUT_PARANOIC) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Checking for: %Q"),&m_szLastIsOnMsg); - QByteArray dat = m_pConnection->encodeText(m_szLastIsOnMsg); - m_pConnection->sendFmtData("ISON%s",dat.data()); - - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckRegister("@notify_naive",20); - - m_iNextNickToCheck += i; -} - -bool KviStupidNotifyListManager::handleIsOn(KviIrcMessage * msg) -{ - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckComplete("@notify_naive"); - - KviCString nk; - const char * aux = msg->trailing(); - while(*aux) - { - nk = ""; - aux = kvi_extractToken(nk,aux,' '); - if(nk.hasData()) - { - QString nkd = m_pConnection->decodeText(nk.ptr()); - QString nksp = " " + nkd; - m_szLastIsOnMsg.replace(nksp,"",Qt::CaseInsensitive); - if(!(m_pConsole->notifyListView()->findEntry(nkd))) - { - // not yet notified - notifyOnLine(nkd); - } - } - } - // ok...check the users that have left irc now... - QStringList sl = m_szLastIsOnMsg.isEmpty()?QStringList():m_szLastIsOnMsg.split(' ',QString::SkipEmptyParts); - - for(QStringList::Iterator it = sl.begin();it != sl.end();++it) - { - if(m_pConsole->notifyListView()->findEntry(*it)) - { - // has just left irc - notifyOffLine(*it); - } // else has never been here... - } - - if(((unsigned int)m_iNextNickToCheck) >= m_pNickList->count()) - { - // have to restart - unsigned int iTimeout = KVI_OPTION_UINT(KviOption_uintNotifyListCheckTimeInSecs); - if(iTimeout < 5) - { - // life first of all. - // don't allow the user to suicide - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("Notify list: Timeout (%d sec) is too short, resetting to something more reasonable (5 sec)"), - iTimeout); - iTimeout = 5; - KVI_OPTION_UINT(KviOption_uintNotifyListCheckTimeInSecs) = 5; - } - m_iRestartTimer = startTimer(iTimeout * 1000); - } else sendIsOn(); - return true; -} - -void KviStupidNotifyListManager::timerEvent(QTimerEvent *e) -{ - if(e->timerId() == m_iRestartTimer) - { - killTimer(m_iRestartTimer); - m_iRestartTimer = 0; - m_iNextNickToCheck = 0; - sendIsOn(); - return; - } - QObject::timerEvent(e); -} - -void KviStupidNotifyListManager::stop() -{ - if(m_pConnection->lagMeter()) - m_pConnection->lagMeter()->lagCheckAbort("@notify_naive"); - - if(m_iRestartTimer) - { - killTimer(m_iRestartTimer); - m_iRestartTimer = 0; - } - m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); - - // The ISON Method needs no stopping -} - -void KviStupidNotifyListManager::buildNickList() -{ - const KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); - KviPointerHashTableIterator it(*d); - m_pNickList->clear(); - while(it.current()) - { - QString notify; - if(it.current()->getProperty("notify",notify)) - { - m_pNickList->append(new QString(notify)); - } - ++it; - } -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Watch notify list manager -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -KviWatchNotifyListManager::KviWatchNotifyListManager(KviIrcConnection * pConnection) -: KviNotifyListManager(pConnection) -{ - m_pRegUserDict = new KviPointerHashTable(17,false); - m_pRegUserDict->setAutoDelete(true); -} - -KviWatchNotifyListManager::~KviWatchNotifyListManager() -{ - delete m_pRegUserDict; -} - -void KviWatchNotifyListManager::buildRegUserDict() -{ - m_pRegUserDict->clear(); - - const KviPointerHashTable * d = g_pRegisteredUserDataBase->userDict(); - KviPointerHashTableIterator it(*d); - while(KviRegisteredUser * u = it.current()) - { - QString notify; - if(u->getProperty("notify",notify)) - { - notify.trimmed(); - QStringList sl = notify.split(' ',QString::SkipEmptyParts); - for(QStringList::Iterator it = sl.begin();it != sl.end();++it) - { - m_pRegUserDict->replace(*it,new QString(u->name())); - } - } - ++it; - } -} - -void KviWatchNotifyListManager::start() -{ - m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); - - buildRegUserDict(); - - QString watchStr; - - KviPointerHashTableIterator it(*m_pRegUserDict); - while(it.current()) - { - QString nk = it.currentKey(); - if(nk.indexOf('*') == -1) - { - if((watchStr.length() + nk.length() + 2) > 501) - { - QByteArray dat = m_pConnection->encodeText(watchStr); - m_pConnection->sendFmtData("WATCH%s",dat.data()); - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Adding watch entries for %Q"),&watchStr); - watchStr = ""; - } - KviQString::appendFormatted(watchStr," +%Q",&nk); - } - ++it; - } - - if(!watchStr.isEmpty()) - { - QByteArray dat = m_pConnection->encodeText(watchStr); - m_pConnection->sendFmtData("WATCH%s",dat.data()); - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Adding watch entries for %Q"),&watchStr); - } -} -void KviWatchNotifyListManager::stop() -{ - m_pConsole->notifyListView()->partAllButOne(m_pConnection->currentNickName()); - m_pConnection->sendFmtData("WATCH clear"); - m_pRegUserDict->clear(); -} - -bool KviWatchNotifyListManager::doMatchUser(KviIrcMessage * msg,const QString ¬ifyString,const KviIrcMask & mask) -{ - QString * nam = m_pRegUserDict->find(notifyString); - - if(nam) - { - // ok...find the user - if(KviRegisteredUser * u = g_pRegisteredUserDataBase->findUserByName(*nam)) - { - // ok ... match the user - if(u->matchesFixed(mask)) - { - // new user online - if(!(m_pConsole->notifyListView()->findEntry(mask.nick()))) - { - notifyOnLine(mask.nick(),mask.user(),mask.host(),"watch"); - } else { - // else already online, and matching...all ok - if(msg->numeric() == RPL_NOWON) - { - // This is a reply to a /watch +something (should not happen, unless the user is messing) or to /watch l (user requested) - notifyOnLine(mask.nick(),mask.user(),mask.host(), - __tr2qs("watch entry listing requested by user"),false); - } else { - // This is a RPL_LOGON....we're desynched ? - notifyOnLine(mask.nick(),mask.user(),mask.host(), - __tr2qs("possible watch list desync"),false); - } - } - } else { - // not matched.... has he been online before ? - if(m_pConsole->notifyListView()->findEntry(mask.nick())) - { - // has been online just a sec ago, but now the mask does not match - // prolly the reguserdb has been changed - notifyOffLine(mask.nick(),mask.user(),mask.host(), - __tr2qs("registration mask changed or desync with the watch service")); - } else { - // has never been online - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE, - __tr("Notify list: \r!n\r%Q\r appears to be online, but the mask [%Q@\r!h\r%Q\r] does not match (watch: registration mask does not match, or nickname is being used by someone else)"), - &(mask.nick()),&(mask.user()),&(mask.host())); - } - } - } else { - // ops... unexpected inconsistency .... reguser db modified ? - m_pConsole->output(KVI_OUT_SYSTEMWARNING, - __tr2qs("Notify list: Unexpected inconsistency, registered user DB modified? (watch: restarting)")); - stop(); - start(); - return false; // critical ... exit from the call stack - } - } else { - // not in our dictionary - // prolly someone used /WATCH behind our back... bad boy! - if(!(m_pConsole->notifyListView()->findEntry(mask.nick()))) - { - notifyOnLine(mask.nick(),mask.user(),mask.host(),__tr2qs("watch entry added by user")); - } - } - return true; -} - -// FIXME: #warning "DEDICATED WATCH LIST VERBOSITY FLAG ? (To allow the user to use /WATCH l and manual /WATCH)" - -bool KviWatchNotifyListManager::handleWatchReply(KviIrcMessage *msg) -{ - // 600: RPL_LOGON - // :prefix 600 :logged online - // 601: RPL_LOGON - // :prefix 601 :logged offline - // 604: PRL_NOWON - // :prefix 604 :is online - // 605: PRL_NOWOFF - // :prefix 605 0 :is offline - -// FIXME: #warning "Use the logintime in some way ?" - - const char * nk = msg->safeParam(1); - const char * us = msg->safeParam(2); - const char * ho = msg->safeParam(3); - QString dnk = m_pConnection->decodeText(nk); - QString dus = m_pConnection->decodeText(us); - QString dho = m_pConnection->decodeText(ho); - - if((msg->numeric() == RPL_LOGON) || (msg->numeric() == RPL_NOWON)) - { - KviIrcMask m(dnk,dus,dho); - doMatchUser(msg,dnk,m); - return true; - - } else if(msg->numeric() == RPL_WATCHOFF) - { - if(m_pConsole->notifyListView()->findEntry(dnk)) - { - notifyOffLine(dnk,dus,dho,__tr2qs("removed from watch list")); - } else { - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: Stopped watching for \r!n\r%Q\r"),&dnk); - } - if(m_pRegUserDict->find(dnk))m_pRegUserDict->remove(dnk); // kill that - - return true; - - } else if((msg->numeric() == RPL_LOGOFF) || (msg->numeric() == RPL_NOWOFF)) - { - if(m_pConsole->notifyListView()->findEntry(dnk)) - { - notifyOffLine(dnk,dus,dho,__tr2qs("watch")); - } else { - if(msg->numeric() == RPL_NOWOFF) - { - // This is a reply to a /watch +something - if(_OUTPUT_VERBOSE) - m_pConsole->output(KVI_OUT_SYSTEMMESSAGE,__tr2qs("Notify list: \r!n\r%Q\r is offline (watch)"),&dnk); - } else { - // This is a RPL_LOGOFF for an user that has not matched the reg-mask - notifyOffLine(dnk,dus,dho,__tr2qs("unmatched watch list entry")); - } - } - return true; - } - - return false; -} - - -#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES -#include "kvi_notifylist.moc" -#endif //!COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/kvi_notifylist.h b/src/kvirc/kernel/kvi_notifylist.h deleted file mode 100644 index 01ac0963c..000000000 --- a/src/kvirc/kernel/kvi_notifylist.h +++ /dev/null @@ -1,160 +0,0 @@ -#ifndef _KVI_NOTIFYLIST_H_ -#define _KVI_NOTIFYLIST_H_ - -//============================================================================= -// -// File : kvi_notifylist.h -// Creation date : Fri Oct 27 2000 23:39:09 CEST by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviPointerList.h" -#include "KviPointerHashTable.h" - -#include -#include - -class KviConsole; -class KviIrcMessage; -class KviIrcMask; -class KviIrcConnection; - -class KVIRC_API KviNotifyListManager : public QObject -{ - friend class KviConsole; - friend class KviConnectionInfo; - friend class KviIrcServerParser; - friend class KviIrcConnection; - Q_OBJECT -protected: - KviNotifyListManager(KviIrcConnection * pConnection); - ~KviNotifyListManager(); -protected: - KviConsole * m_pConsole; - KviIrcConnection * m_pConnection; -protected: - virtual void start(); - virtual void stop(); - virtual bool handleUserhost(KviIrcMessage * msg); - virtual bool handleIsOn(KviIrcMessage * msg); - virtual bool handleWatchReply(KviIrcMessage *msg); - void notifyOnLine(const QString &nick,const QString &user = QString(),const QString &host = QString(),const QString &szReason = QString(),bool bJoin=true); - void notifyOffLine(const QString &nick,const QString &user = QString(),const QString &host = QString(),const QString &szReason = QString()); -public: - KviConsole * console(){ return m_pConsole; }; -}; - -class KVIRC_API KviIsOnNotifyListManager : public KviNotifyListManager -{ - friend class KviConsole; - friend class KviIrcServerParser; - friend class KviIrcConnection; - Q_OBJECT -protected: - KviIsOnNotifyListManager(KviIrcConnection * pConnection); - ~KviIsOnNotifyListManager(); -private: - KviPointerHashTable * m_pRegUserDict; // dict notifystring->reguser name - KviPointerList * m_pNotifyList; // list of notifystring (total) - KviPointerList * m_pIsOnList; // list of notifystring (one session) - QString m_szIsOnString; // m_pIsOnList in form of a string - KviPointerList * m_pOnlineList; // - KviPointerList * m_pUserhostList; - QString m_szUserhostString; - bool m_bExpectingIsOn; - bool m_bExpectingUserhost; - QTimer * m_pDelayedIsOnTimer; - QTimer * m_pDelayedNotifyTimer; - QTimer * m_pDelayedUserhostTimer; - bool m_bRunning; -protected: - virtual void start(); - virtual void stop(); - virtual bool handleUserhost(KviIrcMessage *msg); - virtual bool handleIsOn(KviIrcMessage *msg); -private: - void delayedNotifySession(); - void delayedIsOnSession(); - void delayedUserhostSession(); -private slots: - void newNotifySession(); - void newIsOnSession(); - void newUserhostSession(); - - void buildRegUserDict(); - void buildIsOnList(); - void buildUserhostList(); - void buildNotifyList(); - void sendIsOn(); - void sendUserhost(); - bool doMatchUser(const QString ¬ifyString,const KviIrcMask & mask); - -}; - - -class KVIRC_API KviStupidNotifyListManager : public KviNotifyListManager -{ - friend class KviConsole; - friend class KviIrcServerParser; - friend class KviIrcConnection; - Q_OBJECT -protected: - KviStupidNotifyListManager(KviIrcConnection * pConnection); - ~KviStupidNotifyListManager(); -protected: - KviPointerList * m_pNickList; - QString m_szLastIsOnMsg; - int m_iNextNickToCheck; - int m_iRestartTimer; -protected: - virtual void start(); - virtual void stop(); - virtual bool handleIsOn(KviIrcMessage *msg); -protected: - virtual void timerEvent(QTimerEvent *e); -private: - void buildNickList(); - void sendIsOn(); -}; - -class KVIRC_API KviWatchNotifyListManager : public KviNotifyListManager -{ - friend class KviConsole; - friend class KviIrcServerParser; - friend class KviIrcConnection; - Q_OBJECT -public: - KviWatchNotifyListManager(KviIrcConnection * pConnection); - ~KviWatchNotifyListManager(); -protected: - KviPointerHashTable * m_pRegUserDict; // dict notifystring->reguser name -protected: - void buildRegUserDict(); - virtual void start(); - virtual void stop(); - virtual bool handleWatchReply(KviIrcMessage *msg); - bool doMatchUser(KviIrcMessage *msg,const QString ¬ifyString,const KviIrcMask & mask); - -}; - -#endif //_KVI_NOTIFYLIST_H_ diff --git a/src/kvirc/kernel/kvi_options.cpp b/src/kvirc/kernel/kvi_options.cpp deleted file mode 100644 index deea9046c..000000000 --- a/src/kvirc/kernel/kvi_options.cpp +++ /dev/null @@ -1,1445 +0,0 @@ -//============================================================================= -// -// File : kvi_options.cpp -// Creation date : Tue Jun 20 2000 11:42:00 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - - - -#define _KVI_OPTIONS_CPP_ - -#include "kvi_options.h" -#include "kvi_defaults.h" -#include "KviConfigurationFile.h" -#include "kvi_app.h" -#include "kvi_iconmanager.h" -#include "KviMircCntrl.h" -#include "KviLocale.h" -#include "kvi_confignames.h" -#include "kvi_window.h" -#include "kvi_out.h" -#include "KviStringConversion.h" -#include "kvi_settings.h" -#include "kvi_splash.h" -#include "kvi_frame.h" -#include "kvi_internalcmd.h" -#include "kvi_theme.h" -#include "KviFileUtils.h" -//#include "kvi_textencoding.h" - -#include -#include -#include -#include -#include - -//xml parser -//#include -//!xml parser - -#include - -// kvi_app.cpp -extern KVIRC_API int g_iIdentDaemonRunningUsers; - - -#define RECT_OPTION(_txt,_val,_flags) KviRectOption(KVI_RECT_OPTIONS_PREFIX _txt, _val, _flags) - -KviRectOption g_rectOptionsTable[KVI_NUM_RECT_OPTIONS]= -{ - RECT_OPTION("FrameGeometry",QRect(0,0,10,10),KviOption_sectFlagGeometry), - RECT_OPTION("GeneralOptionsDialogGeometry",QRect(50,50,600,450),KviOption_sectFlagGeometry), - RECT_OPTION("RegisteredUsersDialogGeometry",QRect(50,50,600,450),KviOption_sectFlagGeometry) -}; - -#define BOOL_OPTION(_txt,_val,_flags) KviBoolOption(KVI_BOOL_OPTIONS_PREFIX _txt,_val,_flags) - -KviBoolOption g_boolOptionsTable[KVI_NUM_BOOL_OPTIONS]= -{ - BOOL_OPTION("WindowsRememberProperties",true,KviOption_sectFlagWindows), - BOOL_OPTION("IrcViewShowImages",false,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("IrcViewTimestamp",true,KviOption_sectFlagIrcView), - BOOL_OPTION("IrcViewUrlHighlighting",true,KviOption_sectFlagIrcView | KviOption_groupTheme), - BOOL_OPTION("IrcViewWrapMargin",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("InputHistoryCursorAtEnd",true,KviOption_sectFlagInput), - - BOOL_OPTION("AvoidParserWarnings",false,KviOption_sectFlagUserParser), - BOOL_OPTION("UseProxyHost",false,KviOption_sectFlagConnection), - BOOL_OPTION("ShowGeneralOptionsDialogAsToplevel",true,KviOption_sectFlagFrame), - BOOL_OPTION("ForceBrutalQuit",false,KviOption_sectFlagIrcSocket), - BOOL_OPTION("ShowPingPong",true,KviOption_sectFlagConnection), - BOOL_OPTION("PopupNotifierOnNewQueryMessages",true,KviOption_sectFlagFrame), - BOOL_OPTION("ShowExtendedServerInfo",false,KviOption_sectFlagConnection), - BOOL_OPTION("EchoNumericTopic",true,KviOption_sectFlagConnection), - BOOL_OPTION("ShowOwnParts",true,KviOption_sectFlagConnection), - BOOL_OPTION("UseAntiSpamOnPrivmsg",false,KviOption_sectFlagAntiSpam), - BOOL_OPTION("UseExtendedPrivmsgView",false,KviOption_sectFlagIrcView | KviOption_groupTheme), - BOOL_OPTION("ShowUserAndHostInPrivmsgView",false,KviOption_sectFlagIrcView | KviOption_groupTheme), - BOOL_OPTION("UseWordHighlighting",true,KviOption_sectFlagIrcView), /* _ALL_ newbie users, with who i was taling asks me where can they switch on */ - BOOL_OPTION("UseBigIcons",false,KviOption_sectFlagFrame), /* Almost all users asks me "How to decrease icon size?" */ - BOOL_OPTION("CleanupUnusedModules",true,KviOption_sectFlagModules), - BOOL_OPTION("IgnoreCtcpPing",false,KviOption_sectFlagCtcp), - BOOL_OPTION("IgnoreCtcpVersion",false,KviOption_sectFlagCtcp), - BOOL_OPTION("UseCtcpFloodProtection",true,KviOption_sectFlagCtcp), - BOOL_OPTION("DisableBrokenEventHandlers",true,KviOption_sectFlagUserParser), - BOOL_OPTION("IgnoreCtcpClientinfo",false,KviOption_sectFlagCtcp), - BOOL_OPTION("IgnoreCtcpUserinfo",false,KviOption_sectFlagCtcp), - BOOL_OPTION("IgnoreCtcpFinger",false,KviOption_sectFlagCtcp), - BOOL_OPTION("IgnoreCtcpSource",false,KviOption_sectFlagCtcp), - BOOL_OPTION("IgnoreCtcpTime",false,KviOption_sectFlagCtcp), - BOOL_OPTION("RequestMissingAvatars",true,KviOption_sectFlagAvatar), - BOOL_OPTION("ShowCompactModeChanges",true,KviOption_sectFlagConnection), - BOOL_OPTION("IgnoreCtcpDcc",false,KviOption_sectFlagDcc), - BOOL_OPTION("AutoAcceptDccChat",false,KviOption_sectFlagDcc), - BOOL_OPTION("AutoAcceptDccSend",false,KviOption_sectFlagDcc), - BOOL_OPTION("SendZeroAckInDccRecv",false,KviOption_sectFlagDcc), - BOOL_OPTION("UseFastDccSend",true,KviOption_sectFlagDcc), - BOOL_OPTION("UseCompositingForTransparency",false,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), - BOOL_OPTION("UseWindowListIrcContextIndicator",false,KviOption_sectFlagWindowList | KviOption_resetUpdateGui), - BOOL_OPTION("UseGlobalApplicationFont",false,KviOption_sectFlagGui | KviOption_resetUpdateAppFont | KviOption_groupTheme), - BOOL_OPTION("AlwaysQuitKVIrcClosingLastConsole",false,KviOption_sectFlagFrame), - BOOL_OPTION("AlwaysDisconnectClosingConnectedConsole",false,KviOption_sectFlagFrame), - BOOL_OPTION("FlashWindowOnHighlightedMessages",true,KviOption_sectFlagFrame), - BOOL_OPTION("PopupNotifierOnHighlightedMessages",true,KviOption_sectFlagFrame), - BOOL_OPTION("FlashWindowOnNotifyOnLine",true,KviOption_sectFlagConnection), - BOOL_OPTION("IrcViewTimestampUTC",false,KviOption_sectFlagIrcView), - BOOL_OPTION("UseGlobalPseudoTransparency",false,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), - BOOL_OPTION("UseNotifyList",false,KviOption_sectFlagConnection | KviOption_resetRestartNotifyList), - BOOL_OPTION("NotifyListChangesToActiveWindow",true,KviOption_sectFlagConnection), - BOOL_OPTION("AutoResumeDccSendWhenAutoAccepted",false,KviOption_sectFlagDcc), - BOOL_OPTION("LimitOutgoingTraffic",false,KviOption_sectFlagIrcSocket), - BOOL_OPTION("SendUnknownCommandsAsRaw",true,KviOption_sectFlagUserParser), - BOOL_OPTION("UserListViewDrawGrid",true,KviOption_sectFlagUserListView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("ShowChannelSyncTime",true,KviOption_sectFlagConnection), - BOOL_OPTION("RejoinChannelOnKick",false,KviOption_sectFlagConnection), - BOOL_OPTION("KeepChannelOpenOnKick",true,KviOption_sectFlagConnection), - BOOL_OPTION("AutoCloseDccSendOnSuccess",false,KviOption_sectFlagDcc), - BOOL_OPTION("NotifyDccSendSuccessInConsole",false,KviOption_sectFlagDcc), - BOOL_OPTION("CreateMinimizedDccSend",false,KviOption_sectFlagDcc), - BOOL_OPTION("CreateMinimizedDccChat",false,KviOption_sectFlagDcc), - BOOL_OPTION("AutoAcceptIncomingAvatars",true,KviOption_sectFlagDcc), - BOOL_OPTION("UseNickCompletionPostfixForFirstWordOnly",true,KviOption_sectFlagInput), - BOOL_OPTION("UseWindowListIcons",true,KviOption_sectFlagWindowList | KviOption_resetUpdateGui), - BOOL_OPTION("CreateMinimizedDccSendWhenAutoAccepted",true,KviOption_sectFlagDcc), - BOOL_OPTION("CreateMinimizedDccChatWhenAutoAccepted",true,KviOption_sectFlagDcc), - BOOL_OPTION("DccGuessIpFromServerWhenLocalIsUnroutable",true,KviOption_sectFlagDcc), - BOOL_OPTION("ShowRegisteredUsersDialogAsToplevel",true,KviOption_sectFlagFrame), - BOOL_OPTION("AutoLogQueries",true,KviOption_sectFlagLogging),/* this options enabled by default in mIRC,XChat and irssi. People are confused while they want to see logs, but see empty dir*/ - BOOL_OPTION("AutoLogChannels",true,KviOption_sectFlagLogging), - BOOL_OPTION("AutoLogDccChat",false,KviOption_sectFlagLogging), - BOOL_OPTION("AutoLogConsole",false,KviOption_sectFlagLogging), - BOOL_OPTION("SilentAntiSpam",false,KviOption_sectFlagAntiSpam), - BOOL_OPTION("UseIncomingDccMediaTypeSavePath",true,KviOption_sectFlagDcc), - BOOL_OPTION("NotifyListSendUserhostForOnlineUsers",true,KviOption_sectFlagConnection), - BOOL_OPTION("UseIntelligentNotifyListManager",true,KviOption_sectFlagConnection | KviOption_resetRestartNotifyList), - BOOL_OPTION("UseWatchListIfAvailable",true,KviOption_sectFlagConnection), - BOOL_OPTION("UseTreeWindowList",true,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList | KviOption_groupTheme), - BOOL_OPTION("BindIrcIPv4ConnectionsToSpecifiedAddress",false,KviOption_sectFlagConnection), - BOOL_OPTION("BindIrcIPv6ConnectionsToSpecifiedAddress",false,KviOption_sectFlagConnection), - BOOL_OPTION("UseAntiSpamOnNotice",false,KviOption_sectFlagAntiSpam), - BOOL_OPTION("SetLastAvatarAsDefaultForRegisteredUsers",true,KviOption_sectFlagAvatar), - BOOL_OPTION("CantAcceptIncomingDccConnections",false,KviOption_sectFlagDcc), - BOOL_OPTION("IgnoreCtcpAvatar",false,KviOption_sectFlagCtcp), - BOOL_OPTION("CtcpRepliesToActiveWindow",true,KviOption_sectFlagCtcp), - BOOL_OPTION("AutoAcceptDccCanvas",false,KviOption_sectFlagDcc), - BOOL_OPTION("NotifyDccSendSuccessInNotifier",true,KviOption_sectFlagDcc), - BOOL_OPTION("KillBrokenTimers",true,KviOption_sectFlagUserParser), - BOOL_OPTION("DccVoiceVolumeSliderControlsPCM", true, KviOption_sectFlagDcc), - BOOL_OPTION("DccVoiceForceHalfDuplex", false, KviOption_sectFlagDcc), - BOOL_OPTION("AutoAcceptDccVoice", false, KviOption_sectFlagDcc), - BOOL_OPTION("CreateMinimizedDccVoice", false, KviOption_sectFlagDcc), - BOOL_OPTION("CreateMinimizedDccVoiceWhenAutoAccepted",true,KviOption_sectFlagDcc), -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - BOOL_OPTION("UseIdentService",true,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), -#else - BOOL_OPTION("UseIdentService",false,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), -#endif - BOOL_OPTION("ShowTipAtStartup",false,KviOption_sectFlagFrame), - BOOL_OPTION("IdentdEnableIPv6",false,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - BOOL_OPTION("IdentdIPv6ContainsIPv4",false,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), -#else - BOOL_OPTION("IdentdIPv6ContainsIPv4",true,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), -#endif - BOOL_OPTION("ScaleAvatars",true,KviOption_sectFlagAvatar | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("ColorNicks",false,KviOption_sectFlagIrcView | KviOption_groupTheme), - BOOL_OPTION("BoldedNicks",true,KviOption_sectFlagIrcView | KviOption_groupTheme), - BOOL_OPTION("DccListenOnSpecifiedInterfaceByDefault",false,KviOption_sectFlagDcc), - BOOL_OPTION("ChangeNickAway", false, KviOption_sectFlagConnection), - BOOL_OPTION("AutoGeneratedAwayNick",false,KviOption_sectFlagConnection), /* only ircnet uses 9-symbol nicks */ - BOOL_OPTION("ExitAwayOnInput",false,KviOption_sectFlagConnection), - BOOL_OPTION("AlwaysHighlightNick",true,KviOption_sectFlagIrcView), - BOOL_OPTION("ShowChannelsJoinOnIrc",true,KviOption_sectFlagFrame), - BOOL_OPTION("ShowChannelsJoinDialogAsToplevel",true,KviOption_sectFlagFrame), - BOOL_OPTION("UserDefinedPortRange",false,KviOption_sectFlagDcc), - BOOL_OPTION("CreateQueryOnPrivmsg",true,KviOption_sectFlagConnection), - BOOL_OPTION("CreateQueryOnNotice",false,KviOption_sectFlagConnection), - BOOL_OPTION("CreateMinimizedQuery",true,KviOption_sectFlagConnection), - BOOL_OPTION("AutoJoinOnInvite",false,KviOption_sectFlagConnection), - BOOL_OPTION("ShowServersConnectDialogOnStart",true, KviOption_sectFlagFrame), - BOOL_OPTION("ShowServersConnectDialogAsToplevel",true,KviOption_sectFlagFrame), - BOOL_OPTION("AcceptBrokenFileNameDccResumeRequests",true,KviOption_sectFlagDcc), - BOOL_OPTION("AutoReconnectOnUnexpectedDisconnect",true,KviOption_sectFlagFrame), - BOOL_OPTION("RejoinChannelsAfterReconnect",true,KviOption_sectFlagFrame), - BOOL_OPTION("ReopenQueriesAfterReconnect",true,KviOption_sectFlagFrame), - BOOL_OPTION("EnableQueryTracing",true,KviOption_sectFlagConnection), - BOOL_OPTION("OperatorMessagesToActiveWindow",false,KviOption_sectFlagConnection), - BOOL_OPTION("InviteToActiveWindow",true,KviOption_sectFlagConnection), - BOOL_OPTION("ShowChannelUserFlagInPrivmsgView",true,KviOption_sectFlagConnection), - BOOL_OPTION("DccSendFakeAddressByDefault",false,KviOption_sectFlagDcc), - BOOL_OPTION("UseWindowListActivityMeter",false,KviOption_sectFlagWindowList | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("CloseServerWidgetAfterConnect",false,KviOption_sectFlagFrame), - BOOL_OPTION("ShowIdentityDialogAsToplevel",true,KviOption_sectFlagFrame), - BOOL_OPTION("ShowUserChannelIcons",true,KviOption_sectFlagUserListView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("ShowUserChannelState",false,KviOption_sectFlagUserListView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("EnableIgnoreOnPrivMsg",true,KviOption_sectFlagConnection), - BOOL_OPTION("VerboseIgnore",false,KviOption_sectFlagConnection), - BOOL_OPTION("EnableIgnoreOnNotice",true,KviOption_sectFlagConnection), - BOOL_OPTION("NotifyFailedDccHandshakes",true,KviOption_sectFlagDcc), - BOOL_OPTION("AutoTileWindows",false,KviOption_sectFlagMdi), - BOOL_OPTION("DrawEmoticons",true,KviOption_sectFlagIrcView | KviOption_groupTheme), - BOOL_OPTION("IgnoreCtcpPage",false,KviOption_sectFlagCtcp), - BOOL_OPTION("ShowDialogOnCtcpPage",true,KviOption_sectFlagCtcp), - BOOL_OPTION("BashLikeNickCompletion",false,KviOption_sectFlagInput), - BOOL_OPTION("UseSSLCertificate",false,KviOption_sectFlagConnection), - BOOL_OPTION("UseSSLPrivateKey",false,KviOption_sectFlagConnection), - BOOL_OPTION("WarnAboutPastingMultipleLines",true,KviOption_sectFlagFrame), - BOOL_OPTION("KeepChannelsOpenOnUnexpectedDisconnect",true,KviOption_sectFlagFrame), - BOOL_OPTION("KeepQueriesOpenOnUnexpectedDisconnect",true,KviOption_sectFlagFrame), - BOOL_OPTION("UseLagMeterEngine",true,KviOption_sectFlagConnection | KviOption_resetRestartLagMeter), - BOOL_OPTION("ShowLagOnContextDisplay",true,KviOption_sectFlagFrame), - BOOL_OPTION("DisableBanListRequestOnJoin",false,KviOption_sectFlagConnection), - BOOL_OPTION("DisableBanExceptionListRequestOnJoin",true,KviOption_sectFlagConnection), - BOOL_OPTION("DisableInviteListRequestOnJoin",true,KviOption_sectFlagConnection), - BOOL_OPTION("DisableWhoRequestOnJoin",false,KviOption_sectFlagConnection), - BOOL_OPTION("ShowDockExtension",true,KviOption_sectFlagFrame), - BOOL_OPTION("DccAddressByIrcDns",false,KviOption_sectFlagFrame), - BOOL_OPTION("MinimizeConsoleAfterConnect",false,KviOption_sectFlagFrame), - BOOL_OPTION("HighlightOnlyNormalMsg",false,KviOption_sectFlagFrame), - BOOL_OPTION("HighlightOnlyNormalMsgQueryToo",false,KviOption_sectFlagFrame), - BOOL_OPTION("HighlightOnlyNormalMsgNickinChanToo",false,KviOption_sectFlagFrame), - BOOL_OPTION("HighlightOnlyAtCustomHighlightLevel",false,KviOption_sectFlagFrame), - BOOL_OPTION("MdiManagerInSdiMode",true,KviOption_sectFlagFrame), - BOOL_OPTION("DccBrokenBouncerHack",false,KviOption_sectFlagDcc), - BOOL_OPTION("ExternalMessagesToActiveWindow",true,KviOption_sectFlagConnection), - BOOL_OPTION("IgnoreChannelAvatarRequestsWhenNoAvatarSet",true,KviOption_sectFlagAvatar), - BOOL_OPTION("FlashQueryWindowOnNewMessages",true,KviOption_sectFlagFrame), - BOOL_OPTION("ConfirmCloseWhenThereAreConnections",true,KviOption_sectFlagFrame), - BOOL_OPTION("UseWindowsDesktopForTransparency",false,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), - BOOL_OPTION("CtcpRequestsToActiveWindow",false,KviOption_sectFlagConnection), - BOOL_OPTION("ServerRepliesToActiveWindow",true,KviOption_sectFlagConnection), - BOOL_OPTION("ServerNoticesToActiveWindow",false,KviOption_sectFlagConnection), - BOOL_OPTION("ServicesNoticesToActiveWindow",false,KviOption_sectFlagConnection), - BOOL_OPTION("SortWindowListItemsByName",true,KviOption_sectFlagConnection), - BOOL_OPTION("ShowWindowListToolTips",true,KviOption_sectFlagConnection), - BOOL_OPTION("ShowUserListViewToolTips",true,KviOption_sectFlagConnection), - BOOL_OPTION("WhoisRepliesToActiveWindow",true,KviOption_sectFlagConnection), - BOOL_OPTION("PopupNotifierOnNotifyOnLine",true,KviOption_sectFlagConnection), - BOOL_OPTION("EnableNotifier",true,KviOption_sectFlagConnection), - BOOL_OPTION("DccSendForceIdleStep",false,KviOption_sectFlagDcc), - BOOL_OPTION("StatusBarVisible",true,KviOption_sectFlagFrame), - BOOL_OPTION("TrackLastReadTextViewLine",true,KviOption_sectFlagFrame), - BOOL_OPTION("KeepChannelOpenOnPart",false,KviOption_sectFlagFrame), - BOOL_OPTION("StripMircColorsInUserMessages",false,KviOption_sectFlagFrame | KviOption_groupTheme), - BOOL_OPTION("DoNotSuggestRestoreDefaultScript",false,KviOption_sectFlagFrame), - BOOL_OPTION("LimitDccSendSpeed",false,KviOption_sectFlagDcc), - BOOL_OPTION("LimitDccRecvSpeed",false,KviOption_sectFlagDcc), - BOOL_OPTION("IgnoreModuleVersions",false,KviOption_sectFlagFrame), - BOOL_OPTION("EnableInputHistory",true,KviOption_sectFlagInput | KviOption_resetUpdateGui), - BOOL_OPTION("UseSpecialColorForTimestamp",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("EnableAwayListUpdates",true,KviOption_sectFlagFrame), - BOOL_OPTION("ShowAvatarsInUserlist",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("ShowUserListStatisticLabel",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("ShowIconsInPopupMenus",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("ScriptErrorsToDebugWindow",false,KviOption_sectFlagFrame), - BOOL_OPTION("ShowMinimizedDebugWindow",true,KviOption_sectFlagFrame), - BOOL_OPTION("ShowExtendedInfoInQueryLabel",true,KviOption_resetUpdateGui), - BOOL_OPTION("UseUserListColorsAsNickColors",true,KviOption_sectFlagIrcView | KviOption_groupTheme), - BOOL_OPTION("GzipLogs",false,KviOption_sectFlagLogging), - BOOL_OPTION("UseFullWordHighlighting",false,KviOption_sectFlagIrcView), - BOOL_OPTION("NotifierFlashing",true,KviOption_sectFlagFrame), - BOOL_OPTION("CommandlineInUserFriendlyModeByDefault",false,KviOption_sectFlagFrame), // this confuses existing users and is not mentioned in the docs where there are commandline examples : we need it to be off by default for now - BOOL_OPTION("EnableVisualEffects",true,KviOption_resetUpdateGui), - BOOL_OPTION("DCCFileTransferReplaceOutgoingSpacesWithUnderscores",true,KviOption_sectFlagDcc), - BOOL_OPTION("DoNotUpscaleAvatars",true,KviOption_sectFlagIrcView | KviOption_resetUpdateGui ), - BOOL_OPTION("UseDifferentColorForOwnNick",false,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("CloseInTray",false,KviOption_sectFlagFrame | KviOption_resetUpdateGui), - BOOL_OPTION("StartupMinimized",false,KviOption_sectFlagFrame), - BOOL_OPTION("SortReceivedByDccFilesByNicks",false,KviOption_sectFlagDcc), - BOOL_OPTION("LogChannelHistory",true,KviOption_sectFlagConnection), - BOOL_OPTION("ClassicWindowListSetMaximumButtonWidth",true,KviOption_groupTheme | KviOption_sectFlagGeometry | KviOption_resetUpdateGui), - BOOL_OPTION("KeepChannelsOpenOnDisconnect",true,KviOption_sectFlagFrame), - BOOL_OPTION("KeepQueriesOpenOnDisconnect",true,KviOption_sectFlagFrame), - BOOL_OPTION("HideWindowToolButtons",true,KviOption_sectFlagFrame), - BOOL_OPTION("HideInputToolButtons",true,KviOption_sectFlagFrame), - BOOL_OPTION("StripControlCodesInLogs",false,KviOption_sectFlagLogging), - BOOL_OPTION("EnableTrayIconFlashing",true,KviOption_sectFlagFrame), - BOOL_OPTION("UseFlatClassicWindowListButtons",false,KviOption_sectFlagWindowList | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("StripMsgTypeInLogs",false,KviOption_sectFlagLogging), - BOOL_OPTION("UseLevelBasedTrayNotification",false,KviOption_sectFlagFrame), - BOOL_OPTION("MuteAllSounds",false,KviOption_sectFlagFrame), - BOOL_OPTION("CreateMinimizedChannels",false,KviOption_sectFlagFrame), - BOOL_OPTION("ShowNetworkNameForConsoleWindowListEntry",true,KviOption_sectFlagFrame | KviOption_resetUpdateGui), - BOOL_OPTION("DrawGenderIcons",true,KviOption_sectFlagFrame | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("PrependGenderInfoToRealname",true,KviOption_sectFlagConnection), - BOOL_OPTION("UseIdentServiceOnlyOnConnect",true,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), - BOOL_OPTION("UseSystemUrlHandlers",true,KviOption_sectFlagUrl), - BOOL_OPTION("ScaleAvatarsOnLoad",true,KviOption_sectFlagAvatar), - BOOL_OPTION("NotifierFading",true,KviOption_sectFlagFrame), - BOOL_OPTION("PickRandomIpAddressForRoundRobinServers",true,KviOption_sectFlagConnection), - BOOL_OPTION("PrependAvatarInfoToRealname",true,KviOption_sectFlagConnection), - BOOL_OPTION("EnableAnimatedAvatars",true,KviOption_sectFlagGui | KviOption_resetUpdateGui), - BOOL_OPTION("EnableAnimatedSmiles",true,KviOption_sectFlagGui | KviOption_resetUpdateGui), - BOOL_OPTION("PlaceNickWithNonAlphaCharsAtEnd",true,KviOption_sectFlagGui | KviOption_resetUpdateGui), - BOOL_OPTION("UseStartTlsIfAvailable",true,KviOption_sectFlagConnection), - BOOL_OPTION("PasteLastLogOnChannelJoin",false,KviOption_sectFlagLogging), - BOOL_OPTION("PasteLastLogOnQueryJoin",false,KviOption_sectFlagLogging), - BOOL_OPTION("UseSpecifiedSmartColorForOwnNick",false,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("ZshLikeNickCompletion",false,KviOption_sectFlagInput), - BOOL_OPTION("AutoAcceptDccVideo", false, KviOption_sectFlagDcc), - BOOL_OPTION("CreateMinimizedDccVideo", false, KviOption_sectFlagDcc), - BOOL_OPTION("CreateMinimizedDccVideoWhenAutoAccepted",true,KviOption_sectFlagDcc), - BOOL_OPTION("ShowTreeWindowListHeader",false,KviOption_sectFlagWindowList | KviOption_resetUpdateGui | KviOption_groupTheme), - BOOL_OPTION("FlashDccChatWindowOnNewMessages",true,KviOption_sectFlagFrame), - BOOL_OPTION("PopupNotifierOnNewDccChatMessages",true,KviOption_sectFlagFrame), - BOOL_OPTION("UseAwayMessage",true,KviOption_sectFlagConnection), - BOOL_OPTION("DisableQuietBanListRequestOnJoin",true,KviOption_sectFlagConnection), - BOOL_OPTION("UseSaslIfAvailable",true,KviOption_sectFlagConnection), - BOOL_OPTION("FrameIsMaximized",false,KviOption_sectFlagGeometry), - BOOL_OPTION("PrependNickColorInfoToRealname",true,KviOption_sectFlagConnection), - BOOL_OPTION("DontShowNotifierIfActiveWindowIsFullScreen",true,KviOption_sectFlagFrame), - BOOL_OPTION("WheelScrollsWindowsList",true,KviOption_sectFlagWindowList), - BOOL_OPTION("AcceptMismatchedPortDccResumeRequests",false,KviOption_sectFlagDcc), - BOOL_OPTION("EnableUrlLinkToolTip",true,KviOption_sectFlagGui), - BOOL_OPTION("EnableHostLinkToolTip",true,KviOption_sectFlagGui), - BOOL_OPTION("EnableServerLinkToolTip",true,KviOption_sectFlagGui), - BOOL_OPTION("EnableModeLinkToolTip",true,KviOption_sectFlagGui), - BOOL_OPTION("EnableNickLinkToolTip",true,KviOption_sectFlagGui), - BOOL_OPTION("EnableChannelLinkToolTip",true,KviOption_sectFlagGui), - BOOL_OPTION("EnableEscapeLinkToolTip",true,KviOption_sectFlagGui), - BOOL_OPTION("UseDBusNotifier",false,KviOption_sectFlagConnection) -}; - -#define STRING_OPTION(_txt,_val,_flags) KviStringOption(KVI_STRING_OPTIONS_PREFIX _txt,_val,_flags) - -// FIXME: #warning "Remove the unused string options here!" - -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - #define RUN_THE_BROWSER "run \"cmd.exe /c start \\\"\\\" \\\"$0\\\"\"" -#else - #ifdef COMPILE_KDE_SUPPORT - #define RUN_THE_BROWSER "run xdg-open $0" - #else - #ifdef COMPILE_ON_MAC - #define RUN_THE_BROWSER "run open $0" - #else - #define RUN_THE_BROWSER "run xdg-open $0" - #endif - #endif -#endif - -KviStringOption g_stringOptionsTable[KVI_NUM_STRING_OPTIONS]= -{ - STRING_OPTION("UNUSED:FrameCaption","",KviOption_sectFlagFrame), - STRING_OPTION("Nickname1",KVI_DEFAULT_NICKNAME1,KviOption_sectFlagUser), - STRING_OPTION("Nickname2","",KviOption_sectFlagUser), - STRING_OPTION("Nickname3","",KviOption_sectFlagUser), - STRING_OPTION("Nickname4","",KviOption_sectFlagUser), - STRING_OPTION("Username",KVI_DEFAULT_USERNAME,KviOption_sectFlagUser), - STRING_OPTION("Realname",KVI_DEFAULT_REALNAME,KviOption_sectFlagUser), - STRING_OPTION("LocalHostIp","127.0.0.1",KviOption_sectFlagIrcSocket), - STRING_OPTION("PartMessage",KVI_DEFAULT_PART_MESSAGE,KviOption_sectFlagConnection), - STRING_OPTION("QuitMessage",KVI_DEFAULT_QUIT_MESSAGE,KviOption_sectFlagConnection), - STRING_OPTION("UrlHttpCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), - STRING_OPTION("ExtendedPrivmsgPrefix","[",KviOption_sectFlagIrcView | KviOption_groupTheme), - STRING_OPTION("ExtendedPrivmsgPostfix","] ",KviOption_sectFlagIrcView | KviOption_groupTheme), - STRING_OPTION("CtcpVersionPostfix","",KviOption_sectFlagCtcp), - STRING_OPTION("CtcpUserInfoOther",KVI_DEFAULT_CTCP_USERINFO_REPLY,KviOption_sectFlagUser), - STRING_OPTION("CtcpSourcePostfix","",KviOption_sectFlagCtcp), - STRING_OPTION("UrlFtpCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), - STRING_OPTION("UrlHttpsCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), - STRING_OPTION("UrlMailtoCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), - STRING_OPTION("PreferredMediaPlayer","auto",KviOption_sectFlagFrame), - STRING_OPTION("UrlFileCommand","play $0",KviOption_sectFlagUrl), - STRING_OPTION("NickCompletionPostfix",": ",KviOption_sectFlagInput), - STRING_OPTION("UrlUnknownCommand",RUN_THE_BROWSER,KviOption_sectFlagUrl), - STRING_OPTION("IPv4ConnectionBindAddress","",KviOption_sectFlagConnection), - STRING_OPTION("IPv6ConnectionBindAddress","",KviOption_sectFlagConnection), - STRING_OPTION("DccVoiceSoundDevice", "/dev/dsp",KviOption_sectFlagDcc), - STRING_OPTION("DccVoiceMixerDevice", "/dev/mixer",KviOption_sectFlagDcc), - STRING_OPTION("AwayMessage",KVI_DEFAULT_AWAY_MESSAGE,KviOption_sectFlagConnection), - STRING_OPTION("IdentdUser","kvirc",KviOption_sectFlagConnection | KviOption_resetRestartIdentd), - STRING_OPTION("DccListenDefaultInterface","ppp0",KviOption_sectFlagDcc), - STRING_OPTION("CustomAwayNick", KVI_DEFAULT_AWAY_NICK,KviOption_sectFlagConnection), - STRING_OPTION("DefaultDccFakeAddress","",KviOption_sectFlagDcc), - STRING_OPTION("CtcpPageReply",KVI_DEFAULT_CTCP_PAGE_REPLY,KviOption_sectFlagCtcp), - STRING_OPTION("SSLCertificatePath","",KviOption_sectFlagConnection | KviOption_encodePath), - STRING_OPTION("SSLCertificatePass","",KviOption_sectFlagConnection), - STRING_OPTION("SSLPrivateKeyPath","",KviOption_sectFlagConnection | KviOption_encodePath), - STRING_OPTION("SSLPrivateKeyPass","",KviOption_sectFlagConnection), - STRING_OPTION("SoundSystem","unknown",KviOption_sectFlagFrame), - STRING_OPTION("DefaultUserMode", "", KviOption_sectFlagUser), - STRING_OPTION("LastImageDialogPath","",KviOption_sectFlagUser | KviOption_encodePath), - STRING_OPTION("IconThemeSubdir","",KviOption_sectFlagUser | KviOption_groupTheme | KviOption_resetReloadImages | KviOption_encodePath), - STRING_OPTION("IncomingPath","",KviOption_sectFlagUser | KviOption_encodePath), - STRING_OPTION("MyAvatar","",KviOption_sectFlagUser), - STRING_OPTION("DefaultTextEncoding","",KviOption_sectFlagFrame), - STRING_OPTION("WinampTextEncoding","",KviOption_sectFlagFrame), - STRING_OPTION("Mp3TagsEncoding","",KviOption_sectFlagFrame), - STRING_OPTION("CtcpUserInfoAge","",KviOption_sectFlagUser), - STRING_OPTION("CtcpUserInfoGender","",KviOption_sectFlagUser), - STRING_OPTION("CtcpUserInfoLocation","",KviOption_sectFlagUser), - STRING_OPTION("CtcpUserInfoLanguages","",KviOption_sectFlagUser), - STRING_OPTION("WordSplitters",",\"';:|.%^~!\\$#()?",KviOption_sectFlagIrcView), - STRING_OPTION("OnNewQueryOpenedSound","",KviOption_sectFlagFrame), - STRING_OPTION("OnHighlightedMessageSound","",KviOption_sectFlagFrame), - STRING_OPTION("OnMeKickedSound","",KviOption_sectFlagFrame), - STRING_OPTION("OnQueryMessageSound","",KviOption_sectFlagFrame), - STRING_OPTION("IrcViewTimestampFormat","[hh:mm:ss]",KviOption_sectFlagIrcView), - STRING_OPTION("PreferredTorrentClient","auto",KviOption_sectFlagFrame), - STRING_OPTION("DefaultSrvEncoding","",KviOption_sectFlagFrame), - STRING_OPTION("LogsPath","",KviOption_sectFlagUser | KviOption_encodePath) -}; - -#define STRINGLIST_OPTION(_txt,_flags) \ - KviStringListOption(KVI_STRINGLIST_OPTIONS_PREFIX _txt,QStringList(),_flags) - -#define STRINGLIST_OPTION_WITHDEFAULT(_txt,_flags,_def) \ - KviStringListOption(KVI_STRINGLIST_OPTIONS_PREFIX _txt,QStringList(_def),_flags) - - -KviStringListOption g_stringlistOptionsTable[KVI_NUM_STRINGLIST_OPTIONS]= -{ - STRINGLIST_OPTION("HighlightWords",KviOption_sectFlagIrcView), - STRINGLIST_OPTION("SpamWords",KviOption_sectFlagAntiSpam), - STRINGLIST_OPTION_WITHDEFAULT("RecentChannels",KviOption_sectFlagRecent,"#kvirc" KVI_RECENT_CHANNELS_SEPARATOR "freenode"), - STRINGLIST_OPTION("RecentServers",KviOption_sectFlagRecent), - STRINGLIST_OPTION("RecentNicknames",KviOption_sectFlagRecent), - STRINGLIST_OPTION("ModuleExtensionToolbars",KviOption_sectFlagFrame), - STRINGLIST_OPTION("ImageSearchPaths",KviOption_sectFlagFrame | KviOption_encodePath), - STRINGLIST_OPTION("RecentIrcUrls",KviOption_sectFlagRecent) -}; - -#define MIRC_COLOR_OPTION(_num,_red,_green,_blue) \ - KviColorOption(KVI_MIRCCOLOR_OPTIONS_PREFIX _num,QColor(_red,_green,_blue), \ - KviOption_sectFlagMircColor | KviOption_resetUpdateGui | KviOption_groupTheme) - -KviColorOption g_mirccolorOptionsTable[KVI_NUM_MIRCCOLOR_OPTIONS]= -{ - MIRC_COLOR_OPTION("0",255,255,255), - MIRC_COLOR_OPTION("1",0,0,0), - MIRC_COLOR_OPTION("2",0,0,140), - MIRC_COLOR_OPTION("3",0,100,0), - MIRC_COLOR_OPTION("4",230,0,0), - MIRC_COLOR_OPTION("5",150,0,0), - MIRC_COLOR_OPTION("6",80,0,80), - MIRC_COLOR_OPTION("7",255,90,0), - MIRC_COLOR_OPTION("8",255,255,0), - MIRC_COLOR_OPTION("9",0,255,0), - MIRC_COLOR_OPTION("10",0,150,180), - MIRC_COLOR_OPTION("11",170,170,255), - MIRC_COLOR_OPTION("12",15,15,255), - MIRC_COLOR_OPTION("13",200,0,200), - MIRC_COLOR_OPTION("14",80,80,80), - MIRC_COLOR_OPTION("15",170,170,170) -}; - -#define COLOR_OPTION(_name,_red,_green,_blue,_flags) \ - KviColorOption(KVI_COLOR_OPTIONS_PREFIX _name, \ - QColor(_red,_green,_blue), \ - _flags | KviOption_resetUpdateGui | KviOption_groupTheme | KviOption_resetUpdatePseudoTransparency) - -KviColorOption g_colorOptionsTable[KVI_NUM_COLOR_OPTIONS]= -{ - COLOR_OPTION("MdiBackground",0,0,0,KviOption_sectFlagMdi), - COLOR_OPTION("WindowListNormalText",0,0,0,KviOption_sectFlagWindowList), - COLOR_OPTION("WindowListMinimizedText",60,60,60,KviOption_sectFlagWindowList), - COLOR_OPTION("WindowListHighlight1Text",0,16,144,KviOption_sectFlagWindowList), - COLOR_OPTION("WindowListHighlight2Text",32,0,255,KviOption_sectFlagWindowList), - COLOR_OPTION("WindowListProgressBar",180,180,180,KviOption_sectFlagWindowList), - COLOR_OPTION("UserListViewAwayForeground",143,143,143,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewOwnForeground",255,255,0,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewIrcOpForeground",200,0,0,KviOption_sectFlagUserListView), - COLOR_OPTION("NotifierBackground",255,255,255,KviOption_sectFlagNotifier), - COLOR_OPTION("NotifierForeground",0,0,0,KviOption_sectFlagNotifier), - COLOR_OPTION("NotifierTitleForeground",255,255,255,KviOption_sectFlagNotifier), - COLOR_OPTION("IrcViewBackground",255,255,255,KviOption_sectFlagIrcView), - COLOR_OPTION("InputBackgroundColor",255,255,255,KviOption_sectFlagInput), - COLOR_OPTION("InputSelectionBackground",0,0,0,KviOption_sectFlagInput), - COLOR_OPTION("InputSelectionForeground",255,255,255,KviOption_sectFlagInput), - COLOR_OPTION("InputCursor",0,0,0,KviOption_sectFlagInput), - COLOR_OPTION("InputControl",200,100,0,KviOption_sectFlagInput), - COLOR_OPTION("InputForeground",0,0,0,KviOption_sectFlagInput), - COLOR_OPTION("UserListViewBackground",255,255,255,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewOpForeground",200,0,0,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewVoiceForeground",0,0,200,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewNormalForeground",0,0,0,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewSelectionBackground",0,0,0,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewSelectionForeground",255,255,255,KviOption_sectFlagUserListView), - COLOR_OPTION("LabelBackground",255,255,255,KviOption_sectFlagLabel), - COLOR_OPTION("LabelForeground",0,0,0,KviOption_sectFlagLabel), - COLOR_OPTION("GlobalTransparencyFade",255,255,255,KviOption_sectFlagGui), - COLOR_OPTION("IrcToolBarAppletBackground",255,255,255,KviOption_sectFlagIrcToolBar), - COLOR_OPTION("IrcToolBarAppletForegroundLowContrast",180,180,180,KviOption_sectFlagIrcToolBar), - COLOR_OPTION("IrcToolBarAppletForegroundMidContrast",110,110,110,KviOption_sectFlagIrcToolBar), - COLOR_OPTION("IrcToolBarAppletForegroundHighContrastInactive1",40,40,40,KviOption_sectFlagIrcToolBar), - COLOR_OPTION("IrcToolBarAppletForegroundHighContrastInactive2",40,40,40,KviOption_sectFlagIrcToolBar), - COLOR_OPTION("IrcToolBarAppletForegroundHighContrastActive1",0,0,0,KviOption_sectFlagIrcToolBar), - COLOR_OPTION("IrcToolBarAppletForegroundHighContrastActive2",0,60,0,KviOption_sectFlagIrcToolBar), - COLOR_OPTION("TreeWindowListBackground",255,255,255,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListActiveBackground",200,200,200,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListForeground",0,0,0,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListActiveForeground",0,0,0,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListHighlight1Foreground",0,16,144,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListHighlight2Foreground",32,0,255,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListProgress",150,150,150,KviOption_sectFlagWindowList), - COLOR_OPTION("UserListViewHalfOpForeground",119,0,178,KviOption_sectFlagUserListView), - COLOR_OPTION("WindowListHighlight3Text",128,20,255,KviOption_sectFlagWindowList), - COLOR_OPTION("WindowListHighlight4Text",220,0,255,KviOption_sectFlagWindowList), - COLOR_OPTION("WindowListHighlight5Text",255,0,0,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListHighlight3Foreground",128,0,255,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListHighlight4Foreground",220,0,255,KviOption_sectFlagWindowList), - COLOR_OPTION("TreeWindowListHighlight5Foreground",255,0,0,KviOption_sectFlagWindowList), - COLOR_OPTION("UserListViewChanAdminForeground",83,54,5,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewUserOpForeground",0,127,178,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewGrid",110,110,110,KviOption_sectFlagUserListView), - COLOR_OPTION("UserListViewChanOwnerForeground",81,87,111,KviOption_sectFlagUserListView), - COLOR_OPTION("IrcViewMarkLine",40,40,40,KviOption_sectFlagIrcView) -}; - - -#define IC_COLOR_OPTION(_num,_red,_green,_blue) \ - KviColorOption( \ - KVI_ICCOLOR_OPTIONS_PREFIX _num, \ - QColor(_red,_green,_blue), \ - KviOption_sectFlagWindowList | KviOption_resetUpdateGui | KviOption_groupTheme) - -KviColorOption g_iccolorOptionsTable[KVI_NUM_ICCOLOR_OPTIONS]= -{ - IC_COLOR_OPTION("0",250,250,0), - IC_COLOR_OPTION("1",0,0,0), - IC_COLOR_OPTION("2",0,0,200), - IC_COLOR_OPTION("3",200,0,0), - IC_COLOR_OPTION("4",255,255,255), - IC_COLOR_OPTION("5",0,150,190), - IC_COLOR_OPTION("6",0,130,0), - IC_COLOR_OPTION("7",150,0,170) -}; - -#define PIXMAP_OPTION(_name,_flags) \ - KviPixmapOption( \ - KVI_PIXMAP_OPTIONS_PREFIX _name, \ - KviPixmap(), \ - _flags | KviOption_resetUpdateGui) - -KviPixmapOption g_pixmapOptionsTable[KVI_NUM_PIXMAP_OPTIONS]= -{ - PIXMAP_OPTION("MdiBackground",KviOption_sectFlagMdi | KviOption_groupTheme), - PIXMAP_OPTION("IrcViewBackground",KviOption_sectFlagIrcView | KviOption_groupTheme), - PIXMAP_OPTION("InputBackground",KviOption_sectFlagInput | KviOption_groupTheme), - PIXMAP_OPTION("UserListViewBackground",KviOption_sectFlagUserListView | KviOption_groupTheme), - PIXMAP_OPTION("LabelBackground",KviOption_sectFlagLabel | KviOption_groupTheme), - PIXMAP_OPTION("MyAvatar",KviOption_sectFlagUser), - PIXMAP_OPTION("IrcToolBarAppletBackground",KviOption_sectFlagIrcToolBar | KviOption_groupTheme), - PIXMAP_OPTION("TreeWindowListBackground",KviOption_sectFlagWindowList | KviOption_groupTheme), - PIXMAP_OPTION("GlobalTransparencyBackground",KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), - PIXMAP_OPTION("NotifierBackground",KviOption_sectFlagNotifier | KviOption_groupTheme) -}; - -//#define INT_OPTION(_name,_value,_flags) -// { -// KVI_INT_OPTIONS_PREFIX _name, -// _value, -// _flags -// } -// -//KviIntOption g_intOptionsTable[KVI_NUM_INT_OPTIONS]= -//{ -// INT_OPTION("IrcViewMaxBufferSize",KVI_IRCVIEW_MAX_LINES,KviOption_sectFlagIrcView), -// INT_OPTION("IrcViewTollTipTimeoutInMsec",1800,KviOption_sectFlagIrcView), -// INT_OPTION("IrcViewToolTipHideTimeoutInMsec",10000,KviOption_sectFlagIrcView) -//}; - -#define UINT_OPTION(_name,_value,_flags) \ - KviUIntOption( \ - KVI_UINT_OPTIONS_PREFIX _name, \ - _value, \ - _flags \ - ) - -KviUIntOption g_uintOptionsTable[KVI_NUM_UINT_OPTIONS]= -{ - UINT_OPTION("IrcSocketTimeout",60,KviOption_sectFlagIrcSocket), - UINT_OPTION("ModuleCleanupTimerInterval",90,KviOption_sectFlagModules), - UINT_OPTION("ModuleCleanupTimeout",180,KviOption_sectFlagModules), - UINT_OPTION("MaxCtcpRequests",5,KviOption_sectFlagCtcp), - UINT_OPTION("CtcpFloodCheckInterval",10,KviOption_sectFlagCtcp), - UINT_OPTION("TotalConnectionTime",0,0), - UINT_OPTION("DccSocketTimeout",360,KviOption_sectFlagDcc), - UINT_OPTION("DccSendIdleStepInMSec",30,KviOption_sectFlagDcc), - UINT_OPTION("DccSendPacketSize",4096,KviOption_sectFlagDcc), - UINT_OPTION("GlobalTransparencyParentFadeFactor",10,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), - UINT_OPTION("GlobalTransparencyChildFadeFactor",50,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), - UINT_OPTION("NotifyListCheckTimeInSecs",180,KviOption_sectFlagConnection), - UINT_OPTION("SocketQueueFlushTimeout",500,KviOption_sectFlagIrcSocket), - UINT_OPTION("OutgoingTrafficLimitUSeconds",2000000,KviOption_sectFlagIrcSocket), - UINT_OPTION("NotifyListIsOnDelayTimeInSecs",6,KviOption_sectFlagConnection), - UINT_OPTION("NotifyListUserhostDelayTimeInSecs",6,KviOption_sectFlagConnection), - UINT_OPTION("TreeWindowListMinimumWidth",24,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), - UINT_OPTION("AvatarOfferTimeoutInSecs",60,KviOption_sectFlagAvatar), - UINT_OPTION("IrcViewMaxBufferSize",1024,KviOption_sectFlagIrcView), - UINT_OPTION("IrcViewToolTipTimeoutInMsec",1200,KviOption_sectFlagIrcView), - UINT_OPTION("IrcViewToolTipHideTimeoutInMsec",12000,KviOption_sectFlagIrcView), - UINT_OPTION("DccVoicePreBufferSize",32000,KviOption_sectFlagDcc), - UINT_OPTION("IdentdPort",113,KviOption_sectFlagConnection | KviOption_resetRestartIdentd), - UINT_OPTION("AvatarScaleWidth",80,KviOption_sectFlagAvatar | KviOption_resetUpdateGui), - UINT_OPTION("AvatarScaleHeight",80,KviOption_sectFlagAvatar | KviOption_resetUpdateGui), - UINT_OPTION("DccMinPort",30000,KviOption_sectFlagDcc), - UINT_OPTION("DccMaxPort",31000,KviOption_sectFlagDcc), - UINT_OPTION("SoundOfferTimeoutInSecs",60,KviOption_sectFlagConnection), - UINT_OPTION("MaximumRequestedAvatarSize",524288,KviOption_sectFlagAvatar), - UINT_OPTION("GlobalWindowOpacityPercent",100,KviOption_sectFlagGui | KviOption_resetUpdatePseudoTransparency | KviOption_groupTheme), - UINT_OPTION("PasteDelay",2000,KviOption_sectFlagInput), - UINT_OPTION("MaxDccSendTransfers",10,KviOption_sectFlagDcc), - UINT_OPTION("MaxDccSlots",64,KviOption_sectFlagDcc), - UINT_OPTION("TileMethod",5,KviOption_sectFlagMdi), - UINT_OPTION("LagMeterHeartbeat",5000,KviOption_sectFlagConnection | KviOption_resetRestartLagMeter), - UINT_OPTION("LagAlarmTime",120000,KviOption_sectFlagConnection), - UINT_OPTION("UNUSED",0,KviOption_sectFlagFrame), - UINT_OPTION("WindowListButtonMinWidth",100,KviOption_sectFlagWindowList), - UINT_OPTION("OutputVerbosityLevel",KVI_VERBOSITY_LEVEL_NORMAL,KviOption_sectFlagFrame), - UINT_OPTION("IrcContextAppletWidth",160,KviOption_sectFlagFrame), - UINT_OPTION("MinHighlightLevel",0,KviOption_uintMinHighlightLevel), - UINT_OPTION("UserListViewGridType",3,KviOption_sectFlagUserListView | KviOption_resetUpdateGui | KviOption_groupTheme), - UINT_OPTION("WindowListMaximumRows",2,KviOption_sectFlagFrame), - UINT_OPTION("MaxAutoReconnectAttempts",15,KviOption_sectFlagFrame), - UINT_OPTION("AutoReconnectDelay",10,KviOption_sectFlagFrame), - UINT_OPTION("MaxDccSendSpeed",0,KviOption_sectFlagFrame), - UINT_OPTION("MaxDccRecvSpeed",0,KviOption_sectFlagFrame), - UINT_OPTION("TimeStampForeground",KVI_DARKGRAY,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - UINT_OPTION("TimeStampBackground",KVI_TRANSPARENT,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - UINT_OPTION("UserExperienceLevel",1,KviOption_sectFlagUser), - UINT_OPTION("ClassicWindowListMaximumButtonWidth",100,KviOption_sectFlagGeometry | KviOption_resetUpdateGui | KviOption_groupTheme), - UINT_OPTION("DefaultBanType",7,KviOption_sectFlagIrcSocket), - UINT_OPTION("IrcViewPixmapAlign",0,KviOption_sectFlagIrcView | KviOption_groupTheme), - UINT_OPTION("UserListPixmapAlign",0,KviOption_sectFlagFrame | KviOption_groupTheme), - UINT_OPTION("ToolBarAppletPixmapAlign",0,KviOption_sectFlagFrame | KviOption_groupTheme), - UINT_OPTION("TreeWindowListPixmapAlign",0,KviOption_sectFlagFrame | KviOption_groupTheme), - UINT_OPTION("InputPixmapAlign",0,KviOption_sectFlagFrame | KviOption_groupTheme), - UINT_OPTION("AutoFlushLogs",30,KviOption_sectFlagFrame), - UINT_OPTION("MinTrayLowLevelMessage",1,KviOption_sectFlagFrame), - UINT_OPTION("MinTrayHighLevelMessage",4,KviOption_sectFlagFrame), - UINT_OPTION("IdentdOutputMode",KviIdentdOutputMode::Quiet,KviOption_sectFlagConnection), - UINT_OPTION("ScaleAvatarsOnLoadHeight",640,KviOption_sectFlagAvatar), - UINT_OPTION("ScaleAvatarsOnLoadWidth",480,KviOption_sectFlagAvatar), - UINT_OPTION("NotifierActiveTransparency",100,KviOption_sectFlagNotifier | KviOption_groupTheme), - UINT_OPTION("NotifierInactiveTransparency",80,KviOption_sectFlagNotifier | KviOption_groupTheme), // this may be cool but it confuses the user - UINT_OPTION("IrcViewMarkerStyle",0,KviOption_sectFlagIrcView | KviOption_groupTheme), - UINT_OPTION("IrcViewMarkerSize",1,KviOption_sectFlagIrcView | KviOption_groupTheme), - UINT_OPTION("UrlMouseClickNum",2,KviOption_sectFlagUrl), - UINT_OPTION("NotifierAutoHideTime",30,KviOption_sectFlagModules), - UINT_OPTION("LinesToPasteOnChannelJoin",10,KviOption_sectFlagLogging), - UINT_OPTION("DaysIntervalToPasteOnChannelJoin",10,KviOption_sectFlagLogging), - UINT_OPTION("LinesToPasteOnQueryJoin",10,KviOption_sectFlagLogging), - UINT_OPTION("DaysIntervalToPasteOnQueryJoin",10,KviOption_sectFlagLogging), - UINT_OPTION("SpacesToExpandTabulationInput",4,KviOption_sectFlagInput), - UINT_OPTION("UserIrcViewOwnForeground",4,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - UINT_OPTION("UserIrcViewOwnBackground",8,KviOption_sectFlagIrcView | KviOption_resetUpdateGui | KviOption_groupTheme), - UINT_OPTION("NotifierPixmapAlign",0,KviOption_sectFlagNotifier | KviOption_groupTheme), - UINT_OPTION("OutputDatetimeFormat",0,KviOption_sectFlagIrcView), - UINT_OPTION("OnJoinRequestsDelay",1,KviOption_sectFlagConnection), // FIXME: Wouldn't this be nicer in msecs defaulting to 100-200 ? -}; - -#define FONT_OPTION(_name,_face,_size,_flags) \ - KviFontOption( \ - KVI_FONT_OPTIONS_PREFIX _name, \ - QFont(_face,_size), \ - _flags | KviOption_groupTheme \ - ) - -KviFontOption g_fontOptionsTable[KVI_NUM_FONT_OPTIONS]= -{ -#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) - FONT_OPTION("IrcView","Arial",9,KviOption_sectFlagIrcView | KviOption_resetUpdateGui), - FONT_OPTION("Input","Arial",12,KviOption_sectFlagInput | KviOption_resetUpdateGui), - FONT_OPTION("UserListView","Arial",9,KviOption_sectFlagUserListView | KviOption_resetUpdateGui), - FONT_OPTION("Label","Arial",9,KviOption_sectFlagLabel | KviOption_resetUpdateGui), - FONT_OPTION("Application","Arial",9,KviOption_sectFlagGui | KviOption_resetUpdateAppFont), - FONT_OPTION("IrcToolBarApplet","Arial",9,KviOption_sectFlagIrcToolBar | KviOption_resetUpdateGui), - FONT_OPTION("WindowList","Arial",9,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), - FONT_OPTION("TreeWindowList","Arial",9,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), - FONT_OPTION("Notifier","Arial",9,KviOption_sectFlagNotifier | KviOption_resetUpdateGui), - FONT_OPTION("NotifierTitle","Arial",9,KviOption_sectFlagNotifier | KviOption_resetUpdateGui) -#else - FONT_OPTION("IrcView","Monospace",10,KviOption_sectFlagIrcView | KviOption_resetUpdateGui), - FONT_OPTION("Input","Sans Serif",12,KviOption_sectFlagInput | KviOption_resetUpdateGui), - FONT_OPTION("UserListView","Sans Serif",10,KviOption_sectFlagUserListView | KviOption_resetUpdateGui), - FONT_OPTION("Label","Sans Serif",10,KviOption_sectFlagLabel | KviOption_resetUpdateGui), - FONT_OPTION("Application","Sans Serif",10,KviOption_sectFlagGui | KviOption_resetUpdateAppFont), - FONT_OPTION("IrcToolBarApplet","Sans Serif",10,KviOption_sectFlagIrcToolBar | KviOption_resetUpdateGui), - FONT_OPTION("WindowList","Sans Serif",10,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), - FONT_OPTION("TreeWindowList","Sans Serif",10,KviOption_sectFlagWindowList | KviOption_resetUpdateWindowList), - FONT_OPTION("Notifier","Sans Serif",9,KviOption_sectFlagNotifier | KviOption_resetUpdateNotifier), - FONT_OPTION("NotifierTitle","Sans Serif",9,KviOption_sectFlagNotifier | KviOption_resetUpdateNotifier) -#endif -}; - -#define MSGTYPE_OPTION(_name,_text,_icon,_levl) \ - KviMessageTypeSettingsOption( \ - KVI_MSGTYPE_OPTIONS_PREFIX _name, \ - KviMessageTypeSettings(_text,_icon,KVI_BLACK,KVI_TRANSPARENT,true,_levl), \ - KviOption_sectFlagMsgType | KviOption_groupTheme \ - ) - -#define MSGTYPE_OPTION_SPEC(_name,_text,_icon,_fore,_back,_levl) \ - KviMessageTypeSettingsOption( \ - KVI_MSGTYPE_OPTIONS_PREFIX _name, \ - KviMessageTypeSettings(_text,_icon,_fore,_back,true,_levl), \ - KviOption_sectFlagMsgType | KviOption_groupTheme \ - ) - - - -// FIXME: #warning "FIX THE ICONS HERE!!!" - -KviMessageTypeSettingsOption g_msgtypeOptionsTable[KVI_NUM_MSGTYPE_OPTIONS]= -{ - MSGTYPE_OPTION("Echo",__tr_no_lookup("Normal text"),KVI_SMALLICON_NONE,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION_SPEC("Selection",__tr_no_lookup("Selection"),KVI_SMALLICON_NONE,KVI_WHITE,KVI_BLACK,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION_SPEC("Highlight",__tr_no_lookup("Highlighted text"),KVI_SMALLICON_ALERT,KVI_WHITE,KVI_BLACK,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION_SPEC("Url",__tr_no_lookup("URL foreground"),KVI_SMALLICON_NONE,KVI_BLUE,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION_SPEC("Link",__tr_no_lookup("Link overlay foreground"),KVI_SMALLICON_NONE,KVI_BLUE,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION_SPEC("ParserError",__tr_no_lookup("Parser error"),KVI_SMALLICON_PARSERERROR,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION_SPEC("ParserWarning",__tr_no_lookup("Parser warning"),KVI_SMALLICON_PARSERWARNING,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("HostLookup",__tr_no_lookup("Host lookup result"),KVI_SMALLICON_SERVER,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("SocketMessage",__tr_no_lookup("Socket message"),KVI_SMALLICON_SOCKETMESSAGE,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("SocketWarning",__tr_no_lookup("Socket warning"),KVI_SMALLICON_SOCKETWARNING,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION_SPEC("SocketError",__tr_no_lookup("Socket error"),KVI_SMALLICON_SOCKETERROR,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION_SPEC("SystemError",__tr_no_lookup("System error"),KVI_SMALLICON_SYSTEMERROR,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("Raw",__tr_no_lookup("Raw data to server"),KVI_SMALLICON_RAW,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Connection",__tr_no_lookup("Connection status"),KVI_SMALLICON_WORLD,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("SystemWarning",__tr_no_lookup("System warning"),KVI_SMALLICON_SYSTEMWARNING,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("SystemMessage",__tr_no_lookup("System message"),KVI_SMALLICON_SYSTEMMESSAGE,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("UnhandledReply",__tr_no_lookup("Unhandled server reply"),KVI_SMALLICON_UNHANDLED,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("ServerInfo",__tr_no_lookup("Server information"),KVI_SMALLICON_SERVERINFO,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Motd",__tr_no_lookup("Server Message of the Day"),KVI_SMALLICON_MOTD,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("ServerPing",__tr_no_lookup("Server ping"),KVI_SMALLICON_SERVERPING,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Join",__tr_no_lookup("Join message"),KVI_SMALLICON_JOIN,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Part",__tr_no_lookup("Part message"),KVI_SMALLICON_PART,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Unrecognized",__tr_no_lookup("Unrecognized/broken message"),KVI_SMALLICON_UNRECOGNIZED,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Topic",__tr_no_lookup("Topic message"),KVI_SMALLICON_TOPIC,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("OwnPrivateMessage",__tr_no_lookup("Own private message"),KVI_SMALLICON_OWNPRIVMSG,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("ChannelPrivateMessage",__tr_no_lookup("Channel private message"),KVI_SMALLICON_CHANPRIVMSG,KVI_MSGTYPE_LEVEL_4), - MSGTYPE_OPTION("QueryPrivateMessage",__tr_no_lookup("Query private message"),KVI_SMALLICON_QUERYPRIVMSG,KVI_MSGTYPE_LEVEL_4), - MSGTYPE_OPTION("CtcpReply",__tr_no_lookup("CTCP reply"),KVI_SMALLICON_CTCPREPLY,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("CtcpRequestReplied",__tr_no_lookup("CTCP request replied"),KVI_SMALLICON_CTCPREQUESTREPLIED,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("CtcpRequestIgnored",__tr_no_lookup("CTCP request ignored"),KVI_SMALLICON_CTCPREQUESTIGNORED,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("CtcpRequestFlood",__tr_no_lookup("CTCP request flood warning"),KVI_SMALLICON_CTCPREQUESTFLOOD,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("CtcpRequestUnknown",__tr_no_lookup("CTCP request unknown"),KVI_SMALLICON_CTCPREQUESTUNKNOWN,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("Action",__tr_no_lookup("User action"),KVI_SMALLICON_ACTION,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("AvatarChange",__tr_no_lookup("Avatar change"),KVI_SMALLICON_AVATAR,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("Quit",__tr_no_lookup("Quit message"),KVI_SMALLICON_QUIT,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Split",__tr_no_lookup("Split message"),KVI_SMALLICON_SPLIT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("QuitSplit",__tr_no_lookup("Quit on netsplit message"),KVI_SMALLICON_QUITSPLIT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Nick",__tr_no_lookup("Nick changes"),KVI_SMALLICON_NICK,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Op",__tr_no_lookup("+o mode change"),KVI_SMALLICON_OP,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Deop",__tr_no_lookup("-o mode change"),KVI_SMALLICON_DEOP,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Voice",__tr_no_lookup("+v mode change"),KVI_SMALLICON_VOICE,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Devoice",__tr_no_lookup("-v mode change"),KVI_SMALLICON_DEVOICE,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Mode",__tr_no_lookup("Multiple user mode change"),KVI_SMALLICON_MODE,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Key",__tr_no_lookup("Channel key change"),KVI_SMALLICON_KEY,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Limit",__tr_no_lookup("Channel limit change"),KVI_SMALLICON_LIMIT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Ban",__tr_no_lookup("+b mode change"),KVI_SMALLICON_BAN,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Unban",__tr_no_lookup("-b mode change"),KVI_SMALLICON_UNBAN,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("BanExcept",__tr_no_lookup("+e mode change"),KVI_SMALLICON_BANEXCEPT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("BanUnexcept",__tr_no_lookup("-e mode change"),KVI_SMALLICON_BANUNEXCEPT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("InviteExcept",__tr_no_lookup("+I mode change"),KVI_SMALLICON_INVITEEXCEPT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("InviteUnexcept",__tr_no_lookup("-I mode change"),KVI_SMALLICON_INVITEUNEXCEPT,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("ChanMode",__tr_no_lookup("Multiple channel mode change"),KVI_SMALLICON_CHANMODE,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Who",__tr_no_lookup("Who reply"),KVI_SMALLICON_WHO,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("DccRequest",__tr_no_lookup("DCC request"),KVI_SMALLICON_DCCREQUEST,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("DccMsg",__tr_no_lookup("DCC message"),KVI_SMALLICON_DCCMSG,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("DccError",__tr_no_lookup("DCC error"),KVI_SMALLICON_DCCERROR,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("NicknameProblem",__tr_no_lookup("Nickname problem"),KVI_SMALLICON_NICKNAMEPROBLEM,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("WhoisUser",__tr_no_lookup("Whois user reply"),KVI_SMALLICON_WHOISUSER,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("WhoisChannels",__tr_no_lookup("Whois channels reply"),KVI_SMALLICON_WHOISCHANNELS,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("WhoisIdle",__tr_no_lookup("Whois idle reply"),KVI_SMALLICON_WHOISIDLE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("WhoisServer",__tr_no_lookup("Whois server reply"),KVI_SMALLICON_WHOISSERVER,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("WhoisOther",__tr_no_lookup("Whois other reply"),KVI_SMALLICON_WHOISOTHER,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("CreationTime",__tr_no_lookup("Channel creation time reply"),KVI_SMALLICON_TIME,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("NotifyOnLine",__tr_no_lookup("Notify list joins"),KVI_SMALLICON_NOTIFYONLINE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("NotifyOffLine",__tr_no_lookup("Notify list leaves"),KVI_SMALLICON_NOTIFYOFFLINE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("OwnPrivmsgCrypted",__tr_no_lookup("Own encrypted private message"),KVI_SMALLICON_OWNPRIVMSGCRYPTED,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("ChanPrivmsgCrypted",__tr_no_lookup("Channel encrypted private message"),KVI_SMALLICON_CHANPRIVMSGCRYPTED,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("QueryPrivmsgCrypted",__tr_no_lookup("Query encrypted private message"),KVI_SMALLICON_QUERYPRIVMSGCRYPTED,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("DccChatMsg",__tr_no_lookup("DCC chat message"),KVI_SMALLICON_DCCCHATMSG,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("DccChatMsgCrypted",__tr_no_lookup("Encrypted DCC chat message"),KVI_SMALLICON_DCCCHATMSGCRYPTED,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("Irc",__tr_no_lookup("Login operations completed"),KVI_SMALLICON_IRC,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Kick",__tr_no_lookup("Kick action"),KVI_SMALLICON_KICK,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Links",__tr_no_lookup("Links reply"),KVI_SMALLICON_LINKS,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Spam",__tr_no_lookup("Spam report"),KVI_SMALLICON_SPAM,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("Icq",__tr_no_lookup("ICQ message"),KVI_SMALLICON_ICQ,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("IcqMessage",__tr_no_lookup("ICQ user-message"),KVI_SMALLICON_MESSAGE,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("IcqMessageSent",__tr_no_lookup("Outgoing ICQ user-message"),KVI_SMALLICON_MESSAGESENT,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("ChannelNotice",__tr_no_lookup("Channel notice"),KVI_SMALLICON_CHANNELNOTICE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("ChannelNoticeCrypted",__tr_no_lookup("Encrypted channel notice"),KVI_SMALLICON_CHANNELNOTICECRYPTED,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("QueryNotice",__tr_no_lookup("Query notice"),KVI_SMALLICON_QUERYNOTICE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("QueryNoticeCrypted",__tr_no_lookup("Encrypted query notice"),KVI_SMALLICON_QUERYNOTICECRYPTED,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("ServerNotice",__tr_no_lookup("Server notice"),KVI_SMALLICON_SERVERNOTICE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("HalfOp",__tr_no_lookup("Halfop mode change"),KVI_SMALLICON_HALFOP,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("CtcpReplyUnknown",__tr_no_lookup("Unknown CTCP reply"),KVI_SMALLICON_CTCPREPLYUNKNOWN,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("NickServ",__tr_no_lookup("NickServ message"),KVI_SMALLICON_NICKSERV,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("ChanServ",__tr_no_lookup("ChanServ message"),KVI_SMALLICON_CHANSERV,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Away",__tr_no_lookup("Away message"),KVI_SMALLICON_AWAY,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("Ident",__tr_no_lookup("Ident message"),KVI_SMALLICON_IDENT,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("List",__tr_no_lookup("Channel list message"),KVI_SMALLICON_LIST,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("HalfDeOp",__tr_no_lookup("Half-deop mode change"),KVI_SMALLICON_HALFDEOP,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("Invite",__tr_no_lookup("Invite message"),KVI_SMALLICON_INVITE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("Multimedia",__tr_no_lookup("Multimedia message"),KVI_SMALLICON_MULTIMEDIA,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("QueryTrace",__tr_no_lookup("Query trace message"),KVI_SMALLICON_QUERYTRACE,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Wallops",__tr_no_lookup("Wallops message"),KVI_SMALLICON_WALLOPS,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("JoinError",__tr_no_lookup("Join error message"),KVI_SMALLICON_NOCHANNEL,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("BroadcastPrivmsg",__tr_no_lookup("Broadcast private message"),KVI_SMALLICON_BROADCASTPRIVMSG,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("BroadcastNotice",__tr_no_lookup("Broadcast notice"),KVI_SMALLICON_BROADCASTNOTICE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("MeKick",__tr_no_lookup("Am kicked"),KVI_SMALLICON_MEKICK,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeOp",__tr_no_lookup("Am op'd"),KVI_SMALLICON_MEOP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeVoice",__tr_no_lookup("Am voiced"),KVI_SMALLICON_MEVOICE,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeDeOp",__tr_no_lookup("Am deop'd"),KVI_SMALLICON_MEDEOP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeDeVoice",__tr_no_lookup("Am devoiced"),KVI_SMALLICON_MEDEVOICE,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeHalfOp",__tr_no_lookup("Am halfop'd"),KVI_SMALLICON_MEHALFOP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeDeHalfOp",__tr_no_lookup("Am de-halfop'd"),KVI_SMALLICON_MEDEHALFOP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeBan",__tr_no_lookup("Ban matching my mask"),KVI_SMALLICON_MEBAN,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeUnban",__tr_no_lookup("Unban matching my mask"),KVI_SMALLICON_MEUNBAN,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeBanExcept",__tr_no_lookup("Ban exception matching my mask"),KVI_SMALLICON_MEBANEXCEPT,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeBanUnExcept",__tr_no_lookup("Ban unexception matching my mask"),KVI_SMALLICON_MEBANUNEXCEPT,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeInviteExcept",__tr_no_lookup("Invite exception matching my mask"),KVI_SMALLICON_MEINVITEEXCEPT,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeInviteUnexcept",__tr_no_lookup("Invite unexception matching my mask"),KVI_SMALLICON_MEINVITEUNEXCEPT,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("Ignore",__tr_no_lookup("Ignored user message"),KVI_SMALLICON_IGNORE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("Stats",__tr_no_lookup("Server statistics"),KVI_SMALLICON_STATS,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("SSL",__tr_no_lookup("SSL message"),KVI_SMALLICON_SSL,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("Search",__tr_no_lookup("Search"),KVI_SMALLICON_SEARCH,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("GenericSuccess",__tr_no_lookup("Generic success"),KVI_SMALLICON_CYANSQUARE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION("GenericStatus",__tr_no_lookup("Generic status"),KVI_SMALLICON_GREENSQUARE,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("GenericVerbose",__tr_no_lookup("Generic verbose message"),KVI_SMALLICON_DKGREENSQUARE,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("GenericWarning",__tr_no_lookup("Generic warning"),KVI_SMALLICON_YELLOWSQUARE,KVI_MSGTYPE_LEVEL_3), - MSGTYPE_OPTION_SPEC("GenericError",__tr_no_lookup("Generic error"),KVI_SMALLICON_REDSQUARE,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION_SPEC("GenericCritical",__tr_no_lookup("Generic critical error"),KVI_SMALLICON_BLACKSQUARE,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("ChanAdmin",__tr_no_lookup("Chan admin status set"),KVI_SMALLICON_CHANADMIN,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("ChanUnAdmin",__tr_no_lookup("Chan admin status unset"),KVI_SMALLICON_CHANUNADMIN,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeChanAdmin",__tr_no_lookup("Own chan admin status set"),KVI_SMALLICON_MECHANADMIN,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeChanUnAdmin",__tr_no_lookup("Own chan admin status unset"),KVI_SMALLICON_MECHANUNADMIN,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("UserOp",__tr_no_lookup("Userop mode change"),KVI_SMALLICON_USEROP,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("UserDeOp",__tr_no_lookup("User-deop mode change"),KVI_SMALLICON_DEUSEROP,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("MeUserOp",__tr_no_lookup("Am userop'd"),KVI_SMALLICON_MEUSEROP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeDeUserOp",__tr_no_lookup("Am de-userop'd"),KVI_SMALLICON_MEDEUSEROP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION_SPEC("Verbose",__tr_no_lookup("Verbose/Debug"),KVI_SMALLICON_BINARYTEXT,KVI_DARKGRAY,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("ChanOwner",__tr_no_lookup("Chan owner status set"),KVI_SMALLICON_CHANOWNER,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("ChanUnOwner",__tr_no_lookup("Chan owner status unset"),KVI_SMALLICON_CHANUNOWNER,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeChanOwner",__tr_no_lookup("Own chan owner status set"),KVI_SMALLICON_MECHANOWNER,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeChanUnOwner",__tr_no_lookup("Own chan owner status unset"),KVI_SMALLICON_MECHANUNOWNER,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION_SPEC("ServerError",__tr_no_lookup("Server error"),KVI_SMALLICON_SERVERERROR,KVI_RED,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION_SPEC("Help",__tr_no_lookup("Help"),KVI_SMALLICON_HELP,KVI_DARKGREEN,KVI_TRANSPARENT,KVI_MSGTYPE_LEVEL_1), - MSGTYPE_OPTION("TextEncoding",__tr_no_lookup("Text Encoding Server message"),KVI_SMALLICON_TEXTENCODING,KVI_MSGTYPE_LEVEL_1), - // TODO: add icon and check what level means - // Pragma: the message level is a warning level that is rendered in the WindowList - // messages with higher level are rendered with more visible color (i.e. red) - // messages with very high level might flash the tray and end up in the notifier - // level 1 or 2 for standard torrent messages is ok - MSGTYPE_OPTION("BitTorrent",__tr_no_lookup("BitTorrent message"),KVI_SMALLICON_MULTIMEDIA,KVI_MSGTYPE_LEVEL_2), - MSGTYPE_OPTION("IrcOp",__tr_no_lookup("IRC Op status set"),KVI_SMALLICON_IRCOP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("DeIrcOp",__tr_no_lookup("IRC Op status unset"),KVI_SMALLICON_DEIRCOP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeIrcOp",__tr_no_lookup("Own IRC Op status set"),KVI_SMALLICON_MEIRCOP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("MeDeIrcOp",__tr_no_lookup("Own IRC Op status unset"),KVI_SMALLICON_MEDEIRCOP,KVI_MSGTYPE_LEVEL_5), - MSGTYPE_OPTION("Cap",__tr_no_lookup("Extended capability message"),KVI_SMALLICON_SERVERINFO,KVI_MSGTYPE_LEVEL_1) -}; - -static const char * options_section_table[KVI_NUM_OPTION_SECT_FLAGS] = -{ - "None", "Frame", "Mdi", "Windows", - "WindowList", "IrcView", "MsgType", "MircColor", - "Input", "UserParser", "Connection", "IrcSocket", - "User", "UserListView","Label", "Modules", - "Ctcp", "Dcc", "Gui", "IrcToolBar", - "Logging", "AntiSpam", "Avatar", "Url", - "Recent", "Geometry" -}; - -static void config_set_section(int flag,KviConfigurationFile * cfg) -{ - int index = flag & KviOption_sectMask; - if((index < KVI_NUM_OPTION_SECT_FLAGS) && (index >= 0)) - { - cfg->setGroup(options_section_table[index]); - } else cfg->setGroup(""); // Default group -} - -void KviApp::loadOptions() -{ - QString buffer; - if(getReadOnlyConfigPath(buffer,KVI_CONFIGFILE_MAIN)) - { - KviConfigurationFile cfg(buffer,KviConfigurationFile::Read); - - int prg = 12; - int i; - - #define READ_OPTIONS(_num,_table,_readFnc) \ - for(i=0;i<_num;i++) \ - { \ - config_set_section(_table[i].flags,&cfg); \ - _table[i].option = cfg._readFnc(_table[i].name,_table[i].option); \ - } \ - prg += 3; \ - KVI_SPLASH_SET_PROGRESS(prg) - - READ_OPTIONS(KVI_NUM_RECT_OPTIONS,g_rectOptionsTable,readRectEntry) - READ_OPTIONS(KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable,readBoolEntry) - READ_OPTIONS(KVI_NUM_STRING_OPTIONS,g_stringOptionsTable,readEntry) - READ_OPTIONS(KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable,readColorEntry) - READ_OPTIONS(KVI_NUM_PIXMAP_OPTIONS,g_pixmapOptionsTable,readPixmapEntry) - READ_OPTIONS(KVI_NUM_UINT_OPTIONS,g_uintOptionsTable,readUIntEntry) - READ_OPTIONS(KVI_NUM_FONT_OPTIONS,g_fontOptionsTable,readFontEntry) - READ_OPTIONS(KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable,readMsgTypeEntry) - READ_OPTIONS(KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable,readStringListEntry) - READ_OPTIONS(KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable,readColorEntry) - READ_OPTIONS(KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable,readColorEntry) - - for(i=0;isave(szPixPath,"PNG")) - { - cfg.writeEntry(g_pixmapOptionsTable[i].name,szPixName); - } else { - // we ignore this error for now - qDebug("failed to save %s",szPixPath.toUtf8().data()); - cfg.writeEntry(g_pixmapOptionsTable[i].name,""); - } - } else { - cfg.writeEntry(g_pixmapOptionsTable[i].name,""); - } - } - } - - cfg.writeEntry("stringIconThemeSubdir",options.subdirectory()); - - // find all the "kvi_bigicon" images that we can find in the main pics directory - QString szPicsPath; - - g_pApp->getGlobalKvircDirectory(szPicsPath,KviApp::Pics); - QDir d(szPicsPath); - QStringList sl = d.entryList(QDir::nameFiltersFromString("kvi_bigicon_*.png"),QDir::Files); - - for(QStringList::Iterator it=sl.begin();it != sl.end();it++) - { - KviCachedPixmap * p = g_pIconManager->getPixmapWithCache(*it); - if(p) - { - QString szPixPath = options.absoluteDirectory(); - szPixPath.append(KVI_PATH_SEPARATOR_CHAR); - szPixPath += *it; - - if(!KviFileUtils::copyFile(p->path(),szPixPath)) - { - options.setLastError(__tr2qs("Failed to save one of the theme images")); - return false; - } - } - } - - - szD = options.absoluteDirectory(); - szD.append(KVI_PATH_SEPARATOR_CHAR); - szD.append(KVI_SMALLICONS_SUBDIRECTORY); - - if(!KviFileUtils::makeDir(szD)) - { - options.setLastError(__tr2qs("Failed to create the theme subdirectory")); - return false; - } - - // We actually need to *save* the small icons since - // we have a compatibility mode that can load them from - // the old format kvi_smallicon_XY.png multiimage libraries. - - for(int j=0;jgetSmallIcon(j); - - QString szPixPath = options.absoluteDirectory(); - szPixPath.append(KVI_PATH_SEPARATOR_CHAR); - szPixPath.append(KVI_SMALLICONS_SUBDIRECTORY); - szPixPath.append(KVI_PATH_SEPARATOR_CHAR); - szPixPath.append("kcs_"); - szPixPath.append(g_pIconManager->getSmallIconName(j)); - szPixPath.append(".png"); - - if(!pix->save(szPixPath,"PNG",90)) - { - options.setLastError(__tr2qs("Failed to save one of the theme images")); - return false; - } - } - - return true; - } - - bool load(const QString &themeDir,KviThemeInfo &buffer) - { - if(!buffer.loadFromDirectory(themeDir)) - return false; // makes sure that themedata exists too - - // reset the current theme subdir - KVI_OPTION_STRING(KviOption_stringIconThemeSubdir) = ""; - - // reset the splash screen pointer - QString szPointerFile; - g_pApp->getLocalKvircDirectory(szPointerFile,KviApp::Themes,"current-splash"); - KviFileUtils::removeFile(szPointerFile); - - QString szD = themeDir; - KviQString::ensureLastCharIs(szD,KVI_PATH_SEPARATOR_CHAR); - szD.append(KVI_THEMEDATA_FILE_NAME); - - KviConfigurationFile cfg(szD,KviConfigurationFile::Read); - - cfg.setGroup(KVI_THEMEDATA_CONFIG_GROUP); - - int i; - int iResetFlags = 0; - - #undef READ_OPTIONS - - #define READ_OPTIONS(_num,_table,_readFnc) \ - for(i=0;i<_num;i++) \ - { \ - if(_table[i].flags & KviOption_groupTheme) \ - { \ - if(cfg.hasKey(_table[i].name)) \ - { \ - iResetFlags |= (_table[i].flags & KviOption_resetMask); \ - _table[i].option = cfg._readFnc(_table[i].name,_table[i].option); \ - } \ - } \ - } - - #define READ_ALL_OPTIONS(_num,_table,_readFnc) \ - for(i=0;i<_num;i++) \ - { \ - if(cfg.hasKey(_table[i].name)) \ - { \ - iResetFlags |= (_table[i].flags & KviOption_resetMask); \ - _table[i].option = cfg._readFnc(_table[i].name,_table[i].option); \ - } \ - } - - READ_OPTIONS(KVI_NUM_RECT_OPTIONS,g_rectOptionsTable,readRectEntry) - READ_OPTIONS(KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable,readBoolEntry) - READ_OPTIONS(KVI_NUM_STRING_OPTIONS,g_stringOptionsTable,readEntry) - READ_OPTIONS(KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable,readColorEntry) - READ_OPTIONS(KVI_NUM_UINT_OPTIONS,g_uintOptionsTable,readUIntEntry) - READ_OPTIONS(KVI_NUM_FONT_OPTIONS,g_fontOptionsTable,readFontEntry) - READ_ALL_OPTIONS(KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable,readMsgTypeEntry) - READ_OPTIONS(KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable,readStringListEntry) - READ_OPTIONS(KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable,readColorEntry) - READ_OPTIONS(KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable,readColorEntry) - - #undef READ_OPTIONS - #undef READ_ALL_OPTIONS - KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).trimmed(); - - - // the pixmap options need special processing - for(i=0;ifindImage(szBuffer,szVal); - } else { - szBuffer = szVal; - } - - KviStringConversion::fromString(szBuffer,g_pixmapOptionsTable[i].option); - - // reset anyway - iResetFlags |= g_pixmapOptionsTable[i].flags & KviOption_resetMask; - } - } - } - - // create the splash screen pointer if this theme has some pixmaps in it - if(!KVI_OPTION_STRING(KviOption_stringIconThemeSubdir).isEmpty()) - KviFileUtils::writeFile(szPointerFile,KVI_OPTION_STRING(KviOption_stringIconThemeSubdir)); - - // force reloading of images anyway - g_pApp->optionResetUpdate(iResetFlags | KviOption_resetReloadImages); - - return true; - } -}; - -void KviApp::listAvailableOptions(KviWindow *wnd) -{ - int i; - - #define LIST_OPTIONS(__txt,__num,__table) \ - wnd->output(KVI_OUT_SYSTEMMESSAGE,"%c%s%c",KVI_TEXT_BOLD,__txt,KVI_TEXT_BOLD); \ - for(i = 0;i < __num;i++)wnd->outputNoFmt(KVI_OUT_SYSTEMMESSAGE,__table[i].name); - - LIST_OPTIONS(__tr("Boolean options (1/0)"),KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable) - LIST_OPTIONS(__tr("Rectangle options (x,y,width,height)"),KVI_NUM_RECT_OPTIONS,g_rectOptionsTable) - LIST_OPTIONS(__tr("String options (string value)"),KVI_NUM_STRING_OPTIONS,g_stringOptionsTable) - LIST_OPTIONS(__tr("Color options (#RRGGBB)"),KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable) - LIST_OPTIONS(__tr("Mirccolor options (#RRGGBB)"),KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable) - LIST_OPTIONS(__tr("Irc context color options (#RRGGBB)"),KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable) - LIST_OPTIONS(__tr("Pixmap options (image path)"),KVI_NUM_PIXMAP_OPTIONS,g_pixmapOptionsTable) - LIST_OPTIONS(__tr("Unsigned integer options (unsigned integer constant)"),KVI_NUM_UINT_OPTIONS,g_uintOptionsTable) - LIST_OPTIONS(__tr("Font options (family,pointsize,style,charset,weight,flags (biusf))"),KVI_NUM_FONT_OPTIONS,g_fontOptionsTable) - LIST_OPTIONS(__tr("Message color options (image_id,foreground,background,logFlag (0/1))"),KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable) - LIST_OPTIONS(__tr("String list options (comma separated list of strings)"),KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable) - - #undef LIST_OPTIONS -} - -//using namespace KviStringConversion; -bool KviApp::getOptionString(const QString &optName,QString &buffer) -{ - - #define GET_OPTION_STRING(__numOpt,__table,__prefix,__prefixLen) \ - if(KviQString::equalCIN(optName,__prefix,__prefixLen)) \ - { \ - for(int i=0;i < __numOpt;i++) \ - { \ - if(KviQString::equalCI(optName,__table[i].name)) \ - { \ - KviStringConversion::toString(__table[i].option,buffer); \ - return true; \ - } \ - } \ - return false; \ - } - - // WARNING : stringlist prefix must go BEFORE the string prefix (otherwise it will match) - - GET_OPTION_STRING(KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable,KVI_BOOL_OPTIONS_PREFIX,KVI_BOOL_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_RECT_OPTIONS,g_rectOptionsTable,KVI_BOOL_OPTIONS_PREFIX,KVI_BOOL_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable,KVI_STRINGLIST_OPTIONS_PREFIX,KVI_STRINGLIST_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_STRING_OPTIONS,g_stringOptionsTable,KVI_STRING_OPTIONS_PREFIX,KVI_STRING_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable,KVI_COLOR_OPTIONS_PREFIX,KVI_COLOR_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable,KVI_MIRCCOLOR_OPTIONS_PREFIX,KVI_MIRCCOLOR_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable,KVI_ICCOLOR_OPTIONS_PREFIX,KVI_ICCOLOR_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_PIXMAP_OPTIONS,g_pixmapOptionsTable,KVI_PIXMAP_OPTIONS_PREFIX,KVI_PIXMAP_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_UINT_OPTIONS,g_uintOptionsTable,KVI_UINT_OPTIONS_PREFIX,KVI_UINT_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_FONT_OPTIONS,g_fontOptionsTable,KVI_FONT_OPTIONS_PREFIX,KVI_FONT_OPTIONS_PREFIX_LEN) - GET_OPTION_STRING(KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable,KVI_MSGTYPE_OPTIONS_PREFIX,KVI_MSGTYPE_OPTIONS_PREFIX_LEN) - return false; - - #undef GET_OPTION_STRING -} - -void KviApp::optionResetUpdate(int flags) -{ - if(flags & KviOption_resetReloadImages) - { - g_pIconManager->reloadImages(); - emit reloadImages(); - } - - if(flags & KviOption_resetUpdateAppFont) - { - updateApplicationFont(); - } - -#ifdef COMPILE_PSEUDO_TRANSPARENCY - if(flags & KviOption_resetUpdatePseudoTransparency) - { - triggerUpdatePseudoTransparency(); - } -#endif - - if(flags & KviOption_resetRestartIdentd) - { - if(g_iIdentDaemonRunningUsers) - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_STOP); - - if(KVI_OPTION_BOOL(KviOption_boolUseIdentService) && !KVI_OPTION_BOOL(KviOption_boolUseIdentServiceOnlyOnConnect)) - g_pFrame->executeInternalCommand(KVI_INTERNALCOMMAND_IDENT_START); - } - - if(flags & KviOption_resetUpdateGui) - { - triggerUpdateGui(); - } - - if(flags & KviOption_resetUpdateWindowList) - { - g_pFrame->recreateWindowList(); - } - - if(flags & KviOption_resetRestartNotifyList) - { - g_pApp->restartNotifyLists(); - } - - if(flags & KviOption_resetRestartLagMeter) - { - g_pApp->restartLagMeters(); - } - - if(flags & KviOption_resetRecentChannels) - { - g_pApp->buildRecentChannels(); - } - - if(flags & KviOption_resetUpdateNotifier) - { - emit updateNotifier(); - } -} -bool KviApp::setOptionValue(const QString &optName,const QString &value) -{ - if (!setCommonOptionValue(optName,value)) - return false; - - if(KviQString::equalCI(optName,"stringlistRecentChannels")) - { - buildRecentChannels(); - return true; - } - - // The pixmap options have special treating - if(KviQString::equalCIN(optName,KVI_PIXMAP_OPTIONS_PREFIX,KVI_PIXMAP_OPTIONS_PREFIX_LEN)) - { - // We lookup the image path (so we allow also relative paths for this option type) - QString szVal = value; - szVal.trimmed(); - QString szBuffer; - if(!szVal.isEmpty()) - { - findImage(szBuffer,szVal); - } else { - szBuffer = szVal; - } - - for(int i=0;i < KVI_NUM_PIXMAP_OPTIONS;i++) - { - if(KviQString::equalCI(optName,g_pixmapOptionsTable[i].name)) - { - if(!KviStringConversion::fromString(szBuffer,g_pixmapOptionsTable[i].option))return false; - optionResetUpdate(g_pixmapOptionsTable[i].flags); - return true; - } - } - return false; - } - - return true; -} - -bool KviApp::setCommonOptionValue(const QString &optName,const QString &value) -{ - - #define SET_OPTION_VALUE(__numOpt,__table,__prefix,__prefixLen) \ - if(KviQString::equalCIN(optName,__prefix,__prefixLen)) \ - { \ - for(int i=0;i < __numOpt;i++) \ - { \ - if(KviQString::equalCI(optName,__table[i].name)) \ - { \ - if(!KviStringConversion::fromString(value,__table[i].option))return false; \ - optionResetUpdate(__table[i].flags); \ - return true; \ - } \ - } \ - return false; \ - } - - SET_OPTION_VALUE(KVI_NUM_BOOL_OPTIONS,g_boolOptionsTable,KVI_BOOL_OPTIONS_PREFIX,KVI_BOOL_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_RECT_OPTIONS,g_rectOptionsTable,KVI_BOOL_OPTIONS_PREFIX,KVI_BOOL_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_STRINGLIST_OPTIONS,g_stringlistOptionsTable,KVI_STRINGLIST_OPTIONS_PREFIX,KVI_STRINGLIST_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_STRING_OPTIONS,g_stringOptionsTable,KVI_STRING_OPTIONS_PREFIX,KVI_STRING_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_COLOR_OPTIONS,g_colorOptionsTable,KVI_COLOR_OPTIONS_PREFIX,KVI_COLOR_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_MIRCCOLOR_OPTIONS,g_mirccolorOptionsTable,KVI_MIRCCOLOR_OPTIONS_PREFIX,KVI_MIRCCOLOR_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_ICCOLOR_OPTIONS,g_iccolorOptionsTable,KVI_ICCOLOR_OPTIONS_PREFIX,KVI_ICCOLOR_OPTIONS_PREFIX_LEN) -// SET_OPTION_VALUE(KVI_NUM_PIXMAP_OPTIONS,g_pixmapOptionsTable,KVI_PIXMAP_OPTIONS_PREFIX,KVI_PIXMAP_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_UINT_OPTIONS,g_uintOptionsTable,KVI_UINT_OPTIONS_PREFIX,KVI_UINT_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_FONT_OPTIONS,g_fontOptionsTable,KVI_FONT_OPTIONS_PREFIX,KVI_FONT_OPTIONS_PREFIX_LEN) - SET_OPTION_VALUE(KVI_NUM_MSGTYPE_OPTIONS,g_msgtypeOptionsTable,KVI_MSGTYPE_OPTIONS_PREFIX,KVI_MSGTYPE_OPTIONS_PREFIX_LEN) - - #undef SET_OPTION_VALUE - return true; -} diff --git a/src/kvirc/kernel/kvi_options.h b/src/kvirc/kernel/kvi_options.h deleted file mode 100644 index 3876cd788..000000000 --- a/src/kvirc/kernel/kvi_options.h +++ /dev/null @@ -1,772 +0,0 @@ -#ifndef _KVI_OPTIONS_H_ -#define _KVI_OPTIONS_H_ - -//============================================================================= -// -// File : kvi_options.h -// Creation date : Tue Jun 20 2000 12:42:07 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2000-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviCString.h" -#include "KviPixmap.h" -#include "KviMessageTypeSettings.h" - -#include -#include -#include -#include -#include - -// option structures - - -#define DECLARE_OPTION_STRUCT(_cname,_type) \ - class _cname \ - { \ - public: \ - QString name; \ - _type option; \ - int flags; \ - public: \ - _cname(const QString &n,_type o,int f) \ - : name(n), option(o), flags(f) {}; \ - ~_cname() {}; \ - }; - -DECLARE_OPTION_STRUCT(KviBoolOption,bool) -DECLARE_OPTION_STRUCT(KviRectOption,QRect) -DECLARE_OPTION_STRUCT(KviStringOption,QString) -DECLARE_OPTION_STRUCT(KviColorOption,QColor) -DECLARE_OPTION_STRUCT(KviFontOption,QFont) -DECLARE_OPTION_STRUCT(KviPixmapOption,KviPixmap) -//DECLARE_OPTION_STRUCT(KviIntOption,int) -DECLARE_OPTION_STRUCT(KviUIntOption,unsigned int) -DECLARE_OPTION_STRUCT(KviMessageTypeSettingsOption,KviMessageTypeSettings) -DECLARE_OPTION_STRUCT(KviStringListOption,QStringList) - -#define KVI_COLOR_EXT_USER_OP 50 -#define KVI_COLOR_EXT_USER_HALFOP 51 -#define KVI_COLOR_EXT_USER_ADMIN 52 -#define KVI_COLOR_EXT_USER_OWNER 53 -#define KVI_COLOR_EXT_USER_VOICE 54 -#define KVI_COLOR_EXT_USER_USEROP 55 -#define KVI_COLOR_EXT_USER_NORMAL 56 -#define KVI_COLOR_CUSTOM 255 -#define KVI_COLOR_OWN 254 - -// option entry indexes - -#define KVI_RECT_OPTIONS_PREFIX "rect" -#define KVI_RECT_OPTIONS_PREFIX_LEN 4 - -#define KviOption_rectFrameGeometry 0 /* internal */ -/* FIXME: this should be in the options module (local config) ? */ -#define KviOption_rectGeneralOptionsDialogGeometry 1 /* internal */ -/* FIXME: this should be in the regusers module (local config) ? */ -#define KviOption_rectRegisteredUsersDialogGeometry 2 /* internal */ - -#define KVI_NUM_RECT_OPTIONS 3 - - - -#define KVI_BOOL_OPTIONS_PREFIX "bool" -#define KVI_BOOL_OPTIONS_PREFIX_LEN 4 - -#define KviOption_boolWindowsRememberProperties 0 /* interface::features::global */ -#define KviOption_boolIrcViewShowImages 1 /* interface::features::components::ircview */ -#define KviOption_boolIrcViewTimestamp 2 /* interface::features::components::ircview */ -#define KviOption_boolIrcViewUrlHighlighting 3 /* interface::features::components::ircview */ -#define KviOption_boolIrcViewWrapMargin 4 /* interface::features::components::ircview */ -#define KviOption_boolInputHistoryCursorAtEnd 5 /* interface::features::components::input */ -#define KviOption_boolAvoidParserWarnings 6 /* ircengine::uparser */ -#define KviOption_boolUseProxyHost 7 /* transport */ -#define KviOption_boolShowGeneralOptionsDialogAsToplevel 8 /* interface::features::global */ -#define KviOption_boolForceBrutalQuit 9 /* irc */ -#define KviOption_boolShowPingPong 10 /* ircoutput */ -#define KviOption_boolPopupNotifierOnNewQueryMessages 11 /* query */ -#define KviOption_boolShowExtendedServerInfo 12 /* ircoutput */ -#define KviOption_boolEchoNumericTopic 13 /* channel */ -#define KviOption_boolShowOwnParts 14 /* ircoutput */ -#define KviOption_boolUseAntiSpamOnPrivmsg 15 /* ircengine::outputcontrol::antispam */ -#define KviOption_boolUseExtendedPrivmsgView 16 /* ircengine::outputcontrol::privmsg */ -#define KviOption_boolShowUserAndHostInPrivmsgView 17 /* ircengine::outputcontrol::privmsg */ -#define KviOption_boolUseWordHighlighting 18 /* ircengine::outputcontrol::highlighting */ -#define KviOption_boolUseBigIcons 19 /* internal */ -#define KviOption_boolCleanupUnusedModules 20 /* uparser ? */ -#define KviOption_boolIgnoreCtcpPing 21 /* ctcp */ -#define KviOption_boolIgnoreCtcpVersion 22 /* ctcp */ -#define KviOption_boolUseCtcpFloodProtection 23 /* ctcp */ -#define KviOption_boolDisableBrokenEventHandlers 24 /* ircengine::uparser */ -#define KviOption_boolIgnoreCtcpClientinfo 25 /* ctcp */ -#define KviOption_boolIgnoreCtcpUserinfo 26 /* ctcp */ -#define KviOption_boolIgnoreCtcpFinger 27 /* ctcp */ -#define KviOption_boolIgnoreCtcpSource 28 /* ctcp */ -#define KviOption_boolIgnoreCtcpTime 29 /* ctcp */ -#define KviOption_boolRequestMissingAvatars 30 /* ctcp::avatar */ -#define KviOption_boolShowCompactModeChanges 31 /* ircoutput */ -#define KviOption_boolIgnoreCtcpDcc 32 /* ctcp */ -#define KviOption_boolAutoAcceptDccChat 33 /* dcc::chat */ -#define KviOption_boolAutoAcceptDccSend 34 /* dcc::send */ -#define KviOption_boolSendZeroAckInDccRecv 35 /* dcc::send */ -#define KviOption_boolUseFastDccSend 36 /* dcc::send */ -#define KviOption_boolUseCompositingForTransparency 37 /* interface::look::global */ -#define KviOption_boolUseWindowListIrcContextIndicator 38 /* interface::features::global */ -#define KviOption_boolUseGlobalApplicationFont 39 /* interface::look::global */ -#define KviOption_boolAlwaysQuitKVIrcClosingLastConsole 40 /* internal */ -#define KviOption_boolAlwaysDisconnectClosingConnectedConsole 41 /* internal */ -#define KviOption_boolFlashWindowOnHighlightedMessages 42 /* highlighting */ -#define KviOption_boolPopupNotifierOnHighlightedMessages 43 /* highlighting */ -#define KviOption_boolFlashWindowOnNotifyOnLine 44 /* notify */ -#define KviOption_boolIrcViewTimestampUTC 45 /* interface::features::components::ircview */ -#define KviOption_boolUseGlobalPseudoTransparency 46 /* interface::look::global */ -#define KviOption_boolUseNotifyList 47 /* ircengine::notifylist */ -#define KviOption_boolNotifyListChangesToActiveWindow 48 /* ircengine::notifylist */ -#define KviOption_boolAutoResumeDccSendWhenAutoAccepted 49 /* dcc::send */ -#define KviOption_boolLimitOutgoingTraffic 50 /* transport */ -#define KviOption_boolSendUnknownCommandsAsRaw 51 /* ircengine::uparser */ -#define KviOption_boolUserListViewDrawGrid 52 /* look & feel::interface look::userlist */ -#define KviOption_boolShowChannelSyncTime 53 /* channel */ -#define KviOption_boolRejoinChannelOnKick 54 /* channel */ -#define KviOption_boolKeepChannelOpenOnKick 55 /* channel */ -#define KviOption_boolAutoCloseDccSendOnSuccess 56 /* dcc::send */ -#define KviOption_boolNotifyDccSendSuccessInConsole 57 /* dcc::send */ -#define KviOption_boolCreateMinimizedDccSend 58 /* dcc::send */ -#define KviOption_boolCreateMinimizedDccChat 59 /* dcc::chat */ -#define KviOption_boolAutoAcceptIncomingAvatars 60 /* irc::ctcp::avatar */ -#define KviOption_boolUseNickCompletionPostfixForFirstWordOnly 61 -#define KviOption_boolUseWindowListIcons 62 /* interface::features */ -#define KviOption_boolCreateMinimizedDccSendWhenAutoAccepted 63 /* dcc::send */ -#define KviOption_boolCreateMinimizedDccChatWhenAutoAccepted 64 /* dcc::chat */ -#define KviOption_boolDccGuessIpFromServerWhenLocalIsUnroutable 65 /* dcc */ -#define KviOption_boolShowRegisteredUsersDialogAsToplevel 66 /* interface::features::global */ -#define KviOption_boolAutoLogQueries 67 /* ircengine::logging */ -#define KviOption_boolAutoLogChannels 68 /* ircendine::logging */ -#define KviOption_boolAutoLogDccChat 69 /* ircengine::logging */ -#define KviOption_boolAutoLogConsole 70 /* ircengine::logging */ -#define KviOption_boolSilentAntiSpam 71 /* ircengine::antispam */ -#define KviOption_boolUseIncomingDccMediaTypeSavePath 72 /* dcc::send */ -#define KviOption_boolNotifyListSendUserhostForOnlineUsers 73 /* ircengine::notifylist */ -#define KviOption_boolUseIntelligentNotifyListManager 74 /* ircengine::notifylist */ -#define KviOption_boolUseWatchListIfAvailable 75 /* ircengine::notifylist */ -#define KviOption_boolUseTreeWindowListWindowList 76 /* interface::features::global */ -#define KviOption_boolBindIrcIPv4ConnectionsToSpecifiedAddress 77 /* connection::transport */ -#define KviOption_boolBindIrcIPv6ConnectionsToSpecifiedAddress 78 /* connection::transport */ -#define KviOption_boolUseAntiSpamOnNotice 79 /* ircengine::antispam */ -#define KviOption_boolSetLastAvatarAsDefaultForRegisteredUsers 80 /* irc::ctcp::avatar */ -#define KviOption_boolCantAcceptIncomingDccConnections 81 /* dcc::general */ -#define KviOption_boolIgnoreCtcpAvatar 82 /* irc::ctcp::floodprotection */ -#define KviOption_boolCtcpRepliesToActiveWindow 83 /* ctcp */ -#define KviOption_boolAutoAcceptDccCanvas 84 -#define KviOption_boolNotifyDccSendSuccessInNotifier 85 /* dcc::send */ -#define KviOption_boolKillBrokenTimers 86 /* ircengine::uparser */ -#define KviOption_boolDccVoiceVolumeSliderControlsPCM 87 /* dcc::voice */ -#define KviOption_boolDccVoiceForceHalfDuplex 88 /* dcc::voice */ -#define KviOption_boolAutoAcceptDccVoice 89 /* dcc::voice */ -#define KviOption_boolCreateMinimizedDccVoice 90 /* dcc::voice */ -#define KviOption_boolCreateMinimizedDccVoiceWhenAutoAccepted 91 /* dcc::voice */ -#define KviOption_boolUseIdentService 92 /* connection::ident */ -#define KviOption_boolShowTipAtStartup 93 /* internal */ -#define KviOption_boolIdentdEnableIPv6 94 /* connection::ident */ -#define KviOption_boolIdentdIPv6ContainsIPv4 95 /* connection::ident */ -#define KviOption_boolScaleAvatars 96 /* ctcp::avatar */ -#define KviOption_boolColorNicks 97 /* interface::features::components::ircview */ -#define KviOption_boolBoldedNicks 98 /* interface::features::components::ircview */ -#define KviOption_boolDccListenOnSpecifiedInterfaceByDefault 99 /* dcc */ -#define KviOption_boolChangeNickAway 100 /* ircengine::away */ -#define KviOption_boolAutoGeneratedAwayNick 101 /* ircengine::away */ -#define KviOption_boolExitAwayOnInput 102 /* ircengine::away */ -#define KviOption_boolAlwaysHighlightNick 103 /* ircengine::outputcontrol::highlighting */ -#define KviOption_boolShowChannelsJoinOnIrc 104 /* internal */ -#define KviOption_boolShowChannelsJoinDialogAsToplevel 105 /* FIXME: internal ??? */ -#define KviOption_boolUserDefinedPortRange 106 /* dcc */ -#define KviOption_boolCreateQueryOnPrivmsg 107 /* query */ -#define KviOption_boolCreateQueryOnNotice 108 /* query */ -#define KviOption_boolCreateMinimizedQuery 109 /* query */ -#define KviOption_boolAutoJoinOnInvite 110 /* channel */ -#define KviOption_boolShowServersConnectDialogOnStart 111 /* connection::ircservers */ -#define KviOption_boolShowServersConnectDialogAsToplevel 112 /* FIXME: internal ?? */ -#define KviOption_boolAcceptBrokenFileNameDccResumeRequests 113 /* dcc::send */ -#define KviOption_boolAutoReconnectOnUnexpectedDisconnect 114 /* connection */ -#define KviOption_boolRejoinChannelsAfterReconnect 115 /* connection */ -#define KviOption_boolReopenQueriesAfterReconnect 116 /* connection */ -#define KviOption_boolEnableQueryTracing 117 /* query */ -#define KviOption_boolOperatorMessagesToActiveWindow 118 /* irc::output */ -#define KviOption_boolInvitesToActiveWindow 119 /* irc::output */ -#define KviOption_boolShowChannelUserFlagInPrivmsgView 120 /* ircengine::outputcontrol::privmsg */ -#define KviOption_boolDccSendFakeAddressByDefault 121 /* dcc::general */ -#define KviOption_boolUseWindowListActivityMeter 122 /* irc::output */ -#define KviOption_boolCloseServerWidgetAfterConnect 123 /* IMPLEMENTATION NEEDED !!! */ -#define KviOption_boolShowIdentityDialogAsToplevel 124 /* ??? */ -#define KviOption_boolShowUserChannelIcons 125 /* look & feel::interface features::userlist */ -#define KviOption_boolShowUserChannelState 126 /* look & feel::interface features::userlist */ -#define KviOption_boolEnableIgnoreOnPrivMsg 127 /* irc::ignore */ -#define KviOption_boolVerboseIgnore 128 /* irc::ignore */ -#define KviOption_boolEnableIgnoreOnNotice 129 /* irc::ignore */ -#define KviOption_boolNotifyFailedDccHandshakes 130 -#define KviOption_boolAutoTileWindows 131 /* internal ? */ -#define KviOption_boolDrawEmoticons 132 /* look::interface::features::output */ -#define KviOption_boolIgnoreCtcpPage 133 /* irc::ctcp::floodprotection */ -#define KviOption_boolShowDialogOnCtcpPage 134 -#define KviOption_boolBashLikeNickCompletion 135 -#define KviOption_boolUseSSLCertificate 136 /* ssl */ -#define KviOption_boolUseSSLPrivateKey 137 /* ssl */ -#define KviOption_boolWarnAboutPastingMultipleLines 138 /* internal */ -#define KviOption_boolKeepChannelsOpenOnUnexpectedDisconnect 139 /* connection */ -#define KviOption_boolKeepQueriesOpenOnUnexpectedDisconnect 140 /* connection */ -#define KviOption_boolUseLagMeterEngine 141 /* irc::lag */ -#define KviOption_boolShowLagOnContextDisplay 142 /* irc::lag */ -#define KviOption_boolDisableBanListRequestOnJoin 143 /* channel */ -#define KviOption_boolDisableBanExceptionListRequestOnJoin 144 /* channel */ -#define KviOption_boolDisableInviteListRequestOnJoin 145 /* channel */ -#define KviOption_boolDisableWhoRequestOnJoin 146 /* channel */ -#define KviOption_boolShowDockExtension 147 /* internal ? */ -#define KviOption_boolDccAddressByIrcDns 148 /* irc::general */ -#define KviOption_boolMinimizeConsoleAfterConnect 149 /* irc::connection */ -#define KviOption_boolHighlightOnlyNormalMsg 150 /* irc::output::highlight */ -#define KviOption_boolHighlightOnlyNormalMsgQueryToo 151 /* irc::output::highlight */ -#define KviOption_boolHighlightOnlyNormalMsgHighlightInChanToo 152 /* irc::output::highlight */ -#define KviOption_boolHighlightOnlyAtCostumHighlightLevel 153 /* irc::output::highlight */ -#define KviOption_boolMdiManagerInSdiMode 154 /* internal */ -#define KviOption_boolDccBrokenBouncerHack 155 /* dcc */ -#define KviOption_boolExternalMessagesToActiveWindow 156 /* irc::output */ -#define KviOption_boolIgnoreChannelAvatarRequestsWhenNoAvatarSet 157 /* ctcp */ -#define KviOption_boolFlashQueryWindowOnNewMessages 158 /* query */ -#define KviOption_boolConfirmCloseWhenThereAreConnections 159 /* interface features */ -#define KviOption_boolUseWindowsDesktopForTransparency 160 /* interface::features::global */ -#define KviOption_boolCtcpRequestsToActiveWindow 161 /* irc::output */ -#define KviOption_boolServerRepliesToActiveWindow 162 /* irc::output */ -#define KviOption_boolServerNoticesToActiveWindow 163 /* irc::output */ -#define KviOption_boolServicesNoticesToActiveWindow 164 /* irc::output */ -#define KviOption_boolSortWindowListItemsByName 165 /* interface::features::global */ -#define KviOption_boolShowWindowListToolTips 166 /* interface::features::global */ -#define KviOption_boolShowUserListViewToolTips 167 /* interface::features::global */ -#define KviOption_boolWhoisRepliesToActiveWindow 168 /* irc::output */ -#define KviOption_boolPopupNotifierOnNotifyOnLine 169 /* notify */ -#define KviOption_boolEnableNotifier 170 /* notifier */ -#define KviOption_boolDccSendForceIdleStep 171 /* dcc */ -#define KviOption_boolStatusBarVisible 172 /* internal */ -#define KviOption_boolTrackLastReadTextViewLine 173 /* ircview::features */ -#define KviOption_boolKeepChannelOpenOnPart 174 /* channel */ -#define KviOption_boolStripMircColorsInUserMessages 175 /* irc::output */ -#define KviOption_boolDoNotSuggestRestoreDefaultScript 176 /* internal */ -#define KviOption_boolLimitDccSendSpeed 177 /* dcc::file transfers */ -#define KviOption_boolLimitDccRecvSpeed 178 /* dcc::file transfers */ -#define KviOption_boolIgnoreModuleVersions 179 -#define KviOption_boolEnableInputHistory 180 /* interface::input */ -#define KviOption_boolUseSpecialColorForTimestamp 181 /* interface::output */ -#define KviOption_boolEnableAwayListUpdates 182 /* channel */ -#define KviOption_boolShowAvatarsInUserlist 183 /* interface::userlist */ -#define KviOption_boolShowUserListStatisticLabel 184 /* interface::userlist */ -#define KviOption_boolShowIconsInPopupMenus 185 /* themes::general */ -#define KviOption_boolScriptErrorsToDebugWindow 186 /* parser */ -#define KviOption_boolShowMinimizedDebugWindow 187 /* parser */ -#define KviOption_boolShowExtendedInfoInQueryLabel 188 /* query */ -#define KviOption_boolUseUserListColorsAsNickColors 189 /* irc::usermessages */ -#define KviOption_boolGzipLogs 190 /* ircengine::logging */ -#define KviOption_boolUseFullWordHighlighting 191 /* highlight */ -#define KviOption_boolNotifierFlashing 192 /* interface::notifier */ -#define KviOption_boolCommandlineInUserFriendlyModeByDefault 193 /* interface::input */ -#define KviOption_boolEnableVisualEffects 194 /* interface */ -#define KviOption_boolDCCFileTransferReplaceOutgoingSpacesWithUnderscores 195 -#define KviOption_boolDoNotUpscaleAvatars 196 -#define KviOption_boolUseDifferentColorForOwnNick 197 /* interface */ -#define KviOption_boolCloseInTray 198 /* interface */ -#define KviOption_boolStartupMinimized 199 /* interface */ -#define KviOption_boolSortReceivedByDccFilesByNicks 200 /* dcc */ -#define KviOption_boolLogChannelHistory 201 /* channel */ -#define KviOption_boolClassicWindowListSetMaximumButtonWidth 202 -#define KviOption_boolKeepChannelsOpenOnDisconnect 203 /* connection */ -#define KviOption_boolKeepQueriesOpenOnDisconnect 204 /* connection */ -#define KviOption_boolHideWindowToolButtons 205 /* interface */ -#define KviOption_boolHideInputToolButtons 206 /* interface */ -#define KviOption_boolStripControlCodesInLogs 207 /* log */ -#define KviOption_boolEnableTrayIconFlashing 208 -#define KviOption_boolUseFlatClassicWindowListButtons 209 -#define KviOption_boolStripMsgTypeInLogs 210 /* log */ -#define KviOption_boolUseLevelBasedTrayNotification 211 -#define KviOption_boolMuteAllSounds 212 -#define KviOption_boolCreateMinimizedChannels 213 -#define KviOption_boolShowNetworkNameForConsoleWindowListEntry 214 -#define KviOption_boolDrawGenderIcons 215 -#define KviOption_boolPrependGenderInfoToRealname 216 -#define KviOption_boolUseIdentServiceOnlyOnConnect 217 /* connection::ident */ -#define KviOption_boolUseSystemUrlHandlers 218 /* Windoze only*/ -#define KviOption_boolScaleAvatarsOnLoad 219 -#define KviOption_boolNotifierFading 220 /* interface::notifier */ -#define KviOption_boolPickRandomIpAddressForRoundRobinServers 221 -#define KviOption_boolPrependAvatarInfoToRealname 222 -#define KviOption_boolEnableAnimatedAvatars 223 -#define KviOption_boolEnableAnimatedSmiles 224 -#define KviOption_boolPlaceNickWithNonAlphaCharsAtEnd 225 -#define KviOption_boolUseStartTlsIfAvailable 226 -#define KviOption_boolPasteLastLogOnChannelJoin 227 /* channel */ -#define KviOption_boolPasteLastLogOnQueryJoin 228 /* query */ -#define KviOption_boolUseSpecifiedSmartColorForOwnNick 229 /* interface::ircview */ -#define KviOption_boolZshLikeNickCompletion 230 -#define KviOption_boolAutoAcceptDccVideo 231 /* dcc::video */ -#define KviOption_boolCreateMinimizedDccVideo 232 /* dcc::video */ -#define KviOption_boolCreateMinimizedDccVideoWhenAutoAccepted 233 /* dcc::video */ -#define KviOption_boolShowTreeWindowListHeader 234 -#define KviOption_boolFlashDccChatWindowOnNewMessages 235 /* dcc:chat */ -#define KviOption_boolPopupNotifierOnNewDccChatMessages 236 /* dcc:chat */ -#define KviOption_boolUseAwayMessage 237 /* away */ -#define KviOption_boolDisableQuietBanListRequestOnJoin 238 /* channel */ -#define KviOption_boolUseSaslIfAvailable 239 -#define KviOption_boolFrameIsMaximized 240 /* internal */ -#define KviOption_boolPrependNickColorInfoToRealname 241 -#define KviOption_boolDontShowNotifierIfActiveWindowIsFullScreen 242 /* notifier */ -#define KviOption_boolWheelScrollsWindowsList 243 -#define KviOption_boolAcceptMismatchedPortDccResumeRequests 244 /* dcc::send */ -#define KviOption_boolEnableUrlLinkToolTip 245 /* ircview output */ -#define KviOption_boolEnableHostLinkToolTip 246 /* ircview output */ -#define KviOption_boolEnableServerLinkToolTip 247 /* ircview output */ -#define KviOption_boolEnableModeLinkToolTip 248 /* ircview output */ -#define KviOption_boolEnableNickLinkToolTip 249 /* ircview output */ -#define KviOption_boolEnableChannelLinkToolTip 250 /* ircview output */ -#define KviOption_boolEnableEscapeLinkToolTip 251 /* ircview output */ -#define KviOption_boolUseDBusNotifier 252 /* notifier */ - -#define KVI_NUM_BOOL_OPTIONS 253 - - -#define KVI_STRING_OPTIONS_PREFIX "string" -#define KVI_STRING_OPTIONS_PREFIX_LEN 6 - -//UNUSED ! #define KviOption_stringFrameCaption 0 /* interfacelookglobal */ -#define KviOption_stringNickname1 1 /* identity */ -#define KviOption_stringNickname2 2 /* identity */ -#define KviOption_stringNickname3 3 /* identity */ -#define KviOption_stringNickname4 4 /* identity */ -#define KviOption_stringUsername 5 /* identity */ -#define KviOption_stringRealname 6 /* identity */ -#define KviOption_stringLocalHostIp 7 /* ?????? This is a fallback one */ -#define KviOption_stringPartMessage 8 /* ircengine::defaultmessages */ -#define KviOption_stringQuitMessage 9 /* ircengine::defaultmessages */ -#define KviOption_stringUrlHttpCommand 10 /* urlhandlers */ -#define KviOption_stringExtendedPrivmsgPrefix 11 /* ircengine::outputcontrol::privmsg */ -#define KviOption_stringExtendedPrivmsgPostfix 12 /* ircengine::outputcontrol::privmsg */ -#define KviOption_stringCtcpVersionPostfix 13 /* ircengine::ctcp::replies */ -#define KviOption_stringCtcpUserInfoOther 14 /* identity */ -#define KviOption_stringCtcpSourcePostfix 15 /* ircengine::ctcp::replies */ -#define KviOption_stringUrlFtpCommand 16 /* urlhandlers */ -#define KviOption_stringUrlHttpsCommand 17 /* urlhandlers */ -#define KviOption_stringUrlMailtoCommand 18 /* urlhandlers */ -#define KviOption_stringPreferredMediaPlayer 19 /* still missing in options ! */ -#define KviOption_stringUrlFileCommand 20 /* urlhandlers */ -#define KviOption_stringNickCompletionPostfix 21 -#define KviOption_stringUrlUnknownCommand 22 /* urlhandlers */ -#define KviOption_stringIPv4ConnectionBindAddress 23 /* connection::transport */ -#define KviOption_stringIPv6ConnectionBindAddress 24 /* connection::transport */ -#define KviOption_stringDccVoiceSoundDevice 25 /* dcc::voice */ -#define KviOption_stringDccVoiceMixerDevice 26 /* dcc::voice */ -#define KviOption_stringAwayMessage 27 /* irc::away */ -#define KviOption_stringIdentdUser 28 /* connection::ident */ -#define KviOption_stringDccListenDefaultInterface 29 /* dcc::general */ -#define KviOption_stringCustomAwayNick 30 /* ircengine::away */ -#define KviOption_stringDefaultDccFakeAddress 31 /* dcc::general */ -#define KviOption_stringCtcpPageReply 32 /* ircengine::ctcp::replies */ -#define KviOption_stringSSLCertificatePath 33 /* ssl */ -#define KviOption_stringSSLCertificatePass 34 /* ssl */ -#define KviOption_stringSSLPrivateKeyPath 35 /* ssl */ -#define KviOption_stringSSLPrivateKeyPass 36 /* ssl */ -#define KviOption_stringSoundSystem 37 /* sound */ -#define KviOption_stringDefaultUserMode 38 -#define KviOption_stringLastImageDialogPath 39 /* internal */ -#define KviOption_stringIconThemeSubdir 40 -#define KviOption_stringIncomingPath 41 /* folders */ -#define KviOption_stringMyAvatar 42 -// empty string means guess from locale -#define KviOption_stringDefaultTextEncoding 43 /* text encoding */ - -#define KviOption_stringWinampTextEncoding 44 -#define KviOption_stringMp3TagsEncoding 45 - -#define KviOption_stringCtcpUserInfoAge 46 /* identity */ -#define KviOption_stringCtcpUserInfoGender 47 /* identity */ -#define KviOption_stringCtcpUserInfoLocation 48 /* identity */ -#define KviOption_stringCtcpUserInfoLanguages 49 /* identity */ -#define KviOption_stringWordSplitters 50 /* highlight */ -#define KviOption_stringOnNewQueryOpenedSound 51 /* sounds */ -#define KviOption_stringOnHighlightedMessageSound 52 /* sounds */ -#define KviOption_stringOnMeKickedSound 53 /* sounds */ -#define KviOption_stringOnQueryMessageSound 54 /* sounds */ -#define KviOption_stringIrcViewTimestampFormat 55 -#define KviOption_stringPreferredTorrentClient 56 /* still missing in options ! */ -// empty string means guess from locale -#define KviOption_stringDefaultSrvEncoding 57 /* server encoding */ -#define KviOption_stringLogsPath 58 /* logfolder */ - -#define KVI_NUM_STRING_OPTIONS 59 - - - -#define KVI_STRINGLIST_OPTIONS_PREFIX "stringlist" -#define KVI_STRINGLIST_OPTIONS_PREFIX_LEN 10 - -#define KviOption_stringlistHighlightWords 0 /* ircengine::outputcontrol::highlighting */ -#define KviOption_stringlistSpamWords 1 /* ircengine::outputcontrol::antispam */ -#define KviOption_stringlistRecentChannels 2 /* internal */ -#define KviOption_stringlistRecentServers 3 /* internal */ -#define KviOption_stringlistRecentNicknames 4 /* internal */ -#define KviOption_stringlistModuleExtensionToolbars 5 /* internal */ -#define KviOption_stringlistImageSearchPaths 6 /* ??? */ -#define KviOption_stringlistRecentIrcUrls 7 /* internal */ - -#define KVI_NUM_STRINGLIST_OPTIONS 8 - - - -#define KVI_COLOR_OPTIONS_PREFIX "color" -#define KVI_COLOR_OPTIONS_PREFIX_LEN 5 - -#define KviOption_colorMdiBackground 0 /* ?? look & feel : gui elements : mdi manager */ -#define KviOption_colorWindowListNormalText 1 /* look & feel::interface look::WindowList::classic WindowList */ -#define KviOption_colorWindowListMinimizedText 2 /* look & feel::interface look::WindowList::classic WindowList */ -#define KviOption_colorWindowListHighlight1Text 3 /* look & feel::interface look::WindowList::classic WindowList */ -#define KviOption_colorWindowListHighlight2Text 4 /* look & feel::interface look::WindowList::classic WindowList */ -#define KviOption_colorWindowListProgressBar 5 /* look & feel::interface look::WindowList::classic WindowList */ -#define KviOption_colorUserListViewAwayForeground 6 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewOwnForeground 7 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewIrcOpForeground 8 /* look & feel::interface look::userlist */ -#define KviOption_colorNotifierBackground 9 /* look & feel::interface look::notifier */ -#define KviOption_colorNotifierForeground 10 /* look & feel::interface look::notifier */ -#define KviOption_colorNotifierTitleForeground 11 /* look & feel::interface look::notifier */ -#define KviOption_colorIrcViewBackground 12 /* look & feel::interface look::ircview */ -#define KviOption_colorInputBackground 13 /* look & feel::interface look::input */ -#define KviOption_colorInputSelectionBackground 14 /* look & feel::interface look::input */ -#define KviOption_colorInputSelectionForeground 15 /* look & feel::interface look::input */ -#define KviOption_colorInputCursor 16 /* look & feel::interface look::input */ -#define KviOption_colorInputControl 17 /* look & feel::interface look::input */ -#define KviOption_colorInputForeground 18 /* look & feel::interface look::input */ -#define KviOption_colorUserListViewBackground 19 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewOpForeground 20 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewVoiceForeground 21 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewNormalForeground 22 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewSelectionBackground 23 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewSelectionForeground 24 /* look & feel::interface look::userlist */ -#define KviOption_colorLabelBackground 25 /* look & feel::interface look::topic label */ -#define KviOption_colorLabelForeground 26 /* look & feel::interface look::topic label */ -#define KviOption_colorGlobalTransparencyFade 27 /* look & feel::interface look */ -#define KviOption_colorIrcToolBarAppletBackground 28 /* theme::tool bar applets */ -#define KviOption_colorIrcToolBarAppletForegroundLowContrast 29 /* theme::tool bar applets */ -#define KviOption_colorIrcToolBarAppletForegroundMidContrast 30 /* theme::tool bar applets */ -#define KviOption_colorIrcToolBarAppletForegroundHighContrastInactive1 31 /* theme::tool bar applets */ -#define KviOption_colorIrcToolBarAppletForegroundHighContrastInactive2 32 /* theme::tool bar applets */ -#define KviOption_colorIrcToolBarAppletForegroundHighContrastActive1 33 /* theme::tool bar applets */ -#define KviOption_colorIrcToolBarAppletForegroundHighContrastActive2 34 /* theme::tool bar applets */ -#define KviOption_colorTreeWindowListBackground 35 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorTreeWindowListActiveBackground 36 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorTreeWindowListForeground 37 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorTreeWindowListActiveForeground 38 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorTreeWindowListHighlight1Foreground 39 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorTreeWindowListHighlight2Foreground 40 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorTreeWindowListProgress 41 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorUserListViewHalfOpForeground 42 /* look & feel::interface look::userlist */ -#define KviOption_colorWindowListHighlight3Text 43 /* look & feel::interface look::WindowList::classic WindowList */ -#define KviOption_colorWindowListHighlight4Text 44 /* look & feel::interface look::WindowList::classic WindowList */ -#define KviOption_colorWindowListHighlight5Text 45 /* look & feel::interface look::WindowList::classic WindowList */ -#define KviOption_colorTreeWindowListHighlight3Foreground 46 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorTreeWindowListHighlight4Foreground 47 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorTreeWindowListHighlight5Foreground 48 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_colorUserListViewChanAdminForeground 49 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewUserOpForeground 50 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewGrid 51 /* look & feel::interface look::userlist */ -#define KviOption_colorUserListViewChanOwnerForeground 52 /* look & feel::interface look::userlist */ -#define KviOption_colorIrcViewMarkLine 53 /* look & feel::interface look::ircvew */ - -#define KVI_NUM_COLOR_OPTIONS 54 - - - -#define KVI_PIXMAP_OPTIONS_PREFIX "pixmap" -#define KVI_PIXMAP_OPTIONS_PREFIX_LEN 6 - -#define KviOption_pixmapMdiBackground 0 -#define KviOption_pixmapIrcViewBackground 1 /* interface::look::components::ircview */ -#define KviOption_pixmapInputBackground 2 /* interface::look::components::input */ -#define KviOption_pixmapUserListViewBackground 3 /* look & feel::interface look::userlist */ -#define KviOption_pixmapLabelBackground 4 /* look & feel::interface look::topic label */ -#define KviOption_pixmapMyAvatar 5 /* identity */ -#define KviOption_pixmapIrcToolBarAppletBackground 6 /* theme::tool bar applets */ -#define KviOption_pixmapTreeWindowListBackground 7 /* look & feel::interface look::WindowList::tree WindowList */ -#define KviOption_pixmapGlobalTransparencyBackground 8 /* theme::transparency */ -#define KviOption_pixmapNotifierBackground 9 /* interface::look::components::notifier */ - -#define KVI_NUM_PIXMAP_OPTIONS 10 - - - - -#define KVI_UINT_OPTIONS_PREFIX "uint" -#define KVI_UINT_OPTIONS_PREFIX_LEN 4 - -#define KviOption_uintIrcSocketTimeout 0 /* connection::transport */ -#define KviOption_uintModuleCleanupTimerInterval 1 -#define KviOption_uintModuleCleanupTimeout 2 -#define KviOption_uintMaxCtcpRequests 3 /* ircengine::ctcp */ -#define KviOption_uintCtcpFloodCheckInterval 4 /* ircengine::ctcp */ -#define KviOption_uintTotalConnectionTime 5 -#define KviOption_uintDccSocketTimeout 6 /* dcc::general */ -#define KviOption_uintDccSendIdleStepInMSec 7 /* dcc::send */ -#define KviOption_uintDccSendPacketSize 8 /* dcc::send */ -#define KviOption_uintGlobalTransparencyParentFadeFactor 9 /* interface::look::general */ -#define KviOption_uintGlobalTransparencyChildFadeFactor 10 /* interface::look::general */ -#define KviOption_uintNotifyListCheckTimeInSecs 11 /* notify */ -#define KviOption_uintSocketQueueFlushTimeout 12 /* connection::transport */ -#define KviOption_uintOutgoingTrafficLimitUSeconds 13 /* connection::transport */ -#define KviOption_uintNotifyListIsOnDelayTimeInSecs 14 /* notify */ -#define KviOption_uintNotifyListUserhostDelayTimeInSecs 15 /* notify */ -#define KviOption_uintTreeWindowListMinimumWidth 16 /* ?? interface::general ?? */ -#define KviOption_uintAvatarOfferTimeoutInSecs 17 /* irc::ctcp::avatar */ -#define KviOption_uintIrcViewMaxBufferSize 18 /* interface::features::components::ircview */ -#define KviOption_uintIrcViewToolTipTimeoutInMsec 19 /* interface::features::components::ircview */ -#define KviOption_uintIrcViewToolTipHideTimeoutInMsec 20 /* interface::features::components::ircview */ -#define KviOption_uintDccVoicePreBufferSize 21 /* dcc::voice */ -#define KviOption_uintIdentdPort 22 /* connection::ident */ -#define KviOption_uintAvatarScaleWidth 23 /* ctcp::avatar */ -#define KviOption_uintAvatarScaleHeight 24 /* ctcp::avatar */ -#define KviOption_uintDccMinPort 25 /* dcc::general */ -#define KviOption_uintDccMaxPort 26 /* dcc::general */ -#define KviOption_uintSoundOfferTimeoutInSecs 27 -#define KviOption_uintMaximumRequestedAvatarSize 28 /* ctcp::avatar */ -#define KviOption_uintGlobalWindowOpacityPercent 29 -#define KviOption_uintPasteDelay 30 -// 0 = unlimited! -#define KviOption_uintMaxDccSendTransfers 31 -// 0 = unlimited slots = windows -#define KviOption_uintMaxDccSlots 32 -#define KviOption_uintTileMethod 33 /* internal ? */ -#define KviOption_uintLagMeterHeartbeat 34 -#define KviOption_uintLagAlarmTime 35 -// KVI_TEXT_ENCODING_UNKNOWN = KviLocale::defaultTextEncoding() <-- guessed from locale -//#define KviOption_uintDefaultTextEncoding 36 /* textencoding */ -#define KviOption_uintWindowListButtonMinWidth 37 /* interface::look::WindowList::classic WindowList */ -// follows the verbosity constants defined below -#define KviOption_uintOutputVerbosityLevel 38 -#define KviOption_uintIrcContextAppletWidth 39 /* internal */ -#define KviOption_uintMinHighlightLevel 40 /* look::interface::features::output */ -#define KviOption_uintUserListViewGridType 41 /* look&feel::ircview */ -#define KviOption_uintWindowListMaximumRows 42 /* interface::look::WindowList::classic WindowList */ -// 0 = unlimited attempts -#define KviOption_uintMaxAutoReconnectAttempts 43 /* connection */ -#define KviOption_uintAutoReconnectDelay 44 /* connection */ -#define KviOption_uintMaxDccSendSpeed 45 /* dcc::file transfers */ -#define KviOption_uintMaxDccRecvSpeed 46 /* dcc::file transfers */ -#define KviOption_uintTimeStampForeground 47 -#define KviOption_uintTimeStampBackground 48 -#define KviOption_uintUserExperienceLevel 49 -#define KviOption_uintClassicWindowListMaximumButtonWidth 50 -#define KviOption_uintDefaultBanType 51 -#define KviOption_uintIrcViewPixmapAlign 52 -#define KviOption_uintUserListPixmapAlign 53 -#define KviOption_uintToolBarAppletPixmapAlign 54 -#define KviOption_uintTreeWindowListPixmapAlign 55 -#define KviOption_uintInputPixmapAlign 56 -#define KviOption_uintAutoFlushLogs 57 -#define KviOption_uintMinTrayLowLevelMessage 58 -#define KviOption_uintMinTrayHighLevelMessage 59 -#define KviOption_uintIdentdOutputMode 60 -#define KviOption_uintScaleAvatarsOnLoadHeight 61 -#define KviOption_uintScaleAvatarsOnLoadWidth 62 -#define KviOption_uintNotifierActiveTransparency 63 -#define KviOption_uintNotifierInactiveTransparency 64 -#define KviOption_uintIrcViewMarkerStyle 65 -#define KviOption_uintIrcViewMarkerSize 66 -#define KviOption_uintUrlMouseClickNum 67 -#define KviOption_uintNotifierAutoHideTime 68 -#define KviOption_uintLinesToPasteOnChannelJoin 69 /* channel */ -#define KviOption_uintDaysIntervalToPasteOnChannelJoin 70 /* channel */ -#define KviOption_uintLinesToPasteOnQueryJoin 71 /* query */ -#define KviOption_uintDaysIntervalToPasteOnQueryJoin 72 /* query */ -#define KviOption_uintSpacesToExpandTabulationInput 73 /* number of spaces used in tabulation expansion in the inputbar */ -#define KviOption_uintUserIrcViewOwnForeground 74 /* look & feel::ircview */ -#define KviOption_uintUserIrcViewOwnBackground 75 /* look & feel::ircview */ -#define KviOption_uintNotifierPixmapAlign 76 -#define KviOption_uintOutputDatetimeFormat 77 /* irc::verbosity */ -#define KviOption_uintOnJoinRequestsDelay 78 -#define KVI_NUM_UINT_OPTIONS 79 - -namespace KviIdentdOutputMode { - enum Mode { - Quiet = 0, - ToConsole = 1, - ToActiveWindow = 2 - }; -} - - -#define KVI_FONT_OPTIONS_PREFIX "font" -#define KVI_FONT_OPTIONS_PREFIX_LEN 4 - -#define KviOption_fontIrcView 0 /* interface::look::components::ircview */ -#define KviOption_fontInput 1 /* interface::look::components::input */ -#define KviOption_fontUserListView 2 /* look & feel::interface look::userlist */ -#define KviOption_fontLabel 3 /* look & feel::interface look::topic label */ -#define KviOption_fontApplication 4 /* interface::look::global */ -#define KviOption_fontIrcToolBarApplet 5 /* theme::tool bar applet */ -#define KviOption_fontWindowList 6 /* interface::look::WindowList::classic WindowList */ -#define KviOption_fontTreeWindowList 7 /* interface::look::WindowList::tree WindowList */ -#define KviOption_fontNotifier 8 /* interface::look::components::notifier */ -#define KviOption_fontNotifierTitle 9 /* interface::look::components::notifier */ - -#define KVI_NUM_FONT_OPTIONS 10 - - - - -#define KVI_ICCOLOR_OPTIONS_PREFIX "iccolor" -#define KVI_ICCOLOR_OPTIONS_PREFIX_LEN 7 - -#define KVI_NUM_ICCOLOR_OPTIONS 8 - - -// indices declared in kvi_out.h - -#define KVI_MSGTYPE_OPTIONS_PREFIX "msgtype" -#define KVI_MSGTYPE_OPTIONS_PREFIX_LEN 7 - -#define KVI_NUM_MSGTYPE_OPTIONS 142 - - - -#define KVI_MIRCCOLOR_OPTIONS_PREFIX "mirccolor" -#define KVI_MIRCCOLOR_OPTIONS_PREFIX_LEN 9 - -#define KVI_NUM_MIRCCOLOR_OPTIONS 16 - - -// external declaration of the tables -extern KVIRC_API KviBoolOption g_boolOptionsTable[KVI_NUM_BOOL_OPTIONS]; -extern KVIRC_API KviRectOption g_rectOptionsTable[KVI_NUM_RECT_OPTIONS]; -extern KVIRC_API KviStringOption g_stringOptionsTable[KVI_NUM_STRING_OPTIONS]; -extern KVIRC_API KviColorOption g_colorOptionsTable[KVI_NUM_COLOR_OPTIONS]; -extern KVIRC_API KviPixmapOption g_pixmapOptionsTable[KVI_NUM_PIXMAP_OPTIONS]; -// extern KviIntOption g_intOptionsTable[KVI_NUM_INT_OPTIONS]; -extern KVIRC_API KviUIntOption g_uintOptionsTable[KVI_NUM_UINT_OPTIONS]; -extern KVIRC_API KviFontOption g_fontOptionsTable[KVI_NUM_FONT_OPTIONS]; -extern KVIRC_API KviMessageTypeSettingsOption g_msgtypeOptionsTable[KVI_NUM_MSGTYPE_OPTIONS]; -extern KVIRC_API KviColorOption g_mirccolorOptionsTable[KVI_NUM_MIRCCOLOR_OPTIONS]; -extern KVIRC_API KviColorOption g_iccolorOptionsTable[KVI_NUM_ICCOLOR_OPTIONS]; -extern KVIRC_API KviStringListOption g_stringlistOptionsTable[KVI_NUM_STRINGLIST_OPTIONS]; - -// __this is how we access the options from outside -#define KVI_OPTION_BOOL(_idx) g_boolOptionsTable[_idx].option -#define KVI_OPTION_RECT(_idx) g_rectOptionsTable[_idx].option -#define KVI_OPTION_STRING(_idx) g_stringOptionsTable[_idx].option -#define KVI_OPTION_COLOR(_idx) g_colorOptionsTable[_idx].option -#define KVI_OPTION_PIXMAP(_idx) g_pixmapOptionsTable[_idx].option -#define KVI_OPTION_UINT(_idx) g_uintOptionsTable[_idx].option -#define KVI_OPTION_FONT(_idx) g_fontOptionsTable[_idx].option -#define KVI_OPTION_MSGTYPE(_idx) g_msgtypeOptionsTable[_idx].option -#define KVI_OPTION_MIRCCOLOR(_idx) g_mirccolorOptionsTable[_idx].option -#define KVI_OPTION_STRINGLIST(_idx) g_stringlistOptionsTable[_idx].option -#define KVI_OPTION_ICCOLOR(_idx) g_iccolorOptionsTable[_idx].option - - -// Verbosity constants - -#define KVI_VERBOSITY_LEVEL_MUTE 0 -#define KVI_VERBOSITY_LEVEL_QUIET 1 -#define KVI_VERBOSITY_LEVEL_NORMAL 2 -#define KVI_VERBOSITY_LEVEL_VERBOSE 3 -#define KVI_VERBOSITY_LEVEL_PARANOIC 4 - -#define _OUTPUT_PARANOIC (KVI_OPTION_UINT(KviOption_uintOutputVerbosityLevel) >= KVI_VERBOSITY_LEVEL_PARANOIC) -#define _OUTPUT_VERBOSE (KVI_OPTION_UINT(KviOption_uintOutputVerbosityLevel) >= KVI_VERBOSITY_LEVEL_VERBOSE) -#define _OUTPUT_QUIET (KVI_OPTION_UINT(KviOption_uintOutputVerbosityLevel) <= KVI_VERBOSITY_LEVEL_QUIET) -#define _OUTPUT_MUTE (KVI_OPTION_UINT(KviOption_uintOutputVerbosityLevel) <= KVI_VERBOSITY_LEVEL_MUTE) - - #define START_TABLE_BOLD_ROW "" - #define END_TABLE_BOLD_ROW "" - - #define START_TABLE_NORMAL_ROW "" - - #define SET_ANTI_ALIASING(p) (p).setRenderHint(QPainter::TextAntialiasing); - - -#define KVI_RECENT_CHANNELS_SEPARATOR ":" - -#if defined(_KVI_OPTIONS_CPP_) || defined(_WANT_OPTION_FLAGS_) - - // flag definitions - - // section of the config file (rightmost 8 bits) - #define KviOption_sectFlagNone 0 - #define KviOption_sectFlagFrame 1 - #define KviOption_sectFlagMdi 2 - #define KviOption_sectFlagWindowList 3 - #define KviOption_sectFlagWindows 4 - #define KviOption_sectFlagIrcView 5 - #define KviOption_sectFlagMsgType 6 - #define KviOption_sectFlagMircColor 7 - #define KviOption_sectFlagInput 8 - #define KviOption_sectFlagUserParser 9 - #define KviOption_sectFlagConnection 10 - #define KviOption_sectFlagIrcSocket 11 - #define KviOption_sectFlagUser 12 - #define KviOption_sectFlagUserListView 13 - #define KviOption_sectFlagLabel 14 - #define KviOption_sectFlagModules 15 - #define KviOption_sectFlagCtcp 16 - #define KviOption_sectFlagDcc 17 - #define KviOption_sectFlagGui 18 - #define KviOption_sectFlagIrcToolBar 19 - #define KviOption_sectFlagLogging 20 - #define KviOption_sectFlagAntiSpam 21 - #define KviOption_sectFlagAvatar 22 - #define KviOption_sectFlagUrl 23 - #define KviOption_sectFlagRecent 24 - #define KviOption_sectFlagGeometry 25 - #define KviOption_sectFlagNotifier 26 - - #define KVI_NUM_OPTION_SECT_FLAGS 27 - - #define KviOption_sectMask 255 - - // other logical groupings of options - #define KviOption_groupTheme (1 << 8) - - #define KviOption_groupMask (255 << 8) - - - - // actions to take when an option is set - #define KviOption_resetNone 0 - #define KviOption_resetUpdateNotifier (1 << 16) - #define KviOption_resetUpdateGui (1 << 17) - #define KviOption_resetUpdateWindowList (1 << 18) - #define KviOption_resetUpdateAppFont (1 << 19) - #define KviOption_resetUpdatePseudoTransparency (1 << 20) - #define KviOption_resetRestartNotifyList (1 << 21) - #define KviOption_resetRestartIdentd (1 << 22) - #define KviOption_resetReloadImages (1 << 23) - #define KviOption_resetRestartLagMeter (1 << 24) - #define KviOption_resetRecentChannels (1 << 25) - - #define KviOption_resetMask (~(KviOption_sectMask | KviOption_groupMask)) - - //for file pathes - #define KviOption_encodePath (1 << 25) - -#endif - -#endif //_KVI_OPTIONS_H_ diff --git a/src/kvirc/kernel/kvi_out.h b/src/kvirc/kernel/kvi_out.h index d702f874e..7b423bebc 100644 --- a/src/kvirc/kernel/kvi_out.h +++ b/src/kvirc/kernel/kvi_out.h @@ -168,7 +168,7 @@ #define KVI_OUT_CAP 141 //#define KVI_NUM_MSGTYPE_OPTIONS 142 -// UPDATE THE TOTAL COUNT IN kvi_options.h !!!! +// UPDATE THE TOTAL COUNT IN KviOptions.h !!!! #endif //_KVI_OPTIONS_H_ diff --git a/src/kvirc/kernel/kvi_sslmaster.cpp b/src/kvirc/kernel/kvi_sslmaster.cpp deleted file mode 100644 index 83fc67519..000000000 --- a/src/kvirc/kernel/kvi_sslmaster.cpp +++ /dev/null @@ -1,315 +0,0 @@ -//============================================================================= -// -// File : KviSSLmanager.cpp -// Creation date : Mon Jun 17 2002 20:34:00 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_sslmaster.h" - -#ifdef COMPILE_SSL_SUPPORT - -#include "kvi_window.h" -#include "kvi_options.h" -#include "kvi_out.h" -#include "KviMircCntrl.h" -#include "KviLocale.h" -#include "kvi_kvs_variant.h" - -#ifdef COMPILE_ON_WINDOWS - // - // Since OpenSSL 0.9.8 we need to link in a piece of code from the OpenSSL source. - // This is their own hack to avoid runtime problems when linking to an OpenSSL library - // that has been compiled with a different runtime (different options or compiler at all). - // This file is either installed in ${OPENSSL_INSTALL_ROOT}/include/openssl or - // in ${OPENSSL_INSTALL_ROOT}/ms/. - // - // Failing to include this file manifests itself with an abort when using a certificate. - // Just before the abort a message box complains about "no OPENSSL_Applink" which is - // implemented inside applink.c - // - #include -#endif //COMPILE_ON_WINDOWS - -namespace KviSSLMaster -{ - -KVIRC_API void printSSLCipherInfo(KviWindow * wnd,const char * description,KviSSLCipherInfo * c) -{ - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: %c%s"),KVI_TEXT_BOLD,description); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Cipher: %c%s"),KVI_TEXT_BOLD,c->name()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Version: %c%s"),KVI_TEXT_BOLD,c->version()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Bits: %c%d (%d used)"),KVI_TEXT_BOLD,c->bits(),c->bitsUsed()); -// wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Description: %c%s"),KVI_TEXT_BOLD,c->description()); -} - -KVIRC_API void printSSLCertificate(KviWindow * wnd,const char * description,KviSSLCertificate * c) -{ - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: %c%s"),KVI_TEXT_BOLD,description); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Version: %c%d"),KVI_TEXT_BOLD,c->version()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Serial number: %c%d"),KVI_TEXT_BOLD,c->serialNumber()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Subject:")); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Common name: %c%s"),KVI_TEXT_BOLD,c->subjectCommonName()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Organization: %c%s"),KVI_TEXT_BOLD,c->subjectOrganization()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Organizational unit: %c%s"),KVI_TEXT_BOLD,c->subjectOrganizationalUnit()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Country: %c%s"),KVI_TEXT_BOLD,c->subjectCountry()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: State or province: %c%s"),KVI_TEXT_BOLD,c->subjectStateOrProvince()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Locality: %c%s"),KVI_TEXT_BOLD,c->subjectLocality()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Issuer:")); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Common name: %c%s"),KVI_TEXT_BOLD,c->issuerCommonName()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Organization: %c%s"),KVI_TEXT_BOLD,c->issuerOrganization()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Organizational unit: %c%s"),KVI_TEXT_BOLD,c->issuerOrganizationalUnit()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Country: %c%s"),KVI_TEXT_BOLD,c->issuerCountry()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: State or province: %c%s"),KVI_TEXT_BOLD,c->issuerStateOrProvince()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Locality: %c%s"),KVI_TEXT_BOLD,c->issuerLocality()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Public key: %c%s (%d bits)"),KVI_TEXT_BOLD,c->publicKeyType(),c->publicKeyBits()); - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Signature type: %c%s"),KVI_TEXT_BOLD,c->signatureType()); - KviCString tmp = c->signatureContents(); - if(tmp.len() > 40) - { - tmp.cutRight(tmp.len() - 40); - tmp.append("..."); - } - wnd->output(KVI_OUT_SSL,__tr2qs("[SSL]: Signature contents: %c%s"),KVI_TEXT_BOLD,tmp.ptr()); - -} - -KVIRC_API void printSSLConnectionInfo(KviWindow * wnd,KviSSL * s) -{ - KviSSLCertificate * sc = s->getPeerCertificate(); - if(sc) - { - QString tmp(__tr2qs("Peer X509 certificate")); - KviSSLMaster::printSSLCertificate(wnd,tmp.toLocal8Bit().data(),sc); - delete sc; - } else wnd->outputNoFmt(KVI_OUT_SSL,__tr2qs("[SSL]: The peer didn't provide a certificate")); - KviSSLCipherInfo * ci = s->getCurrentCipherInfo(); - if(ci) - { - QString tmp(__tr2qs("Current transmission cipher")); - KviSSLMaster::printSSLCipherInfo(wnd,tmp.toLocal8Bit().data(),ci); - delete ci; - } else wnd->outputNoFmt(KVI_OUT_SSL,__tr2qs("[SSL]: Can't find out the current cipher info")); -} - -KVIRC_API KviSSL * allocSSL(KviWindow * wnd,kvi_socket_t sock,KviSSL::Method m,const char * contextString) -{ - KviSSL * s = new KviSSL(); - if(!s->initContext(m)) - { - delete s; - return 0; - } - - if(!contextString)contextString = KviCString::emptyString().ptr(); - - if(KVI_OPTION_BOOL(KviOption_boolUseSSLCertificate)) - { - switch(s->useCertificateFile( - KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data(), - KVI_OPTION_STRING(KviOption_stringSSLCertificatePass).toUtf8().data())) - { - case KviSSL::Success: - if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL]: Using certificate file %s"),contextString,KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data()); - break; - case KviSSL::FileIoError: - if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL ERROR]: File I/O error while trying to use the certificate file %s"),contextString,KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data()); - break; - default: - { - KviCString buffer; - while(s->getLastErrorString(buffer)) - { - if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL ERROR]: %s"),contextString,buffer.ptr()); - } - } - break; - } - } - if(KVI_OPTION_BOOL(KviOption_boolUseSSLPrivateKey)) - { - switch(s->usePrivateKeyFile( - KVI_OPTION_STRING(KviOption_stringSSLPrivateKeyPath).toUtf8().data(), - KVI_OPTION_STRING(KviOption_stringSSLPrivateKeyPass).toUtf8().data())) - { - case KviSSL::Success: - if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL]: Using private key file %s"),contextString,KVI_OPTION_STRING(KviOption_stringSSLPrivateKeyPath).toUtf8().data()); - break; - case KviSSL::FileIoError: - if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL ERROR]: File I/O error while trying to use the private key file %s"),contextString,KVI_OPTION_STRING(KviOption_stringSSLPrivateKeyPath).toUtf8().data()); - break; - default: - { - KviCString buffer; - while(s->getLastErrorString(buffer)) - { - if(wnd)wnd->output(KVI_OUT_SSL,__tr2qs("[%s]: [SSL ERROR]: %s"),contextString,buffer.ptr()); - } - } - break; - } - } - - if(!s->initSocket(sock)) - { - delete s; - return 0; - } - - return s; -} - -KVIRC_API void freeSSL(KviSSL * s) -{ - delete s; -} - -/** - * Used for $certificate() and $dcc.getSSLCertInfo() function - */ -KVIRC_API bool getSSLCertInfo(KviSSLCertificate * pCert, QString szQuery, QString szOptionalParam, KviKvsVariant * pRetBuffer) -{ - pRetBuffer->setString(""); - - if(szQuery.compare("signatureType")==0) - { - pRetBuffer->setString(pCert->signatureType()); - return true; - } - if(szQuery.compare("signatureContents")==0) - { - pRetBuffer->setString(pCert->signatureContents()); - return true; - } - if(szQuery.compare("subjectCountry")==0) - { - pRetBuffer->setString(pCert->subjectCountry()); - return true; - } - if(szQuery.compare("subjectStateOrProvince")==0) - { - pRetBuffer->setString(pCert->subjectStateOrProvince()); - return true; - } - if(szQuery.compare("subjectLocality")==0) - { - pRetBuffer->setString(pCert->subjectLocality()); - return true; - } - if(szQuery.compare("subjectOrganization")==0) - { - pRetBuffer->setString(pCert->subjectOrganization()); - return true; - } - if(szQuery.compare("subjectOrganizationalUnit")==0) - { - pRetBuffer->setString(pCert->subjectOrganizationalUnit()); - return true; - } - if(szQuery.compare("subjectCommonName")==0) - { - pRetBuffer->setString(pCert->subjectCommonName()); - return true; - } - if(szQuery.compare("issuerCountry")==0) - { - pRetBuffer->setString(pCert->issuerCountry()); - return true; - } - if(szQuery.compare("issuerStateOrProvince")==0) - { - pRetBuffer->setString(pCert->issuerStateOrProvince()); - return true; - } - if(szQuery.compare("issuerLocality")==0) - { - pRetBuffer->setString(pCert->issuerLocality()); - return true; - } - if(szQuery.compare("issuerOrganization")==0) - { - pRetBuffer->setString(pCert->issuerOrganization()); - return true; - } - if(szQuery.compare("issuerOrganizationalUnit")==0) - { - pRetBuffer->setString(pCert->issuerOrganizationalUnit()); - return true; - } - if(szQuery.compare("issuerCommonName")==0) - { - pRetBuffer->setString(pCert->issuerCommonName()); - return true; - } - if(szQuery.compare("publicKeyBits")==0) - { - pRetBuffer->setInteger(pCert->publicKeyBits()); - return true; - } - if(szQuery.compare("publicKeyType")==0) - { - pRetBuffer->setString(pCert->publicKeyType()); - return true; - } - if(szQuery.compare("serialNumber")==0) - { - pRetBuffer->setInteger(pCert->serialNumber()); - return true; - } - if(szQuery.compare("pemBase64")==0) - { - const char * szTmp=pCert->getX509Base64(); - QString szBase64(szTmp); - pRetBuffer->setString(szBase64); - delete szTmp; - return true; - } - if(szQuery.compare("version")==0) - { - pRetBuffer->setInteger(pCert->version()); - return true; - } - if(szQuery.compare("fingerprintIsValid")==0) - { - pRetBuffer->setBoolean(pCert->fingerprintIsValid()); - return true; - } - if(szQuery.compare("fingerprintDigestId")==0) - { - pRetBuffer->setInteger(pCert->fingerprintDigestId()); - return true; - } - if(szQuery.compare("fingerprintDigestStr")==0) - { - pRetBuffer->setString(pCert->fingerprintDigestStr()); - return true; - } - if(szQuery.compare("fingerprintContents")==0) - { - pRetBuffer->setString(pCert->fingerprintContents(szOptionalParam)); - return true; - } - - // the warning is displayed in the caller - return false; -} - -}; -#endif diff --git a/src/kvirc/kernel/kvi_sslmaster.h b/src/kvirc/kernel/kvi_sslmaster.h deleted file mode 100644 index 6fb4a5cfe..000000000 --- a/src/kvirc/kernel/kvi_sslmaster.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef _KVI_SSLMASTER_H_ -#define _KVI_SSLMASTER_H_ -//============================================================================= -// -// File : kvi_sslmaster.h -// Creation date : Mon Jun 17 2002 20:34:00 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" - -#ifdef COMPILE_SSL_SUPPORT - -#include "KviSSL.h" -#include "kvi_sockettype.h" - -class KviWindow; -class KviKvsVariant; - -namespace KviSSLMaster -{ - extern KVIRC_API void printSSLCipherInfo(KviWindow * wnd,const char * description,KviSSLCipherInfo * c); - extern KVIRC_API void printSSLCertificate(KviWindow * wnd,const char * description,KviSSLCertificate * c); - - extern KVIRC_API void printSSLConnectionInfo(KviWindow * wnd,KviSSL * s); - - extern KVIRC_API KviSSL * allocSSL(KviWindow * wnd,kvi_socket_t sock,KviSSL::Method m,const char * contextString = 0); - extern KVIRC_API void freeSSL(KviSSL * s); - - extern KVIRC_API bool getSSLCertInfo(KviSSLCertificate * pCert, QString szQuery, QString szOptionalParam, KviKvsVariant * pRetBuffer); -} - -#endif - - -#endif //_KVI_SSLMASTER_H_ diff --git a/src/kvirc/kernel/kvi_texticonmanager.cpp b/src/kvirc/kernel/kvi_texticonmanager.cpp deleted file mode 100644 index 058ec1fc3..000000000 --- a/src/kvirc/kernel/kvi_texticonmanager.cpp +++ /dev/null @@ -1,309 +0,0 @@ -//============================================================================= -// -// File : kvi_texticonmanager.cpp -// Creation date : Thu 15 May 2002 12:04:12 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - -#define _KVI_TEXTICONMANAGER_CPP_ - -#include "kvi_iconmanager.h" -#include "kvi_texticonmanager.h" -#include "KviCString.h" -#include "KviPointerList.h" -#include "KviConfigurationFile.h" -#include "kvi_app.h" -#include "kvi_confignames.h" -#include "KviAnimatedPixmap.h" -#include "kvi_options.h" - -#include -#include - -static KviTextIconAssocEntry default_associations[]= -{ - { ":)" , KVI_SMALLICON_SMILE }, - { ":*" , KVI_SMALLICON_KISS }, - { ":D" , KVI_SMALLICON_BIGGRIN }, - { ":(" , KVI_SMALLICON_UGLY }, - { ":/" , KVI_SMALLICON_ANGRY }, - { ":O" , KVI_SMALLICON_SURPRISED2 }, - { ":P" , KVI_SMALLICON_TONGUE }, - { ";)" , KVI_SMALLICON_EYE }, - { ":°)" , KVI_SMALLICON_TEARSMILE }, - { ":°" , KVI_SMALLICON_CRY }, - { ":S" , KVI_SMALLICON_AFRAID }, - { ":|" , KVI_SMALLICON_DEMORALIZED }, - { ":P°" , KVI_SMALLICON_SLURP }, - { 0 , 0 } -}; - -KVIRC_API KviTextIconManager * g_pTextIconManager = 0; - -KviTextIcon::KviTextIcon(int iId) -: m_iId(iId),m_pAnimatedPixmap(0) -{ -} - -KviTextIcon::KviTextIcon(QString szFile) -: m_iId(-1), m_szFileName(szFile) -{ - QString szRetPath; - - if(g_pApp->findImage(szRetPath, szFile)) - { - m_pAnimatedPixmap = new KviAnimatedPixmap(szRetPath); -#if 0 // this doesn't work anyway - if(KVI_OPTION_BOOL(KviOption_boolEnableAnimatedSmiles)) - { - m_pAnimatedPixmap->start(); - } else { - m_pAnimatedPixmap->stop(); - } -#endif - } else { - m_pAnimatedPixmap = NULL; - } -} - -KviTextIcon::KviTextIcon(KviTextIcon * pIcon) -{ - m_iId = pIcon->id(); - m_szFileName = pIcon->m_szFileName; - if(pIcon->m_pAnimatedPixmap) - { - m_pAnimatedPixmap = new KviAnimatedPixmap(*(pIcon->m_pAnimatedPixmap)); - } else { - m_pAnimatedPixmap = NULL; - } -} - -KviTextIcon::~KviTextIcon() -{ - if(m_pAnimatedPixmap) - delete m_pAnimatedPixmap; -} - -void KviTextIcon::setId(int iId) -{ - m_iId = iId; - m_szFileName=QString(); -} - -void KviTextIcon::setFilename(QString szFileName) -{ - m_iId = -1; - m_szFileName = szFileName; -} - -QPixmap * KviTextIcon::pixmap() -{ - if(m_iId >= 0) - return g_pIconManager->getSmallIcon(m_iId); - - // This is actually wrong (at least for the current implementation). - // Users of this class expect the pointer to be permanent while - // g_pIconManager returns temporary pointers. - // KviIrcView will happily crash dereferencing a hollow pointer sooner or later - return g_pIconManager->getPixmap(m_szFileName); -} - -KviTextIconManager::KviTextIconManager() -: QObject() -{ - m_pTextIconDict = new KviPointerHashTable(47,false); - m_pTextIconDict->setAutoDelete(true); -} - -KviTextIconManager::~KviTextIconManager() -{ - delete m_pTextIconDict; -} - -void KviTextIconManager::clear() -{ - m_pTextIconDict->clear(); -} - -void KviTextIconManager::insert(const QString & szName, int iId) -{ - m_pTextIconDict->replace(szName, new KviTextIcon(iId)); - emit changed(); -} - -void KviTextIconManager::insert(const QString & szName,KviTextIcon & icon) -{ - m_pTextIconDict->replace(szName, new KviTextIcon(&icon)); - emit changed(); -} - -void KviTextIconManager::checkDefaultAssociations() -{ - for(int i=0; default_associations[i].name; i++) - { - if(!m_pTextIconDict->find(default_associations[i].name)) - insert(QString::fromUtf8(default_associations[i].name),default_associations[i].iVal); - } - emit changed(); -} - -void KviTextIconManager::load() -{ - QString szTmp; - int iUpd = 0; - if(g_pApp->getReadOnlyConfigPath(szTmp,KVI_CONFIGFILE_TEXTICONS)) - { - iUpd = load(szTmp,false); - } - - if(iUpd == TEXTICONMANAGER_CURRENT_CONFIG_UPDATE) - return; - - // do a merge of the texticons if we have a new config version - g_pApp->getGlobalKvircDirectory(szTmp,KviApp::Config,KVI_CONFIGFILE_TEXTICONS); - - if(QFile::exists(szTmp)) - load(szTmp,true); -} - -void KviTextIconManager::applyOptions() -{ - for( - KviTextIcon * pIcon = m_pTextIconDict->first(); - pIcon; - pIcon = m_pTextIconDict->next() - ) - { - if(pIcon->animatedPixmap()) - { - if(KVI_OPTION_BOOL(KviOption_boolEnableAnimatedSmiles)) - { - pIcon->animatedPixmap()->start(); - } else { - pIcon->animatedPixmap()->stop(); - } - } - } -} - -void KviTextIconManager::save() -{ - QString szTmp; - g_pApp->getLocalKvircDirectory(szTmp,KviApp::Config,KVI_CONFIGFILE_TEXTICONS); - save(szTmp); -} - -int KviTextIconManager::load(const QString & szFileName, bool bMerge) -{ - if(!bMerge) m_pTextIconDict->clear(); - - KviConfigurationFile cfg(szFileName,KviConfigurationFile::Read); - - cfg.setGroup("Manager"); - int iUpd = cfg.readIntEntry("ConfigUpdate",0); - - KviConfigurationFileGroup * pDict = cfg.dict()->find("TextIcons"); - if(pDict) - { - KviConfigurationFileGroupIterator it(*pDict); - - KviPointerList names; - names.setAutoDelete(true); - - while(it.current()) - { - names.append(new QString(it.currentKey())); - ++it; - } - - cfg.setGroup("TextIcons"); - - for(QString * s = names.first(); s; s = names.next()) - { - int iId = cfg.readIntEntry(*s,-1); - QString szTmp; - QPixmap * pix = 0; - //qDebug("%s %s %i %i",__FILE__,__FUNCTION__,__LINE__,id); - if(iId != -1) - { - pix = g_pIconManager->getSmallIcon(iId); - } else { - szTmp = cfg.readEntry(*s); - pix=g_pIconManager->getPixmap(szTmp); - if(!pix) - { - iId = KVI_SMALLICON_HELP; - pix = g_pIconManager->getSmallIcon(iId); - } - } - - if(pix) - { - if(bMerge) - { - if(!m_pTextIconDict->find(*s)) - { - if(iId != -1) - { - m_pTextIconDict->replace(*s,new KviTextIcon(iId)); - } else { - m_pTextIconDict->replace(*s,new KviTextIcon(szTmp)); - } - } - } else { - if(iId != -1) - { - m_pTextIconDict->replace(*s,new KviTextIcon(iId)); - } else { - m_pTextIconDict->replace(*s,new KviTextIcon(szTmp)); - } - } - } - } - } - - emit changed(); - - return iUpd; -} - -void KviTextIconManager::save(const QString & szFileName) -{ - KviConfigurationFile cfg(szFileName,KviConfigurationFile::Write); - - cfg.setGroup("Manager"); - cfg.writeEntry("ConfigUpdate",TEXTICONMANAGER_CURRENT_CONFIG_UPDATE); - - cfg.setGroup("TextIcons"); - - KviPointerHashTableIterator it(*m_pTextIconDict); - while(KviTextIcon * pIcon = it.current()) - { - if(pIcon->id() != -1) - cfg.writeEntry(it.currentKey(),pIcon->id()); - else - cfg.writeEntry(it.currentKey(),pIcon->filename()); - ++it; - } -} - -#ifndef COMPILE_USE_STANDALONE_MOC_SOURCES -#include "kvi_texticonmanager.moc" -#endif //COMPILE_USE_STANDALONE_MOC_SOURCES diff --git a/src/kvirc/kernel/kvi_texticonmanager.h b/src/kvirc/kernel/kvi_texticonmanager.h deleted file mode 100644 index eeeca2564..000000000 --- a/src/kvirc/kernel/kvi_texticonmanager.h +++ /dev/null @@ -1,244 +0,0 @@ -#ifndef _KVI_TEXTICONMANAGER_H_ -#define _KVI_TEXTICONMANAGER_H_ - -//============================================================================= -// -// File : kvi_texticonmanager.h -// Creation date : Thu 15 May 2002 12:04:12 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2002-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_texticonmanager.h -* \author Szymon Stefanek -* \brief -* -* \def TEXTICONMANAGER_CURRENT_CONFIG_UPDATE This MUST match the ConfigUpdate entry in the configuration file shipped with KVIrc -*/ - -#include "kvi_settings.h" -#include "KviPointerHashTable.h" -#include "KviAnimatedPixmap.h" - -#include - -#define TEXTICONMANAGER_CURRENT_CONFIG_UPDATE 4 - -/** -* \typedef KviTextIconAssocEntry -* \struct _KviTextIconAssocEntry -* \brief A struct that contains the icon association entries -*/ -typedef struct _KviTextIconAssocEntry -{ - const char * name; /**< the name of the icon */ - int iVal; /**< the id of the icon */ -} KviTextIconAssocEntry; - -/** -* \class KviTextIcon -* \brief The class that holds the icons -*/ -class KVIRC_API KviTextIcon -{ -protected: - int m_iId; - QString m_szFileName; - KviAnimatedPixmap * m_pAnimatedPixmap; -public: - /** - * \brief Constructs the icon object - * \param iId The id of the icon - * \return KviTextIcon - */ - KviTextIcon(int iId); - - /** - * \brief Constructs the icon object - * \param szFile The filename the icon - * \return KviTextIcon - */ - KviTextIcon(QString szFile); - - /** - * \brief Constructs the icon object - * \param pIcon The pointer to the icon - * \return KviTextIcon - */ - KviTextIcon(KviTextIcon * pIcon); - - /** - * \brief Destroys the icon object - */ - ~KviTextIcon(); -public: - /** - * \brief Returns the id of the icon - * \return int - */ - inline int id(){ return m_iId; }; - - /** - * \brief Sets the id of the icon - * \param iId The id of the icon - * \return void - */ - void setId(int iId); - - /** - * \brief Sets the filename of the icon - * \param szFileName The filename of the icon - * \return void - */ - void setFilename(QString szFileName); - - /** - * \brief Returns the filename of the icon - * \return QString - */ - inline QString filename(){ return m_szFileName; }; - - /** - * \brief Returns the pixmap associated to the icon - * \return QPixmap * - */ - QPixmap * pixmap(); - - /** - * \brief Returns the animated pixmap associated to the icon - * \return KviAnimatedPixmap * - */ - inline KviAnimatedPixmap * animatedPixmap(){ return m_pAnimatedPixmap; }; -}; - -/** -* \class KviTextIconManager -* \brief The class that manages the icons -*/ -class KVIRC_API KviTextIconManager : public QObject -{ - friend class KviTextIconWindow; - friend class KviTextIconsOptionsWidget; - Q_OBJECT -public: - /** - * \brief Constructs the icon manager object - * \return KviTextIconManager - */ - KviTextIconManager(); - - /** - * \brief Destroys the icon manager object - */ - ~KviTextIconManager(); -private: - KviPointerHashTable * m_pTextIconDict; -public: - /** - * \brief Returns the dictionary of the icons - * \return KviPointerHashTable * - */ - inline KviPointerHashTable * textIconDict(){ return m_pTextIconDict; }; - - /** - * \brief Checks and updates the default associations - * \return void - */ - void checkDefaultAssociations(); - - /** - * \brief Clears the dictionary - * \return void - */ - void clear(); - - /** - * \brief Inserts an icon in the dictionary - * \param szName The name of the icon - * \param iId The id of the icon - * \return void - */ - void insert(const QString & szName, int iId); - - /** - * \brief Inserts an icon in the dictionary - * \param szName The name of the icon - * \param icon The icon - * \return void - */ - void insert(const QString & szName, KviTextIcon & icon); - - /** - * \brief Returns the text of the icon - * \param szName The name of the icon - * \return KviTextIcon * - */ - inline KviTextIcon * lookupTextIcon(const QString & szName){ return m_pTextIconDict->find(szName); }; - - /** - * \brief Loads the dictionary - * \return void - */ - void load(); - - /** - * \brief Saves the dictionary - * \return void - */ - void save(); - - /** - * \brief Applies the options - * \return void - */ - void applyOptions(); -protected: - /** - * \brief Saves the dictionary to a file - * - * This is the real save() function - * \param szFileName The filename where to save - * \return void - */ - void save(const QString & szFileName); - - /** - * \brief Loads the dictionary from a file - * - * This is the real load() function - * It returns the config update - * \param szFileName The filename from where to load - * \param bMerge Whether to merge the existing dictionary with the loaded one - * \return int - */ - int load(const QString & szFileName, bool bMerge = false); -signals: - /** - * \brief Called when the default associations change - * \return void - */ - void changed(); -}; - -#ifndef _KVI_TEXTICONMANAGER_CPP_ - extern KVIRC_API KviTextIconManager * g_pTextIconManager; -#endif - -#endif //_KVI_TEXTICONMANAGER_H_ diff --git a/src/kvirc/kernel/kvi_theme.cpp b/src/kvirc/kernel/kvi_theme.cpp deleted file mode 100644 index 56adc7e75..000000000 --- a/src/kvirc/kernel/kvi_theme.cpp +++ /dev/null @@ -1,295 +0,0 @@ -//============================================================================= -// -// File : kvi_themeinfo.cpp -// Creation date : Mon Jan 08 2007 03:23:00 CEST by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2007-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_theme.h" -#include "KviFileUtils.h" -#include "KviConfigurationFile.h" -#include "KviLocale.h" -#include "KviMiscUtils.h" -#include "kvi_sourcesdate.h" - -#include - -#define KVI_THEME_SMALL_SCREENSHOT_NAME "screenshot_small.png" -#define KVI_THEME_MEDIUM_SCREENSHOT_NAME "screenshot_medium.png" -#define KVI_THEME_LARGE_SCREENSHOT_NAME "screenshot.png" - -#define QIMAGE_SCALE_MIN Qt::KeepAspectRatio - - -KviThemeInfo::KviThemeInfo() -: KviHeapObject() -{ -} - -KviThemeInfo::~KviThemeInfo() -{ -} - - - -bool KviThemeInfo::load(const QString &szThemeFileName) -{ - if(!KviFileUtils::fileExists(szThemeFileName)) - { - m_szLastError = __tr2qs("The theme information file does not exist"); - return false; - } - - KviConfigurationFile cfg(szThemeFileName,KviConfigurationFile::Read); - - cfg.setGroup(KVI_THEMEINFO_CONFIG_GROUP); - - m_szThemeEngineVersion = cfg.readEntry("ThemeEngineVersion","1.0.0"); - if(KviMiscUtils::compareVersions(m_szThemeEngineVersion,KVI_CURRENT_THEME_ENGINE_VERSION) < 0) - { - KviQString::sprintf(m_szLastError,__tr2qs("This KVIrc executable is too old for this theme (minimum theme engine version required is %Q while this theme engine has version %s)"),&m_szThemeEngineVersion,KVI_CURRENT_THEME_ENGINE_VERSION); - return false; // incompatible theme engine (will not work) - } - - // mandatory fields - m_szName = cfg.readEntry("Name",""); - - if(m_szName.isEmpty()) - { - m_szLastError = __tr2qs("Theme information file is not valid"); - return false; - } - - // optional fields - m_szVersion = cfg.readEntry("Version",""); - if(m_szVersion.isEmpty()) - m_szVersion = "?.?.?"; - m_szAuthor = cfg.readEntry("Author",""); - QString szUnknown = __tr2qs("Unknown"); - if(m_szAuthor.isEmpty()) - m_szAuthor = szUnknown; - m_szDescription = cfg.readEntry("Description",""); - m_szDate = cfg.readEntry("Date",""); - if(m_szDate.isEmpty()) - m_szDate = szUnknown; - m_szApplication = cfg.readEntry("Application",""); - if(m_szApplication.isEmpty()) - m_szApplication = szUnknown; - - return true; -} - -bool KviThemeInfo::save(const QString &szThemeFileName) -{ - KviConfigurationFile inf(szThemeFileName,KviConfigurationFile::Write); - - inf.clear(); - - inf.setGroup(KVI_THEMEINFO_CONFIG_GROUP); - - inf.writeEntry("Name",m_szName); - inf.writeEntry("Version",m_szVersion); - inf.writeEntry("Author",m_szAuthor); - inf.writeEntry("Description",m_szDescription); - inf.writeEntry("Date",m_szDate); - inf.writeEntry("ThemeEngineVersion",KVI_CURRENT_THEME_ENGINE_VERSION); - inf.writeEntry("Application","KVIrc " KVI_VERSION "." KVI_SOURCES_DATE); - - return true; -} - -bool KviThemeInfo::loadFromDirectory(const QString &szThemeDirectory,bool bIgnoreThemeData) -{ - QString szD = szThemeDirectory; - szD.append(KVI_PATH_SEPARATOR_CHAR); - szD.append(KVI_THEMEINFO_FILE_NAME); - - if(!load(szD)) - return false; // loading failed for some reason - - m_szAbsoluteDirectory = szThemeDirectory; - - if(bIgnoreThemeData) - return true; // assume success - - // check if themedata file exists - szD = szThemeDirectory; - szD.append(KVI_PATH_SEPARATOR_CHAR); - szD.append(KVI_THEMEDATA_FILE_NAME); - - return KviFileUtils::fileExists(szD); -} - -QString KviThemeInfo::smallScreenshotPath() -{ - QString ret; - if(!m_szAbsoluteDirectory.isEmpty()) - { - ret = m_szAbsoluteDirectory; - KviQString::ensureLastCharIs(ret,KVI_PATH_SEPARATOR_CHAR); - ret.append(KVI_THEME_SMALL_SCREENSHOT_NAME); - } - return ret; -} - -const QPixmap & KviThemeInfo::smallScreenshot() -{ - if(!m_pixScreenshotSmall.isNull())return m_pixScreenshotSmall; - - if(!m_szAbsoluteDirectory.isEmpty()) - { - QString szFileName = m_szAbsoluteDirectory; - KviQString::ensureLastCharIs(szFileName,KVI_PATH_SEPARATOR_CHAR); - szFileName.append(KVI_THEME_SMALL_SCREENSHOT_NAME); - QPixmap pix(szFileName); - if(!pix.isNull()) - { - m_pixScreenshotSmall = pix; - return m_pixScreenshotSmall; - } - // try to scale it from the large one (and save it by the way) - pix = mediumScreenshot(); - if(pix.isNull())return m_pixScreenshotSmall; - - if(pix.width() > 300 || pix.height() > 225) - { - QImage sbri = pix.toImage(); - pix = QPixmap::fromImage(sbri.scaled(300,225,QIMAGE_SCALE_MIN,Qt::SmoothTransformation)); - } - pix.save(szFileName,"PNG"); - - m_pixScreenshotSmall = pix; - return m_pixScreenshotSmall; - } - - return m_pixScreenshotSmall; -} - -const QPixmap & KviThemeInfo::mediumScreenshot() -{ - if(!m_pixScreenshotMedium.isNull())return m_pixScreenshotMedium; - - if(!m_szAbsoluteDirectory.isEmpty()) - { - QString szFileName = m_szAbsoluteDirectory; - KviQString::ensureLastCharIs(szFileName,KVI_PATH_SEPARATOR_CHAR); - szFileName.append(KVI_THEME_MEDIUM_SCREENSHOT_NAME); - QPixmap pix(szFileName); - if(!pix.isNull()) - { - m_pixScreenshotMedium = pix; - return m_pixScreenshotMedium; - } - // try to scale it from the large one (and save it by the way) - pix = largeScreenshot(); - if(pix.isNull())return m_pixScreenshotMedium; - - if(pix.width() > 600 || pix.height() > 450) - { - QImage sbri = pix.toImage(); - pix.fromImage(sbri.scaled(640,450,QIMAGE_SCALE_MIN,Qt::SmoothTransformation)); - } - - pix.save(szFileName,"PNG"); - - m_pixScreenshotMedium = pix; - return m_pixScreenshotMedium; - } - - return m_pixScreenshotMedium; -} - -const QPixmap & KviThemeInfo::largeScreenshot() -{ - if(!m_pixScreenshotLarge.isNull())return m_pixScreenshotLarge; - - if(!m_szAbsoluteDirectory.isEmpty()) - { - QString szFileName = m_szAbsoluteDirectory; - KviQString::ensureLastCharIs(szFileName,KVI_PATH_SEPARATOR_CHAR); - szFileName.append(KVI_THEME_LARGE_SCREENSHOT_NAME); - QPixmap pix(szFileName); - if(pix.isNull())return m_pixScreenshotLarge; - m_pixScreenshotLarge = pix; - } - return m_pixScreenshotLarge; -} - - -namespace KviTheme -{ - bool saveScreenshots(KviThemeInfo &options,const QString &szOriginalScreenshotPath) - { - QImage pix(szOriginalScreenshotPath); - if(pix.isNull()) - { - options.setLastError(__tr2qs("Failed to load the specified screenshot image")); - return false; - } - - QImage out; - - QString szScreenshotFileName = options.absoluteDirectory(); - if(szScreenshotFileName.isEmpty()) - { - options.setLastError(__tr2qs("Invalid option")); - return false; - } - - KviQString::ensureLastCharIs(szScreenshotFileName,KVI_PATH_SEPARATOR_CHAR); - szScreenshotFileName.append(KVI_THEME_LARGE_SCREENSHOT_NAME); - if(!pix.save(szScreenshotFileName,"PNG")) - { - options.setLastError(__tr2qs("Failed to save the screenshot image")); - return false; - } - - if(pix.width() > 600 || pix.height() > 450) - out = pix.scaled(640,450,QIMAGE_SCALE_MIN,Qt::SmoothTransformation); - else - out = pix; - - szScreenshotFileName = options.absoluteDirectory(); - KviQString::ensureLastCharIs(szScreenshotFileName,KVI_PATH_SEPARATOR_CHAR); - szScreenshotFileName.append(KVI_THEME_MEDIUM_SCREENSHOT_NAME); - if(!out.save(szScreenshotFileName,"PNG")) - { - options.setLastError(__tr2qs("Failed to save the screenshot image")); - return false; - } - - if(pix.width() > 300 || pix.height() > 225) - out = pix.scaled(300,225,QIMAGE_SCALE_MIN,Qt::SmoothTransformation); - else - out = pix; - - szScreenshotFileName = options.absoluteDirectory(); - KviQString::ensureLastCharIs(szScreenshotFileName,KVI_PATH_SEPARATOR_CHAR); - szScreenshotFileName.append(KVI_THEME_SMALL_SCREENSHOT_NAME); - if(!out.save(szScreenshotFileName,"PNG")) - { - options.setLastError(__tr2qs("Failed to save the screenshot image")); - return false; - } - - return true; - } -}; diff --git a/src/kvirc/kernel/kvi_theme.h b/src/kvirc/kernel/kvi_theme.h deleted file mode 100644 index 26119ff4c..000000000 --- a/src/kvirc/kernel/kvi_theme.h +++ /dev/null @@ -1,170 +0,0 @@ -#ifndef _KVI_THEME_H_ -#define _KVI_THEME_H_ - -//============================================================================= -// -// File : kvi_theme.h -// Creation date : Mon Jan 08 2007 03:23:00 CEST by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2007-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_settings.h" -#include "KviQString.h" -#include "KviHeapObject.h" -#include "kvi_fileextensions.h" - -#include - -#define KVI_THEMEINFO_FILE_NAME "themeinfo" KVI_FILEEXTENSION_CONFIG -#define KVI_THEMEDATA_FILE_NAME "themedata" KVI_FILEEXTENSION_CONFIG -#define KVI_THEMEINFO_CONFIG_GROUP "ThemeInfo" -#define KVI_THEMEDATA_CONFIG_GROUP "ThemeData" - -/// -/// The current theme engine version: bump up if you make INCOMPATIBLE -/// changes in the method of saving the theme. -/// -#define KVI_CURRENT_THEME_ENGINE_VERSION "1.0.0" - -/// -/// \class KviThemeInfo -/// -/// \brief A set of information about a KVIrc theme -/// -/// This object contains a set of information about -/// a theme that can be read and stored to a standard -/// KVIrc configuration file (which is usually named -/// themeinfo.kvc but this is not strictly necessary). -/// -class KVIRC_API KviThemeInfo : public KviHeapObject -{ -public: - KviThemeInfo(); - ~KviThemeInfo(); -protected: - QString m_szName; //< name of the theme - QString m_szVersion; //< version of the theme - QString m_szSubdirectory; //< subdirectory of $LOCALKVIRCDIR/themes where the theme is saved to (not always used) - QString m_szAbsoluteDirectory; //< absolute directory where the theme should be saved to (or is loaded from) - QString m_szAuthor; //< author of the theme - QString m_szDescription; //< description of the theme - QString m_szDate; //< theme creation date - QString m_szApplication; //< theme creation (KVIrc) version - QString m_szThemeEngineVersion; //< the theme engine version that saved this theme - - QString m_szLastError; //< reported when some function fails - - QPixmap m_pixScreenshotLarge; //< the large screenshot pixmap - QPixmap m_pixScreenshotMedium; //< the medium screenshot pixmap - QPixmap m_pixScreenshotSmall; //< the small screenshot pixmap -public: - /// - /// load data from a specified theme config file - /// - bool load(const QString &szThemeFileName); - /// - /// save the currently defined theme configuration in the specified file - /// - bool save(const QString &szThemeFileName); - - const QString & lastError(){ return m_szLastError; }; - void setLastError(const QString &szLastError){ m_szLastError = szLastError; }; - const QString & name(){ return m_szName; }; - void setName(const QString &szName){ m_szName = szName; }; - const QString & version(){ return m_szVersion; }; - void setVersion(const QString &szVersion){ m_szVersion = szVersion; }; - const QString & subdirectory(){ return m_szSubdirectory; }; - void setSubdirectory(const QString &szSubdirectory){ m_szSubdirectory = szSubdirectory; }; - const QString & absoluteDirectory(){ return m_szAbsoluteDirectory; }; - void setAbsoluteDirectory(const QString &szAbsoluteDirectory){ m_szAbsoluteDirectory = szAbsoluteDirectory; } - const QString & author(){ return m_szAuthor; }; - void setAuthor(const QString &szAuthor){ m_szAuthor = szAuthor; }; - const QString & description(){ return m_szDescription; }; - void setDescription(const QString &szDescription){ m_szDescription = szDescription; }; - const QString & date(){ return m_szDate; }; - void setDate(const QString &szDate){ m_szDate = szDate; }; - const QString & application(){ return m_szApplication; }; - void setApplication(const QString &szApplication){ m_szApplication = szApplication; }; - const QString & themeEngineVersion(){ return m_szThemeEngineVersion; }; - void setThemeEngineVersion(const QString &szThemeEngineVersion){ m_szThemeEngineVersion = szThemeEngineVersion; }; - - /// - /// Attempt to load a themeinfo.kvc file present in the specified directory. - /// This function will fail if the directory contains a valid themeinfo.kvc - /// file but no themedata.kvc file unless bIgnoreThemeData is set to true - /// - bool loadFromDirectory(const QString &szThemeDirectory,bool bIgnoreThemeData = false); - - /// - /// Attempt to load the theme screenshot from THEMEDIR/screenshot_*.png - /// This function will work only if the absoluteDirectory() of the theme - /// has been set, otherwise the returned pixmap will be null. - /// - const QPixmap & smallScreenshot(); - /// - /// Attempt to load the theme screenshot from THEMEDIR/screenshot_*.png - /// This function will work only if the absoluteDirectory() of the theme - /// has been set, otherwise the returned pixmap will be null. - /// - const QPixmap & mediumScreenshot(); - /// - /// Attempt to load the theme screenshot from THEMEDIR/screenshot_*.png - /// This function will work only if the absoluteDirectory() of the theme - /// has been set, otherwise the returned pixmap will be null. - /// - const QPixmap & largeScreenshot(); - /// - /// Attempt to load the theme screenshot from THEMEDIR/screenshot_*.png - /// This function will work only if the absoluteDirectory() of the theme - /// has been set, otherwise the returned pixmap will be null. - /// - QString smallScreenshotPath(); -}; - -namespace KviTheme -{ - /// - /// Attempt to load (apply) a theme in the specified directory - /// Will return true on success and false on failure. - /// On success this function will return the theme information in the buffer. - /// On failure this function will also set buffer.lastError() to a meaningful value - /// Note that for convenience this function is implemented in kvi_options.cpp - /// - bool KVIRC_API load(const QString &szThemeDir,KviThemeInfo &buffer); - /// - /// Save a theme given the specified options. - /// Will return true on success and false on failure. - /// On failure this function will also set options.lastError() to a meaningful value - /// This function requires both absoluteDirectory() and subdirectory() to be - /// set to the right values. In theory this function could save a theme - /// in a directory different than $KVIRC_LOCAL_DIR/themes/subdirectory - /// but this feature is actually unused. - /// Note that for convenience this function is implemented in kvi_options.cpp - /// - bool KVIRC_API save(KviThemeInfo &options); - /// - /// Save the theme screenshots in the given EXISTING directory and given - /// an existing screenshot on disk (usually in the tmp directory). - /// - bool KVIRC_API saveScreenshots(KviThemeInfo &options,const QString &szOriginalScreenshotPath); -} - - -#endif //_KVI_THEME_H_ diff --git a/src/kvirc/kernel/kvi_useraction.cpp b/src/kvirc/kernel/kvi_useraction.cpp deleted file mode 100644 index 90a96d082..000000000 --- a/src/kvirc/kernel/kvi_useraction.cpp +++ /dev/null @@ -1,43 +0,0 @@ -//============================================================================= -// -// File : kvi_userlistview.cpp -// Creation date : Tue Mar 18 2003 13:36:12 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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 "kvi_useraction.h" - -static int useraction_table[KVI_NUM_USERACTION_TYPES] = -{ - 25, // ACTION (typically human) - 25, // PRIVMSG - 25, // NOTICE - 20, // TOPIC - 5, // KICK - -5, // NICK - -20, // CHANMODE - -25, // JOIN - -25 // PART (this works only for channels and not for single users on channels) -}; - -int kvi_getUserActionTemperature(unsigned int uIdx) -{ - return useraction_table[uIdx]; -} diff --git a/src/kvirc/kernel/kvi_useraction.h b/src/kvirc/kernel/kvi_useraction.h deleted file mode 100644 index a9ebabd5b..000000000 --- a/src/kvirc/kernel/kvi_useraction.h +++ /dev/null @@ -1,98 +0,0 @@ -#ifndef _KVI_USERACTION_H_ -#define _KVI_USERACTION_H_ - -//============================================================================= -// -// File : kvi_useraction.h -// Creation date : Tue Mar 18 2003 13:36:12 by Szymon Stefanek -// -// This file is part of the KVirc irc client distribution -// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_useraction.h -* \author Szymon Stefanek -* \brief This file defines the user action "temperatures" -* -* The more "hot" is an action, the more humanity is in it -* -* \def KVI_USERACTION_ACTION The action 'action' -* \def KVI_USERACTION_PRIVMSG The action 'message' (channel message) -* \def KVI_USERACTION_NOTICE The action 'notice' -* \def KVI_USERACTION_TOPIC The action 'topic' -* \def KVI_USERACTION_KICK The action 'kick' -* \def KVI_USERACTION_NICK The action 'nick' -* \def KVI_USERACTION_CHANMODE The action 'mode' (channel mode) -* \def KVI_USERACTION_JOIN The action 'join' -* \def KVI_USERACTION_PART The action 'part' -* \def KVI_NUM_USERACTION_TYPES The number of actions' type -* -* These are the temperature levels for a single user on a channel -* -* \def KVI_MAX_TEMPERATURE Maximum: can't go above this -* \def KVI_HOT_TEMPERATURE Hot: human -* \def KVI_HALF_HOT_TEMPERATURE Half hot: signs of humanity -* \def KVI_MID_TEMPERATURE Mid: uncertain -* \def KVI_HALF_COLD_TEMPERATURE Half cold: automa ? -* \def KVI_COLD_TEMPERATURE Cold: bot -* \def KVI_MIN_TEMPERATURE Minimum: can't drop below this -*/ - -#include "kvi_settings.h" - -#define KVI_USERACTION_ACTION 0 -#define KVI_USERACTION_PRIVMSG 1 -#define KVI_USERACTION_NOTICE 2 -#define KVI_USERACTION_TOPIC 3 -#define KVI_USERACTION_KICK 4 -#define KVI_USERACTION_NICK 5 -#define KVI_USERACTION_CHANMODE 6 -#define KVI_USERACTION_JOIN 7 -#define KVI_USERACTION_PART 8 - -#define KVI_NUM_USERACTION_TYPES 9 - -#define KVI_MAX_TEMPERATURE 150 -#define KVI_HOT_TEMPERATURE 100 -#define KVI_HALF_HOT_TEMPERATURE 40 -#define KVI_MID_TEMPERATURE 0 -#define KVI_HALF_COLD_TEMPERATURE -40 -#define KVI_COLD_TEMPERATURE -100 -#define KVI_MIN_TEMPERATURE -150 - -// -// ACTION 30 -// NOTICE 25 -// PRIVMSG 25 -// TOPIC 20 -// KICK 10 -// OP 5 -// VOICE 5 -// DEOP -5 -// DEVOICE -5 -// UNBAN -15 -// BAN -20 -// CHANMODE -25 -// NICK -30 -// JOIN -30 -// - -extern KVIRC_API int kvi_getUserActionTemperature(unsigned int uIdx); - -#endif // _KVI_USERACTION_H_ diff --git a/src/kvirc/kernel/kvi_userinput.cpp b/src/kvirc/kernel/kvi_userinput.cpp deleted file mode 100644 index b6625ec81..000000000 --- a/src/kvirc/kernel/kvi_userinput.cpp +++ /dev/null @@ -1,156 +0,0 @@ -//============================================================================= -// -// File : kvi_userinput.cpp -// Creation date : Sun 25 Sep 2005 05:27:57 by Szymon Stefanek -// -// This file is part of the KVIrc IRC Client distribution -// Copyright (C) 2005-2010 Szymon Stefanek -// -// 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 opinion) 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 "kvi_userinput.h" -#include "kvi_kvs_variantlist.h" -#include "kvi_console.h" -#include "kvi_kvs_script.h" -#include "KviLocale.h" -#include "kvi_ircconnection.h" -#include "kvi_ircconnectionuserinfo.h" -#include "kvi_out.h" -#include "kvi_options.h" -#include "kvi_kvs_eventtriggers.h" - -namespace KviUserInput -{ - bool parse(QString & szData, KviWindow * pWindow, const QString & szContext, bool bUserFriendlyCommandline) - { - const QChar * b = KviQString::nullTerminatedArray(szData); - const QChar * c = b; - if(!c)return true; // empty - - while(c->isSpace()) c++; - - if(!c->unicode()) - return true; // empty - - if(c->unicode() == '\\') - { - c++; - if(c->unicode() != '/') - c--; - } else { - if(c->unicode() == '/') - { - c++; - if(c->unicode() != '/') - { - szData.remove(0, c - b); - return parseCommand(szData,pWindow,szContext,bUserFriendlyCommandline); - } else { - // C++ comment, probably - c--; - } - } - } - - if(KVS_TRIGGER_EVENT_1_HALTED(KviEvent_OnTextInput,pWindow,szData)) - return true; // halted - - if(c != b) - szData.remove(0,c-b); - - parseNonCommand(szData,pWindow); - return true; - } - - bool parseCommand(const QString & szData, KviWindow * pWindow, const QString & szContext, bool bUserFriendlyCommandline) - { - if(bUserFriendlyCommandline) - { - static QString szUserFriendlyCommandlineContext(__tr2qs("commandline::userfriendly")); - - QString szCmd = szData; - KviQString::escapeKvs(&szCmd); - - KviKvsScript kvs(szContext.isEmpty() ? szUserFriendlyCommandlineContext : szContext,szCmd); - return (kvs.run(pWindow,0,0) != KviKvsScript::Error); - } else { - static QString szCommandlineContext(__tr2qs("commandline::kvs")); - - KviKvsScript kvs(szContext.isEmpty() ? szCommandlineContext : szContext,szData); - return (kvs.run(pWindow,0,0/*,KviKvsScript::AssumeLocals*/) != KviKvsScript::Error); - } - } - - void parseNonCommand(QString & szData, KviWindow * pWindow) - { - const QChar * aux = KviQString::nullTerminatedArray(szData); - const QChar * beg = aux; - - if(!beg) - return; // empty - - while(aux->unicode()) - { - while(aux->unicode() && (aux->unicode() != '\n')) - aux++; - - QString buf(beg, aux - beg); - if(aux->unicode() == '\n') - aux++; - beg = aux; - - if(buf.isEmpty()) - buf = " "; // avoid "No text to send" (d3vah) - - switch(pWindow->type()) - { - case KVI_WINDOW_TYPE_CONSOLE: - if(pWindow->connection()) - { - QByteArray data = pWindow->connection()->encodeText(buf); - - if(((KviConsole *)pWindow)->connection()->sendData(data.data())) - { - pWindow->output(KVI_OUT_RAW,"[RAW]: %Q",&buf); - return; - } - } - pWindow->output(KVI_OUT_PARSERERROR,__tr2qs("You are not connected to a server")); - break; - case KVI_WINDOW_TYPE_CHANNEL: - case KVI_WINDOW_TYPE_QUERY: - if(pWindow->connection()) - { - if(KVI_OPTION_BOOL(KviOption_boolExitAwayOnInput)) - { - if(pWindow->connection()->userInfo()->isAway()) - parseCommand("back",pWindow->console()); - } - } - pWindow->ownMessage(buf); - break; - case KVI_WINDOW_TYPE_DCCCHAT: - case KVI_WINDOW_TYPE_DCCVIDEO: - pWindow->ownMessage(buf); - break; - default: - // FIXME: Should pass the message somewhere ?.. a KviWindow handler ? - break; - } - } - } -}; diff --git a/src/kvirc/kernel/kvi_userinput.h b/src/kvirc/kernel/kvi_userinput.h deleted file mode 100644 index 1dc02114f..000000000 --- a/src/kvirc/kernel/kvi_userinput.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef _KVI_USERINPUT_H_ -#define _KVI_USERINPUT_H_ -//============================================================================= -// -// File : kvi_userinput.h -// Creation date : Sun 25 Sep 2005 05:27:57 by Szymon Stefanek -// -// This file is part of the KVIrc IRC Client distribution -// Copyright (C) 2005-2010 Szymon Stefanek -// -// 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 opinion) 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. -// -//============================================================================= - -/** -* \file kvi_userinput.h -* \author Szymon Stefanek -* \brief User input parsing -*/ - -#include "kvi_settings.h" -#include "KviQString.h" -#include "kvi_window.h" - -/** -* \namespace KviUserInput -* \brief Namespace that contains parsing function for the user input -*/ -namespace KviUserInput -{ - /** - * \brief Returns false if szData is a command and it fails to run - * \param szData The input data to parse - * \param pWindow The window associated to the input - * \param szContext The context associated to the input - * \param bUserFriendlyCommandline Whether the commandline is in user friendly mode - * \return bool - * \warning May destroy szData - */ - KVIRC_API bool parse(QString & szData, KviWindow * pWindow, const QString & szContext = KviQString::Empty, bool bUserFriendlyCommandline = false); - - /** - * \brief Returns true if the command run - * \param szData The input data to parse - * \param pWindow The window associated to the input - * \param szContext The context associated to the input - * \param bUserFriendlyCommandline Whether the commandline is in user friendly mode - * \return bool - */ - KVIRC_API bool parseCommand(const QString & szData, KviWindow * pWindow, const QString & szContext = KviQString::Empty, bool bUserFriendlyCommandline = false); - - /** - * \brief Parses the non command input data - * \param szData The input data to parse - * \param pWindow The window associated to the input - * \return void - */ - KVIRC_API void parseNonCommand(QString & szData, KviWindow * pWindow); - - /** - * \brief Escapes any kvs special character from a string - * \param szData The string to escape - * \return void - */ - KVIRC_API void escapeString(QString & szData); - - //bool parseCommandWithSingleArgument(const QString & szData, KviWindow * pWindow, const QString & szContext = KviQString::Empty); -} - -#endif //_KVI_USERINPUT_H_ diff --git a/src/kvirc/kvs/KviKvs.cpp b/src/kvirc/kvs/KviKvs.cpp new file mode 100644 index 000000000..ba2e735a8 --- /dev/null +++ b/src/kvirc/kvs/KviKvs.cpp @@ -0,0 +1,141 @@ +//============================================================================= +// +// File : KviKvs.cpp +// Creation date : Wed 1 Oct 2003 01.38 CEST by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 "KviKvs.h" +#include "KviKvsKernel.h" +#include "KviKvsAliasManager.h" +#include "KviKvsDnsManager.h" +#include "KviKvsTimerManager.h" +#include "KviKvsPopupManager.h" +#include "KviKvsEventManager.h" +#include "KviKvsScriptAddonManager.h" +#include "KviKvsObjectController.h" + +namespace KviKvs +{ + void init() + { + KviKvsKernel::init(); + KviKvsAliasManager::init(); + KviKvsPopupManager::init(); + KviKvsEventManager::init(); + // FIXME: Could we delay the init of these objects ? + // It could be delayed to the first *::instance() call + KviKvsScriptAddonManager::init(); + KviKvsTimerManager::init(); + KviKvsDnsManager::init(); + } + + void done() + { + //KviKvsScriptManager::done(); + KviKvsEventManager::done(); + KviKvsPopupManager::done(); + KviKvsAliasManager::done(); + KviKvsScriptAddonManager::done(); + KviKvsTimerManager::done(); + KviKvsDnsManager::done(); + KviKvsKernel::done(); + } + + void loadPopups(const QString &szFileName) + { + KviKvsPopupManager::instance()->load(szFileName); + } + + void savePopups(const QString &szFileName) + { + KviKvsPopupManager::instance()->save(szFileName); + } + + void clearPopups() + { + KviKvsPopupManager::instance()->clear(); + } + + void loadAliases(const QString &szFileName) + { + KviKvsAliasManager::instance()->load(szFileName); + } + + void saveAliases(const QString &szFileName) + { + KviKvsAliasManager::instance()->save(szFileName); + } + + void clearAliases() + { + KviKvsAliasManager::instance()->clear(); + } + + void loadAppEvents(const QString &szFileName) + { + KviKvsEventManager::instance()->loadAppEvents(szFileName); + } + + void saveAppEvents(const QString &szFileName) + { + KviKvsEventManager::instance()->saveAppEvents(szFileName); + } + + void clearAppEvents() + { + KviKvsEventManager::instance()->removeAllScriptAppHandlers(); + } + + void loadRawEvents(const QString &szFileName) + { + KviKvsEventManager::instance()->loadRawEvents(szFileName); + } + + void saveRawEvents(const QString &szFileName) + { + KviKvsEventManager::instance()->saveRawEvents(szFileName); + } + + void clearRawEvents() + { + KviKvsEventManager::instance()->removeAllScriptRawHandlers(); + } + + void loadScriptAddons(const QString &szFileName) + { + KviKvsScriptAddonManager::instance()->load(szFileName); + } + + void saveScriptAddons(const QString &szFileName) + { + KviKvsScriptAddonManager::instance()->save(szFileName); + } + + void clearScriptAddons() + { + KviKvsScriptAddonManager::instance()->clear(); + } + + void flushUserClasses() + { + KviKvsKernel::instance()->objectController()->flushUserClasses(); + } +}; diff --git a/src/kvirc/kvs/KviKvs.h b/src/kvirc/kvs/KviKvs.h new file mode 100644 index 000000000..97042d0b0 --- /dev/null +++ b/src/kvirc/kvs/KviKvs.h @@ -0,0 +1,59 @@ +#ifndef _KVI_KVS_H_ +#define _KVI_KVS_H_ +//============================================================================= +// +// File : KviKvs.h +// Creation date : Wed 1 Oct 2003 01.37 CEST by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2003-2010 Szymon Stefanek (pragma at kvirc dot net) +// +// 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 opinion) 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 header contains ALL the stuff that the user should see +#include "KviKvsScript.h" + +namespace KviKvs +{ + void init(); // this never fails + void done(); // this never fails + + void loadAliases(const QString &szFileName); + void saveAliases(const QString &szFileName); + void clearAliases(); + + void loadPopups(const QString &szFileName); + void savePopups(const QString &szFileName); + void clearPopups(); + + void loadAppEvents(const QString &szFileName); + void saveAppEvents(const QString &szFileName); + void clearAppEvents(); + + void loadRawEvents(const QString &szFileName); + void saveRawEvents(const QString &szFileName); + void clearRawEvents(); + + void loadScriptAddons(const QString &szFileName); + void saveScriptAddons(const QString &szFileName); + void clearScriptAddons(); + + void flushUserClasses(); +}; + + +#endif //!_KVI_KVS_H_ diff --git a/src/kvirc/kvs/KviKvsAction.cpp b/src/kvirc/kvs/KviKvsAction.cpp new file mode 100644 index 000000000..92aedd1df --- /dev/null +++ b/src/kvirc/kvs/KviKvsAction.cpp @@ -0,0 +1,50 @@ +//============================================================================= +// +// File : KviKvsAction.cpp +// Creation date : Sat 04 Dec 2004 04:22:12 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsAction.h" +#include "KviKvsScript.h" +#include "KviWindow.h" + +KviKvsAction::KviKvsAction(QObject * pParent, const QString & szName, const QString & szScriptCode, const QString & szVisibleName, const QString & szDescription, KviActionCategory * pCategory, const QString & szBigIconId, const QString & szSmallIconId, unsigned int uFlags, const QString & szKeySequence) +: KviAction(pParent,szName,szVisibleName,szDescription,pCategory,szBigIconId,szSmallIconId,uFlags,szKeySequence) +{ + m_szScript = QString(szScriptCode); +} + +KviKvsAction::~KviKvsAction() +{ + unregisterAccelerator(); +} + +const QString & KviKvsAction::scriptCode() +{ + return m_szScript; +} + +void KviKvsAction::activate() +{ + if(!isEnabled()) + return; // no way + KviKvsScript::run(m_szScript,g_pActiveWindow); +} diff --git a/src/kvirc/kvs/KviKvsAction.h b/src/kvirc/kvs/KviKvsAction.h new file mode 100644 index 000000000..dbf552724 --- /dev/null +++ b/src/kvirc/kvs/KviKvsAction.h @@ -0,0 +1,82 @@ +#ifndef _KVI_KVSACTION_H_ +#define _KVI_KVSACTION_H_ +//============================================================================= +// +// File : KviKvsAction.h +// Creation date : Sat 04 Dec 2004 04:22:12 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2004-2010 Szymon Stefanek +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviKvsAction.h +* \author Szymon Stefanek +* \brief Actions handling +*/ + +#include "kvi_settings.h" +#include "KviAction.h" + +class KviKvsScript; + +/** +* \class KviKvsAction +* \brief This class handles the actions +*/ +class KVIRC_API KviKvsAction : public KviAction +{ + Q_OBJECT +protected: + QString m_szScript; +public: + /** + * \brief Contructs the action object + * \param pParent The parent object + * \param szName The name of the action + * \param szScriptCode The code of the script contained in the action + * \param szVisibleName Permanent visible name, visible at least in the action drawer + * \param szDescription The description of the action + * \param pCategory One of KviActionManager::category*() or 0 (default category) + * \param szBigIconId The id of a big icon (32x32) + * \param szSmallIconId The id of a small icon (16x16) + * \param uFlags Flags of the action like connection needed, context needed, ... + * \param szKeySequence The shortcut to activate the action + * \return KviKvsAction + */ + KviKvsAction(QObject * pParent, const QString & szName, const QString & szScriptCode, const QString & szVisibleName, const QString & szDescription, KviActionCategory * pCategory = NULL, const QString & szBigIconId = QString(), const QString & szSmallIconId = QString(), unsigned int uFlags = 0, const QString & szKeySequence = QString()); + + /** + * \brief Destroys the action object + */ + ~KviKvsAction(); +public: + /** + * \brief Returns the code of the script contained in the action + * \return const QString & + */ + const QString & scriptCode(); + + /** + * \brief Executes the action + * \return void + */ + virtual void activate(); +}; + +#endif // _KVI_KVSACTION_H_ diff --git a/src/kvirc/kvs/KviKvsAliasManager.cpp b/src/kvirc/kvs/KviKvsAliasManager.cpp new file mode 100644 index 000000000..0745ce70a --- /dev/null +++ b/src/kvirc/kvs/KviKvsAliasManager.cpp @@ -0,0 +1,156 @@ +//============================================================================= +// +// File : KviKvsAliasManager.cpp +// Creation date : Mon 15 Dec 2003 02:11:41 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsAliasManager.h" +#include "KviConfigurationFile.h" + +KviKvsAliasManager * KviKvsAliasManager::m_pAliasManager = 0; + +KviKvsAliasManager::KviKvsAliasManager() +{ + m_pAliasManager = this; + m_pAliasDict = new KviPointerHashTable(51,false); + m_pAliasDict->setAutoDelete(true); +} + +KviKvsAliasManager::~KviKvsAliasManager() +{ + delete m_pAliasDict; + m_pAliasManager = 0; +} + +void KviKvsAliasManager::init() +{ + if(KviKvsAliasManager::instance()) + { + qDebug("WARNING: Trying to create the KviKvsAliasManager twice!"); + return; + } + (void)new KviKvsAliasManager(); +} + +void KviKvsAliasManager::done() +{ + if(!KviKvsAliasManager::instance()) + { + qDebug("WARNING: Trying to destroy the KviKvsAliasManager twice!"); + return; + } + delete KviKvsAliasManager::instance(); +} + +void KviKvsAliasManager::add(const QString &szName,KviKvsScript * pAlias) +{ + // This piece of code, when inlined by gcc (i.e, placed in a header), + // shows an interesting problem. + + // KviKvsPointerHashTable<>::replace() is a template and is likely to be inlined too. + // The internals of replace() use another template called KviKvsPointerHashTableEntry<>. + // When this function is called from a dynamically loaded shared library + // the internal template is likely to be instantiated in the shared library itself. + // Now if the shared library is unloaded, a dangling vtable pointer is stored + // in the inner template and it will die once we attempt to clear the m_pAliasDict ht. + // + // This happens for KviAliasEditor, for instance. In it's commit() function + // it called this method and caused the vtable pointer to be 0x7fffdfab0030. + // + // (gdb) info symbol 0x7fffdfab0030 + // vtable for KviPointerList > + 16 in section .data.rel.ro + // of /usr/local/lib/kvirc/4.0/modules/libkvialiaseditor.so <-- inside the module + // + // while the correct vtable (the one that appears when the add() function is called from somewhere else) is + // + //(gdb) info symbol 0x6bc210 + // vtable for KviPointerList > + 16 in section .rodata + // of /usr/local/bin/kvirc <-- inside the executable + // + // This is a linkage problem. Either caused by gcc itself, or maybe wrong flags + // passed by the cmake generated Makefiles. Gcc should notice that the symbol is already defined + // inside the executable and use that one instead. + // + // So finally, we can't inline this. + + // The bad news is that this problem may pop up also in other pieces of code... + m_pAliasDict->replace(szName,pAlias); + emit aliasRefresh(szName); +} + +void KviKvsAliasManager::completeCommand(const QString &word,KviPointerList * matches) +{ + KviPointerHashTableIterator it(*m_pAliasDict); + while(it.current()) + { + if(KviQString::equalCIN(word,it.current()->name(),word.length())) + matches->append(new QString(it.current()->name())); + ++it; + } +} + +// FIXME: #warning "A binary config would work better and faster here!" + +void KviKvsAliasManager::save(const QString & filename) +{ + KviConfigurationFile cfg(filename,KviConfigurationFile::Write); + cfg.clear(); + + KviPointerHashTableIterator it(*m_pAliasDict); + + while(it.current()) + { + cfg.setGroup(it.current()->name()); + cfg.writeEntry("_Buffer",it.current()->code()); + ++it; + } +} + +void KviKvsAliasManager::load(const QString & filename) +{ + m_pAliasDict->clear(); + KviConfigurationFile cfg(filename,KviConfigurationFile::Read); + + KviConfigurationFileIterator it(*(cfg.dict())); + + KviPointerList l; + l.setAutoDelete(true); + + while(it.current()) + { + l.append(new QString(it.currentKey())); + ++it; + } + + for(QString * s = l.first();s;s = l.next()) + { + cfg.setGroup(*s); + QString szCode = cfg.readEntry("_Buffer",""); + if(!szCode.isEmpty()) + { + KviKvsScript * m = new KviKvsScript(*s,szCode); + m_pAliasDict->insert(*s,m); + } + ++it; + } +} diff --git a/src/kvirc/kvs/KviKvsAliasManager.h b/src/kvirc/kvs/KviKvsAliasManager.h new file mode 100644 index 000000000..39d4174cb --- /dev/null +++ b/src/kvirc/kvs/KviKvsAliasManager.h @@ -0,0 +1,67 @@ +#ifndef _KVI_KVS_ALIASMANAGER_H_ +#define _KVI_KVS_ALIASMANAGER_H_ +//============================================================================= +// +// File : KviKvsAliasManager.h +// Creation date : Mon 15 Dec 2003 02:11:41 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviPointerHashTable.h" + +#include "KviPointerList.h" +#include "KviQString.h" + +#include "KviKvsScript.h" + +class KVIRC_API KviKvsAliasManager : public QObject +{ + Q_OBJECT +protected: // it only can be created and destroyed by KviKvsAliasManager::init()/done() + KviKvsAliasManager(); + ~KviKvsAliasManager(); +protected: + KviPointerHashTable * m_pAliasDict; + static KviKvsAliasManager * m_pAliasManager; +public: + static KviKvsAliasManager * instance() + { return m_pAliasManager; }; + static void init(); // called by KviKvs::init() + static void done(); // called by KviKvs::done() + + KviPointerHashTable * aliasDict(){ return m_pAliasDict; }; + const KviKvsScript * lookup(const QString & szName) + { return m_pAliasDict->find(szName); }; + void add(const QString &szName,KviKvsScript * pAlias); + bool remove(const QString & szName) + { return m_pAliasDict->remove(szName); }; + void clear() + { m_pAliasDict->clear(); }; + + void save(const QString & filename); + void load(const QString & filename); + + void completeCommand(const QString &word,KviPointerList * matches); +signals: + void aliasRefresh(const QString &); +}; +// namespaces are handled completly in the editing! +#endif //!_KVI_KVS_ALIASMANAGER_H_ diff --git a/src/kvirc/kvs/KviKvsArray.cpp b/src/kvirc/kvs/KviKvsArray.cpp new file mode 100644 index 000000000..bd1b268ed --- /dev/null +++ b/src/kvirc/kvs/KviKvsArray.cpp @@ -0,0 +1,249 @@ +//============================================================================= +// +// File : KviKvsArray.cpp +// Creation date : Tue 07 Oct 2003 01:07:31 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsArray.h" +#include "KviMemory.h" + +#include + +#define KVI_KVS_ARRAY_ALLOC_CHUNK 8 + +KviKvsArray::KviKvsArray() +: KviHeapObject() +{ + m_pData = 0; + m_uSize = 0; + m_uAllocSize = 0; +} + +KviKvsArray::KviKvsArray(const KviKvsArray & array) +: KviHeapObject() +{ + m_uSize = array.m_uSize; + m_uAllocSize = array.m_uAllocSize; + if(m_uAllocSize > 0) + { + m_pData = (KviKvsVariant **)KviMemory::allocate((sizeof(KviKvsVariant *)) * m_uAllocSize); + kvs_uint_t u; + for(u = 0; u < m_uSize; u++) + { + if(array.m_pData[u]) + m_pData[u] = new KviKvsVariant(*(array.m_pData[u])); + else m_pData[u] = 0; + } + } else { + m_pData = 0; + } +} + +KviKvsArray::~KviKvsArray() +{ + if(m_pData) + { + for(kvs_uint_t u = 0; u < m_uSize; u++) + { + if(m_pData[u]) + delete m_pData[u]; + } + KviMemory::free(m_pData); + } +} + +int KviKvsArray::compareReverse(const void * pV1, const void * pV2) +{ + if(*((KviKvsVariant **)pV1)) + return (*((KviKvsVariant **)pV1))->compare(*((KviKvsVariant **)pV2)); + if(*((KviKvsVariant **)pV2)) + return -(*((KviKvsVariant **)pV2))->compare(*((KviKvsVariant **)pV1)); + return 0; +} + +int KviKvsArray::compare(const void * pV1, const void * pV2) +{ + if(*((KviKvsVariant **)pV1)) + return -(*((KviKvsVariant **)pV1))->compare(*((KviKvsVariant **)pV2)); + if(*((KviKvsVariant **)pV2)) + return (*((KviKvsVariant **)pV2))->compare(*((KviKvsVariant **)pV1)); + return 0; +} + +void KviKvsArray::sort() +{ + if(m_uSize < 2) + return; // already sorted + qsort(m_pData,m_uSize,sizeof(KviKvsVariant *),compare); + findNewSize(); +} + +void KviKvsArray::rsort() +{ + if(m_uSize < 2) + return; // already sorted + qsort(m_pData,m_uSize,sizeof(KviKvsVariant *),compareReverse); + findNewSize(); +} + +void KviKvsArray::unset(kvs_uint_t uIdx) +{ + if(uIdx >= m_uSize) + return; + + if(m_pData[uIdx]) + { + delete m_pData[uIdx]; + m_pData[uIdx] = 0; + } + + if(uIdx == (m_uSize - 1)) + { + findNewSize(); + } +} + +void KviKvsArray::findNewSize() +{ + // find the new size + if(m_uSize == 0) + return; + kvs_uint_t u = m_uSize - 1; + while(u > 0) + { + if(m_pData[u]) + break; + u--; + } + + if(m_pData[u]) + m_uSize = u + 1; + else { + // u == 0, and there is no data in there + m_uSize = 0; + } + // need to shrink ? + + if((m_uAllocSize - m_uSize) > KVI_KVS_ARRAY_ALLOC_CHUNK) + { + m_uAllocSize = m_uSize; + // m_pData is non-zero here since was m_uSize > 0 initally + if(m_uSize > 0) + { + m_pData = (KviKvsVariant **)KviMemory::reallocate(m_pData,(sizeof(KviKvsVariant *)) * m_uAllocSize); + } else { + KviMemory::free(m_pData); + m_pData = 0; + } + } +} + +void KviKvsArray::set(kvs_uint_t uIdx, KviKvsVariant * pVal) +{ + if(uIdx >= m_uSize) + { + if(uIdx == m_uSize) + m_uAllocSize += KVI_KVS_ARRAY_ALLOC_CHUNK; // sequential set + else + m_uAllocSize = uIdx + 1; + + if(m_pData) + m_pData = (KviKvsVariant **)KviMemory::reallocate(m_pData,(sizeof(KviKvsVariant *)) * m_uAllocSize); + else + m_pData = (KviKvsVariant **)KviMemory::allocate((sizeof(KviKvsVariant *)) * m_uAllocSize); + + for(kvs_uint_t u=m_uSize;u= m_uSize) + { + if(uIdx == m_uSize) + m_uAllocSize += KVI_KVS_ARRAY_ALLOC_CHUNK; // sequential set + else + m_uAllocSize = uIdx + 1; + + if(m_pData) + m_pData = (KviKvsVariant **)KviMemory::reallocate(m_pData,(sizeof(KviKvsVariant *)) * m_uAllocSize); + else + m_pData = (KviKvsVariant **)KviMemory::allocate((sizeof(KviKvsVariant *)) * m_uAllocSize); + + for(kvs_uint_t u = m_uSize; u < uIdx; u++) + m_pData[u] = 0; + m_uSize = uIdx+1; + m_pData[uIdx] = new KviKvsVariant(); + } else { + if(!m_pData[uIdx]) + m_pData[uIdx] = new KviKvsVariant(); + } + return m_pData[uIdx]; +} + +void KviKvsArray::serialize(QString & szResult) +{ + QString szBuffer; + szResult = "["; + kvs_uint_t u = 0; + bool bNeedComma = false; + while(u < m_uSize) + { + if(bNeedComma) + szResult.append(','); + else + bNeedComma = true; + + if(m_pData[u]) + { + m_pData[u]->serialize(szBuffer); + szResult.append(szBuffer); + } else { + szResult.append("null"); + } + u++; + } + szResult.append(']'); +} + +void KviKvsArray::appendAsString(QString & szBuffer) +{ + kvs_uint_t u = 0; + bool bNeedComma = false; + while(u < m_uSize) + { + if(bNeedComma) + szBuffer.append(','); + else + bNeedComma = true; + + if(m_pData[u]) + m_pData[u]->appendAsString(szBuffer); + u++; + } +} diff --git a/src/kvirc/kvs/KviKvsArray.h b/src/kvirc/kvs/KviKvsArray.h new file mode 100644 index 000000000..2172b4e39 --- /dev/null +++ b/src/kvirc/kvs/KviKvsArray.h @@ -0,0 +1,163 @@ +#ifndef _KVI_KVS_ARRAY_H_ +#define _KVI_KVS_ARRAY_H_ +//============================================================================= +// +// File : KviKvsArray.h +// Creation date : Tue 07 Oct 2003 01:07:31 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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. +// +//============================================================================= + +/** +* \file KviKvsArray.h +* \author Szymon Stefanek +* \brief Handling of array data type in KVS +*/ + +#include "kvi_settings.h" +#include "KviKvsVariant.h" +#include "KviHeapObject.h" + +/** +* \class KviKvsArray +* \brief This class defines a new data type which contains array data +* \warning This class must not have virtual functions nor destructor. Otherwise it will happily +* crash on windows when it is allocated in modules and destroyed anywhere else around +*/ +class KVIRC_API KviKvsArray : public KviHeapObject +{ +public: + /** + * \brief Constructs the array data + * \return KviKvsArray + */ + KviKvsArray(); + + /** + * \brief Constructs the array data + * + * This is a carbon copy + * \param array The array to copy from + * \return KviKvsArray + */ + KviKvsArray(const KviKvsArray & array); + + /** + * \brief Destroys the array data + */ + ~KviKvsArray(); +protected: + KviKvsVariant ** m_pData; + kvs_uint_t m_uSize; + kvs_uint_t m_uAllocSize; +public: + /** + * \brief Unsets an element from the array + * \param uIdx The index of the element to unset + * \return void + */ + void unset(kvs_uint_t uIdx); + + /** + * \brief Sets an element into the array at the given index + * \param uIdx The index of the element to set + * \param pVal The value to set + * \return void + */ + void set(kvs_uint_t uIdx, KviKvsVariant * pVal); + + /** + * \brief Returns the element at the given index + * \param uIdx The index of the element to retrieve + * \return KviKvsVariant * + */ + KviKvsVariant * at(kvs_uint_t uIdx) const { return (uIdx < m_uSize) ? m_pData[uIdx] : 0; }; + + /** + * \brief Returns the element at the given index + * + * If the element doesn't exists, it returns an empty element. If the index is out of + * array bounds, it increases the array size, fillin the array in with zeros. + * \param uIdx The index of the element to retrieve + * \return KviKvsVariant * + */ + KviKvsVariant * getAt(kvs_uint_t uIdx); + + /** + * \brief Returns true if the array is empty + * \return bool + */ + bool isEmpty(){ return m_uSize == 0; }; + + /** + * \brief Returns the size of the array + * \return kvs_uint_t + */ + kvs_uint_t size(){ return m_uSize; }; + + /** + * \brief Appends data to the array converting it into a string + * \param szBuffer The string to append + * \return void + */ + void appendAsString(QString & szBuffer); + + /** + * \brief Serializes the array to a given buffer + * \param szResult The buffer to store + * \return void + */ + void serialize(QString & szResult); + + /** + * \brief Sorts the array + * \return void + */ + void sort(); + + /** + * \brief Sorts the array in reverse order + * \return void + */ + void rsort(); +protected: + /** + * \brief Finds the new size of the array + * \return void + */ + void findNewSize(); +private: + /** + * \brief Compares two elements of the array + * \param pV1 The first element to compare + * \param pV2 The second element to compare + * \return int + */ + static int compare(const void * pV1, const void * pV2); + + /** + * \brief Compares two elements of the array in reverse order + * \param pV1 The first element to compare + * \param pV2 The second element to compare + * \return int + */ + static int compareReverse(const void * pV1, const void * pV2); +}; + +#endif // _KVI_KVS_ARRAY_H_ diff --git a/src/kvirc/kvs/KviKvsArrayCast.cpp b/src/kvirc/kvs/KviKvsArrayCast.cpp new file mode 100644 index 000000000..16d392dd2 --- /dev/null +++ b/src/kvirc/kvs/KviKvsArrayCast.cpp @@ -0,0 +1,44 @@ +//============================================================================= +// +// File : KviKvsArrayCast.cpp +// Creation date : Tue 10 May 2005 00:05:50 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsArrayCast.h" + +KviKvsArrayCast::~KviKvsArrayCast() +{ + if(m_pArray) + if(m_bOwned) + delete m_pArray; +} + +void KviKvsArrayCast::clear() +{ + if(m_pArray) + { + if(m_bOwned) + delete m_pArray; + m_pArray = 0; + } +} diff --git a/src/kvirc/kvs/KviKvsArrayCast.h b/src/kvirc/kvs/KviKvsArrayCast.h new file mode 100644 index 000000000..65fb139be --- /dev/null +++ b/src/kvirc/kvs/KviKvsArrayCast.h @@ -0,0 +1,50 @@ +#ifndef _KVI_KVS_ARRAYCAST_H_ +#define _KVI_KVS_ARRAYCAST_H_ +//============================================================================= +// +// File : KviKvsArrayCast.h +// Creation date : Tue 10 May 2005 00:05:50 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviKvsArray.h" + +class KVIRC_API KviKvsArrayCast +{ +protected: + KviKvsArray * m_pArray; + bool m_bOwned; +public: + KviKvsArrayCast() + : m_pArray(0) {}; + ~KviKvsArrayCast(); +public: + void clear(); + KviKvsArray * array() + { return m_pArray; }; + void release() + { m_bOwned = false; }; + void set(KviKvsArray * pArry,bool bOwned) + { m_pArray = pArry; m_bOwned = bOwned; }; +}; + + +#endif //!_KVI_KVS_ARRAYCAST_H_ diff --git a/src/kvirc/kvs/KviKvsAsyncDnsOperation.cpp b/src/kvirc/kvs/KviKvsAsyncDnsOperation.cpp new file mode 100644 index 000000000..3d72b2892 --- /dev/null +++ b/src/kvirc/kvs/KviKvsAsyncDnsOperation.cpp @@ -0,0 +1,122 @@ +//============================================================================= +// +// File : KviKvsAsyncDnsOperation.cpp +// Creation date : Sun 10 Jul 2005 04:36:15 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsAsyncDnsOperation.h" +#include "KviDnsResolver.h" +#include "KviKvsScript.h" +#include "KviKvsVariant.h" +#include "KviApplication.h" +#include "kvi_out.h" +#include "KviLocale.h" +#include "KviError.h" +#include "KviKvsVariantList.h" + +#include + + +KviKvsAsyncDnsOperation::KviKvsAsyncDnsOperation(KviWindow * pWnd,QString &szQuery,KviDnsResolver::QueryType eType,KviKvsScript * pCallback,KviKvsVariant * pMagic) +: KviKvsAsyncOperation(pWnd) +{ + m_pDns = new KviDnsResolver(); + m_szQuery = szQuery; + m_eType = eType; + m_pCallback = pCallback; + m_pMagic = pMagic; + connect(m_pDns,SIGNAL(lookupDone(KviDnsResolver *)),this,SLOT(lookupTerminated(KviDnsResolver *))); + if(!m_pDns->lookup(szQuery,eType)) + QTimer::singleShot(10,this,SLOT(dnsStartFailed())); +} + +KviKvsAsyncDnsOperation::~KviKvsAsyncDnsOperation() +{ + if(m_pDns)delete m_pDns; + if(m_pMagic)delete m_pMagic; + if(m_pCallback)delete m_pCallback; +} + +void KviKvsAsyncDnsOperation::dnsStartFailed() +{ + lookupTerminated(m_pDns); +} + +void KviKvsAsyncDnsOperation::lookupTerminated(KviDnsResolver *) +{ + KviWindow * pWnd = window(); + if(!g_pApp->windowExists(pWnd))pWnd = g_pActiveWindow; + + if(m_pCallback) + { + KviKvsVariantList params; + params.setAutoDelete(true); + if(m_pDns->state() == KviDnsResolver::Failure) + { + params.append(new KviKvsVariant(m_szQuery)); + params.append(new KviKvsVariant((kvs_int_t)0)); + params.append(new KviKvsVariant(KviError::getDescription(m_pDns->error()))); + params.append(new KviKvsVariant()); + params.append(new KviKvsVariant(*m_pMagic)); + } else { + QString * fh = m_pDns->hostnameList()->first(); + QString * fi = m_pDns->ipAddressList()->first(); + + params.append(new KviKvsVariant(m_szQuery)); + params.append(new KviKvsVariant((kvs_int_t)1)); + params.append(new KviKvsVariant(fi ? *fi : QString("?.?.?.?"))); + params.append(new KviKvsVariant(fh ? *fh : QString("?.?"))); + params.append(new KviKvsVariant(*m_pMagic)); + } + + m_pCallback->run(pWnd,¶ms,0,KviKvsScript::PreserveParams); + + delete this; + return; + } + + // we have no callback : output the results + QString szQuery = m_pDns->query(); + pWnd->output(KVI_OUT_HOSTLOOKUP,__tr2qs_ctx("DNS Lookup result for query \"%Q\"","kvs"),&szQuery); + + if(m_pDns->state() == KviDnsResolver::Failure) + { + QString strDescription(KviError::getDescription(m_pDns->error())); + pWnd->output(KVI_OUT_HOSTLOOKUP,__tr2qs_ctx("Error: %Q","kvs"),&strDescription); + } else { + int idx = 1; + for(QString * h = m_pDns->hostnameList()->first();h;h = m_pDns->hostnameList()->next()) + { + pWnd->output(KVI_OUT_HOSTLOOKUP,__tr2qs_ctx("Hostname %d: %Q","kvs"),idx,h); + idx++; + } + idx = 1; + for(QString * a = m_pDns->ipAddressList()->first();a;a = m_pDns->ipAddressList()->next()) + { + pWnd->output(KVI_OUT_HOSTLOOKUP,__tr2qs_ctx("IP address %d: %Q","kvs"),idx,a); + idx++; + } + } + + delete this; +} diff --git a/src/kvirc/kvs/KviKvsAsyncDnsOperation.h b/src/kvirc/kvs/KviKvsAsyncDnsOperation.h new file mode 100644 index 000000000..5beb05d28 --- /dev/null +++ b/src/kvirc/kvs/KviKvsAsyncDnsOperation.h @@ -0,0 +1,53 @@ +#ifndef _KVI_KVS_ASYNCDNSOPERATION_H_ +#define _KVI_KVS_ASYNCDNSOPERATION_H_ +//============================================================================= +// +// File : KviKvsAsyncDnsOperation.h +// Creation date : Sun 10 Jul 2005 04:36:15 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviKvsAsyncOperation.h" +#include "KviQString.h" +#include "KviDnsResolver.h" + +class KviWindow; +class KviKvsScript; +class KviKvsVariant; + +class KVIRC_API KviKvsAsyncDnsOperation : public KviKvsAsyncOperation +{ + Q_OBJECT +public: + KviKvsAsyncDnsOperation(KviWindow * pWnd,QString &szQuery,KviDnsResolver::QueryType eType,KviKvsScript * pCallback = 0,KviKvsVariant * pMagic = 0); + virtual ~KviKvsAsyncDnsOperation(); +protected: + KviDnsResolver * m_pDns; + KviDnsResolver::QueryType m_eType; + KviKvsVariant * m_pMagic; + KviKvsScript * m_pCallback; + QString m_szQuery; +protected slots: + void lookupTerminated(KviDnsResolver *); + void dnsStartFailed(); +}; + +#endif //!_KVI_KVS_ASYNCDNSOPERATION_H_ diff --git a/src/kvirc/kvs/KviKvsAsyncOperation.cpp b/src/kvirc/kvs/KviKvsAsyncOperation.cpp new file mode 100644 index 000000000..f82304bc8 --- /dev/null +++ b/src/kvirc/kvs/KviKvsAsyncOperation.cpp @@ -0,0 +1,66 @@ +//============================================================================= +// +// File : KviKvsAsyncOperation.cpp +// Creation date : Sat 09 Jul 2005 04:54:24 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsAsyncOperation.h" +#include "KviKvsKernel.h" +#include "KviWindow.h" + +KviKvsAsyncOperation::KviKvsAsyncOperation(KviWindow * pWnd) +: QObject() +{ + m_pWnd = pWnd; + KviKvsKernel::instance()->asyncOperationManager()->registerOperation(this); +} + +KviKvsAsyncOperation::~KviKvsAsyncOperation() +{ + KviKvsKernel::instance()->asyncOperationManager()->unregisterOperation(this); +} + + +KviKvsAsyncOperationManager::KviKvsAsyncOperationManager() +{ + m_pOperationList = new KviPointerList; + m_pOperationList->setAutoDelete(false); +} + +KviKvsAsyncOperationManager::~KviKvsAsyncOperationManager() +{ + while(m_pOperationList->first()) + delete m_pOperationList->first(); + delete m_pOperationList; +} + +void KviKvsAsyncOperationManager::registerOperation(KviKvsAsyncOperation * o) +{ + m_pOperationList->append(o); +} + +void KviKvsAsyncOperationManager::unregisterOperation(KviKvsAsyncOperation * o) +{ + m_pOperationList->removeRef(o); +} + diff --git a/src/kvirc/kvs/KviKvsAsyncOperation.h b/src/kvirc/kvs/KviKvsAsyncOperation.h new file mode 100644 index 000000000..4c7d3c0ce --- /dev/null +++ b/src/kvirc/kvs/KviKvsAsyncOperation.h @@ -0,0 +1,60 @@ +#ifndef _KVI_KVS_ASYNCOPERATION_H_ +#define _KVI_KVS_ASYNCOPERATION_H_ +//============================================================================= +// +// File : KviKvsAsyncOperation.h +// Creation date : Sat 09 Jul 2005 04:54:24 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviPointerList.h" + +#include + +class KviWindow; + +class KVIRC_API KviKvsAsyncOperation : public QObject +{ + Q_OBJECT +public: + KviKvsAsyncOperation(KviWindow * pWnd); + virtual ~KviKvsAsyncOperation(); +protected: + KviWindow * m_pWnd; +public: + KviWindow * window(){ return m_pWnd; }; +}; + + +class KVIRC_API KviKvsAsyncOperationManager +{ + friend class KviKvsAsyncOperation; +public: + KviKvsAsyncOperationManager(); + ~KviKvsAsyncOperationManager(); +protected: + KviPointerList * m_pOperationList; +protected: + void registerOperation(KviKvsAsyncOperation * o); + void unregisterOperation(KviKvsAsyncOperation * o); +}; + +#endif //!_KVI_KVS_ASYNCOPERATION_H_ diff --git a/src/kvirc/kvs/KviKvsCallbackObject.cpp b/src/kvirc/kvs/KviKvsCallbackObject.cpp new file mode 100644 index 000000000..8c94c1197 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCallbackObject.cpp @@ -0,0 +1,108 @@ +//============================================================================= +// +// File : KviKvsCallbackObject.cpp +// Creation date : Mon 21 Nov 2005 01:46:51 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCallbackObject.h" +#include "KviConsoleWindow.h" +#include "KviApplication.h" + + +KviKvsCallbackObject::KviKvsCallbackObject(const QString &szCallbackName,KviWindow * pTargetWindow,const QString &szCallbackCode,KviKvsVariantList * pMagicParams,unsigned int uFlags) +: KviHeapObject() +{ + m_uFlags = uFlags; + m_pTargetWindow = pTargetWindow; + if(pTargetWindow) + m_pTargetConsole = pTargetWindow->console(); + else + m_pTargetConsole = 0; + m_pMagicParams = new KviKvsVariantList(); + if(pMagicParams) + for(KviKvsVariant * v = pMagicParams->first();v;v = pMagicParams->next()) + m_pMagicParams->append(new KviKvsVariant(*v)); + QString szName; + szName = szCallbackName; + szName += "::"; + szName += "callback"; + m_pScript = new KviKvsScript(szName,szCallbackCode); +} + +KviKvsCallbackObject::~KviKvsCallbackObject() +{ + delete m_pScript; + delete m_pMagicParams; +} + +KviKvsCallbackObject::CallbackStatus KviKvsCallbackObject::execute(KviKvsVariantList * pParams,KviKvsVariant * pRetVal) +{ + // first of all check the window + if(!m_pTargetWindow) + m_pTargetWindow = g_pApp->activeConsole(); + if(!g_pApp->windowExists(m_pTargetWindow)) + { + // target window dead + if(m_uFlags & OnlyIfWindowExists) + return TargetWindowDead; + // rebind + m_pTargetWindow = m_pTargetConsole; + if(!m_pTargetWindow) + { + m_pTargetWindow = g_pApp->activeConsole(); + if(!m_pTargetWindow) + return Error; // ooops... + } else { + if(!g_pApp->windowExists(m_pTargetWindow)) + { + m_pTargetWindow = g_pApp->activeConsole(); + if(!m_pTargetWindow) + return Error; // ooops... + } + } + } + // ok, got the window + // now take care of the params + KviKvsVariantList params; + params.setAutoDelete(false); + KviKvsVariant * v; + + if(pParams) + for(v = pParams->first();v;v = pParams->next()) + params.append(v); + + for(v = m_pMagicParams->first();v;v = m_pMagicParams->next()) + params.append(v); + + unsigned int uRet = m_pScript->run(m_pTargetWindow,¶ms,pRetVal,KviKvsScript::PreserveParams); + + if(uRet) + { + if(uRet & KviKvsScript::HaltEncountered) + return HaltEncountered; + return Success; + } + + // ooops... error + return Error; +} diff --git a/src/kvirc/kvs/KviKvsCallbackObject.h b/src/kvirc/kvs/KviKvsCallbackObject.h new file mode 100644 index 000000000..fa725d627 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCallbackObject.h @@ -0,0 +1,84 @@ +#ifndef _KVI_KVS_CALLBACKOBJECT_H_ +#define _KVI_KVS_CALLBACKOBJECT_H_ +//============================================================================= +// +// File : KviKvsCallbackObject.h +// Creation date : Mon 21 Nov 2005 01:46:51 by Szymon Stefanek +// +// This file is part of the KVIrc IRC Client distribution +// Copyright (C) 2005-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviHeapObject.h" + +#include "KviWindow.h" +#include "KviQString.h" +#include "KviKvsVariantList.h" +#include "KviKvsScript.h" + + +// +// This is a simple callback object useful in stuff like dialog.message(){} +// You derive a class from KviKvsCallbackObject, pass the callback data (code,window and magic params) +// and when the time comes ask it to execute the callback (maybe by passing some special parameters) +// +// + +class KVIRC_API KviKvsCallbackObject : public KviHeapObject +{ +public: + enum CallbackFlags { + // Execute the callback only if the target window exists + // If this flag is not used then if the target window dies + // the callback is executed in another window (the associated console, if possible, otherwise the first available console) + OnlyIfWindowExists = 1 + }; + enum CallbackStatus { + // succesfull execution + Success, + // error in command + Error, + // succesfull execution, but halt encountered + HaltEncountered, + // execution aborted since OnlyIfWindowExists was passed and the target window is dead + TargetWindowDead + }; +public: + KviKvsCallbackObject( + const QString &szCallbackSource, // the name of this callback (should identify its source, like "dialog.message"): displayed in error messages + KviWindow * pTargetWindow, // the window that this callback should be triggered in (can be zero: to execute in the first available console) + const QString &szCallbackCode, // the callback code (may be empty!) + KviKvsVariantList * pMagicParams, // magic parameters that should be passed to the callback (this class makes a copy of them) + unsigned int uFlags = 0 // a combination of CallbackFlags + ); + virtual ~KviKvsCallbackObject(); +protected: + KviKvsScript * m_pScript; // the callback script + KviWindow * m_pTargetWindow; + KviWindow * m_pTargetConsole; + KviKvsVariantList * m_pMagicParams; + unsigned int m_uFlags; +protected: + // the parameter list is always shallow! + CallbackStatus execute(KviKvsVariantList * pParams = 0,KviKvsVariant * pRetVal = 0); +}; + + + +#endif //!_KVI_KVS_CALLBACKOBJECT_H_ diff --git a/src/kvirc/kvs/KviKvsCoreCallbackCommands.cpp b/src/kvirc/kvs/KviKvsCoreCallbackCommands.cpp new file mode 100644 index 000000000..5df6791d4 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreCallbackCommands.cpp @@ -0,0 +1,1205 @@ +//============================================================================= +// +// File : KviKvsCoreCallbackCommands.cpp +// Creation date : Fri 31 Oct 2003 04:07:58 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCoreCallbackCommands.h" + +#include "KviKvsKernel.h" +#include "KviKvsTimerManager.h" +#include "KviKvsAliasManager.h" +#include "KviKvsVariantList.h" +#include "KviKvsAsyncDnsOperation.h" +#include "KviKvsEventManager.h" +#include "KviKvsProcessManager.h" +#include "KviKvsObjectController.h" + +#include "KviCommandFormatter.h" +#include "KviIrcConnectionAsyncWhoisData.h" +#include "KviIrcConnection.h" +#include "KviScriptButton.h" +#include "KviIconManager.h" +#include "KviLocale.h" + +#include "KviTalToolTip.h" + +#include + +namespace KviKvsCoreCallbackCommands +{ + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: ahost + @type: + command + @title: + ahost + @syntax: + ahost [-i] [-a] ([,]){ } + @short: + DNS lookup + @switches: + !sw: --ipv6 | -i + Causes the command to run in IPv6 mode + !sw: --any | -a + Causes the command to run in unspecified mode and lookup both IPv4 and IPv6 addresses + @description: + Starts a DNS lookup for the and reports the + results by calling the callback routine. + The -i switch causes the command to execute + in IPv6 mode (and lookup ONLY IPv6 hosts!).[br] + The -a switch causes the command to run in "unspecified" mode + and return any available address: IPv4 or Ipv6.[br] + This command also performs reverse lookups (if you pass an IP address as ).[br] + The callback command gets passed five parameters:[br] + $0 contains the query string ( in fact)[br] + $1 contains the value 1 if the query was succesfull.[br] + In that case the remaining parameters are set as follows:[br] + $2 contains the first ip address associated to the [br] + $3 contains the hostname associated to the [br] + $4 contains the eventual passed.[br] + If $1 contains the value 0 then the query has failed and[br] + $2 contains an error message explaining the failure.[br] + $3 is empty[br] + $4 contains the eventual passed.[br] + Please note that if the dns query fails to even start for some + reason then your callback MAY be called even before ahost() returns.[br] + @switches: + !sw: -i + Causes the command to execute in IPv6 mode (and lookup ONLY IPv6 hosts!). + !sw: -a + The -a switch causes the command to run in "unspecified" mode + and return any available address: IPv4 or Ipv6. + @examples: + [example] + ahost("localhost") + { + [cmd]echo[/cmd] "Lookup: "$0; + if($1) + { + [cmd]echo[/cmd] "Ip address: "$2; + [cmd]echo[/cmd] "Hostname: "$3; + } else { + [cmd]echo[/cmd] "Error: $2"; + } + } + ahost -i ("irc.flashnet.it","Hello :)") + { + [cmd]echo[/cmd] "Lookup: "$0; + [cmd]echo[/cmd] "Magic: $3"; + if($1) + { + [cmd]echo[/cmd] "Ip address: "$2; + [cmd]echo[/cmd] "Hostname: "$3; + } else { + [cmd]echo[/cmd] "Error: $2"; + } + } + ahost -a ("cafe:babe::dead:beef") + { + [cmd]echo[/cmd] "Lookup: "$0; + [cmd]echo[/cmd] "Magic: $3"; + if($1) + { + [cmd]echo[/cmd] "Ip address: "$2; + [cmd]echo[/cmd] "Hostname: "$3; + } else { + [cmd]echo[/cmd] "Error: $2"; + } + } + [/example] + @seealso: + [cmd]host[/cmd] + */ + + KVSCCC(ahost) + { + QString szQuery; + KviKvsVariant * pMagicPtr; + KVSCCC_PARAMETERS_BEGIN + KVSCCC_PARAMETER("dnsquery",KVS_PT_NONEMPTYSTRING,0,szQuery) + KVSCCC_PARAMETER("magic",KVS_PT_VARIANT,KVS_PF_OPTIONAL,pMagicPtr) + KVSCCC_PARAMETERS_END + + KviDnsResolver::QueryType queryType = KviDnsResolver::IPv4; + if(KVSCCC_pSwitches->find('i',"ipv6"))queryType = KviDnsResolver::IPv6; + if(KVSCCC_pSwitches->find('a',"any"))queryType = KviDnsResolver::Any; + + KviKvsVariant * pMagic = pMagicPtr ? new KviKvsVariant(*pMagicPtr) : new KviKvsVariant(); + + new KviKvsAsyncDnsOperation( + KVSCCC_pContext->window(), + szQuery, + queryType, + new KviKvsScript(*KVSCCC_pCallback), + pMagic); + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: alias + @title: + alias + @type: + command + @short: + Adds a new alias or modifies an existing one + @syntax: + alias [-q] () + alias [-q] (){} + @switches: + !sw: -q | --quiet + Causes the command to run quietly + @description: + Adds the alias with the specified code. + The implementation code can be either a single KVS instruction + or an instruction block (instruction list enclosed in braces).[br] + If the alias already exists, it is replaced with the new implementation.[br] + If the is empty (eg. "{}" or just a ";") + the alias is removed. + If the "remove" form is used but the specified does not exist + in the alias store then a warning is printed unless + the -q (--quiet) switch is used. + If contains a "::" prefix, then the alias + is created in the namespace specified by . + If the namespace does not exist, it is created. + Any alias without the "::" prefix is created in the root + namespace. Namespaces are useful to avoid collisions in alias names + between scripts. Only really common aliases should be created + in the root namespace - all of the internal functionality of your + scripts should be hidden in your own namespace. + @examples: + [example] + [comment]# Add the alias j[/comment] + alias(j) + { + [cmd]join[/cmd] $0; + } + [comment]# Remove the alias j[/comment] + alias(j){} + [comment]# Add the alias j in namespace letters[/comments] + alias(letters::j) + { + [cmd]echo[/cmd] "j" + } + [/example] + @seealso: + [doc:kvs_aliasesandfunctions]Aliases and functions[/doc] + */ + + /* + @doc: function + @title: + function + @type: + command + @short: + A synomim for alias + @syntax: + function [-q] () + function [-q] (){} + @switches: + !sw: -q | --quiet + Causes the command to run quietly + @description: + This command is a synonim for [cmd]alias[/cmd]. + @seealso: + [doc:kvs_aliasesandfunctions]Aliases and functions[/doc] + */ + + + KVSCCC(alias) + { + KviKvsVariant * vName = KVSCCC_pParams->first(); + + if(!vName || vName->isEmpty()) + { + KVSCCC_pContext->error(__tr2qs_ctx("Missing alias name","kvs")); + return false; + } + + QString szName; + vName->asString(szName); + + // we allow only [\w:]+ + QRegExp re("[\\w:]+"); + if(!re.exactMatch(szName)) + { + KVSCCC_pContext->error(__tr2qs_ctx("Alias names can contain only letters, digits, underscores and '::' namespace separators","kvs")); + return false; + } + + // make sure that we have only doubled "::" and not ":" or ":::..." + QString tmp = szName; + tmp.replace("::","@"); // @ is not allowed by the rule above + if(tmp.indexOf(":") != -1) + { + KVSCCC_pContext->error(__tr2qs_ctx("Stray ':' character in alias name: did you mean ...:: ?","kvs")); + return false; + } + + if(tmp.indexOf("@@") != -1) + { + KVSCCC_pContext->error(__tr2qs_ctx("Found an empty namespace in alias name","kvs")); + return false; + } + + if(KVSCCC_pCallback->code().isEmpty()) + { + if(!KviKvsAliasManager::instance()->remove(szName)) + { + if(!KVSCCC_pSwitches->find('q',"quiet")) + KVSCCC_pContext->warning(__tr2qs_ctx("The alias '%Q' does not exist","kvs"),&szName); + } + } else { + KviKvsScript * pScript = new KviKvsScript(*KVSCCC_pCallback); + pScript->setName(szName); + KviKvsAliasManager::instance()->add(szName,pScript); + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: awhois + @type: + command + @title: + awhois + @syntax: + awhois [-i] ([,]) + { + + } + @short: + Asynchronous WHOIS + @switches: + !sw: -i | --idle-time + Ask the whois information to the server that is + connected to, effectively returning the user's idle time. + @description: + AWHOIS stands for Asynchronous WHOIS. It is used to obtain data for a specified + irc user (designated by ). This command sends a WHOIS query to the + server and silently awaits the sequence of replies. When the "End of WHOIS" message + is received from server the is executed passing the WHOIS + information as positional parameters.[br] + The string is an optional string to be evaluated at AWHOIS execution time. + It is passed as the last positional parameter.[br] + Callback command parameters:[br] + $0 = nickname[br] + $1 = username[br] + $2 = hostname[br] + $3 = realname (may be empty)[br] + $4 = server[br] + $5 = idle time (may be empty)[br] + $6 = signon time (may be empty)[br] + $7 = channels (may be empty)[br] + $8 = server that provided the information[br] + $9 = away message (empty if user hasn't set an away message)[br] + $10 = magic string evaluated at awhois call (may be empty)[br] + $11 = account the user is logged into (may be empty)[br] + $12 = additional, server-specific info (may be empty)[br] + If the -i switch is specified, the whois message is sent to the server + that the user is connected to; in this way you will probably + get the idle time of the user too.[br] + If the server replies with a "No such nick/channel error message" the + will be still triggered, but will have all the parameters + empty with the exception of $0.[br] + If the connection gets interrupted before all the information have been received, + the will never be triggered.[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc].[br] + @examples: + [example] + awhois(pragma){ echo $0-; } + [/example] + */ + + KVSCCC(awhois) + { + QString szNick; + KviKvsVariant * pMagic; + KVSCCC_PARAMETERS_BEGIN + KVSCCC_PARAMETER("nickname",KVS_PT_NONEMPTYSTRING,0,szNick) + KVSCCC_PARAMETER("magic",KVS_PT_VARIANT,KVS_PF_OPTIONAL,pMagic) + KVSCCC_PARAMETERS_END + + KVSCCC_REQUIRE_CONNECTION + + QByteArray szN = KVSCCC_pConnection->encodeText(szNick); + + KviAsyncWhoisInfo * info = new KviAsyncWhoisInfo(); + info->pCallback = new KviKvsScript(*KVSCCC_pCallback); + info->pMagic = pMagic ? new KviKvsVariant(*pMagic) : new KviKvsVariant(); + info->szNick = szNick; + info->pWindow = KVSCCC_pWindow; + + KVSCCC_pConnection->asyncWhoisData()->add(info); + + if(KVSCCC_pSwitches->find('i',"idle-time"))KVSCCC_pConnection->sendFmtData("WHOIS %s %s",szN.data(),szN.data()); + else KVSCCC_pConnection->sendFmtData("WHOIS %s",szN.data()); + + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: button + @title: + button + @type: + command + @short: + Adds/removes/changes user definable buttons + @syntax: + button [-d] [-q] (,[,[,]]) + { + + } + @switches: + !sw: -d | --disabled + Creates the button as disabled + !sw: -q | --quiet + Run quietly, print no warnings + @description: + Adds a new user defined button with the specified .[br] + [br] + The parameter is ignored and is present only for + backward compatibility. + [br] + The button image is specified by the [doc:image_id][/doc].[br] + The optional button text is specified by .[br] + The will be executed as reaction to a button press.[br] + [br] + The "window" type button can be added only to the windows that have a button container: this + actually includes at least console, channels and queries.[br] + The button is added to the current window; if you want to add it to a different + window, use the [doc:command_rebinding]standard -r command rebinding[/doc] switch.[br] + The will be executed as reaction to a button press; the + code execution will be bound to the window that the button is attacched to.[br] + If a button with already exists in the current window, its parameters are changed + according to the passed values (, and ).[br] + [br] + Passing an empty removes the button.[br] + The callback parameters $0 and $1 will contain the screen coordinates of the bottom-left + corner of the button: this is useful for showing a popup menu in response to the click.[br] + If the -q switch is used, this command prints no warnings.[br] + The -d switch causes the button to be disabled (grayed).[br] + @examples: + [example] + button(w,test,-1,Test button){ echo Test!; } + button(w,test){} + [/example] + + */ + + KVSCCC(button) + { + KviKvsVariant * pUnused; + QString szName,szIcon,szLabel; + KVSCCC_PARAMETERS_BEGIN + KVSCCC_PARAMETER("type_unused",KVS_PT_VARIANT,0,pUnused) + KVSCCC_PARAMETER("name",KVS_PT_NONEMPTYSTRING,0,szName) + KVSCCC_PARAMETER("icon",KVS_PT_NONEMPTYSTRING,KVS_PF_OPTIONAL,szIcon) + KVSCCC_PARAMETER("label",KVS_PT_NONEMPTYSTRING,KVS_PF_OPTIONAL,szLabel) + KVSCCC_PARAMETERS_END + + KviScriptUserButton * pButton = 0; + + if(!KVSCCC_pWindow->buttonContainer()) + { + if(!KVSCCC_pSwitches->find('q',"quiet")) + KVSCCC_pContext->warning(__tr2qs_ctx("The specified window has no button containers","kvs")); + return true; + } + + //pButton = (KviScriptUserButton *)(KVSCCC_pWindow->buttonContainer())->child(szName.toUtf8().data(),"KviWindowScriptButton"); + pButton = (KviScriptUserButton *)(KVSCCC_pWindow->buttonContainer())->findChild(szName); + + if(KVSCCC_pCallback->code().isEmpty()) + { + if(pButton)delete pButton; + else { + if(!KVSCCC_pSwitches->find('q',"quiet")) + KVSCCC_pContext->warning(__tr2qs_ctx("Window button '%Q' not found","kvs"),&szName); + } + return true; + } + + if(!pButton) + { + pButton = new KviWindowScriptButton(KVSCCC_pWindow->buttonContainer(),KVSCCC_pWindow,szName.toUtf8().data()); + pButton->show(); + } + + KviTalToolTip::remove(pButton); + if(!szLabel.isEmpty()) + { + pButton->setButtonText(szLabel); + KviTalToolTip::add(pButton,szLabel); + } + + pButton->setButtonCode(new KviKvsScript(*KVSCCC_pCallback)); + + if(!szIcon.isEmpty()) + { + QPixmap * pix = g_pIconManager->getImage(szIcon); + if(pix) + { + pButton->setButtonPixmap(*pix); + } else { + if(!KVSCCC_pSwitches->find('q',"quiet")) + KVSCCC_pContext->warning(__tr2qs_ctx("Can't find the icon '%Q'","kvs"),&szIcon); + } + } + + pButton->setEnabled(!(KVSCCC_pSwitches->find('d',"disabled"))); + + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: event + @title: + event + @type: + command + @short: + Adds a new event handler + @syntax: + event [-q] (,) + { + + } + @switches: + !sw: -q | --quiet + Do not print any warnings + @description: + Adds the handler with to + the list of handlers for the event .[br] + If the is empty + the handler is removed from the handler + list instead of being added.[br] + The may be one of the kvirc-builtin event names + or a numeric code (from 0 to 999) of a raw server message.[br] + If the -q switch is specified then the command runs in quiet mode. + @seealso: + [cmd]eventctl[/cmd] + */ + + KVSCCC(event) + { + QString szEventName,szHandlerName; + KVSCCC_PARAMETERS_BEGIN + KVSCCC_PARAMETER("event_name",KVS_PT_NONEMPTYSTRING,0,szEventName) + KVSCCC_PARAMETER("handler_name",KVS_PT_NONEMPTYSTRING,0,szHandlerName) + KVSCCC_PARAMETERS_END + + bool bOk; + int iNumber = szEventName.toInt(&bOk); + bool bIsRaw = (bOk && (iNumber >= 0) && (iNumber < 1000)); + + if(bIsRaw) + { + if(!KviKvsEventManager::instance()->isValidRawEvent(iNumber)) + { + if(!KVSCCC_pSwitches->find('q',"quiet")) + KVSCCC_pContext->warning(__tr2qs_ctx("No such event (%Q)","kvs"),&szEventName); + return true; + } + } else { + iNumber = KviKvsEventManager::instance()->findAppEventIndexByName(szEventName); + if(!KviKvsEventManager::instance()->isValidAppEvent(iNumber)) + { + if(!KVSCCC_pSwitches->find('q',"quiet")) + KVSCCC_pContext->warning(__tr2qs_ctx("No such event (%Q)","kvs"),&szEventName); + return true; + } + } + + if(KVSCCC_pCallback->code().isEmpty()) + { + if(bIsRaw) + { + if(!KviKvsEventManager::instance()->removeScriptRawHandler(iNumber,szHandlerName)) + { + if(!KVSCCC_pSwitches->find('q',"quiet")) + KVSCCC_pContext->warning(__tr2qs_ctx("No handler '%Q' for raw numeric event '%d'","kvs"),&szHandlerName,iNumber); + } + } else { + if(!KviKvsEventManager::instance()->removeScriptAppHandler(iNumber,szHandlerName)) + { + if(!KVSCCC_pSwitches->find('q',"quiet")) + KVSCCC_pContext->warning(__tr2qs_ctx("No handler '%Q' for event '%Q'","kvs"),&szHandlerName,&szEventName); + } + } + } else { + if(bIsRaw) + { + // remove the old handler + KviKvsEventManager::instance()->removeScriptRawHandler(iNumber,szHandlerName); + QString contextName; + KviQString::sprintf(contextName,"RawEvent%d::%Q",iNumber,&szHandlerName); + KviKvsScriptEventHandler * pHandler = new KviKvsScriptEventHandler(szHandlerName,contextName,KVSCCC_pCallback->code()); + KviKvsEventManager::instance()->addRawHandler(iNumber,pHandler); + } else { + // remove the old handler + KviKvsEventManager::instance()->removeScriptAppHandler(iNumber,szHandlerName); + QString contextName; + KviQString::sprintf(contextName,"%Q::%Q",&szEventName,&szHandlerName); + KviKvsScriptEventHandler * pHandler = new KviKvsScriptEventHandler(szHandlerName,contextName,KVSCCC_pCallback->code()); + KviKvsEventManager::instance()->addAppHandler(iNumber,pHandler); + } + } + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: exec + @type: + command + @title: + exec + @syntax: + exec [switches] ([,]) + { + + } + @short: + Asynchronous execution of external programs + @switches: + !sw: -q | --quiet + Quiet: do not print any warnings + !sw: -t | --trigger-termination + Trigger the termination event + !sw: -x | --trigger-startup + Trigger the startup event + !sw: -n | --no-stdout + Do NOT trigger any stdout events + !sw: -e | --trigger-stderr + Trigger stderr events + !sw: -b | --output-block + Trigger the with the stdout and stderr events exactly once, + passing the complete block of process output. The events are triggered even + if the process output is empty. + !sw: -k= | --kill-after= + Kill the process unconditionally after milliseconds. + If the -t switch is used then the termination event will be + triggered just after the process has been killed. + !sw: -p= | --trigger-ping= + Trigger with "ping" events every milliseconds. + !sw: -w | --bind-to-window + Kill the process if the current window is closed. In this case the + termination event is NOT triggered (since the parent window has been lost). + If this switch is not used then the process is rebound to + the active console window and continues running. + !sw: -s= | --shell= + Use instead of the default interpreter "sh -c". + The should be able to launch the interpeter + and should contain the necessary arguments in order to allow + KVirc to pass the "commandline" by appending it as the last parameter. + !sw: -d | --direct + Use no command interpreter at all: run the command directly. + Takes precedence over -s. + !sw: -q | --quiet + Run quietly + @description: + [b]Overview[/b][br] + Executes the by passing it to a command interpreter. + The is executed asynchronously: this means that + when exec returns the control to the next command, + may be still running.[br] + [br] + [b]The callback[/b][br] + The is triggered on several events related to the + child process and it gets passed the following parameters:[br] + $0 = [br] + $1 = [br] + $2 = [br] + The first parameter specifies the event cause and contains one of the + following strings: "stdout","stderr","terminated","started" and "ping". + [b]By default (if no switches are used) only "stdout" type events are triggered[/b]. + The second parameter depends on the event cause and contains data sensible + to each event type. The third parameter is the eventual + passed to the exec command call.[br] + [br] + [b]Interacting with the process[/b][br] + If you use [cmd]halt[/cmd] to terminate + the callback then the slave process is killed immediately and + no other callback events are triggered.[br] If you return some non empty string + then this string will be written to the process stdin stream. This trick + can be used to control interactive processes. Please note that you must + include all the relevant carriage returns and newlines in the return value + (see [fnc]$cr[/fnc] and [fnc]$lf[/fnc]).[br] + [br] + [b]Startup event[/b][br] + If the -x switch is used then the startup event is triggered + just after the process has been successfully launched. + The $0 parameter passed to the callback contains the string "started". + Parameter $1 contains the pid of the slave process.[br] + [br] + [b]Stdout data event[/b][br] + The stdout data event is triggered when the process prints some output + on its stdout stream. This event is triggered by default and to disable + it you must use the -n switch. $0 contains the string "stdout". + If the -b switch is not used then $1 contains a single line of process + output with the trailing carriage return and/or line feed stripped. + If -b is used then $1 contains the whole process output + block (eventually empty) with all the cr/lf pairs.[br] + [br] + [b]Stderr data event[/b][br] + The stderr data event is similar to the stdout one but there are three differences. + The first one is that the stderr event is NOT triggered by default: you must + use the -e switch to enable it. The second difference is that $0 + contains "stderr" instead of "stdout". The last difference is that $1 contains data + coming from the slave process stderr stream.[br] + [br] + [b]Termination event[/b][br] + The termination event is triggered after the slave process has terminated its + execution. You must use the -t switch to enable it since it is + disabled by default. $0 contains the string "terminated". $1 contains the process exit + status value. (Note that if the process has crashed or has been terminated + by an external singnal then this value will be 0).[br] + [br] + [b]Ping event[/b][br] + The ping event is triggered only if the -p= switch is passed.[br] + This event may be useful to monitor the process status while it is not + emitting any output, to write data to its stdin stream (by the means of [cmd]return[/cmd]) + or simply to give some feedback to the user while the slave process is + doing a long computation.[br] + [br] + [b]The extended scope variables[/b][br] + The has a set of [doc:data_types]extended scope variables[/doc] + that conserve their value during the whole life time of the slave process.[br] + These variables can be accessed through the %: syntax and are + useful to store process private data between multiple calls.[br] + [b]Some words about the switches[/b][br] + If the -b switch is used then the is called only once + for the events stdout and stderr (if enabled) with the complete output block from the process. + With the -b switch the events stdout and stderr are triggered once even if the process + emits no output. + The -s= switch may be used to specify the path of the command interpreter + that is "sh -c" by default on unix machines and "cmd.exe /c" on windows. + The interpreter executable is searched on the system PATH. + If the process can't be started then a warning message is printed in the current window + unless the -q (quiet) flag is used.[br] + [br] + @examples: + [example] + [comment]# Really simple example: print only the stdout of a slave process[/comment] + exec("cat /proc/cpuinfo"){ echo $1; }; + [comment]# Now print only stderr: enable stderr and disable stdout[/comment] + exec -e -n ("sed -senseless"){ echo $1; }; + [comment]# Do it another way: enable stderr and filter out stdout[/comment] + exec -e ("sed -senseless"){ if($0 == "stderr")echo $1; } + [comment]# Now enable all (almost) events and print them[/comment] + exec -e -t -x ("cat /proc/cpuinfo && sed -senseless"){ echo [event:$0] $1; } + [comment]# Now see what happens if -b is used[/comment] + exec -b -e -t -x ("cat /proc/cpuinfo && sed -senseless"){ echo [event:$0] $1; } + [comment]# Run an iterative script and kill it after 20 seconds[/comment] + exec -k=20000 ("while true; do sleep 1; echo \"Tic\"; done"){ echo [event:$0] $1; } + [comment]# Run a blocking process, kill it after 20 seconds[/comment] + [comment]# and give feedback to the user by the means of ping[/comment] + exec -k=20000 -p=1000 -t ("cat") + { + if($0 == "ping")echo "[event:$0] Please wait while doing a huge computation ..." + else if($0 == "terminated")echo "[event:$0] Ok, done :)" + } + [comment]# Do the same but this time use the extended scope vars[/comment] + [comment]# Use also a nicer syntax[/comment] + exec -k=20000 -p=1000 -t ("cat") + { + switch($0) + { + case("ping"): + { + if(%:x == 1) + { + %:x = 0; + echo "Tic!" + } else { + %:x = 1; + echo "Tac!" + } + } + break; + case("terminated"): + { + echo "Ok, done :)" + } + break; + } + } + [comment]# Again do the same but kill the process explicitly[/comment] + exec -x -p=1000 -t ("cat") + { + switch($0) + { + case("started"): + { + [comment]# Initialize the counter[/comment] + %:x = 10; + } + break; + case("ping"): + { + echo %:x + %:x-- + [comment]# When the counter reaches zero, kill the process with halt[/comment] + if(%:x == 0)halt; + } + break; + case("terminated"): + { + echo "Boom!" + } + break; + } + } + [comment]# Now play with an interactive process[/comment] + [comment]# WARNING: Please note that spam is illegal and generates bad karma[/comment] + [comment]# Try it only with your own e-mail address as recipient[/comment] + exec -s -k=60000 -t ("telnet my.mail.server.com 25") + { + if($0 == "started") + { + %:state = 0 + [comment]# Returning an empty string does not write to stdin[/comment] + return + } + + if($1 == "stderr") + { + echo "[stderr] $1" + return + } + + if($1 == "terminated") + { + echo "[process terminated]" + return + } + + echo "[stdout] $1" + + switch(%:state) + { + case(0): + { + [comment]# Waiting for 220 (ready)[/comment] + if($str.match("220*",$1)) + { + %:state++ + echo "Sending HELO..." + return "HELO myhostname$cr$lf"; + } + } + break + case(1): + { + [comment]# Waiting for 250 (after the HELO)[/comment] + if($str.match("250*",$1)) + { + %:state++ + echo "Sending MAIL..." + return "MAIL From: $cr$lf" + } else { + echo "HELO command not accepted: $1" + halt + } + } + break; + case(2): + { + [comment]# Waiting for another 250 (MAIL accepted)[/comment] + if($str.match("250*",$1)) + { + %:state++ + echo "Sending RCPT..." + return "RCPT To: $cr$lf" + } else { + echo "MAIL command not accepted: $1" + halt + } + } + break; + case(3): + { + [comment]# Waiting for another 250 (RCPT accepted)[/comment] + if($str.match("250*",$1)) + { + %:state++ + echo "Sending DATA..." + return "DATA$cr$lf" + } else { + echo "RCPT not accepted: $1" + halt + } + } + break; + case(4): + { + [comment]# Waiting for 354 (ok, go on)[/comment] + if($str.match("354*",$1)) + { + %:state++ + echo "Sending body..." + return "This is a test message :)$cr$lf$cr$lf.$cr$lf" + } else { + echo "Mail body not accepted: $1" + halt + } + } + break; + case(5): + { + [comment]# We don't wait anymore :)[/comment] + %:state++ + echo "Sending QUIT..." + return "QUIT$cr$lf" + } + break; + default: + { + [comment]# Usually the mail server closes the connection[/comment] + %:state++ + if(%:state > 10) + { + [comment]# But if it does not in few messages[/comment] + [comment]# Then force the process to die[/comment] + halt + } + } + } + } + [/example] + */ + + KVSCCC(exec) + { + QString szCommandline; + KviKvsVariant * pMagic; + KVSCCC_PARAMETERS_BEGIN + KVSCCC_PARAMETER("commandline",KVS_PT_NONEMPTYSTRING,0,szCommandline) + KVSCCC_PARAMETER("magic",KVS_PT_VARIANT,KVS_PF_OPTIONAL,pMagic) + KVSCCC_PARAMETERS_END + + int f = 0; + + if(KVSCCC_pSwitches->find('t',"trigger-termination") != 0)f |= KVI_KVS_PROCESSDESCRIPTOR_TRIGGERTERMINATED; + if(KVSCCC_pSwitches->find('n',"no-stdout") == 0)f |= KVI_KVS_PROCESSDESCRIPTOR_TRIGGERSTDOUT; + if(KVSCCC_pSwitches->find('e',"trigger-stderr") != 0)f |= KVI_KVS_PROCESSDESCRIPTOR_TRIGGERSTDERR; + if(KVSCCC_pSwitches->find('x',"trigger-startup") != 0)f |= KVI_KVS_PROCESSDESCRIPTOR_TRIGGERSTARTED; + if(KVSCCC_pSwitches->find('b',"output-block") != 0)f |= KVI_KVS_PROCESSDESCRIPTOR_OUTPUTBYBLOCKS; + if(KVSCCC_pSwitches->find('w',"bind-to-window") != 0)f |= KVI_KVS_PROCESSDESCRIPTOR_KILLIFNOWINDOW; + if(KVSCCC_pSwitches->find('d',"direct") != 0)f |= KVI_KVS_PROCESSDESCRIPTOR_NOSHELL; + + QString szShell; + KVSCCC_pSwitches->getAsStringIfExisting('s',"shell",szShell); + + kvs_int_t iPingTime = 0; + kvs_int_t iMaxRunTime = 0; + + KviKvsVariant * pPing = KVSCCC_pSwitches->find('p',"trigger-ping"); + if(pPing) + { + if(!(pPing->asInteger(iPingTime) && iPingTime > 0)) + { + KVSCCC_pContext->warning(__tr2qs_ctx("The specified ping time is invalid: assuming zero (no ping)","kvs")); + iPingTime = 0; + } + } + + KviKvsVariant * pKill = KVSCCC_pSwitches->find('k',"kill-after"); + if(pKill) + { + if(!(pKill->asInteger(iMaxRunTime) && iMaxRunTime > 0)) + { + KVSCCC_pContext->warning(__tr2qs_ctx("The specified maximum run time is invalid: assuming zero (infinite)","kvs")); + iMaxRunTime = 0; + } + } + + KviKvsProcessDescriptorData * d = new KviKvsProcessDescriptorData; + + d->szCommandline = szCommandline; + d->szShell = szShell; + d->pWnd = KVSCCC_pContext->window(); + d->pMagic =pMagic ? new KviKvsVariant(*pMagic) : 0; + d->iFlags = f; + d->pCallback = new KviKvsScript(*KVSCCC_pCallback); + d->iMaxRunTime = iMaxRunTime; + d->iPingTimeout = iPingTime; + + KviKvsProcessAsyncOperation * op = new KviKvsProcessAsyncOperation(d); + if(!op->start()) + { + if(KVSCCC_pSwitches->find('q',"quiet") == 0)KVSCCC_pContext->warning(__tr2qs_ctx("Failed to start the process","kvs")); + delete op; + } + + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: privateimpl + @title: + privateimpl + @type: + command + @short: + Adds a private implementation of a function + @syntax: + privateimpl(,) + @description: + Adds a private implementation of function to the + existing object designed by . + must be a valid command sequence.[br] + Side note:[br] + This command can not successfully implement + the "constructor" function since it must be called + after this one has already been executed.[br] + To implement a constructor you MUST write your own class definition.[br] + @seealso: + [cmd]class[/cmd], + [doc:objects]Objects documentation[/doc] + */ + + KVSCCC(privateimpl) + { + Q_UNUSED(__pSwitches); + + kvs_hobject_t hObject; + QString szFunctionName; + KVSCCC_PARAMETERS_BEGIN + KVSCCC_PARAMETER("object_handle",KVS_PT_HOBJECT,0,hObject) + KVSCCC_PARAMETER("function_name",KVS_PT_NONEMPTYSTRING,0,szFunctionName) + KVSCCC_PARAMETERS_END + + KviKvsObject * o = KviKvsKernel::instance()->objectController()->lookupObject(hObject); + if(!o) + { + KVSCCC_pContext->error(__tr2qs_ctx("The specified object does not exist","kvs")); + return false; + } + + o->registerPrivateImplementation(szFunctionName,KVSCCC_pCallback->code()); + + return true; + } + + + ///////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: timer + @title: + timer + @type: + command + @short: + Starts a timer + @syntax: + timer [-s] [-p] (,[,[,[,...]]]) + { + + } + @switches: + !sw: -s | --single-shot + Causes the timer to trigger only once (single shot timer) + !sw: -p | --persistent + Creates a persistent timer bound to any existing window + @description: + Starts a new timer named with the specified delay (in milliseconds).[br] + The timer periodically calls the specified code passing the + eventual strings as positional parameters.[br] + If a timer with the same name already exists, it is replaced by this one.[br] + [b]The is evaluated at timer "shot" time and NOT while + this command is being parsed. This means that the identifiers that you put + inside will NOT have the current values.[/b] + The values will be assigned at timer "shot" time.[br] + This is a common scripters error and problem: if it is not clear, look at the examples below.[br] + The timer is bound to the window in that this command is executed in.[br] + If the window gets destroyed, the timer is stopped; unless the -p switch is used.[br] + The -p switch causes the timer to be persistent across the application and exists until + the last window has been closed: it is basically rebound to another (random) window when the + original window is destroyed.[br] + The -s switch cuases this timer to trigger only once: it will be automatically destroyed after that.[br] + The time has an associated set of [doc:data_structures]extended scope variables[/doc]: + the variables that begin with "%:" have their life extended to the whole "life" of the timer.[br] + Using a very low delay is a common method to perform some background processing: you + basically split a huge job in small slices and execute them when the timer is triggered + until you run out of slices. A delay of 0 will cause the timer to be called whenever + KVIrc has some "idle time" to spend. + On the other hand, remember that timers are precious resources: many timers running + with a very low delay will cause KVIrc to slow down.[br] + Since all the kvirc timers share the same namespace it is a good idea to use + descriptive timer names: a timer named "a" is likely to be used by two or more scripts + at once causing one (or both) of them to fail.[br] + A timer can be stopped at any time by using the [cmd]killtimer[/cmd] command. + @seealso: + [cmd]killtimer[/cmd] + @examples: + [example] + [comment]# Just a plain timer[/comment] + timer(test,1000){ echo "Hello!"; } + [comment]# Now watch the timer running[/comment] + killtimer test + [comment]# Single shot timer[/comment] + timer -s (test,1000){ echo "This will fire only once!"; } + [comment]# The call above is equivalent to[/comment] + timer(test,1000){ echo "This will file only once!"; killtimer test; } + [comment]# Callback parameters: consider the following code[/comment] + %parameter = "some string value" + echo "Before calling /timer \%parameter is \"%parameter\"" + timer -s (test,1000,%parameter){ echo "inside the callback \%parameter is \"%parameter\" but \$0 is \"$0\""; } + [comment]# watch the timer running, and note the behaviour of the %parameter variable[/comment] + killtimer test + [comment]# Use the extended scope timer variables[/comment] + timer(test,1000) + { + [comment]# Use the extended scope %:count variable to keep track[/comment] + [comment]# of the times that this timer has been called[/comment] + [cmd]if[/cmd]("%:count" == "")%:count = 1 + else %:count++ + [cmd]echo[/cmd] "This timer has fired %:count times" + if(%:count == 10) + { + # This will kill the current timer, we don't need to specify the name + [cmd]killtimer[/cmd] + } + } + [comment]# Use isTimer to check if the timer exists[/comment] + [cmd]echo[/cmd] [fnc]$isTimer[/fnc](test) + [comment]# Repeat the command above after the 10th timeout...[/comment] + [/example] + [example] + [comment]# Execute a command at a precise time[/comment] + %secsfrom= $($date("H")*3600+$date("M")*60+$date("S")); #now + %secsto= $(7*3600+10*60+0); #end time: 07:10:00 + %secsdiff=$(%secsto-%secsfrom); #difference + if(%secsdiff <= 0) + { + #we're past that time for today + %secsdiff+=86400; #60 secs * 60 mins * 24 hours + } + # timer wants msecs + %msecs = $(%secsdiff*1000); + timer -s -p (reminder, %msecs) + { + echo "Hey man it's ten past seven am, time to wake up!" + } + [/example] + */ + + KVSCCC(timer) + { + KviKvsVariant * vName = KVSCCC_pParams->first(); + KviKvsVariant * vDelay = KVSCCC_pParams->next(); + + if(!vName || vName->isEmpty()) + { + KVSCCC_pContext->error(__tr2qs_ctx("Missing timer name","kvs")); + return false; + } + + QString szName; + vName->asString(szName); + + if(!vDelay) + { + KVSCCC_pContext->error(__tr2qs_ctx("Missing timeout delay","kvs")); + return false; + } + + kvs_int_t iDelay; + if(!vDelay->asInteger(iDelay)) + { + KVSCCC_pContext->error(__tr2qs_ctx("The timeout delay didn't evaluate to an integer","kvs")); + return false; + } + + KviKvsTimer::Lifetime lt; + + if(KVSCCC_pSwitches->find('s',"single-shot"))lt = KviKvsTimer::SingleShot; + else if(KVSCCC_pSwitches->find('p',"persistent"))lt = KviKvsTimer::Persistent; + else lt = KviKvsTimer::WindowLifetime; + + // prepare the callback parameters + KviKvsVariantList * l = new KviKvsVariantList(); + l->setAutoDelete(true); + + KviKvsVariant * v = KVSCCC_pParams->next(); + while(v) + { + l->append(new KviKvsVariant(*v)); // copy + v = KVSCCC_pParams->next(); + } + + if(!KviKvsTimerManager::instance()->addTimer(szName,lt,KVSCCC_pContext->window(),iDelay,new KviKvsScript(*KVSCCC_pCallback),l)) + { + KVSCCC_pContext->error(__tr2qs_ctx("Unable to add the timer: insufficient system resources","kvs")); + return false; + } + + return true; + } + + + void init() + { + KviKvsKernel * pKern = KviKvsKernel::instance(); + +#define _REGCMD(__cmdName,__routine) \ + { \ + KviKvsCoreCallbackCommandExecRoutine * r = new KviKvsCoreCallbackCommandExecRoutine; \ + r->proc = KVI_PTR2MEMBER(KviKvsCoreCallbackCommands::__routine); \ + pKern->registerCoreCallbackCommandExecRoutine(QString(__cmdName),r); \ + } + + _REGCMD("ahost",ahost); + _REGCMD("awhois",awhois); + _REGCMD("alias",alias); + _REGCMD("button",button); + _REGCMD("event",event); + _REGCMD("exec",exec); + _REGCMD("privateimpl",privateimpl); + _REGCMD("function",alias); + _REGCMD("timer",timer); + +#undef _REGCMD + } +}; diff --git a/src/kvirc/kvs/KviKvsCoreCallbackCommands.h b/src/kvirc/kvs/KviKvsCoreCallbackCommands.h new file mode 100644 index 000000000..039786fab --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreCallbackCommands.h @@ -0,0 +1,74 @@ +#ifndef _KVI_KVS_CORECALLBACKCOMMANDS_H_ +#define _KVI_KVS_CORECALLBACKCOMMANDS_H_ +//============================================================================= +// +// File : KviKvsCoreCallbackCommands.h +// Creation date : Fri 31 Oct 2003 04:07:58 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviKvsRunTimeContext.h" +#include "KviKvsVariantList.h" +#include "KviKvsSwitchList.h" +#include "KviKvsScript.h" +#include "KviKvsParameterProcessor.h" + + +#define KVSCCC(_name) bool _name(KviKvsRunTimeContext * __pContext,KviKvsVariantList * __pParams,KviKvsSwitchList * __pSwitches,const KviKvsScript * __pCallback) + +#define KVSCCC_pContext __pContext +#define KVSCCC_pParams __pParams +#define KVSCCC_pSwitches __pSwitches +#define KVSCCC_pCallback __pCallback + +#define KVSCCC_PARAMETER(a,b,c,d) KVS_PARAMETER(a,b,c,d) + +#define KVSCCC_PARAMETERS_BEGIN \ + KVS_PARAMETERS_BEGIN(parameter_format_list) + +#define KVSCCC_PARAMETERS_END \ + KVS_PARAMETERS_END \ + if(!KviKvsParameterProcessor::process(KVSCCC_pParams,KVSCCC_pContext,parameter_format_list))return false; + +#define KVSCCC_REQUIRE_CONNECTION \ + if(!KVSCCC_pContext->window()->context())return KVSCCC_pContext->errorNoIrcContext(); \ + if(!KVSCCC_pContext->window()->connection())return KVSCCC_pContext->warningNoIrcConnection(); + +#define KVSCCC_pWindow __pContext->window() +#define KVSCCC_pConnection __pContext->window()->connection() +#define KVSCCC_pIrcContext __pContext->context() + + +namespace KviKvsCoreCallbackCommands +{ + KVSCCC(ahost); + KVSCCC(awhois); + KVSCCC(alias); + KVSCCC(button); + KVSCCC(event); + KVSCCC(exec); + KVSCCC(privateimpl); + KVSCCC(timer); + + void init(); +}; + +#endif //!_KVI_KVS_CORECALLBACKCOMMANDS_H_ diff --git a/src/kvirc/kvs/KviKvsCoreFunctions.cpp b/src/kvirc/kvs/KviKvsCoreFunctions.cpp new file mode 100644 index 000000000..7b22fcb0b --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreFunctions.cpp @@ -0,0 +1,167 @@ +//============================================================================= +// +// File : KviKvsCoreFunctions.cpp +// Creation date : Fri 31 Oct 2003 01:52:04 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCoreFunctions.h" +#include "KviKvsKernel.h" +#include "KviKvsObject.h" +#include "KviLocale.h" + +namespace KviKvsCoreFunctions +{ + void init() + { + KviKvsKernel * pKern = KviKvsKernel::instance(); + +#define _REGFNC(__fncName,__routine) \ + { \ + KviKvsCoreFunctionExecRoutine * r = new KviKvsCoreFunctionExecRoutine; \ + r->proc = KVI_PTR2MEMBER(KviKvsCoreFunctions::__routine); \ + pKern->registerCoreFunctionExecRoutine(QString(__fncName),r); \ + } + + // a_f + _REGFNC("active",active) + _REGFNC("aliasBody",aliasBody) + _REGFNC("array",array) + _REGFNC("ascii",unicode) + _REGFNC("asciiToHex",asciiToHex) + _REGFNC("asciiToBase64",asciiToBase64) + _REGFNC("away",away) + _REGFNC("b",b) + _REGFNC("base64ToAscii",base64ToAscii) + _REGFNC("bool",boolean) + _REGFNC("boolean",boolean) + _REGFNC("certificate",certificate) + _REGFNC("channel",channel) + _REGFNC("char",charCKEYWORDWORKAROUND) + _REGFNC("classDefined",classDefined) + _REGFNC("console",console) + _REGFNC("context",context) + _REGFNC("countStatusBarItems",countStatusBarItems) + _REGFNC("cr",cr) + _REGFNC("date",date) + _REGFNC("escape",escape) + _REGFNC("false",falseCKEYWORDWORKAROUND) + _REGFNC("features",features) + _REGFNC("firstConnectedConsole",firstConnectedConsole) + _REGFNC("flatten",flatten) + _REGFNC("fmtlink",fmtlink) + // g_l + _REGFNC("globals",globals); + _REGFNC("hash",hash); +// _REGFNC("inputText",inputText); + _REGFNC("hexToAscii",hexToAscii); + _REGFNC("hostname",hostname); + _REGFNC("hptimestamp",hptimestamp); + _REGFNC("ic",context); + _REGFNC("icon",icon); + _REGFNC("iconName",iconName); + _REGFNC("int",integer) + _REGFNC("integer",integer) + _REGFNC("isEmpty",isEmpty) + _REGFNC("isEventEnabled",isEventEnabled) + _REGFNC("isMainWindowActive",isMainWindowActive) + _REGFNC("isMainWindowMinimized",isMainWindowMinimized) + _REGFNC("isNumeric",isNumeric) + _REGFNC("isSet",isSet) + _REGFNC("isTimer",isTimer) + _REGFNC("isWellKnown",isWellKnown) + _REGFNC("k",k) + _REGFNC("keys",keys) + _REGFNC("lag",lag) + _REGFNC("lang",lang) + _REGFNC("length",length) + _REGFNC("lf",lf) + _REGFNC("link",link) + _REGFNC("listtimers",listtimers) + // m_r + _REGFNC("mask",mask) + _REGFNC("me",me) + _REGFNC("msgtype",msgtype) + _REGFNC("new",newCKEYWORDWORKAROUND) + _REGFNC("nothing",nothing) + _REGFNC("null",nullCKEYWORDWORKAROUND) + _REGFNC("o",o) + _REGFNC("option",option) + _REGFNC("query",query) + _REGFNC("r",r) + _REGFNC("rand",rand) + _REGFNC("real",real) + _REGFNC("realname",realname) + _REGFNC("receivedBytes",receivedBytes) + _REGFNC("rsort",rsort) + // s_z + _REGFNC("selected",selected) + _REGFNC("sentBytes",sentBytes) + _REGFNC("serialize",serialize) + _REGFNC("server",server) + _REGFNC("sort",sort) + _REGFNC("string",string) + _REGFNC("sw",sw) + _REGFNC("target",target) + _REGFNC("this",thisCKEYWORDWORKAROUND) + _REGFNC("tr",tr) + _REGFNC("true",trueCKEYWORDWORKAROUND) + _REGFNC("typeof",typeofCKEYWORDWORKAROUND) + _REGFNC("u",u) + _REGFNC("uflags",uflags) + _REGFNC("unicode",unicode) + _REGFNC("unixtime",unixtime) + _REGFNC("unserialize",unserialize) + _REGFNC("username",username) + _REGFNC("version",version) + _REGFNC("window",window) + _REGFNC("$",thisCKEYWORDWORKAROUND) + _REGFNC("@",strayAt) + _REGFNC("@?",mightBeStrayAtOrThis) +#undef _REGCMD + } + + static QString g_szStaticStrayConstantAt("@"); + + KVSCF(strayAt) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setString(g_szStaticStrayConstantAt); + return true; + } + + KVSCF(mightBeStrayAtOrThis) + { + Q_UNUSED(__pParams); + + KviKvsObject * o = KVSCF_pContext->thisObject(); + if(o) + { + KVSCF_pRetBuffer->setHObject(o->handle()); + } else { + KVSCF_pRetBuffer->setString(g_szStaticStrayConstantAt); + } + return true; + } +}; diff --git a/src/kvirc/kvs/KviKvsCoreFunctions.h b/src/kvirc/kvs/KviKvsCoreFunctions.h new file mode 100644 index 000000000..e452ed2f2 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreFunctions.h @@ -0,0 +1,156 @@ +#ifndef _KVI_KVS_COREFUNCTIONS_H_ +#define _KVI_KVS_COREFUNCTIONS_H_ +//============================================================================= +// +// File : KviKvsCoreFunctions.h +// Creation date : Fri 31 Oct 2003 01:52:04 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "kvi_settings.h" +#include "KviKvsRunTimeContext.h" +#include "KviKvsVariantList.h" +#include "KviKvsVariant.h" +#include "KviKvsParameterProcessor.h" + + +#define KVSCF(_name) bool _name(KviKvsRunTimeContext * __pContext,KviKvsVariantList * __pParams,KviKvsVariant * __pRetBuffer) + +#define KVSCF_pContext __pContext +#define KVSCF_pParams __pParams +#define KVSCF_pRetBuffer __pRetBuffer + +#define KVSCF_PARAMETER(a,b,c,d) KVS_PARAMETER(a,b,c,d) + +#define KVSCF_PARAMETERS_BEGIN \ + KVS_PARAMETERS_BEGIN(parameter_format_list) + +#define KVSCF_PARAMETERS_END \ + KVS_PARAMETERS_END \ + if(!KviKvsParameterProcessor::process(KVSCF_pParams,KVSCF_pContext,parameter_format_list))return false; + + +namespace KviKvsCoreFunctions +{ + // a_f + KVSCF(active); + KVSCF(aliasBody); + KVSCF(array); + KVSCF(asciiToBase64); + KVSCF(asciiToHex); + KVSCF(avatar); + KVSCF(away); + KVSCF(b); + KVSCF(base64ToAscii); + KVSCF(boolean); + KVSCF(certificate); + KVSCF(channel); + KVSCF(charCKEYWORDWORKAROUND); + KVSCF(classDefined); + KVSCF(console); + KVSCF(context); + KVSCF(countStatusBarItems); + KVSCF(cr); + KVSCF(date); + KVSCF(escape); + KVSCF(falseCKEYWORDWORKAROUND); + KVSCF(features); + KVSCF(firstConnectedConsole); + KVSCF(flatten); + KVSCF(fmtlink); + // g_l + KVSCF(globals); + KVSCF(hash); + KVSCF(inputText); + KVSCF(hexToAscii); + KVSCF(hostname); + KVSCF(hptimestamp); + KVSCF(icon); + KVSCF(iconName); + KVSCF(integer); + KVSCF(isAnyConsoleConnected); + KVSCF(isEmpty); + KVSCF(isEventEnabled); + KVSCF(isNumeric); + KVSCF(isMeOp); + KVSCF(isMeUserOp); + KVSCF(isMeHalfOp); + KVSCF(isMeVoice); + KVSCF(isMainWindowActive); + KVSCF(isMainWindowMinimized); + KVSCF(isSet); + KVSCF(isTimer); + KVSCF(isWellKnown); + KVSCF(k); + KVSCF(keys); + KVSCF(lag); + KVSCF(lang); + KVSCF(length); + KVSCF(lf); + KVSCF(link); + KVSCF(listtimers); + // m_r + KVSCF(mask); + KVSCF(me); + KVSCF(msgtype); + KVSCF(newCKEYWORDWORKAROUND); + KVSCF(nothing); + KVSCF(nullCKEYWORDWORKAROUND); + KVSCF(o); + KVSCF(option); + KVSCF(query); + KVSCF(r); + KVSCF(rand); + KVSCF(real); + KVSCF(realname); + KVSCF(receivedBytes); + KVSCF(rsort); + // s_z + KVSCF(selected); + KVSCF(sentBytes); + KVSCF(serialize); + KVSCF(server); + KVSCF(sort); + KVSCF(split); + KVSCF(string); + KVSCF(sw); + KVSCF(target); + KVSCF(thisCKEYWORDWORKAROUND); + KVSCF(timeCFUNCTIONWORKAROUND); + KVSCF(tr); + KVSCF(trueCKEYWORDWORKAROUND); + KVSCF(typeofCKEYWORDWORKAROUND); + KVSCF(u); + KVSCF(uflags); + KVSCF(unicode); + KVSCF(unixtime); + KVSCF(unserialize); + KVSCF(username); + KVSCF(version); + KVSCF(window); + // specials + KVSCF(strayAt); + KVSCF(mightBeStrayAtOrThis); + //bool redirectToModule(const QString &szFrom,const QString &szModName,const QString &szFuncName + + void init(); +}; + +#endif //!_KVI_KVS_COREFUNCTIONS_H_ diff --git a/src/kvirc/kvs/KviKvsCoreFunctions_af.cpp b/src/kvirc/kvs/KviKvsCoreFunctions_af.cpp new file mode 100644 index 000000000..c36aeb373 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreFunctions_af.cpp @@ -0,0 +1,1528 @@ +//============================================================================= +// +// File : KviKvsCoreFunctions_af.cpp +// Creation date : Fri 31 Oct 2003 01:52:04 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// Copyright © 2010 Kai Wasserbäch +// +// 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 opinion) 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 "KviKvsCoreFunctions.h" +#include "KviKvsKernel.h" +#include "KviKvsObjectController.h" +#include "KviLocale.h" +#include "KviApplication.h" +#include "KviChannelWindow.h" +#include "KviConsoleWindow.h" +#include "KviIrcConnection.h" +#include "KviIrcConnectionUserInfo.h" +#include "KviMircCntrl.h" +#include "KviAvatar.h" +#include "KviIrcUserDataBase.h" +#include "KviMainWindow.h" +#include "KviStatusBar.h" +#include "KviQString.h" +#include "KviSSLMaster.h" +#include "KviOptions.h" + +#include "KviKvsAliasManager.h" +#include "KviKvsScript.h" + +// date includes +#include +#include +#include + + +namespace KviKvsCoreFunctions +{ + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: active + @type: + function + @title: + $active + @short: + Retrieves the window ID of the active window + @syntax: + $active[()] + @description: + Returns the [b]window ID[/b] of the active window + bound to the IRC context specified by . + If no window matches the specified IRC context, and invalid + window ID is returned (0).[br] + If no is specified, then + the application active window is returned (the window + that currently has the input focus). Note that in this + case the returned window may also belong to another IRC + context or be not bound to any IRC context at all. + In some extreme cases you may even get a window that + has no output widget and thus has its output redirected. + Using the "global" active window should be used only + for communicating something REALLY urgent (and maybe + unrelated to a specific IRC connection) to the user. + @seealso: + [fnc]$window[/fnc] + */ + + KVSCF(active) + { + kvs_uint_t uContextId; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("context_id",KVS_PT_UINT,KVS_PF_OPTIONAL,uContextId) + KVSCF_PARAMETERS_END + + KviWindow * wnd; + KviConsole * cons; + if(KVSCF_pParams->count() > 0) + { + cons = g_pApp->findConsole(uContextId); + if(cons)wnd = cons->activeWindow(); + else wnd = 0; + } else { + wnd = g_pActiveWindow; + } + + KVSCF_pRetBuffer->setInteger((kvs_int_t)(wnd ? wnd->numericId() : 0)); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: aliasBody + @type: + function + @title: + $aliasBody + @short: + Returns the body of an alias, if it exists + @syntax: + $aliasBody() + @description: + Returns the KVS body of the specified alias. + If the alias doesn't exist it just returns an empty string. + @seealso: + [cmd]alias[/cmd] + */ + + KVSCF(aliasBody) + { + QString szAliasName; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("alias_name",KVS_PT_STRING,0,szAliasName) + KVSCF_PARAMETERS_END + + const KviKvsScript * pAlias = KviKvsAliasManager::instance()->lookup(szAliasName); + if(pAlias) + KVSCF_pRetBuffer->setString(pAlias->code()); + else + KVSCF_pRetBuffer->setString(QString()); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: ascii + @type: + function + @title: + $ascii + @short: + Returns the UNICODE code of a character + @syntax: + $ascii() + @description: + This function has been renamed to $unicode and is present + only for backward compatibility. + @seealso: + [fnc]$cr[/fnc], [fnc]$lf[/fnc], [fnc]$char[/fnc] + */ + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: asciiToBase64 + @type: + function + @title: + $asciiToBase64 + @short: + Returns an encoded base64 string + @syntax: + $asciiToBase64() + @description: + Encodes an ASCII string to its base64 encoded rappresentation + Please note that since KVS is UNICODE based, this function + will first encode the string in UTF8 and then base64-encode. + This means that it is substantially only 7bit safe (ASCII codes below 128). + @examples: + [cmd]echo[/cmd] $asciiToBase64("Hello!") + @seealso: + [fnc]$base64toascii[/fnc] + */ + + KVSCF(asciiToBase64) + { + QString szAscii; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("ascii_string",KVS_PT_STRING,0,szAscii) + KVSCF_PARAMETERS_END + + KviCString tmp1(szAscii); + if(tmp1.len() > 0) + { + KviCString tmp2; + tmp2.bufferToBase64(tmp1.ptr(),tmp1.len()); + KVSCF_pRetBuffer->setString(QString(tmp2.ptr())); + } else { + KVSCF_pRetBuffer->setString(QString()); + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: asciiToHex + @type: + function + @title: + $asciiToHex + @short: + Returns an encoded hex string + @syntax: + $asciiToHex() + @description: + Encodes an ASCII string to its hex encoded rappresentation. + Please note that since KVS is UNICODE based, this function + will first encode the string in UTF8 and then hex-encode. + This means that it is substantially only 7bit safe (ASCII codes below 128). + @examples: + [cmd]echo[/cmd] $asciiToHex("Hello!") + @seealso: + [fnc]$hextoascii[/fnc] + */ + + KVSCF(asciiToHex) + { + QString szAscii; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("ascii_string",KVS_PT_STRING,0,szAscii) + KVSCF_PARAMETERS_END + + KviCString tmp1(szAscii); + if(tmp1.len() > 0) + { + KviCString tmp2; + tmp2.bufferToHex(tmp1.ptr(),tmp1.len()); + KVSCF_pRetBuffer->setString(QString(tmp2.ptr())); + } else { + KVSCF_pRetBuffer->setString(QString()); + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: array + @type: + function + @title: + $array + @short: + Explicitly creates an array + @syntax: + $array(,,,....); + @description: + Returns an array with the specified items. The items are indexed starting from 0. + This is just an explicit way of creating an array with a defined set of items, + useful for increasing readability. + @examples: + [example] + [cmd]alias[/cmd](test) { + [cmd]return[/cmd] $array(1,2,3); + } + %x = $test(); + [cmd]foreach[/cmd](%y,%x) { + [cmd]echo[/cmd] %y; + } + [/example] + @seealso: + [fnc]$hash[/fnc] + */ + + KVSCF(array) + { + Q_UNUSED(__pContext); + + KviKvsArray * a = new KviKvsArray(); + kvs_int_t idx = 0; + + for(KviKvsVariant * v = KVSCF_pParams->first();v;v = KVSCF_pParams->next()) + { + a->set(idx,new KviKvsVariant(*v)); + idx++; + } + + KVSCF_pRetBuffer->setArray(a); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: away + @type: + function + @title: + $away + @short: + Returns true if the current user is away + @syntax: + $away + @description: + Returns true if the current user is away, else false. + If the current IRC context is not connected at all, this function returns false. + */ + + KVSCF(away) + { + kvs_uint_t uCntx; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("irc_context_id",KVS_PT_UINT,KVS_PF_OPTIONAL,uCntx) + KVSCF_PARAMETERS_END + + KviConsole * cns; + + if(KVSCF_pParams->count() > 0) + { + cns = g_pApp->findConsole(uCntx); + if(cns) + { + if(cns->context()->isConnected()) + KVSCF_pRetBuffer->setBoolean(cns->connection()->userInfo()->isAway()); + else + KVSCF_pRetBuffer->setNothing(); + } else { + KVSCF_pRetBuffer->setNothing(); + } + } else { + if(KVSCF_pContext->window()->console()) + { + cns = KVSCF_pContext->window()->console(); + if(cns->context()->isConnected()) + KVSCF_pRetBuffer->setBoolean(cns->connection()->userInfo()->isAway()); + else + KVSCF_pRetBuffer->setNothing(); + } else { + KVSCF_pContext->warning(__tr2qs_ctx("This window has no associated IRC context","kvs")); + KVSCF_pRetBuffer->setNothing(); + } + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: b + @type: + function + @title: + $b + @short: + Returns the BOLD mIRC control character + @syntax: + $b + @description: + Returns the BOLD mIRC control character (CTRL+B).[br] + @seealso: + [fnc]$k[/fnc], [fnc]$u[/fnc] + */ + + KVSCF(b) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setString(QString(QChar(KVI_TEXT_BOLD))); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: base64toAscii + @type: + function + @title: + $base64ToAscii + @short: + Returns a decoded base64 string + @syntax: + $base64ToAscii() + @description: + Decodes a base64 encoded string. + @seealso: + [fnc]$asciiToBase64[/fnc] + */ + + KVSCF(base64ToAscii) + { + QString szBase64; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("base64_encoded_string",KVS_PT_STRING,0,szBase64) + KVSCF_PARAMETERS_END + + KviCString tmp1(szBase64); + char * buf; + int len = tmp1.base64ToBuffer(&buf,true); + QString szRet(buf); + szRet.truncate(len); + KVSCF_pRetBuffer->setString(szRet); + KviCString::freeBuffer(buf); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: boolean + @type: + function + @title: + $boolean + @short: + Casts a variable to a boolean + @syntax: + $boolean() + @description: + Forces to be a boolean data type by first casting + to integer (see [fnc]$int[/fnc]()) and then comparing the result against zero. + A zero integer will result in a false value while a non-zero one + will result in a true value. + This function is similar to the C++ (bool) cast and is internally + aliased to [fnc]$bool[/fnc] too. + Note that since KVIrc does most of the casting work automatically + you shouldn't need to use this function. + @seealso: + [fnc]$real[/fnc] + [fnc]$integer[/fnc] + */ + + /* + @doc: bool + @type: + function + @title: + $bool + @short: + Casts a variable to a boolean + @syntax: + $bool() + @description: + This is an internal alias to [fnc]$boolean[/fnc](). + @seealso: + [fnc]$real[/fnc] + [fnc]$integer[/fnc] + */ + + KVSCF(boolean) + { + KviKvsVariant * v; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,v) + KVSCF_PARAMETERS_END + + kvs_int_t iVal; + v->castToInteger(iVal); + KVSCF_pRetBuffer->setBoolean(iVal); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: certificate + @type: + function + @title: + $certificate + @short: + Returns information about the local certificate + @syntax: + $certificate([,]) + @description: + Returns the requested information about local certificate.[br] + Some queries can accept an optional parameter [br] + Available query strings are:[br] + [ul] + [li]signatureType[/li] + [li]signatureContents[/li] + [li]subjectCountry[/li] + [li]subjectStateOrProvince[/li] + [li]subjectLocality[/li] + [li]subjectOrganization[/li] + [li]subjectOrganizationalUnit[/li] + [li]subjectCommonName[/li] + [li]issuerCountry[/li] + [li]issuerStateOrProvince[/li] + [li]issuerLocality[/li] + [li]issuerOrganization[/li] + [li]issuerOrganizationalUnit[/li] + [li]issuerCommonName[/li] + [li]publicKeyBits[/li] + [li]publicKeyType[/li] + [li]serialNumber[/li] + [li]pemBase64[/li] + [li]version[/li] + [li]fingerprintIsValid[/li] + [li]fingerprintDigestId[/li] + [li]fingerprintDigestStr[/li] + [li]fingerprintContents * accepts parameter interpreted as "digest name"[/li] + [/ul] + @seealso: + [fnc]$str.evpSign[/fnc] + [fnc]$str.evpVerify[/fnc] + [fnc]$dcc.getSSLCertInfo[/fnc] + */ + + KVSCF(certificate) + { + QString szQuery; + QString szParam1; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("query",KVS_PT_STRING,0,szQuery) + KVSCF_PARAMETER("param1",KVS_PT_STRING,KVS_PF_OPTIONAL,szParam1) + KVSCF_PARAMETERS_END + +#ifndef COMPILE_SSL_SUPPORT + KVSCF_pContext->warning(__tr2qs_ctx("This executable was built without SSL support","dcc")); + return true; +#else + KviSSL::globalSSLInit(); + X509 *cert = 0; + + if(!KVI_OPTION_BOOL(KviOption_boolUseSSLCertificate)) + { + KVSCF_pContext->warning(__tr2qs("No public key certificate defined in KVIrc options.")); + KVSCF_pRetBuffer->setString(""); + return true; + } + + FILE * f = fopen(KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data(),"r"); + if(!f) + { + KVSCF_pContext->warning(__tr2qs("File I/O error while trying to use the public key file %s"),KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data()); + KVSCF_pRetBuffer->setString(""); + return true; + } + + QString szPass = KVI_OPTION_STRING(KviOption_stringSSLCertificatePass).toUtf8(); + PEM_read_X509(f, &cert, NULL, szPass.data()); + + fclose(f); + + if(!cert) + { + KVSCF_pContext->warning(__tr2qs("Can't load certificate from public key file %s"),KVI_OPTION_STRING(KviOption_stringSSLCertificatePath).toUtf8().data()); + KVSCF_pRetBuffer->setString(""); + return true; + } + + // KviSSLCertificate takes ownership of the X509 structure, no need to free it + KviSSLCertificate * pCert = new KviSSLCertificate(cert); + + if(!pCert) + { + KVSCF_pContext->warning(__tr2qs_ctx("Error retrieving information from the local certificate","dcc")); + KVSCF_pRetBuffer->setString(""); + return true; + } + + if(KviSSLMaster::getSSLCertInfo(pCert, szQuery, szParam1, KVSCF_pRetBuffer)) + return true; + + KVSCF_pContext->warning(__tr2qs_ctx("Unable to get certificate information: query not recognized","dcc")); + KVSCF_pRetBuffer->setString(""); + return true; +#endif + } + + /* + @doc: channel + @type: + function + @title: + $channel + @short: + Retrieves the window ID of a specified channel + @syntax: + $channel[([,])] + @description: + Returns the [b]window ID[/b] of channel matching the + and bound to the connection specified by + [br] + If no window matches the specified name or connection, an invalid + window ID is returned (0).[br] + If no is specified, this function looks for + the channel in the current connection context (if any).[br] + If no is specified, this function returns the current + channel window ID, if executed in a channel, else 0.[br] + @seealso: + [fnc]$window[/fnc], + [fnc]$query[/fnc], + [fnc]$console[/fnc], + [doc:window_naming_conventions]Window naming conventions[/doc] + */ + + KVSCF(channel) + { + QString szName; + kvs_uint_t uContextId; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("channel_name",KVS_PT_NONEMPTYSTRING,KVS_PF_OPTIONAL,szName) + KVSCF_PARAMETER("context_id",KVS_PT_UINT,KVS_PF_OPTIONAL,uContextId) + KVSCF_PARAMETERS_END + + KviWindow * wnd = 0; + if(KVSCF_pParams->count() > 0) + { + if(KVSCF_pParams->count() > 1) + { + KviConsole * cons = g_pApp->findConsole(uContextId); + if(!cons)KVSCF_pContext->warning(__tr2qs_ctx("No such IRC context (%u)","kvs"),uContextId); + else { + if(cons->connection()) + wnd = cons->connection()->findChannel(szName); + else + wnd = 0; + } + } else { + if(KVSCF_pContext->window()->connection())wnd = KVSCF_pContext->window()->connection()->findChannel(szName); + else { + if(!KVSCF_pContext->window()->console()) + KVSCF_pContext->warning(__tr2qs_ctx("This window is not associated to an IRC context","kvs")); + wnd = 0; + } + } + } else { + if(KVSCF_pContext->window()->type() == KVI_WINDOW_TYPE_CHANNEL)wnd = KVSCF_pContext->window(); + } + + KVSCF_pRetBuffer->setInteger((kvs_int_t)(wnd ? wnd->numericId() : 0)); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: char + @type: + function + @title: + $char + @short: + Returns a character specified by unicode + @syntax: + $char() + @description: + Returns a character corresponding to the UNICODE code .[br] + This function can not return NUL character (UNICODE 0). Basically + you should never need it: if you do, drop me a mail.[br] + If the is not a valid UNICODE code (or is 0), this function returns + an empty string.[br] + @seealso: + [fnc]$cr[/fnc], [fnc]$lf[/fnc], [fnc]$unicode[/fnc] + */ + + KVSCF(charCKEYWORDWORKAROUND) + { + kvs_uint_t ac; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("unicode_value",KVS_PT_UINT,0,ac) + KVSCF_PARAMETERS_END + + if(ac != 0 && ac < 65536) + KVSCF_pRetBuffer->setString(QString(QChar((unsigned short)ac))); + else + KVSCF_pRetBuffer->setString(QString()); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: classdefined + @type: + function + @title: + $classdefined + @short: + Checks if a class is defined + @syntax: + $classdefined() + @description: + Returns 1 if the class is defined, else 0. + */ + + KVSCF(classDefined) + { + // prologue: parameter handling + QString szClassName; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("className",KVS_PT_NONEMPTYSTRING,0,szClassName) + KVSCF_PARAMETERS_END + KVSCF_pRetBuffer->setBoolean(KviKvsKernel::instance()->objectController()->lookupClass(szClassName) != 0); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: console + @type: + function + @title: + $console + @short: + Retrieves the window ID of a specified console + @syntax: + $console[()] + @description: + Returns the [b]window ID[/b] of the console bound + to the IRC context specified by . + If no window matches the specified IRC context, an invalid + window ID is returned (0).[br] + If no is specified, this function looks for + the console in the current IRC context (if any).[br] + @seealso: + [fnc]$window[/fnc], + [fnc]$channel[/fnc], + [fnc]$query[/fnc], + [doc:window_naming_conventions]Window naming conventions[/doc] + */ + + KVSCF(console) + { + kvs_uint_t uContextId; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("context_id",KVS_PT_UINT,KVS_PF_OPTIONAL,uContextId) + KVSCF_PARAMETERS_END + + KviConsole * cons; + if(KVSCF_pParams->count() > 0) + { + cons = g_pApp->findConsole(uContextId); + } else { + cons = KVSCF_pContext->window()->console(); + if(!cons)KVSCF_pContext->warning(__tr2qs_ctx("This window is not associated to an IRC context","kvs")); + } + + KVSCF_pRetBuffer->setInteger((kvs_int_t)(cons ? cons->numericId() : 0)); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: context + @type: + function + @title: + $context + @short: + Retrieves the ID of the specified IRC context + @syntax: + $context[(,)] + @description: + Returns the [b]IRC context ID[/b] of the IRC context that uses + the specified and local user's .[br] This function can + find only connected IRC contexts. + If no context matches the server and nickname, and invalid + [b]IRC context ID[/b] is returned (0).[br] + If is an empty string, the first context that matches + the specified nickname is returned. If is an empty string + the first context that uses the specified server is returned. + If both parameters are missing this function returns the + id of the current IRC context, or '0' if the + window in that this call is executed is not bound to any IRC context. + Please note that in this last case you may find an [b]IRC context[/b] + that is 'not connected'. + This can only happen if the current window is a console that is + in "idle" state, with no connection established yet.[br] + It is a good idea to take a look at the + [doc:window_naming_conventions]window naming conventions[/doc]. + This identifier is equivalent to [fnc]$ic[/fnc].[br] + @seealso: + [fnc]$window.context[/fnc] + */ + + KVSCF(context) + { + QString szServer,szNick; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("server",KVS_PT_STRING,KVS_PF_OPTIONAL,szServer) + KVSCF_PARAMETER("nick",KVS_PT_STRING,KVS_PF_OPTIONAL,szNick) + KVSCF_PARAMETERS_END + + KviConsole * cons; + if(!(szServer.isEmpty() && szNick.isEmpty())) + { + cons = g_pApp->findConsole(szServer,szNick); + } else { + cons = KVSCF_pContext->window()->console(); + } + + KVSCF_pRetBuffer->setInteger(cons ? cons->context()->id() : 0); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: countStatusBarItems + @type: + function + @title: + $countStatusBarItems + @short: + Returns the number of items in the statusbar + @syntax: + $countStatusBarItems + @description: + Returns the number of items in the statusbar + @seealso: + [class]widget class[/class] + */ + + KVSCF(countStatusBarItems) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + if (g_pFrame->mainStatusBar()) + { + QList widgets = g_pFrame->mainStatusBar()->findChildren(); + KVSCF_pRetBuffer->setInteger(widgets.count()); + } + else KVSCF_pRetBuffer->setInteger(0); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: cr + @type: + function + @title: + $cr + @short: + Returns a carriage return character + @syntax: + $cr + @description: + Returns a carriage return character + @seealso: + [fnc]$lf[/fnc], [fnc]$ascii[/fnc], [fnc]$char[/fnc] + */ + + KVSCF(cr) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setString(QString(QChar('\r'))); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: date + @type: + function + @title: + $date + @short: + Returns a date/time string using a specified format + @syntax: + $date([,]) + @description: + Returns the string representation of or + of the current time if is not given, + based on .[br] + The should contain a set of characters + that will be transformed according to the following rules:[br] + [br] + [table] + [tr][td][b]a[/b][/td][td]The abbreviated weekday name according to the current locale.[/td][/tr] + [tr][td][b]A[/b][/td][td]The full weekday name according to the current locale.[/td][/tr] + [tr][td][b]b[/b][/td][td]The abbreviated month name according to the current locale.[/td][/tr] + [tr][td][b]B[/b][/td][td]The full month name according to the current locale.[/td][/tr] + [tr][td][b]c[/b][/td][td]The preferred date and time representation for the current locale.[/td][/tr] + [tr][td][b]C[/b][/td][td]The century number (year/100) as a 2-digit integer. (SU)[/td][/tr] + [tr][td][b]d[/b][/td][td]The day of the month as a decimal number (range 01 to 31).[/td][/tr] + [tr][td][b]D[/b][/td][td]Equivalent to m/d/y.[/td][/tr] + [tr][td][b]e[/b][/td][td]Like d, the day of the month as a decimal number, but a leading + zero is replaced by a space. (SU)[/td][/tr] + [tr][td][b]F[/b][/td][td]Equivalent to Y-m-d (the ISO 8601 date format). (C99)[/td][/tr] + [tr][td][b]h[/b][/td][td]Equivalent to b.[/td][/tr] + [tr][td][b]H[/b][/td][td]The hour as a decimal number using a 24-hour clock (range 00 to 23).[/td][/tr] + [tr][td][b]I[/b][/td][td]The hour as a decimal number using a 12-hour clock (range 01 to 12).[/td][/tr] + [tr][td][b]j[/b][/td][td]The day of the year as a decimal number (range 001 to 366).[/td][/tr] + [tr][td][b]k[/b][/td][td]The hour (24-hour clock) as a decimal number (range 0 to 23); sin- + gle digits are preceded by a blank. (See also H.)[/td][/tr] + [tr][td][b]l[/b][/td][td]The hour (12-hour clock) as a decimal number (range 1 to 12); sin- + gle digits are preceded by a blank. (See also I.)[/td][/tr] + [tr][td][b]m[/b][/td][td]The month as a decimal number (range 01 to 12).[/td][/tr] + [tr][td][b]M[/b][/td][td]The minute as a decimal number (range 00 to 59).[/td][/tr] + [tr][td][b]n[/b][/td][td]A newline character. (SU)[/td][/tr] + [tr][td][b]p[/b][/td][td]Either `AM' or `PM' according to the given time value, or the cor- + responding strings for the current locale. Noon is treated as `pm' and midnight as `am'.[/td][/tr] + [tr][td][b]r[/b][/td][td]The time in a.m. or p.m. notation. In the POSIX locale this is + equivalent to `I:M:S p'.[/td][/tr] + [tr][td][b]s[/b][/td][td]The number of seconds since the Epoch, i.e., since 1970-01-01 + 00:00:00 UTC.[/td][/tr] + [tr][td][b]S[/b][/td][td]The second as a decimal number (range 00 to 60). (The range is up + to 60 to allow for occasional leap seconds.)[/td][/tr] + [tr][td][b]t[/b][/td][td]A tab character.[/td][/tr] + [tr][td][b]T[/b][/td][td]The time in 24-hour notation (H:M:S). (SU)[/td][/tr] + [tr][td][b]u[/b][/td][td]The day of the week as a decimal, range 1 to 7, Monday being 1. + See also w.[/td][/tr] + [tr][td][b]V[/b][/td][td]The ISO 8601:1988 week number of the current year as a decimal num- + ber, range 01 to 53, where week 1 is the first week that has at + least 4 days in the current year, and with Monday as the first day + of the week. See also U and W.[/td][/tr] + [tr][td][b]w[/b][/td][td]The day of the week as a decimal, range 0 to 6, Sunday being 0.[/td][/tr] + [tr][td][b]W[/b][/td][td]The week number of the current year as a decimal number, range 00 + to 53, starting with the first Monday as the first day of week 01.[/td][/tr] + [tr][td][b]y[/b][/td][td]The year as a decimal number without a century (range 00 to 99).[/td][/tr] + [tr][td][b]Y[/b][/td][td]The year as a decimal number including the century.[/td][/tr] + [tr][td][b]z[/b][/td][td]The time-zone as hour offset from GMT. Required to emit + RFC822-conformant dates (using "a, d b Y H:M:S z").[/td][/tr] + [tr][td][b]Z[/b][/td][td]The time zone or name or abbreviation (not implemented yet).[/td][/tr] + [/table] + @examples: + [example] + [cmd]echo[/cmd] $date("d/m/Y H:M:S") + [/example] + @seealso: + [fnc]$unixtime[/fnc], [fnc]$hptimestamp[/fnc] + @author: + Kai Wasserbäch + */ + + KVSCF(date) + { + QString szFormat; + kvs_int_t iTime; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("format",KVS_PT_NONEMPTYSTRING,0,szFormat) + KVSCF_PARAMETER("unixtime",KVS_PT_INT,KVS_PF_OPTIONAL,iTime) + KVSCF_PARAMETERS_END + + // strftime() is not sufficient, as shown by #769, the following is + // derived from KDateTime (not a copy, but the structure is similar, + // which isn't surprising), but limited/extended to the required set of + // functionality. + // The reason for this is platform independency. + QDateTime qDt; + QString szFmtTime; + int iLength, iVal, iTemp, iLocalTzH, iLocalTzM, iUtcH, iUtcM, iTzOffset; + int iTzOffsetH, iTzOffsetM; + QChar cDiv; + + if(KVSCF_pParams->count() > 1) + qDt.setTime_t(iTime); + else + qDt = QDateTime::currentDateTime(); + + if(!qDt.isValid()) + { + KVSCF_pContext->warning(__tr2qs_ctx("Couldn't construct QDateTime object.","kvs")); + goto leavenow; + } + + for(int i = 0; i < szFormat.size(); i++) + { + ushort ch = szFormat.at(i).unicode(); + iLength = 2; + iVal = 0x8000000; + cDiv = ' '; + + switch(ch) + { + // FIXME: G, g, U, x, X, Z not implemented yet. + // + // E and O probably never will be implemented. + case 'a': // the abbreviated localized day name (e.g. + // 'Mon' to 'Sun'). Uses + // QDate::shortDayName(). + szFmtTime += qDt.toString("ddd"); + break; + case 'A': // the long localized day name (e.g. + // 'Monday' to 'Qt::Sunday'). Uses + // QDate::longDayName(). + szFmtTime += qDt.toString("dddd"); + break; + case 'b': // the abbreviated localized month name + case 'h': // (e.g. 'Jan' to 'Dec'). Uses + // QDate::shortMonthName(). + szFmtTime += qDt.toString("MMM"); + break; + case 'B': // the long localized month name (e.g. + // 'January' to 'December'). Uses + // QDate::longMonthName(). + szFmtTime += qDt.toString("MMMM"); + break; + case 'c': // If the format is Qt::TextDate, the string + // is formatted in the default way. + szFmtTime += qDt.toString(Qt::TextDate); + break; + case 'C': // 2-digit "century" (yyyy/100) + iVal = qDt.date().year() / 100; + break; + case 'd': // the day as number with a leading zero + // (01 to 31) + cDiv = '0'; + // break omitted on purpose, NEXT MUST BE 'e' + case 'e': // 2-character wide day representation, + // space padded + iVal = qDt.date().day(); + break; + case 'D': // American formatting + szFmtTime += qDt.toString("MM/dd/yy"); + break; + case 'F': // yyyy-MM-dd (ISO 8601) + szFmtTime += qDt.date().toString(Qt::ISODate); + break; + case 'H': // the hour with a leading zero (00 to 23) + cDiv = '0'; + // no break; on purpose (NEXT MUST BE case 'k') + case 'k': // same as H, only that single-character values + // are prefixed with a space + iVal = qDt.time().hour(); + break; + case 'I': // hour, 01 - 12 + cDiv = '0'; + // fall through to 'l' + case 'l': // hour, 1 - 12 + iVal = (qDt.time().hour() + 11) % 12 + 1; + break; + case 'j': // day of the year (001 to 365/366) + iVal = qDt.date().dayOfYear(); + iLength = 3; + cDiv = '0'; + break; + case 'M': // minutes (00 to 59) + szFmtTime += qDt.toString("mm"); + break; + case 'm': // month (01-12) + szFmtTime += qDt.toString("MM"); + break; + case 'n': // newline + szFmtTime += "\n"; + break; + case 'p': // AM/PM + // FIXME: l10n for the am/pm? Maybe we can + // draw it from a different source? + // Qt doesn't offer l10n strings + // for this. + if(qDt.time().hour() < 12) + szFmtTime += "AM"; + else + szFmtTime += "PM"; + break; + case 'P': // am/pm, the same FIXME as for p applies. + if(qDt.time().hour() < 12) + szFmtTime += "am"; + else + szFmtTime += "pm"; + break; + case 'r': // "I:M:S p" + szFmtTime += qDt.toString("hh:mm:ss AP"); + break; + case 'R': // "H:M" + szFmtTime += qDt.toString("hh:mm"); + break; + case 's': // seconds since epoch (currently 1970-01-01 00:00:00 UTC) + szFmtTime += QString::number(qDt.toTime_t()); + break; + case 'S': // seconds (00-60) + cDiv = '0'; + iVal = qDt.time().second(); + break; + case 't': // Tab + szFmtTime += "\t"; + break; + case 'T': // H:M:S + szFmtTime += qDt.toString("hh:mm:ss"); + break; + case 'u': // day of the week (1-7) + iVal = qDt.date().dayOfWeek(); + iLength = 1; + break; + case 'V': // week of the year (ISO 8601) + case 'W': // W is not entirely correct, but that's a + // lot easier this way. + iVal = qDt.date().weekNumber(); + cDiv = '0'; + break; + case 'w': // day of week (0-6, 0==Sunday) + iTemp = qDt.date().dayOfWeek(); + if(iTemp == Qt::Sunday) + iTemp = 0; + szFmtTime += QString::number(iTemp); + break; + case 'y': // year (2-character) + szFmtTime += qDt.toString("yy"); + break; + case 'Y': // year (4-character) + szFmtTime += qDt.toString("yyyy"); + break; + case 'z': // numerical timezone offset + iLocalTzH = qDt.time().hour(); + iLocalTzM = qDt.time().minute(); + iUtcH = qDt.toUTC().time().hour(); + iUtcM = qDt.toUTC().time().minute(); + iTzOffsetH = iLocalTzH - iUtcH; + iTzOffsetM = iLocalTzM - iUtcM; + iTzOffset = iTzOffsetH * 100 + iTzOffsetM; + + //clamp to -12:00 / +12:00 (ticket #924) + if(iTzOffset < 1200) + iTzOffset+= 2400; + + if(iTzOffset > 1200) + iTzOffset-= 2400; + + if(iTzOffset > 0) + szFmtTime += "+"; + + szFmtTime += QString("%1").arg(iTzOffset, 4, 10, QChar('0')); + break; + // FIXME + // The abbrev. time zone name is a little bit trickier, + // as I don't want to reimplement KTimeZone, but can't + // use KTimeZone. I'll need to do some research on this. + //case 'Z': // TZ abbrev. + // szFmtTime += + default: + szFmtTime += szFormat.at(i); + } + + if(iVal != 0x8000000) + { + if(iVal < 0) + { + iVal = -iVal; + szFmtTime += "-"; + } + szFmtTime += QString("%1").arg(iVal, iLength, 10, cDiv); + } + } + + KVSCF_pRetBuffer->setString(szFmtTime); + + leavenow: + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: escape + @type: + function + @title: + $escape + @short: + Returns a kvs-escaped version of the string + @syntax: + $escape() + @description: + In KVS some characters in a string have special meanings: % marks the start of a variable name, $ the start of a function name, etc..[br] + Sometimes you could need to escape them using a \ character to avoid kvirc from interpreting the special meaning of these characters: + this function will to the dirty job for you, returning a correctly kvs-escaped version of the string passed as a parameter.[br] + @seealso: + [cmd]eval[/cmd] + */ + + KVSCF(escape) + { + QString szData; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("text",KVS_PT_NONEMPTYSTRING,0,szData) + KVSCF_PARAMETERS_END + + KviQString::escapeKvs(&szData); + + KVSCF_pRetBuffer->setString(szData); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: false + @type: + function + @title: + $false + @short: + The boolean false constant + @syntax: + $false + @description: + Evaluates to the false boolean constant. False + is equivalent to the integer 0 too. This function/constant + is useful to keep your code readable: when you + have a variable that can assume boolean values it's + nicer to use [fnc]$true[/fnc] and $false instead of + the integer constants 1 and 0. The reader will + undestand immediately that the variable simply can't + assume any other value. + @examples: + [example] + %a = $false + [cmd]echo[/cmd] $typeof(%a) + [cmd]echo[/cmd] $(%a + 1) + [/example] + @seealso: + [fnc]$true[/fnc] + */ + + KVSCF(falseCKEYWORDWORKAROUND) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setBoolean(false); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: features + @type: + function + @title: + $features + @short: + Returns the features that KVIrc supports + @syntax: + $features() + $features() + @description: + The parameterless form returns an array of feature descripton strings that this KVIrc executable supports.[br] + This function is useful when some part of your script depends on + an optional KVIrc feature (like SSL support or IPV6 support).[br] + The returned value may be assigned to a dictionary too: it will be used to simulate an array.[br] + The form with the [test_feature] parameter returns true if and only if [test_feature] is available.[br] + @examples: + [example] + %myfeats[] = $features + [cmd]echo[/cmd] %myfeats[] + %i = %myfeats[]# + [cmd]while[/cmd](%i > 0) + { + [cmd]echo[/cmd] "Supporting feature %myfeats[%i]" + %i--; + } + [/example] + Nearly the same loop, just really shorter: + [example] + [cmd]foreach[/cmd](%f,$features) + [cmd]echo[/cmd] "Supporting feature %myfeats[%i]" + [/example] + You can test for a specific feature in the following way: + [example] + [cmd]if[/cmd]($features("SSL"))[cmd]echo[/cmd] "Yes! SSL is available"; + [/example] + If used in "non-array" context it returns just a comma separated list of entries:[br] + [example] + [cmd]echo[/cmd] $features + [/example] + @seealso: + [fnc]$version[/fnc] + */ + + KVSCF(features) + { + QString szFeature; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("test_feature",KVS_PT_STRING,KVS_PF_OPTIONAL,szFeature) + KVSCF_PARAMETERS_END + + static const char * feature_array[]= + { + "IRC", + #ifdef COMPILE_IPV6_SUPPORT + "IPv6", + #endif + #ifdef COMPILE_CRYPT_SUPPORT + "Crypt", + #endif + #ifdef COMPILE_SSL_SUPPORT + "SSL", + #endif + #ifdef COMPILE_GET_INTERFACE_ADDRESS + "IfAddr", + #endif + #ifndef COMPILE_NO_IPC + "IPC", + #endif + #ifdef COMPILE_KDE_SUPPORT + "KDE", + #endif + #ifdef COMPILE_OSS_SUPPORT + "OSS", + #endif + #ifdef COMPILE_ARTS_SUPPORT + "ARTS", + #endif + #ifdef COMPILE_ESD_SUPPORT + "ESD", + #endif + #ifdef COMPILE_AUDIOFILE_SUPPORT + "Audiofile", + #endif + #ifdef COMPILE_PSEUDO_TRANSPARENCY + "Transparency", + #endif + #ifdef COMPILE_ix86_ASM + "ix86-ASM", + #endif + #ifdef COMPILE_SCRIPTTOOLBAR + "ScriptToolBar", + #endif // COMPILE_SCRIPTTOOLBAR + #ifdef COMPILE_PHONON_SUPPORT + "Phonon", + #endif + #ifdef COMPILE_WEBKIT_SUPPORT + "Webkit", + #endif + #ifndef COMPILE_DISABLE_DCC_VIDEO + "DCCVideo", + #endif + #ifndef COMPILE_DISABLE_DCC_VOICE + "DCCVoice", + #endif + #ifdef COMPILE_DCC_CANVAS + "DCCCanvas", + #endif + #ifdef COMPILE_PERL_SUPPORT + "Perl", + #endif + #ifdef COMPILE_PYTHON_SUPPORT + "Python", + #endif + "Qt4", + "KVS", + 0 + }; + + if(!szFeature.isEmpty()) + { + for(int i=0;feature_array[i];i++) + { + if(KviQString::equalCI(feature_array[i],szFeature)) + { + KVSCF_pRetBuffer->setBoolean(true); + return true; + } + } + KVSCF_pRetBuffer->setBoolean(false); + } else { + KviKvsArray * a = new KviKvsArray(); + for(int i=0;feature_array[i];i++)a->set(i,new KviKvsVariant(QString(feature_array[i]))); + KVSCF_pRetBuffer->setArray(a); + } + + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: firstconnectedconsole + @type: + function + @title: + $firstConnectedConsole + @short: + Returns the window id of the first connected console + @syntax: + $firstConnectedConsole() + @description: + Returns the window id of the first connected console + or 0 if no console is actually connected. + */ + + KVSCF(firstConnectedConsole) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KviConsole * c = g_pApp->topmostConnectedConsole(); + // FIXME: The window id's should be numeric!!! + KVSCF_pRetBuffer->setString(c ? c->id() : "0"); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: flatten + @type: + function + @title: + $flatten + @short: + Returns a flattened array of items + @syntax: + $flatten([,[,...]]) + @description: + Returns an array of items built from the passed arguments + with the following rules:[br] + [ul] + [li]If an argument is a scalar value then the argument itself + is appended to the result.[/li] + [li]If an argument is an array then each contained item + is appended to the result.[/li] + [li]If an argument is a hash then each contained value + is appended to the result.[/li] + [/ul] + A simple example of usage is to merge N arrays into a new one. + (Please note that for merging one array into another the + [doc:arrayconcatenation]<+ operator[/doc] is more efficient). + */ + + KVSCF(flatten) + { + Q_UNUSED(__pContext); + + KviKvsArray * a = new KviKvsArray(); + KVSCF_pRetBuffer->setArray(a); + unsigned int uIdx = 0; + for(KviKvsVariant * v = KVSCF_pParams->first();v;v = KVSCF_pParams->next()) + { + switch(v->type()) + { + case KviKvsVariantData::Array: + { + KviKvsArray * z = v->array(); + unsigned int uSize = z->size(); + unsigned int uIdx2 = 0; + while(uIdx2 < uSize) + { + KviKvsVariant * pInternal = z->at(uIdx2); + if(pInternal) + a->set(uIdx,new KviKvsVariant(*pInternal)); + // else + // don't set anything: just leave empty entry (nothing) + uIdx++; + uIdx2++; + } + } + break; + case KviKvsVariantData::Hash: + { + KviKvsHash * h = v->hash(); + KviKvsHashIterator it(*(h->dict())); + while(KviKvsVariant * pInternal = it.current()) + { + a->set(uIdx,new KviKvsVariant(*pInternal)); + uIdx++; + ++it; + } + } + break; + default: + a->set(uIdx,new KviKvsVariant(*v)); + uIdx++; + break; + } + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: fmtlink + @type: + function + @title: + $fmtlink + @short: + Returns a formatted link buffer + @syntax: + $fmtlink(,[,]) + @description: + Returns a link formatted for the [cmd]echo[/cmd] command.[br] + If you pass the returned string to the echo command, the string will be displayed + as a link and will be highlighted when the user moves the mouse over it.[br] + If the user will leave the mouse for a few seconds over the link, the + will be displayed in a small tooltip window. If is not given, + then no tooltip will be shown.[br] + The will be executed when the user will double click on the link.[br] + Please remember that if contains identifiers + that must be evaluated at double-click time, you MUST escape them in the $fmtlink() call + to prevent the evaluation.[br] + You might also take a look at [doc:escape_sequences]the escape sequences documentation[/doc] + to learn more about how the links are implemented and how to create more powerful links (add + right and middle button actions, use predefined kvirc links etc...). Also take a look at [fnc]$link[/fnc] + which has related functionality. + @seealso: + [cmd]echo[/cmd], [doc:escape_sequences]the escape sequences documentation[/doc], [fnc]$link[/fnc] + */ + + KVSCF(fmtlink) + { + QString szLinkText,szCmd,szToolTip; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("link_text",KVS_PT_NONEMPTYSTRING,0,szLinkText) + KVSCF_PARAMETER("double_click_command",KVS_PT_STRING,0,szCmd) + KVSCF_PARAMETER("tooltip_text",KVS_PT_STRING,KVS_PF_OPTIONAL,szToolTip) + KVSCF_PARAMETERS_END + + QString szPart; + KviQString::sprintf(szPart,"[!dbl]%Q",&szCmd); + if(!szToolTip.isEmpty())KviQString::appendFormatted(szPart,"[!txt]%Q",&szToolTip); + QString szLink; + KviQString::sprintf(szLink,"\r!%Q\r%Q\r",&szPart,&szLinkText); + + KVSCF_pRetBuffer->setString(szLink); + return true; + } +}; diff --git a/src/kvirc/kvs/KviKvsCoreFunctions_gl.cpp b/src/kvirc/kvs/KviKvsCoreFunctions_gl.cpp new file mode 100644 index 000000000..85cbb4174 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreFunctions_gl.cpp @@ -0,0 +1,1050 @@ +//============================================================================= +// +// File : KviKvsCoreFunctions_gl.cpp +// Creation date : Fri 31 Oct 2003 01:52:04 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCoreFunctions.h" +#include "KviKvsKernel.h" +#include "KviKvsTimerManager.h" +#include "KviKvsArrayCast.h" +#include "KviLocale.h" +#include "KviInput.h" +#include "KviApplication.h" +#include "KviChannelWindow.h" +#include "KviConsoleWindow.h" +#include "KviIconManager.h" +#include "KviMircCntrl.h" +#include "KviMainWindow.h" +#include "KviTimeUtils.h" +#include "KviKvsEventManager.h" +#include "KviKvsEventHandler.h" +#include "KviLagMeter.h" + +#include + +namespace KviKvsCoreFunctions +{ + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: globals + @type: + function + @title: + $globals + @short: + Dump globals variables + @syntax: + $globals() + @description: + Returns an hashtable of all global variables set. + @examples: + echo $globals() + @seealso: + [cmd]global[/cmd] + [fnc]$hash[/fnc] + */ + + KVSCF(globals) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setHash(new KviKvsHash( *(KviKvsKernel::instance()->globalVariables()) )); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: hash + @type: + function + @title: + $hash + @short: + Explicitly creates a hash + @syntax: + $hash([,,[,]],...) + @description: + Returns a hash with the specified items. Each is indexed by the preceeding . + This is just an explicit way of creating a hash with a defined set of items, + useful for increasing readability. + @examples: + [example] + [cmd]alias[/cmd](test){ [cmd]return[/cmd] $hash(1,X,2,Y,3,Z); }; + %x = $test(); + [cmd]foreach[/cmd](%y,%x) + { + [cmd]echo[/cmd] %y; + } + [cmd]foreach[/cmd](%y,[fnc]$keys[/fnc](%x)) + { + [cmd]echo[/cmd] %y + } + [/example] + @seealso: + [fnc]$array[/fnc] + */ + + KVSCF(hash) + { + Q_UNUSED(__pContext); + + KviKvsHash * a = new KviKvsHash(); + + for(KviKvsVariant * key = KVSCF_pParams->first();key;key = KVSCF_pParams->next()) + { + KviKvsVariant * val = KVSCF_pParams->next(); + if(!val)break; + QString sz; + key->asString(sz); + a->set(sz,new KviKvsVariant(*val)); + } + + KVSCF_pRetBuffer->setHash(a); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: hextoAscii + @type: + function + @title: + $hexToAscii + @short: + Returns a decoded hex string + @syntax: + $hexToAscii() + @description: + Decodes the to its ASCII representation. + @examples: + [example] + [cmd]echo[/cmd] $hexToAscii(6B76697263) + [/example] + @seealso: + [fnc]$asciiToHex[/fnc] + */ + + KVSCF(hexToAscii) + { + QString szHex; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("hex_encoded_string",KVS_PT_STRING,0,szHex) + KVSCF_PARAMETERS_END + + KviCString tmp1(szHex); + char * buf; + int len = tmp1.hexToBuffer(&buf,true); + KVSCF_pRetBuffer->setString(QString(QByteArray(buf,len))); + KviCString::freeBuffer(buf); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: hostname + @type: + function + @title: + $hostname + @short: + Returns the hostname of the specified user + @syntax: + $hostname() + @description: + Returns the hostname of the specified IRC user IF it is known.[br] + The hostname is known if [fnc]$isWellKnown[/fnc] returns 1.[br] + The hostname is generally known if the user is on a channel with you + or has an open query with you.[br] + Detailed explaination:[br] + KVIrc has an internal database of users that are currently + visible by *this client*: this includes users on open channels + and queries.[br] The other IRC users are NOT in the database: + this means that KVIrc knows NOTHING about them and can't return + any information immediately. In this case this function will return + an EMPTY string.[br] + If a user is in the database, at least his nickname is known.[br] + The username and hostname are known only if the server provides that information + spontaneously or after a KVIrc request.[br] + KVIrc requests user information for all the users in open queries + and channels. This information takes some time to be retrieved, + in this interval of time KVIrc knows only the user's nickname. + This function will return the string "*" in this case.[br] + @seealso: + [fnc]$isWellKnown[/fnc], [fnc]$username[/fnc], [cmd]awhois[/cmd] + */ + + KVSCF(hostname) + { + QString szNick; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("nick",KVS_PT_NONEMPTYSTRING,0,szNick) + KVSCF_PARAMETERS_END + + if( + KVSCF_pContext->window()->console() && + KVSCF_pContext->window()->console()->isConnected()) + { + KviIrcUserEntry * e = KVSCF_pContext->window()->connection()->userDataBase()->find(szNick); + if(e) + { + KVSCF_pRetBuffer->setString(e->host()); + return true; + } + } + + KVSCF_pRetBuffer->setNothing(); + return true; + } + + //------------------------------------------------- + /* + @doc: lag + @type: + function + @title: + $lag + @short: + Returns the lag on the current server + @syntax: + lag + @description: + This function returns the lag in the current server, in milliseconds.[br] + */ + + KVSCF(lag) + { + Q_UNUSED(__pParams); + + if(!KVSCF_pContext->window()->console()) return KVSCF_pContext->errorNoIrcContext(); + if(!KVSCF_pContext->window()->console()->connection()) return KVSCF_pContext->warningNoIrcConnection(); + if(!KVSCF_pContext->window()->console()->connection()->lagMeter()) + { + KVSCF_pContext->warning(__tr2qs_ctx("Lag meter was not enabled","kvs")); + return false; + } + + KVSCF_pRetBuffer->setInteger( KVSCF_pContext->window()->console()->connection()->lagMeter()->lag()); + return true; + } + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: hptimestamp + @type: + function + @title: + $hptimestamp + @short: + Returns a high precision timestamp + @syntax: + $hptimestamp + @description: + Returns a high precision timestamp as a floaint point value. + The timestamp rappresent the number of seconds elapsed since + a certain moment in the past. The number of seconds + contains a "high precision" fractional part. The "certain moment" definition + depends on the platform KVIrc is executed. This means that + this timestamp is totally useless to rappresent a time value + but is useful to compute time intervals with sub-second precision. + @examples: + [example] + %tmp = $hptimestamp + [cmd]echo[/cmd] $($hptimestamp - %tmp) + [/example] + @seealso: + [fnc]$unixTime[/fnc], [fnc]$date[/fnc] + */ + + KVSCF(hptimestamp) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + struct timeval tv; + kvi_gettimeofday(&tv,0); + kvs_real_t dTimestamp = (kvs_real_t)(tv.tv_sec); + dTimestamp += (((kvs_real_t)(tv.tv_usec)) / 1000000.0); + KVSCF_pRetBuffer->setReal(dTimestamp); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: icon + @type: + function + @title: + $icon + @short: + Returns the ID of an icon + @syntax: + $icon() + @description: + Returns the ID of the icon . + You should always use this function where an is required + and you want to use an internal icon. + See [fnc]$iconname[/fnc] for a list of the icon names supported by kvirc.[br] + @examples: + [example] + [cmd]echo[/cmd] $icon(linux) + [/example] + @seealso: + [fnc]$iconName[/fnc] + */ + + KVSCF(icon) + { + QString szName; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("iconName",KVS_PT_NONEMPTYSTRING,0,szName) + KVSCF_PARAMETERS_END + + KVSCF_pRetBuffer->setInteger(g_pIconManager->getSmallIconIdFromName(szName)); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: iconname + @type: + function + @title: + $iconname + @short: + Returns the name of an icon + @syntax: + $iconname() + @description: + Returns the name of a builtin icon given an . + The is returned by the function [fnc]$icon[/fnc]. + If the is not valid, an empty name is returned.[br] + The following code will list all the available icon names:[br] + [example] + %i = 0 + [cmd]do[/cmd] { + %name = $iconname(%i) + echo The icon by ID %i is named %name + %i++ + } [cmd]while[/cmd](%name != "") + [/example] + @examples: + [example] + [cmd]echo[/cmd] $iconname(24) + [cmd]echo[/cmd] $iconname([fnc]$icon[/fnc](linux)) + [/example] + @seealso: + [fnc]$iconName[/fnc] + */ + + KVSCF(iconName) + { + kvs_uint_t uIco; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("iconid",KVS_PT_UINT,0,uIco) + KVSCF_PARAMETERS_END + + if(uIco < KVI_NUM_SMALL_ICONS) + { + KVSCF_pRetBuffer->setString(g_pIconManager->getSmallIconName(uIco)); + } else { + KVSCF_pRetBuffer->setNothing(); + } + return true; + } + + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: integer + @type: + function + @title: + $integer + @short: + Casts a variable to an integer + @syntax: + $integer() + @description: + Forces to be an integer data type with the following + semantics:[br] + [ul] + [li]If is an integer, itself is returned.[/li] + [li]If is a boolean, its numeric value is returned (either 1 or 0).[/li] + [li]If is a real, its integer part is returned.[/li] + [li]If is an array, the count of its items is returned.[/li] + [li]If is a hash, the count of its items is returned.[/li] + [li]If is a string, its length is returned.[/li] + [li]If is an object, 0 is returned if the reference is null (invalid) and 1 otherwise[/li] + [/ul] + This function is similar to the C (int) cast and is internally + aliased to [fnc]$int[/fnc]() too. + Note that since KVIrc does most of the casting work automatically + you shouldn't need to use this function. + @seealso: + [fnc]$real[/fnc] + [fnc]$boolean[/fnc] + */ + + /* + @doc: int + @type: + function + @title: + $int + @short: + Casts a variable to an integer + @syntax: + $int() + @description: + This is an internal alias to [fnc]$integer[/fnc](). + @seealso: + [fnc]$real[/fnc] + [fnc]$boolean[/fnc] + */ + + KVSCF(integer) + { + KviKvsVariant * v; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,v) + KVSCF_PARAMETERS_END + + kvs_int_t iVal; + v->castToInteger(iVal); + KVSCF_pRetBuffer->setInteger(iVal); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: isMainWindowActive + @type: + function + @title: + $isMainWindowActive + @short: + Checks if main KVirc window is active + @syntax: + $isMainWindowActive() + @description: + Returns true if the KVIrc's window is currently + the active window on the current desktop. + */ + + KVSCF(isMainWindowActive) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setBoolean(g_pFrame->isActiveWindow()); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: isMainWindowMinimized + @type: + function + @title: + $isMainWindowMinimized + @short: + Checks if main KVirc window is minimized + @syntax: + $isMainWindowMinimized() + @description: + Returns true if main KVirc window is minimized and false otherwise. + */ + + KVSCF(isMainWindowMinimized) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setBoolean(g_pFrame->isMinimized()); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: isempty + @type: + function + @title: + $isEmpty + @short: + Checks if a variable is set (empty or non empty) + @syntax: + $isEmpty() + @description: + Returns 0 if is actually set to some non-empty value + and 1 otherwise. Since KVIrc treats unset variables as empty + ones then this function is the exact opposite of [fnc]$isSet[/fnc]. + @seealso: + [fnc]$isSet[/fnc] + */ + + KVSCF(isEmpty) + { + KviKvsVariant * v; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,v) + KVSCF_PARAMETERS_END + + KVSCF_pRetBuffer->setBoolean(v->isEmpty()); + return true; + } + //FIXME: documentation + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: iseventenabled + @type: + function + @title: + $isEventEnabled + @short: + Checks if an event enabled + @syntax: + $isEventEnabled(,) + @description: + Returns 1 if the event handler enabled + */ + + /////////////////////////////////////////////////////////////////////////////////////////////// + + KVSCF(isEventEnabled) + { + QString szEventName,szHandlerName; + KviKvsScriptEventHandler *h=0; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("event_name",KVS_PT_NONEMPTYSTRING,0,szEventName) + KVSCF_PARAMETER("handler_name",KVS_PT_NONEMPTYSTRING,0,szHandlerName) + KVSCF_PARAMETERS_END + + bool bOk; + int iNumber = szEventName.toInt(&bOk); + bool bIsRaw = (bOk && (iNumber >= 0) && (iNumber < 1000)); + + if(bIsRaw) + { + if(!KviKvsEventManager::instance()->isValidRawEvent(iNumber)) + { + KVSCF_pContext->warning(__tr2qs_ctx("No such event (%Q)","kvs"),&szEventName); + } else { + h=KviKvsEventManager::instance()->findScriptRawHandler(iNumber,szHandlerName); + } + } else { + iNumber = KviKvsEventManager::instance()->findAppEventIndexByName(szEventName); + if(!KviKvsEventManager::instance()->isValidAppEvent(iNumber)) + { + KVSCF_pContext->warning(__tr2qs_ctx("No such event (%Q)","kvs"),&szEventName); + } else { + h=KviKvsEventManager::instance()->findScriptAppHandler(iNumber,szHandlerName); + } + } + if(h) + KVSCF_pRetBuffer->setBoolean(h->isEnabled()); + else + KVSCF_pContext->warning(__tr2qs_ctx("No such event handler (%Q) for event %Q","kvs"),&szHandlerName,&szEventName); + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: isnumeric + @type: + function + @title: + $isNumeric + @syntax: + $isNumeric() + @short: + Finds whether a variable contains a rappresentation of a number + @description: + Returns 1 if the is an integer or a real number, 0 otherwise. + */ + + KVSCF(isNumeric) + { + KviKvsVariant * v; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,v) + KVSCF_PARAMETERS_END + + KviKvsNumber n; + KVSCF_pRetBuffer->setBoolean(v->asNumber(n)); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: isset + @type: + function + @title: + $isSet + @short: + Checks if a variable is set (non-empty) + @syntax: + $isSet() + @description: + Returns 1 if is actually set to some non-empty value + and 0 otherwise. If is a variable, then this function + simply checks if the variable is set. If is a constant + then this function checks if the constant is non empty. + Since KVIrc treats empty strings as "unset" values then + this function could be also called "isNonEmpty" and it is + the perfect opposite of [fnc]$isEmpty[/fnc] + @seealso: + [fnc]$isEmpty[/fnc], [cmd]unset[/cmd] + */ + + KVSCF(isSet) + { + KviKvsVariant * v; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,v) + KVSCF_PARAMETERS_END + + KVSCF_pRetBuffer->setBoolean(!v->isEmpty()); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: istimer + @type: + function + @title: + $isTimer + @short: + Checks for a timer existence + @syntax: + $istimer() + @description: + Returns 1 if the timer named is actually running, else 0 + @seealso: + [cmd]timer[/cmd], [cmd]killtimer[/cmd] + */ + + KVSCF(isTimer) + { + QString szName; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("timerName",KVS_PT_NONEMPTYSTRING,0,szName) + KVSCF_PARAMETERS_END + KVSCF_pRetBuffer->setBoolean(KviKvsTimerManager::instance()->timerExists(szName)); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: iswellknown + @type: + function + @title: + $isWellKnown + @short: + Returns $true if the specified user is well known + @syntax: + $isWellKnown() + @description: + Returns 1 if KVIrc has the basic user information about the specified .[br] + The basic information include the username and hostname.[br] + This is almost always true if the user is on a channel with you or + you have an open query with him.[br] + If $isWellKnown returns 0, [fnc]$username[/fnc] and [fnc]$hostname[/fnc] + will return empty strings.[br] + In this case you must use [cmd]awhois[/cmd] to obtain the user basic information.[br] + */ + + KVSCF(isWellKnown) + { + QString szNick; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("nick",KVS_PT_NONEMPTYSTRING,0,szNick) + KVSCF_PARAMETERS_END + + if(KVSCF_pContext->window()->console()) + { + if(KVSCF_pContext->window()->console()->isConnected()) + { + KviIrcUserEntry * e = KVSCF_pContext->window()->connection()->userDataBase()->find(szNick); + if(e) + { + KVSCF_pRetBuffer->setBoolean(e->hasHost() && e->hasUser()); + return true; + } + } + } + + KVSCF_pRetBuffer->setBoolean(false); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: k + @type: + function + @title: + $k + @short: + Returns the COLOR mIRC control character + @syntax: + $k([,]) + $k + @description: + Returns the COLOR mIRC control character (Qt::CTRL+K).[br] + If and are passed, a standard mIRC + color escape is returned.[br] + @seealso: + [fnc]$b[/fnc] + */ + + KVSCF(k) + { + kvs_uint_t iFore,iBack; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("foreground",KVS_PT_UINT,KVS_PF_OPTIONAL,iFore) + KVSCF_PARAMETER("background",KVS_PT_UINT,KVS_PF_OPTIONAL,iBack) + KVSCF_PARAMETERS_END + + QString szRet = QChar(KVI_TEXT_COLOR); + if(KVSCF_pParams->count() > 0) + { + KviQString::appendFormatted(szRet,"%u",iFore); + if(KVSCF_pParams->count() > 1) + KviQString::appendFormatted(szRet,",%u",iBack); + } + KVSCF_pRetBuffer->setString(szRet); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: keys + @type: + function + @title: + $keys + @short: + Returns the array of keys of a hash + @syntax: + $keys() + @description: + Returns an array with the keys of the parameter. + must be obviously a hash (or eventually an empty variable + that is treated as an empty hash). + @seealso: + [cmd]foreach[/cmd] + */ + + KVSCF(keys) + { + KviKvsHash * pHash = 0; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("hash",KVS_PT_HASH,KVS_PF_OPTIONAL,pHash) + KVSCF_PARAMETERS_END + + KviKvsArray * a = new KviKvsArray(); + + // we have to support an empty hash, returning an empty array (ticket #940) + if(pHash) + { + kvs_int_t idx = 0; + KviKvsHashIterator it(*(pHash->dict())); + while(it.current()) + { + a->set(idx,new KviKvsVariant(it.currentKey())); + idx++; + ++it; + } + } + KVSCF_pRetBuffer->setArray(a); + return true; + } + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: lang + @type: + function + @title: + $lang + @short: + Returns name of currently used language + @syntax: + $lang([]) + @description: + Returns the short name of currently used language + Type should be one of: [br] + "full" - returns full locale name, such as ru_RU.UTF-8 (default) + "lang" - return language name, such as "ru_RU" + "short" - returns only language group such as "ru" + */ + + KVSCF(lang) + { + QString szType; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("type",KVS_PT_NONEMPTYSTRING,KVS_PF_OPTIONAL,szType) + KVSCF_PARAMETERS_END + + QString szLocale(KviLocale::localeName().ptr()); + if(szType=="lang") KVSCF_pRetBuffer->setString(szLocale.left(5)); + else if(szType=="short") KVSCF_pRetBuffer->setString(szLocale.left(2)); + else KVSCF_pRetBuffer->setString(szLocale); + return true; + } + + + + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: length + @type: + function + @title: + $length + @short: + Returns the length of a variable + @syntax: + $length() + @description: + When is an array or a hash, it returns the number + of its elements. When is an object reference it returns 0. + In all the other cases is interpreted + as a string and its length is returned. + @seealso: + [fnc]$str.len[/fnc] + */ + + KVSCF(length) + { + KviKvsVariant * pVar; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("value",KVS_PT_VARIANT,0,pVar) + KVSCF_PARAMETERS_END + + switch(pVar->type()) + { + case KviKvsVariantData::Array: + KVSCF_pRetBuffer->setInteger(pVar->array()->size()); + break; + case KviKvsVariantData::Hash: + KVSCF_pRetBuffer->setInteger(pVar->hash()->size()); + break; + case KviKvsVariantData::HObject: + KVSCF_pRetBuffer->setInteger(0); + break; + default: + { + QString tmp; + pVar->asString(tmp); + KVSCF_pRetBuffer->setInteger(tmp.length()); + } + break; + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: lf + @type: + function + @title: + $lf + @short: + Returns a line feed character + @syntax: + $lf + @description: + Returns a line feed character + @seealso: + [fnc]$cr[/fnc], [fnc]$ascii[/fnc], [fnc]$char[/fnc] + */ + + KVSCF(lf) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setString(QString(QChar('\n'))); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: link + @type: + function + @title: + $link + @short: + Returns the text specified as a link + @syntax: + $link([,]) + @description: + Gets the text you pass as the first parameter and formats it + so that KVIrc will display it as a link. You can specify the + type of the link as the second parameter. Valid values for the + second parameter are:[br] + [ul] + [li]nick link to a nickname[/li] + [li]channel link to a channel name[/li] + [li]host link to an host[/li] + [li]url (default) link to an url[/li] + [/ul] + Please note that the text you get as the output is valid only + when interpreted locally. Sending this text to the server you can + get unpredictable results, depending on the irc client other people + is using. + The returned string format is described by [doc:escape_sequences]the escape sequences documentation[/doc] + and you might also take a look at [fnc]$fmtlink[/fnc] which has related functionality. + @examples: + echo $link(pragma,nick) + @seealso: + [cmd]echo[/cmd], [fnc]$fmtlink[/fnc]. + */ + + KVSCF(link) + { + QString szData, szType; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("text",KVS_PT_NONEMPTYSTRING,0,szData) + KVSCF_PARAMETER("type",KVS_PT_NONEMPTYSTRING,KVS_PF_OPTIONAL,szType) + KVSCF_PARAMETERS_END + + QString szRet("\r!"); + if(szType=="nick") + { + szRet.append("n\r"); + } else if(szType=="channel") { + szRet.append("c\r"); + } else if(szType=="host") { + szRet.append("h\r"); + } else { + szRet.append("u\r"); + } + szRet.append(szData); + szRet.append("\r"); + KVSCF_pRetBuffer->setString(szRet); + return true; + } + + /* + @doc: listtimers + @title: + $listtimers + @type: + function + @short: + Returns a list of the active timers + @syntax: + $listtimers([][,]) + @description: + Returns a list of all the active timers.[br] + If you specify a , only timers matching that name are returned; + You can use the * and ? wildcards in .[br] + can be any combination of the characters 's' and 'r'[br] + If the flag 'r' is specified then is assumed to be a standard regular expression. + If the flag 's' is specified the matches are case sensitive.[br] + + @seealso: + [cmd]timer[/cmd], [fnc]$isTimer[/fnc], [cmd]killtimer[/cmd], [cmd]listtimers[/cmd] + */ + + KVSCF(listtimers) + { + QString szText, szFlags; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("text",KVS_PT_STRING,KVS_PF_OPTIONAL,szText) + KVSM_PARAMETER("flags",KVS_PT_STRING,KVS_PF_OPTIONAL,szFlags) + KVSCF_PARAMETERS_END + + bool bCaseSensitive = szFlags.indexOf('s',0,Qt::CaseInsensitive) != -1; + bool bRegexp = szFlags.indexOf('r',0,Qt::CaseInsensitive) != -1; + bool bMatch = !szText.isEmpty(); + + KviPointerHashTable * pTimerDict = KviKvsTimerManager::instance()->timerDict(); + KviKvsArray * a = new KviKvsArray(); + + if(!pTimerDict) + return true; + + QRegExp re(szText,bCaseSensitive?Qt::CaseSensitive:Qt::CaseInsensitive,bRegexp?QRegExp::RegExp:QRegExp::Wildcard); + KviPointerHashTableIterator it(*pTimerDict); + kvs_int_t idx=0; + + while(KviKvsTimer * pTimer = it.current()) + { + if(bMatch) + { + if(!re.exactMatch(pTimer->name())) + { + ++it; + continue; + } + } + + a->set(idx,new KviKvsVariant(pTimer->name())); + idx++; + ++it; + } + + KVSCF_pRetBuffer->setArray(a); + return true; + } + +}; diff --git a/src/kvirc/kvs/KviKvsCoreFunctions_mr.cpp b/src/kvirc/kvs/KviKvsCoreFunctions_mr.cpp new file mode 100644 index 000000000..71b3f0aec --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreFunctions_mr.cpp @@ -0,0 +1,752 @@ +//============================================================================= +// +// File : KviKvsCoreFunctions_mr.cpp +// Creation date : Fri 31 Oct 2003 01:52:04 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCoreFunctions.h" +#include "KviKvsKernel.h" +#include "KviKvsArrayCast.h" +#include "KviKvsObjectController.h" +#include "KviLocale.h" +#include "KviIrcConnection.h" +#include "KviMircCntrl.h" +#include "KviOptions.h" +#include "KviConsoleWindow.h" +#include "KviIrcUserDataBase.h" +#include "KviIrcMask.h" +#include "kvi_socket.h" +#include "KviApplication.h" +#include "KviQueryWindow.h" + +#include // rand & srand + +namespace KviKvsCoreFunctions +{ + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: mask + @type: + function + @title: + $mask + @short: + Retrieves the host mask of a user + @syntax: + $mask[([,])] + @description: + Returns the specified type of mask for the user with .[br] + If the host or username are not known, the mask may contain less information + than requested.[br] + If the is not given it is assumed to be the current nickname.[br] + If is not given or is invalid, it is assumed to be 0.[br] + Available mask types:[br] + 0 : nick!user@machine.host.top (nick!user@XXX.XXX.XXX.XXX) (default)[br] + 1 : nick!user@*.abc.host.top (nick!user@XXX.XXX.XXX.*)[br] + 2 : nick!user@*[br] + 3 : nick!*@machine.host.top (nick!user@XXX.XXX.XXX.XXX)[br] + 4 : nick!*@*.abc.host.top (nick!user@XXX.XXX.XXX.*)[br] + 5 : nick!*@*[br] + 6 : *!user@machine.host.top (*!user@XXX.XXX.XXX.XX)[br] + 7 : *!user@*.abc.host.top (*!user@XXX.XXX.XXX.*)[br] + 8 : *!user@*[br] + 9 : *!*@machine.host.top (*!*@XXX.XXX.XXX.XXX)[br] + 10: *!*@*.abc.host.top (*!*@XXX.XXX.XXX.*)[br] + 11: nick!*user@machine.host.top (nick!*user@XXX.XXX.XXX.XXX)[br] + 12: nick!*user@*.abc.host.top (nick!*user@XXX.XXX.XXX.*)[br] + 13: nick!*user@*[br] + 14: *!*user@machine.host.top (*!*user@XXX.XXX.XXX.XXX)[br] + 15: *!*user@*.abc.host.top (*!*user@XXX.XXX.XXX.*)[br] + 16: *!*user@*[br] + 17: nick!~user@*.host.top (nick!~user@XXX.XXX.*)[br] + 18: nick!*@*.host.top (nick!*@XXX.XXX.*)[br] + 19: *!~user@*.host.top (*!~user@XXX.XXX.*)[br] + 20: nick!*user@*.host.top (nick!*user@XXX.XXX.*)[br] + 21: *!*user@*.host.top (*!user@*XXX.XXX.*)[br] + 22: nick!~user@*.host.top (nick!~user@XXX.XXX.*)[br] + 23: nick!*@*.host.top (nick!*@XXX.XXX.*)[br] + 24: *!~user@*.host.top (*!~user@XXX.XXX.*)[br] + 25: nick!*user@*.host.top (nick!*user@XXX.XXX.*)[br] + 26: *!*user@*.host.top (*!user@*XXX.XXX.*)[br] + If some data is missing, these types may change:[br] + For example, if the hostname is missing, the mask type 3 or 4 may be reduced to type 5.[br] + If the user with is not found in the current IRC context user database, + an empty string is returned.[br] + The masks 22-26 are the smart versions of the masks 17-21 that try take care of masked ip addresses + in the form xxx.xxx.INVALID-TOP-MASK. If a masked ip address is found then + the XXX.XXX.* or XXX.* host mask is returned instead of the (wrong) *.INVALID-TOP-MASK + @examples: + @seealso: + */ + + KVSCF(mask) + { + QString szNick; + kvs_uint_t maskType; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("nickname",KVS_PT_STRING,KVS_PF_OPTIONAL,szNick) + KVSCF_PARAMETER("maskType",KVS_PT_UINT,KVS_PF_OPTIONAL,maskType) + KVSCF_PARAMETERS_END + + if(maskType > 26) maskType = 0; + + if(KVSCF_pContext->window()->console()) + { + if(KVSCF_pContext->window()->console()->isConnected()) + { + KviIrcUserEntry * e = KVSCF_pContext->window()->connection()->userDataBase()->find(szNick.isEmpty() ? KVSCF_pContext->window()->connection()->currentNickName() : szNick); + if(e) + { + KviIrcMask u; + u.setNick(szNick); + u.setUsername(e->user()); + u.setHost(e->host()); + + QString tmp; + u.mask(tmp,(KviIrcMask::MaskType)maskType); + KVSCF_pRetBuffer->setString(tmp); + return true; + } + } + } + KVSCF_pRetBuffer->setNothing(); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: me + @type: + function + @title: + $me + @short: + Returns the current nickname + @syntax: + $me[()] + @description: + Returns the current nickname used in the specified IRC context.[br] + If no is specified, the current IRC context is used.[br] + If you are not connected to a server, this function will return a null string.[br] + If the current window is a DCC chat and no irc_context is specified, + the local nickname is returned.[br] + If the current window does not belong to any IRC context, no irc_context_id + is specified, and the current window is not a DCC chat, a warning is printed.[br] + */ + + KVSCF(me) + { + kvs_uint_t uCntx; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("irc_context_id",KVS_PT_UINT,KVS_PF_OPTIONAL,uCntx) + KVSCF_PARAMETERS_END + + KviConsole * cns; + + if(KVSCF_pParams->count() > 0) + { + cns = g_pApp->findConsole(uCntx); + if(cns) + { + if(cns->isConnected()) + KVSCF_pRetBuffer->setString(cns->connection()->currentNickName()); + else + KVSCF_pRetBuffer->setNothing(); + } else { + KVSCF_pRetBuffer->setNothing(); + } + } else { + if(KVSCF_pContext->window()->console()) + { + cns = KVSCF_pContext->window()->console(); + if(cns->isConnected()) + KVSCF_pRetBuffer->setString(cns->connection()->currentNickName()); + else + KVSCF_pRetBuffer->setNothing(); + } else { + if(KVSCF_pContext->window()->type() == KVI_WINDOW_TYPE_DCCCHAT) + { + KVSCF_pRetBuffer->setString(KVSCF_pContext->window()->localNick()); + } else { + KVSCF_pContext->warning(__tr2qs_ctx("This window has no associated IRC context and is not a DCC chat","kvs")); + KVSCF_pRetBuffer->setNothing(); + } + } + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: msgtype + @type: + function + @title: + $msgtype + @short: + Returns the id of a message type color set + @syntax: + $msgtype() + @description: + Returns the id of a message type color set used by the [cmd]echo[/cmd] command. + You can take a look at the options dialog section related to the + message output to see the list of available message type names. + @examples: + [example] + [cmd]echo[/cmd] -i=$msgtype(Highlight) Highlighted text! + [/example] + @seealso: + [cmd]echo[/cmd] + */ + + KVSCF(msgtype) + { + QString szName; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("msg_type_color_set_name",KVS_PT_NONEMPTYSTRING,0,szName) + KVSCF_PARAMETERS_END + + QString tmp = "msgtype"; + tmp += szName; + for(int i=0;i< KVI_NUM_MSGTYPE_OPTIONS;i++) + { + if(KviQString::equalCI(tmp,g_msgtypeOptionsTable[i].name)) + { + KVSCF_pRetBuffer->setInteger(i); + return true; + } + } + KVSCF_pRetBuffer->setInteger(0); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: new + @type: + function + @title: + $new + @short: + Creates a new object + @syntax: + $new(,[ [,[,[,[...]]]]) + @description: + Creates a new instance of the object with + the parent object and the specified .[br] + and are optional: if not specified, + is assumed to be an empty string and default to 0 (parentless object).[br] + This function accepts a list of optional parameters that will be passed to the 's constructor. + Please see the [doc:objects]objects documentation[/doc] for more information.[br] + @examples: + [example] + %myobj = $new(widget,0,pippo) + [/example] + @seealso: + [doc:objects]Objects documentation[/doc], [cmd]delete[/cmd] + */ + + KVSCF(newCKEYWORDWORKAROUND) + { + // prologue: parameter handling + QString szClassName; + QString szName; + kvs_hobject_t hParent = 0; + KviKvsVariantList vList; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("className",KVS_PT_NONEMPTYSTRING,0,szClassName) + KVSCF_PARAMETER("parentHandle",KVS_PT_HOBJECT,KVS_PF_OPTIONAL,hParent) + KVSCF_PARAMETER("name",KVS_PT_STRING,KVS_PF_OPTIONAL,szName) + KVSCF_PARAMETER("parameterList",KVS_PT_VARIANTLIST,KVS_PF_OPTIONAL,vList) + KVSCF_PARAMETERS_END + + KviKvsObjectClass * pClass = KviKvsKernel::instance()->objectController()->lookupClass(szClassName); + if(!pClass) + { + KVSCF_pContext->error(__tr2qs_ctx("Class '%Q' is not defined","kvs"),&szClassName); + return false; + } + + KviKvsObject * pParent; + if(hParent != (kvs_hobject_t)0) + { + pParent = KviKvsKernel::instance()->objectController()->lookupObject(hParent); + if(!pParent) + { + KVSCF_pContext->error(__tr2qs_ctx("The specified parent object does not exist","kvs")); + return false; + } + } else { + pParent = 0; + } + + KviKvsObject * pObject = pClass->allocateInstance(pParent,szName,KVSCF_pContext,&vList); + + // epilogue: set the return value + KVSCF_pRetBuffer->setHObject(pObject ? pObject->handle() : (kvs_hobject_t)0); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: nothing + @type: + function + @title: + $nothing + @short: + Evaluates to an empty variable + @syntax: + $nothing + @description: + Evaluates to an empty variable. This is a special value somewhat similar + to the [fnc]$null[/fnc] object: it is used to denote absence + of information. For example, a function might decide to return + a meaningful value when the input parameters are correct and + $nothing when the input parameters are wrong. + @seealso: + [fnc]$null[/fnc] + */ + + KVSCF(nothing) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setNothing(); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + + /* + @doc: null + @type: + function + @title: + $null + @short: + Evaluates to the null object handle. + @syntax: + $null + @description: + Evaluates to the null object handle. This is a special + object handle that is returned by some functions. + Please note that writing $null is semantically equivalent to writing 0 + or even [fnc]$nothing[/fnc] in place of the handle, but $null increases code readability. + @seealso: + [fnc]$new[/fnc], [fnc]$nothing[/fnc] + */ + + KVSCF(nullCKEYWORDWORKAROUND) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setHObject(0); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: o + @type: + function + @title: + $o + @short: + Returns the RESET mIRC control character + @syntax: + $o + @description: + Returns the RESET mIRC control character (CTRL+O).[br] + @seealso: + [fnc]$k[/fnc], [fnc]$b[/fnc], [fnc]$u[/fnc], [fnc]$r[/fnc] + */ + + KVSCF(o) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setString(QString(QChar(KVI_TEXT_RESET))); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: option + @type: + function + @title: + $option + @short: + Returns the value of an option + @syntax: + $option() + @description: + Returns the current value of the internal option named . + See the [cmd]option[/cmd] command documentation for more info about options. + @examples: + [example] + [cmd]echo[/cmd] $option(fontIrcView) + [/example] + @seealso: + [cmd]option[/cmd], + */ + + KVSCF(option) + { + QString szOpt; + // FIXME: This should return a variant in general + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("optionName",KVS_PT_NONEMPTYSTRING,0,szOpt) + KVSCF_PARAMETERS_END + QString tmp; + if(g_pApp->getOptionString(szOpt,tmp))KVSCF_pRetBuffer->setString(tmp); + else { + KVSCF_pContext->warning(__tr2qs_ctx("There is no option named '%Q'","kvs"),&szOpt); + KVSCF_pRetBuffer->setNothing(); + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: query + @type: + function + @title: + $query + @short: + Retrieves the window ID of a specified query + @syntax: + $query[([,])] + @description: + Returns the [b]window ID[/b] of the query that has + in the list of targets and is bound to the connection specified by + [br] + If no window matches the specified target or context, and invalid + window ID is returned (0).[br] + If no is specified, this function looks for + the query in the current connection context (if any).[br] + If no is specified, this function returns the current + query window ID, if executed in a query, else 0.[br] + @examples: + [example] + [/example] + @seealso: + [fnc]$window[/fnc], + [fnc]$channel[/fnc], + [fnc]$console[/fnc] + [doc:window_naming_conventions]Window naming conventions[/doc] + */ + + KVSCF(query) + { + QString szName; + kvs_uint_t uContextId; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("query_name",KVS_PT_NONEMPTYSTRING,KVS_PF_OPTIONAL,szName) + KVSCF_PARAMETER("context_id",KVS_PT_UINT,KVS_PF_OPTIONAL,uContextId) + KVSCF_PARAMETERS_END + + KviWindow * wnd = 0; + if(KVSCF_pParams->count() > 0) + { + if(KVSCF_pParams->count() > 1) + { + KviConsole * cons = g_pApp->findConsole(uContextId); + if(!cons)KVSCF_pContext->warning(__tr2qs_ctx("No such IRC context (%u)","kvs"),uContextId); + else { + if(cons->connection()) + wnd = cons->connection()->findQuery(szName); + else + wnd = 0; + } + } else { + if(KVSCF_pContext->window()->connection())wnd = KVSCF_pContext->window()->connection()->findQuery(szName); + else { + if(!KVSCF_pContext->window()->console()) + KVSCF_pContext->warning(__tr2qs_ctx("This window is not associated to an IRC context","kvs")); + wnd = 0; + } + } + } else { + if(KVSCF_pContext->window()->type() == KVI_WINDOW_TYPE_QUERY)wnd = KVSCF_pContext->window(); + } + + KVSCF_pRetBuffer->setInteger((kvs_int_t)(wnd ? wnd->numericId() : 0)); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: r + @type: + function + @title: + $r + @short: + Returns the REVERSE mIRC control character + @syntax: + $r + @description: + Returns the REVERSE mIRC control character (CTRL+R).[br] + @seealso: + [fnc]$k[/fnc], [fnc]$b[/fnc], [fnc]$u[/fnc], [fnc]$o[/fnc] + */ + + KVSCF(r) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setString(QString(QChar(KVI_TEXT_REVERSE))); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: rand + @type: + function + @title: + $rand + @short: + Generates a random number + @syntax: + $rand() + @description: + Returns a random integer number from 0 to max inclusive. + You can repeat sequences of random numbers by calling [cmd]srand[/cmd] + with the same seed value. If [cmd]srand[/cmd] has not been called + $rand is automatically seeded with value of 1. + If no is specified, this function returns an integer between + 0 and RAND_MAX that is system dependant. + @examples: + [example] + [/example] + @seealso: + [cmd]srand[/cmd] + */ + + KVSCF(rand) + { + // prologue: parameter handling + kvs_uint_t uMax; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("max",KVS_PT_UINT,KVS_PF_OPTIONAL,uMax) + KVSCF_PARAMETERS_END + if(KVSCF_pParams->count() > 0) + { + KVSCF_pRetBuffer->setInteger(::rand() % (uMax+1)); + } else { + KVSCF_pRetBuffer->setInteger(::rand()); + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: real + @type: + function + @title: + $real + @short: + Casts a variable to a real + @syntax: + $real() + @description: + Forces to be a "real" data type with the following + semantics:[br] + [ul] + [li]If is a real, itself is returned.[/li] + [li]If is an integer, itself is returned, in its real form.[/li] + [li]If is a boolean, its numeric value is returned (either 1.0 or 0.0).[/li] + [li]If is an array, the count of its items is returned.[/li] + [li]If is a hash, the count of its items is returned.[/li] + [li]If is a string, its length is returned.[/li] + [li]If is an object, 0.0 is returned if the reference is null (invalid) and 1.0 otherwise[/li] + [/ul] + This function is similar to the C (double) cast.[br] + Note that since KVIrc does most of the casting work automatically + you shouldn't need to use this function. + @seealso: + [fnc]$int[/fnc] + */ + + KVSCF(real) + { + KviKvsVariant * v; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,v) + KVSCF_PARAMETERS_END + + kvs_real_t dVal; + if(v->asReal(dVal)) + KVSCF_pRetBuffer->setReal(dVal); + else { + kvs_int_t iVal; + v->castToInteger(iVal); + KVSCF_pRetBuffer->setReal((double)iVal); + } + return true; + } + + /* + @doc: realname + @type: + function + @title: + $realname + @short: + Returns the realname of the specified user + @syntax: + $realname() + @description: + Returns the realname of the specified IRC user IF it is known.[br] + The realname is known if [fnc]$isWellKnown[/fnc] returns 1.[br] + The realname is generally known if the user is on a channel with you + or has an open query with you.[br] + Detailed explaination:[br] + KVIrc has an internal database of users that are currently + visible by *this client*: this includes users on open channels + and queries.[br] The other IRC users are NOT in the database: + this means that KVIrc knows NOTHING about them and can't return + any information immediately. In this case this function will return + an EMPTY string.[br] + If a user is in the database, at least his nickname is known.[br] + The username and hostname are known only if the server provides that information + spontaneously or after a KVIrc request.[br] + KVIrc requests user information for all the users in open queries + and channels. This information takes some time to be retrieved, + in this interval of time KVIrc knows only the user's nickname. + This function will return the string "*" in this case.[br] + @seealso: + [fnc]$isWellKnown[/fnc], [fnc]$hostname[/fnc], [fnc]$username[/fnc], [cmd]awhois[/cmd] + */ + + KVSCF(realname) + { + QString szNick; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("nick",KVS_PT_NONEMPTYSTRING,0,szNick) + KVSCF_PARAMETERS_END + + if(KVSCF_pContext->window()->console()) + { + if(KVSCF_pContext->window()->console()->isConnected()) + { + KviIrcUserEntry * e = KVSCF_pContext->window()->connection()->userDataBase()->find(szNick); + if(e) + { + KVSCF_pRetBuffer->setString(e->realName()); + return true; + } + } + } + + KVSCF_pRetBuffer->setNothing(); + return true; + } + + + /* + @doc: receivedBytes + @type: + function + @title: + $receivedBytes + @short: + Returns total received bytes + @syntax: + $receivedBytes() + @description: + Returns total received bytes + @seealso: + [fnc]$sentBytes[/fnc] + */ + + KVSCF(receivedBytes) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setInteger(g_uIncomingTraffic); + return true; + } + + /* + @doc: rsort + @type: + function + @title: + $rsort + @short: + Sorts an array in reverse order + @syntax: + $rsort() + @description: + Sorts an array in descending order. + @seealso: + [fnc]$sort[/fnc] + */ + + KVSCF(rsort) + { + KviKvsArrayCast a; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_ARRAYCAST,0,a) + KVSCF_PARAMETERS_END + + if(a.array()) + { + KviKvsArray * arry = new KviKvsArray(*(a.array())); + arry->rsort(); + KVSCF_pRetBuffer->setArray(arry); + } else { + KVSCF_pRetBuffer->setArray(new KviKvsArray()); + } + return true; + } +}; diff --git a/src/kvirc/kvs/KviKvsCoreFunctions_sz.cpp b/src/kvirc/kvs/KviKvsCoreFunctions_sz.cpp new file mode 100644 index 000000000..d01c92dae --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreFunctions_sz.cpp @@ -0,0 +1,1136 @@ +//============================================================================= +// +// File : KviKvsCoreFunctions_sz.cpp +// Creation date : Fri 31 Oct 2003 01:52:04 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCoreFunctions.h" + +#include "KviKvsKernel.h" +#include "KviKvsArrayCast.h" +#include "KviKvsObjectController.h" + +#include "KviWindow.h" +#include "kvi_out.h" +#include "KviLocale.h" +#include "KviApplication.h" +#include "KviOptions.h" +#include "KviChannelWindow.h" +#include "KviConsoleWindow.h" +#include "KviTimeUtils.h" +#include "KviIrcUserDataBase.h" +#include "KviModuleManager.h" +#include "KviMircCntrl.h" +#include "kvi_sourcesdate.h" +#include "kvi_socket.h" +#include "KviBuildInfo.h" + +#include // rand & srand + +/* + Data types: + + + + + + + + + + + + + + $isEmpty() == $true + + == + == + + +*/ + +namespace KviKvsCoreFunctions +{ + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: selected + @type: + function + @title: + $selected + @short: + Returns the list of selected nicknames in the channel + @syntax: + $selected + $selected() + @description: + This is an internal alias for [fnc]$userlist.selected[/fnc].[br] + This function is deprecated and its use is discouraged. + @seealso: + [fnc]$userlist.selected[/fnc] + */ + + KVSCF(selected) + { + KviKvsScript::evaluate("$userlist.selected", KVSCF_pContext->window(), KVSCF_pParams,KVSCF_pRetBuffer); + return true; + } + + + /* + @doc: sentBytes + @type: + function + @title: + $sentBytes + @short: + Returns total sent bytes + @syntax: + $sentBytes() + @description: + Returns total sent bytes + @seealso: + [fnc]$receivedBytes[/fnc] + */ + + KVSCF(sentBytes) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setInteger(g_uOutgoingTraffic); + return true; + } + + /* + @doc: serialize + @type: + function + @title: + $serialize + @short: + Encodes variable to JSON string + @syntax: + $serialize() + @description: + Decodes JSON-encoded string + $serialize() returns a string containing a byte-stream representation of value that can be stored anywhere. + @seealso: + [fnc]$unserialize[/fnc] + */ + KVSCF(serialize) + { + KviKvsVariant *pVar = 0; + QString szBuffer; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,pVar) + KVSCF_PARAMETERS_END + + if(!pVar) return false; + pVar->serialize(szBuffer); + KVSCF_pRetBuffer->setString(szBuffer); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: server + @type: + function + @title: + $server + @short: + Returns the current server name (if any) + @syntax: + $server[(irc_context_id:uint)] + @description: + Returns the current server name of the specified IRC context.[br] + If no is specified, the current IRC context is used.[br] + If you are not connected to a server, this function will return an empty string.[br] + If the current window does not belong to any IRC context and no irc_context_id + is specified, this function prints a warning and also returns an empty string.[br] + */ + + KVSCF(server) + { + kvs_uint_t uCntx; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("irc_context_id",KVS_PT_UINT,KVS_PF_OPTIONAL,uCntx) + KVSCF_PARAMETERS_END + + KviConsole * cns; + + if(KVSCF_pParams->count() > 0) + { + cns = g_pApp->findConsole(uCntx); + if(cns) + { + if(cns->context()->isConnected() || cns->context()->isLoggingIn()) + KVSCF_pRetBuffer->setString(cns->connection()->currentServerName()); + else + KVSCF_pRetBuffer->setNothing(); + } else { + KVSCF_pRetBuffer->setNothing(); + } + } else { + if(KVSCF_pContext->window()->console()) + { + cns = KVSCF_pContext->window()->console(); + if(cns->context()->isConnected() || cns->context()->isLoggingIn()) + KVSCF_pRetBuffer->setString(cns->connection()->currentServerName()); + else + KVSCF_pRetBuffer->setNothing(); + } else { + KVSCF_pContext->warning(__tr2qs_ctx("This window has no associated IRC context","kvs")); + KVSCF_pRetBuffer->setNothing(); + } + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: sort + @type: + function + @title: + $sort + @short: + Sorts an array + @syntax: + $sort() + @description: + Sorts an array in ascending order. + @seealso: + [fnc]$rsort[/fnc] + */ + + KVSCF(sort) + { + KviKvsArrayCast a; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_ARRAYCAST,0,a) + KVSCF_PARAMETERS_END + + if(a.array()) + { + KviKvsArray * arry = new KviKvsArray(*(a.array())); + arry->sort(); + KVSCF_pRetBuffer->setArray(arry); + } else { + KVSCF_pRetBuffer->setArray(new KviKvsArray()); + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: string + @type: + function + @title: + $string + @short: + Casts a variable to a string + @syntax: + $string() + @description: + Forces to be a string data type with the following semantics: + [ul] + [li]If is a string then itself is returned.[/li] + [li]If is an integer then its decimal rappresentation is returned.[/li] + [li]If is a real then its decimal floating-point rappresentation is returned.[/li] + [li]If is a boolean then the string "1" is returned for a true value and the string "0" for a false value.[/li] + [li]If is nothing (unset) then an empty string is returned[/li] + [li]If is an array then a string with all the items converted to strings and separated by commas is returned[/li] + [li]If is a hash then a string with all the values converted to strings and separated by commas is returned[/li] + [li]If is a hobject then the string "object" is returned[/li] + [/ul] + Note that since KVIrc does most of the casting work automatically + you shouldn't need to use this function. + @seealso: + [fnc]$real[/fnc] + [fnc]$integer[/fnc] + */ + + KVSCF(string) + { + KviKvsVariant * v; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,v) + KVSCF_PARAMETERS_END + + QString szVal; + v->asString(szVal); + KVSCF_pRetBuffer->setString(szVal); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: sw + @type: + function + @title: + $sw + @short: + Returns the value of a switch for an alias + @syntax: + $sw([,]) + @description: + This function is valid and useful only in aliases. + It allows an alias to handle switches just like any other + KVIrc command. If a switch in the form - was + passed to the current alias then $sw() + returns 1 (true). If a switch in the form -= + was passed to the current alias then is returned. + If the switch was not present at all then this function + returns an empty string (that evaluates to false in an expression). + A warning is printed if this function is used non-alias code. + @examples: + [example] + [cmd]alias[/cmd](test){ + if($sw(a,append)) [cmd]echo[/cmd] "Switch -a was passed" + %x = $sw(x); + if(%x) [cmd]echo[/cmd] "Switch -x=%x was passed" + } + test -a + test -x + test --append -x + test -a -x + test -a -x=test + test -a=10 -x=test + [/example] + */ + + KVSCF(sw) + { + QString szSwitch; + QString szLongSwitch; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("switch_name",KVS_PT_STRING,0,szSwitch) + KVSCF_PARAMETER("long_name",KVS_PT_STRING, KVS_PF_OPTIONAL, szLongSwitch) + KVSCF_PARAMETERS_END + + KviKvsSwitchList * sl = KVSCF_pContext->aliasSwitchList(); + if(!sl) + { + KVSCF_pContext->warning(__tr2qs_ctx("The $sw() function can be used only in aliases","kvs")); + return true; + } + + KviKvsVariant * v; + + + if(szSwitch.length() > 1) + { + if(szLongSwitch.isEmpty()) + v = sl->find(szSwitch); + else + v = sl->find(szSwitch[0].unicode(),szLongSwitch); + }else { + if(szLongSwitch.isEmpty()) + v = sl->find(szSwitch[0]); + else + v = sl->find(szSwitch[0].unicode(),szLongSwitch); + } + + if(v)KVSCF_pRetBuffer->copyFrom(*v); + else KVSCF_pRetBuffer->setNothing(); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: target + @type: + function + @title: + $target + @short: + Returns the target of the current window + @syntax: + $target + $target() + @description: + The form with the parameter returns the target + of the channel,query or dcc that has the specified ID. + The form without parameters returns the target of the current window, + thus it is equivalent to calling $target([fnc]$window[/fnc]). + For channel windows the target is the channel name, + for query windows it is the list of the "queried" users, for the + dcc windows it is the remote end of the connection. + The other windows have an empty target. + @examples: + [example] + [cmd]echo[/cmd] $target + [/example] + @seealso: + [fnc]$window[/fnc], + [fnc]$console[/fnc], + [fnc]$channel[/fnc], + [fnc]$query[/fnc], + [doc:window_naming_conventions]Window naming conventions[/doc] + */ + + KVSCF(target) + { + QString winId; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("winId",KVS_PT_NONEMPTYSTRING,KVS_PF_OPTIONAL,winId) + KVSCF_PARAMETERS_END + + KviWindow * wnd; + if(KVSCF_pParams->count() > 0) + { + wnd = g_pApp->findWindow(winId.toUtf8().data()); + if(!wnd) + { + KVSCF_pContext->warning(__tr2qs_ctx("Window with ID '%s' not found, returning empty string","kvs"),winId.toUtf8().data()); + KVSCF_pRetBuffer->setNothing(); + return true; + } + } else { + wnd = KVSCF_pContext->window(); + } + + //qDebug("CALLING $target on window %s",wnd->name()); + QString szTa = wnd->target(); + + + KVSCF_pRetBuffer->setString(wnd->target()); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: this + @type: + function + @title: + $this + @short: + Retrieves the ID of the current object + @syntax: + $this + @description: + Returns the ID of the current object or ('0') if there is + none. This function has a "quick" version with syntax: + [b]$$[/b][br] + */ + + /* + @doc: $ + @type: + function + @title: + $$ + @short: + Retrieves the ID of the current object + @syntax: + $$ + @description: + Returns the ID of the current object or ('0') if there is + none. This function has equivalent to [fnc]$this[/fnc] + */ + + KVSCF(thisCKEYWORDWORKAROUND) + { + Q_UNUSED(__pParams); + + // prologue: parameter handling + KviKvsObject * o = KVSCF_pContext->thisObject(); + KVSCF_pRetBuffer->setHObject(o ? o->handle() : ((kvs_hobject_t)0)); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: script_localization + @type: + generic + @title: + Localization of scripts + @short: + Explains how to add translation capabilities to your scripts + @body: + [p] + [big]Introduction[/big] + [/p] + [p] + Adding the translated versions of the strings adds a great + value to your scripts. The process of translating a part of + software is called localization. KVIrc offers some commands + and functions for this purpose and this document explains + briefly how to use them. + [/p] + + [p] + [big]The big picture[/big] + [/p] + [p] + All of the strings in your script are written in a "primary language". + The most common "primary language" is english, but theoretically + it can be any language of your choice. + [/p] + [p] + By the means of the gettext package programs you extract + the strings from your script and produce a translation file. + [/p] + [p] + The translation file is then effectively translated in another + language and later compiled in a binary form. + [/p] + [p] + The binary form translations are then loaded in the KVIrc + executable at runtime and a function is used to look up the + translations. + [/p] + + [p] + [big]How to translate scripts[/big] + [/p] + [p] + Your strings should be surrounded by the [fnc]$tr[/fnc]() function in the following way: + [example] + [fnc]$tr[/fnc]("your default language text") + [/example] + [/p] + [p] + Then you should run the xgettext command on your script files. + This is done by a shell commandline similar to the following:[br] + [pre]xgettext -o myscript.pot -ktr mykvsfile1.kvs mykvsfile2.kvs ...[/pre] + [/p] + [p] + Copy the translation file obtained in the following way:[br] + [pre]cp myscript.pot myscript_XX.pot[/pre] + Where the XX is your country/language code. For example, for Italian + it would be:[br] + [pre]cp myscript.pot myscript_it.po[/pre] + [/p] + [p] + Translate mytranslation_it.po. The format of the po file is straightforward. + There are msgid lines with the original english text and immediately + following msgstr lines that must be filled with the corresponding translation. + For example in Italian you would translate:[br] + msgid "your default language text" + msgstr "il tuo testo in linguaggio predefinito" + [/p] + [p] + Compile your translation to binary form with the following command:[br] + [pre]msgfmt -o myscript_it.mo myscript_it.po[/pre] + [/p] + [p] + Copy the generated *.mo file to the "locale" subdirectory + in the KVIrc's local directory (usually $HOME/.kvirc/locale/). + [/p] + [p] + Set the system language to the XX above with the following command:[br] + [pre]export LANG="XX"[/pre][br] + For Italian it would be:[br] + [pre]export LANG="it"[/pre][br] + [/p] + [p] + Start KVIrc and type in the commandline: + [example] + [cmd]echo[/cmd] [fnc]$tr[/fnc]("your default language text","myscript") + [/example] + If you did everything well, you should see the translated + text echoed in the window :)[br] + [/p] + [p] + Obviously if you don't set LANG="XX", the same command will + output the original string unchanged. + [/p] + [p] + You can manage translations in several languages by producing + several *.mo files all with the proper language/country code appended. + The right *.mo file will be magically loaded by KVIrc that + will look up the user's LANG variable. (If you don't want + to use LANG, you can use KVIRC_LANG instead, it will still work). + [/p] + + [big]Caveats[/big] + [/p] + [p] + You should NEVER use variables or identifiers inside the $tr() function. + This because the translation files are generated offline, + when the string is not evaluated yet (i.e variables ad identifiers + are not substituted by their actual return values). + The translation process, instead, happens at runtime, when + the variables and identifiers have been substituted by their + actual values. This would lead to a mismatch between the + string you look up in the translation catalogue and the + effectively translated one. If you need to include variables + in your strings you should compose the string with smaller pieces + [example] + [cmd]echo[/cmd] [fnc]$tr[/fnc]("On this channel") %number [fnc]$tr[/fnc]("users are operators") + [/example] + [/p] + [p] + The translation process can be realized only if your + scripts are written in external files. This makes sense since + if you're translating the script then you will probably want to + distribute it and the only way to distribute it is on files. + But well.. this is a caveat. + [/p] + */ + + /* + @doc: tr + @type: + function + @title: + $tr + @short: + Translates an english string to the current language + @syntax: + $tr([,]) + @description: + This function searches for the translation of + in the specified translation or in the main + KVIrc translation file if is omitted.[br] + If no translation is found then is returned.[br] + is a string in your script default + language (which should probably be english since it is the + most common language spoken by the translators...).[br] + If the is not loaded yet, KVIrc will attempt to load it, + but only the first time that the catalogue is accessed (i.e. a load + failure will cause the catalogue to be ignored completly until [cmd]trunload[/cmd] + is explicitly used.[br] + KVIrc will search the catalogue only in [fnc]$file.localdir[/fnc]/locale/ + and in [fnc]$file.globaldir[/fnc]/locale/. If your catalogues are + in some other place then you must load them explicitly by the + means of [cmd]trload[/cmd]. + For more information see the documentation about [doc:script_localization]script localization[/doc]. + @examples: + [example] + [cmd]echo[/cmd] $tr("Hello World!") + [/example] + @seealso: + [cmd]trload[/cmd], [cmd]trunload[/cmd] + */ + + KVSCF(tr) + { + // prologue: parameter handling + QString szString; + QString szCatalogue; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("default_language_string",KVS_PT_STRING,0,szString) + KVSCF_PARAMETER("catalogue",KVS_PT_STRING,KVS_PF_OPTIONAL,szCatalogue) + KVSCF_PARAMETERS_END + if(szString.isEmpty()) return true; + // body: the real job + QString translation; + + if(!szCatalogue.isEmpty()) + { + KviMessageCatalogue * pCat = KviLocale::getLoadedCatalogue(szCatalogue); + if(pCat) + { + translation = pCat->translateToQString(szString.toUtf8().data()); + } else { + // attempt to load it automatically + QString szDir; + g_pApp->getLocalKvircDirectory(szDir,KviApplication::Locale); + if(!KviLocale::loadCatalogue(szCatalogue,szDir)) + { + g_pApp->getGlobalKvircDirectory(szDir,KviApplication::Locale); + KviLocale::loadCatalogue(szCatalogue,szDir); + } + // If the code above fails to load the catalogue + // then __tr2qs_ctx_no_xgettext will place + // a dummy catalogue in its place + // This means that the next call to getLoadedCatalogue will + // not fail unless /trunload is explicitly used + // This will avoid trashing the user's disk too much + // when a catalogue for a given language is not available + translation = __tr2qs_ctx_no_xgettext(szString.toUtf8().data(),szCatalogue.toUtf8().data()); + } + } else { + translation = __tr2qs_no_xgettext(szString.toUtf8().data()); + } + + // epilogue: set the return value + KVSCF_pRetBuffer->setString(translation); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: true + @type: + function + @title: + $true + @short: + The boolean true constant + @syntax: + $true + @description: + Evaluates to the true boolean constant. True + is equivalent to the integer 1 too. This function/constant + is useful to keep your code readable: when you + have a variable that can assume boolean values it's + nicer to use $true and [fnc]$false[/fnc] instead of + the integer constants 1 and 0. The reader will + undestand immediately that the variable simply can't + assume any other value. + @examples: + [example] + %a = $true + [cmd]echo[/cmd] $typeof(%a) + [cmd]echo[/cmd] $(%a + 1) + [/example] + @seealso: + [fnc]$false[/fnc] + */ + + KVSCF(trueCKEYWORDWORKAROUND) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setBoolean(true); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: typeof + @type: + function + @title: + $typeof + @short: + Returns the internal data type of a variable + @syntax: + $typeof() + @description: + Returns the internal data type of the . + @examples: + [example] + [cmd]echo[/cmd] $typeof("test") + %a = "test" + [cmd]echo[/cmd] $typeof(%a) + %a = 1 + [cmd]echo[/cmd] $typeof(%a) + %a = $(1 + 2) + [cmd]echo[/cmd] $typeof(%a) + [cmd]echo[/cmd] $typeof($typeof(%a)) + [/example] + */ + + KVSCF(typeofCKEYWORDWORKAROUND) + { + KviKvsVariant * v; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_VARIANT,0,v) + KVSCF_PARAMETERS_END + + QString szType; + v->getTypeName(szType); + KVSCF_pRetBuffer->setString(szType); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: u + @type: + function + @title: + $u + @short: + Returns the UNDERLINE mIRC control character + @syntax: + $u + @description: + Returns the UNDERLINE mIRC control character (CTRL+U).[br] + @seealso: + [fnc]$k[/fnc], [fnc]$b[/fnc], [fnc]$r[/fnc], [fnc]$o[/fnc] + */ + + KVSCF(u) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setString(QString(QChar(KVI_TEXT_UNDERLINE))); + return true; + } + + /* + @doc: uflags + @type: + function + @title: + $uflags + @short: + Retrieves the user flags of a user + @syntax: + $uflags[()] + @description: + Returns the user flags of the user with .[br] + If the is not given it is assumed to be the current nickname.[br] + If this information is not known yet or the user with is not found + in the current IRC context user database, an empty string is returned.[br] + @examples: + @seealso: + */ + + KVSCF(uflags) + { + QString szNick; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("nickname",KVS_PT_STRING,KVS_PF_OPTIONAL,szNick) + KVSCF_PARAMETERS_END + + if(KVSCF_pContext->window()->console()) + { + if(KVSCF_pContext->window()->console()->isConnected()) + { + KviIrcUserEntry * e = KVSCF_pContext->window()->connection()->userDataBase()->find(szNick.isEmpty() ? KVSCF_pContext->window()->connection()->currentNickName() : szNick); + if(e) + { + KVSCF_pRetBuffer->setString(e->userFlags()); + return true; + } + } + } + KVSCF_pRetBuffer->setNothing(); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: unicode + @type: + function + @title: + $unicode + @short: + Returns the UNICODE code of a sets of characters + @syntax: + $unicode() + @description: + If is composed only of a single character + then returns its UNICODE code point as an integer. + If is composed of more than one character + then an array of UNICODE code points is returned. + @seealso: + [fnc]$cr[/fnc], [fnc]$lf[/fnc], [fnc]$char[/fnc] + */ + + KVSCF(unicode) + { + QString sz; + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("char",KVS_PT_NONEMPTYSTRING,0,sz) + KVSCF_PARAMETERS_END + + if(sz.length() > 1) + { + KviKvsArray * a = new KviKvsArray(); + for(kvs_int_t i=0;iset(i,new KviKvsVariant((kvs_int_t)(sz[(int)i].unicode()))); + KVSCF_pRetBuffer->setArray(a); + } else { + KVSCF_pRetBuffer->setInteger((kvs_int_t)(sz[0].unicode())); + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: unixtime + @type: + function + @title: + $unixTime + @short: + Returns the current UNIX time + @syntax: + $unixtime + @description: + Returns the time since the Epoch (00:00:00 UTC, January 1, 1970), + measured in seconds. + @seealso: + [fnc]$date[/fnc], [fnc]$hpTimeStamp[/fnc] + */ + + KVSCF(unixtime) + { + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + KVSCF_pRetBuffer->setInteger((kvs_int_t)(time(0))); + return true; + } + + /* + @doc: unserialize + @type: + function + @title: + $unserialize + @short: + Decodes JSON-encoded string + @syntax: + $unserialize() + @description: + Decodes JSON-encoded string + @seealso: + [fnc]$serialize[/fnc] + */ + + KVSCF(unserialize) + { + QString szData; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("data",KVS_PT_NONEMPTYSTRING,0,szData) + KVSCF_PARAMETERS_END + + KviKvsVariant *pVar = KviKvsVariant::unserialize(szData); + if(pVar) + KVSCF_pRetBuffer->copyFrom(pVar); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: username + @type: + function + @title: + $username + @short: + Returns the username of the specified user + @syntax: + $username() + @description: + Returns the username of the specified IRC user IF it is known.[br] + The username is known if [fnc]$isWellKnown[/fnc] returns 1.[br] + The username is generally known if the user is on a channel with you + or has an open query with you.[br] + Detailed explaination:[br] + KVIrc has an internal database of users that are currently + visible by *this client*: this includes users on open channels + and queries.[br] The other IRC users are NOT in the database: + this means that KVIrc knows NOTHING about them and can't return + any information immediately. In this case this function will return + an EMPTY string.[br] + If a user is in the database, at least his nickname is known.[br] + The username and hostname are known only if the server provides that information + spontaneously or after a KVIrc request.[br] + KVIrc requests user information for all the users in open queries + and channels. This information takes some time to be retrieved, + in this interval of time KVIrc knows only the user's nickname. + This function will return the string "*" in this case.[br] + @seealso: + [fnc]$isWellKnown[/fnc], [fnc]$hostname[/fnc], [fnc]$realname[/fnc], [cmd]awhois[/cmd] + */ + + KVSCF(username) + { + QString szNick; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("nick",KVS_PT_NONEMPTYSTRING,0,szNick) + KVSCF_PARAMETERS_END + + if(KVSCF_pContext->window()->console()) + { + if(KVSCF_pContext->window()->console()->isConnected()) + { + KviIrcUserEntry * e = KVSCF_pContext->window()->connection()->userDataBase()->find(szNick); + if(e) + { + KVSCF_pRetBuffer->setString(e->user()); + return true; + } + } + } + + KVSCF_pRetBuffer->setNothing(); + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: version + @type: + function + @title: + $version + @short: + Returns information about the version of KVIrc. + @syntax: + $version() + $version() + @description: + Returns information about the version of the currently running KVIrc.[br] + Type can be one of:[br] + [ul] + [li]b: return the build date in human readable form[/li] + [li]n: return the release name[/li] + [li]r: return the revision number[/li] + [li]s: return the current sources date[/li] + [li]v: return the current numeric version[/li] + [/ul] + + If is omitted a full string is returned.[br] + @examples: + [example] + [cmd]echo[/cmd] $version $version(r) + [/example] + @seealso: + [fnc]$features[/fnc] + */ + + KVSCF(version) + { + QString szType; + QString szVersion; + QString szRetValue; + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("type",KVS_PT_STRING,KVS_PF_OPTIONAL,szType) + KVSCF_PARAMETERS_END + + szVersion = KVI_RELEASE_NAME " " KVI_VERSION; + szVersion += ", revision: "; + szVersion += KviBuildInfo::buildRevision(); + szVersion += ", sources date: "; + szVersion += KviBuildInfo::buildSourcesDate(); + szVersion += ", built on: "; + szVersion += KviBuildInfo::buildDate(); + + if(szType.isEmpty()) + KVSCF_pRetBuffer->setString(szVersion); + else { + if(szType.indexOf('b') != -1) + szRetValue = KviBuildInfo::buildDate(); + else if(szType.indexOf('n') != -1) + szRetValue = KVI_RELEASE_NAME; + else if(szType.indexOf('r') != -1) + szRetValue = KviBuildInfo::buildRevision(); + else if(szType.indexOf('s') != -1) + szRetValue = KviBuildInfo::buildSourcesDate(); + else if(szType.indexOf('v') != -1) + szRetValue = KVI_VERSION; + else szRetValue = szVersion; + + KVSCF_pRetBuffer->setString(szRetValue); + } + return true; + } + + ///////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: window + @type: + function + @title: + $window + @short: + Retrieve the id of a specified window. + @syntax: + $window + $window([[,]]) + @description: + Returns the [b]window id[/b] of the first window that + has the specified .[br] + If no window matches the specified , and invalid + window id is returned (0).[br] + If no is specified, this function returns the id + of the current window.[br] + restricts search in only one irc context. + @examples: + [example] + [cmd]echo[/cmd] This is the window with id $window + [/example] + @seealso: + [fnc]$channel[/fnc], + [fnc]$query[/fnc], + [fnc]$console[/fnc], + [doc:window_naming_conventions]Window naming conventions[/doc] + */ + + KVSCF(window) + { + //#warning "FIXME: the window identifiers could be numbers!" + QString szCaption; + kvs_int_t iContextId; // kvs_int_t is 64bit while int is 32 (and thus KVSCF_PARAMETER() crashes) + + KVSCF_PARAMETERS_BEGIN + KVSCF_PARAMETER("caption_text",KVS_PT_STRING,KVS_PF_OPTIONAL,szCaption) + KVSCF_PARAMETER("context_id",KVS_PT_INTEGER,KVS_PF_OPTIONAL,iContextId) + KVSCF_PARAMETERS_END + + if(KVSCF_pParams->count() < 2) + iContextId = -1; + + KviWindow * pWnd; + if(szCaption.isEmpty()) + { + pWnd = KVSCF_pContext->window(); + } else { + pWnd = g_pApp->findWindowByCaption(szCaption,iContextId); + if(!pWnd) + { + //follow the documented behaviour + KVSCF_pRetBuffer->setInteger(0); + return true; + } + } + KVSCF_pRetBuffer->setInteger(pWnd->numericId()); + return true; + } +}; diff --git a/src/kvirc/kvs/KviKvsCoreSimpleCommands.cpp b/src/kvirc/kvs/KviKvsCoreSimpleCommands.cpp new file mode 100644 index 000000000..6d1b8b716 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreSimpleCommands.cpp @@ -0,0 +1,246 @@ +//============================================================================= +// +// File : KviKvsCoreSimpleCommands.cpp +// Creation date : Fri 31 Oct 2003 00:04:25 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviIrcConnectionServerInfo.h" +#include "KviKvsCoreSimpleCommands.h" + +#include "KviKvsKernel.h" +#include "KviOptions.h" +#include "KviIrcConnection.h" +#include "KviLocale.h" +#include "KviKvsTreeNodeCommand.h" + +#include +#include + +namespace KviKvsCoreSimpleCommands +{ + void init() + { + KviKvsKernel * pKern = KviKvsKernel::instance(); + +#define _REGCMD(__cmdName,__routine) \ + { \ + KviKvsCoreSimpleCommandExecRoutine * r = new KviKvsCoreSimpleCommandExecRoutine; \ + r->proc = KVI_PTR2MEMBER(KviKvsCoreSimpleCommands::__routine); \ + pKern->registerCoreSimpleCommandExecRoutine(QString(__cmdName),r); \ + } + // a_f + _REGCMD("admin",rfc2812wrapper) + _REGCMD("away",away) + _REGCMD("back",back) + _REGCMD("ban",ban) + _REGCMD("beep",beep) + _REGCMD("buttonctl",buttonctl) + _REGCMD("cap",cap) + _REGCMD("chanadmin",chanadmin) + _REGCMD("chanowner",chanowner) + _REGCMD("codepage",rfc2812wrapper) + _REGCMD("ctcp",ctcp) + _REGCMD("debug",debugCKEYWORDWORKAROUND) + _REGCMD("dechanadmin",dechanadmin) + _REGCMD("dechanowner",dechanowner) + _REGCMD("dehalfop",dehalfop) + _REGCMD("delete",deleteCKEYWORDWORKAROUND) + _REGCMD("delpopupitem",delpopupitem) + _REGCMD("destroy",deleteCKEYWORDWORKAROUND) + _REGCMD("deop",deop) + _REGCMD("deuserop",deuserop) + _REGCMD("devoice",devoice) + _REGCMD("die",error) + _REGCMD("echoprivmsg",echoprivmsg) + _REGCMD("echo",echo) + _REGCMD("error",error) + _REGCMD("eval",eval) + _REGCMD("eventctl",eventctl) + _REGCMD("exit",exit) + // g_l + _REGCMD("halfop",halfop) + _REGCMD("halt",halt) + _REGCMD("help",help) + _REGCMD("host",host) + _REGCMD("include",parse) + _REGCMD("info",rfc2812wrapper) + _REGCMD("inject",inject) + _REGCMD("invite",rfc2812wrapper) + _REGCMD("join",join) + _REGCMD("kick",kick) + _REGCMD("killtimer",killtimer) + _REGCMD("leave",part) + _REGCMD("links",rfc2812wrapper) + _REGCMD("list",rfc2812wrapper) + _REGCMD("listtimers",listtimers) + _REGCMD("lusers",rfc2812wrapper) + // m_r + _REGCMD("me",me) + _REGCMD("mode",mode) + _REGCMD("motd",rfc2812wrapper) + _REGCMD("msg",privmsg) + _REGCMD("nick",nick) + _REGCMD("notice",notice) + _REGCMD("op",op) + _REGCMD("openurl",openurl) + _REGCMD("oper",rfc2812wrapper) + _REGCMD("option",option) + _REGCMD("parse",parse) + _REGCMD("part",part) + _REGCMD("pass",rfc2812wrapper) + _REGCMD("play",play) + _REGCMD("popup",popup) + _REGCMD("privmsg",privmsg) + _REGCMD("query",query) + _REGCMD("quit",quit) + _REGCMD("quote",raw) + _REGCMD("raise",raise) + _REGCMD("raw",raw) + _REGCMD("return",returnCKEYWORDWORKAROUND) + _REGCMD("rebind",rebind) + // s_z + _REGCMD("run",run) + _REGCMD("say",say) + _REGCMD("server",server) + _REGCMD("service",rfc2812wrapper) + _REGCMD("setmenu",setmenu) + _REGCMD("setreturn",setreturn) + _REGCMD("sockets",rfc2812wrapper) + _REGCMD("squery",squery) + _REGCMD("squit",rfc2812wrapper) + _REGCMD("srand",srand) + _REGCMD("stats",rfc2812wrapper) + _REGCMD("time",rfc2812wrapper) + _REGCMD("topic",topic) + _REGCMD("trace",rfc2812wrapper) + _REGCMD("trload",trload) + _REGCMD("trunload",trunload) + _REGCMD("unban",unban) + _REGCMD("userop",userop) + _REGCMD("version",rfc2812wrapper) + _REGCMD("voice",voice) + _REGCMD("warning",warning) + _REGCMD("who",who) + _REGCMD("whois",whois) + _REGCMD("whowas",whowas) + +#undef _REGCMD + } + + + bool multipleModeCommand(KviKvsRunTimeContext * __pContext,KviKvsVariantList * __pParams,KviKvsSwitchList * __pSwitches,char plusminus,char flag) + { + Q_UNUSED(__pSwitches); + + QString szTokens; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("tokens",KVS_PT_STRING,KVS_PF_APPENDREMAINING,szTokens) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + if(KVSCSC_pWindow->type() != KVI_WINDOW_TYPE_CHANNEL) + { + KVSCSC_pContext->warning(__tr2qs_ctx("This is not a channel","kvs")); + return true; + } + + QStringList sl = szTokens.split(QRegExp("[, ]+"),QString::SkipEmptyParts); + + QByteArray szFlags; + QByteArray szTarget = KVSCSC_pConnection->encodeText(KVSCSC_pWindow->windowName()); + QByteArray szMessage; + + int i = 0; + for(QStringList::Iterator it = sl.begin();it != sl.end();++it) + { + QByteArray szTxt = KVSCSC_pConnection->encodeText(*it); + if(!szTxt.isEmpty()) + { + szFlags += flag; + if(szMessage.length() > 0)szMessage += " "; + szMessage += szTxt; + i++; + if(i >= KVSCSC_pConnection->serverInfo()->maxModeChanges()) + { + if(!KVSCSC_pConnection->sendFmtData("MODE %s %c%s %s",szTarget.data(),plusminus,szFlags.data(),szMessage.data())) + return KVSCSC_pContext->warningNoIrcConnection(); + i = 0; + szFlags = ""; + szMessage = ""; + } + } + } + + if(i > 0) + { + if(!KVSCSC_pConnection->sendFmtData("MODE %s %c%s %s",szTarget.data(),plusminus,szFlags.data(),szMessage.data())) + return KVSCSC_pContext->warningNoIrcConnection(); + } + + return true; + } + + /* + @doc: rfc2821wrappers + @title: + RFC2821 Wrappers + @type: + generic + @short: + Wrappers for rfc2821 commands + @body: + Some less used KVIrc commands are implemented as simple wrappers + around the standard [doc]rfc2821[/doc] commands.[br] + For example, the /[cmd:oper]OPER[/cmd] command will be used only by server operators + and probably only once per connection.[br] + These commands should only be needed by experienced IRC users. + Due to this fact, these commands have no special kind of parsing performed by KVIrc; + the parameters are extracted, the identifiers are parsed normally + and are sent to the server without any semantic check.[br] + This means that while [cmd:oper]OPER[/cmd] requires two parameters, KVIrc will not + complain if you send a single parameter only or use ten parameters.[br] + The exact parameter syntax/semantic checking is left to you.[br] + This also means that if some of these commands accept parameters with spaces, + it is left to you to add the leading ':' before the last parameter.[br] + You should refer to [doc]rfc2812[/doc] if any of these commands do not work properly for you.[br] + */ + + KVSCSC(rfc2812wrapper) + { + Q_UNUSED(__pSwitches); + + QString szText; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("text",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szText) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + QByteArray txt = KVSCSC_pConnection->encodeText(szText); + QByteArray cmd = KVSCSC_pConnection->encodeText(((KviKvsTreeNodeCommand *)(KVSCSC_pContext->defaultReportLocation()))->commandName()); + + if(!KVSCSC_pConnection->sendFmtData("%s %s",cmd.data(),txt.data() ? txt.data() : "")) + return KVSCSC_pContext->warningNoIrcConnection(); + + return true; + } +}; diff --git a/src/kvirc/kvs/KviKvsCoreSimpleCommands.h b/src/kvirc/kvs/KviKvsCoreSimpleCommands.h new file mode 100644 index 000000000..813d49337 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreSimpleCommands.h @@ -0,0 +1,140 @@ +#ifndef _KVI_KVS_CORESIMPLECOMMANDS_H_ +#define _KVI_KVS_CORESIMPLECOMMANDS_H_ +//============================================================================= +// +// File : KviKvsCoreSimpleCommands.h +// Creation date : Fri 31 Oct 2003 00:04:25 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviMainWindow.h" +#include "KviConsoleWindow.h" +#include "kvi_settings.h" +#include "KviKvsRunTimeContext.h" +#include "KviKvsVariantList.h" +#include "KviKvsSwitchList.h" +#include "KviKvsParameterProcessor.h" + + +#define KVSCSC(_name) bool _name(KviKvsRunTimeContext * __pContext,KviKvsVariantList * __pParams,KviKvsSwitchList * __pSwitches) + +#define KVSCSC_pContext __pContext +#define KVSCSC_pParams __pParams +#define KVSCSC_pSwitches __pSwitches + +#define KVSCSC_PARAMETER(a,b,c,d) KVS_PARAMETER(a,b,c,d) + +#define KVSCSC_PARAMETERS_BEGIN \ + KVS_PARAMETERS_BEGIN(parameter_format_list) + +#define KVSCSC_PARAMETERS_END \ + KVS_PARAMETERS_END \ + if(!KviKvsParameterProcessor::process(KVSCSC_pParams,KVSCSC_pContext,parameter_format_list))return false; + +#define KVSCSC_REQUIRE_CONNECTION \ + if(!KVSCSC_pContext->window()->context())return KVSCSC_pContext->errorNoIrcContext(); \ + if(!KVSCSC_pContext->window()->connection())return KVSCSC_pContext->warningNoIrcConnection(); + +#define KVSCSC_pWindow __pContext->window() +#define KVSCSC_pConnection __pContext->window()->connection() +#define KVSCSC_pIrcContext __pContext->context() + +namespace KviKvsCoreSimpleCommands +{ + // a_f + KVSCSC(away); + KVSCSC(back); + KVSCSC(ban); + KVSCSC(beep); + KVSCSC(buttonctl); + KVSCSC(cap); + KVSCSC(chanadmin); + KVSCSC(chanowner); + KVSCSC(ctcp); + KVSCSC(debugCKEYWORDWORKAROUND); + KVSCSC(dechanadmin); + KVSCSC(dechanowner); + KVSCSC(dehalfop); + KVSCSC(deleteCKEYWORDWORKAROUND); + KVSCSC(delpopupitem); + KVSCSC(deop); + KVSCSC(deuserop); + KVSCSC(devoice); + KVSCSC(echoprivmsg); + KVSCSC(echo); + KVSCSC(error); + KVSCSC(eval); + KVSCSC(eventctl); + KVSCSC(exit); + // g_l + KVSCSC(halfop); + KVSCSC(halt); + KVSCSC(help); + KVSCSC(host); + KVSCSC(inject); + KVSCSC(join); + KVSCSC(kick); + KVSCSC(killtimer); + KVSCSC(listtimers); + // m_r + KVSCSC(me); + KVSCSC(mode); + KVSCSC(nick); + KVSCSC(notice); + KVSCSC(op); + KVSCSC(openurl); + KVSCSC(option); + KVSCSC(parse); + KVSCSC(part); + KVSCSC(play); + KVSCSC(popup); + KVSCSC(privmsg); + KVSCSC(query); + KVSCSC(quit); + KVSCSC(raise); + KVSCSC(raw); + KVSCSC(returnCKEYWORDWORKAROUND); + KVSCSC(rebind); + KVSCSC(rfc2812wrapper); + KVSCSC(run); + // s_z + KVSCSC(say); + KVSCSC(server); + KVSCSC(setmenu); + KVSCSC(setreturn); + KVSCSC(squery); + KVSCSC(srand); + KVSCSC(topic); + KVSCSC(trload); + KVSCSC(trunload); + KVSCSC(unban); + KVSCSC(userop); + KVSCSC(voice); + KVSCSC(warning); + KVSCSC(who); + KVSCSC(whois); + KVSCSC(whowas); + + bool multipleModeCommand(KviKvsRunTimeContext * __pContext,KviKvsVariantList * __pParams,KviKvsSwitchList * __pSwitches,char plusminus,char flag); + + void init(); +}; + +#endif //!_KVI_KVS_CORESIMPLECOMMANDS_H_ diff --git a/src/kvirc/kvs/KviKvsCoreSimpleCommands_af.cpp b/src/kvirc/kvs/KviKvsCoreSimpleCommands_af.cpp new file mode 100644 index 000000000..95a3fcc17 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreSimpleCommands_af.cpp @@ -0,0 +1,1565 @@ +//============================================================================= +// +// File : KviKvsCoreSimpleCommands_af.cpp +// Creation date : Fri 31 Oct 2003 00:04:25 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCoreSimpleCommands.h" + + +#include "KviWindow.h" +#include "kvi_out.h" +#include "KviLocale.h" +#include "KviApplication.h" +#include "KviOptions.h" +#include "KviIrcView.h" // this is only for KviIrcView::NoTimestamp +#include "KviDebugWindow.h" +#include "KviConsoleWindow.h" +#include "KviScriptButton.h" +#include "KviIconManager.h" + +#include "KviKvsEventManager.h" +#include "KviKvsKernel.h" +#include "KviKvsObjectController.h" + +#ifdef COMPILE_X11_SUPPORT + #ifndef COMPILE_NO_X_BELL + #include "KviXlib.h" // XBell : THIS SHOULD BE INCLUDED AS LAST! + #include // for usleep(); + + #include + #define get_xdisplay QX11Info::display + #endif +#endif +#include "KviTalToolTip.h" + +// KviApplication.cpp +extern KviPointerHashTable * g_pGlobalWindowDict; + +namespace KviKvsCoreSimpleCommands +{ + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: admin + @type: + command + @title: + admin + @syntax: + admin [target server] + @short: + Requests the admin info from a server + @description: + Requests admin information from the specified server or the current server if no [target server] is specified.[br] + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RFC2821 wrapper + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: away + @type: + command + @title: + away + @syntax: + away [-a | --all-networks] [] + @short: + Puts you into 'away' state + @switches: + !sw: -a | --all-networks + Set away on all networks + @description: + Puts you into 'away' state in the connection associated to the + current [b]IRC context[/b].[br] This command is "server based"; + this means that the effects will be visible only after the + server has acknowledged the change.[br] + When you use this command, other people will know that you are + away from the keyboard, and they will know why you're not here.[br] + To return from being away you must use [cmd]back[/cmd].[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc].[br] + If no away reason is specified, the behaviour of this command depends from the value + of the option boolUseAwayMessage: if enabled, user will be set away using the default + away message; otherway, the user will return from a previous away state. + @examples: + [example] + away I'm asleep. Don't wake me up. + [/example] + */ + + KVSCSC(away) + { + QString szReason; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("reason",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szReason) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + if(szReason.isEmpty()) + { + if(KVI_OPTION_BOOL(KviOption_boolUseAwayMessage)) + { + //user want to use its default away message + szReason = KVI_OPTION_STRING(KviOption_stringAwayMessage); + } else { + //user want to /back + if(KVSCSC_pSwitches->find('a',"all-networks")) + { + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + while(KviWindow * wnd = it.current()) + { + if(wnd->type()==KVI_WINDOW_TYPE_CONSOLE) + { + KviConsole* pConsole=(KviConsole*)wnd; + if(pConsole->isConnected()) + pConsole->connection()->sendFmtData("AWAY"); + } + ++it; + } + } else { + KVSCSC_REQUIRE_CONNECTION + + if(!(KVSCSC_pConnection->sendFmtData("AWAY"))) + return KVSCSC_pContext->warningNoIrcConnection(); + } + return true; + } + } + + if(KVSCSC_pSwitches->find('a',"all-networks")) + { + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + while(KviWindow * wnd = it.current()) + { + if(wnd->type()==KVI_WINDOW_TYPE_CONSOLE) + { + KviConsole* pConsole=(KviConsole*)wnd; + if(pConsole->isConnected()) + pConsole->connection()->sendFmtData("AWAY :%s", + pConsole->connection()->encodeText(szReason).data() + ); + } + ++it; + } + } else { + QByteArray szR = KVSCSC_pConnection->encodeText(szReason); + if(!(KVSCSC_pConnection->sendFmtData("AWAY :%s",szR.data()))) + return KVSCSC_pContext->warningNoIrcConnection(); + } + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: back + @type: + command + @title: + back + @syntax: + back [-a | --all-networks] + @switches: + !sw: -a | --all-networks + Set back on all networks + @short: + Allows you to return from being away + @description: + Using this command makes you return from being [cmd]away[/cmd] in the connection associated to the + current [b]IRC context[/b].[br] This command is "server based"; + this means that the effects will be visible only after the + server has acknowledged the change.[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc].[br] + @examples: + [example] + back + [/example] + */ + + KVSCSC(back) + { + Q_UNUSED(__pParams); + + if(KVSCSC_pSwitches->find('a',"all-networks")) + { + KviPointerHashTableIterator it(*g_pGlobalWindowDict); + while(KviWindow * wnd = it.current()) + { + if(wnd->type()==KVI_WINDOW_TYPE_CONSOLE) + { + KviConsole* pConsole=(KviConsole*)wnd; + if(pConsole->isConnected()) + pConsole->connection()->sendFmtData("AWAY"); + } + ++it; + } + } else { + KVSCSC_REQUIRE_CONNECTION + + if(!(KVSCSC_pConnection->sendFmtData("AWAY"))) + return KVSCSC_pContext->warningNoIrcConnection(); + } + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: ban + @type: + command + @title: + ban + @syntax: + ban + @short: + Sets ban masks for the channel + @description: + Sets the ban masks specified in the , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of +b flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + ban Maxim,Gizmo!*@*,*!root@* + [/example] + @seealso: + [cmd]op[/cmd], + [cmd]deop[/cmd], + [cmd]voice[/cmd], + [cmd]devoice[/cmd], + [cmd]unban[/cmd] + */ + + KVSCSC(ban) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'+','b'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: beep + @type: + command + @title: + beep + @syntax: + beep [-p=] [-d=] [-s] [volume:uint] + @short: + Beep beep! + @switches: + !sw: -p= | --pitch= + Sets the bell to the specified pitch, if possible + !sw: -d= | --duration= + Sets the duration of the beep to milliseconds + !sw: -s | --synchronous + Causes KVIrc to wait for completion of the beeping before + returning from this command + @description: + Beeps (when possible :D)[br] + ...[br] + No, really...[br] + This command rings the bell on the keyboard (the PC speaker). + The volume must be in range 0-100; the default is 100.[br] + The pitch is specified in Hz and must be positive.[br] + The duration is specified in milliseconds.[br] + An invalid (or unspecified) pitch, volume or duration + makes KVIrc to use the default values set by the system.[br] + The duration of the bell is only indicative and + can be shortened by a subsequent call to /beep (that + will override the currently playing one).[br] + If the -s switch is specified the bell becomes synchronous: + KVIrc waits the bell to complete before continuing.[br] + The precision of the bell pitch, duration and + volume is strongly dependant on the system and the underlying hardware.[br][br] + On Windows, the bell is always synchronous and it is not + event granted that the bell will be a bell at all... you might + get the system default sound instead... + On some security-enchanced Windows variants (2008 Server, Seven and possibly + some 64-bit Vista builds) the access to the PC speaker + may be silently denied so don't be surprised too much if you don't hear any + sound at all on such systems...[br][br] + WARNING[br][br] + The main KVIrc thread is stopped while a synchronous bell is playing + so if you play long notes (duration > 100) the entire application may appear to + freeze for a while. Be careful :)[br] + @seealso: + [cmd]snd.play[/cmd] + */ + + KVSCSC(beep) + { + kvs_uint_t uVolume; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("volume",KVS_PT_UINT,KVS_PF_OPTIONAL,uVolume) + KVSCSC_PARAMETERS_END + + kvs_int_t pitch = -1; + kvs_int_t duration = -1; + + KviKvsVariant * pPitch = KVSCSC_pSwitches->find('p',"pitch"); + if(pPitch) + { + if(!pPitch->asInteger(pitch)) + { + KVSCSC_pContext->warning(__tr2qs_ctx("Invalid pitch value: using default","kvs")); + pitch = -1; + } + } + + KviKvsVariant * pDuration = KVSCSC_pSwitches->find('d',"duration"); + if(pDuration) + { + if(!pDuration->asInteger(duration)) + { + KVSCSC_pContext->warning(__tr2qs_ctx("Invalid duration value: using default","kvs")); + duration = -1; + } + } + + if((uVolume > 100) || (uVolume < 1))uVolume = 100; + +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + Beep(pitch,duration); +#else + #ifdef COMPILE_X11_SUPPORT + #ifndef COMPILE_NO_X_BELL + bool bSync = (KVSCSC_pSwitches->find('s',"sync") != 0); + + XKeyboardState st; + XKeyboardControl ctl; + + XGetKeyboardControl(get_xdisplay(),&st); + + unsigned long mask = KBBellPercent; + ctl.bell_percent = uVolume; + if(pitch >= 0) + { + ctl.bell_pitch = pitch; + mask |= KBBellPitch; + } + if(duration >= 0) + { + ctl.bell_duration = duration; + mask |= KBBellDuration; + } + XChangeKeyboardControl(get_xdisplay(),mask,&ctl); + + XBell(get_xdisplay(),100); + + if(bSync) + { + if(duration >= 0)usleep(duration * 1000); + else usleep(st.bell_duration * 1000); + } + + ctl.bell_pitch = st.bell_pitch; + ctl.bell_duration = st.bell_duration; + ctl.bell_percent = st.bell_percent; + + XChangeKeyboardControl(get_xdisplay(),mask,&ctl); + + #endif //COMPILE_NO_X_BELL + #endif //COMPILE_X11_SUPPORT +#endif + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: buttonctl + @title: + buttonctl + @type: + command + @short: + changes user definable buttons + @syntax: + buttonctl [-q] [parameter:string] + @switches: + !sw: -q | --quiet + Run quietly + @description: + Changes an existing user defined button.[br] + is ignored and present only for backward compatibility.[br] + is the name of the button.[br] + may be one of the constant strings "enable", "disable", "image", + "text".[br] + Operations "enable" and "disable" do not require the fourth [parameter] and have + the obvious meaning.[br] Operation "image" requires the [parameter] to be + a valid [doc:image_id]image_id[/doc] and sets the button image.[br] + Operation "text" requires the [parameter] (and in fact all the following ones) + to be a string containing the button text label.[br] + The constants may be abbreviated, even to the single letters 'e','d','i' and 't'.[br] + The -q switch causes the command to be quiet about errors and warnings.[br] + @seealso: + [cmd]button[/cmd] + */ + +//#warning "ALSO /HELP must NOT interpret the identifiers!" +//#warning "ALSO /DEBUG that relays to the DEBUG WINDOW" + + KVSCSC(buttonctl) + { + QString tbTypeUnused,tbName,tbOp,tbPar; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("type",KVS_PT_STRING,0,tbTypeUnused) + KVSCSC_PARAMETER("name",KVS_PT_STRING,0,tbName) + KVSCSC_PARAMETER("operation",KVS_PT_STRING,0,tbOp) + KVSCSC_PARAMETER("parameter",KVS_PT_STRING,KVS_PF_OPTIONAL,tbPar) + KVSCSC_PARAMETERS_END + + KviScriptUserButton * pButton = 0; + + if(!KVSCSC_pWindow->buttonContainer()) + { + if(!KVSCSC_pSwitches->find('q',"quiet"))KVSCSC_pContext->warning(__tr2qs_ctx("The specified window has no button containers","kvs")); + return true; + } + + //pButton = (KviScriptUserButton *)(KVSCSC_pWindow->buttonContainer())->child(tbName.toUtf8().data(),"KviWindowScriptButton"); + pButton = (KviScriptUserButton *)(KVSCSC_pWindow->buttonContainer())->findChild(tbName); + + if(!pButton) + { + if(!KVSCSC_pSwitches->find('q',"quiet"))KVSCSC_pContext->warning(__tr2qs_ctx("No button with type %Q named %Q","kvs"),&tbTypeUnused,&tbName); + return true; + } + QChar o; + if (tbOp.length() > 0) o=tbOp[0]; + else o=QChar('x'); + + // QChar o = tbOp.length() > 0 ? tbOp[0] : QChar('x'); + + switch(o.unicode()) + { + case 't': + KviTalToolTip::remove(pButton); + KviTalToolTip::add(pButton,tbPar); + pButton->setButtonText(tbPar); + break; + case 'i': + if(!tbPar.isEmpty()) + { + QPixmap * pix = g_pIconManager->getImage(tbPar); + if(pix) + { + pButton->setButtonPixmap(*pix); + } else { + if(!KVSCSC_pSwitches->find('q',"quiet"))KVSCSC_pContext->warning(__tr2qs_ctx("Can't find the icon '%Q'","kvs"),&tbPar); + } + } + break; + case 'e': + pButton->setEnabled(true); + break; + case 'd': + pButton->setEnabled(false); + break; + } + return true; + + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: cap + @type: + command + @title: + cap + @syntax: + cap [parameters:string] + @short: + Sends a CAP command + @description: + Sends a CAP command to the server.[br] + The may be one of LS,REQ,LIST and ACK as per CAP specification (Google for draft-mitchell-irc-capabilities-02). + The string usually contains a list of capabilities to be activated or deactivated (deactivation is triggered + by prepending a - prefix to the capability name.[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc] and actually works only on servers + that implement the CAP capability. + @examples: + [example] + cap LS + cap REQ identify-msg + cap LIST + cap REQ -identify-msg + [/example] + */ + + KVSCSC(cap) + { + Q_UNUSED(__pSwitches); + + QString szCommand,szParams; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("command",KVS_PT_NONEMPTYSTRING,0,szCommand) + KVSCSC_PARAMETER("parameters",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szParams) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + QByteArray szEncodedCommand = KVSCSC_pConnection->encodeText(szCommand); + QByteArray szEncodedParams = KVSCSC_pConnection->encodeText(szParams); + + if(szEncodedParams.isEmpty()) + { + if(!(KVSCSC_pConnection->sendFmtData("CAP %s",szEncodedCommand.data()))) + return KVSCSC_pContext->warningNoIrcConnection(); + } else { + if(!(KVSCSC_pConnection->sendFmtData("CAP %s :%s",szEncodedCommand.data(),szEncodedParams.data()))) + return KVSCSC_pContext->warningNoIrcConnection(); + } + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: chanadmin + @type: + command + @title: + chanadmin + @syntax: + chanadmin + @short: + Sets chan admin status from the specified users + @description: + Sets channel administrator status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of +a flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + chanadmin Pragma,Crocodile + [/example] + @seealso: + [cmd]chanowner[/cmd], [cmd]dechanowner[/cmd], [cmd]dechanadmin[/cmd], [cmd]op[/cmd], [cmd]deop[/cmd], [cmd]halfop[/cmd], [cmd]dehalfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd], [cmd]userop[/cmd], [cmd]deuserop[/cmd] + */ + + KVSCSC(chanadmin) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'+','a'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: chanowner + @type: + command + @title: + chanowner + @syntax: + chanowner + @short: + Sets chan owner status from the specified users + @description: + Sets channel owner status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of +q flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + chanowner Pragma,Crocodile + [/example] + @seealso: + [cmd]dechanowner[/cmd], [cmd]chanadmin[/cmd], [cmd]dechanadmin[/cmd], [cmd]op[/cmd], [cmd]deop[/cmd], [cmd]halfop[/cmd], [cmd]dehalfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd], [cmd]userop[/cmd], [cmd]deuserop[/cmd] + */ + + KVSCSC(chanowner) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'+','q'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: codepage + @type: + command + @title: + codepage + @syntax: + codepage + @short: + Tries to set the codepage on server + @description: + This is a not-widely implemented extension + that allows the user to set the codepage mapping + on server. + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RFC2821 wrapper + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: ctcp + @type: + command + @title: + ctcp + @syntax: + ctcp [-n] + @short: + Sends a CTCP message + @description: + Sends a CTCP message to the specified .[br] + The target may be a nickname, a channel, or a comma separated list of nicknames.[br] + The is a string containing the ctcp type followed by the ctcp parameters.[br] + For more info take a look at the [doc:ctcp_handling]ctcp protocol implementation notes[/doc].[br] + The CTCP message will be a request (sent through a PRIVMSG) unless the -n switch + specified: in that case it will be a reply (sent through a NOTICE).[br] + If is the single string "ping" then a trailing time string argument + is added in order to determine the round trip time when the ping reply comes back. + To override this behaviour simply specify your own time string parameter.[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc].[br] + @examples: + [example] + ctcp Pragma VERSION + [/example] + */ + + KVSCSC(ctcp) + { + QString szTarget,szCtcpData; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("target",KVS_PT_NONEMPTYSTRING,0,szTarget) + KVSCSC_PARAMETER("ctcp_data",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szCtcpData) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + if(KviQString::equalCI(szCtcpData,"PING")) + { + struct timeval tv; + kvi_gettimeofday(&tv,0); + KviQString::appendFormatted(szCtcpData," %d.%d",tv.tv_sec,tv.tv_usec); + } + + QByteArray szT = KVSCSC_pConnection->encodeText(szTarget); + QByteArray szD = KVSCSC_pConnection->encodeText(szCtcpData); + + if(!(KVSCSC_pConnection->sendFmtData("%s %s :%c%s%c", + KVSCSC_pSwitches->find('n',"notice") ? "NOTICE" : "PRIVMSG",szT.data(),0x01,szD.data(),0x01))) + return KVSCSC_pContext->warningNoIrcConnection(); + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: debug + @type: + command + @title: + debug + @syntax: + debug [-s] [-c] + @short: + Outputs text to the debug window + @switches: + !sw: -s | --system-console + Output to the system console instead of the debug window. + !sw: -c | --scriptcontext-name + Prepend the script's context name to the output. + @description: + If the -s switch is not specified then outputs the <text> to the debug window. + If the -s switch is used then the output is sent to the system console instead. + If the -c switch is used then the script's context name will be prepended to the output. + This is useful if you need to debug destructors of objects + or events that are triggered at kvirc shutdown. + @seealso: + */ + + KVSCSC(debugCKEYWORDWORKAROUND) + { + Q_UNUSED(__pContext); + + QString szAll; + KVSCSC_pParams->allAsString(szAll); + if(KVSCSC_pSwitches->find('c',"scriptcontext-name")) + szAll.prepend(__pContext->script()->name()+": "); + if(KVSCSC_pSwitches->find('s',"system-console")) + qDebug("%s",szAll.toUtf8().data()); + else { + KviWindow * pWnd = KviDebugWindow::getInstance(); + pWnd->outputNoFmt(KVI_OUT_NONE,szAll); + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: dechanadmin + @type: + command + @title: + dechanadmin + @syntax: + dechanadmin + @short: + Removes chan admin status from the specified users + @description: + Removes channel admin status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of -a flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + dechanadmin Pragma,Crocodile + [/example] + @seealso: + [cmd]chanowner[/cmd], [cmd]dechanowner[/cmd], [cmd]chanadmin[/cmd], [cmd]op[/cmd], [cmd]deop[/cmd], [cmd]halfop[/cmd], [cmd]dehalfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd], [cmd]userop[/cmd], [cmd]deuserop[/cmd] + */ + + KVSCSC(dechanadmin) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'-','a'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: dechanowner + @type: + command + @title: + dechanowner + @syntax: + dechanowner + @short: + Removes chan owner status from the specified users + @description: + Removes channel owner status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of -q flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + dechanowner Pragma,Crocodile + [/example] + @seealso: + [cmd]chanowner[/cmd], [cmd]chanadmin[/cmd], [cmd]dechanadmin[/cmd], [cmd]op[/cmd], [cmd]deop[/cmd], [cmd]halfop[/cmd], [cmd]dehalfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd], [cmd]userop[/cmd], [cmd]deuserop[/cmd] + */ + + KVSCSC(dechanowner) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'-','q'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: dehalfop + @type: + command + @title: + dehalfop + @syntax: + dehalfop + @short: + Removes half op status from the specified users + @description: + Removes channel half operator status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of -h flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + dehalfop Pragma,Crocodile + [/example] + @seealso: + [cmd]op[/cmd], [cmd]deop[/cmd], [cmd]halfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd] + */ + + KVSCSC(dehalfop) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'-','h'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: delete + @type: + command + @title: + delete + @syntax: + delete [-q] [-i] + @short: + Destroys an object + @switches: + !sw: -q | --quiet + Causes the command to run quietly + !sw: -i | --immediate + Causes the object to be destroyed immediately + instead of simply scheduling its later deletion. + @description: + Schedules for destruction the object designed by . + This command is internally aliased to [cmd]destroy[/cmd]. + Please note that the object is NOT immediately destroyed: + it will be destroyed when KVIrc returns to the main event loop, + so after the current script code part has been executed. + This behaviour makes the object destruction safe in any + part of the script, but may lead to problems when + using signals and slots.[br] + For example, when you delete an object that emits some signals, + the signals may be still emitted after the delete call. + You have to disconnect the signals explicitly if you don't want it + to happen.[br] + Alternatively you can use the -i switch: it causes the object + to be destructed immediately but is intrinsicly unsafe: + in complex script scenarios it may lead to a SIGSEGV; + usually when called from one of the deleted object function + handlers, or from a slot connected to one of the deleted object + signals. Well, it actually does not SIGSEGV, but I can't guarantee it; + so, if use the -i switch, test your script 10 times before releasing it. + The -q switch causes the command to run a bit more silently: it still + complains if the parameter passed is not an object reference, but + it fails silently if the reference just points to an inexistant object (or is null). + @examples: + [example] + [/example] + */ + + /* + @doc: destroy + @type: + command + @title: + destroy + @syntax: + destroy [-q] [-i] + @short: + Destroys an object + @description: + This is a builtin alias for the command [cmd]delete[/cmd] + */ + + KVSCSC(deleteCKEYWORDWORKAROUND) + { + kvs_hobject_t hObject; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("objectHandle",KVS_PT_HOBJECT,0,hObject) + KVSCSC_PARAMETERS_END + if(hObject == (kvs_hobject_t)0) + { + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("Can't delete a null object reference","kvs")); + } else { + KviKvsObject * o = KviKvsKernel::instance()->objectController()->lookupObject(hObject); + if(!o) + { + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("Can't delete an inexistant object","kvs")); + } else { + if(KVSCSC_pSwitches->find('i',"immediate")) + o->dieNow(); + else + o->die(); + } + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: delpopupitem + @type: + command + @title: + delpopupitem + @syntax: + delpopupitem [-d] [-q] + @short: + Deletes an item from a popup + @switches: + !sw: -q | --quiet + Run quietly + !sw: -d | --deep + Search the whole popup tree instead of only the first level + @description: + This is an internal alias for [cmd]popup.delitem[/cmd].[br] + This function is deprecated and its use is discouraged. + @seealso: + [cmd]popup.delitem[/cmd] + */ + + KVSCSC(delpopupitem) + { + QString szParams; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("params",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szParams) + KVSCSC_PARAMETERS_END + + // We just alias the popup.delitem function + QString szSwitches=""; + if(KVSCSC_pSwitches->find('d',"deep"))szSwitches.append("-d "); + if(KVSCSC_pSwitches->find('q',"quiet"))szSwitches.append("-q "); + + KviQString::escapeKvs(&szParams); + KviKvsScript s("delpopupitem","popup.delitem " + szSwitches + szParams); + s.run(KVSCSC_pContext->window()); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: deop + @type: + command + @title: + deop + @syntax: + deop + @short: + Removes chanop status from the specified users + @description: + Removes channel operator status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of -o flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + deop Pragma,Crocodile + [/example] + @seealso: + [cmd]chanowner[/cmd], [cmd]dechanowner[/cmd], [cmd]chanadmin[/cmd], [cmd]dechanadmin[/cmd], [cmd]op[/cmd], [cmd]halfop[/cmd], [cmd]dehalfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd], [cmd]userop[/cmd], [cmd]deuserop[/cmd] + */ + + KVSCSC(deop) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'-','o'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: deuserop + @type: + command + @title: + deuserop + @syntax: + deuserop + @short: + Removes user op status from the specified users + @description: + Removes channel user operator status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of -u flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + deuserop Pragma,Crocodile + [/example] + @seealso: + [cmd]chanowner[/cmd], [cmd]dechanowner[/cmd], [cmd]chanadmin[/cmd], [cmd]dechanadmin[/cmd], [cmd]op[/cmd], [cmd]deop[/cmd], [cmd]halfop[/cmd], [cmd]dehalfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd], [cmd]userop[/cmd] + */ + + KVSCSC(deuserop) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'-','u'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: devoice + @type: + command + @title: + devoice + @syntax: + devoice + @short: + Removes voice flag for the specified users + @description: + Removes the voice flag for the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of -v flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + devoice Pragma,Crocodile + [/example] + @seealso: + [cmd]chanowner[/cmd], [cmd]dechanowner[/cmd], [cmd]chanadmin[/cmd], [cmd]dechanadmin[/cmd], [cmd]op[/cmd], [cmd]deop[/cmd], [cmd]halfop[/cmd], [cmd]dehalfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd], [cmd]userop[/cmd] + */ + + KVSCSC(devoice) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'-','v'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: die + @type: + command + @title: + die + @syntax: + die + @short: + Prints an error message and stops the script + @description: + Prints an error message and stops the current script + This command is equivalent to [cmd]error[/cmd] + */ + // Internally aliased to error + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: echo + @type: + command + @title: + echo + @syntax: + echo [-d] [-w=] [-i=] [-n] + @short: + Outputs text to a KVirc window + @switches: + !sw: -w= | --window= + Causes the output to be redirected to the window specified by <window_id> + !sw: -i= | --color-set= + Causes the message to use the specified icon scheme (icon and colors). + !sw: -n | --no-timestamp + Disables the message timestamping + !sw: -d | --debug + Send the output to the debug window (takes precedence over -w) + @description: + Outputs the <text> to the current window.[br] + If the 'w' switch is present, outputs the <text> + to the specified window instead of the current one. + The parameter is the [doc:window_naming_conventions]global ID[/doc] of the window + that has to be used.[br] + If the 'i' switch is given, it uses the specified + icon scheme (icon and colors), otherwise it uses + the default one (0).[br] + If the -d switch is used then the output is sent to a special + window called "Debug" (the window is created if not existing yet). + This is useful for script debugging purposes (you get the output + in Debug regardless of the window that the executed command is attacched to). + The KVIrc view widgets support clickable links that can be realized by using special [doc:escape_sequences]escape sequences[/doc].[br] + The 'n' switch disables timestamping so you can output your own timestamp + or not timestamp at all.[br] + @examples: + [example] + echo Hey! this is my first echo test! + echo -i=[fnc]$msgtype[/fnc](parsererror) this has the colors of the parser error messages + [/example] + @seealso: + [fnc]$window[/fnc], + [fnc]$msgtype[/fnc], + [doc:window_naming_conventions]window naming conventions documentation[/doc] + */ + + KVSCSC(echo) + { + QString szAll; + KVSCSC_pParams->allAsString(szAll); + + kvs_int_t iMsgType = KVI_OUT_NONE; + KviWindow * pWnd = KVSCSC_pContext->window(); + + if(!KVSCSC_pSwitches->isEmpty()) + { + KviKvsVariant * v; + if((v = KVSCSC_pSwitches->find('w',"window"))) + { + QString szWnd; + v->asString(szWnd); + //#warning "FIXME: the window database is not unicode! (we even could keep integer window id's at this point!)" + pWnd = g_pApp->findWindow(szWnd.toUtf8().data()); + if(!pWnd) + { + KVSCSC_pContext->warning(__tr2qs_ctx("The argument of the -w switch did not evaluate to a valid window id: using default","kvs")); + pWnd = KVSCSC_pContext->window(); + } + } + + if((v = KVSCSC_pSwitches->find('i',"color-set"))) + { + if(!v->asInteger(iMsgType)) + { + KVSCSC_pContext->warning(__tr2qs_ctx("The argument of the i switch did not evaluate to a number: using default","kvs")); + iMsgType = KVI_OUT_NONE; + } else { + iMsgType = iMsgType % KVI_NUM_MSGTYPE_OPTIONS; + } + } + + if(KVSCSC_pSwitches->find('d',"debug")) + { + pWnd = KviDebugWindow::getInstance(); + } + } + + int iFlags = KVSCSC_pSwitches->find('n',"no-timestamp") ? KviIrcView::NoTimestamp : 0; + pWnd->outputNoFmt(iMsgType,szAll,iFlags); + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: echoprivmsg + @type: + command + @title: + echoprivmsg + @syntax: + echoprivmsg [switches] + @short: + Outputs text to a KVIrc window + @switches: + !sw: -p[=] | --prefix[=] + The message is printed with the specified custom nickname prefix. + If is omitted then an empty string is assumed. + !sw: -s[=] | --suffix[=] + The message is printed with the specified custom nickname suffix. + If is omitted then an empty string is assumed. + !sw: -w= | --window= + The message is printed to the window specified by [doc:window_naming_conventions]window_id[/doc] + !sw: -i= | --color-set= + Causes the message to use the specified icon scheme (icon and colors). + !sw: -n | --no-highlighting + Do not apply the highlighting rules + !sw: -x | --no-notifier + Never cause the notifier window to pop up + !sw: -f | --no-flashing + Never cause the window taskbar entry to flash (this works only on some platforms) + @description: + Outputs a to the current window in the privmsg format.[br] + The and parameters are formatted + as specified by the user preferences (for example + the nick may use smart colorisation). + If you don't know the username and host then just use '*' for + that parameters. + The message will also get the highlighting rules applied. + If the 'w' switch is present, outputs + to the specified window instead of the current one. + The parameter is the [doc:window_naming_conventions]global ID[/doc] of the window + that has to be used.[br] + Please note that this is not the same as the standard + [doc:command_rebinding]-r rebinding switch[/doc]: + -w causes the specified window to be used only for output, + but the command parameters are evaluated in the current window.[br] + If the 'i' switch is given, it uses the specified + icon scheme (icon and colors), otherwise it uses + the default one (0).[br] + If the -n switch is present then the highlighting rules + are not applied.[br] + If the -x switch is present then the message will never cause + the notifier window to be popped up.[br] + If the -f switch is present then the message will never cause + the system taskbar to flash.[br] + Actually -x and -f have a sense only if highlighting is used and thus -n is not present.[br] + For more information about the icon/color schemes see [fnc]$msgtype[/fnc]. + The KVIrc view widgets support clickable sockets that can be realized by using special [doc:escape_sequences]escape sequences[/doc].[br] + @examples: + [example] + echoprivmsg Test * * This is a test message + echoprivmsg -i=$msgtype(ChanPrivmsgCrypted) Pragma pragma staff.kvirc.net Hi people! :) + [/example] + @seealso: + [fnc]$window[/fnc], + [fnc]$window.caption[/fnc], + [fnc]$msgtype[/fnc], + [cmd]echo[/cmd], + [doc:window_naming_conventions]Window Naming Conventions[/doc] + */ + + KVSCSC(echoprivmsg) + { + QString szNick,szUser,szHost,szText; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("nick",KVS_PT_NONEMPTYSTRING,0,szNick) + KVSCSC_PARAMETER("user",KVS_PT_STRING,0,szUser) + KVSCSC_PARAMETER("host",KVS_PT_STRING,0,szHost) + KVSCSC_PARAMETER("text",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szText) + KVSCSC_PARAMETERS_END + + int type = KVI_OUT_NONE; + KviWindow * pWnd = KVSCSC_pWindow; + KviConsole * pConsole = pWnd->console(); + if(!pConsole)pConsole = g_pApp->activeConsole(); + + KviKvsVariant * v; + + if( (v = KVSCSC_pSwitches->find('i',"color-set")) ) + { + kvs_int_t msgType; + if(v->asInteger(msgType)) + { + if(msgType < 0)msgType = -msgType; + type = (int)(msgType % KVI_NUM_MSGTYPE_OPTIONS); + } else KVSCSC_pContext->warning(__tr2qs_ctx("Invalid color-set specification, using default","kvs")); + } + + if( (v = KVSCSC_pSwitches->find('w',"window")) ) + { + QString szWin; + v->asString(szWin); + pWnd = g_pApp->findWindow(szWin); + if(!pWnd) + { + KVSCSC_pContext->warning(__tr2qs_ctx("Window '%Q' not found, using current one","kvs"),&szWin); + pWnd = KVSCSC_pWindow; + } + } + + QString szPrefix,szSuffix; + bool bPrefix = false; + bool bSuffix = false; + + if( (v = KVSCSC_pSwitches->find('p',"prefix")) ) + { + v->asString(szPrefix); + bPrefix = true; + } + if( (v = KVSCSC_pSwitches->find('s',"suffix")) ) + { + v->asString(szSuffix); + bSuffix = true; + } + + int iFlags = 0; + if(KVSCSC_pSwitches->find('n',"no-highlighting"))iFlags |= KviConsole::NoHighlighting; + if(KVSCSC_pSwitches->find('f',"no-flashing"))iFlags |= KviConsole::NoWindowFlashing; + if(KVSCSC_pSwitches->find('x',"no-notifier"))iFlags |= KviConsole::NoNotifier; + + pConsole->outputPrivmsg(pWnd,type, + szNick,szUser,szHost,szText, + iFlags, + bPrefix ? szPrefix : QString(),bSuffix ? szSuffix : QString()); + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: error + @type: + command + @title: + error + @syntax: + error + @short: + Prints an error message and stops the script + @description: + Prints an error message and stops the current script + This command is equivalent to [cmd]die[/cmd] + @seealso: + [cmd]warning[/cmd] + */ + + KVSCSC(error) + { + Q_UNUSED(__pSwitches); + + QString szAll; + KVSCSC_pParams->allAsString(szAll); + KVSCSC_pContext->error("%Q",&szAll); + return false; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: eval + @type: + command + @title: + eval + @syntax: + eval [-q] [-r=] + @switches: + !sw: -q | --quiet + Disable any error output + !sw: -f | --force + Continue execution even if fails with an error + @short: + Change the behaviour of a set of commands + @description: + This command is useful to execute variable command sequences.[br] + is first evaluated as a normal parameter (thus identifiers + and variables are substituted) then the evaluated string is executed + as a command sequence.[br] + -q causes eval to run quietly and don't display any errors in the inner command.[br] + -f causes eval to ignore the errors inside and continue execution.[br] + This command may be used to rebind the to a specified window. + shares the local variables with this command scope so you + can easily exchange data with it. + Remember that is still a normal parameter and it must be + enclosed in quotes if you want it to be a complex command sequence. + eval propagates the return value.[br] + [br] + [b]WARNING: If some part of the comes from external input you MUST + sanitize it by using [fnc]$escape[/fnc]() in order to avoid command injection.[/b] + Note that nicknames, usernames, hostnames, channel names and any kind of text that + isn't generated under your control may contain malicious code. For instance, if you + try to eval the string built by concatenating "echo" and the result of [fnc]$channel.name[/fnc] + inside a channel named "#test;quit" (yes, that's a valid channel name) you'll obtain + a disconnection as a side effect. To avoid this you need to use [fnc]$escape[/fnc]() around + [fnc]$chan.name[/fnc]. + @examples: + [example] + [comment]# evaluate a variable command[/comment] + [cmd]if[/cmd](%somecondition)%tmp = "echo yeah" + else %tmp = "echo -i=10 yeah" + eval %tmp + [comment]# Rebind the command to the #linux channel to get the user list[/comment] + eval -r=[fnc]$channel[/fnc](#linux) "%Nicks[]=$chan.array;" + [comment]# A nice alias that allows iterating commands through all the consoles[/comment] + [comment]# This is by LatinSuD :)[/comment] + [cmd]alias[/cmd](iterate) + { + %ctxt[]=[fnc]$window.list[/fnc](console,all) + [cmd]for[/cmd](%i=0;%i<%ctxt[]#;%i++) + { + [cmd]eval[/cmd] -r=%ctxt[%i] $0- + } + } + iterate [cmd]echo[/cmd] Hi ppl! :) + [comment]# A little bit shorter (but less "colorful") version might be...[/comment] + [cmd]alias[/cmd](iterate) + { + [cmd]foreach[/cmd](%x,[fnc]$window.list[/fnc](console,all)) + [cmd]eval[/cmd] -r=%x $0-; + } + iterate [cmd]echo[/cmd] Hi again! + [comment]# Evaluate a command block[/comment] + eval "{ echo First command!; echo Second command!; }" + [/example] + @seealso: + [fnc]$escape[/fnc] + */ + + KVSCSC(eval) + { + QString szCommands; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("commands",KVS_PT_STRING,KVS_PF_APPENDREMAINING,szCommands) + KVSCSC_PARAMETERS_END + + KviKvsScript s("eval::inner",szCommands); + int iRunFlags = 0; + if(KVSCSC_pContext->reportingDisabled() || KVSCSC_pSwitches->find('q',"quiet")) + iRunFlags |= KviKvsScript::Quiet; + bool bRet = s.run(KVSCSC_pContext,iRunFlags) ? true : false; + if(!bRet) + { + if(!KVSCSC_pSwitches->find('f',"force")) + return false; + KVSCSC_pContext->clearError(); + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: eventctl + @title: + eventctl + @type: + command + @short: + Controls the execution of event handlers + @syntax: + eventctl [-u] [-e] [-d] [-q] [parameters] + @switches: + !sw: -u | --unregister + Unregisters the specified handler + !sw: -e | --enable + Enables the specified handler + !sw: -d | --disable + Disables the specified handler + !sw: -q | --quiet + Do not print any warnings + @description: + Performs control actions on the handler for + the event . + Without any switch it triggers the handler for testing purposes, + eventually passing [parameters].[br] + With the -u switch the handler is unregistered.[br] + With the -d swtich is is disabled (so it is never executed) + and with -e is enabled again.[br] + The may be one of the kvirc-builtin event names + or a numeric code (from 0 to 999) of a raw server message.[br] + @seealso: + [cmd]event[/cmd] + */ + KVSCSC(eventctl) + { + QString szEventName,szHandlerName; + KviKvsVariantList vList; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("event_name",KVS_PT_NONEMPTYSTRING,0,szEventName) + KVSCSC_PARAMETER("handler_name",KVS_PT_NONEMPTYSTRING,0,szHandlerName) + KVSCSC_PARAMETER("parameters",KVS_PT_VARIANTLIST,KVS_PF_OPTIONAL,vList) + KVSCSC_PARAMETERS_END + + bool bOk; + int iNumber = szEventName.toInt(&bOk); + bool bIsRaw = (bOk && (iNumber >= 0) && (iNumber < 1000)); + + if(bIsRaw) + { + if(!KviKvsEventManager::instance()->isValidRawEvent(iNumber)) + { + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("No such event (%Q)","kvs"),&szEventName); + return true; + } + } else { + iNumber = KviKvsEventManager::instance()->findAppEventIndexByName(szEventName); + if(!KviKvsEventManager::instance()->isValidAppEvent(iNumber)) + { + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("No such event (%Q)","kvs"),&szEventName); + return true; + } + } + + if(KVSCSC_pSwitches->find('u',"unregister")) + { + // unregister it + if(bIsRaw) + { + if(!KviKvsEventManager::instance()->removeScriptRawHandler(iNumber,szHandlerName)) + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("No handler '%Q' for raw numeric event '%d'","kvs"),&szHandlerName,iNumber); + } else { + if(!KviKvsEventManager::instance()->removeScriptAppHandler(iNumber,szHandlerName)) + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("No handler '%Q' for event '%Q'","kvs"),&szHandlerName,&szEventName); + } + } else if(KVSCSC_pSwitches->find('e',"enable") || KVSCSC_pSwitches->find('d',"disable")) + { + // enable it + if(bIsRaw) + { + if(!KviKvsEventManager::instance()->enableScriptRawHandler(iNumber,szHandlerName,KVSCSC_pSwitches->find('e',"enable"))) + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("No handler '%Q' for raw numeric event '%d'","kvs"),&szHandlerName,iNumber); + } else { + if(!KviKvsEventManager::instance()->enableScriptAppHandler(iNumber,szHandlerName,KVSCSC_pSwitches->find('e',"enable"))) + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("No handler '%Q' for event '%Q'","kvs"),&szHandlerName,&szEventName); + } + } else { + // trigger it + KviKvsScriptEventHandler * h; + QString code; + + if(bIsRaw) + { + h = KviKvsEventManager::instance()->findScriptRawHandler(iNumber,szHandlerName); + } else { + h = KviKvsEventManager::instance()->findScriptAppHandler(iNumber,szHandlerName); + } + + if(h) + { + KviKvsScript * s = h->script(); + KviKvsScript copy(*s); + KviKvsVariant retVal; + copy.run(KVSCSC_pWindow,&vList,0,KviKvsScript::PreserveParams); + } else { + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("No handler '%Q' for event '%Q'","kvs"),&szHandlerName,&szEventName); + } + } + + return true; + } + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: exit + @type: + command + @title: + exit + @syntax: + exit + @switches: + @short: + Closes KVIrc + @description: + It closes KVirc application + */ + + KVSCSC(exit) + { + Q_UNUSED(__pSwitches); + Q_UNUSED(__pContext); + Q_UNUSED(__pParams); + + g_pApp->quit(); + return true; + } + +}; diff --git a/src/kvirc/kvs/KviKvsCoreSimpleCommands_gl.cpp b/src/kvirc/kvs/KviKvsCoreSimpleCommands_gl.cpp new file mode 100644 index 000000000..03a39089d --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreSimpleCommands_gl.cpp @@ -0,0 +1,694 @@ +//============================================================================= +// +// File : KviKvsCoreSimpleCommands_gl.cpp +// Creation date : Fri 31 Oct 2003 00:04:25 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCoreSimpleCommands.h" +#include "KviKvsTimerManager.h" +#include "KviKvsAsyncDnsOperation.h" +#include "KviKvsScript.h" +#include "KviFileUtils.h" +#include "KviIrcConnection.h" +#include "KviIrcConnectionServerInfo.h" +#include "KviLocale.h" +#include "kvi_out.h" + +namespace KviKvsCoreSimpleCommands +{ + /* + @doc: halfop + @type: + command + @title: + halfop + @syntax: + halfop + @short: + Sets halfop status to the specified users + @description: + Sets channel half operator status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of +h flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + halfop Pragma,Crocodile + [/example] + @seealso: + [cmd]dehalfop[/cmd], [cmd]op[/cmd], [cmd]deop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd] + */ + + KVSCSC(halfop) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'+','h'); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: halt + @type: + command + @title: + halt + @syntax: + halt + @short: + Stops the execution of the current script + @description: + Stops the execution of the current script.[br] + Note that this is different from [cmd]return[/cmd]: halt doesn't + set the return value (use [cmd]setreturn[/cmd] for that) and + in the event handlers this command may have additional semantics: + refer to the specific event documentation for more info.[br] + In fact, this command should be used [b]only[/b] in the event handlers, + use [cmd]return[/cmd] in any other context.[br] + */ + + KVSCSC(halt) + { + Q_UNUSED(__pSwitches); + Q_UNUSED(__pParams); + + KVSCSC_pContext->setHaltCalled(); + return false; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: help + @type: + command + @title: + help + @syntax: + help.open [-n] [-m] [document: string] + @short: + Shows a help document + @description: + Finds the first available help browser in the current frame + then opens the specified [document]. + If no [document] is specified it the documentation index is shown. + If no help browser is available, a new one is created. + [document] can be an absolute path or a relative one: in this case + the document is searched in the KVIrc documentation directory.[br] + If no document has been found using absolute and relative paths, + the first document matching [document] in the help search database + is shown. Otherway, an error page is displayed.[br/] + The help browser has limited html browsing capabilities: you can + use it to view simple html files on your filesystem.[br] + This command is an alias for the [cmd]help.open[cmd] command exported + by the "help" module. + @switches: + !sw: -m | --mdi + The created browser is a MDI window, + otherwise it is a static window. + !sw: -n | --new + The window creation is forced even + if there are other help browsers already open.[br] + @seealso: + [cmd]help.open[/cmd] + @examples: + [example] + help /home/pragma/myfile.html //absolute path + help cmd_snd.play.html //relative path + help "Binding operator" //keyword search, remember quoting + help OnNickServAuth //keyword search for an event + help \$my.user //keyword search, $ needs to be escaped + [/example] + */ + + KVSCSC(help) + { + QString szParams; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("params",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szParams) + KVSCSC_PARAMETERS_END + + // We just alias the help.open function + QString szSwitches=""; + if(KVSCSC_pSwitches->find('m',"mdi"))szSwitches.append("-m "); + if(KVSCSC_pSwitches->find('n',"new"))szSwitches.append("-n "); + + if(szParams.endsWith("()")) + szParams.chop(2); + + KviQString::escapeKvs(&szParams); + KviKvsScript s("help","help.open " + szSwitches + szParams); + s.run(KVSCSC_pContext->window()); + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: host + @type: + command + @title: + host + @syntax: + host [-i] [-a] + @short: + DNS lookup + @switches: + !sw: --ipv6 | -i + Causes the command to run in IPv6 mode + !sw: --any | -a + Causes the command to run in unspecified mode and lookup both IPv4 and IPv6 addresses + @description: + Starts a DNS lookup for the (hostname) and prints + the results in the current window.[br] + The -i switch causes the command to execute + in IPv6 mode (and lookup ONLY IPv6 hosts!).[br] + The -a switch causes the command to run in "unspecified" mode + and return any available address: IPv4 or Ipv6.[br] + This command also performs reverse lookups (if you pass an IP address as ).[br] + @examples: + [example] + host localhost + host irc.flashnet.it + host -i irc.flashnet.it + host -i A0E0:FFFF:::1010:1111:E0E0:A0A0 + host -a 127.0.0.1 + host 255.41.31.23 + host -a irc.stealth.net + [/example] + @seealso: + [cmd]ahost[/cmd] + */ + + KVSCSC(host) + { + QString szQuery; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("dnsquery",KVS_PT_NONEMPTYSTRING,0,szQuery) + KVSCSC_PARAMETERS_END + + KviDnsResolver::QueryType queryType = KviDnsResolver::IPv4; + if(KVSCSC_pSwitches->find('i',"ipv6"))queryType = KviDnsResolver::IPv6; + if(KVSCSC_pSwitches->find('a',"any"))queryType = KviDnsResolver::Any; + + new KviKvsAsyncDnsOperation( + KVSCSC_pContext->window(), + szQuery, + queryType); + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: include + @type: + command + @title: + include + @syntax: + include [-q] [-e] [-f] [-r] [ [ [...]]] + @short: + A builtin alias for parse + @description: + This is a builtin alias for [cmd]parse[/cmd] that gives scripts a "more C-ish" look :) + @seealso: + [cmd]parse[/cmd] + */ + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: info + @type: + command + @title: + info + @syntax: + info [target server] + @short: + Requests the server daemon info from a server + @description: + Requests server daemon information from the specified server or the current server if no [target server] is specified.[br] + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RFC2821 wrapper + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: inject + @type: + command + @title: + inject + @syntax: + inject + @short: + Injects to the socket + @switches: + !sw: -q | --quiet + Does not print injection warnings on the console + @description: + Injects to the socket as if it comes from the server.[br] + It's useful to test scripts without spamming or flooding the server.[br] + Each injection causes a warning to be displayed in the console window and in + the socketspy window (if open). The -q switch suppresses only the console warnings. + @examples: + [example] + [comment]Injects the string as we were sending a query message[/comment][br] + inject :foo!bar@foobar PRIVMSG HelLViS69 :message + [/example] + */ + KVSCSC(inject) + { + Q_UNUSED(__pSwitches); + + QString szText; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("text",KVS_PT_NONEMPTYSTRING,KVS_PF_APPENDREMAINING,szText) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + if(!((KVSCSC_pWindow->type() == KVI_WINDOW_TYPE_CHANNEL) || + (KVSCSC_pWindow->type() == KVI_WINDOW_TYPE_QUERY) || + (KVSCSC_pWindow->type() == KVI_WINDOW_TYPE_CONSOLE))) + { + KVSCSC_pContext->warning(__tr2qs_ctx("The current window is not a channel, a query or a console","kvs")); + return false; + } + + // Get the active window where we ran the command + KviWindow * pActive = KVSCSC_pWindow->context()->console()->activeWindow(); + + // Get the list of open windows + KviPointerList * pList = KVSCSC_pWindow->frame()->windowList(); + + // Scan the windows + for(KviWindow * pWnd = pList->first(); pWnd; pWnd = pList->next()) + { + // Search for the right socketspy + if( + (pWnd->type() == KVI_WINDOW_TYPE_SOCKETSPY) && + (pWnd->context() == pActive->context()) + ) + { + // Ok, found... send the warning + pWnd->outputNoFmt(KVI_OUT_SOCKETMESSAGE,__tr2qs_ctx("The following string was injected by the user:","kvs")); + break; + } + } + + // Send the warning to the right console + if(!KVSCSC_pSwitches->find('q',"quiet")) + pActive->console()->output(KVI_WINDOW_TYPE_SOCKETSPY,__tr2qs_ctx("Injected incoming data: %1","kvs").arg(szText)); + + // Encode the text for the socket + QByteArray szT = KVSCSC_pConnection->encodeText(szText); + + // Send the converted text to the socket + KVSCSC_pConnection->incomingMessage(szT.constData()); + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: invite + @type: + command + @title: + invite + @syntax: + invite + @short: + Invites an user to a channel + @description: + Invites the specified user to the .[br] + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RCF2821 wrapper + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: join + @type: + command + @title: + join + @syntax: + join [key list] + @short: + Joins the specified channels + @description: + Joins the channels specified in by using the + optional keys in the [key list].[br] + This command is "server based"; you will see its results only + after the server acknowledges it.[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc].[br] + @examples: + [example] + join #kvirc + join #linux-it,#xmms,#kde linus + [/example] + */ + + KVSCSC(join) + { + Q_UNUSED(__pSwitches); + + QString szChans,szKeys; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("chans",KVS_PT_NONEMPTYSTRING,0,szChans) + KVSCSC_PARAMETER("keys",KVS_PT_STRING,KVS_PF_OPTIONAL,szKeys) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + QStringList slChans = szChans.split(",",QString::SkipEmptyParts); + + QString szChanTypes = KVSCSC_pConnection->serverInfo()->supportedChannelTypes(); + for(QStringList::Iterator it=slChans.begin();it != slChans.end();++it) + { + if(!(*it).isEmpty()) + { + bool bFound = false; + int id = 0; + QChar f = (*it)[0]; + while((id < szChanTypes.length()) && !bFound) + { + if(f == szChanTypes[id])bFound = true; + id++; + } + if(!bFound) + (*it).prepend("#"); + } + } + + szChans = slChans.join(","); + QByteArray szEncodedChans = KVSCSC_pConnection->encodeText(szChans); + + if(szKeys.isEmpty()) + { + if(!(KVSCSC_pConnection->sendFmtData("JOIN %s",szEncodedChans.data()))) + return KVSCSC_pContext->warningNoIrcConnection(); + } else { + QByteArray szEncodedKeys = KVSCSC_pConnection->encodeText(szKeys); + if(!(KVSCSC_pConnection->sendFmtData("JOIN %s %s",szEncodedChans.data(),szEncodedKeys.data()))) + return KVSCSC_pContext->warningNoIrcConnection(); + } + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: kick + @type: + command + @title: + kick + @syntax: + kick [reason:string] + @short: + Kicks an user from a channel + @description: + Kicks the specified from the current channel.[br] + This command is a simple wrapper over the IRC KICK command. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + kick Pragma Go coding in Pascal! + [/example] + */ + + KVSCSC(kick) + { + Q_UNUSED(__pSwitches); + + QString szUser; + QString szReason; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("user",KVS_PT_NONEMPTYSTRING,0,szUser) + KVSCSC_PARAMETER("reason",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szReason) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + if(KVSCSC_pWindow->type() != KVI_WINDOW_TYPE_CHANNEL) + { + KVSCSC_pContext->warning(__tr2qs_ctx("The current window is not a channel","kvs")); + return false; + } + + QByteArray szC = KVSCSC_pConnection->encodeText(KVSCSC_pWindow->target()); + QByteArray szU = KVSCSC_pConnection->encodeText(szUser); + QByteArray szR = KVSCSC_pConnection->encodeText(szReason); + + if(szR.isEmpty()) + { + if(!KVSCSC_pConnection->sendFmtData("KICK %s %s",szC.data(),szU.data())) + return KVSCSC_pContext->warningNoIrcConnection(); + } else { + if(!KVSCSC_pConnection->sendFmtData("KICK %s %s :%s",szC.data(),szU.data(),szR.data())) + return KVSCSC_pContext->warningNoIrcConnection(); + } + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: killtimer + @title: + killtimer + @type: + command + @short: + Stops a timer + @syntax: + killtimer [-a] + killtimer [-q] [name] + @switches: + !sw: -a | --active + Requests to kill all the active timers + !sw: -q | --quiet + Does not print warnings if the specified timer is not running + @description: + The first version (with -a) kill all the running timers.[br] + The second verdion kills a running timer named [name].[br] + The timer has been started by the [cmd]timer[/cmd].[br] + [name] can be omitted if this command is called from a [cmd]timer[/cmd] callback: + in this case the current timer will be scheduled for killing immediately + after it has returned control to KVIrc. + @seealso: + [cmd]timer[/cmd], [fnc]$isTimer[/fnc], [cmd]listtimers[/cmd], [fnc]$listtimers[/fnc] + */ + + KVSCSC(killtimer) + { + QString szName; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("name",KVS_PT_STRING,KVS_PF_OPTIONAL,szName) + KVSCSC_PARAMETERS_END + + if(KVSCSC_pSwitches->find('a',"active")) + { + KviKvsTimerManager::instance()->deleteAllTimers(); + return true; + } + + if(szName.isEmpty()) + { + if(!KviKvsTimerManager::instance()->deleteCurrentTimer()) + { + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("Timer name omitted but there is not current timer (this is not a timer callback)","kvs")); + } + } else { + if(!KviKvsTimerManager::instance()->deleteTimer(szName)) + { + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pContext->warning(__tr2qs_ctx("Can't kill the timer '%Q' since it is not running","kvs"),&szName); + } + } + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: leave + @type: + command + @title: + leave + @syntax: + leave [-k] [-q] [-s] [part message] + @short: + Alias for part + @description: + Builtin alias for the command [cmd]part[/cmd]. + */ + // Internally aliased to leave + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: links + @type: + command + @title: + links + @syntax: + links + @short: + Lists server links + @description: + List server links.[br] + The syntax of the parameters of this command is different on many servers.[br] + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RFC2821 wrapper + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: list + @type: + command + @title: + list + @syntax: + list [ *( "," ) [ ] ] + @short: + Lists channels + @description: + List channels.[br] + The syntax of the parameters of this command is different on many servers.[br] + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RFC2821 wrapper + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: listtimers + @title: + listtimers + @type: + command + @short: + Lists the active timers + @syntax: + listtimers + @description: + Lists the currently active timers + @seealso: + [cmd]timer[/cmd], [fnc]$isTimer[/fnc], [cmd]killtimer[/cmd] + */ + + KVSCSC(listtimers) + { + Q_UNUSED(__pSwitches); + Q_UNUSED(__pParams); + + KviPointerHashTable * pTimerDict = KviKvsTimerManager::instance()->timerDict(); + + if(!pTimerDict) + return true; + + KviPointerHashTableIterator it(*pTimerDict); + + KVSCSC_pContext->window()->outputNoFmt(KVI_OUT_VERBOSE,__tr2qs_ctx("List of active timers","kvs")); + + unsigned int uCnt = 0; + + while(KviKvsTimer * pTimer = it.current()) + { + QString szName = pTimer->name(); + QString szLifetime; + switch(pTimer->lifetime()) + { + case KviKvsTimer::Persistent: + szLifetime = __tr2qs_ctx("Persistent","kvs"); + break; + case KviKvsTimer::WindowLifetime: + szLifetime = __tr2qs_ctx("WindowLifetime","kvs"); + break; + case KviKvsTimer::SingleShot: + szLifetime = __tr2qs_ctx("SingleShot","kvs"); + break; + default: + szLifetime = __tr2qs_ctx("Unknown","kvs"); + break; + } + QString szDelay; + szDelay.setNum(pTimer->delay()); + QString szWindow; + szWindow = pTimer->window() ? pTimer->window()->id() : __tr2qs_ctx("None","kvs"); + + KVSCSC_pContext->window()->output(KVI_OUT_VERBOSE, + "Timer \"%Q\": Lifetime: %Q, Delay: %Q, Window: %Q", + &szName,&szLifetime,&szDelay,&szWindow + ); + + uCnt++; + ++it; + } + + KVSCSC_pContext->window()->output(KVI_OUT_VERBOSE,__tr2qs_ctx("Total: %u timers running","kvs"),uCnt); + + return true; + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: lusers + @type: + command + @title: + lusers + @syntax: + lusers [ [ ] ] + @short: + Requests statistics about users on IRC + @description: + The LUSERS command is used to get statistics about the size of the + IRC network.[br]If no parameter is given, the reply will be about the + whole net.[br]If a is specified, then the reply will only + concern the part of the network formed by the servers matching the + mask.[br]Finally, if the parameter is specified, the request + is forwarded to that server which will generate the reply.[br] + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RFC2821 wrapper +}; diff --git a/src/kvirc/kvs/KviKvsCoreSimpleCommands_mr.cpp b/src/kvirc/kvs/KviKvsCoreSimpleCommands_mr.cpp new file mode 100644 index 000000000..eb8bdb316 --- /dev/null +++ b/src/kvirc/kvs/KviKvsCoreSimpleCommands_mr.cpp @@ -0,0 +1,1306 @@ +//============================================================================= +// +// File : KviKvsCoreSimpleCommands_mr.cpp +// Creation date : Fri 31 Oct 2003 00:04:25 by Szymon Stefanek +// +// This file is part of the KVIrc IRC client distribution +// Copyright (C) 2003-2010 Szymon Stefanek +// +// 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 opinion) 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 "KviKvsCoreSimpleCommands.h" + +#include "KviWindow.h" +#include "KviConsoleWindow.h" +#include "KviQueryWindow.h" +#include "KviIrcUserDataBase.h" +#include "kvi_out.h" +#include "KviLocale.h" +#include "KviApplication.h" +#include "KviOptions.h" +#include "KviFileUtils.h" +#include "KviFileDialog.h" +#include "KviIrcConnection.h" +#include "KviChannelWindow.h" +#include "KviIrcUrl.h" +#include "KviMainWindow.h" +#include "KviModuleManager.h" +#include "KviKvsModuleInterface.h" + +#include "KviKvsVariantList.h" +#include "KviKvsScript.h" +#include "KviKvsPopupManager.h" + +#include +#include +#include + +namespace KviKvsCoreSimpleCommands +{ + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: me + @type: + command + @title: + me + @syntax: + me + @short: + Sends a CTCP ACTION + @description: + Sends a CTCP ACTION to the current channel, query or dcc chat.[br] + If you execute it in any other window type, you will get an error.[br] + If you want to use this command in a window that is not a channel + query or dcc chat, you may use the [doc:command_rebinding]standard -r switch[/doc]. + @examples: + [example] + me is Hungry! + [/example] + */ + + KVSCSC(me) + { + Q_UNUSED(__pSwitches); + + QString szText; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("text",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szText) + KVSCSC_PARAMETERS_END + + switch(KVSCSC_pWindow->type()) + { + case KVI_WINDOW_TYPE_CHANNEL: + case KVI_WINDOW_TYPE_QUERY: + KVSCSC_REQUIRE_CONNECTION + case KVI_WINDOW_TYPE_DCCCHAT: + case KVI_WINDOW_TYPE_DCCVIDEO: + KVSCSC_pWindow->ownAction(szText); + break; + default: + KVSCSC_pContext->warning(__tr2qs_ctx("/me can be used only in channels, queries and DCC chat windows","kvs")); + break; + } + + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: mode + @type: + command + @title: + mode + @syntax: + mode [mode parameters] + @short: + Sends a MODE irc message + @description: + Sends a MODE irc message to the server of the current IRC context.[br] + The parameters are not modified in any way by KVIrc: so + you should use the RFC1459 syntax.[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + mode #kvirc +oo-b Pragma Buti *!*root@* + [/example] + */ + + KVSCSC(mode) + { + Q_UNUSED(__pSwitches); + + QString szText; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("text",KVS_PT_STRING,KVS_PF_APPENDREMAINING,szText) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + QByteArray szTxt = KVSCSC_pConnection->encodeText(szText); + + if(!szTxt.isEmpty()) + { + if(!KVSCSC_pConnection->sendFmtData("MODE %s",szTxt.data())) + return KVSCSC_pContext->warningNoIrcConnection(); + } + + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: motd + @type: + command + @title: + motd + @syntax: + motd [target server] + @short: + Requests the Message of the day + @description: + Requests the Message of the day from the specified server or the current server if no [target server] is specified.[br] + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RCF2821 wrapper + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: msg + @type: + command + @title: + msg + @syntax: + msg [-q] + @short: + Alias for privmsg + @switches: + !sw: -q | --quiet + Do not print any output + @description: + Sends a private message to the specified . + may be any PRIVMSG target allowed by the underlying + IRC protocol (see RFC1459). + This is really similar to [cmd]privmsg[/cmd] but also outputs the + message locally (unless the [-q] switch is used).[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc].[br] + */ + // Internally aliased to privmsg + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: nick + @type: + command + @title: + nick + @syntax: + nick + @short: + Changes your nickname + @description: + Changes your nickname in the connection associated to the + current [b]IRC context[/b].[br] This command is "server based"; + this means that the effects will be visible only after the + server has acknowledged the change.[br] + This command is [doc:connection_dependant_commands]connection dependant[/doc].[br] + @examples: + [example] + nick Pragma + [/example] + */ + + KVSCSC(nick) + { + Q_UNUSED(__pSwitches); + + QString szNick; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("nickname",KVS_PT_NONEMPTYSTRING,0,szNick) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + QByteArray szData = KVSCSC_pConnection->encodeText(szNick); + if(!szData.data())szData = ""; + + if(!KVSCSC_pConnection->sendFmtData("NICK %s",szData.data())) + return KVSCSC_pContext->warningNoIrcConnection(); + + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: notice + @type: + command + @title: + notice + @syntax: + notice [-q] + @short: + Sends a private notice + @switches: + !sw: -q | --quiet + Do not print any output + @description: + Sends a private notice to the specified . + may be any NOTICE target allowed by the underlying + IRC protocol (see RFC1459). + If the [-q] switch is specified, no output is printed. + This command is [doc:connection_dependant_commands]connection dependant[/doc].[br] + @examples: + [example] + notice Pragma Hello! + notice Pragma,Crocodile Hello to you both! + notice #kvirc Hello from outside! + [/example] + */ + + KVSCSC(notice) + { + QString szTarget,szText; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("target",KVS_PT_NONEMPTYSTRING,0,szTarget) + KVSCSC_PARAMETER("text",KVS_PT_STRING,KVS_PF_OPTIONAL | KVS_PF_APPENDREMAINING,szText) + KVSCSC_PARAMETERS_END + + KVSCSC_REQUIRE_CONNECTION + + KviWindow * w = KVSCSC_pConnection->findChannel(szTarget); + if(!w)w = KVSCSC_pConnection->findQuery(szTarget); + + QByteArray szT = KVSCSC_pConnection->encodeText(szTarget); + QByteArray szD = w ? w->encodeText(szText) : KVSCSC_pConnection->encodeText(szText); + if(!szT.data())szT = ""; // encoding problems ? + if(!szD.data())szD = ""; // encoding problems ? + + if(!(KVSCSC_pConnection->sendFmtData("NOTICE %s :%s",szT.data(),szD.data()))) + return KVSCSC_pContext->warningNoIrcConnection(); + + if(!KVSCSC_pSwitches->find('q',"quiet")) + KVSCSC_pWindow->output(KVI_OUT_OWNPRIVMSG,"[NOTICE >>> %Q]: %Q",&szTarget,&szText); + + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: op + @type: + command + @title: + op + @syntax: + op + @short: + Sets op status to the specified users + @description: + Sets channel operator status to the users specified in , + which is a comma separated list of nicknames. + This command works only if executed in a channel window. + The command is translated to a set of MODE messages containing + a variable number of +o flags. + This command is [doc:connection_dependant_commands]connection dependant[/doc]. + @examples: + [example] + op Pragma,Crocodile + [/example] + @seealso: + [cmd]chanowner[/cmd], [cmd]dechanowner[/cmd], [cmd]chanadmin[/cmd], [cmd]dechanadmin[/cmd], [cmd]deop[/cmd], [cmd]halfop[/cmd], [cmd]dehalfop[/cmd], [cmd]voice[/cmd], [cmd]devoice[/cmd], [cmd]userop[/cmd], [cmd]deuserop[/cmd] + */ + + KVSCSC(op) + { + return multipleModeCommand(__pContext,__pParams,__pSwitches,'+','o'); + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: openurl + @type: + command + @title: + openurl + @syntax: + openurl + @short: + Opens an url + @description: + Opens the specified with an appropriate handler.
+ The handlers for the supported url types are specified in the options dialog.
+ Each handler is a kvirc commandline that the url will be passed to as the first parameter ($0).
+ The supported url types are:
+ HTTP: http://<url> or sth that begins with "www."
+ HTTPS: https://<url>
+ FILE: file://<url>
+ IRC: irc[s][6]://[:][/[?]] (Handled internally)
+ FTP: ftp:// or sth that begins with "ftp."
+ MAIL: mailto:
+ @examples: + [example] + openurl http://www.kvirc.net + openurl https://www.secure.net + openurl file://home/pragma/pippo.txt + openurl irc://irc.eu.dal.net:6667 + openurl irc6://irc.ircd.it/#kvirc + openurl ircs://crypto.azzurra.org:9999 + openurl ircs6://ngnet.azzurra.org:9999 + openurl ftp://ftp.localhost.net/pub/kvirc/ + openurl mailto:users@domain.extension + [/example] + */ + + KVSCSC(openurl) + { + Q_UNUSED(__pSwitches); + + QString szUrl; + KVSCSC_PARAMETERS_BEGIN + KVSCSC_PARAMETER("url",KVS_PT_NONEMPTYSTRING,KVS_PF_APPENDREMAINING,szUrl) + KVSCSC_PARAMETERS_END + + QString szCommand; + if(KviQString::equalCIN(szUrl,"www.",4)) + { + szCommand = KVI_OPTION_STRING(KviOption_stringUrlHttpCommand); + szUrl.prepend("http://"); + } else if(KviQString::equalCIN(szUrl,"http:",5)) + { + szCommand = KVI_OPTION_STRING(KviOption_stringUrlHttpCommand); + } else if(KviQString::equalCIN(szUrl,"https:",6)) + { + szCommand = KVI_OPTION_STRING(KviOption_stringUrlHttpsCommand); + } else if(KviQString::equalCIN(szUrl,"ftp",3)) + { + szCommand = KVI_OPTION_STRING(KviOption_stringUrlFtpCommand); + if(KviQString::equalCIN(szUrl,"ftp.",4))szUrl.prepend("ftp://"); + } else if(KviQString::equalCIN(szUrl,"file",4)) + { + szCommand = KVI_OPTION_STRING(KviOption_stringUrlFileCommand); + } else if(KviQString::equalCIN(szUrl,"irc",3)) + { + if(KviIrcUrl::run(szUrl,KviIrcUrl::FirstFreeContext,KVSCSC_pContext->console()) & KviIrcUrl::InvalidProtocol) + { + KVSCSC_pContext->warning(__tr2qs_ctx("Invalid IRC url (%Q)","kvs"),&szUrl); + } + return true; + } else if(KviQString::equalCIN(szUrl,"mailto",6)) + { + szCommand = KVI_OPTION_STRING(KviOption_stringUrlMailtoCommand); + } +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + if(KVI_OPTION_BOOL(KviOption_boolUseSystemUrlHandlers)) + { + int iRet = (int)::ShellExecute(NULL, "open", szUrl.toLocal8Bit().data(),NULL, NULL, SW_SHOWNORMAL); + if(iRet <= 32) + KVSCSC_pContext->warning(__tr2qs_ctx("The system handler for the url failed to execute: system error is %1","kvs").arg(iRet)); + } else { +#endif + if(szCommand.isEmpty())szCommand = KVI_OPTION_STRING(KviOption_stringUrlUnknownCommand); + + if(!szCommand.isEmpty()) + { + KviKvsVariantList vList; + vList.append(new KviKvsVariant(szUrl)); + + QString szName = "openurl::handler"; + KviKvsScript script(szName,szCommand); + + if(!script.run(KVSCSC_pWindow,&vList,0,KviKvsScript::PreserveParams)) + KVSCSC_pContext->warning(__tr2qs_ctx("The commandline for this url type seems to be broken (%Q)","kvs"),&szUrl); + + } else KVSCSC_pContext->warning(__tr2qs_ctx("No commandline specified for this type of url (%Q)","kvs"),&szUrl); +#if defined(COMPILE_ON_WINDOWS) || defined(COMPILE_ON_MINGW) + } +#endif + + return true; + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + /* + @doc: oper + @type: + command + @title: + oper + @syntax: + oper + @short: + Requests IRC operator status + @description: + Requests IRC operator status.[br] + This command is a [doc:rfc2821wrappers]RFC2821 command wrapper[/doc]; see that document for more information.[br] + */ + // RFC2821 wrapper + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + /* + @doc: option + @type: + command + @title: + option + @syntax: + option [ ] + @short: + Sets an internal option + @description: + Sets an internal option named to the value . The value + must be appropriate for the type of option that you're going to set.[br] + With no parameters this command lists all the available option names + sorted by option type.[br] The possible option types are:[br] + [b]Boolean[/b]: must be "1" or "0"[br] + [b]String[/b]: can be any string[br] + [b]StringList[/b]: must be a comma separated list of strings (eventually empty)[br] + [b]Color[/b]: must have the format #RRGGBB where R G and B are hex digits[br] + [b]Font[/b]: is a comma separated list of font properties: + ,,