diff options
| author | 2008-02-20 20:55:48 +0000 | |
|---|---|---|
| committer | 2008-02-20 20:55:48 +0000 | |
| commit | 2166bc6d3eeeef2c27fc0babc81d278d36ed2522 (patch) | |
| tree | cf75fc64c4ef157462c4721e01eee0ce98133f23 | |
| parent | enabled avatars as default (diff) | |
| download | KVIrc-2166bc6d3eeeef2c27fc0babc81d278d36ed2522.tar.gz KVIrc-2166bc6d3eeeef2c27fc0babc81d278d36ed2522.tar.bz2 KVIrc-2166bc6d3eeeef2c27fc0babc81d278d36ed2522.zip | |
fixed doc (file format win32 -> unix)
git-svn-id: https://svn.kvirc.de/svn/trunk/kvirc@1144 17fca916-40b9-46aa-a4ea-0a15b648b75c
| -rw-r--r-- | src/modules/file/libkvifile.cpp | 2520 | ||||
| -rw-r--r-- | src/modules/objects/class_buttongroup.cpp | 174 | ||||
| -rw-r--r-- | src/modules/objects/class_layout.cpp | 548 | ||||
| -rw-r--r-- | src/modules/objects/class_pixmap.cpp | 634 | ||||
| -rw-r--r-- | src/modules/objects/class_socket.cpp | 2662 | ||||
| -rw-r--r-- | src/modules/objects/class_widget.cpp | 3490 |
6 files changed, 5014 insertions, 5014 deletions
diff --git a/src/modules/file/libkvifile.cpp b/src/modules/file/libkvifile.cpp index 5d82470d6..d6d976876 100644 --- a/src/modules/file/libkvifile.cpp +++ b/src/modules/file/libkvifile.cpp @@ -1,1260 +1,1260 @@ -//=============================================================================
-//
-// File : libkvifile.cpp
-// Creation date : Fri Nov 9 03:27:59 2001 GMT by Szymon Stefanek
-//
-// This file is part of the KVirc irc client distribution
-// Copyright (C) 2001-2005 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-//
-//=============================================================================
-
-#include "kvi_module.h"
-#include "kvi_fileutils.h"
-#include "kvi_locale.h"
-#include "kvi_malloc.h"
-#include "kvi_app.h"
-#include "kvi_options.h"
-#include "kvi_qcstring.h"
-
-#include "kvi_kvs_arraycast.h"
-
-#include <qfileinfo.h>
-#include "kvi_file.h"
-#include <qdir.h>
-#include <qtextstream.h>
-
-/*
- @doc: file.copy
- @type:
- command
- @title:
- file.copy
- @keyterms:
- copying files
- @short:
- Makes a copy of a file
- @syntax:
- file.copy [-o] <source:string> <destination:string>
- @switches:
- !sw: -o | --overwrite
- Overwrites the file even if it already exists.
- @description:
- Makes a copy of the <source> file as <destination>.[br]
- If the [-o] switch is used , the <destination> file is overwritten , if already exists.[br]
- With no [-o] switch , this command does not overwrite files.[br]
- The destination path must be already existing: if you want to ensure this, use [fnc]$file.mkdir[/fnc] first.[br]
- The paths (<source> and <destination>) are adjusted according to the system that KVIrc
- is running on so you don't have to bother about portability: it *should* be automatically
- guaranteed. Just use UNIX style paths for them.[br]
- @seealso:
- [cmd]file.rename[/cmd], [fnc]$file.exists[/fnc]()
-*/
-
-static bool file_kvs_cmd_copy(KviKvsModuleCommandCall * c)
-{
- QString szSrc,szDst;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("source",KVS_PT_NONEMPTYSTRING,0,szSrc)
- KVSM_PARAMETER("destination",KVS_PT_NONEMPTYSTRING,0,szDst)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szSrc);
- KviFileUtils::adjustFilePath(szDst);
- if(KviFileUtils::fileExists(szDst) && !c->switches()->find('o',"overwrite"))
- {
- c->warning(__tr2qs("Destinaion file exists: no copy made"));
- return true;
- }
- if(!KviFileUtils::copyFile(szSrc,szDst))
- {
- c->warning(__tr2qs("Failed to copy from %Q to %Q"),&szSrc,&szDst);
- c->warning(__tr2qs("Either the source doesn't exist or the destination can not be created"));
- }
- return true;
-}
-
-
-/*
- @doc: file.addimagepath
- @type:
- command
- @title:
- file.addimagepath
- @short:
- Adds an image search path
- @syntax:
- file.addimagepath <path:string>
- @description:
- Adds <path> to the image search path list.[br]
- KVIrc will look for images files (also) in that path (when a relative image file name is used).[br]
- Yes, this function is a bit misplaced...
- @seealso:
- [cmd]file.delimagepath[/cmd]
-*/
-
-static bool file_kvs_cmd_addimagepath(KviKvsModuleCommandCall * c)
-{
- QString szDst;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("path",KVS_PT_NONEMPTYSTRING,0,szDst)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szDst);
-
- QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).find(szDst);
- if(it == KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).end())
- KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).append(szDst);
- return true;
-}
-
-
-
-/*
- @doc: file.delimagepath
- @type:
- command
- @title:
- file.delimagepath
- @short:
- Removes an image search path
- @syntax:
- file.delimagepath <path:string>
- @description:
- Removes <path> from the image search path list.[br]
- Yes, this function is a bit misplaced...
- @seealso:
- [cmd]file.addimagepath[/cmd]
-*/
-
-static bool file_kvs_cmd_delimagepath(KviKvsModuleCommandCall * c)
-{
- QString szDst;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("path",KVS_PT_NONEMPTYSTRING,0,szDst)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szDst);
-
- QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).find(szDst);
- if(it == KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).end())
- KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).remove(szDst);
- return true;
-}
-
-
-/*
- @doc: file.write
- @type:
- command
- @title:
- file.write
- @keyterms:
- writing data to files
- @short:
- Writes an ascii data string to a file
- @syntax:
- file.write [-a] [-l] <filename:string> <data:string>
- @switches:
- !sw: -a | --append
- If the file already exists, append the data instead of overwriting the original contents.
- !sw: -l | --local-8-bit
- Causes the file to be written in the local 8 bit character set instead of the
- default utf8.
- @description:
- Writes <data> (which is an ASCII string) to the file <filename>.[br]
- It does NOT append a traling LF character: if you want it you must explicitly specify it in the <data> parameter.[br]
- -a causes the command to append the <data> to the file instead of overwriting the entire file.[br]
- The path is adjusted according to the system that KVIrc
- is running on so you don't have to bother about portability: it *should* be automatically
- guaranteed. Just use UNIX style paths for them.[br]
- The file is saved in utf8 unless the -l switch is specified (in that case the local 8 bit encoding is used).
- Please note that uf8 is the only character set that preserves ALL the possible characters.
- @seealso:
- [cmd]file.rename[/cmd], [fnc]$file.exists[/fnc]()
-*/
-
-static bool file_kvs_cmd_write(KviKvsModuleCommandCall * c)
-{
- QString szFileName,szData;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szFileName)
- KVSM_PARAMETER("data",KVS_PT_NONEMPTYSTRING,0,szData)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szFileName);
-
- bool bRet;
- if(c->switches()->find('l',"local-8-bit"))
- bRet = KviFileUtils::writeFileLocal8Bit(szFileName,szData,c->switches()->find('a',"append"));
- else
- bRet = KviFileUtils::writeFile(szFileName,szData,c->switches()->find('a',"append"));
-
- if(!bRet)
- c->warning(__tr2qs("Failed to write to file %Q: the destination couldn't be opened"),&szFileName);
-
- return true;
-}
-
-
-/*
- @doc: file.rename
- @type:
- command
- @title:
- file.rename
- @keyterms:
- copying files
- @short:
- Makes a copy of a file
- @syntax:
- file.rename <oldname:string> <newname:string>
- @description:
- Renames a file from <oldname> to <newname>.[br]
- This command can also rename directories.[br]
- If the <newname> file already exists , this command fails.[br]
- The paths (<oldname> and <newname>) are adjusted according to the system that KVIrc
- is running on so you don't have to bother about portability: it *should* be automatically
- guaranteed.Just use UNIX style paths for them.[br]
- @seealso:
- [cmd]file.copy[/cmd], [fnc]$file.exists[/fnc]()
-*/
-
-static bool file_kvs_cmd_rename(KviKvsModuleCommandCall * c)
-{
- QString szOld,szNew;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("oldname",KVS_PT_NONEMPTYSTRING,0,szOld)
- KVSM_PARAMETER("newname",KVS_PT_NONEMPTYSTRING,0,szNew)
- KVSM_PARAMETERS_END(c)
-
- KviFileUtils::adjustFilePath(szOld);
- KviFileUtils::adjustFilePath(szNew);
-
- if(KviFileUtils::fileExists(szNew))
- c->warning(__tr2qs("Destination file exists: file not renamed"));
-
- if(!KviFileUtils::renameFile(szOld,szNew))
- c->warning(__tr2qs("Failed to rename %Q to %Q"),&szOld,&szNew);
- return true;
-}
-
-
-/*
- @doc: file.mkdir
- @type:
- command
- @title:
- file.mkdir
- @keyterms:
- creating directories
- @short:
- Creates a directory
- @syntax:
- file.mkdir <directory:string>
- @description:
- Creates the <directory>.[br]
- The path is adjusted according to the system that KVIrc
- is running on so you don't have to bother about portability: it *should* be automatically
- guaranteed. Just use an UNIX style path.[br]
- @seealso:
- [fnc]$file.exists[/fnc]()
-*/
-
-static bool file_kvs_cmd_mkdir(KviKvsModuleCommandCall * c)
-{
- QString szDir;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("directory",KVS_PT_NONEMPTYSTRING,0,szDir)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szDir);
- if(!KviFileUtils::makeDir(szDir))
- c->warning(__tr2qs("Failed to make the directory %Q"),&szDir);
- return true;
-}
-
-
-
-/*
- @doc: file.remove
- @type:
- command
- @title:
- file.remove
- @keyterms:
- removing files
- @short:
- Removes a file
- @syntax:
- file.remove [-q] <name:string>
- @switches:
- !sw: -q | --quiet
- Suppresses any warning message
- @description:
- Removes the file <name>.[br]
- -q suppresses any warning message (about non existing file , for example).[br]
- The path is adjusted according to the system that KVIrc
- is running on so you don't have to bother about portability: it *should* be automatically
- guaranteed. Just use an UNIX style path.[br]
- @seealso:
- [fnc]$file.exists[/fnc]()
-*/
-
-static bool file_kvs_cmd_remove(KviKvsModuleCommandCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("name",KVS_PT_NONEMPTYSTRING,0,szName)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szName);
- if(!KviFileUtils::removeFile(szName))
- {
- if(!c->switches()->find('q',"quiet"))
- c->warning(__tr2qs("Failed to remove the file %Q"),&szName);
- }
- return true;
-}
-
-
-/*
- @doc: file.rmdir
- @type:
- command
- @title:
- file.rmdir
- @keyterms:
- removing directories
- @short:
- Removes a directory
- @syntax:
- file.rmdir [-q] <name:string>
- @switches:
- !sw: -q | --quiet
- Suppresses any warning message
- @description:
- Removes the directory <name>.[br]
- The directory must be empty for this command to success.[br]
- -q suppresses any warning message (about non existing directory , for example).[br]
- The path is adjusted according to the system that KVIrc
- is running on so you don't have to bother about portability: it *should* be automatically
- guaranteed. Just use an UNIX style path.[br]
- @seealso:
- [fnc]$file.exists[/fnc]()
- [cmd]file.remove[/cmd]
-*/
-
-static bool file_kvs_cmd_rmdir(KviKvsModuleCommandCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("name",KVS_PT_NONEMPTYSTRING,0,szName)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szName);
- if(!KviFileUtils::removeDir(szName))
- {
- if(!c->switches()->find('q',"quiet"))
- c->warning(__tr2qs("Failed to remove the directory %Q"),&szName);
- }
- return true;
-}
-
-
-/*
- @doc: file.exists
- @type:
- function
- @title:
- $file.exists
- @short:
- Check if a file exists
- @syntax:
- <boolean> $file.exists(<filename:string>)
- @description:
- Returns true if the file <filename> exists (this is also valid for directories!).[br]
- The <filename> should be an unix-style file path and is adjusted according to the system that KVIrc is running on.[br]
-*/
-
-static bool file_kvs_fnc_exists(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filename",KVS_PT_STRING,0,szName)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szName);
- QFileInfo f(szName);
- c->returnValue()->setBoolean(f.exists());
- return true;
-}
-
-
-/*
- @doc: file.type
- @type:
- function
- @title:
- $file.type
- @short:
- Checks the type of a path
- @syntax:
- <string> $file.type(<filename:string>)
- @description:
- Returns "f" if the <filename> points to a real file , "d" if <filename>
- is the name of a directory or "l" if it is a symbolic link.[br]
- The <filename> should be an unix-style file path and is adjusted according to the system that KVIrc is running on.[br]
-*/
-
-static bool file_kvs_fnc_type(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szName)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szName);
- QFileInfo f(szName);
- if(f.isFile())c->returnValue()->setString("f");
- else if(f.isDir())c->returnValue()->setString("d");
- else if(f.isSymLink())c->returnValue()->setString("l");
- return true;
-}
-
-
-/*
- @doc: file.size
- @type:
- function
- @title:
- $file.size
- @short:
- Returns the size of a file
- @syntax:
- <integer> $file.size(<filename:string>)
- @description:
- Returns the size of the file pointed by <filename>.[br]
- If the file does not exist , this function returns 0.[br]
- The <filename> should be an unix-style file path and is adjusted according to the system that KVIrc is running on.[br]
-*/
-
-static bool file_kvs_fnc_size(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szName)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szName);
- QFileInfo f(szName);
- c->returnValue()->setInteger(f.size());
- return true;
-}
-/*
- @doc: file.allSizese
- @type:
- function
- @title:
- $file.allSizes
- @short:
- Returns all sizes of a specified directory.
- @syntax:
- <array> $file.allSize(<dirname:string>)
- @description:
- Returns the size of every files of the specified directory as an array.[br]
-*/
-
-static bool file_kvs_fnc_allSizes(KviKvsModuleFunctionCall * c)
-{
- QString szDir;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("directory",KVS_PT_NONEMPTYSTRING,0,szDir)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szDir);
-
- QDir d(szDir);
- if(!d.exists())
- {
- c->warning(__tr2qs("The specified directory does not exist '%Q'"),&szDir);
- return true;
- }
-
- QStringList sl;
- sl = d.entryList(QDir::Files);
-
- KviKvsArray * a = new KviKvsArray();
- QString szFile;
- if(!sl.isEmpty())
- {
- int idx = 0;
- for(QStringList::Iterator it = sl.begin();it != sl.end();++it)
- {
- szFile=szDir+(*it);
- QFileInfo f(szFile);
- a->set(idx,new KviKvsVariant((kvs_int_t)f.size()));
- idx++;
- }
- }
- c->returnValue()->setArray(a);
-
-
-
-
- return true;
-}
-
-/*
- @doc: file.fixpath
- @type:
- function
- @title:
- $file.fixpath
- @short:
- Converts file paths
- @syntax:
- <string> $file.fixpath(<filename:string>)
- @description:
- Returns the <filename> adjusted to match the current operating
- system file path conventions.[br] This means that on UNIX , a path like "C:\folder\file.mp3"
- will be returned as "/folder/file.mp3" and vice-versa.[br]
- There is a minor problem with unix paths converted to the windows system: unix
- has no "drive" concept thus the unix paths do not contain a drive. KVIrc will
- always map the paths to the "default" C: drive.[br]
- This is a good reason to avoid using absolute hard-coded paths :).[br]
- Please note that you DON'T NEED to call this function on paths that you
- pass to the other file.* functions: they are adjusted automatically.[br]
- @seealso:
- [fnc]$file.ps[/fnc]
-*/
-
-
-static bool file_kvs_fnc_fixpath(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filename",KVS_PT_STRING,0,szName)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szName);
- c->returnValue()->setString(szName);
- return true;
-}
-
-
-/*
- @doc: file.ps
- @type:
- function
- @title:
- $file.ps
- @short:
- Returns the file path separator
- @syntax:
- <string> $file.ps()
- @description:
- Returns the file path separator for the current operating system.[br]
- On windows , '\' is returned , on UNIX , '/'.[br]
- @seealso:
- [fnc]$file.fixpath[/fnc]
-*/
-
-static bool file_kvs_fnc_ps(KviKvsModuleFunctionCall * c)
-{
- c->returnValue()->setString(QString(QChar(KVI_PATH_SEPARATOR_CHAR)));
- return true;
-}
-
-
-/*
- @doc: file.ls
- @type:
- function
- @title:
- $file.ls
- @short:
- Returns a directory listing
- @syntax:
- <array> $file.ls(<directory:string>,[<flags:string>[,<namefilter:string>]])
- @description:
- Returns the listing of the specified directory as an array.[br]
- The <directory> should be an unix-style file path and is adjusted according to the system that KVIrc is running on.[br]
- <flags> may be a combination of the following characters:[br]
- d: list directories[br]
- f: list files[br]
- l: list symbolic links[br]
- r: list readable files[br]
- w: list writeable files[br]
- x: list executable files[br]
- h: list hidden files[br]
- s: list system files[br]
- n: sort files by name[br]
- t: sort files by file time[br]
- b: sort files by file size[br]
- z: put the directories first, then the files[br]
- k: invert sort order[br]
- i: case insensitive sort[br]
- If <flags> is empty then a default of 'dfrwxhs'.[br]
- If none of r,w,x is set then KVIrc sets all of them by default.[br]
- If <namefilter> is passed then it is interpreted as a wildcard string
- that must match the entries to be returned.[br]
- @example:
- [example]
- %dir[]=$file.ls(/,"d")
- [cmd]foreach[/cmd](%f,%dir[])echo %f
- %dir[]=$file.ls(/usr/include,"f","t*.h");
- [cmd]foreach[/cmd](%f,%dir[])echo %f
- %dir[]=$file.ls($file.homedir,"dfr");
- [cmd]foreach[/cmd](%f,%dir[])echo %f
- [/example]
-*/
-
-static bool file_kvs_fnc_ls(KviKvsModuleFunctionCall * c)
-{
- QString szDir,szFlags,szFilter;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("directory",KVS_PT_NONEMPTYSTRING,0,szDir)
- KVSM_PARAMETER("flags",KVS_PT_STRING,KVS_PF_OPTIONAL,szFlags)
- KVSM_PARAMETER("filter",KVS_PT_STRING,KVS_PF_OPTIONAL,szFilter)
- KVSM_PARAMETERS_END(c)
-
- KviFileUtils::adjustFilePath(szDir);
-
- QDir d(szDir);
- if(!d.exists())
- {
- c->warning(__tr2qs("The specified directory does not exist '%Q'"),&szDir);
- return true;
- }
-
-#ifdef COMPILE_USE_QT4
- QFlags<QDir::Filter> iFlags = 0;
-#else
- int iFlags = 0;
-#endif
- if(szFlags.isEmpty())iFlags = QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::Readable | QDir::Writable | QDir::Executable | QDir::Hidden | QDir::System;
- else {
- if(szFlags.find('d',false) != -1)iFlags |= QDir::Dirs;
- if(szFlags.find('f',false) != -1)iFlags |= QDir::Files;
- if(szFlags.find('l',false) == -1)iFlags |= QDir::NoSymLinks;
- if(szFlags.find('r',false) != -1)iFlags |= QDir::Readable;
- if(szFlags.find('w',false) != -1)iFlags |= QDir::Writable;
- if(szFlags.find('x',false) != -1)iFlags |= QDir::Executable;
- if(szFlags.find('h',false) != -1)iFlags |= QDir::Hidden;
- if(szFlags.find('s',false) != -1)iFlags |= QDir::System;
- }
-#ifdef COMPILE_USE_QT4
- QFlags<QDir::SortFlag> iSort = 0;
-#else
- int iSort = 0;
-#endif
- if(szFlags.isEmpty())iSort = QDir::Unsorted;
- else {
- if(szFlags.find('n',false) != -1)iSort |= QDir::Name;
- if(szFlags.find('t',false) != -1)iSort |= QDir::Time;
- if(szFlags.find('b',false) != -1)iSort |= QDir::Size;
- if(szFlags.find('z',false) != -1)iSort |= QDir::DirsFirst;
- if(szFlags.find('k',false) != -1)iSort |= QDir::Reversed;
- if(szFlags.find('i',false) != -1)iSort |= QDir::IgnoreCase;
- }
-
- QStringList sl;
- if(!szFilter.isEmpty())sl = d.entryList(szFilter,iFlags,iSort);
- else sl = d.entryList(iFlags,iSort);
-
- KviKvsArray * a = new KviKvsArray();
- if(!sl.isEmpty())
- {
- int idx = 0;
- for(QStringList::Iterator it = sl.begin();it != sl.end();++it)
- {
- a->set(idx,new KviKvsVariant(*it));
- idx++;
- }
- }
- c->returnValue()->setArray(a);
-
- return true;
-}
-
-/*
- @doc: file.read
- @type:
- function
- @title:
- $file.read
- @short:
- Reads a text file
- @syntax:
- <string> $file.read(<filename:string>[,<size:integer>[,<flags:string>]])
- @description:
- Reads at most <size> bytes of the file pointed by <filename>.[br]
- <size> is an upper limit but may be not reached if the real file is smaller.[br]
- The data read is returned as a string , so if the file contains binary data,
- expect strange results.[br] If <size> is not specified, then KVIrc tries to read
- the whole file up to the 1 MB limit (so if you want to read a file that is
- bigger thatn 1 MB then you MUST specify the <size>).[br]
- WARNING: always check the file size before attemting to read a whole file...
- reading a CDROM iso image may sit down your system :) (and will prolly crash while
- allocating memory , before attempting to read anything)[br]
- An empty string is returned if a serious error occures.[br]
- The <filename> is adjusted according to the system that KVIrc is running on.[br]
- Flags are actually limited to the single letter 'l'. By default the file
- is decoded from the ut8 characters set. If 'l' is present the the file
- is decoded by using the local 8 bit character set instead.
- @examples:
- [example]
- echo $file.read(/proc/cpuinfo)
- [/example]
- @seealso:
- [fnc]$file.readbinary[/fnc]
-*/
-
-static bool file_kvs_fnc_read(KviKvsModuleFunctionCall * c)
-{
- QString szNameZ;
- kvs_uint_t uSize;
- QString szFlags;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szNameZ)
- KVSM_PARAMETER("size",KVS_PT_UINT,KVS_PF_OPTIONAL,uSize)
- KVSM_PARAMETER("flags",KVS_PT_STRING,KVS_PF_OPTIONAL,szFlags)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szNameZ);
-
- QFile f(szNameZ);
- if(!f.open(IO_ReadOnly))
- {
- c->warning(__tr2qs("Can't open the file \"%Q\" for reading"),&szNameZ);
- return true;
- }
-
- if(c->params()->count() < 2)uSize = 1024 * 1024; // 1 meg file default
-
- char * buf = (char *)kvi_malloc(sizeof(char) * (uSize + 1));
- unsigned int uReaded = 0;
- unsigned int uRetries = 0;
-
- while((uReaded < uSize) && (!f.atEnd()))
- {
- int readedNow = f.readBlock(buf + uReaded,uSize - uReaded);
- if(readedNow < 0)
- {
- kvi_free(buf);
- c->warning(__tr2qs("Read error for file %Q"),&szNameZ);
- return true;
- } else readedNow += uReaded;
- uRetries ++;
- if(uRetries > 1000)
- {
- // ops
- kvi_free(buf);
- c->warning(__tr2qs("Read error for file %Q (have been unable to read the requested size in 1000 retries)"),&szNameZ);
- return true;
- }
- uReaded += readedNow;
- }
-
- buf[uReaded] = '\0';
-
- if(szFlags.find('l',false) == -1)
- c->returnValue()->setString(QString::fromUtf8(buf));
- else
- c->returnValue()->setString(QString::fromLocal8Bit(buf));
-
- kvi_free(buf);
-
- return true;
-}
-
-
-/*
- @doc: file.readLines
- @type:
- function
- @title:
- $file.readLines
- @short:
- Reads lines of a text file
- @syntax:
- <array> $file.readLines(<filename:string>[,<startline:integer>,[<count:integer>[,<flags:string>]]])
- @description:
- Reads lines from the specified file and returns them as an array of strings.
- The lines are assumed to be separated by linefeed characters (which are NOT returned).
- Eventual terminating carriage return characters at the end of the line are stripped.
- If <startline> is specified, then all the lines with indexes lower that <startline> are
- discarded. If <count> is specified then a maximum of <count> lines is returned.
- If <count> is not specified then all the lines until the end are read.
- The <filename> is adjusted according to the system that KVIrc is running on.[br]
- Flags are actually limited to the single letter 'l'. By default the file
- is decoded from the ut8 characters set. If 'l' is present the the file
- is decoded by using the local 8 bit character set instead.
- WARNING: Always check the size of the file you're going to read: it is not
- a good idea attempting to read a 700 MB binary file with this function since
- it will probably sit down your system and exhaust your virtual memory.
- @examples:
- [example]
- echo $file.readLines(/proc/cpuinfo)
- [/example]
- @seealso:
- [fnc]$file.read[/fnc](), [cmd]file.writeLines[/fnc], [fnc]$lf[/fnc]
-*/
-
-
-
-static bool file_kvs_fnc_readLines(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- QString szFlags;
- kvs_int_t iStartLine;
- kvs_int_t iCount;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szName)
- KVSM_PARAMETER("startline",KVS_PT_INT,KVS_PF_OPTIONAL,iStartLine)
- KVSM_PARAMETER("count",KVS_PT_INT,KVS_PF_OPTIONAL,iCount)
- KVSM_PARAMETER("flags",KVS_PT_STRING,KVS_PF_OPTIONAL,szFlags)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::adjustFilePath(szName);
-
- QFile f(szName);
- if(!f.open(IO_ReadOnly))
- {
- c->warning(__tr2qs("Can't open the file \"%Q\" for reading"),&szName);
- return true;
- }
-
- if(c->params()->count() < 2)iStartLine = 0;
- if(c->params()->count() < 3)iCount = -1;
-
- bool bLocal8Bit = szFlags.find('l',0,false) != -1;
-
- KviKvsArray * a = new KviKvsArray();
-
- int iIndex=0;
-
- QTextStream stream( &f );
-
- stream.setEncoding(bLocal8Bit ? QTextStream::Locale : QTextStream::UnicodeUTF8);
- for(int i=0;i<iStartLine;i++)
- stream.readLine();
-
- if(iCount>0)
- {
- for(; (iCount>0 && !stream.atEnd()) ; iCount-- )
- a->set(iIndex,new KviKvsVariant(stream.readLine()));
- iIndex++;
- } else {
- while(!stream.atEnd()) {
- a->set(iIndex,new KviKvsVariant(stream.readLine()));
- iIndex++;
- }
- }
-
- f.close();
-
- c->returnValue()->setArray(a);
-
- return true;
-}
-
-
-/*
- @doc: file.writelines
- @type:
- command
- @title:
- file.writeLines
- @short:
- Writes an array of lines to a file
- @syntax:
- file.writeLines [-l] [-a] [-c] <filename:string> <lines:array>
- @switches:
- !sw: -l | --local-8-bit
- Causes the lines to be saved in local 8 bit character set instead
- of the default unicode encoding.
- !sw: -a | --append
- If the file already exists, then the lines are appended to the end
- instead of overwriting the file.
- !sw: -c | --crlf
- The lines are separated by a carriage-return+line-feed character
- combination, compatible with windows text mode files.
- This is the only way to make the file readable in windows notepad, for example.
- Please note that this is broken design: do NOT use it :)
- !sw: -n | --no-separator
- Do not separate the lines at all (either the separators are already
- inside the lines array or no line separation is desired at all).
- -n takes precedence over -c.
- !sw: -q | --quiet
- Don't complain if the file can't be opened: just fail silently
- @description:
- Writes the array of <lines> to the specified file.
- The lines are separated by a single linefeed character (see also [fnc]$lf[/fnc])
- unless the -c or -n switches are used. If the file already exists then it is
- overwritten with the new data unless the -a switch is used.
- The lines array is encoded in the ut8 character set unless the -l switch is used.
- @seealso:
- [fnc]$file.readLines[/fnc]
-*/
-
-
-
-static bool file_kvs_cmd_writeLines(KviKvsModuleCommandCall * c)
-{
- QString szFile,szFlags;
- KviKvsArrayCast a;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szFile)
- KVSM_PARAMETER("lines",KVS_PT_ARRAYCAST,0,a)
- KVSM_PARAMETERS_END(c)
-
- KviFileUtils::adjustFilePath(szFile);
-
- KviFile f(szFile);
- int iFlags = IO_WriteOnly;
-
- if(!f.openForWriting(c->switches()->find('a',"append")))
- {
- if(!c->switches()->find('q',"quiet"))
- c->warning(__tr2qs("Can't open the file \"%Q\" for writing"),&szFile);
- return true;
- }
-
- bool bLocal8Bit = c->switches()->find('l',"local-8-bit");
- bool bNoSeparator = c->switches()->find('n',"no-separator");
- bool bAddCR = c->switches()->find('c',"crlf");
-
- unsigned int u = 0;
- while(u < a.array()->size())
- {
- KviKvsVariant * v = a.array()->at(u);
- KviQCString dat;
- if(v)
- {
- QString szDat;
- v->asString(szDat);
- KviQCString dat = bLocal8Bit ? szDat.local8Bit() : szDat.utf8();
- }
- if(!bNoSeparator)
- {
- if(bAddCR)dat += "\r\n";
- else dat += '\n';
- }
- f.writeBlock(dat.data(),dat.length());
- u++;
- }
-
- f.close();
-
- return true;
-}
-
-
-/*
- @doc: file.localdir
- @type:
- function
- @title:
- $file.localdir
- @short:
- Get the KVIrc local directory
- @syntax:
- <string> $file.localdir([relative_path:string])
- @description:
- Returns the path to the KVIrc local data directory.[br]
- The KVIrc local data directory is always writeable and contains
- the various subdirectories that KVIrc uses internally: audio , avatars ,
- config , help , incoming , log , modules , msgcolors and pics.[br]
- If <relative_path> is passed , then it is appended at the end of the directory
- to form a complete filepath.[br]
- The path is adjusted to contain single separators suitable for the platform
- that KVIrc is atually running on (thus you not need to care about path
- separators in the <relative_path> , KVIrc will adjust them).[br]
- @examples:
- [example]
- echo KVIrc looks for pictures in $file.localdir(pics)
- echo panic.png would be translated to $file.localdir(pics/panic.png)
- [/example]
-*/
-
-static bool file_kvs_fnc_localdir(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName)
- KVSM_PARAMETERS_END(c)
- if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR);
- QString szPath;
- g_pApp->getLocalKvircDirectory(szPath,KviApp::None,szName);
- KviFileUtils::adjustFilePath(szPath);
- c->returnValue()->setString(szPath);
- return true;
-}
-
-
-
-/*
- @doc: file.homedir
- @type:
- function
- @title:
- $file.homedir
- @short:
- Get the user's HOME directory
- @syntax:
- <string> $file.homedir([relative_path:string])
- @description:
- Returns the user's HOME directory path.[br]
- If <relative_path> is passed , then it is appended at the end of the directory
- to form a complete filepath.[br]
- The path is adjusted to contain single separators suitable for the platform
- that KVIrc is atually running on (thus you not need to care about path
- separators in the <relative_path> , KVIrc will adjust them).[br]
-*/
-
-static bool file_kvs_fnc_homedir(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName)
- KVSM_PARAMETERS_END(c)
- if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR);
- QString szPath = QDir::homeDirPath();
- KviQString::ensureLastCharIs(szPath,KVI_PATH_SEPARATOR_CHAR);
- szPath.append(szName);
- KviFileUtils::adjustFilePath(szPath);
- c->returnValue()->setString(szPath);
- return true;
-}
-
-
-
-/*
- @doc: file.rootdir
- @type:
- function
- @title:
- $file.rootdir
- @short:
- Get the system root directory
- @syntax:
- $file.rootdir(<relative_path>)
- $file.rootdir
- @description:
- Returns the system's root directory (/ on UNIX and C:/ on Windows).[br]
- If <relative_path> is passed , then it is appended at the end of the directory
- to form a complete filepath.[br]
- The path is adjusted to contain single separators suitable for the platform
- that KVIrc is atually running on (thus you not need to care about path
- separators in the <relative_path> , KVIrc will adjust them).[br]
-*/
-
-static bool file_kvs_fnc_rootdir(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName)
- KVSM_PARAMETERS_END(c)
- if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR);
- QString szPath = QDir::rootDirPath();
- KviQString::ensureLastCharIs(szPath,KVI_PATH_SEPARATOR_CHAR);
- szPath.append(szName);
- KviFileUtils::adjustFilePath(szPath);
- c->returnValue()->setString(szPath);
- return true;
-}
-
-
-/*
- @doc: file.cwd
- @type:
- function
- @title:
- $file.currentdir
- @short:
- Get the current directory
- @syntax:
- <string> $file.cwd([relative_path:string])
- @description:
- Returns the current working directory.[br]
- If <relative_path> is passed , then it is appended at the end of the directory
- to form a complete filepath.[br]
- The path is adjusted to contain single separators suitable for the platform
- that KVIrc is atually running on (thus you not need to care about path
- separators in the <relative_path> , KVIrc will adjust them).[br]
-*/
-
-static bool file_kvs_fnc_cwd(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName)
- KVSM_PARAMETERS_END(c)
- if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR);
- QString szPath = QDir::currentDirPath();
- KviQString::ensureLastCharIs(szPath,KVI_PATH_SEPARATOR_CHAR);
- szPath.append(szName);
- KviFileUtils::adjustFilePath(szPath);
- c->returnValue()->setString(szPath);
- return true;
-}
-
-
-/*
- @doc: file.globaldir
- @type:
- function
- @title:
- $file.globaldir
- @short:
- Get the KVIrc global directory
- @syntax:
- $file.globaldir(<relative_path>)
- $file.globaldir
- @description:
- Returns the path to the KVIrc global data directory.[br]
- The KVIrc local data directory is always readable but usually not writeable and contains
- the various subdirectories that KVIrc uses internally: audio , avatars ,
- config , help , incoming , log , modules , msgcolors and pics.[br]
- If <relative_path> is passed , then it is appended at the end of the directory
- to form a complete filepath.[br]
- The path is adjusted to contain single separators suitable for the platform
- that KVIrc is atually running on (thus you not need to care about path
- separators in the <relative_path> , KVIrc will adjust them).[br]
- @examples:
- [example]
- echo KVIrc looks for pictures in $file.globaldir(pics)
- echo panic.png would be translated to $file.globaldir(pics/panic.png)
- [/example]
-*/
-
-static bool file_kvs_fnc_globaldir(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName)
- KVSM_PARAMETERS_END(c)
- if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR);
- QString szPath;
- g_pApp->getGlobalKvircDirectory(szPath,KviApp::None,szName);
- KviFileUtils::adjustFilePath(szPath);
- c->returnValue()->setString(szPath);
- return true;
-}
-
-/*
- @doc: file.extractpath
- @type:
- function
- @title:
- $file.extractpath
- @short:
- Extract the path from a filename
- @syntax:
- <string> $file.extractpath(<filepath:string>)
- @description:
- Returns the path part of the <filepath> translated to match the current
- platform filesystem conventions.[br]
- The path will NOT contain a trailing path separator.[br]
- For example, if <filepath> is /usr/arch/mp3/Carisma_SuonoDelSilenzio.mp3 then
- this function will return /usr/arch/mp3 on UNIX and C:\usr\arch\mp3 on Windows.
- @seealso:
- [fnc]$file.extractfilename[/fnc]
-*/
-
-static bool file_kvs_fnc_extractpath(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filepath",KVS_PT_NONEMPTYSTRING,0,szName)
- KVSM_PARAMETERS_END(c)
- c->returnValue()->setString(QFileInfo(szName).dirPath(TRUE));
- return true;
-}
-
-
-/*
- @doc: file.extractfilename
- @type:
- function
- @title:
- $file.extractfilename
- @short:
- Extract the filename from a file path
- @syntax:
- <string> $file.extractpath(<filepath:string>)
- @description:
- Returns the filename part of the filepath translated to match the current
- platform filesystem conventions.[br]
- For example, if <filepath> is /usr/arch/mp3/Carisma_SuonoDelSilenzio.mp3 then
- this function will return Carisma_SuonoDelSilenzio.mp3
- @seealso:
- [fnc]$file.extractpath[/fnc]
-*/
-
-static bool file_kvs_fnc_extractfilename(KviKvsModuleFunctionCall * c)
-{
- QString szName;
- KVSM_PARAMETERS_BEGIN(c)
- KVSM_PARAMETER("filepath",KVS_PT_NONEMPTYSTRING,0,szName)
- KVSM_PARAMETERS_END(c)
- KviFileUtils::extractFileName(szName);
- KviQString::cutToLast(szName,KVI_PATH_SEPARATOR_CHAR);
- c->returnValue()->setString(szName);
- return true;
-}
-
-
-
-static bool file_module_init(KviModule * m)
-{
-
- KVSM_REGISTER_SIMPLE_COMMAND(m,"copy",file_kvs_cmd_copy);
- KVSM_REGISTER_SIMPLE_COMMAND(m,"rename",file_kvs_cmd_rename);
- KVSM_REGISTER_SIMPLE_COMMAND(m,"mkdir",file_kvs_cmd_mkdir);
- KVSM_REGISTER_SIMPLE_COMMAND(m,"write",file_kvs_cmd_write);
- KVSM_REGISTER_SIMPLE_COMMAND(m,"remove",file_kvs_cmd_remove);
- KVSM_REGISTER_SIMPLE_COMMAND(m,"rmdir",file_kvs_cmd_rmdir);
- KVSM_REGISTER_SIMPLE_COMMAND(m,"addimagepath",file_kvs_cmd_addimagepath);
- KVSM_REGISTER_SIMPLE_COMMAND(m,"delimagepath",file_kvs_cmd_delimagepath);
- KVSM_REGISTER_SIMPLE_COMMAND(m,"writeLines",file_kvs_cmd_writeLines);
-
- KVSM_REGISTER_FUNCTION(m,"exists",file_kvs_fnc_exists);
- KVSM_REGISTER_FUNCTION(m,"type",file_kvs_fnc_type);
- KVSM_REGISTER_FUNCTION(m,"size",file_kvs_fnc_size);
-
- KVSM_REGISTER_FUNCTION(m,"allsizes",file_kvs_fnc_allSizes);
-
- KVSM_REGISTER_FUNCTION(m,"fixpath",file_kvs_fnc_fixpath);
- KVSM_REGISTER_FUNCTION(m,"ps",file_kvs_fnc_ps);
- KVSM_REGISTER_FUNCTION(m,"read",file_kvs_fnc_read);
- KVSM_REGISTER_FUNCTION(m,"localdir",file_kvs_fnc_localdir);
- KVSM_REGISTER_FUNCTION(m,"homedir",file_kvs_fnc_homedir);
- KVSM_REGISTER_FUNCTION(m,"rootdir",file_kvs_fnc_rootdir);
- KVSM_REGISTER_FUNCTION(m,"cwd",file_kvs_fnc_cwd);
- KVSM_REGISTER_FUNCTION(m,"globaldir",file_kvs_fnc_globaldir);
- KVSM_REGISTER_FUNCTION(m,"extractpath",file_kvs_fnc_extractpath);
- KVSM_REGISTER_FUNCTION(m,"extractfilename",file_kvs_fnc_extractfilename);
- KVSM_REGISTER_FUNCTION(m,"ls",file_kvs_fnc_ls);
- KVSM_REGISTER_FUNCTION(m,"readLines",file_kvs_fnc_readLines);
-
-
- return true;
-}
-
-static bool file_module_cleanup(KviModule *m)
-{
- return true;
-}
-
-KVIRC_MODULE(
- "File", // module name
- "1.0.0", // module version
- "Copyright (C) 2001 Szymon Stefanek (pragma at kvirc dot net)", // author & (C)
- "Interface to the file system",
- file_module_init,
- 0,
- 0,
- file_module_cleanup
-)
+//============================================================================= +// +// File : libkvifile.cpp +// Creation date : Fri Nov 9 03:27:59 2001 GMT by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2001-2005 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +//============================================================================= + +#include "kvi_module.h" +#include "kvi_fileutils.h" +#include "kvi_locale.h" +#include "kvi_malloc.h" +#include "kvi_app.h" +#include "kvi_options.h" +#include "kvi_qcstring.h" + +#include "kvi_kvs_arraycast.h" + +#include <qfileinfo.h> +#include "kvi_file.h" +#include <qdir.h> +#include <qtextstream.h> + +/* + @doc: file.copy + @type: + command + @title: + file.copy + @keyterms: + copying files + @short: + Makes a copy of a file + @syntax: + file.copy [-o] <source:string> <destination:string> + @switches: + !sw: -o | --overwrite + Overwrites the file even if it already exists. + @description: + Makes a copy of the <source> file as <destination>.[br] + If the [-o] switch is used , the <destination> file is overwritten , if already exists.[br] + With no [-o] switch , this command does not overwrite files.[br] + The destination path must be already existing: if you want to ensure this, use [fnc]$file.mkdir[/fnc] first.[br] + The paths (<source> and <destination>) are adjusted according to the system that KVIrc + is running on so you don't have to bother about portability: it *should* be automatically + guaranteed. Just use UNIX style paths for them.[br] + @seealso: + [cmd]file.rename[/cmd], [fnc]$file.exists[/fnc]() +*/ + +static bool file_kvs_cmd_copy(KviKvsModuleCommandCall * c) +{ + QString szSrc,szDst; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("source",KVS_PT_NONEMPTYSTRING,0,szSrc) + KVSM_PARAMETER("destination",KVS_PT_NONEMPTYSTRING,0,szDst) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szSrc); + KviFileUtils::adjustFilePath(szDst); + if(KviFileUtils::fileExists(szDst) && !c->switches()->find('o',"overwrite")) + { + c->warning(__tr2qs("Destinaion file exists: no copy made")); + return true; + } + if(!KviFileUtils::copyFile(szSrc,szDst)) + { + c->warning(__tr2qs("Failed to copy from %Q to %Q"),&szSrc,&szDst); + c->warning(__tr2qs("Either the source doesn't exist or the destination can not be created")); + } + return true; +} + + +/* + @doc: file.addimagepath + @type: + command + @title: + file.addimagepath + @short: + Adds an image search path + @syntax: + file.addimagepath <path:string> + @description: + Adds <path> to the image search path list.[br] + KVIrc will look for images files (also) in that path (when a relative image file name is used).[br] + Yes, this function is a bit misplaced... + @seealso: + [cmd]file.delimagepath[/cmd] +*/ + +static bool file_kvs_cmd_addimagepath(KviKvsModuleCommandCall * c) +{ + QString szDst; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("path",KVS_PT_NONEMPTYSTRING,0,szDst) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szDst); + + QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).find(szDst); + if(it == KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).end()) + KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).append(szDst); + return true; +} + + + +/* + @doc: file.delimagepath + @type: + command + @title: + file.delimagepath + @short: + Removes an image search path + @syntax: + file.delimagepath <path:string> + @description: + Removes <path> from the image search path list.[br] + Yes, this function is a bit misplaced... + @seealso: + [cmd]file.addimagepath[/cmd] +*/ + +static bool file_kvs_cmd_delimagepath(KviKvsModuleCommandCall * c) +{ + QString szDst; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("path",KVS_PT_NONEMPTYSTRING,0,szDst) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szDst); + + QStringList::Iterator it = KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).find(szDst); + if(it == KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).end()) + KVI_OPTION_STRINGLIST(KviOption_stringlistImageSearchPaths).remove(szDst); + return true; +} + + +/* + @doc: file.write + @type: + command + @title: + file.write + @keyterms: + writing data to files + @short: + Writes an ascii data string to a file + @syntax: + file.write [-a] [-l] <filename:string> <data:string> + @switches: + !sw: -a | --append + If the file already exists, append the data instead of overwriting the original contents. + !sw: -l | --local-8-bit + Causes the file to be written in the local 8 bit character set instead of the + default utf8. + @description: + Writes <data> (which is an ASCII string) to the file <filename>.[br] + It does NOT append a traling LF character: if you want it you must explicitly specify it in the <data> parameter.[br] + -a causes the command to append the <data> to the file instead of overwriting the entire file.[br] + The path is adjusted according to the system that KVIrc + is running on so you don't have to bother about portability: it *should* be automatically + guaranteed. Just use UNIX style paths for them.[br] + The file is saved in utf8 unless the -l switch is specified (in that case the local 8 bit encoding is used). + Please note that uf8 is the only character set that preserves ALL the possible characters. + @seealso: + [cmd]file.rename[/cmd], [fnc]$file.exists[/fnc]() +*/ + +static bool file_kvs_cmd_write(KviKvsModuleCommandCall * c) +{ + QString szFileName,szData; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szFileName) + KVSM_PARAMETER("data",KVS_PT_NONEMPTYSTRING,0,szData) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szFileName); + + bool bRet; + if(c->switches()->find('l',"local-8-bit")) + bRet = KviFileUtils::writeFileLocal8Bit(szFileName,szData,c->switches()->find('a',"append")); + else + bRet = KviFileUtils::writeFile(szFileName,szData,c->switches()->find('a',"append")); + + if(!bRet) + c->warning(__tr2qs("Failed to write to file %Q: the destination couldn't be opened"),&szFileName); + + return true; +} + + +/* + @doc: file.rename + @type: + command + @title: + file.rename + @keyterms: + copying files + @short: + Makes a copy of a file + @syntax: + file.rename <oldname:string> <newname:string> + @description: + Renames a file from <oldname> to <newname>.[br] + This command can also rename directories.[br] + If the <newname> file already exists , this command fails.[br] + The paths (<oldname> and <newname>) are adjusted according to the system that KVIrc + is running on so you don't have to bother about portability: it *should* be automatically + guaranteed.Just use UNIX style paths for them.[br] + @seealso: + [cmd]file.copy[/cmd], [fnc]$file.exists[/fnc]() +*/ + +static bool file_kvs_cmd_rename(KviKvsModuleCommandCall * c) +{ + QString szOld,szNew; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("oldname",KVS_PT_NONEMPTYSTRING,0,szOld) + KVSM_PARAMETER("newname",KVS_PT_NONEMPTYSTRING,0,szNew) + KVSM_PARAMETERS_END(c) + + KviFileUtils::adjustFilePath(szOld); + KviFileUtils::adjustFilePath(szNew); + + if(KviFileUtils::fileExists(szNew)) + c->warning(__tr2qs("Destination file exists: file not renamed")); + + if(!KviFileUtils::renameFile(szOld,szNew)) + c->warning(__tr2qs("Failed to rename %Q to %Q"),&szOld,&szNew); + return true; +} + + +/* + @doc: file.mkdir + @type: + command + @title: + file.mkdir + @keyterms: + creating directories + @short: + Creates a directory + @syntax: + file.mkdir <directory:string> + @description: + Creates the <directory>.[br] + The path is adjusted according to the system that KVIrc + is running on so you don't have to bother about portability: it *should* be automatically + guaranteed. Just use an UNIX style path.[br] + @seealso: + [fnc]$file.exists[/fnc]() +*/ + +static bool file_kvs_cmd_mkdir(KviKvsModuleCommandCall * c) +{ + QString szDir; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("directory",KVS_PT_NONEMPTYSTRING,0,szDir) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szDir); + if(!KviFileUtils::makeDir(szDir)) + c->warning(__tr2qs("Failed to make the directory %Q"),&szDir); + return true; +} + + + +/* + @doc: file.remove + @type: + command + @title: + file.remove + @keyterms: + removing files + @short: + Removes a file + @syntax: + file.remove [-q] <name:string> + @switches: + !sw: -q | --quiet + Suppresses any warning message + @description: + Removes the file <name>.[br] + -q suppresses any warning message (about non existing file , for example).[br] + The path is adjusted according to the system that KVIrc + is running on so you don't have to bother about portability: it *should* be automatically + guaranteed. Just use an UNIX style path.[br] + @seealso: + [fnc]$file.exists[/fnc]() +*/ + +static bool file_kvs_cmd_remove(KviKvsModuleCommandCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("name",KVS_PT_NONEMPTYSTRING,0,szName) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szName); + if(!KviFileUtils::removeFile(szName)) + { + if(!c->switches()->find('q',"quiet")) + c->warning(__tr2qs("Failed to remove the file %Q"),&szName); + } + return true; +} + + +/* + @doc: file.rmdir + @type: + command + @title: + file.rmdir + @keyterms: + removing directories + @short: + Removes a directory + @syntax: + file.rmdir [-q] <name:string> + @switches: + !sw: -q | --quiet + Suppresses any warning message + @description: + Removes the directory <name>.[br] + The directory must be empty for this command to success.[br] + -q suppresses any warning message (about non existing directory , for example).[br] + The path is adjusted according to the system that KVIrc + is running on so you don't have to bother about portability: it *should* be automatically + guaranteed. Just use an UNIX style path.[br] + @seealso: + [fnc]$file.exists[/fnc]() + [cmd]file.remove[/cmd] +*/ + +static bool file_kvs_cmd_rmdir(KviKvsModuleCommandCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("name",KVS_PT_NONEMPTYSTRING,0,szName) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szName); + if(!KviFileUtils::removeDir(szName)) + { + if(!c->switches()->find('q',"quiet")) + c->warning(__tr2qs("Failed to remove the directory %Q"),&szName); + } + return true; +} + + +/* + @doc: file.exists + @type: + function + @title: + $file.exists + @short: + Check if a file exists + @syntax: + <boolean> $file.exists(<filename:string>) + @description: + Returns true if the file <filename> exists (this is also valid for directories!).[br] + The <filename> should be an unix-style file path and is adjusted according to the system that KVIrc is running on.[br] +*/ + +static bool file_kvs_fnc_exists(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filename",KVS_PT_STRING,0,szName) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szName); + QFileInfo f(szName); + c->returnValue()->setBoolean(f.exists()); + return true; +} + + +/* + @doc: file.type + @type: + function + @title: + $file.type + @short: + Checks the type of a path + @syntax: + <string> $file.type(<filename:string>) + @description: + Returns "f" if the <filename> points to a real file , "d" if <filename> + is the name of a directory or "l" if it is a symbolic link.[br] + The <filename> should be an unix-style file path and is adjusted according to the system that KVIrc is running on.[br] +*/ + +static bool file_kvs_fnc_type(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szName) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szName); + QFileInfo f(szName); + if(f.isFile())c->returnValue()->setString("f"); + else if(f.isDir())c->returnValue()->setString("d"); + else if(f.isSymLink())c->returnValue()->setString("l"); + return true; +} + + +/* + @doc: file.size + @type: + function + @title: + $file.size + @short: + Returns the size of a file + @syntax: + <integer> $file.size(<filename:string>) + @description: + Returns the size of the file pointed by <filename>.[br] + If the file does not exist , this function returns 0.[br] + The <filename> should be an unix-style file path and is adjusted according to the system that KVIrc is running on.[br] +*/ + +static bool file_kvs_fnc_size(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szName) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szName); + QFileInfo f(szName); + c->returnValue()->setInteger(f.size()); + return true; +} +/* + @doc: file.allSizese + @type: + function + @title: + $file.allSizes + @short: + Returns all sizes of a specified directory. + @syntax: + <array> $file.allSize(<dirname:string>) + @description: + Returns the size of every files of the specified directory as an array.[br] +*/ + +static bool file_kvs_fnc_allSizes(KviKvsModuleFunctionCall * c) +{ + QString szDir; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("directory",KVS_PT_NONEMPTYSTRING,0,szDir) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szDir); + + QDir d(szDir); + if(!d.exists()) + { + c->warning(__tr2qs("The specified directory does not exist '%Q'"),&szDir); + return true; + } + + QStringList sl; + sl = d.entryList(QDir::Files); + + KviKvsArray * a = new KviKvsArray(); + QString szFile; + if(!sl.isEmpty()) + { + int idx = 0; + for(QStringList::Iterator it = sl.begin();it != sl.end();++it) + { + szFile=szDir+(*it); + QFileInfo f(szFile); + a->set(idx,new KviKvsVariant((kvs_int_t)f.size())); + idx++; + } + } + c->returnValue()->setArray(a); + + + + + return true; +} + +/* + @doc: file.fixpath + @type: + function + @title: + $file.fixpath + @short: + Converts file paths + @syntax: + <string> $file.fixpath(<filename:string>) + @description: + Returns the <filename> adjusted to match the current operating + system file path conventions.[br] This means that on UNIX , a path like "C:\folder\file.mp3" + will be returned as "/folder/file.mp3" and vice-versa.[br] + There is a minor problem with unix paths converted to the windows system: unix + has no "drive" concept thus the unix paths do not contain a drive. KVIrc will + always map the paths to the "default" C: drive.[br] + This is a good reason to avoid using absolute hard-coded paths :).[br] + Please note that you DON'T NEED to call this function on paths that you + pass to the other file.* functions: they are adjusted automatically.[br] + @seealso: + [fnc]$file.ps[/fnc] +*/ + + +static bool file_kvs_fnc_fixpath(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filename",KVS_PT_STRING,0,szName) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szName); + c->returnValue()->setString(szName); + return true; +} + + +/* + @doc: file.ps + @type: + function + @title: + $file.ps + @short: + Returns the file path separator + @syntax: + <string> $file.ps() + @description: + Returns the file path separator for the current operating system.[br] + On windows , '\' is returned , on UNIX , '/'.[br] + @seealso: + [fnc]$file.fixpath[/fnc] +*/ + +static bool file_kvs_fnc_ps(KviKvsModuleFunctionCall * c) +{ + c->returnValue()->setString(QString(QChar(KVI_PATH_SEPARATOR_CHAR))); + return true; +} + + +/* + @doc: file.ls + @type: + function + @title: + $file.ls + @short: + Returns a directory listing + @syntax: + <array> $file.ls(<directory:string>,[<flags:string>[,<namefilter:string>]]) + @description: + Returns the listing of the specified directory as an array.[br] + The <directory> should be an unix-style file path and is adjusted according to the system that KVIrc is running on.[br] + <flags> may be a combination of the following characters:[br] + d: list directories[br] + f: list files[br] + l: list symbolic links[br] + r: list readable files[br] + w: list writeable files[br] + x: list executable files[br] + h: list hidden files[br] + s: list system files[br] + n: sort files by name[br] + t: sort files by file time[br] + b: sort files by file size[br] + z: put the directories first, then the files[br] + k: invert sort order[br] + i: case insensitive sort[br] + If <flags> is empty then a default of 'dfrwxhs'.[br] + If none of r,w,x is set then KVIrc sets all of them by default.[br] + If <namefilter> is passed then it is interpreted as a wildcard string + that must match the entries to be returned.[br] + @example: + [example] + %dir[]=$file.ls(/,"d") + [cmd]foreach[/cmd](%f,%dir[])echo %f + %dir[]=$file.ls(/usr/include,"f","t*.h"); + [cmd]foreach[/cmd](%f,%dir[])echo %f + %dir[]=$file.ls($file.homedir,"dfr"); + [cmd]foreach[/cmd](%f,%dir[])echo %f + [/example] +*/ + +static bool file_kvs_fnc_ls(KviKvsModuleFunctionCall * c) +{ + QString szDir,szFlags,szFilter; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("directory",KVS_PT_NONEMPTYSTRING,0,szDir) + KVSM_PARAMETER("flags",KVS_PT_STRING,KVS_PF_OPTIONAL,szFlags) + KVSM_PARAMETER("filter",KVS_PT_STRING,KVS_PF_OPTIONAL,szFilter) + KVSM_PARAMETERS_END(c) + + KviFileUtils::adjustFilePath(szDir); + + QDir d(szDir); + if(!d.exists()) + { + c->warning(__tr2qs("The specified directory does not exist '%Q'"),&szDir); + return true; + } + +#ifdef COMPILE_USE_QT4 + QFlags<QDir::Filter> iFlags = 0; +#else + int iFlags = 0; +#endif + if(szFlags.isEmpty())iFlags = QDir::Dirs | QDir::Files | QDir::NoSymLinks | QDir::Readable | QDir::Writable | QDir::Executable | QDir::Hidden | QDir::System; + else { + if(szFlags.find('d',false) != -1)iFlags |= QDir::Dirs; + if(szFlags.find('f',false) != -1)iFlags |= QDir::Files; + if(szFlags.find('l',false) == -1)iFlags |= QDir::NoSymLinks; + if(szFlags.find('r',false) != -1)iFlags |= QDir::Readable; + if(szFlags.find('w',false) != -1)iFlags |= QDir::Writable; + if(szFlags.find('x',false) != -1)iFlags |= QDir::Executable; + if(szFlags.find('h',false) != -1)iFlags |= QDir::Hidden; + if(szFlags.find('s',false) != -1)iFlags |= QDir::System; + } +#ifdef COMPILE_USE_QT4 + QFlags<QDir::SortFlag> iSort = 0; +#else + int iSort = 0; +#endif + if(szFlags.isEmpty())iSort = QDir::Unsorted; + else { + if(szFlags.find('n',false) != -1)iSort |= QDir::Name; + if(szFlags.find('t',false) != -1)iSort |= QDir::Time; + if(szFlags.find('b',false) != -1)iSort |= QDir::Size; + if(szFlags.find('z',false) != -1)iSort |= QDir::DirsFirst; + if(szFlags.find('k',false) != -1)iSort |= QDir::Reversed; + if(szFlags.find('i',false) != -1)iSort |= QDir::IgnoreCase; + } + + QStringList sl; + if(!szFilter.isEmpty())sl = d.entryList(szFilter,iFlags,iSort); + else sl = d.entryList(iFlags,iSort); + + KviKvsArray * a = new KviKvsArray(); + if(!sl.isEmpty()) + { + int idx = 0; + for(QStringList::Iterator it = sl.begin();it != sl.end();++it) + { + a->set(idx,new KviKvsVariant(*it)); + idx++; + } + } + c->returnValue()->setArray(a); + + return true; +} + +/* + @doc: file.read + @type: + function + @title: + $file.read + @short: + Reads a text file + @syntax: + <string> $file.read(<filename:string>[,<size:integer>[,<flags:string>]]) + @description: + Reads at most <size> bytes of the file pointed by <filename>.[br] + <size> is an upper limit but may be not reached if the real file is smaller.[br] + The data read is returned as a string , so if the file contains binary data, + expect strange results.[br] If <size> is not specified, then KVIrc tries to read + the whole file up to the 1 MB limit (so if you want to read a file that is + bigger thatn 1 MB then you MUST specify the <size>).[br] + WARNING: always check the file size before attemting to read a whole file... + reading a CDROM iso image may sit down your system :) (and will prolly crash while + allocating memory , before attempting to read anything)[br] + An empty string is returned if a serious error occures.[br] + The <filename> is adjusted according to the system that KVIrc is running on.[br] + Flags are actually limited to the single letter 'l'. By default the file + is decoded from the ut8 characters set. If 'l' is present the the file + is decoded by using the local 8 bit character set instead. + @examples: + [example] + echo $file.read(/proc/cpuinfo) + [/example] + @seealso: + [fnc]$file.readbinary[/fnc] +*/ + +static bool file_kvs_fnc_read(KviKvsModuleFunctionCall * c) +{ + QString szNameZ; + kvs_uint_t uSize; + QString szFlags; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szNameZ) + KVSM_PARAMETER("size",KVS_PT_UINT,KVS_PF_OPTIONAL,uSize) + KVSM_PARAMETER("flags",KVS_PT_STRING,KVS_PF_OPTIONAL,szFlags) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szNameZ); + + QFile f(szNameZ); + if(!f.open(IO_ReadOnly)) + { + c->warning(__tr2qs("Can't open the file \"%Q\" for reading"),&szNameZ); + return true; + } + + if(c->params()->count() < 2)uSize = 1024 * 1024; // 1 meg file default + + char * buf = (char *)kvi_malloc(sizeof(char) * (uSize + 1)); + unsigned int uReaded = 0; + unsigned int uRetries = 0; + + while((uReaded < uSize) && (!f.atEnd())) + { + int readedNow = f.readBlock(buf + uReaded,uSize - uReaded); + if(readedNow < 0) + { + kvi_free(buf); + c->warning(__tr2qs("Read error for file %Q"),&szNameZ); + return true; + } else readedNow += uReaded; + uRetries ++; + if(uRetries > 1000) + { + // ops + kvi_free(buf); + c->warning(__tr2qs("Read error for file %Q (have been unable to read the requested size in 1000 retries)"),&szNameZ); + return true; + } + uReaded += readedNow; + } + + buf[uReaded] = '\0'; + + if(szFlags.find('l',false) == -1) + c->returnValue()->setString(QString::fromUtf8(buf)); + else + c->returnValue()->setString(QString::fromLocal8Bit(buf)); + + kvi_free(buf); + + return true; +} + + +/* + @doc: file.readLines + @type: + function + @title: + $file.readLines + @short: + Reads lines of a text file + @syntax: + <array> $file.readLines(<filename:string>[,<startline:integer>,[<count:integer>[,<flags:string>]]]) + @description: + Reads lines from the specified file and returns them as an array of strings. + The lines are assumed to be separated by linefeed characters (which are NOT returned). + Eventual terminating carriage return characters at the end of the line are stripped. + If <startline> is specified, then all the lines with indexes lower that <startline> are + discarded. If <count> is specified then a maximum of <count> lines is returned. + If <count> is not specified then all the lines until the end are read. + The <filename> is adjusted according to the system that KVIrc is running on.[br] + Flags are actually limited to the single letter 'l'. By default the file + is decoded from the ut8 characters set. If 'l' is present the the file + is decoded by using the local 8 bit character set instead. + WARNING: Always check the size of the file you're going to read: it is not + a good idea attempting to read a 700 MB binary file with this function since + it will probably sit down your system and exhaust your virtual memory. + @examples: + [example] + echo $file.readLines(/proc/cpuinfo) + [/example] + @seealso: + [fnc]$file.read[/fnc](), [cmd]file.writeLines[/fnc], [fnc]$lf[/fnc] +*/ + + + +static bool file_kvs_fnc_readLines(KviKvsModuleFunctionCall * c) +{ + QString szName; + QString szFlags; + kvs_int_t iStartLine; + kvs_int_t iCount; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szName) + KVSM_PARAMETER("startline",KVS_PT_INT,KVS_PF_OPTIONAL,iStartLine) + KVSM_PARAMETER("count",KVS_PT_INT,KVS_PF_OPTIONAL,iCount) + KVSM_PARAMETER("flags",KVS_PT_STRING,KVS_PF_OPTIONAL,szFlags) + KVSM_PARAMETERS_END(c) + KviFileUtils::adjustFilePath(szName); + + QFile f(szName); + if(!f.open(IO_ReadOnly)) + { + c->warning(__tr2qs("Can't open the file \"%Q\" for reading"),&szName); + return true; + } + + if(c->params()->count() < 2)iStartLine = 0; + if(c->params()->count() < 3)iCount = -1; + + bool bLocal8Bit = szFlags.find('l',0,false) != -1; + + KviKvsArray * a = new KviKvsArray(); + + int iIndex=0; + + QTextStream stream( &f ); + + stream.setEncoding(bLocal8Bit ? QTextStream::Locale : QTextStream::UnicodeUTF8); + for(int i=0;i<iStartLine;i++) + stream.readLine(); + + if(iCount>0) + { + for(; (iCount>0 && !stream.atEnd()) ; iCount-- ) + a->set(iIndex,new KviKvsVariant(stream.readLine())); + iIndex++; + } else { + while(!stream.atEnd()) { + a->set(iIndex,new KviKvsVariant(stream.readLine())); + iIndex++; + } + } + + f.close(); + + c->returnValue()->setArray(a); + + return true; +} + + +/* + @doc: file.writelines + @type: + command + @title: + file.writeLines + @short: + Writes an array of lines to a file + @syntax: + file.writeLines [-l] [-a] [-c] <filename:string> <lines:array> + @switches: + !sw: -l | --local-8-bit + Causes the lines to be saved in local 8 bit character set instead + of the default unicode encoding. + !sw: -a | --append + If the file already exists, then the lines are appended to the end + instead of overwriting the file. + !sw: -c | --crlf + The lines are separated by a carriage-return+line-feed character + combination, compatible with windows text mode files. + This is the only way to make the file readable in windows notepad, for example. + Please note that this is broken design: do NOT use it :) + !sw: -n | --no-separator + Do not separate the lines at all (either the separators are already + inside the lines array or no line separation is desired at all). + -n takes precedence over -c. + !sw: -q | --quiet + Don't complain if the file can't be opened: just fail silently + @description: + Writes the array of <lines> to the specified file. + The lines are separated by a single linefeed character (see also [fnc]$lf[/fnc]) + unless the -c or -n switches are used. If the file already exists then it is + overwritten with the new data unless the -a switch is used. + The lines array is encoded in the ut8 character set unless the -l switch is used. + @seealso: + [fnc]$file.readLines[/fnc] +*/ + + + +static bool file_kvs_cmd_writeLines(KviKvsModuleCommandCall * c) +{ + QString szFile,szFlags; + KviKvsArrayCast a; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filename",KVS_PT_NONEMPTYSTRING,0,szFile) + KVSM_PARAMETER("lines",KVS_PT_ARRAYCAST,0,a) + KVSM_PARAMETERS_END(c) + + KviFileUtils::adjustFilePath(szFile); + + KviFile f(szFile); + int iFlags = IO_WriteOnly; + + if(!f.openForWriting(c->switches()->find('a',"append"))) + { + if(!c->switches()->find('q',"quiet")) + c->warning(__tr2qs("Can't open the file \"%Q\" for writing"),&szFile); + return true; + } + + bool bLocal8Bit = c->switches()->find('l',"local-8-bit"); + bool bNoSeparator = c->switches()->find('n',"no-separator"); + bool bAddCR = c->switches()->find('c',"crlf"); + + unsigned int u = 0; + while(u < a.array()->size()) + { + KviKvsVariant * v = a.array()->at(u); + KviQCString dat; + if(v) + { + QString szDat; + v->asString(szDat); + KviQCString dat = bLocal8Bit ? szDat.local8Bit() : szDat.utf8(); + } + if(!bNoSeparator) + { + if(bAddCR)dat += "\r\n"; + else dat += '\n'; + } + f.writeBlock(dat.data(),dat.length()); + u++; + } + + f.close(); + + return true; +} + + +/* + @doc: file.localdir + @type: + function + @title: + $file.localdir + @short: + Get the KVIrc local directory + @syntax: + <string> $file.localdir([relative_path:string]) + @description: + Returns the path to the KVIrc local data directory.[br] + The KVIrc local data directory is always writeable and contains + the various subdirectories that KVIrc uses internally: audio , avatars , + config , help , incoming , log , modules , msgcolors and pics.[br] + If <relative_path> is passed , then it is appended at the end of the directory + to form a complete filepath.[br] + The path is adjusted to contain single separators suitable for the platform + that KVIrc is atually running on (thus you not need to care about path + separators in the <relative_path> , KVIrc will adjust them).[br] + @examples: + [example] + echo KVIrc looks for pictures in $file.localdir(pics) + echo panic.png would be translated to $file.localdir(pics/panic.png) + [/example] +*/ + +static bool file_kvs_fnc_localdir(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName) + KVSM_PARAMETERS_END(c) + if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR); + QString szPath; + g_pApp->getLocalKvircDirectory(szPath,KviApp::None,szName); + KviFileUtils::adjustFilePath(szPath); + c->returnValue()->setString(szPath); + return true; +} + + + +/* + @doc: file.homedir + @type: + function + @title: + $file.homedir + @short: + Get the user's HOME directory + @syntax: + <string> $file.homedir([relative_path:string]) + @description: + Returns the user's HOME directory path.[br] + If <relative_path> is passed , then it is appended at the end of the directory + to form a complete filepath.[br] + The path is adjusted to contain single separators suitable for the platform + that KVIrc is atually running on (thus you not need to care about path + separators in the <relative_path> , KVIrc will adjust them).[br] +*/ + +static bool file_kvs_fnc_homedir(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName) + KVSM_PARAMETERS_END(c) + if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR); + QString szPath = QDir::homeDirPath(); + KviQString::ensureLastCharIs(szPath,KVI_PATH_SEPARATOR_CHAR); + szPath.append(szName); + KviFileUtils::adjustFilePath(szPath); + c->returnValue()->setString(szPath); + return true; +} + + + +/* + @doc: file.rootdir + @type: + function + @title: + $file.rootdir + @short: + Get the system root directory + @syntax: + $file.rootdir(<relative_path>) + $file.rootdir + @description: + Returns the system's root directory (/ on UNIX and C:/ on Windows).[br] + If <relative_path> is passed , then it is appended at the end of the directory + to form a complete filepath.[br] + The path is adjusted to contain single separators suitable for the platform + that KVIrc is atually running on (thus you not need to care about path + separators in the <relative_path> , KVIrc will adjust them).[br] +*/ + +static bool file_kvs_fnc_rootdir(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName) + KVSM_PARAMETERS_END(c) + if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR); + QString szPath = QDir::rootDirPath(); + KviQString::ensureLastCharIs(szPath,KVI_PATH_SEPARATOR_CHAR); + szPath.append(szName); + KviFileUtils::adjustFilePath(szPath); + c->returnValue()->setString(szPath); + return true; +} + + +/* + @doc: file.cwd + @type: + function + @title: + $file.currentdir + @short: + Get the current directory + @syntax: + <string> $file.cwd([relative_path:string]) + @description: + Returns the current working directory.[br] + If <relative_path> is passed , then it is appended at the end of the directory + to form a complete filepath.[br] + The path is adjusted to contain single separators suitable for the platform + that KVIrc is atually running on (thus you not need to care about path + separators in the <relative_path> , KVIrc will adjust them).[br] +*/ + +static bool file_kvs_fnc_cwd(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName) + KVSM_PARAMETERS_END(c) + if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR); + QString szPath = QDir::currentDirPath(); + KviQString::ensureLastCharIs(szPath,KVI_PATH_SEPARATOR_CHAR); + szPath.append(szName); + KviFileUtils::adjustFilePath(szPath); + c->returnValue()->setString(szPath); + return true; +} + + +/* + @doc: file.globaldir + @type: + function + @title: + $file.globaldir + @short: + Get the KVIrc global directory + @syntax: + $file.globaldir(<relative_path>) + $file.globaldir + @description: + Returns the path to the KVIrc global data directory.[br] + The KVIrc local data directory is always readable but usually not writeable and contains + the various subdirectories that KVIrc uses internally: audio , avatars , + config , help , incoming , log , modules , msgcolors and pics.[br] + If <relative_path> is passed , then it is appended at the end of the directory + to form a complete filepath.[br] + The path is adjusted to contain single separators suitable for the platform + that KVIrc is atually running on (thus you not need to care about path + separators in the <relative_path> , KVIrc will adjust them).[br] + @examples: + [example] + echo KVIrc looks for pictures in $file.globaldir(pics) + echo panic.png would be translated to $file.globaldir(pics/panic.png) + [/example] +*/ + +static bool file_kvs_fnc_globaldir(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("relative_path",KVS_PT_STRING,KVS_PF_OPTIONAL,szName) + KVSM_PARAMETERS_END(c) + if(szName.isEmpty())szName.append(KVI_PATH_SEPARATOR_CHAR); + QString szPath; + g_pApp->getGlobalKvircDirectory(szPath,KviApp::None,szName); + KviFileUtils::adjustFilePath(szPath); + c->returnValue()->setString(szPath); + return true; +} + +/* + @doc: file.extractpath + @type: + function + @title: + $file.extractpath + @short: + Extract the path from a filename + @syntax: + <string> $file.extractpath(<filepath:string>) + @description: + Returns the path part of the <filepath> translated to match the current + platform filesystem conventions.[br] + The path will NOT contain a trailing path separator.[br] + For example, if <filepath> is /usr/arch/mp3/Carisma_SuonoDelSilenzio.mp3 then + this function will return /usr/arch/mp3 on UNIX and C:\usr\arch\mp3 on Windows. + @seealso: + [fnc]$file.extractfilename[/fnc] +*/ + +static bool file_kvs_fnc_extractpath(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filepath",KVS_PT_NONEMPTYSTRING,0,szName) + KVSM_PARAMETERS_END(c) + c->returnValue()->setString(QFileInfo(szName).dirPath(TRUE)); + return true; +} + + +/* + @doc: file.extractfilename + @type: + function + @title: + $file.extractfilename + @short: + Extract the filename from a file path + @syntax: + <string> $file.extractpath(<filepath:string>) + @description: + Returns the filename part of the filepath translated to match the current + platform filesystem conventions.[br] + For example, if <filepath> is /usr/arch/mp3/Carisma_SuonoDelSilenzio.mp3 then + this function will return Carisma_SuonoDelSilenzio.mp3 + @seealso: + [fnc]$file.extractpath[/fnc] +*/ + +static bool file_kvs_fnc_extractfilename(KviKvsModuleFunctionCall * c) +{ + QString szName; + KVSM_PARAMETERS_BEGIN(c) + KVSM_PARAMETER("filepath",KVS_PT_NONEMPTYSTRING,0,szName) + KVSM_PARAMETERS_END(c) + KviFileUtils::extractFileName(szName); + KviQString::cutToLast(szName,KVI_PATH_SEPARATOR_CHAR); + c->returnValue()->setString(szName); + return true; +} + + + +static bool file_module_init(KviModule * m) +{ + + KVSM_REGISTER_SIMPLE_COMMAND(m,"copy",file_kvs_cmd_copy); + KVSM_REGISTER_SIMPLE_COMMAND(m,"rename",file_kvs_cmd_rename); + KVSM_REGISTER_SIMPLE_COMMAND(m,"mkdir",file_kvs_cmd_mkdir); + KVSM_REGISTER_SIMPLE_COMMAND(m,"write",file_kvs_cmd_write); + KVSM_REGISTER_SIMPLE_COMMAND(m,"remove",file_kvs_cmd_remove); + KVSM_REGISTER_SIMPLE_COMMAND(m,"rmdir",file_kvs_cmd_rmdir); + KVSM_REGISTER_SIMPLE_COMMAND(m,"addimagepath",file_kvs_cmd_addimagepath); + KVSM_REGISTER_SIMPLE_COMMAND(m,"delimagepath",file_kvs_cmd_delimagepath); + KVSM_REGISTER_SIMPLE_COMMAND(m,"writeLines",file_kvs_cmd_writeLines); + + KVSM_REGISTER_FUNCTION(m,"exists",file_kvs_fnc_exists); + KVSM_REGISTER_FUNCTION(m,"type",file_kvs_fnc_type); + KVSM_REGISTER_FUNCTION(m,"size",file_kvs_fnc_size); + + KVSM_REGISTER_FUNCTION(m,"allsizes",file_kvs_fnc_allSizes); + + KVSM_REGISTER_FUNCTION(m,"fixpath",file_kvs_fnc_fixpath); + KVSM_REGISTER_FUNCTION(m,"ps",file_kvs_fnc_ps); + KVSM_REGISTER_FUNCTION(m,"read",file_kvs_fnc_read); + KVSM_REGISTER_FUNCTION(m,"localdir",file_kvs_fnc_localdir); + KVSM_REGISTER_FUNCTION(m,"homedir",file_kvs_fnc_homedir); + KVSM_REGISTER_FUNCTION(m,"rootdir",file_kvs_fnc_rootdir); + KVSM_REGISTER_FUNCTION(m,"cwd",file_kvs_fnc_cwd); + KVSM_REGISTER_FUNCTION(m,"globaldir",file_kvs_fnc_globaldir); + KVSM_REGISTER_FUNCTION(m,"extractpath",file_kvs_fnc_extractpath); + KVSM_REGISTER_FUNCTION(m,"extractfilename",file_kvs_fnc_extractfilename); + KVSM_REGISTER_FUNCTION(m,"ls",file_kvs_fnc_ls); + KVSM_REGISTER_FUNCTION(m,"readLines",file_kvs_fnc_readLines); + + + return true; +} + +static bool file_module_cleanup(KviModule *m) +{ + return true; +} + +KVIRC_MODULE( + "File", // module name + "1.0.0", // module version + "Copyright (C) 2001 Szymon Stefanek (pragma at kvirc dot net)", // author & (C) + "Interface to the file system", + file_module_init, + 0, + 0, + file_module_cleanup +) diff --git a/src/modules/objects/class_buttongroup.cpp b/src/modules/objects/class_buttongroup.cpp index 2a7cfe5b2..9cdfc82d2 100644 --- a/src/modules/objects/class_buttongroup.cpp +++ b/src/modules/objects/class_buttongroup.cpp @@ -1,87 +1,87 @@ -//
-// File : class_buttongroup.cpp
-// Creation date : Fri Jan 28 14:21:48 CEST 2005
-// by Tonino Imbesi(Grifisx) and Alessandro Carbone(Noldor)
-//
-// This file is part of the KVirc irc client distribution
-// Copyright (C) 1999-2005 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-//
-
-#include <qbuttongroup.h>
-#include "class_buttongroup.h"
-#include <qradiobutton.h>
-#include "kvi_error.h"
-#include "kvi_debug.h"
-
-#include "kvi_locale.h"
-#include "kvi_iconmanager.h"
-
-
-/*
- @doc: buttongroup
- @keyterms:
- buttongroup object class,
- @title:
- buttongroup class
- @type:
- class
- @short:
- Provides a buttongroup bar.
- @inherits:
- [class]groupbox[/class]
- [class]object[/class]
- [class]widget[/class]
- @description:
- This widget organizes buttons in a group.
- It will be usually a parent for other child controls.
- You can either use a child layout to manage the children geometries
- or use $setColumnLayout function to manage the layout automatically.
- The class ineriths groupbox.
-
- @functions:
-
-*/
-
-KVSO_BEGIN_REGISTERCLASS(KviKvsObject_buttongroup,"buttongroup","groupbox")
-
-KVSO_END_REGISTERCLASS(KviKvsObject_buttongroup)
-
-KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_buttongroup,KviKvsObject_groupbox)
-
-KVSO_END_CONSTRUCTOR(KviKvsObject_buttongroup)
-
-
-KVSO_BEGIN_DESTRUCTOR(KviKvsObject_buttongroup)
-
-KVSO_END_CONSTRUCTOR(KviKvsObject_buttongroup)
-
-// CHECK ME
-bool KviKvsObject_buttongroup::init(KviKvsRunTimeContext * pContext,KviKvsVariantList *pParams)
-{
- #ifdef COMPILE_USE_QT4
- QButtonGroup *group=new QButtonGroup(parentScriptWidget());
- group->setObjectName(name());
- setObject(group,true);
- #else
- setObject(new QButtonGroup(name(),parentScriptWidget()), true);
- #endif
-
-
- return true;
-}
-
-
+// +// File : class_buttongroup.cpp +// Creation date : Fri Jan 28 14:21:48 CEST 2005 +// by Tonino Imbesi(Grifisx) and Alessandro Carbone(Noldor) +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 1999-2005 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// + +#include <qbuttongroup.h> +#include "class_buttongroup.h" +#include <qradiobutton.h> +#include "kvi_error.h" +#include "kvi_debug.h" + +#include "kvi_locale.h" +#include "kvi_iconmanager.h" + + +/* + @doc: buttongroup + @keyterms: + buttongroup object class, + @title: + buttongroup class + @type: + class + @short: + Provides a buttongroup bar. + @inherits: + [class]groupbox[/class] + [class]object[/class] + [class]widget[/class] + @description: + This widget organizes buttons in a group. + It will be usually a parent for other child controls. + You can either use a child layout to manage the children geometries + or use $setColumnLayout function to manage the layout automatically. + The class ineriths groupbox. + + @functions: + +*/ + +KVSO_BEGIN_REGISTERCLASS(KviKvsObject_buttongroup,"buttongroup","groupbox") + +KVSO_END_REGISTERCLASS(KviKvsObject_buttongroup) + +KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_buttongroup,KviKvsObject_groupbox) + +KVSO_END_CONSTRUCTOR(KviKvsObject_buttongroup) + + +KVSO_BEGIN_DESTRUCTOR(KviKvsObject_buttongroup) + +KVSO_END_CONSTRUCTOR(KviKvsObject_buttongroup) + +// CHECK ME +bool KviKvsObject_buttongroup::init(KviKvsRunTimeContext * pContext,KviKvsVariantList *pParams) +{ + #ifdef COMPILE_USE_QT4 + QButtonGroup *group=new QButtonGroup(parentScriptWidget()); + group->setObjectName(name()); + setObject(group,true); + #else + setObject(new QButtonGroup(name(),parentScriptWidget()), true); + #endif + + + return true; +} + + diff --git a/src/modules/objects/class_layout.cpp b/src/modules/objects/class_layout.cpp index f895abd7f..1420aab9b 100644 --- a/src/modules/objects/class_layout.cpp +++ b/src/modules/objects/class_layout.cpp @@ -1,274 +1,274 @@ -//
-// File : class_layout.cpp
-// Creation date : Fri Now 22 2002 00:50:01 by Szymon Stefanek
-//
-// This file is part of the KVirc irc client distribution
-// Copyright (C) 2002 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-//
-#define _KVI_DEBUG_CHECK_RANGE_
-#include "kvi_debug.h"
-
-#include "kvi_locale.h"
-
-#include "class_layout.h"
-
-#ifdef COMPILE_USE_QT4
-#define QLAYOUT_AUTO_CONSTRAINT QLayout::SetDefaultConstraint
-#define QLAYOUT_FIXED QLayout::SetFixedSize
-#define QLAYOUT_FREE_RESIZE QLayout::SetNoConstraint
-#define QLAYOUT_MINIMUM QLayout::SetMinimumSize
-#else
-#define QLAYOUT_AUTO_CONSTRAINT QLayout::Auto
-#define QLAYOUT_FIXED QLayout::Fixed
-#define QLAYOUT_FREE_RESIZE QLayout::FreeResize
-#define QLAYOUT_MINIMUM QLayout::Minimum
-#endif
-
-
-/*
- @doc: layout
- @keyterms:
- layout object class, child widgets
- @title:
- layout class
- @type:
- class
- @short:
- Manages child widget geometry
- @inherits:
- [class]object[/class]
- @description:
- The layout is a geometry management tool for child widgets.
- You create a layout , give it some widgets to manage and it will layout them
- automatically.[br]
- The parent of the layout must be the widget for which child widget geometries have to be managed.
- A layout is a grid of NxM cells in which you insert child widgets with [classfnc:layout]$addWidget[/classfnc]().[br]
- Widgets that must span multiple cells can be added to the layout with [classfnc:layout]$addMultiCellWidget[/classfnc]().[br]
- @functions:
- !fn: $addWidget(<widget:object widget>,<row:uint>,<column:uint>)
- Adds a widget to this layout placing it at position <row>,<column> in the grid
- !fn: $addMultiCellWidget(<widget:object widget>,<start_row:uint>,<end_row:uint>,<start_col:uint>,<end_col:uint>)
- Adds a widget to this layout spanning multiple grid cells
- !fn: $setRowStretch(<row:uint>,<stretch:uint>)
- Sets the stretch value for a particular row of this layout. The <stretch_value>
- must be a positive integer. The rows with bigger stretch values will take more space
- in the layout.
- !fn: $setColStretch(<column:uint>,<stretch:uint>)
- Sets the stretch value for a particular column in this layout. The <stretch_value>
- must be a positive integer. The rows with bigger stretch values will take more space
- in the layout.
- !fn: $addRowSpacing(<row:uint>,<spacing:uint>)
- Sets the minimum height of the specified <row> to <spacing> which must be a positive integer
- !fn: $addColSpacing(<column:uint>,<spacing:uint>)
- Sets the minimum width of the specigfied <column> to <spacing> which must be a positive integer
- !fn: $setSpacing(<spacing:uint>)
- Sets the default spacing of the widgets in pixels
- !fn: $setMargin(<margin:uint>)
- Sets the dimension of the layout margin : the distance from the border to the outermost child widget edges.
- !fn: $setResizeMode(<resize_mode:string>)
- Sets the resize mode of the parent widget in relation to this layout.
- <mode> can be one of:[br]
- -Auto: this is the default[br]
- -Fixed: the parent widget of this layout is resized to the "sizeHint" value and it cannot be resized by the user.[br]
- -Minimum: the minimum size of the parent widget of this layout is set to minimumSize() and it cannot be smaller[br]
- -FreeResize: the parent widget of this layout is not constrained at all[br]
-*/
-
-
-KVSO_BEGIN_REGISTERCLASS(KviKvsObject_layout,"layout","object")
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"addWidget", functionAddWidget)
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"addMultiCellWidget", functionAddMultiCellWidget)
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setRowStretch", functionSetRowStretch)
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setColStretch", functionSetColStretch)
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"addRowSpacing", functionAddRowSpacing)
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"addColSpacing", functionAddColSpacing)
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setMargin", functionSetMargin)
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setSpacing", functionSetSpacing)
- KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setResizeMode", functionSetResizeMode)
-KVSO_END_REGISTERCLASS(KviKvsObject_layout)
-
-KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_layout,KviKvsObject)
-
-KVSO_END_CONSTRUCTOR(KviKvsObject_layout)
-
-
-KVSO_BEGIN_DESTRUCTOR(KviKvsObject_layout)
-
-KVSO_END_CONSTRUCTOR(KviKvsObject_layout)
-
-bool KviKvsObject_layout::init(KviKvsRunTimeContext * pContext,KviKvsVariantList *pParams)
-{
- QWidget * w = parentScriptWidget();
-
- if(!w)
- {
- pContext->warning(__tr2qs("The parent of a layout must be a widget!"));
- return false;
- }
- setObject(new QGridLayout(w));
- return true;
-}
-
-bool KviKvsObject_layout::functionAddWidget(KviKvsObjectFunctionCall *c)
-{
- KviKvsObject * pObject;
- kvs_hobject_t hObject;
- kvs_uint_t uCol,uRow;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("widget",KVS_PT_HOBJECT,0,hObject)
- KVSO_PARAMETER("row",KVS_PT_UNSIGNEDINTEGER,0,uRow)
- KVSO_PARAMETER("col",KVS_PT_UNSIGNEDINTEGER,0,uCol)
- KVSO_PARAMETERS_END(c)
- pObject=KviKvsKernel::instance()->objectController()->lookupObject(hObject);
- if(!widget())return true;
- if (!pObject)
- {
- c->warning(__tr2qs("Widget parameter is not an object"));
- return true;
- }
- if (!pObject->object())
- {
- c->warning(__tr2qs("Widget parameter is not a valid object"));
- return true;
- }
- if(!pObject->object()->isWidgetType())
- {
- c->warning(__tr2qs("Can't add a non-widget object"));
- return true;
- }
- ((QGridLayout *)object())->addWidget(((QWidget *)(pObject->object())),uRow,uCol);
- return true;
-}
-bool KviKvsObject_layout::functionAddMultiCellWidget(KviKvsObjectFunctionCall *c)
-{
- KviKvsObject * pObject;
- kvs_hobject_t hObject;
- kvs_uint_t uStartCol,uStartRow,uEndCol,uEndRow;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("widget",KVS_PT_HOBJECT,0,hObject)
- KVSO_PARAMETER("start_row",KVS_PT_UNSIGNEDINTEGER,0,uStartRow)
- KVSO_PARAMETER("end_row",KVS_PT_UNSIGNEDINTEGER,0,uEndRow)
- KVSO_PARAMETER("start_column",KVS_PT_UNSIGNEDINTEGER,0,uStartCol)
- KVSO_PARAMETER("end_column",KVS_PT_UNSIGNEDINTEGER,0,uEndCol)
- KVSO_PARAMETERS_END(c)
- pObject=KviKvsKernel::instance()->objectController()->lookupObject(hObject);
- if(!widget())return true;
- if (!pObject)
- {
- c->warning(__tr2qs("Widget parameter is not an object"));
- return true;
- }
- if (!pObject->object())
- {
- c->warning(__tr2qs("Widget parameter is not a valid object"));
- return true;
- }
- if(!pObject->object()->isWidgetType())
- {
- c->warning(__tr2qs("Can't add a non-widget object"));
- return true;
- }
- ((QGridLayout *)object())->addMultiCellWidget(((QWidget *)(pObject->object())),uStartRow,uEndRow,uStartCol,uEndCol);
- return true;
-}
-bool KviKvsObject_layout::functionSetRowStretch(KviKvsObjectFunctionCall *c)
-{
- kvs_uint_t uRow,uStretch;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("row",KVS_PT_UNSIGNEDINTEGER,0,uRow)
- KVSO_PARAMETER("stretch",KVS_PT_UNSIGNEDINTEGER,0,uStretch)
- KVSO_PARAMETERS_END(c)
- if(!widget())return true;
- ((QGridLayout *)object())->setRowStretch(uRow,uStretch);
- return true;
-}
-bool KviKvsObject_layout::functionSetColStretch(KviKvsObjectFunctionCall *c)
-{
- kvs_uint_t uCol,uStretch;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("column",KVS_PT_UNSIGNEDINTEGER,0,uCol)
- KVSO_PARAMETER("stretch",KVS_PT_UNSIGNEDINTEGER,0,uStretch)
- KVSO_PARAMETERS_END(c)
- if(!widget())return true;
- ((QGridLayout *)object())->setColStretch(uCol,uStretch);
- return true;
-}
-
-bool KviKvsObject_layout::functionSetMargin(KviKvsObjectFunctionCall *c)
-{
- kvs_uint_t uMargin;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("margin",KVS_PT_UNSIGNEDINTEGER,0,uMargin)
- KVSO_PARAMETERS_END(c)
- if (widget()) ((QGridLayout *)object())->setMargin(uMargin);
- return true;
-}
-
-bool KviKvsObject_layout::functionSetSpacing(KviKvsObjectFunctionCall *c)
-{
- kvs_uint_t uSpacing;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("spacing",KVS_PT_UNSIGNEDINTEGER,0,uSpacing)
- KVSO_PARAMETERS_END(c)
- if (widget()) ((QGridLayout *)object())->setSpacing(uSpacing);
- return true;
-}
-
-
-bool KviKvsObject_layout::functionAddRowSpacing(KviKvsObjectFunctionCall *c)
-{
- kvs_uint_t uSpacing,uRow;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("row",KVS_PT_UNSIGNEDINTEGER,0,uRow)
- KVSO_PARAMETER("spacing",KVS_PT_UNSIGNEDINTEGER,0,uSpacing)
- KVSO_PARAMETERS_END(c)
- if (widget()) ((QGridLayout *)object())->addRowSpacing(uRow,uSpacing);
- return true;
-}
-
-bool KviKvsObject_layout::functionAddColSpacing(KviKvsObjectFunctionCall *c)
-{
- kvs_uint_t uSpacing,uCol;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("column",KVS_PT_UNSIGNEDINTEGER,0,uCol)
- KVSO_PARAMETER("spacing",KVS_PT_UNSIGNEDINTEGER,0,uSpacing)
- KVSO_PARAMETERS_END(c)
- if (widget()) ((QGridLayout *)object())->addColSpacing(uCol,uSpacing);
- return true;
-}
-
-bool KviKvsObject_layout::functionSetResizeMode(KviKvsObjectFunctionCall *c)
-{
- QString szMode;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("resize_mode",KVS_PT_STRING,0,szMode)
- KVSO_PARAMETERS_END(c)
- if(!widget())return true;
-#ifdef COMPILE_USE_QT4
- QLayout::SizeConstraint r = QLAYOUT_AUTO_CONSTRAINT;
-#else
- QLayout::ResizeMode r = QLAYOUT_AUTO_CONSTRAINT;
-#endif
- if(KviQString::equalCI(szMode,"FreeResize")) r = QLAYOUT_FREE_RESIZE;
- else if(KviQString::equalCI(szMode,"Minimum")) r = QLAYOUT_MINIMUM;
- else if(KviQString::equalCI(szMode,"Fixed"))r = QLAYOUT_FIXED;
- else c->warning(__tr2qs("Invalid resize mode defaulting to Auto"));
- ((QGridLayout *)object())->setResizeMode(r);
- return true;
-
-}
-
+// +// File : class_layout.cpp +// Creation date : Fri Now 22 2002 00:50:01 by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2002 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +#define _KVI_DEBUG_CHECK_RANGE_ +#include "kvi_debug.h" + +#include "kvi_locale.h" + +#include "class_layout.h" + +#ifdef COMPILE_USE_QT4 +#define QLAYOUT_AUTO_CONSTRAINT QLayout::SetDefaultConstraint +#define QLAYOUT_FIXED QLayout::SetFixedSize +#define QLAYOUT_FREE_RESIZE QLayout::SetNoConstraint +#define QLAYOUT_MINIMUM QLayout::SetMinimumSize +#else +#define QLAYOUT_AUTO_CONSTRAINT QLayout::Auto +#define QLAYOUT_FIXED QLayout::Fixed +#define QLAYOUT_FREE_RESIZE QLayout::FreeResize +#define QLAYOUT_MINIMUM QLayout::Minimum +#endif + + +/* + @doc: layout + @keyterms: + layout object class, child widgets + @title: + layout class + @type: + class + @short: + Manages child widget geometry + @inherits: + [class]object[/class] + @description: + The layout is a geometry management tool for child widgets. + You create a layout , give it some widgets to manage and it will layout them + automatically.[br] + The parent of the layout must be the widget for which child widget geometries have to be managed. + A layout is a grid of NxM cells in which you insert child widgets with [classfnc:layout]$addWidget[/classfnc]().[br] + Widgets that must span multiple cells can be added to the layout with [classfnc:layout]$addMultiCellWidget[/classfnc]().[br] + @functions: + !fn: $addWidget(<widget:object widget>,<row:uint>,<column:uint>) + Adds a widget to this layout placing it at position <row>,<column> in the grid + !fn: $addMultiCellWidget(<widget:object widget>,<start_row:uint>,<end_row:uint>,<start_col:uint>,<end_col:uint>) + Adds a widget to this layout spanning multiple grid cells + !fn: $setRowStretch(<row:uint>,<stretch:uint>) + Sets the stretch value for a particular row of this layout. The <stretch_value> + must be a positive integer. The rows with bigger stretch values will take more space + in the layout. + !fn: $setColStretch(<column:uint>,<stretch:uint>) + Sets the stretch value for a particular column in this layout. The <stretch_value> + must be a positive integer. The rows with bigger stretch values will take more space + in the layout. + !fn: $addRowSpacing(<row:uint>,<spacing:uint>) + Sets the minimum height of the specified <row> to <spacing> which must be a positive integer + !fn: $addColSpacing(<column:uint>,<spacing:uint>) + Sets the minimum width of the specigfied <column> to <spacing> which must be a positive integer + !fn: $setSpacing(<spacing:uint>) + Sets the default spacing of the widgets in pixels + !fn: $setMargin(<margin:uint>) + Sets the dimension of the layout margin : the distance from the border to the outermost child widget edges. + !fn: $setResizeMode(<resize_mode:string>) + Sets the resize mode of the parent widget in relation to this layout. + <mode> can be one of:[br] + -Auto: this is the default[br] + -Fixed: the parent widget of this layout is resized to the "sizeHint" value and it cannot be resized by the user.[br] + -Minimum: the minimum size of the parent widget of this layout is set to minimumSize() and it cannot be smaller[br] + -FreeResize: the parent widget of this layout is not constrained at all[br] +*/ + + +KVSO_BEGIN_REGISTERCLASS(KviKvsObject_layout,"layout","object") + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"addWidget", functionAddWidget) + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"addMultiCellWidget", functionAddMultiCellWidget) + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setRowStretch", functionSetRowStretch) + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setColStretch", functionSetColStretch) + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"addRowSpacing", functionAddRowSpacing) + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"addColSpacing", functionAddColSpacing) + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setMargin", functionSetMargin) + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setSpacing", functionSetSpacing) + KVSO_REGISTER_HANDLER(KviKvsObject_layout,"setResizeMode", functionSetResizeMode) +KVSO_END_REGISTERCLASS(KviKvsObject_layout) + +KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_layout,KviKvsObject) + +KVSO_END_CONSTRUCTOR(KviKvsObject_layout) + + +KVSO_BEGIN_DESTRUCTOR(KviKvsObject_layout) + +KVSO_END_CONSTRUCTOR(KviKvsObject_layout) + +bool KviKvsObject_layout::init(KviKvsRunTimeContext * pContext,KviKvsVariantList *pParams) +{ + QWidget * w = parentScriptWidget(); + + if(!w) + { + pContext->warning(__tr2qs("The parent of a layout must be a widget!")); + return false; + } + setObject(new QGridLayout(w)); + return true; +} + +bool KviKvsObject_layout::functionAddWidget(KviKvsObjectFunctionCall *c) +{ + KviKvsObject * pObject; + kvs_hobject_t hObject; + kvs_uint_t uCol,uRow; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("widget",KVS_PT_HOBJECT,0,hObject) + KVSO_PARAMETER("row",KVS_PT_UNSIGNEDINTEGER,0,uRow) + KVSO_PARAMETER("col",KVS_PT_UNSIGNEDINTEGER,0,uCol) + KVSO_PARAMETERS_END(c) + pObject=KviKvsKernel::instance()->objectController()->lookupObject(hObject); + if(!widget())return true; + if (!pObject) + { + c->warning(__tr2qs("Widget parameter is not an object")); + return true; + } + if (!pObject->object()) + { + c->warning(__tr2qs("Widget parameter is not a valid object")); + return true; + } + if(!pObject->object()->isWidgetType()) + { + c->warning(__tr2qs("Can't add a non-widget object")); + return true; + } + ((QGridLayout *)object())->addWidget(((QWidget *)(pObject->object())),uRow,uCol); + return true; +} +bool KviKvsObject_layout::functionAddMultiCellWidget(KviKvsObjectFunctionCall *c) +{ + KviKvsObject * pObject; + kvs_hobject_t hObject; + kvs_uint_t uStartCol,uStartRow,uEndCol,uEndRow; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("widget",KVS_PT_HOBJECT,0,hObject) + KVSO_PARAMETER("start_row",KVS_PT_UNSIGNEDINTEGER,0,uStartRow) + KVSO_PARAMETER("end_row",KVS_PT_UNSIGNEDINTEGER,0,uEndRow) + KVSO_PARAMETER("start_column",KVS_PT_UNSIGNEDINTEGER,0,uStartCol) + KVSO_PARAMETER("end_column",KVS_PT_UNSIGNEDINTEGER,0,uEndCol) + KVSO_PARAMETERS_END(c) + pObject=KviKvsKernel::instance()->objectController()->lookupObject(hObject); + if(!widget())return true; + if (!pObject) + { + c->warning(__tr2qs("Widget parameter is not an object")); + return true; + } + if (!pObject->object()) + { + c->warning(__tr2qs("Widget parameter is not a valid object")); + return true; + } + if(!pObject->object()->isWidgetType()) + { + c->warning(__tr2qs("Can't add a non-widget object")); + return true; + } + ((QGridLayout *)object())->addMultiCellWidget(((QWidget *)(pObject->object())),uStartRow,uEndRow,uStartCol,uEndCol); + return true; +} +bool KviKvsObject_layout::functionSetRowStretch(KviKvsObjectFunctionCall *c) +{ + kvs_uint_t uRow,uStretch; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("row",KVS_PT_UNSIGNEDINTEGER,0,uRow) + KVSO_PARAMETER("stretch",KVS_PT_UNSIGNEDINTEGER,0,uStretch) + KVSO_PARAMETERS_END(c) + if(!widget())return true; + ((QGridLayout *)object())->setRowStretch(uRow,uStretch); + return true; +} +bool KviKvsObject_layout::functionSetColStretch(KviKvsObjectFunctionCall *c) +{ + kvs_uint_t uCol,uStretch; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("column",KVS_PT_UNSIGNEDINTEGER,0,uCol) + KVSO_PARAMETER("stretch",KVS_PT_UNSIGNEDINTEGER,0,uStretch) + KVSO_PARAMETERS_END(c) + if(!widget())return true; + ((QGridLayout *)object())->setColStretch(uCol,uStretch); + return true; +} + +bool KviKvsObject_layout::functionSetMargin(KviKvsObjectFunctionCall *c) +{ + kvs_uint_t uMargin; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("margin",KVS_PT_UNSIGNEDINTEGER,0,uMargin) + KVSO_PARAMETERS_END(c) + if (widget()) ((QGridLayout *)object())->setMargin(uMargin); + return true; +} + +bool KviKvsObject_layout::functionSetSpacing(KviKvsObjectFunctionCall *c) +{ + kvs_uint_t uSpacing; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("spacing",KVS_PT_UNSIGNEDINTEGER,0,uSpacing) + KVSO_PARAMETERS_END(c) + if (widget()) ((QGridLayout *)object())->setSpacing(uSpacing); + return true; +} + + +bool KviKvsObject_layout::functionAddRowSpacing(KviKvsObjectFunctionCall *c) +{ + kvs_uint_t uSpacing,uRow; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("row",KVS_PT_UNSIGNEDINTEGER,0,uRow) + KVSO_PARAMETER("spacing",KVS_PT_UNSIGNEDINTEGER,0,uSpacing) + KVSO_PARAMETERS_END(c) + if (widget()) ((QGridLayout *)object())->addRowSpacing(uRow,uSpacing); + return true; +} + +bool KviKvsObject_layout::functionAddColSpacing(KviKvsObjectFunctionCall *c) +{ + kvs_uint_t uSpacing,uCol; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("column",KVS_PT_UNSIGNEDINTEGER,0,uCol) + KVSO_PARAMETER("spacing",KVS_PT_UNSIGNEDINTEGER,0,uSpacing) + KVSO_PARAMETERS_END(c) + if (widget()) ((QGridLayout *)object())->addColSpacing(uCol,uSpacing); + return true; +} + +bool KviKvsObject_layout::functionSetResizeMode(KviKvsObjectFunctionCall *c) +{ + QString szMode; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("resize_mode",KVS_PT_STRING,0,szMode) + KVSO_PARAMETERS_END(c) + if(!widget())return true; +#ifdef COMPILE_USE_QT4 + QLayout::SizeConstraint r = QLAYOUT_AUTO_CONSTRAINT; +#else + QLayout::ResizeMode r = QLAYOUT_AUTO_CONSTRAINT; +#endif + if(KviQString::equalCI(szMode,"FreeResize")) r = QLAYOUT_FREE_RESIZE; + else if(KviQString::equalCI(szMode,"Minimum")) r = QLAYOUT_MINIMUM; + else if(KviQString::equalCI(szMode,"Fixed"))r = QLAYOUT_FIXED; + else c->warning(__tr2qs("Invalid resize mode defaulting to Auto")); + ((QGridLayout *)object())->setResizeMode(r); + return true; + +} + diff --git a/src/modules/objects/class_pixmap.cpp b/src/modules/objects/class_pixmap.cpp index 89247edb9..c24ef09ab 100644 --- a/src/modules/objects/class_pixmap.cpp +++ b/src/modules/objects/class_pixmap.cpp @@ -1,317 +1,317 @@ -//mdm:
-// Painter : class_pixmap.h
-// Creation date : Fri Mar 18 14:30:48 CEST 2005
-// by Tonino Imbesi(Grifisx) and Alessandro Carbone(Noldor)
-// Lucia Papini (^ashura^) English Translation.
-// This file is part of the KVirc irc client distribution
-// Copyright (C) 1999-2000 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-//
-
-#include "class_pixmap.h"
-#include "kvi_debug.h"
-
-#include "kvi_locale.h"
-#include <qfile.h>
-
-/*
- @doc: pixmap
- @keyterms:
- pixmap object class
- @title:
- pixmap class
- @type:
- class
- @short:
- This class provide a pixmap.
- @inherits:
- [class]object[/class]
- [class]widget[/class]
- @description:
- The pixmap class is an off-screen, pixel-based paint device.
- @functions:
- !fn: $fill(<widget:object>,<x_offset:integer>,<y:offset>)
- Fills the pixmap with the widget's background color or pixmap.[br]
- Note that x_offset, y_offest are offsets in the widget.
- !fn: $resize(<width:integer>,<height:integer>)
- Resizes the pixmap to w width and h height. Set wh or hg to 0, to have a null pixmap.
- !fn: $scale(<sx:real>,<sy:real>)
- Scales the pixmap by sx horizontally and sy vertically.
- !fn: $rotate(<a:real>)
- Rotates the pixmap by a degrees.
- !fn: $load(<file_name:string>)
- Load a pixmap from the <file>.
- !fn: <integer> $height()
- Return the height of the pixmap.
- !fn: <integer> $width()
- Return the width of the pixmap.
-
-*/
-
-
-KVSO_BEGIN_REGISTERCLASS(KviKvsObject_pixmap,"pixmap","object")
-
- KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"fill",functionfill)
- KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"resize",functionresize)
- KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"load",functionload)
- KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"height",functionheight)
- KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"width",functionwidth)
- KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"setOpacity",functionsetOpacity)
- KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"scale",functionscale)
- KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"rotate",functionrotate)
-
-KVSO_END_REGISTERCLASS(KviKvsObject_pixmap)
-
-
-KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_pixmap,KviKvsObject)
- m_pPixmap=new QPixmap();
- m_pImage=new QImage();
- bPixmapModified=false;
- bImageModified=false;
-KVSO_END_CONSTRUCTOR(KviKvsObject_pixmap)
-
-
-KVSO_BEGIN_DESTRUCTOR(KviKvsObject_pixmap)
-
- emit aboutToDie();
- delete m_pPixmap;
- if (m_pImage) delete m_pImage;
-
-KVSO_END_CONSTRUCTOR(KviKvsObject_pixmap)
-
-
-bool KviKvsObject_pixmap::functionfill(KviKvsObjectFunctionCall *c)
-{
- KviKvsObject *ob;
- kvs_int_t iXoffset,iYoffset;
- kvs_hobject_t hObject;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("widget",KVS_PT_HOBJECT,0,hObject)
- KVSO_PARAMETER("x_offset",KVS_PT_INT,0,iXoffset)
- KVSO_PARAMETER("y_offset",KVS_PT_INT,0,iYoffset)
- KVSO_PARAMETERS_END(c)
-
- ob=KviKvsKernel::instance()->objectController()->lookupObject(hObject);
- if (!ob)
- {
- c->warning(__tr2qs("Widget parameter is not an object"));
- return true;
- }
- if(!ob->object()->isWidgetType())
- {
- c->warning(__tr2qs("Widget object required"));
- return true;
- }
- bPixmapModified=true;
- m_pPixmap->fill(((QWidget *)(ob->object())),iXoffset,iYoffset);
- return true;
-}
-
-bool KviKvsObject_pixmap::functionscale(KviKvsObjectFunctionCall *c)
-{
- kvs_real_t uScaleX,uScaleY;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("sx",KVS_PT_REAL,0,uScaleX)
- KVSO_PARAMETER("sy",KVS_PT_REAL,0,uScaleY)
- KVSO_PARAMETERS_END(c)
- #ifdef COMPILE_USE_QT4
- *m_pPixmap = m_pPixmap->scaled((m_pPixmap->width() * uScaleX), (m_pPixmap->height() * uScaleX));
- #else
- QWMatrix wm;
- wm.scale(uScaleX, uScaleY);
- *m_pPixmap = m_pPixmap->xForm(wm);
- #endif
- bPixmapModified=true;
- return true;
-}
-
-bool KviKvsObject_pixmap::functionrotate(KviKvsObjectFunctionCall *c)
-{
- kvs_real_t uDegrees;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("a",KVS_PT_REAL,0,uDegrees)
- KVSO_PARAMETERS_END(c)
- #ifdef COMPILE_USE_QT4
- QMatrix m;
- m.rotate(uDegrees);
- *m_pPixmap = m_pPixmap->transformed(m);
- #else
- QWMatrix wm;
- wm.rotate(uDegrees);
- *m_pPixmap = m_pPixmap->xForm(wm);
- #endif
- bPixmapModified=true;
- return true;
-}
-
-bool KviKvsObject_pixmap::functionresize(KviKvsObjectFunctionCall *c)
-{
- kvs_int_t uWidth,uHeight;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("width",KVS_PT_UNSIGNEDINTEGER,0,uWidth)
- KVSO_PARAMETER("height",KVS_PT_UNSIGNEDINTEGER,0,uHeight)
- KVSO_PARAMETERS_END(c)
- m_pPixmap->resize(uWidth,uHeight);
- bPixmapModified=true;
- return true;
-}
-
-
-bool KviKvsObject_pixmap::functionload(KviKvsObjectFunctionCall *c)
-{
- QString szFile;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("file",KVS_PT_STRING,0,szFile)
- KVSO_PARAMETERS_END(c)
-
- if(!QFile::exists(szFile))
- {
- c->warning(__tr2qs("I can't find the specified file %Q."),&szFile);
- return true;
- }
- m_pPixmap->load(szFile);
- bPixmapModified=true;
- return true;
-}
-bool KviKvsObject_pixmap::functionheight(KviKvsObjectFunctionCall *c)
-{
- c->returnValue()->setInteger(m_pPixmap->height());
- return true;
-}
-bool KviKvsObject_pixmap::functionwidth(KviKvsObjectFunctionCall *c)
-{
- c->returnValue()->setInteger(m_pPixmap->width());
- return true;
-}
-bool KviKvsObject_pixmap::functionsetOpacity(KviKvsObjectFunctionCall *c)
-{
- if(!m_pPixmap)return true;
- kvs_real_t dOpacity;
- kvs_uint_t uXoffset,uYoffset;
- kvs_uint_t uWidth,uHeight;
-
- KviKvsObject * pObDest;
- kvs_hobject_t hObject;
-
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("opacity_factor",KVS_PT_DOUBLE,0,dOpacity)
- KVSO_PARAMETER("destination",KVS_PT_HOBJECT,0,hObject)
-
- KVSO_PARAMETER("x_offset",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uXoffset)
- KVSO_PARAMETER("y_offset",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uYoffset)
- KVSO_PARAMETER("width",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uWidth)
- KVSO_PARAMETER("height",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uHeight)
- KVSO_PARAMETERS_END(c)
- pObDest=KviKvsKernel::instance()->objectController()->lookupObject(hObject);
-
- if (!pObDest)
- {
- c->warning(__tr2qs("Destination parameter is not an object"));
- return true;
- }
-
- if(!pObDest->inherits("KviKvsObject_pixmap"))
- {
- c->warning(__tr2qs("Destination must be a pixmap object"));
- return true;
- }
- QImage *buffer=((KviKvsObject_pixmap *)pObDest)->getImage();
- ((KviKvsObject_pixmap *)pObDest)->imageChanged();
- if (bPixmapModified) {
- *m_pImage=m_pPixmap->convertToImage();
- }
- if (uWidth>buffer->width() || uHeight>buffer->height())
- {
- c->warning(__tr2qs("Area dimensions are out of destination size "));
- return true;
- }
- if (!uWidth){
- if(m_pImage->width()>buffer->width())
- {
- c->warning(__tr2qs("Pixmap dimensions are out of destination size "));
- return true;
- }
- }
-
- if (!uHeight)
- {
- if(m_pImage->height()>buffer->height())
- {
- c->warning(__tr2qs("Pixmap dimensions are out of destination size "));
- return true;
- }
- }
-
-
-if(uXoffset+uWidth>m_pImage->width())
- {
- c->warning(__tr2qs("Offset width area is out of pixmap size "));
- return true;
- }
- if( uYoffset+uHeight>m_pImage->height())
- {
- c->warning(__tr2qs("Offset height area is out of pixmap size "));
- return true;
- }
-
- buffer->setAlphaBuffer(true);
- int iHedge=uHeight?uHeight:m_pImage->height();
- int iWedge=uWidth?uWidth:m_pImage->width();
-
- for(int y = uYoffset;y<iHedge;y++)
- {
- QRgb * dst = (QRgb *)buffer->scanLine(y);
- QRgb * src = (QRgb *)m_pImage->scanLine(y);
- src += uXoffset;
- QRgb * end;
- end = src + iWedge;
- while(src < end)
- {
- *dst = qRgba(
- (int)(qRed(*src)),
- (int)(qGreen(*src)),
- (int)(qBlue(*src)),
- (int)(qAlpha(*src)*dOpacity)
- );
- src++;
- dst++;
- }
- }
- return true;
-}
-
-
-QPixmap * KviKvsObject_pixmap::getPixmap()
-{
- if (bImageModified) {
- m_pPixmap->convertFromImage(*m_pImage);
- bImageModified=false;
- }
- return m_pPixmap;
-}
-QImage * KviKvsObject_pixmap::getImage()
-{
- if (bPixmapModified) {
- *m_pImage=m_pPixmap->convertToImage();
- //debug ("image info2 %d and %d",test.width(),test.height());
-
- bPixmapModified=false;
- }
-
- return m_pImage;
-}
-
-#include "m_class_pixmap.moc"
+//mdm: +// Painter : class_pixmap.h +// Creation date : Fri Mar 18 14:30:48 CEST 2005 +// by Tonino Imbesi(Grifisx) and Alessandro Carbone(Noldor) +// Lucia Papini (^ashura^) English Translation. +// This file is part of the KVirc irc client distribution +// Copyright (C) 1999-2000 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// + +#include "class_pixmap.h" +#include "kvi_debug.h" + +#include "kvi_locale.h" +#include <qfile.h> + +/* + @doc: pixmap + @keyterms: + pixmap object class + @title: + pixmap class + @type: + class + @short: + This class provide a pixmap. + @inherits: + [class]object[/class] + [class]widget[/class] + @description: + The pixmap class is an off-screen, pixel-based paint device. + @functions: + !fn: $fill(<widget:object>,<x_offset:integer>,<y:offset>) + Fills the pixmap with the widget's background color or pixmap.[br] + Note that x_offset, y_offest are offsets in the widget. + !fn: $resize(<width:integer>,<height:integer>) + Resizes the pixmap to w width and h height. Set wh or hg to 0, to have a null pixmap. + !fn: $scale(<sx:real>,<sy:real>) + Scales the pixmap by sx horizontally and sy vertically. + !fn: $rotate(<a:real>) + Rotates the pixmap by a degrees. + !fn: $load(<file_name:string>) + Load a pixmap from the <file>. + !fn: <integer> $height() + Return the height of the pixmap. + !fn: <integer> $width() + Return the width of the pixmap. + +*/ + + +KVSO_BEGIN_REGISTERCLASS(KviKvsObject_pixmap,"pixmap","object") + + KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"fill",functionfill) + KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"resize",functionresize) + KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"load",functionload) + KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"height",functionheight) + KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"width",functionwidth) + KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"setOpacity",functionsetOpacity) + KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"scale",functionscale) + KVSO_REGISTER_HANDLER(KviKvsObject_pixmap,"rotate",functionrotate) + +KVSO_END_REGISTERCLASS(KviKvsObject_pixmap) + + +KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_pixmap,KviKvsObject) + m_pPixmap=new QPixmap(); + m_pImage=new QImage(); + bPixmapModified=false; + bImageModified=false; +KVSO_END_CONSTRUCTOR(KviKvsObject_pixmap) + + +KVSO_BEGIN_DESTRUCTOR(KviKvsObject_pixmap) + + emit aboutToDie(); + delete m_pPixmap; + if (m_pImage) delete m_pImage; + +KVSO_END_CONSTRUCTOR(KviKvsObject_pixmap) + + +bool KviKvsObject_pixmap::functionfill(KviKvsObjectFunctionCall *c) +{ + KviKvsObject *ob; + kvs_int_t iXoffset,iYoffset; + kvs_hobject_t hObject; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("widget",KVS_PT_HOBJECT,0,hObject) + KVSO_PARAMETER("x_offset",KVS_PT_INT,0,iXoffset) + KVSO_PARAMETER("y_offset",KVS_PT_INT,0,iYoffset) + KVSO_PARAMETERS_END(c) + + ob=KviKvsKernel::instance()->objectController()->lookupObject(hObject); + if (!ob) + { + c->warning(__tr2qs("Widget parameter is not an object")); + return true; + } + if(!ob->object()->isWidgetType()) + { + c->warning(__tr2qs("Widget object required")); + return true; + } + bPixmapModified=true; + m_pPixmap->fill(((QWidget *)(ob->object())),iXoffset,iYoffset); + return true; +} + +bool KviKvsObject_pixmap::functionscale(KviKvsObjectFunctionCall *c) +{ + kvs_real_t uScaleX,uScaleY; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("sx",KVS_PT_REAL,0,uScaleX) + KVSO_PARAMETER("sy",KVS_PT_REAL,0,uScaleY) + KVSO_PARAMETERS_END(c) + #ifdef COMPILE_USE_QT4 + *m_pPixmap = m_pPixmap->scaled((m_pPixmap->width() * uScaleX), (m_pPixmap->height() * uScaleX)); + #else + QWMatrix wm; + wm.scale(uScaleX, uScaleY); + *m_pPixmap = m_pPixmap->xForm(wm); + #endif + bPixmapModified=true; + return true; +} + +bool KviKvsObject_pixmap::functionrotate(KviKvsObjectFunctionCall *c) +{ + kvs_real_t uDegrees; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("a",KVS_PT_REAL,0,uDegrees) + KVSO_PARAMETERS_END(c) + #ifdef COMPILE_USE_QT4 + QMatrix m; + m.rotate(uDegrees); + *m_pPixmap = m_pPixmap->transformed(m); + #else + QWMatrix wm; + wm.rotate(uDegrees); + *m_pPixmap = m_pPixmap->xForm(wm); + #endif + bPixmapModified=true; + return true; +} + +bool KviKvsObject_pixmap::functionresize(KviKvsObjectFunctionCall *c) +{ + kvs_int_t uWidth,uHeight; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("width",KVS_PT_UNSIGNEDINTEGER,0,uWidth) + KVSO_PARAMETER("height",KVS_PT_UNSIGNEDINTEGER,0,uHeight) + KVSO_PARAMETERS_END(c) + m_pPixmap->resize(uWidth,uHeight); + bPixmapModified=true; + return true; +} + + +bool KviKvsObject_pixmap::functionload(KviKvsObjectFunctionCall *c) +{ + QString szFile; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("file",KVS_PT_STRING,0,szFile) + KVSO_PARAMETERS_END(c) + + if(!QFile::exists(szFile)) + { + c->warning(__tr2qs("I can't find the specified file %Q."),&szFile); + return true; + } + m_pPixmap->load(szFile); + bPixmapModified=true; + return true; +} +bool KviKvsObject_pixmap::functionheight(KviKvsObjectFunctionCall *c) +{ + c->returnValue()->setInteger(m_pPixmap->height()); + return true; +} +bool KviKvsObject_pixmap::functionwidth(KviKvsObjectFunctionCall *c) +{ + c->returnValue()->setInteger(m_pPixmap->width()); + return true; +} +bool KviKvsObject_pixmap::functionsetOpacity(KviKvsObjectFunctionCall *c) +{ + if(!m_pPixmap)return true; + kvs_real_t dOpacity; + kvs_uint_t uXoffset,uYoffset; + kvs_uint_t uWidth,uHeight; + + KviKvsObject * pObDest; + kvs_hobject_t hObject; + + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("opacity_factor",KVS_PT_DOUBLE,0,dOpacity) + KVSO_PARAMETER("destination",KVS_PT_HOBJECT,0,hObject) + + KVSO_PARAMETER("x_offset",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uXoffset) + KVSO_PARAMETER("y_offset",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uYoffset) + KVSO_PARAMETER("width",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uWidth) + KVSO_PARAMETER("height",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uHeight) + KVSO_PARAMETERS_END(c) + pObDest=KviKvsKernel::instance()->objectController()->lookupObject(hObject); + + if (!pObDest) + { + c->warning(__tr2qs("Destination parameter is not an object")); + return true; + } + + if(!pObDest->inherits("KviKvsObject_pixmap")) + { + c->warning(__tr2qs("Destination must be a pixmap object")); + return true; + } + QImage *buffer=((KviKvsObject_pixmap *)pObDest)->getImage(); + ((KviKvsObject_pixmap *)pObDest)->imageChanged(); + if (bPixmapModified) { + *m_pImage=m_pPixmap->convertToImage(); + } + if (uWidth>buffer->width() || uHeight>buffer->height()) + { + c->warning(__tr2qs("Area dimensions are out of destination size ")); + return true; + } + if (!uWidth){ + if(m_pImage->width()>buffer->width()) + { + c->warning(__tr2qs("Pixmap dimensions are out of destination size ")); + return true; + } + } + + if (!uHeight) + { + if(m_pImage->height()>buffer->height()) + { + c->warning(__tr2qs("Pixmap dimensions are out of destination size ")); + return true; + } + } + + +if(uXoffset+uWidth>m_pImage->width()) + { + c->warning(__tr2qs("Offset width area is out of pixmap size ")); + return true; + } + if( uYoffset+uHeight>m_pImage->height()) + { + c->warning(__tr2qs("Offset height area is out of pixmap size ")); + return true; + } + + buffer->setAlphaBuffer(true); + int iHedge=uHeight?uHeight:m_pImage->height(); + int iWedge=uWidth?uWidth:m_pImage->width(); + + for(int y = uYoffset;y<iHedge;y++) + { + QRgb * dst = (QRgb *)buffer->scanLine(y); + QRgb * src = (QRgb *)m_pImage->scanLine(y); + src += uXoffset; + QRgb * end; + end = src + iWedge; + while(src < end) + { + *dst = qRgba( + (int)(qRed(*src)), + (int)(qGreen(*src)), + (int)(qBlue(*src)), + (int)(qAlpha(*src)*dOpacity) + ); + src++; + dst++; + } + } + return true; +} + + +QPixmap * KviKvsObject_pixmap::getPixmap() +{ + if (bImageModified) { + m_pPixmap->convertFromImage(*m_pImage); + bImageModified=false; + } + return m_pPixmap; +} +QImage * KviKvsObject_pixmap::getImage() +{ + if (bPixmapModified) { + *m_pImage=m_pPixmap->convertToImage(); + //debug ("image info2 %d and %d",test.width(),test.height()); + + bPixmapModified=false; + } + + return m_pImage; +} + +#include "m_class_pixmap.moc" diff --git a/src/modules/objects/class_socket.cpp b/src/modules/objects/class_socket.cpp index 3819ca05b..c10c89e1e 100644 --- a/src/modules/objects/class_socket.cpp +++ b/src/modules/objects/class_socket.cpp @@ -1,1331 +1,1331 @@ -//
-// File : class_socket.cpp
-// Creation date : Sun Nov 11 03:13:45 2001 GMT by Szymon Stefanek
-//
-// This file is part of the KVirc irc client distribution
-// Copyright (C) 2001 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-//
-
-#include "kvi_settings.h"
-#include "kvi_qstring.h"
-
-#define _KVI_DEBUG_CHECK_RANGE_
-#include "kvi_debug.h"
-
-
-#include "kvi_locale.h"
-#include "kvi_error.h"
-#include "kvi_netutils.h"
-#include "kvi_dns.h"
-#include "kvi_error.h"
-#include "kvi_socket.h"
-#include "kvi_malloc.h"
-#include "kvi_memmove.h"
-#include "kvi_databuffer.h"
-#include "kvi_qcstring.h"
-
-#include "class_socket.h"
-
-//#include <stdlib.h>
-
-#define KVI_IN_BUFFER_ALLOC_CHUNK 4096
-#define KVI_READ_CHUNK 1024
-/*
-static KviScriptObjectClass * g_pSocketClass = 0;
-
-static KviScriptObject * socketClassCreateInstance(KviScriptObjectClass * cls,KviScriptObject *par,const char * nam)
-{
- return new KviScriptSocketObject(cls,par,nam);
-}
-
-KviScriptSocketObject::KviScriptSocketObject(KviScriptObjectClass * cla,KviScriptObject * par,const char * nam)
-: KviScriptObject(cla,par,nam)
-{
- m_uConnectionId = 0;
- m_sock = KVI_INVALID_SOCKET;
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED;
- m_uRemotePort = 0;
- m_uSecondaryPort = 0;
- m_pSn = 0;
- m_pDns = 0;
- m_pDelayTimer = 0;
- m_uConnectTimeout = 60000;
- m_pInBuffer = 0;
- m_uInBufferLen = 0;
- m_uInDataLen = 0;
- m_pOutBuffer = new KviDataBuffer();
- m_pFlushTimer = new QTimer();
- m_bIpV6 = false;
- m_uLocalPort = 0;
- m_secondarySock = KVI_INVALID_SOCKET;
- connect(m_pFlushTimer,SIGNAL(timeout()),this,SLOT(tryFlush()));
-}
-
-KviScriptSocketObject::~KviScriptSocketObject()
-{
- delete m_pOutBuffer;
- delete m_pFlushTimer;
-
- if(m_pInBuffer)kvi_free(m_pInBuffer);
- if(m_pDelayTimer)delete m_pDelayTimer;
- if(m_pDns)delete m_pDns;
- if(m_pSn)delete m_pSn;
- if(m_sock != KVI_INVALID_SOCKET)kvi_socket_close(m_sock);
- if(m_secondarySock != KVI_INVALID_SOCKET)kvi_socket_close(m_secondarySock);
-}
-
-void KviScriptSocketObject::reset()
-{
- m_uConnectionId++; // this is the only place where this is incremented!
- if(m_pDelayTimer)
- {
- delete m_pDelayTimer;
- m_pDelayTimer = 0;
- }
- if(m_pDns)
- {
- delete m_pDns;
- m_pDns = 0;
- }
- if(m_pSn)
- {
- delete m_pSn;
- m_pSn = 0;
- }
- if(m_sock != KVI_INVALID_SOCKET)
- {
- kvi_socket_close(m_sock);
- m_sock = KVI_INVALID_SOCKET;
- }
- if(m_pInBuffer)
- {
- kvi_free(m_pInBuffer);
- m_pInBuffer = 0;
- }
- if(m_secondarySock)
- {
- kvi_socket_close(m_secondarySock);
- m_secondarySock = KVI_INVALID_SOCKET;
- }
- m_uSecondaryPort = 0;
- m_szSecondaryIp.clear();
- delete m_pOutBuffer;
- if(m_pFlushTimer->isActive())m_pFlushTimer->stop();
- m_pOutBuffer = new KviDataBuffer();
- m_uInBufferLen = 0;
- m_uInDataLen = 0;
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED;
- m_uRemotePort = 0;
- m_szRemoteIp.clear();
- m_uLocalPort = 0;
- m_szLocalIp.clear();
- m_bIpV6 = false;
-}
-
-/*
- @doc: socket
- @keyterms:
- socket object class
- @title:
- socket class
- @type:
- class
- @short:
- A Ipv4/Ipv6 TCP socket
- @inherits:
- [class]object[/class]
- @description:
- This class provides a standard TCP/IP socket functionality.[br]
- It can be used either for connecting to a remote host or to listening for incoming connections.[br]
- If the KVIrc executable has been compiled with the IPV6 protocol support , this socket also supports it.[br]
- @functions:
- !fn: $status()
- Returns the status of the socket :[br]
- 4=connected[br]
- 3=listening[br]
- 2=connecting[br]
- 1=in dns call[br]
- 0=disconnected
-
- !fn: $connectTimeout()
- Returns the value of the connect attempt timeout in milliseconds.[br]
- This is the timeout after that a connection attempt will be considered as failed if the remote
- host is not responding. You can set it with [classfnc:socket]$setConnectTimeout[/classfnc]().
-
- !fn: $setConnectTimeout(<timeout>)
- Sets the connect timeout for this socket. <timeout> must be a positive value in milliseconds.[br]
- The default timeout is 60000.
-
- !fn: $connect(<host>,<port>)
- Attempts a connection to <host> on port <port>.[br]
- <host> can be a numeric internet address (either Ipv4 or Ipv6 (if supported)) or a hostname.[br]
- If a hostname is used, a DNS lookup is performed (the socket enters the "dns call" state).[br]
- This function returns 1 if the connect attempt can be succesfully initiated,
- 0 otherwise.[br] In fact , this function returns 0 only if the supplied <port> parameter
- is invalid or the socket is in an incoherent state (already connected or listening):
- for a newly created socket and with a valid <port> number you can safely ignore
- the return value.[br]
- Please note that the connection is asynchronous: when this function returns
- the socket is NOT connected: it has just initiated the connect attempt
- and you will be notified of the attempt result by an asynchronous event call:
- in case of failure , $connectFailedEvent() will be called , in case of
- succes , $connectEvent() will be called.
-
- !fn: $listen([<port>[,<interface>[,<force_ipv6>]]])
- Attempts to listen on the specified <port> and <interface>.[br]
- If <port> is not passed it is assumed to be 0 , if <interface> is not passed , it is assumed to be
- "any interface" (INADDR_ANY).[br] Port 0 means that the kernel should choose a "random" port to listen on.[br]
- If the <interface> is recognized as IPV6 address , and IPV6 is supported , the socket listens
- in IPV6 mode. If <interface> is an empty string and <force_ipv6> is 1 the socket listens
- on "any ipv6 interface".[br]
- This function returns '1' in case of success and '0' in case of failure.[br]
- On some systems listening in the IPV6 namespace allows to accept also IPV4 connections (this includes
- linux but not windows afaik).[br]
- When an incoming connection will arrive , $incomingConnectionEvent() will be called.
-
- !fn: $accept(<socketId>)
- This function can be called only from inside $incomingConnectionEvent().[br]
- <socketId> must be a newly created socket sub-class instance object.[br]
- The passed object will be set up to handle the incoming connection and this object
- will remain in listening state (unless you explicitly close it).[br]
- This function returns '1' in case of success and '0' in case of failure.
-
- !fn: $connectEvent()
- This function is called when a connection attempt has been succesfully completed.
- The socket is actually connected to [classfnc:socket]$remoteIp[/classfnc]() on
- [classfnc:socket]$remotePort[/classfnc](). You can start
- writing data and you may expect [classfnc:socket]$dataAvailableEvent[/classfnc]() to be
- triggered.
-
- !fn: $incomingConnectionEvent()
- This function is called when an incoming connection arrives over a socket in listening state.[br]
- You must call [classfnc:socket]$accept[/classfnc]() passing a newly created socket object
- to accept and handle the connection.[br] If you don't call [classfnc:socket]$accept[/classfnc]()
- the incoming connection will be automatically terminated.
-
- !fn: $connectFailedEvent(<reason>)
- This function is called when a connection attempt fails for some reason. <reason> contains
- the error string.[br]
- This function may be called only between a call to [classfnc:socket]$connect[/classfnc]() and
- the [classfnc:socket]$connectEvent[/classfnc]().
-
- !fn: $disconnectEvent([error])
- This function is called when a connection is terminated either cleanly or because of an error.[br]
- [error] is an empty string in case of a "clean" termination (connection closed by the remote host)
- or is a message describing the socket error that caused the connection to be interrupted.
-
- !fn: $dataAvailableEvent(<data_length>)
- This function is called when some data is available to be read: the <data_length> parameter specifies
- the length of the available data in bytes.[br]
- You can use one of the $read* functions to obtain the data.
-
- !fn: $read(<length>)
- Reads at most <length> bytes of data from the socket. If <length> is anything "outside" the
- available data range (<length> < 0 or <length> > available_data_length), this function
- returns all the available data.[br]
- Please note that this function can't deal withi binary data: NULL characters are transformed to
- ASCII characters 255.
-
- !fn: $readHex(<length>)
- Reads at most <length> bytes of data from the socket. If <length> is anything "outside" the
- available data range (<length> < 0 or <length> > available_data_length), this function
- returns all the available data.[br]
- Returns the data encoded as hexadecimal digit string: this function can deal with binary data too.
-
- !fn: $write(<data>)
- Writes <data> to the socket.[br]
- This function can't deal with binary data (you can't send a NULL character)[br]
- Please note that when this function finishes it does not mean that the data has reached the remote end.[br]
- Basically it does not even mean that the data has been sent to the remote host.[br]
- The data is enqueued for sending and will be sent as soon as possible.[br]
- If you're going to [cmd]delete[/cmd] this object just after the $write call, you should
- call [classfnc:socket]$close[/classfnc]() just before [cmd]delete[/cmd] to ensure the data delivery.
-
- !fn: $writeHex(<hex_data>)
- Writes <data> to the socket.[br]
- <data> is expected to be a hexadecimal rappresentation of the bytes to be sent (two HEX characters
- for each byte). This means that the length of <hex_data> string must be a multiple of 2.[br]
- Returns the length of the actually decoded and sent data in bytes or -1 in case of error (the string
- was not a valid hexadecimla rappresentation).[br]
- Please note that when this function finishes it does not mean that the data has reached the remote end.[br]
- Basically it does not even mean that the data has been sent to the remote host.[br]
- The data is enqueued for sending and will be sent as soon as possible.[br]
- If you're going to [cmd]delete[/cmd] this object just after the $writeHex call, you should
- call [classfnc:socket]$close[/classfnc]() just before [cmd]delete[/cmd] to ensure the data delivery.
-
- !fn: $close()
- Resets this socket state: kills any pending or active connection. After a close() call
- the socket may be used for a new connection.[br]
- If there is an active connection, there is a last attempt to flush the pending outgoing data.[br]
- You don't need to call $close() if you [cmd]delete[/cmd] the socket: KVIrc will
- reset the socket state automatically and free the memory. But if you want to ensure data delivery
- after a $write call sequece and just before a [cmd]delete[/cmd], $close() is the only chance to do it.
-
- !fn: $remoteIp()
- Returns the IP address of the remote end of this socket.[br]
- The return value is meaningful only if the socket is in connected or connecting state.
-
- !fn: $setProtocol(<protocol>)
- Let KVIrc use TCP jr UDP protocol
-
- !fn: $remotePort()
- Returns the port of the remote end of this socket.[br]
- The return value is meaningful only if the socket is in connected or connecting state.
-
- !fn: $localIp()
- Returns the IP address of the local end of this socket.[br]
- The return value is meaningful only if the socket is in connected , listening or connecting state.
-
- !fn: $localPort()
- Returns the port of the local end of this socket.[br]
- The return value is meaningful only if the socket is in connected , listening or connecting state.
-
-@examples:
- [example]
- #Server socket: listen 80 port and answer to requests (multi-threaded)[br]
-[br]
- class (webserver,socket) {[br]
- constructor () {[br]
- $$->$listen(80, "127.0.0.1")[br]
- }[br]
- incomingConnectionEvent()[br]
- {[br]
- %tmp = $new(socket)[br]
- $$->$accept(%tmp)[br]
- echo "Webserver incoming Conection from: %tmp->$remoteIp : %tmp->$remotePort"[br]
- %tmp->$write("HTTP/1.1 200 OK\n\n<html><head></head><body><h1>KVIrc Webserver</h1></body></html>\n")[br]
- %tmp->$close()[br]
- delete %tmp[br]
- }[br]
- }[br]
- [br]
- #finally start webserver[br]
- %WebS = $new(webserver)[br]
- [br]
- [/example]
- [example]
- #Client socket - go to google and grab request header[br]
- class (httprequest,socket) {[br]
- constructor () [br]
- {[br]
- # connect to the server[br]
- $$->$connect("www.google.de",80)[br]
- }[br]
- destructor()[br]
- {[br]
- # if the socket is still open close it[br]
- if($$->$status() == 4) $$->$close()[br]
- }[br]
- connectFailedEvent() [br]
- {[br]
- # the connection to the server failed[br]
- echo "Connection failed: "$0[br]
- delete $$[br]
- }[br]
- connectEvent() [br]
- {[br]
- # connection is complete[br]
- # send a request to receive the headers only from http://www.google.de/[br]
- $$->$write("HEAD / HTTP/1.1\r\nHost: www.google.de\r\nConnction: Close\r\nUser-Agent: KVIrc socket\r\n\r\n");[br]
- }[br]
- dataAvailableEvent() [br]
- {[br]
- # reading the received data[br]
- %newdata = $$->$read($0)[br]
- echo %newdata[br]
- #close and delete the socket[br]
- $$->$close()[br]
- delete $$[br]
- }[br]
- disconnectEvent() [br]
- {[br]
- # connection has been closed[br]
- echo "Connection closed"[br]
- delete $$[br]
- }[br]
-}[br]
-
-#Creating the socket[br]
-%Temp = $new(httprequest)[br]
- [/example]
-*/
-
-KVSO_BEGIN_REGISTERCLASS(KviKvsObject_socket,"socket","object")
-
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"status",functionStatus)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"remotePort",functionRemotePort)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"remoteIp",functionRemoteIp)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"localIp",functionLocalIp)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"localPort",functionLocalPort)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"connect",functionConnect)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"connectTimeout",functionConnectTimeout)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"setConnectTimeout",functionSetConnectTimeout)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"close",functionClose)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"read",functionRead)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"readHex",functionReadHex)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"write",functionWrite)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"writeHex",functionWriteHex)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"setProtocol",functionSetProtocol)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"listen",functionListen)
- KVSO_REGISTER_HANDLER(KviKvsObject_socket,"accept",functionAccept)
-
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"connectEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"connectFailedEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"disconnectEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"dataAvailableEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"incomingConnectionEvent")
-
-KVSO_END_REGISTERCLASS(KviKvsObject_socket)
-
-
-KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_socket,KviKvsObject)
-
-
- m_bUdp = false;
- m_uConnectionId = 0;
- m_sock = KVI_INVALID_SOCKET;
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED;
- m_uRemotePort = 0;
- m_uSecondaryPort = 0;
- m_pSn = 0;
- m_pDns = 0;
- m_pDelayTimer = 0;
- m_uConnectTimeout = 60000;
- m_pInBuffer = 0;
- m_uInBufferLen = 0;
- m_uInDataLen = 0;
- m_pOutBuffer = new KviDataBuffer();
- m_pFlushTimer = new QTimer();
- m_bIpV6 = false;
- m_uLocalPort = 0;
- m_secondarySock = KVI_INVALID_SOCKET;
- connect(m_pFlushTimer,SIGNAL(timeout()),this,SLOT(tryFlush()));
-KVSO_END_CONSTRUCTOR(KviKvsObject_socket)
-
-KVSO_BEGIN_DESTRUCTOR(KviKvsObject_socket)
- delete m_pOutBuffer;
- delete m_pFlushTimer;
-
- if(m_pInBuffer)kvi_free(m_pInBuffer);
- if(m_pDelayTimer)delete m_pDelayTimer;
- if(m_pDns)delete m_pDns;
- if(m_pSn)delete m_pSn;
- if(m_sock != KVI_INVALID_SOCKET)kvi_socket_close(m_sock);
- if(m_secondarySock != KVI_INVALID_SOCKET)kvi_socket_close(m_secondarySock);
-KVSO_END_DESTRUCTOR(KviKvsObject_socket)
-//----------------------
-
-
-bool KviKvsObject_socket::functionStatus(KviKvsObjectFunctionCall *c)
-{
- c->returnValue()->setInteger(m_iStatus);
- return true;
-}
-
-bool KviKvsObject_socket::functionClose(KviKvsObjectFunctionCall *c)
-{
- if((m_pOutBuffer->size() != 0) && (m_iStatus == KVI_SCRIPT_SOCKET_STATUS_CONNECTED))
- tryFlush();
-
- reset();
- return true;
-}
-
-bool KviKvsObject_socket::functionConnectTimeout(KviKvsObjectFunctionCall *c)
-{
- c->returnValue()->setInteger(m_uConnectTimeout);
- return true;
-}
-
-bool KviKvsObject_socket::functionSetConnectTimeout(KviKvsObjectFunctionCall *c)
-{
- kvs_uint_t uTimeout;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("time_out",KVS_PT_UNSIGNEDINTEGER,0,uTimeout)
- KVSO_PARAMETERS_END(c)
- m_uConnectTimeout = uTimeout;
- return true;
-}
-
-bool KviKvsObject_socket::functionRemotePort(KviKvsObjectFunctionCall *c)
-{
- c->returnValue()->setInteger(m_uRemotePort);
- return true;
-}
-
-bool KviKvsObject_socket::functionRemoteIp(KviKvsObjectFunctionCall *c)
-{
- c->returnValue()->setString(m_szRemoteIp);
- return true;
-}
-
-bool KviKvsObject_socket::functionLocalPort(KviKvsObjectFunctionCall *c)
-{
- c->returnValue()->setInteger(m_uLocalPort);
- return true;
-}
-
-bool KviKvsObject_socket::functionLocalIp(KviKvsObjectFunctionCall *c)
-{
- c->returnValue()->setString(m_szLocalIp);
- return true;
-}
-
-bool KviKvsObject_socket::functionAccept(KviKvsObjectFunctionCall *c)
-{
- KviKvsObject * pObject;
- kvs_hobject_t hObject;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("object_socket",KVS_PT_HOBJECT,0,hObject)
- KVSO_PARAMETERS_END(c)
-
- pObject = KviKvsKernel::instance()->objectController()->lookupObject(hObject);
-
- if(!pObject)
- {
- c->warning(__tr2qs("No socket object specified"));
- return true;
- }
-
- if(!pObject->inherits("KviKvsObject_socket"))
- {
- c->warning(__tr2qs("Invalid socket object specified (it doesn't inherit from socket)"));
- return true;
- }
-
- if(m_secondarySock != KVI_INVALID_SOCKET)
- {
- ((KviKvsObject_socket *)pObject)->acceptConnection(m_secondarySock,m_uSecondaryPort,m_szSecondaryIp);
-
- m_secondarySock = KVI_INVALID_SOCKET;
- m_uSecondaryPort = 0;
- m_szSecondaryIp="";
- } else {
- c->warning(__tr2qs("There is no connection to accept!"));
- }
- return true;
-}
-
-
-bool KviKvsObject_socket::functionSetProtocol(KviKvsObjectFunctionCall *c)
-{
- QString m_szHex;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("hex_string",KVS_PT_STRING,0,m_szHex)
- KVSO_PARAMETERS_END(c)
-
- m_bUdp=KviQString::equalCI(m_szHex,"udp");
- return false;
-}
-
-bool KviKvsObject_socket::functionWriteHex(KviKvsObjectFunctionCall *c)
-{
- QString m_szHex;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("hex_string",KVS_PT_STRING,0,m_szHex)
- KVSO_PARAMETERS_END(c)
-
- if(m_szHex.length() > 0)
- {
- bool bOk;
- QString szTmp;
- szTmp=m_szHex.setNum(m_szHex.toInt(&bOk,16),16);
- if(szTmp.length()>0)
- {
- KviQCString szData8 = szTmp.utf8();
- m_pOutBuffer->append((const unsigned char *)(szData8.data()),szData8.length());
- delayedFlush(0);
- c->returnValue()->setInteger(szData8.length());
- }
- }
-
- /*
- if(pszData)
- {
- if(pszData->len() > 0)
- {
- char * ptr;
- len = pszData->hexToBuffer(&ptr);
- if(len > 0)
- {
- m_pOutBuffer->append((const unsigned char *)(ptr),len);
- delayedFlush(0);
- KviStr::freeBuffer(ptr);
- }
- }
- }
- buffer.append(KviStr::Format,"%d",len);
-*/
- return true;
-}
-
-
-
-
-
-bool KviKvsObject_socket::functionConnect(KviKvsObjectFunctionCall *c)
-{
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("remote_ip",KVS_PT_STRING,0,m_szRemoteIp)
- KVSO_PARAMETER("remote_port",KVS_PT_UNSIGNEDINTEGER,0,m_uRemotePort)
- KVSO_PARAMETERS_END(c)
- debug ("Function connect");
-
-
- if (m_uRemotePort>65535)
- {
- c->warning(__tr2qs("Value %d for port is out of range (values allowed are from 0 to 65535"),m_uRemotePort);
- return true;
- }
- if((m_sock != KVI_INVALID_SOCKET) || (m_iStatus != KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED))
- {
- c->warning(__tr2qs("Another connection in progress"));
- c->returnValue()->setBoolean(true);
- return true;
- }
-
-
-#ifdef COMPILE_IPV6_SUPPORT
- if(kvi_isValidStringIp(m_szRemoteIp) || kvi_isValidStringIp_V6(m_szRemoteIp))
-#else
- if(kvi_isValidStringIp(m_szRemoteIp))
-#endif
- {
- debug ("ok connecting");
- debug ("connectinhg on ip %s ",m_szRemoteIp.latin1());
- debug ("non so ip");
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_CONNECTING;
- delayedConnect();
- } else {
- debug ("connectinhg on ip %s port %d",m_szRemoteIp.latin1(),m_uRemotePort);
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DNS;
- delayedLookupRemoteIp();
- }
- c->returnValue()->setBoolean(true);
- return true;
-}
-
-
-
-
-
-
-bool KviKvsObject_socket::functionListen(KviKvsObjectFunctionCall *c)
-{
- if((m_sock != KVI_INVALID_SOCKET) || (m_iStatus != KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED))
- {
- c->warning(__tr2qs("Another connection in progress"));
- c->returnValue()->setBoolean(false);
- return true;
- }
- kvs_uint_t uLocalPort;
- QString m_szLocalIp;
- bool m_bIpV6;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("local_port",KVS_PT_UNSIGNEDINTEGER,0,uLocalPort)
- KVSO_PARAMETER("local_ip",KVS_PT_STRING,KVS_PF_OPTIONAL,m_szLocalIp)
- KVSO_PARAMETER("bool_ipV6",KVS_PT_BOOLEAN,KVS_PF_OPTIONAL,m_bIpV6)
- KVSO_PARAMETERS_END(c)
- m_uLocalPort=uLocalPort;
-
-#ifndef COMPILE_IPV6_SUPPORT
- if(m_bIpV6)
- {
- c->warning(__tr2qs("No IPV6 support in this executable"));
- c->returnValue()->setBoolean(false);
- reset();
- return true;
- }
-#endif
-
- bool bGotIp = false;
-
- if(!m_szLocalIp.isEmpty())
- {
-
- // Check the address type
- if(kvi_isValidStringIp(m_szLocalIp))bGotIp = true;
- else {
-#ifdef COMPILE_IPV6_SUPPORT
- if(kvi_isValidStringIp_V6(m_szLocalIp))
- {
- bGotIp = true;
- m_bIpV6 = true;
- } else {
-#else
- c->warning(__tr2qs("Invalid IP address specified ('%Q')"),&m_szLocalIp);
- c->returnValue()->setBoolean(false);
- reset();
- return true;
-#endif
-#ifdef COMPILE_IPV6_SUPPORT
- }
-#endif
- }
- }
-
-
-#ifdef COMPILE_IPV6_SUPPORT
- m_sock = kvi_socket_create(m_bIpV6 ? KVI_SOCKET_PF_INET6 : KVI_SOCKET_PF_INET,
- m_bUdp ? KVI_SOCKET_TYPE_DGRAM : KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP);
-#else
- m_sock = kvi_socket_create(KVI_SOCKET_PF_INET,m_bUdp ? KVI_SOCKET_TYPE_DGRAM : KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP);
-#endif
-
- if(m_sock == KVI_INVALID_SOCKET)
- {
- c->warning(__tr2qs("Socket creation failed"));
- c->returnValue()->setBoolean(false);
- reset();
- return true;
- }
-
- if(!m_szLocalIp.isEmpty())
- {
-#ifdef COMPILE_IPV6_SUPPORT
- KviSockaddr sa(m_szLocalIp,m_uLocalPort,m_bIpV6,m_bUdp);
-#else
- KviSockaddr sa(m_szLocalIp,m_uLocalPort,false,m_bUdp);
-#endif
- if(!sa.socketAddress())
- {
- c->warning(__tr2qs("Invalid socket address"));
- reset();
- c->returnValue()->setBoolean(false);
- return true;
- }
-
- if(!kvi_socket_bind(m_sock,sa.socketAddress(),((int)(sa.addressLength()))))
- {
- c->warning(__tr2qs("Bind failure"));
- reset();
- c->returnValue()->setBoolean(false);
- return true;
- }
- } else {
-#ifdef COMPILE_IPV6_SUPPORT
- KviSockaddr sa(m_uLocalPort,m_bIpV6,m_bUdp);
-#else
- KviSockaddr sa(m_uLocalPort,false,m_bUdp);
-#endif
- if(!sa.socketAddress())
- {
- c->warning(__tr2qs("Invalid socket address"));
- reset();
- c->returnValue()->setBoolean(false);
- return true;
- }
-
- if(!kvi_socket_bind(m_sock,sa.socketAddress(),((int)(sa.addressLength()))))
- {
- c->warning(__tr2qs("Bind failure"));
- reset();
- c->returnValue()->setBoolean(false);
- return true;
- }
- }
-
-
- if(!kvi_socket_listen(m_sock,5))
- {
- c->warning(__tr2qs("Listen failure"));
- reset();
- c->returnValue()->setBoolean(false);
- return true;
- }
-
-
- // Reread the port in case we're binding to a random one (0)
-
-#ifdef COMPILE_IPV6_SUPPORT
- KviSockaddr sareal(0,m_bIpV6,m_bUdp);
-#else
- KviSockaddr sareal(0,false,m_bUdp);
-#endif
-
- int size = (int)sareal.addressLength();
-
- if(kvi_socket_getsockname(m_sock,sareal.socketAddress(),&size))
- {
- m_uLocalPort = sareal.port();
- sareal.getStringAddress(m_szLocalIp);
- }
-
- // and setup the READ notifier...
- m_pSn = new QSocketNotifier(m_sock,QSocketNotifier::Read);
- QObject::connect(m_pSn,SIGNAL(activated(int)),this,SLOT(incomingConnection(int)));
- m_pSn->setEnabled(true);
-
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_LISTENING;
-
- c->returnValue()->setBoolean(true);
- return true;
-}
-
-void KviKvsObject_socket::incomingConnection(int)
-{
-#ifdef COMPILE_IPV6_SUPPORT
- struct sockaddr_in6 hostSockAddr6;
-#endif
- struct sockaddr_in hostSockAddr;
-
- int size = sizeof(hostSockAddr);
- struct sockaddr * addr = (struct sockaddr *)&hostSockAddr;
-
-#ifdef COMPILE_IPV6_SUPPORT
- if(m_bIpV6)
- {
- addr = (struct sockaddr *)&hostSockAddr6;
- size = sizeof(hostSockAddr6);
- }
-#endif
-
- // Incoming connection
- m_secondarySock = kvi_socket_accept(m_sock,addr,&size);
- if(m_secondarySock != KVI_INVALID_SOCKET)
- {
- // Connected
-#ifdef COMPILE_IPV6_SUPPORT
- if(m_bIpV6)
- {
- m_uSecondaryPort = ntohs(((struct sockaddr_in6 *)addr)->sin6_port);
- if(!kvi_binaryIpToStringIp_V6(((struct sockaddr_in6 *)addr)->sin6_addr,m_szSecondaryIp))
- m_szSecondaryIp = __tr("unknown");
- } else {
-#endif
- m_uSecondaryPort = ntohs(((struct sockaddr_in *)addr)->sin_port);
- if(!kvi_binaryIpToStringIp(((struct sockaddr_in *)addr)->sin_addr,m_szSecondaryIp))
- m_szSecondaryIp = __tr("unknown");
-#ifdef COMPILE_IPV6_SUPPORT
- }
-#endif
- KviKvsVariantList *params=0;
- callFunction(this,"incomingConnectionEvent",params);
- if(m_secondarySock != KVI_INVALID_SOCKET)
- {
- kvi_socket_close(m_secondarySock);
- m_secondarySock = KVI_INVALID_SOCKET;
- m_uSecondaryPort = 0;
- m_szSecondaryIp="";
- }
-
- } // else..huh ?... wait for the next notifier call
-}
-
-void KviKvsObject_socket::acceptConnection(kvi_socket_t s,kvi_u32_t uPort,const char * szIp)
-{
- reset();
- m_sock = s;
- m_uRemotePort = uPort;
- m_szRemoteIp = szIp;
-#ifdef COMPILE_IPV6_SUPPORT
- KviSockaddr sareal(0,m_bIpV6,m_bUdp);
-#else
- KviSockaddr sareal(0,false,m_bUdp);
-#endif
-
- int size = (int)sareal.addressLength();
-
- if(kvi_socket_getsockname(m_sock,sareal.socketAddress(),&size))
- {
- m_uLocalPort = sareal.port();
- sareal.getStringAddress(m_szLocalIp);
- }
-
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_CONNECTED;
-
- m_pSn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read);
- QObject::connect(m_pSn,SIGNAL(activated(int)),this,SLOT(readNotifierFired(int)));
- m_pSn->setEnabled(true);
-}
-
-void KviKvsObject_socket::delayedConnect()
-{
- if(m_pDelayTimer)delete m_pDelayTimer;
- m_pDelayTimer = new QTimer();
- connect(m_pDelayTimer,SIGNAL(timeout()),this,SLOT(doConnect()));
- m_pDelayTimer->start(0,true);
-}
-
-void KviKvsObject_socket::doConnect()
-{
- debug ("doConnect function");
- if(m_pDelayTimer)delete m_pDelayTimer;
- m_pDelayTimer = 0;
-
-
- KviSockaddr sa(m_szRemoteIp,m_uRemotePort,!kvi_isValidStringIp(m_szRemoteIp),m_bUdp);
-
- if(!sa.socketAddress())
- {
- unsigned int uOldConnectionId = m_uConnectionId;
- QString ipAddressError=__tr2qs("Invalid ip address ");
-
- ipAddressError.append(m_szRemoteIp);
-
- KviKvsVariantList params;
- QString tmp;
- KviQString::sprintf(tmp,__tr2qs("Invalid ip address (%Q)"),&m_szRemoteIp);
- params.append(new KviKvsVariant(tmp));
- callFunction(this,"connectFailedEvent",¶ms);
- /* callEventFunction("connectFailedEvent",0,new KviParameterList(
- new KviStr(KviStr::Format,__tr("Invalid ip address (%s)"),m_szRemoteIp.ptr())));
- */ if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- return;
- }
-debug ("Socket created");
-
- // create the socket
-#ifdef COMPILE_IPV6_SUPPORT
- m_bIpV6 = sa.isIpV6();
- m_sock = kvi_socket_create(sa.isIpV6() ? KVI_SOCKET_PF_INET6 : KVI_SOCKET_PF_INET,m_bUdp ? KVI_SOCKET_TYPE_DGRAM : KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP);
-#else
- m_bIpV6 = false;
- m_sock = kvi_socket_create(KVI_SOCKET_PF_INET,m_bUdp ? KVI_SOCKET_TYPE_DGRAM : KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP);
-#endif
-
- if(m_sock == KVI_INVALID_SOCKET)
- {
- unsigned int uOldConnectionId = m_uConnectionId;
- callFunction(this,"connectFailedEvent",new KviKvsVariantList(
- new KviKvsVariant(__tr2qs("Failed to create the socket"))));
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- return;
- }
- debug ("Valid socket");
-
- if(!kvi_socket_setNonBlocking(m_sock))
- {
- unsigned int uOldConnectionId = m_uConnectionId;
-
- callFunction(this,"connectFailedEvent",new KviKvsVariantList(
- new KviKvsVariant(__tr2qs("Failed to setup a nonblocking socket"))));
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- return;
- }
-
- if(!kvi_socket_connect(m_sock,sa.socketAddress(),((int)(sa.addressLength()))))
- {
- int err = kvi_socket_error();
- if(!kvi_socket_recoverableConnectError(err))
- {
- // Ops...
- int sockError=err;
- if(sockError==0)
- {
- // Zero error ?...let's look closer
- int iSize=sizeof(int);
- if(!kvi_socket_getsockopt(m_sock,SOL_SOCKET,SO_ERROR,
- (void *)&sockError,&iSize))sockError=0;
- }
- unsigned int uOldConnectionId = m_uConnectionId;
- QString callBackError=__tr2qs("Connect failure: ");
-
- callBackError.append((KviError::getDescription(KviError::translateSystemError(sockError)).utf8().data()));
- callFunction(this,"connectFailedEvent",new KviKvsVariantList(
- new KviKvsVariant(callBackError)));
-
-/* callEventFunction("connectFailedEvent",0,new KviParameterList(
- new KviStr(KviStr::Format,__tr("Connect failure: %s"),KviError::getDescription(KviError::translateSystemError(sockError)).utf8().data())));
-*/ if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- return;
- }
- }
- debug ("Socket connected");
- m_pDelayTimer = new QTimer();
- connect(m_pDelayTimer,SIGNAL(timeout()),this,SLOT(connectTimeout()));
- m_pDelayTimer->start(m_uConnectTimeout,true);
-
- m_pSn = new QSocketNotifier((int)m_sock,QSocketNotifier::Write);
- QObject::connect(m_pSn,SIGNAL(activated(int)),this,SLOT(writeNotifierFired(int)));
- m_pSn->setEnabled(true);
-}
-
-void KviKvsObject_socket::connectTimeout()
-{
- unsigned int uOldConnectionId = m_uConnectionId;
-
- callFunction(this,"connectFailedEvent",new KviKvsVariantList(
- new KviKvsVariant(__tr2qs("Connect attempt timed out"))));
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
-}
-
-void KviKvsObject_socket::delayedLookupRemoteIp()
-{
- if(m_pDelayTimer)delete m_pDelayTimer;
- m_pDelayTimer = new QTimer();
- connect(m_pDelayTimer,SIGNAL(timeout()),this,SLOT(lookupRemoteIp()));
- m_pDelayTimer->start(0,true);
-}
-
-void KviKvsObject_socket::lookupRemoteIp()
-{
- debug ("Resolve dns");
- if(m_pDelayTimer)delete m_pDelayTimer;
- m_pDelayTimer = 0;
- if(m_pDns)delete m_pDns;
- m_pDns = new KviDns();
- connect(m_pDns,SIGNAL(lookupDone(KviDns *)),this,SLOT(lookupDone(KviDns *)));
- if(!m_pDns->lookup(m_szRemoteIp,KviDns::Any))
- {
- unsigned int uOldConnectionId = m_uConnectionId;
-
- callFunction(this,"connectFailedEvent",new KviKvsVariantList(
- new KviKvsVariant(__tr2qs("Can't start the DNS thread"))));
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- }
-}
-
-void KviKvsObject_socket::lookupDone(KviDns *pDns)
-{
-
- if(pDns->state() != KviDns::Success)
- {
- unsigned int uOldConnectionId = m_uConnectionId;
-
- callFunction(this,"connectFailedEvent",new KviKvsVariantList(
- new KviKvsVariant(KviError::getDescription(pDns->error()))));
-
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- return;
- }
- m_szRemoteIp = pDns->firstIpAddress();
- debug ("Dns resolved in %s",m_szRemoteIp.latin1());
-
- delete m_pDns;
- m_pDns = 0;
- doConnect();
-}
-
-void KviKvsObject_socket::writeNotifierFired(int)
-{
- debug ("Here in the writeNotifierFired");
- if(m_pSn)
- {
- delete m_pSn;
- m_pSn = 0;
- }
- if(m_pDelayTimer)
- {
- delete m_pDelayTimer;
- m_pDelayTimer = 0;
- }
-
- // Check for errors...
- int sockError;
- int iSize=sizeof(int);
- if(!kvi_socket_getsockopt(m_sock,SOL_SOCKET,SO_ERROR,(void *)&sockError,&iSize))sockError = -1;
- //sockError = 0;
- if(sockError != 0)
- {
- //debug("Failed here %d",sockError);
- //failed
- if(sockError > 0)sockError = KviError::translateSystemError(sockError);
- else sockError = KviError_unknownError; //Error 0 ?
- unsigned int uOldConnectionId = m_uConnectionId;
- callFunction(this,"connectFailedEvent",new KviKvsVariantList(
- new KviKvsVariant(KviError::getDescription(sockError))));
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- } else {
- // Succesfully connected
- // create the correct read notifier now...
- m_pSn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read);
- QObject::connect(m_pSn,SIGNAL(activated(int)),this,SLOT(readNotifierFired(int)));
- m_pSn->setEnabled(true);
-
-#ifdef COMPILE_IPV6_SUPPORT
- KviSockaddr sareal(0,m_bIpV6,m_bUdp);
-#else
- KviSockaddr sareal(0,false,m_bUdp);
-#endif
- int size = (int)sareal.addressLength();
- if(kvi_socket_getsockname(m_sock,sareal.socketAddress(),&size))
- {
- m_uLocalPort = sareal.port();
- sareal.getStringAddress(m_szLocalIp);
- }
- unsigned int uOldConnectionId = m_uConnectionId;
- KviKvsVariantList *params=0;
- callFunction(this,"connectEvent",params);
- if(m_uConnectionId == uOldConnectionId)
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_CONNECTED;
- // else the connection has been already changed!
- }
-}
-
-void KviKvsObject_socket::readNotifierFired(int)
-{
- debug ("here in the readNotifierFired");
- //read data
- if((m_uInBufferLen - m_uInDataLen) < KVI_READ_CHUNK)
- {
- m_uInBufferLen += KVI_IN_BUFFER_ALLOC_CHUNK;
- m_pInBuffer = (char *)kvi_realloc(m_pInBuffer,m_uInBufferLen);
- }
-
- int readLength = kvi_socket_recv(m_sock,m_pInBuffer + m_uInDataLen,KVI_READ_CHUNK);
-
- if(readLength <= 0)
- {
- if(readLength==0)
- {
- unsigned int uOldConnectionId = m_uConnectionId;
- KviKvsVariantList *params=0;
- callFunction(this,"disconnectEvent",params);
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- return;
- } else {
- //check for transmission errors
- int err = kvi_socket_error();
-#ifdef COMPILE_ON_WINDOWS
- if((err != EAGAIN) && (err != EINTR) && (err != WSAEWOULDBLOCK))
-#else
- if((err != EAGAIN) && (err != EINTR))
-#endif
- {
- unsigned int uOldConnectionId = m_uConnectionId;
- if(err > 0)
-
- {
- // QString error=KviError::translateSystemError(err);
- callFunction(this,"disconnectEvent",new KviKvsVariantList(
- new KviKvsVariant((kvs_int_t)KviError::translateSystemError(err))));
- } else {
- callFunction(this,"disconnectEvent",new KviKvsVariantList(
- new KviKvsVariant(KviError::getDescription(KviError_remoteEndClosedConnection))));
-
- }
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- return;
- } //else transient error...wait again...
- }
- return; // can do nothing
- }
- // readLength > 0
- m_uInDataLen += readLength;
-
- //KviStr * s = new KviStr();
- QString s;
- s.setNum(m_uInDataLen);
-
-
- unsigned int uOldConnectionId = m_uConnectionId;
- callFunction(this,"dataAvailableEvent",new KviKvsVariantList(new KviKvsVariant(s)));
- if(m_uConnectionId == uOldConnectionId)
- {
- if(m_uInDataLen > (4096 * 1024)) // too much data in buffer (not reading)
- {
- callFunction(this,"disconnectEvent",new KviKvsVariantList(
- new KviKvsVariant(__tr2qs("Too much unprocessed incoming data (you've left this socket unmanaged ?)"))));
- reset();
- }
- }
-}
-
-void KviKvsObject_socket::eatInData(unsigned int uLen)
-{
- if(uLen > m_uInDataLen)uLen = m_uInDataLen;
-
- m_uInDataLen -= uLen;
-
- if(m_uInDataLen > 0)
- {
- kvi_memmove(m_pInBuffer,m_pInBuffer + uLen,m_uInDataLen);
- }
-
- unsigned int uSpace = m_uInBufferLen - m_uInDataLen;
-
- if(uSpace > KVI_IN_BUFFER_ALLOC_CHUNK)
- {
- m_uInBufferLen -= KVI_IN_BUFFER_ALLOC_CHUNK;
- m_pInBuffer = (char *)kvi_realloc(m_pInBuffer,m_uInBufferLen);
- }
-}
-
-void KviKvsObject_socket::delayedFlush(unsigned int uTimeout)
-{
- if(m_pFlushTimer->isActive())m_pFlushTimer->stop();
- m_pFlushTimer->start(uTimeout);
-}
-
-void KviKvsObject_socket::tryFlush()
-{
- if(m_pFlushTimer->isActive())m_pFlushTimer->stop();
-
- if(m_pOutBuffer->size() == 0)
- {
- return;
- }
-
- int result = kvi_socket_send(m_sock,m_pOutBuffer->data(),m_pOutBuffer->size());
-
- if(result >= 0)
- {
- if(result == m_pOutBuffer->size())
- {
- m_pOutBuffer->clear();
- } else {
- if(result > 0)m_pOutBuffer->remove(result);
- delayedFlush(500);
- }
- } else {
- // Oops...error ?
- int err = kvi_socket_error();
-#ifdef COMPILE_ON_WINDOWS
- if((err == EAGAIN) || (err == EINTR) || (err = WSAEWOULDBLOCK))
-#else
- if((err == EAGAIN)||(err == EINTR))
-#endif
- {
- // Transient error...partial send as before...
- // Async continue...
- delayedFlush(500);
- return;
- } else {
- // Disconnected... :(
- unsigned int uOldConnectionId = m_uConnectionId;
- callFunction(this,"disconnectEvent",0,new KviKvsVariantList(
- new KviKvsVariant(KviError::getDescription(KviError::translateSystemError(err)))));
- if(m_uConnectionId == uOldConnectionId)reset();
- // else it has already been called!
- return;
- }
- }
-}
-void KviKvsObject_socket::reset()
-{
- m_uConnectionId++; // this is the only place where this is incremented!
- if(m_pDelayTimer)
- {
- delete m_pDelayTimer;
- m_pDelayTimer = 0;
- }
- if(m_pDns)
- {
- delete m_pDns;
- m_pDns = 0;
- }
- if(m_pSn)
- {
- delete m_pSn;
- m_pSn = 0;
- }
- if(m_sock != KVI_INVALID_SOCKET)
- {
- kvi_socket_close(m_sock);
- m_sock = KVI_INVALID_SOCKET;
- }
- if(m_pInBuffer)
- {
- kvi_free(m_pInBuffer);
- m_pInBuffer = 0;
- }
- if(m_secondarySock)
- {
- kvi_socket_close(m_secondarySock);
- m_secondarySock = KVI_INVALID_SOCKET;
- }
- m_uSecondaryPort = 0;
- m_szSecondaryIp="";
- delete m_pOutBuffer;
- if(m_pFlushTimer->isActive())m_pFlushTimer->stop();
- m_pOutBuffer = new KviDataBuffer();
- m_uInBufferLen = 0;
- m_uInDataLen = 0;
- m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED;
- m_uRemotePort = 0;
- m_szRemoteIp="";
- m_uLocalPort = 0;
- m_szLocalIp="";
- m_bIpV6 = false;
-}
-unsigned int KviKvsObject_socket::readGetLength(KviKvsObjectFunctionCall *c)
-{
- kvs_uint_t uLen;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("length",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uLen)
- KVSO_PARAMETERS_END(c)
- if (uLen>m_uInDataLen || !uLen) return m_uInDataLen;
- else return uLen;
- }
-
-bool KviKvsObject_socket::functionRead(KviKvsObjectFunctionCall *c)
-{
- unsigned int uLen = readGetLength(c);
-
- if(uLen > 0)
- {
- // convert NULLS to char 255
- for(unsigned int i = 0;i < uLen;i++)
- {
- if(!m_pInBuffer[i])m_pInBuffer[i] = (char)(255);
- }
- QString tmpBuffer = QString::fromUtf8(m_pInBuffer,uLen);
- c->returnValue()->setString(tmpBuffer);
-
- eatInData(uLen);
- }
- return true;
-}
-
-bool KviKvsObject_socket::functionReadHex(KviKvsObjectFunctionCall *c)
-{
- //??? funzioner�
- unsigned int uLen = readGetLength(c);
- bool bOk;
- if(uLen > 0)
- {
- QString szTmp;
- szTmp =m_pInBuffer;
- szTmp.toInt(&bOk,16);
- c->returnValue()->setString(szTmp);
- eatInData(uLen);
- }
- return true;
-}
-
-bool KviKvsObject_socket::functionWrite(KviKvsObjectFunctionCall *c)
-{
- QString szData;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("szData",KVS_PT_STRING,0,szData)
- KVSO_PARAMETERS_END(c)
-
-KviQCString szData8 = szData.utf8();
- if(szData8.length() > 0)
- {
- m_pOutBuffer->append((const unsigned char*)szData8.data(),szData8.length());
- delayedFlush(0);
- }
- return true;
-}
-
-
-
-//--------------
-
-#include "m_class_socket.moc"
+// +// File : class_socket.cpp +// Creation date : Sun Nov 11 03:13:45 2001 GMT by Szymon Stefanek +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 2001 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// + +#include "kvi_settings.h" +#include "kvi_qstring.h" + +#define _KVI_DEBUG_CHECK_RANGE_ +#include "kvi_debug.h" + + +#include "kvi_locale.h" +#include "kvi_error.h" +#include "kvi_netutils.h" +#include "kvi_dns.h" +#include "kvi_error.h" +#include "kvi_socket.h" +#include "kvi_malloc.h" +#include "kvi_memmove.h" +#include "kvi_databuffer.h" +#include "kvi_qcstring.h" + +#include "class_socket.h" + +//#include <stdlib.h> + +#define KVI_IN_BUFFER_ALLOC_CHUNK 4096 +#define KVI_READ_CHUNK 1024 +/* +static KviScriptObjectClass * g_pSocketClass = 0; + +static KviScriptObject * socketClassCreateInstance(KviScriptObjectClass * cls,KviScriptObject *par,const char * nam) +{ + return new KviScriptSocketObject(cls,par,nam); +} + +KviScriptSocketObject::KviScriptSocketObject(KviScriptObjectClass * cla,KviScriptObject * par,const char * nam) +: KviScriptObject(cla,par,nam) +{ + m_uConnectionId = 0; + m_sock = KVI_INVALID_SOCKET; + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED; + m_uRemotePort = 0; + m_uSecondaryPort = 0; + m_pSn = 0; + m_pDns = 0; + m_pDelayTimer = 0; + m_uConnectTimeout = 60000; + m_pInBuffer = 0; + m_uInBufferLen = 0; + m_uInDataLen = 0; + m_pOutBuffer = new KviDataBuffer(); + m_pFlushTimer = new QTimer(); + m_bIpV6 = false; + m_uLocalPort = 0; + m_secondarySock = KVI_INVALID_SOCKET; + connect(m_pFlushTimer,SIGNAL(timeout()),this,SLOT(tryFlush())); +} + +KviScriptSocketObject::~KviScriptSocketObject() +{ + delete m_pOutBuffer; + delete m_pFlushTimer; + + if(m_pInBuffer)kvi_free(m_pInBuffer); + if(m_pDelayTimer)delete m_pDelayTimer; + if(m_pDns)delete m_pDns; + if(m_pSn)delete m_pSn; + if(m_sock != KVI_INVALID_SOCKET)kvi_socket_close(m_sock); + if(m_secondarySock != KVI_INVALID_SOCKET)kvi_socket_close(m_secondarySock); +} + +void KviScriptSocketObject::reset() +{ + m_uConnectionId++; // this is the only place where this is incremented! + if(m_pDelayTimer) + { + delete m_pDelayTimer; + m_pDelayTimer = 0; + } + if(m_pDns) + { + delete m_pDns; + m_pDns = 0; + } + if(m_pSn) + { + delete m_pSn; + m_pSn = 0; + } + if(m_sock != KVI_INVALID_SOCKET) + { + kvi_socket_close(m_sock); + m_sock = KVI_INVALID_SOCKET; + } + if(m_pInBuffer) + { + kvi_free(m_pInBuffer); + m_pInBuffer = 0; + } + if(m_secondarySock) + { + kvi_socket_close(m_secondarySock); + m_secondarySock = KVI_INVALID_SOCKET; + } + m_uSecondaryPort = 0; + m_szSecondaryIp.clear(); + delete m_pOutBuffer; + if(m_pFlushTimer->isActive())m_pFlushTimer->stop(); + m_pOutBuffer = new KviDataBuffer(); + m_uInBufferLen = 0; + m_uInDataLen = 0; + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED; + m_uRemotePort = 0; + m_szRemoteIp.clear(); + m_uLocalPort = 0; + m_szLocalIp.clear(); + m_bIpV6 = false; +} + +/* + @doc: socket + @keyterms: + socket object class + @title: + socket class + @type: + class + @short: + A Ipv4/Ipv6 TCP socket + @inherits: + [class]object[/class] + @description: + This class provides a standard TCP/IP socket functionality.[br] + It can be used either for connecting to a remote host or to listening for incoming connections.[br] + If the KVIrc executable has been compiled with the IPV6 protocol support , this socket also supports it.[br] + @functions: + !fn: $status() + Returns the status of the socket :[br] + 4=connected[br] + 3=listening[br] + 2=connecting[br] + 1=in dns call[br] + 0=disconnected + + !fn: $connectTimeout() + Returns the value of the connect attempt timeout in milliseconds.[br] + This is the timeout after that a connection attempt will be considered as failed if the remote + host is not responding. You can set it with [classfnc:socket]$setConnectTimeout[/classfnc](). + + !fn: $setConnectTimeout(<timeout>) + Sets the connect timeout for this socket. <timeout> must be a positive value in milliseconds.[br] + The default timeout is 60000. + + !fn: $connect(<host>,<port>) + Attempts a connection to <host> on port <port>.[br] + <host> can be a numeric internet address (either Ipv4 or Ipv6 (if supported)) or a hostname.[br] + If a hostname is used, a DNS lookup is performed (the socket enters the "dns call" state).[br] + This function returns 1 if the connect attempt can be succesfully initiated, + 0 otherwise.[br] In fact , this function returns 0 only if the supplied <port> parameter + is invalid or the socket is in an incoherent state (already connected or listening): + for a newly created socket and with a valid <port> number you can safely ignore + the return value.[br] + Please note that the connection is asynchronous: when this function returns + the socket is NOT connected: it has just initiated the connect attempt + and you will be notified of the attempt result by an asynchronous event call: + in case of failure , $connectFailedEvent() will be called , in case of + succes , $connectEvent() will be called. + + !fn: $listen([<port>[,<interface>[,<force_ipv6>]]]) + Attempts to listen on the specified <port> and <interface>.[br] + If <port> is not passed it is assumed to be 0 , if <interface> is not passed , it is assumed to be + "any interface" (INADDR_ANY).[br] Port 0 means that the kernel should choose a "random" port to listen on.[br] + If the <interface> is recognized as IPV6 address , and IPV6 is supported , the socket listens + in IPV6 mode. If <interface> is an empty string and <force_ipv6> is 1 the socket listens + on "any ipv6 interface".[br] + This function returns '1' in case of success and '0' in case of failure.[br] + On some systems listening in the IPV6 namespace allows to accept also IPV4 connections (this includes + linux but not windows afaik).[br] + When an incoming connection will arrive , $incomingConnectionEvent() will be called. + + !fn: $accept(<socketId>) + This function can be called only from inside $incomingConnectionEvent().[br] + <socketId> must be a newly created socket sub-class instance object.[br] + The passed object will be set up to handle the incoming connection and this object + will remain in listening state (unless you explicitly close it).[br] + This function returns '1' in case of success and '0' in case of failure. + + !fn: $connectEvent() + This function is called when a connection attempt has been succesfully completed. + The socket is actually connected to [classfnc:socket]$remoteIp[/classfnc]() on + [classfnc:socket]$remotePort[/classfnc](). You can start + writing data and you may expect [classfnc:socket]$dataAvailableEvent[/classfnc]() to be + triggered. + + !fn: $incomingConnectionEvent() + This function is called when an incoming connection arrives over a socket in listening state.[br] + You must call [classfnc:socket]$accept[/classfnc]() passing a newly created socket object + to accept and handle the connection.[br] If you don't call [classfnc:socket]$accept[/classfnc]() + the incoming connection will be automatically terminated. + + !fn: $connectFailedEvent(<reason>) + This function is called when a connection attempt fails for some reason. <reason> contains + the error string.[br] + This function may be called only between a call to [classfnc:socket]$connect[/classfnc]() and + the [classfnc:socket]$connectEvent[/classfnc](). + + !fn: $disconnectEvent([error]) + This function is called when a connection is terminated either cleanly or because of an error.[br] + [error] is an empty string in case of a "clean" termination (connection closed by the remote host) + or is a message describing the socket error that caused the connection to be interrupted. + + !fn: $dataAvailableEvent(<data_length>) + This function is called when some data is available to be read: the <data_length> parameter specifies + the length of the available data in bytes.[br] + You can use one of the $read* functions to obtain the data. + + !fn: $read(<length>) + Reads at most <length> bytes of data from the socket. If <length> is anything "outside" the + available data range (<length> < 0 or <length> > available_data_length), this function + returns all the available data.[br] + Please note that this function can't deal withi binary data: NULL characters are transformed to + ASCII characters 255. + + !fn: $readHex(<length>) + Reads at most <length> bytes of data from the socket. If <length> is anything "outside" the + available data range (<length> < 0 or <length> > available_data_length), this function + returns all the available data.[br] + Returns the data encoded as hexadecimal digit string: this function can deal with binary data too. + + !fn: $write(<data>) + Writes <data> to the socket.[br] + This function can't deal with binary data (you can't send a NULL character)[br] + Please note that when this function finishes it does not mean that the data has reached the remote end.[br] + Basically it does not even mean that the data has been sent to the remote host.[br] + The data is enqueued for sending and will be sent as soon as possible.[br] + If you're going to [cmd]delete[/cmd] this object just after the $write call, you should + call [classfnc:socket]$close[/classfnc]() just before [cmd]delete[/cmd] to ensure the data delivery. + + !fn: $writeHex(<hex_data>) + Writes <data> to the socket.[br] + <data> is expected to be a hexadecimal rappresentation of the bytes to be sent (two HEX characters + for each byte). This means that the length of <hex_data> string must be a multiple of 2.[br] + Returns the length of the actually decoded and sent data in bytes or -1 in case of error (the string + was not a valid hexadecimla rappresentation).[br] + Please note that when this function finishes it does not mean that the data has reached the remote end.[br] + Basically it does not even mean that the data has been sent to the remote host.[br] + The data is enqueued for sending and will be sent as soon as possible.[br] + If you're going to [cmd]delete[/cmd] this object just after the $writeHex call, you should + call [classfnc:socket]$close[/classfnc]() just before [cmd]delete[/cmd] to ensure the data delivery. + + !fn: $close() + Resets this socket state: kills any pending or active connection. After a close() call + the socket may be used for a new connection.[br] + If there is an active connection, there is a last attempt to flush the pending outgoing data.[br] + You don't need to call $close() if you [cmd]delete[/cmd] the socket: KVIrc will + reset the socket state automatically and free the memory. But if you want to ensure data delivery + after a $write call sequece and just before a [cmd]delete[/cmd], $close() is the only chance to do it. + + !fn: $remoteIp() + Returns the IP address of the remote end of this socket.[br] + The return value is meaningful only if the socket is in connected or connecting state. + + !fn: $setProtocol(<protocol>) + Let KVIrc use TCP jr UDP protocol + + !fn: $remotePort() + Returns the port of the remote end of this socket.[br] + The return value is meaningful only if the socket is in connected or connecting state. + + !fn: $localIp() + Returns the IP address of the local end of this socket.[br] + The return value is meaningful only if the socket is in connected , listening or connecting state. + + !fn: $localPort() + Returns the port of the local end of this socket.[br] + The return value is meaningful only if the socket is in connected , listening or connecting state. + +@examples: + [example] + #Server socket: listen 80 port and answer to requests (multi-threaded)[br] +[br] + class (webserver,socket) {[br] + constructor () {[br] + $$->$listen(80, "127.0.0.1")[br] + }[br] + incomingConnectionEvent()[br] + {[br] + %tmp = $new(socket)[br] + $$->$accept(%tmp)[br] + echo "Webserver incoming Conection from: %tmp->$remoteIp : %tmp->$remotePort"[br] + %tmp->$write("HTTP/1.1 200 OK\n\n<html><head></head><body><h1>KVIrc Webserver</h1></body></html>\n")[br] + %tmp->$close()[br] + delete %tmp[br] + }[br] + }[br] + [br] + #finally start webserver[br] + %WebS = $new(webserver)[br] + [br] + [/example] + [example] + #Client socket - go to google and grab request header[br] + class (httprequest,socket) {[br] + constructor () [br] + {[br] + # connect to the server[br] + $$->$connect("www.google.de",80)[br] + }[br] + destructor()[br] + {[br] + # if the socket is still open close it[br] + if($$->$status() == 4) $$->$close()[br] + }[br] + connectFailedEvent() [br] + {[br] + # the connection to the server failed[br] + echo "Connection failed: "$0[br] + delete $$[br] + }[br] + connectEvent() [br] + {[br] + # connection is complete[br] + # send a request to receive the headers only from http://www.google.de/[br] + $$->$write("HEAD / HTTP/1.1\r\nHost: www.google.de\r\nConnction: Close\r\nUser-Agent: KVIrc socket\r\n\r\n");[br] + }[br] + dataAvailableEvent() [br] + {[br] + # reading the received data[br] + %newdata = $$->$read($0)[br] + echo %newdata[br] + #close and delete the socket[br] + $$->$close()[br] + delete $$[br] + }[br] + disconnectEvent() [br] + {[br] + # connection has been closed[br] + echo "Connection closed"[br] + delete $$[br] + }[br] +}[br] + +#Creating the socket[br] +%Temp = $new(httprequest)[br] + [/example] +*/ + +KVSO_BEGIN_REGISTERCLASS(KviKvsObject_socket,"socket","object") + + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"status",functionStatus) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"remotePort",functionRemotePort) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"remoteIp",functionRemoteIp) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"localIp",functionLocalIp) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"localPort",functionLocalPort) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"connect",functionConnect) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"connectTimeout",functionConnectTimeout) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"setConnectTimeout",functionSetConnectTimeout) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"close",functionClose) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"read",functionRead) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"readHex",functionReadHex) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"write",functionWrite) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"writeHex",functionWriteHex) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"setProtocol",functionSetProtocol) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"listen",functionListen) + KVSO_REGISTER_HANDLER(KviKvsObject_socket,"accept",functionAccept) + + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"connectEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"connectFailedEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"disconnectEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"dataAvailableEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_socket,"incomingConnectionEvent") + +KVSO_END_REGISTERCLASS(KviKvsObject_socket) + + +KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_socket,KviKvsObject) + + + m_bUdp = false; + m_uConnectionId = 0; + m_sock = KVI_INVALID_SOCKET; + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED; + m_uRemotePort = 0; + m_uSecondaryPort = 0; + m_pSn = 0; + m_pDns = 0; + m_pDelayTimer = 0; + m_uConnectTimeout = 60000; + m_pInBuffer = 0; + m_uInBufferLen = 0; + m_uInDataLen = 0; + m_pOutBuffer = new KviDataBuffer(); + m_pFlushTimer = new QTimer(); + m_bIpV6 = false; + m_uLocalPort = 0; + m_secondarySock = KVI_INVALID_SOCKET; + connect(m_pFlushTimer,SIGNAL(timeout()),this,SLOT(tryFlush())); +KVSO_END_CONSTRUCTOR(KviKvsObject_socket) + +KVSO_BEGIN_DESTRUCTOR(KviKvsObject_socket) + delete m_pOutBuffer; + delete m_pFlushTimer; + + if(m_pInBuffer)kvi_free(m_pInBuffer); + if(m_pDelayTimer)delete m_pDelayTimer; + if(m_pDns)delete m_pDns; + if(m_pSn)delete m_pSn; + if(m_sock != KVI_INVALID_SOCKET)kvi_socket_close(m_sock); + if(m_secondarySock != KVI_INVALID_SOCKET)kvi_socket_close(m_secondarySock); +KVSO_END_DESTRUCTOR(KviKvsObject_socket) +//---------------------- + + +bool KviKvsObject_socket::functionStatus(KviKvsObjectFunctionCall *c) +{ + c->returnValue()->setInteger(m_iStatus); + return true; +} + +bool KviKvsObject_socket::functionClose(KviKvsObjectFunctionCall *c) +{ + if((m_pOutBuffer->size() != 0) && (m_iStatus == KVI_SCRIPT_SOCKET_STATUS_CONNECTED)) + tryFlush(); + + reset(); + return true; +} + +bool KviKvsObject_socket::functionConnectTimeout(KviKvsObjectFunctionCall *c) +{ + c->returnValue()->setInteger(m_uConnectTimeout); + return true; +} + +bool KviKvsObject_socket::functionSetConnectTimeout(KviKvsObjectFunctionCall *c) +{ + kvs_uint_t uTimeout; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("time_out",KVS_PT_UNSIGNEDINTEGER,0,uTimeout) + KVSO_PARAMETERS_END(c) + m_uConnectTimeout = uTimeout; + return true; +} + +bool KviKvsObject_socket::functionRemotePort(KviKvsObjectFunctionCall *c) +{ + c->returnValue()->setInteger(m_uRemotePort); + return true; +} + +bool KviKvsObject_socket::functionRemoteIp(KviKvsObjectFunctionCall *c) +{ + c->returnValue()->setString(m_szRemoteIp); + return true; +} + +bool KviKvsObject_socket::functionLocalPort(KviKvsObjectFunctionCall *c) +{ + c->returnValue()->setInteger(m_uLocalPort); + return true; +} + +bool KviKvsObject_socket::functionLocalIp(KviKvsObjectFunctionCall *c) +{ + c->returnValue()->setString(m_szLocalIp); + return true; +} + +bool KviKvsObject_socket::functionAccept(KviKvsObjectFunctionCall *c) +{ + KviKvsObject * pObject; + kvs_hobject_t hObject; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("object_socket",KVS_PT_HOBJECT,0,hObject) + KVSO_PARAMETERS_END(c) + + pObject = KviKvsKernel::instance()->objectController()->lookupObject(hObject); + + if(!pObject) + { + c->warning(__tr2qs("No socket object specified")); + return true; + } + + if(!pObject->inherits("KviKvsObject_socket")) + { + c->warning(__tr2qs("Invalid socket object specified (it doesn't inherit from socket)")); + return true; + } + + if(m_secondarySock != KVI_INVALID_SOCKET) + { + ((KviKvsObject_socket *)pObject)->acceptConnection(m_secondarySock,m_uSecondaryPort,m_szSecondaryIp); + + m_secondarySock = KVI_INVALID_SOCKET; + m_uSecondaryPort = 0; + m_szSecondaryIp=""; + } else { + c->warning(__tr2qs("There is no connection to accept!")); + } + return true; +} + + +bool KviKvsObject_socket::functionSetProtocol(KviKvsObjectFunctionCall *c) +{ + QString m_szHex; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("hex_string",KVS_PT_STRING,0,m_szHex) + KVSO_PARAMETERS_END(c) + + m_bUdp=KviQString::equalCI(m_szHex,"udp"); + return false; +} + +bool KviKvsObject_socket::functionWriteHex(KviKvsObjectFunctionCall *c) +{ + QString m_szHex; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("hex_string",KVS_PT_STRING,0,m_szHex) + KVSO_PARAMETERS_END(c) + + if(m_szHex.length() > 0) + { + bool bOk; + QString szTmp; + szTmp=m_szHex.setNum(m_szHex.toInt(&bOk,16),16); + if(szTmp.length()>0) + { + KviQCString szData8 = szTmp.utf8(); + m_pOutBuffer->append((const unsigned char *)(szData8.data()),szData8.length()); + delayedFlush(0); + c->returnValue()->setInteger(szData8.length()); + } + } + + /* + if(pszData) + { + if(pszData->len() > 0) + { + char * ptr; + len = pszData->hexToBuffer(&ptr); + if(len > 0) + { + m_pOutBuffer->append((const unsigned char *)(ptr),len); + delayedFlush(0); + KviStr::freeBuffer(ptr); + } + } + } + buffer.append(KviStr::Format,"%d",len); +*/ + return true; +} + + + + + +bool KviKvsObject_socket::functionConnect(KviKvsObjectFunctionCall *c) +{ + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("remote_ip",KVS_PT_STRING,0,m_szRemoteIp) + KVSO_PARAMETER("remote_port",KVS_PT_UNSIGNEDINTEGER,0,m_uRemotePort) + KVSO_PARAMETERS_END(c) + debug ("Function connect"); + + + if (m_uRemotePort>65535) + { + c->warning(__tr2qs("Value %d for port is out of range (values allowed are from 0 to 65535"),m_uRemotePort); + return true; + } + if((m_sock != KVI_INVALID_SOCKET) || (m_iStatus != KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED)) + { + c->warning(__tr2qs("Another connection in progress")); + c->returnValue()->setBoolean(true); + return true; + } + + +#ifdef COMPILE_IPV6_SUPPORT + if(kvi_isValidStringIp(m_szRemoteIp) || kvi_isValidStringIp_V6(m_szRemoteIp)) +#else + if(kvi_isValidStringIp(m_szRemoteIp)) +#endif + { + debug ("ok connecting"); + debug ("connectinhg on ip %s ",m_szRemoteIp.latin1()); + debug ("non so ip"); + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_CONNECTING; + delayedConnect(); + } else { + debug ("connectinhg on ip %s port %d",m_szRemoteIp.latin1(),m_uRemotePort); + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DNS; + delayedLookupRemoteIp(); + } + c->returnValue()->setBoolean(true); + return true; +} + + + + + + +bool KviKvsObject_socket::functionListen(KviKvsObjectFunctionCall *c) +{ + if((m_sock != KVI_INVALID_SOCKET) || (m_iStatus != KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED)) + { + c->warning(__tr2qs("Another connection in progress")); + c->returnValue()->setBoolean(false); + return true; + } + kvs_uint_t uLocalPort; + QString m_szLocalIp; + bool m_bIpV6; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("local_port",KVS_PT_UNSIGNEDINTEGER,0,uLocalPort) + KVSO_PARAMETER("local_ip",KVS_PT_STRING,KVS_PF_OPTIONAL,m_szLocalIp) + KVSO_PARAMETER("bool_ipV6",KVS_PT_BOOLEAN,KVS_PF_OPTIONAL,m_bIpV6) + KVSO_PARAMETERS_END(c) + m_uLocalPort=uLocalPort; + +#ifndef COMPILE_IPV6_SUPPORT + if(m_bIpV6) + { + c->warning(__tr2qs("No IPV6 support in this executable")); + c->returnValue()->setBoolean(false); + reset(); + return true; + } +#endif + + bool bGotIp = false; + + if(!m_szLocalIp.isEmpty()) + { + + // Check the address type + if(kvi_isValidStringIp(m_szLocalIp))bGotIp = true; + else { +#ifdef COMPILE_IPV6_SUPPORT + if(kvi_isValidStringIp_V6(m_szLocalIp)) + { + bGotIp = true; + m_bIpV6 = true; + } else { +#else + c->warning(__tr2qs("Invalid IP address specified ('%Q')"),&m_szLocalIp); + c->returnValue()->setBoolean(false); + reset(); + return true; +#endif +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + } + } + + +#ifdef COMPILE_IPV6_SUPPORT + m_sock = kvi_socket_create(m_bIpV6 ? KVI_SOCKET_PF_INET6 : KVI_SOCKET_PF_INET, + m_bUdp ? KVI_SOCKET_TYPE_DGRAM : KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP); +#else + m_sock = kvi_socket_create(KVI_SOCKET_PF_INET,m_bUdp ? KVI_SOCKET_TYPE_DGRAM : KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP); +#endif + + if(m_sock == KVI_INVALID_SOCKET) + { + c->warning(__tr2qs("Socket creation failed")); + c->returnValue()->setBoolean(false); + reset(); + return true; + } + + if(!m_szLocalIp.isEmpty()) + { +#ifdef COMPILE_IPV6_SUPPORT + KviSockaddr sa(m_szLocalIp,m_uLocalPort,m_bIpV6,m_bUdp); +#else + KviSockaddr sa(m_szLocalIp,m_uLocalPort,false,m_bUdp); +#endif + if(!sa.socketAddress()) + { + c->warning(__tr2qs("Invalid socket address")); + reset(); + c->returnValue()->setBoolean(false); + return true; + } + + if(!kvi_socket_bind(m_sock,sa.socketAddress(),((int)(sa.addressLength())))) + { + c->warning(__tr2qs("Bind failure")); + reset(); + c->returnValue()->setBoolean(false); + return true; + } + } else { +#ifdef COMPILE_IPV6_SUPPORT + KviSockaddr sa(m_uLocalPort,m_bIpV6,m_bUdp); +#else + KviSockaddr sa(m_uLocalPort,false,m_bUdp); +#endif + if(!sa.socketAddress()) + { + c->warning(__tr2qs("Invalid socket address")); + reset(); + c->returnValue()->setBoolean(false); + return true; + } + + if(!kvi_socket_bind(m_sock,sa.socketAddress(),((int)(sa.addressLength())))) + { + c->warning(__tr2qs("Bind failure")); + reset(); + c->returnValue()->setBoolean(false); + return true; + } + } + + + if(!kvi_socket_listen(m_sock,5)) + { + c->warning(__tr2qs("Listen failure")); + reset(); + c->returnValue()->setBoolean(false); + return true; + } + + + // Reread the port in case we're binding to a random one (0) + +#ifdef COMPILE_IPV6_SUPPORT + KviSockaddr sareal(0,m_bIpV6,m_bUdp); +#else + KviSockaddr sareal(0,false,m_bUdp); +#endif + + int size = (int)sareal.addressLength(); + + if(kvi_socket_getsockname(m_sock,sareal.socketAddress(),&size)) + { + m_uLocalPort = sareal.port(); + sareal.getStringAddress(m_szLocalIp); + } + + // and setup the READ notifier... + m_pSn = new QSocketNotifier(m_sock,QSocketNotifier::Read); + QObject::connect(m_pSn,SIGNAL(activated(int)),this,SLOT(incomingConnection(int))); + m_pSn->setEnabled(true); + + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_LISTENING; + + c->returnValue()->setBoolean(true); + return true; +} + +void KviKvsObject_socket::incomingConnection(int) +{ +#ifdef COMPILE_IPV6_SUPPORT + struct sockaddr_in6 hostSockAddr6; +#endif + struct sockaddr_in hostSockAddr; + + int size = sizeof(hostSockAddr); + struct sockaddr * addr = (struct sockaddr *)&hostSockAddr; + +#ifdef COMPILE_IPV6_SUPPORT + if(m_bIpV6) + { + addr = (struct sockaddr *)&hostSockAddr6; + size = sizeof(hostSockAddr6); + } +#endif + + // Incoming connection + m_secondarySock = kvi_socket_accept(m_sock,addr,&size); + if(m_secondarySock != KVI_INVALID_SOCKET) + { + // Connected +#ifdef COMPILE_IPV6_SUPPORT + if(m_bIpV6) + { + m_uSecondaryPort = ntohs(((struct sockaddr_in6 *)addr)->sin6_port); + if(!kvi_binaryIpToStringIp_V6(((struct sockaddr_in6 *)addr)->sin6_addr,m_szSecondaryIp)) + m_szSecondaryIp = __tr("unknown"); + } else { +#endif + m_uSecondaryPort = ntohs(((struct sockaddr_in *)addr)->sin_port); + if(!kvi_binaryIpToStringIp(((struct sockaddr_in *)addr)->sin_addr,m_szSecondaryIp)) + m_szSecondaryIp = __tr("unknown"); +#ifdef COMPILE_IPV6_SUPPORT + } +#endif + KviKvsVariantList *params=0; + callFunction(this,"incomingConnectionEvent",params); + if(m_secondarySock != KVI_INVALID_SOCKET) + { + kvi_socket_close(m_secondarySock); + m_secondarySock = KVI_INVALID_SOCKET; + m_uSecondaryPort = 0; + m_szSecondaryIp=""; + } + + } // else..huh ?... wait for the next notifier call +} + +void KviKvsObject_socket::acceptConnection(kvi_socket_t s,kvi_u32_t uPort,const char * szIp) +{ + reset(); + m_sock = s; + m_uRemotePort = uPort; + m_szRemoteIp = szIp; +#ifdef COMPILE_IPV6_SUPPORT + KviSockaddr sareal(0,m_bIpV6,m_bUdp); +#else + KviSockaddr sareal(0,false,m_bUdp); +#endif + + int size = (int)sareal.addressLength(); + + if(kvi_socket_getsockname(m_sock,sareal.socketAddress(),&size)) + { + m_uLocalPort = sareal.port(); + sareal.getStringAddress(m_szLocalIp); + } + + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_CONNECTED; + + m_pSn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); + QObject::connect(m_pSn,SIGNAL(activated(int)),this,SLOT(readNotifierFired(int))); + m_pSn->setEnabled(true); +} + +void KviKvsObject_socket::delayedConnect() +{ + if(m_pDelayTimer)delete m_pDelayTimer; + m_pDelayTimer = new QTimer(); + connect(m_pDelayTimer,SIGNAL(timeout()),this,SLOT(doConnect())); + m_pDelayTimer->start(0,true); +} + +void KviKvsObject_socket::doConnect() +{ + debug ("doConnect function"); + if(m_pDelayTimer)delete m_pDelayTimer; + m_pDelayTimer = 0; + + + KviSockaddr sa(m_szRemoteIp,m_uRemotePort,!kvi_isValidStringIp(m_szRemoteIp),m_bUdp); + + if(!sa.socketAddress()) + { + unsigned int uOldConnectionId = m_uConnectionId; + QString ipAddressError=__tr2qs("Invalid ip address "); + + ipAddressError.append(m_szRemoteIp); + + KviKvsVariantList params; + QString tmp; + KviQString::sprintf(tmp,__tr2qs("Invalid ip address (%Q)"),&m_szRemoteIp); + params.append(new KviKvsVariant(tmp)); + callFunction(this,"connectFailedEvent",¶ms); + /* callEventFunction("connectFailedEvent",0,new KviParameterList( + new KviStr(KviStr::Format,__tr("Invalid ip address (%s)"),m_szRemoteIp.ptr()))); + */ if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + return; + } +debug ("Socket created"); + + // create the socket +#ifdef COMPILE_IPV6_SUPPORT + m_bIpV6 = sa.isIpV6(); + m_sock = kvi_socket_create(sa.isIpV6() ? KVI_SOCKET_PF_INET6 : KVI_SOCKET_PF_INET,m_bUdp ? KVI_SOCKET_TYPE_DGRAM : KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP); +#else + m_bIpV6 = false; + m_sock = kvi_socket_create(KVI_SOCKET_PF_INET,m_bUdp ? KVI_SOCKET_TYPE_DGRAM : KVI_SOCKET_TYPE_STREAM,KVI_SOCKET_PROTO_TCP); +#endif + + if(m_sock == KVI_INVALID_SOCKET) + { + unsigned int uOldConnectionId = m_uConnectionId; + callFunction(this,"connectFailedEvent",new KviKvsVariantList( + new KviKvsVariant(__tr2qs("Failed to create the socket")))); + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + return; + } + debug ("Valid socket"); + + if(!kvi_socket_setNonBlocking(m_sock)) + { + unsigned int uOldConnectionId = m_uConnectionId; + + callFunction(this,"connectFailedEvent",new KviKvsVariantList( + new KviKvsVariant(__tr2qs("Failed to setup a nonblocking socket")))); + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + return; + } + + if(!kvi_socket_connect(m_sock,sa.socketAddress(),((int)(sa.addressLength())))) + { + int err = kvi_socket_error(); + if(!kvi_socket_recoverableConnectError(err)) + { + // Ops... + int sockError=err; + if(sockError==0) + { + // Zero error ?...let's look closer + int iSize=sizeof(int); + if(!kvi_socket_getsockopt(m_sock,SOL_SOCKET,SO_ERROR, + (void *)&sockError,&iSize))sockError=0; + } + unsigned int uOldConnectionId = m_uConnectionId; + QString callBackError=__tr2qs("Connect failure: "); + + callBackError.append((KviError::getDescription(KviError::translateSystemError(sockError)).utf8().data())); + callFunction(this,"connectFailedEvent",new KviKvsVariantList( + new KviKvsVariant(callBackError))); + +/* callEventFunction("connectFailedEvent",0,new KviParameterList( + new KviStr(KviStr::Format,__tr("Connect failure: %s"),KviError::getDescription(KviError::translateSystemError(sockError)).utf8().data()))); +*/ if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + return; + } + } + debug ("Socket connected"); + m_pDelayTimer = new QTimer(); + connect(m_pDelayTimer,SIGNAL(timeout()),this,SLOT(connectTimeout())); + m_pDelayTimer->start(m_uConnectTimeout,true); + + m_pSn = new QSocketNotifier((int)m_sock,QSocketNotifier::Write); + QObject::connect(m_pSn,SIGNAL(activated(int)),this,SLOT(writeNotifierFired(int))); + m_pSn->setEnabled(true); +} + +void KviKvsObject_socket::connectTimeout() +{ + unsigned int uOldConnectionId = m_uConnectionId; + + callFunction(this,"connectFailedEvent",new KviKvsVariantList( + new KviKvsVariant(__tr2qs("Connect attempt timed out")))); + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! +} + +void KviKvsObject_socket::delayedLookupRemoteIp() +{ + if(m_pDelayTimer)delete m_pDelayTimer; + m_pDelayTimer = new QTimer(); + connect(m_pDelayTimer,SIGNAL(timeout()),this,SLOT(lookupRemoteIp())); + m_pDelayTimer->start(0,true); +} + +void KviKvsObject_socket::lookupRemoteIp() +{ + debug ("Resolve dns"); + if(m_pDelayTimer)delete m_pDelayTimer; + m_pDelayTimer = 0; + if(m_pDns)delete m_pDns; + m_pDns = new KviDns(); + connect(m_pDns,SIGNAL(lookupDone(KviDns *)),this,SLOT(lookupDone(KviDns *))); + if(!m_pDns->lookup(m_szRemoteIp,KviDns::Any)) + { + unsigned int uOldConnectionId = m_uConnectionId; + + callFunction(this,"connectFailedEvent",new KviKvsVariantList( + new KviKvsVariant(__tr2qs("Can't start the DNS thread")))); + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + } +} + +void KviKvsObject_socket::lookupDone(KviDns *pDns) +{ + + if(pDns->state() != KviDns::Success) + { + unsigned int uOldConnectionId = m_uConnectionId; + + callFunction(this,"connectFailedEvent",new KviKvsVariantList( + new KviKvsVariant(KviError::getDescription(pDns->error())))); + + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + return; + } + m_szRemoteIp = pDns->firstIpAddress(); + debug ("Dns resolved in %s",m_szRemoteIp.latin1()); + + delete m_pDns; + m_pDns = 0; + doConnect(); +} + +void KviKvsObject_socket::writeNotifierFired(int) +{ + debug ("Here in the writeNotifierFired"); + if(m_pSn) + { + delete m_pSn; + m_pSn = 0; + } + if(m_pDelayTimer) + { + delete m_pDelayTimer; + m_pDelayTimer = 0; + } + + // Check for errors... + int sockError; + int iSize=sizeof(int); + if(!kvi_socket_getsockopt(m_sock,SOL_SOCKET,SO_ERROR,(void *)&sockError,&iSize))sockError = -1; + //sockError = 0; + if(sockError != 0) + { + //debug("Failed here %d",sockError); + //failed + if(sockError > 0)sockError = KviError::translateSystemError(sockError); + else sockError = KviError_unknownError; //Error 0 ? + unsigned int uOldConnectionId = m_uConnectionId; + callFunction(this,"connectFailedEvent",new KviKvsVariantList( + new KviKvsVariant(KviError::getDescription(sockError)))); + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + } else { + // Succesfully connected + // create the correct read notifier now... + m_pSn = new QSocketNotifier((int)m_sock,QSocketNotifier::Read); + QObject::connect(m_pSn,SIGNAL(activated(int)),this,SLOT(readNotifierFired(int))); + m_pSn->setEnabled(true); + +#ifdef COMPILE_IPV6_SUPPORT + KviSockaddr sareal(0,m_bIpV6,m_bUdp); +#else + KviSockaddr sareal(0,false,m_bUdp); +#endif + int size = (int)sareal.addressLength(); + if(kvi_socket_getsockname(m_sock,sareal.socketAddress(),&size)) + { + m_uLocalPort = sareal.port(); + sareal.getStringAddress(m_szLocalIp); + } + unsigned int uOldConnectionId = m_uConnectionId; + KviKvsVariantList *params=0; + callFunction(this,"connectEvent",params); + if(m_uConnectionId == uOldConnectionId) + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_CONNECTED; + // else the connection has been already changed! + } +} + +void KviKvsObject_socket::readNotifierFired(int) +{ + debug ("here in the readNotifierFired"); + //read data + if((m_uInBufferLen - m_uInDataLen) < KVI_READ_CHUNK) + { + m_uInBufferLen += KVI_IN_BUFFER_ALLOC_CHUNK; + m_pInBuffer = (char *)kvi_realloc(m_pInBuffer,m_uInBufferLen); + } + + int readLength = kvi_socket_recv(m_sock,m_pInBuffer + m_uInDataLen,KVI_READ_CHUNK); + + if(readLength <= 0) + { + if(readLength==0) + { + unsigned int uOldConnectionId = m_uConnectionId; + KviKvsVariantList *params=0; + callFunction(this,"disconnectEvent",params); + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + return; + } else { + //check for transmission errors + int err = kvi_socket_error(); +#ifdef COMPILE_ON_WINDOWS + if((err != EAGAIN) && (err != EINTR) && (err != WSAEWOULDBLOCK)) +#else + if((err != EAGAIN) && (err != EINTR)) +#endif + { + unsigned int uOldConnectionId = m_uConnectionId; + if(err > 0) + + { + // QString error=KviError::translateSystemError(err); + callFunction(this,"disconnectEvent",new KviKvsVariantList( + new KviKvsVariant((kvs_int_t)KviError::translateSystemError(err)))); + } else { + callFunction(this,"disconnectEvent",new KviKvsVariantList( + new KviKvsVariant(KviError::getDescription(KviError_remoteEndClosedConnection)))); + + } + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + return; + } //else transient error...wait again... + } + return; // can do nothing + } + // readLength > 0 + m_uInDataLen += readLength; + + //KviStr * s = new KviStr(); + QString s; + s.setNum(m_uInDataLen); + + + unsigned int uOldConnectionId = m_uConnectionId; + callFunction(this,"dataAvailableEvent",new KviKvsVariantList(new KviKvsVariant(s))); + if(m_uConnectionId == uOldConnectionId) + { + if(m_uInDataLen > (4096 * 1024)) // too much data in buffer (not reading) + { + callFunction(this,"disconnectEvent",new KviKvsVariantList( + new KviKvsVariant(__tr2qs("Too much unprocessed incoming data (you've left this socket unmanaged ?)")))); + reset(); + } + } +} + +void KviKvsObject_socket::eatInData(unsigned int uLen) +{ + if(uLen > m_uInDataLen)uLen = m_uInDataLen; + + m_uInDataLen -= uLen; + + if(m_uInDataLen > 0) + { + kvi_memmove(m_pInBuffer,m_pInBuffer + uLen,m_uInDataLen); + } + + unsigned int uSpace = m_uInBufferLen - m_uInDataLen; + + if(uSpace > KVI_IN_BUFFER_ALLOC_CHUNK) + { + m_uInBufferLen -= KVI_IN_BUFFER_ALLOC_CHUNK; + m_pInBuffer = (char *)kvi_realloc(m_pInBuffer,m_uInBufferLen); + } +} + +void KviKvsObject_socket::delayedFlush(unsigned int uTimeout) +{ + if(m_pFlushTimer->isActive())m_pFlushTimer->stop(); + m_pFlushTimer->start(uTimeout); +} + +void KviKvsObject_socket::tryFlush() +{ + if(m_pFlushTimer->isActive())m_pFlushTimer->stop(); + + if(m_pOutBuffer->size() == 0) + { + return; + } + + int result = kvi_socket_send(m_sock,m_pOutBuffer->data(),m_pOutBuffer->size()); + + if(result >= 0) + { + if(result == m_pOutBuffer->size()) + { + m_pOutBuffer->clear(); + } else { + if(result > 0)m_pOutBuffer->remove(result); + delayedFlush(500); + } + } else { + // Oops...error ? + int err = kvi_socket_error(); +#ifdef COMPILE_ON_WINDOWS + if((err == EAGAIN) || (err == EINTR) || (err = WSAEWOULDBLOCK)) +#else + if((err == EAGAIN)||(err == EINTR)) +#endif + { + // Transient error...partial send as before... + // Async continue... + delayedFlush(500); + return; + } else { + // Disconnected... :( + unsigned int uOldConnectionId = m_uConnectionId; + callFunction(this,"disconnectEvent",0,new KviKvsVariantList( + new KviKvsVariant(KviError::getDescription(KviError::translateSystemError(err))))); + if(m_uConnectionId == uOldConnectionId)reset(); + // else it has already been called! + return; + } + } +} +void KviKvsObject_socket::reset() +{ + m_uConnectionId++; // this is the only place where this is incremented! + if(m_pDelayTimer) + { + delete m_pDelayTimer; + m_pDelayTimer = 0; + } + if(m_pDns) + { + delete m_pDns; + m_pDns = 0; + } + if(m_pSn) + { + delete m_pSn; + m_pSn = 0; + } + if(m_sock != KVI_INVALID_SOCKET) + { + kvi_socket_close(m_sock); + m_sock = KVI_INVALID_SOCKET; + } + if(m_pInBuffer) + { + kvi_free(m_pInBuffer); + m_pInBuffer = 0; + } + if(m_secondarySock) + { + kvi_socket_close(m_secondarySock); + m_secondarySock = KVI_INVALID_SOCKET; + } + m_uSecondaryPort = 0; + m_szSecondaryIp=""; + delete m_pOutBuffer; + if(m_pFlushTimer->isActive())m_pFlushTimer->stop(); + m_pOutBuffer = new KviDataBuffer(); + m_uInBufferLen = 0; + m_uInDataLen = 0; + m_iStatus = KVI_SCRIPT_SOCKET_STATUS_DISCONNECTED; + m_uRemotePort = 0; + m_szRemoteIp=""; + m_uLocalPort = 0; + m_szLocalIp=""; + m_bIpV6 = false; +} +unsigned int KviKvsObject_socket::readGetLength(KviKvsObjectFunctionCall *c) +{ + kvs_uint_t uLen; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("length",KVS_PT_UNSIGNEDINTEGER,KVS_PF_OPTIONAL,uLen) + KVSO_PARAMETERS_END(c) + if (uLen>m_uInDataLen || !uLen) return m_uInDataLen; + else return uLen; + } + +bool KviKvsObject_socket::functionRead(KviKvsObjectFunctionCall *c) +{ + unsigned int uLen = readGetLength(c); + + if(uLen > 0) + { + // convert NULLS to char 255 + for(unsigned int i = 0;i < uLen;i++) + { + if(!m_pInBuffer[i])m_pInBuffer[i] = (char)(255); + } + QString tmpBuffer = QString::fromUtf8(m_pInBuffer,uLen); + c->returnValue()->setString(tmpBuffer); + + eatInData(uLen); + } + return true; +} + +bool KviKvsObject_socket::functionReadHex(KviKvsObjectFunctionCall *c) +{ + //??? funzioner� + unsigned int uLen = readGetLength(c); + bool bOk; + if(uLen > 0) + { + QString szTmp; + szTmp =m_pInBuffer; + szTmp.toInt(&bOk,16); + c->returnValue()->setString(szTmp); + eatInData(uLen); + } + return true; +} + +bool KviKvsObject_socket::functionWrite(KviKvsObjectFunctionCall *c) +{ + QString szData; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("szData",KVS_PT_STRING,0,szData) + KVSO_PARAMETERS_END(c) + +KviQCString szData8 = szData.utf8(); + if(szData8.length() > 0) + { + m_pOutBuffer->append((const unsigned char*)szData8.data(),szData8.length()); + delayedFlush(0); + } + return true; +} + + + +//-------------- + +#include "m_class_socket.moc" diff --git a/src/modules/objects/class_widget.cpp b/src/modules/objects/class_widget.cpp index 3d9cb936a..db3da521f 100644 --- a/src/modules/objects/class_widget.cpp +++ b/src/modules/objects/class_widget.cpp @@ -1,1745 +1,1745 @@ -//=============================================================================
-//
-// File : class_widget.cpp
-// Creation date : Mon Sep 11 16:35:32 CET 2000 by Krzysztof Godlewski
-//
-// This file is part of the KVirc irc client distribution
-// Copyright (C) 1999-2005 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-//
-//=============================================================================
-
-#include "kvi_malloc.h"
-#include "kvi_debug.h"
-
-#include "kvi_error.h"
-#include "kvi_locale.h"
-#include "kvi_iconmanager.h"
-#include "kvi_window.h"
-#include "kvi_out.h"
-#include "kvi_mirccntrl.h"
-#include "kvi_app.h"
-#include "kvi_string.h"
-#include <qcursor.h>
-#include <qiconset.h>
-#include <qcolor.h>
-#include <qlayout.h>
-#include <qbitmap.h>
-#include <qmetaobject.h>
-#include "class_widget.h"
-#include "class_pixmap.h"
-
-#ifdef COMPILE_USE_QT4
- #include <QKeyEvent>
- #include <QDesktopWidget>
-#else
- #include <qwidgetlist.h>
-#endif
-
-#include <qwidget.h>
-#include <qtooltip.h>
-#include <qfont.h>
-#include <qvariant.h>
-
-// FIX ME: WFLAGS
-const char * const widgettypes_tbl[] = {
- "TopLevel",
- "Dialog",
- "Popup",
- "Desktop",
- "Customize",
- "Title",
- "StaysOnTop",
- "SysMenu",
- "Minimize",
- "Maximize",
- "NoAutoErase"
- };
-#ifdef COMPILE_USE_QT4
-const Qt::WidgetAttribute widgetattributes_cod[]= {
- Qt::WA_OpaquePaintEvent,
- Qt::WA_NoSystemBackground,
- Qt::WA_PaintOnScreen,
- Qt::WA_NoMousePropagation,
-};
-
-const char * const widgetattributes_tbl[] = {
- "opaquePaintEvent",
- "noSystemBackground",
- "paintOnScreen",
- "noMousePropagation",
-};
-#define widgetattributes_num (sizeof(widgetattributes_tbl) / sizeof(widgetattributes_tbl[0]))
-
-
-const Qt::WindowType widgettypes_cod[] = {
-#else
-const int widgettypes_cod[] = {
-#endif
- Qt::WType_TopLevel,
- Qt::WType_Dialog,
- Qt::WType_Popup,
- Qt::WType_Desktop,
- Qt::WStyle_Customize,
- Qt::WStyle_Title,
- Qt::WStyle_StaysOnTop,
- Qt::WStyle_SysMenu,
- Qt::WStyle_Minimize,
- Qt::WStyle_Maximize,
- Qt::WNoAutoErase
-};
-
-
-#ifdef COMPILE_USE_QT4
-
- #define QT_WIDGET_TABFOCUS Qt::TabFocus
- #define QT_WIDGET_CLICKFOCUS Qt::ClickFocus
- #define QT_WIDGET_STRONGFOCUS Qt::StrongFocus
- #define QT_WIDGET_NOFOCUS Qt::NoFocus
-
-#else
- #define QT_WIDGET_TABFOCUS QWidget::TabFocus
- #define QT_WIDGET_CLICKFOCUS QWidget::ClickFocus
- #define QT_WIDGET_STRONGFOCUS QWidget::StrongFocus
- #define QT_WIDGET_NOFOCUS QWidget::NoFocus
-#endif
-
-
-#define widgettypes_num (sizeof(widgettypes_tbl) / sizeof(widgettypes_tbl[0]))
-
-/*
- @doc: widget
- @keyterms:
- widget object class
- @title:
- widget class
- @type:
- class
- @short:
- Base class for all widgets
- @inherits:
- [class]object[/class]
- @description:
- This object class is the rappresentation of a widget.
- All the other widget-type classes inherit from this one.
- @functions:
- !fn: $show()
- Shows this widget and the children.
- See also [classfnc]$hide[/classfnc]() and [classfnc]$isVisible[/classfnc].
- !fn: $hide()
- Hides this widget (and conseguently all the children).
- See also [classfnc]$show[/classfnc]() and [classfnc]$isVisible[/classfnc].
- !fn: $repaint(<bool erase>)
- Repaints the widget directly by calling [classfnc]$paintEvent[/classfnc]() immediately.[br]
- If erase is TRUE, erases the widget before the $paintEvent() call.
- !fn: $x()
- Returns the x coordinate of the upper-left corner
- of this widget relative to the parent widget,
- or to the desktop if this widget is a toplevel one.
- !fn: $y()
- Returns the y coordinate of the uspper-left corner
- of this widget relative to the parent widget,
- or to the desktop if this widget is a toplevel one.
- !fn: $width()
- Returns the width of this widget in pixels.
- !fn: $height()
- Returns the height of this widget in pixels.
- !fn: $geometry()
- Returns the widget geometry in this form:[br]
- x, y, width, height.
- !fn: $setGeometry(<x_or_array>,[<y>,<width>,<heigth>])
- Sets the geometry of this widget. <x> and <y> are relative
- to the parent widget or to the desktop (if this widget is
- a toplevel one). All the parameters are in pixels.
- !fn: $setMinimumWidth(<value>)
- Sets the minimum width of this widget to <value>.
- The user will not be able to resize the widget to a smaller
- value. This value is also used by the [class:layout]layout class[/class].
- !fn: $setMinimumHeight(<value>)
- Sets the minimum height of this widget to <value>.
- The user will not be able to resize the widget to a smaller
- value. This value is also used by the [class:layout]layout class[/class].
- !fn: $setMaximumWidth(<value>)
- Sets the maximum width of this widget to <value>.
- The user will not be able to resize the widget to a bigger
- value. This value is also used by the [class:layout]layout class[/class].
- !fn: $setMaximumHeight(<value>)
- Sets the maximum height of this widget to <value>.
- The user will not be able to resize the widget to a bigger
- value. This value is also used by the [class:layout]layout class[/class].
- !fn: $move(<x_or_array>[,<y>])
- Moves this widget to the coordinate <x> and <y> relative to its
- parent widget (or the desktop if this widget is a toplevel one).
- This is equivalent to [classfnc]$setGeometry[/classfnc](<x>,<y>,
- [classfnc]$width[/classfnc](),[classfnc]$height[/classfnc]()).
- !fn: $resize(<w_or_array>,[height])
- Changes the widget's width to <width> and height to <height>.
- See also [classfnc]$setGeometry[/classfnc]().
- !fn: $isEnabled()
- Returns '1' if the widget is enabled , '0' otherwise.
- See also [classfnc:widget]$setEnabled[/classfnc]().
- !fn: $setEnabled(<bool>)
- Sets the widget state to enabled or disabled if <bool> is 1 or 0 respectively.
- A disabled widget does not receive keyboard nor mouse input.
- !fn: $setCaption(<text>)
- Sets the caption of this widget to <text>.
- This is meaningful for toplevel widgets only.
- !fn: $setToolTip(<tooltip_text>)
- Set the tooltip of this widget; the text can contain HTML formatting.
- !fn: $window.caption()
- Returns the caption text of this widget.
- !fn: $isTopLevel()
- Returns '1' if this widget is a toplevel (parentless) one,
- '0' otherwise.
- !fn: $isVisible()
- Returns '1' if this widget is currently visible (read: is managed
- by the window manager and displayed by the X server; the widget
- may be hidden behind other widgets). If the widget is not visible
- this function returns '0'.
- See also [classfnc]$show[/classfnc]() and [classfnc]$hide[/classfnc]().
- !fn: $raise()
- Moves this widget to the top of the stack of the widgets relative
- to its parent. See also [classfnc]$lower[/classfnc].
- !fn: $lower()
- Moves this widget to the bottom of the stack of the widgets relative
- to its parent. See also [classfnc]$raise[/classfnc]
- !fn: $hasFocus()
- Returns '1' if this widget has the keyboard focus.
- See also [classfnc]$setFocus[/classfnc].
- !fn: $setFocus()
- Sets this widget to be the one that receives keyboard events.
- See also [classfnc]$hasFocus[/classfnc]
- !fn: $parentWidget()
- Returns the object id of the parent widget, or '0' if this
- widget is a toplevel one.
- !fn: $backgroundColor()
- Returns the background color of this widget in hexadecimal
- html-like format. For example , for a black bacground you will get
- the string "000000" , for a red one , "FF0000", for a white one
- "FFFFFF". See also [classfnc]$setBackgroundColor[/classfnc]()
- !fn: $setBackgroundColor(<rgb(hex string)_array(red:integer,green:integer,blue_integer)_or_red>,[geen:integer],[blue:integer])
- Sets the background color of this widget to <rgb_value>:valid values are:
- - hex string: must be a string with 6 hexadecimal digits (like the ones used to
- specify colors in html pages). The first two digits specify
- the RED component, the third and fourth digit specify the GREEN component
- and the last two specify the BLUE component.
- For example "FFFF00" means full red, full green and no blue that gives
- a yellow color, "808000" designates a brown color (dark yellow),
- "A000A0" is a kind of violet.
- - array(red:integer,green:integer,blue:integer)
- - red:integer,green:integer,blue:integer.
- See also [classfnc]$foregroundColor[/classfnc].
- !fn: $setForegroundColor(<rgb(hex string)_array(red:integer,green:integer,blue_integer)_or_red>,[geen:integer],[blue:integer])
- Sets the foreground color of this widget to <rgb_value>:valid values are:
- - hex string: must be a string with 6 hexadecimal digits (like the ones used to
- specify colors in html pages). The first two digits specify
- the RED component, the third and fourth digit specify the GREEN component
- and the last two specify the BLUE component.
- For example "FFFF00" means full red, full green and no blue that gives
- a yellow color, "808000" designates a brown color (dark yellow),
- "A000A0" is a kind of violet.
- - array(red:integer,green:integer,blue:integer)
- - red:integer,green:integer,blue:integer.
- See also [classfnc]$foregroundColor[/classfnc].
- !fn: $foregroundColor()
- Returns the foreground color of this widget in hexadecimal
- html-like format.
- See also [classfnc]$setForegroundColor[/classfnc].
- !fn: $setMouseTracking(<bool>)
- Enables or disables the mouse tracking if <bool> is '1' or '0' respectively.
- When mouse tracking is enabled you will receive mouse move events
- even if no button is pressed, otherwise you will receive it only
- when a mouse button is being pressed (so after a mousePressEvent).
- !fn: $mousePressEvent(<button>,<x>,<y>)
- This function is called when a mouse button is pressed while
- the cursor is in this widget. <button> is 0 if the pressed button
- is the left one, 1 if the button is the right one and 2 if it is the middle one.
- The <x> and <y> coordinates are relative to this widget upper-left corner
- and are expressed in pixels.
- If you call "[cmd]setreturn[/cmd] 1" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $mouseReleaseEvent(<button>,<x>,<y>)
- This function is called when a mouse button is released while
- the cursor is in this widget. <button> is 0 if the released button
- is the left one, 1 if the button is the right one and 2 if it is the middle one.
- The <x> and <y> coordinates are relative to this widget upper-left corner
- and are expressed in pixels.
- If you call "[cmd]setreturn[/cmd] 1" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $mouseDoubleClickEvent(<button>,<x>,<y>)
- This function is called when a mouse button is double clicked while
- the cursor is in this widget. <button> is 0 if the double clicked button
- is the left one, 1 if the button is the right one and 2 if it is the middle one.
- The <x> and <y> coordinates are relative to this widget upper-left corner
- and are expressed in pixels.
- If you call "[cmd]setreturn[/cmd] 1" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $mouseMoveEvent(<button>,<x>,<y>)
- This function is called when the mouse cursor moves inside this widget.
- <button> is 0 if the pressed button
- is the left one, 1 if the button is the right one and 2 if it is the middle one.
- The special value of -1 indicates that no button is being pressed.
- The <x> and <y> coordinates are relative to this widget upper-left corner
- and are expressed in pixels.
- Normally you will receive this event only if a mouse button is being pressed
- while moving. If you want to receive it also when the mouse buttons are not
- pressed, call [classfnc]$setMouseTracking[/classfnc]().
- If you call "[cmd]return[/cmd]$true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $focusInEvent()
- This function is called when this widget gains keyboard focus.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $focusOutEvent()
- This function is called when this widget looses keyboard focus.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $mouseLeaveEvent()
- This function is called when the mouse leaves this widget.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $mouseEnterEvent()
- This function is called when the mouse enters this widget.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $showEvent()
- This function is called when this widget is being shown.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $hideEvent()
- This function is called when this widget is being hidden.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $closeEvent()
- This function is called when this widget is going to be closed.
- If you call "[cmd]return[/cmd] $true" you will ignore the close event.
- The default implementation does nothing.
- !fn: $resizeEvent()
- This function is called immediately after this widget has been resized.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: $moveEvent()
- This function is called immediately after this widget has been moved.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event. The default implementation does nothing.
- !fn: <tip:string> $maybeTipEvent(<x_tip_pos:integer>,<y_tip_pos:integer>)[QT4 only]
- This event handler is called when a eventualy tip is going to be show.
- You can be reimplement this event and set a dynamic tool tip by using "[cmd]return[/cmd] <tooltip_string>".
- If a tooltip has setted with [classfnc]$setTooltip[/classfnc] the dynamic tooltip will be ignored.
- The default implementation does nothing.
- !fn: $paintEvent()
- This event handler can be reimplemented to repaint all or part of the widget.
- It's needed by the Painter class.
- It's very useful for drawing flicker free animations or low level special graphic effects.
- If you call "[cmd]return[/cmd] $true" you will stop the internal processing
- of this event.
- The default implementation does nothing.
- !fn: $setIcon(<image_id>)
- Sets the icon for this widget. This is meaningful only for toplevel widgets.
- See the [doc:image_id]image identifier[/doc] documentation for the explaination
- of the <image_id> parameter.
- !fn: $setBackgroundImage(<image_id>)
- Sets the background image for this widget.
- See the [doc:image_id]image identifier[/doc] documentation for the explaination
- of the <image_id> parameter.
- For some kind of widgets, setting a background pixmap may have no effect or
- have strange results. Experiment with it.
- To unset the background image call [classfnc]$setBackgroundColor[/classfnc]
- !fn: $setFont(<size>,<family>,<style>)[br]
- Set the font's size, family and stile, valid flag for style are:[br]
- [pre]
- italic [br]
- bold [br]
- underline [br]
- overline [br]
- strikeout [br]
- fixedpitch [br]
- [/pre]
- !fn: $setWFlags(<flag1>, <flag2>, ...)
- This function sets widget flags, given as parameters.
- Valid flags are:
- [pre]
- TopLevel - indicates that this widget is a top-level widget[br]
- Dialog - indicates that this widget is a top-level window that should be decorated as a dialog[br]
- Desktop - indicates that this widget is the desktop[br]
- Popup - indicates that this widget is a popup top-level window[br]
- NoAutoErase - indicates that this widget paints all its pixels. Updating, resizing, scrolling and focus changes should therefore not erase the widget.
- Customize - let's the user to customize the style of the widget.[br]
- [br]
- Valid parameter for a customized widget are:[br]
- Title - gives the window a title bar[br]
- StaysOnTop - window stays on top [br]
- SysMenu - add a windows system menu[br]
- Minimize - add a minimize button for the sysmenu style[br]
- Maximize - add a maximixe button for the sysmenu style[br]
- [/pre]
- !fn: $centerToScreen()
- Centers the window on the screen (useful only for toplevel widgets).[br]
- The best place to call this function is in $showEvent()
- !fn: $setFocusPolicy(<key focus>)
- Sets the way the widget accepts keyboard focus.[br]
- Valid parameters are:
- [pre]
- - TabFocus; (widget accepts keyboard focus by tabbing)[br]
- - ClickFocus; (widget accepts keyboard focus by clicking)[br]
- - StrongFocus; (widget accepts both tabbing/clicking)[br]
- - No Focus; (widget does not accept focus at all; this is the default value)[br]
- [/pre]
- !fn: $keyPressEvent(<key>)
- If widget accepts keyboard focus (see [classfnc]$setFocusPolicy[/classfnc] ) this function handles for keys;
- In its argument the key pressed.[br]
- Special keys are:
- [pre]
- - Return [br]
- - Enter [br]
- - Down (cursor arrow down) [br]
- - Up (cursor arrow up) [br]
- - Left (cursor arrow left) [br]
- - Right (cursor arrow right) [br]
- - Shift [br]
- - Ctrl [br]
- - Alt [br]
- - CapsLock [br]
- - Backspace [br]
- - Del [br]
- - Esc [br]
- - 0 [br]
- - 1 [br]
- - 2 [br]
- - 3 [br]
- - 4 [br]
- - 5 [br]
- - 6 [br]
- - 7 [br]
- - 8 [br]
- - 9 [br]
- - + [br]
- - - [br]
- - * [br]
- - / [br]
- - ( [br]
- - ) [br]
- - = [br]
- - . [br]
- - ^ [br]
-
- [/pre]
- !fn: $mapFromGlobal(<x>,<y>)
- Translates the global screen coordinate pos to widget coordinates.
- !fn: $mapToGlobal(<x>,<y>)
- Translates widget coordinates into the global screen coordinate pos.
- !fn: integer $globalCursorX()
- Return the x coordinate of mouse pointer global position.
- !fn: integer $globalCursorY()
- Return the y coordinate of the mo>use pointer global position.
- @examples:
- [example]
- %Widget = $new(widget)
- # This is the main container for other elements.
-
- %Widget->$setCaption("This is the widget title")
-
- %Widget->$setGeometry(100,200,170,290)
- # 100 and 200 are distance (pixel) from the left and the top of father widget (in this case the KVIrc window)
- # 300 and 400 are the weight and the height of the widget
-
- %Widget->%label = $new(label,%Widget)
- %Widget->%label->$setText("This is a text label")
- %Widget->%label->$setGeometry(10,10,150,20)
-
- %Widget->%lineedit = $new(lineedit,%Widget)
- %Widget->%lineedit->$setText("This is a lineedit")
- %Widget->%lineedit->$setGeometry(10,40,150,20)
-
- %Widget->%multilineedit = $new(multilineedit,%Widget)
- %Widget->%multilineedit->$setText("This is a multilineedit")
- %Widget->%multilineedit->$setGeometry(10,70,150,40)
-
- %Widget->%checkbox = $new(checkbox,%Widget)
- %Widget->%checkbox->$setText("This is a checkbox")
- %Widget->%checkbox->$setGeometry(10,120,150,20)
-
- %Widget->%combobox = $new(combobox,%Widget)
- %Widget->%combobox->$setGeometry(10,150,150,20)
- %Widget->%combobox->$insertItem("This is a combobox")
- %Widget->%combobox->$insertItem("This is a combobox's item")
-
- %Widget->%listbox = $new(listbox,%Widget)
- %Widget->%listbox->$setGeometry(10,180,150,40)
- %Widget->%listbox->$insertItem("This is another item")
- %Widget->%listbox->$insertItem("This is a listbox's item")
- %Widget->%listbox->$insertItem("This is a listbox")
-
- %Widget->%radiobutton = $new(radiobutton,%Widget)
- %Widget->%radiobutton->$setGeometry(10,230,150,20)
- %Widget->%radiobutton->$setText("This is a radiobutton")
-
- %Widget->%button = $new(button, %Widget)
- %Widget->%button->$setText("Close me")
- %Widget->%button->$setGeometry(10,260,150,20)
-
- %Widget->$show()
- # This shows the widget
-
- privateimpl(%Widget->%button, mousePressEvent) {
- delete %Widget
- # This closes the widget automatically
- }
- # privateimpl is triggered when user press the button.
- # To do that, widget must be a global variable.
- [/example]
-
-*/
-
-
-
-
-//
-// If you never call c->error() , c->warning() (your function never fails)
-// and never call a function that can call c->error() or c->warning()
-// you can avoid ENTER_STACK_FRAME and c->leaveStackFrame()
-// Just return true.
-// c->error() should be called only in really critical situations
-// (we have to define better "critical situation")
-// if possible , leave the things go after just a c->warning()
-//
-
- // widget() will be never 0 in THIS class
- // but in derived classes WILL be
- // ... now that I think about it , it
- // may happen that widget() will be zero here too:
- // If the Qt "physical" widget gets destroyed
- // by some external factor (for example when children
- // of a wrapper widget destroyed by KVIrc).
- //
- // as a convention:
- // if widget() can be 0 in a class
- // the user must have a function to check it
- // (sth as object::$hasObject() could do the trick)
- // obviously this will happen only in well defined cases
- // as in a qtwrapper not yet wrapped or failed to wrap (so
- // qtwrapper::$wrap() returned '0' for example)
- // or after the widget has been destroyed...
- // if widget() is 0 , the functions perform no actions
- // return no errors and results that have to be assumed
- // as invalid (this allows the minimum overhead: if widget()
-
-//=============================================================================================================
-
-
-
-KVSO_BEGIN_REGISTERCLASS(KviKvsObject_widget,"widget","object")
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"reparent",function_reparent)
- // apparence
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"show",function_show)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"hide",function_hide)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"repaint",function_repaint)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"isTopLevel",function_isTopLevel)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"isVisible",function_isVisible)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"raise",function_raise)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"lower",function_lower)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setEnabled",function_setEnabled)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"isEnabled",function_isEnabled)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMouseTracking",function_setMouseTracking)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setCaption",function_setCaption)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"caption",function_caption)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"hasFocus",function_hasFocus)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setFocus",function_setFocus)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setToolTip",function_setToolTip)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setWFlags",function_setWFlags)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setIcon",function_setIcon)
- // fonts
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"fontDescent",function_fontDescent)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"fontAscent",function_fontAscent)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"fontMetricsWidth",function_fontMetricsWidth)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"fontMetricsHeight",function_fontMetricsHeight)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setFont",function_setFont)
- // geometry
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"screenResolution",function_screenResolution)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"centerToScreen",function_centerToScreen)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"geometry",function_geometry)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setGeometry",function_setGeometry)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"mapToGlobal",function_mapToGlobal)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"mapFromGlobal",function_mapFromGlobal)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"y",function_y)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"x",function_x)
-
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"globalCursorX",function_globalCursorX)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"globalCursorY",function_globalCursorY)
-
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"width",function_width)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"height",function_height)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMinimumWidth",function_setMinimumWidth)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMinimumHeight",function_setMinimumHeight)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMaximumWidth",function_setMaximumWidth)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMaximumHeight",function_setMaximumHeight)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"move",function_move)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"sizeHint",function_sizeHint)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"resize",function_resize)
-
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setFocusPolicy",function_setFocusPolicy)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"addWidgetToWrappedLayout",function_addWidgetToWrappedLayout)
-
- // colors and image
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setForegroundColor",function_setPaletteForeground)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setBackgroundColor",function_setBackgroundColor)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setBackgroundImage",function_setBackgroundImage)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"backgroundColor",function_backgroundColor)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"foregroundColor",function_foregroundColor)
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMask",function_setMask)
-
- // QT4 only
-#ifdef COMPILE_USE_QT4
- KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setAttribute",function_setAttribute)
-#endif
-
- // events
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mousePressEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseReleaseEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseDoubleClickEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseMoveEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"focusInEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"focusOutEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseLeaveEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseEnterEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"showEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"hideEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"closeEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"resizeEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"moveEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"paintEvent")
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"keyPressEvent")
-#ifdef COMPILE_USE_QT4
- KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"maybeTipEvent")
-#endif
-
-
-KVSO_END_REGISTERCLASS(KviKvsObject_widget)
-
-
-KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_widget,KviKvsObject)
-KVSO_END_CONSTRUCTOR(KviKvsObject_widget)
-
-KVSO_BEGIN_DESTRUCTOR(KviKvsObject_widget)
- emit aboutToDie();
-KVSO_END_CONSTRUCTOR(KviKvsObject_widget)
-
-bool KviKvsObject_widget::init(KviKvsRunTimeContext * pContext,KviKvsVariantList * pParams)
-{
- setObject(new QWidget(parentScriptWidget(),getName()),true);
- return true;
-}
-
-bool KviKvsObject_widget::eventFilter(QObject *o,QEvent *e)
-{
- if(o == object())
- {
- bool ret=false;
- int aparam;
- bool brokenhandler=false;
- KviKvsVariant *retv=new KviKvsVariant(ret);
-
- switch(e->type())
- {
- #ifdef COMPILE_USE_QT4
- case QEvent::ToolTip:
- {
- QHelpEvent *helpEvent = static_cast<QHelpEvent *>(e);
- QPoint point=helpEvent->pos();
- QString szTooltip;
- KviKvsVariant *tipret=new KviKvsVariant(szTooltip);
- KviKvsVariantList params(new KviKvsVariant((kvs_int_t)point.x()),new KviKvsVariant((kvs_int_t)point.y()));
- callFunction(this,"maybeTipEvent",tipret,¶ms);
- tipret->asString(szTooltip);
- QToolTip::showText(helpEvent->globalPos(),szTooltip);
- break;
- }
- #endif
- case QEvent::Paint:
- {
- QRect rect=((QPaintEvent *)e)->rect();
- KviKvsVariantList params(new KviKvsVariant((kvs_int_t)rect.x()),new KviKvsVariant((kvs_int_t)rect.y()),new KviKvsVariant((kvs_int_t)rect.width()),new KviKvsVariant((kvs_int_t)rect.height()));
- callFunction(this,"paintEvent",retv,¶ms);
- break;
- }
-
- case QEvent::KeyPress:
- {
- QString tmp="";
- switch(((QKeyEvent *)e)->key())
- {
- case Qt::Key_Return:
- tmp="Return";
- break;
- case Qt::Key_Down:
- tmp="Down";
- break;
- case Qt::Key_Up:
- tmp="Up";
- break;
- case Qt::Key_Left:
- tmp="Left";
- break;
- case Qt::Key_Right:
- tmp="Right";
- break;
- case Qt::Key_Shift:
- tmp="Shift";
- break;
- case Qt::Key_Control:
- tmp="Ctrl";
- break;
- case Qt::Key_Alt:
- tmp="Alt";
- break;
- case Qt::Key_CapsLock:
- tmp="CapsLock";
- break;
- case Qt::Key_Backspace:
- tmp="Backspace";
- break;
- case Qt::Key_Delete:
- tmp="Del";
- break;
-
- case Qt::Key_Enter:
- tmp="Enter";
- break;
- case Qt::Key_Escape:
- tmp="Esc";
- break;
- case Qt::Key_0:
- tmp="0";
- case Qt::Key_1:
- tmp="1";
- break;
- case Qt::Key_2:
- tmp="2";
- break;
- case Qt::Key_3:
- tmp="3";
- break;
- case Qt::Key_4:
- tmp="4";
- break;
- case Qt::Key_5:
- tmp="5";
- break;
- case Qt::Key_6:
- tmp="6";
- break;
- case Qt::Key_7:
- tmp="7";
- break;
- case Qt::Key_8:
- tmp="8";
- break;
- case Qt::Key_9:
- tmp="9";
- break;
- case Qt::Key_Plus:
- tmp="+";
- break;
- case Qt::Key_Minus:
- tmp="-";
- break;
- case Qt::Key_Slash:
- tmp="/";
- break;
- case Qt::Key_Asterisk:
- tmp="*";
- break;
- case Qt::Key_Period:
- tmp=".";
- break;
- case Qt::Key_ParenLeft:
- tmp="(";
- break;
- case Qt::Key_ParenRight:
- tmp=")";
- break;
- case Qt::Key_Equal:
- tmp="=";
- break;
- case Qt::Key_AsciiCircum:
- tmp="^";
- break;
- default:
- if (!((QKeyEvent *)e)->text().isEmpty()) tmp = ((QKeyEvent *)e)->text();
- }
-
- KviKvsVariantList params(new KviKvsVariant(tmp));
- callFunction(this,"keyPressEvent",0,¶ms);
- }
- break;
- case QEvent::MouseButtonPress:
- if(((QMouseEvent *)e)->button() & Qt::LeftButton)aparam = 0;
- else {
- if(((QMouseEvent *)e)->button() & Qt::RightButton)aparam = 1;
- else aparam = 2;
- }
- if(!callFunction(this,"mousePressEvent",retv,new KviKvsVariantList(new KviKvsVariant((kvs_int_t)aparam),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().x()),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().y())
- ))) brokenhandler = true; // ignore results of a broken event handler
- break;
- case QEvent::MouseButtonRelease:
- if(((QMouseEvent *)e)->button() & Qt::LeftButton)aparam = 0;
- else {
- if(((QMouseEvent *)e)->button() & Qt::RightButton)aparam = 1;
- else aparam = 2;
- }
- if(!callFunction(this,"mouseReleaseEvent",retv,new KviKvsVariantList(new KviKvsVariant((kvs_int_t)aparam),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().x()),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().y())
- ))) brokenhandler = true; // ignore results of a broken event handler
- break;
- case QEvent::MouseButtonDblClick:
- if(( (QMouseEvent *)e)->button() & Qt::LeftButton)aparam = 0;
- else {
- if(((QMouseEvent *)e)->button() & Qt::RightButton)aparam = 1;
- else aparam = 2;
- }
- if(!callFunction(this,"mouseDoubleClickEvent",retv,new KviKvsVariantList(new KviKvsVariant((kvs_int_t)aparam),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().x()),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().y())
- ))) brokenhandler = true; // ignore results of a broken event handler
-
- break;
- case QEvent::MouseMove:
- if( (((QMouseEvent *)e)->state()) & Qt::LeftButton) aparam = 0;
- else
- {
- if(((QMouseEvent *)e)->state() & Qt::RightButton)aparam = 1;
- else
- {
- if(((QMouseEvent *)e)->state() & Qt::MidButton)aparam = 2;
- else aparam = -1;
- }
- }
- if(!callFunction(this,"mouseMoveEvent",retv,new KviKvsVariantList(new KviKvsVariant((kvs_int_t)aparam),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().x()),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().y())
- ))) brokenhandler = true; // ignore results of a broken event handler
- break;
- case QEvent::FocusIn:
- if(!callFunction(this,"focusInEvent",retv,0))brokenhandler = true;
- break;
- case QEvent::FocusOut:
- if(!callFunction(this,"focusOutEvent",retv,0))brokenhandler = true;
- break;
- case QEvent::Resize:
- if(!callFunction(this,"resizeEvent",retv,0))brokenhandler = true;
- break;
- case QEvent::Move:
- if(!callFunction(this,"moveEvent",retv,0))brokenhandler = true;
- break;
- case QEvent::Close:
- if(!callFunction(this,"closeEvent",retv,0))brokenhandler = true;
- break;
- case QEvent::Enter:
- if(!callFunction(this,"mouseEnterEvent",retv,0))brokenhandler = true;
- break;
- case QEvent::Leave:
- if(!callFunction(this,"mouseLeaveEvent",retv,0))brokenhandler = true;
- break;
- case QEvent::Show:
- if(!callFunction(this,"showEvent",retv,0))brokenhandler = true;
- break;
- case QEvent::Hide:
- if(!callFunction(this,"hideEvent",retv,0))ret =false;
- break;
- default:
- return KviKvsObject::eventFilter(o,e);
- break;
-
- }
- if (!brokenhandler) ret=retv->asBoolean();
- delete retv;
- return ret;
- /*
- if(ret.length() == 1)
- {
- if(KviQString::equalCI("1",ret))return true;
- }
- */
- }
-
- return KviKvsObject::eventFilter(o,e);
-}
-
-
-bool KviKvsObject_widget::function_show(KviKvsObjectFunctionCall *c)
-{
- if(!widget())return true; // should we warn here ?
- widget()->show();
- return true;
-}
-
-bool KviKvsObject_widget::function_setEnabled(KviKvsObjectFunctionCall *c)
-{
- bool bEnabled;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("bEnabled",KVS_PT_BOOL,0,bEnabled)
- KVSO_PARAMETERS_END(c)
- if(!widget())return true;
- widget()->setEnabled(bEnabled);
- return true;
-}
-bool KviKvsObject_widget::function_isEnabled(KviKvsObjectFunctionCall *c)
-{
- if(!widget()) return true;
- c->returnValue()->setBoolean(widget()->isEnabled());
- return true;
-}
-bool KviKvsObject_widget::function_fontDescent(KviKvsObjectFunctionCall * c)
-{
- if(!widget()) return true;
- QFontMetrics fm = widget()->fontMetrics();
- int d = fm.descent();
- c->returnValue()->setInteger(d);
- return true;
-}
-
-bool KviKvsObject_widget::function_fontAscent(KviKvsObjectFunctionCall * c)
-{
- if(!widget()) return true;
- QFontMetrics fm = widget()->fontMetrics();
- int d = fm.ascent();
- c->returnValue()->setInteger(d);
- return true;
-
-}
-
-bool KviKvsObject_widget::function_repaint(KviKvsObjectFunctionCall * c)
-{
- bool bEnabled;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("bEnabled",KVS_PT_BOOL,0,bEnabled)
- KVSO_PARAMETERS_END(c)
- if(!widget()) return true;
- widget()->repaint(bEnabled);
- return true;
-}
-
-bool KviKvsObject_widget::function_fontMetricsWidth(KviKvsObjectFunctionCall * c)
-{
- QString m_szStr;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("string",KVS_PT_STRING,0,m_szStr)
- KVSO_PARAMETERS_END(c)
- if(!widget()) return true;
-// int fm = widget()->fontMetrics().width(m_szStr);
- c->returnValue()->setInteger(widget()->fontMetrics().width(m_szStr));
- return true;
-}
-
-bool KviKvsObject_widget::function_fontMetricsHeight(KviKvsObjectFunctionCall * c)
-{
- if(!widget())return true;
- int fm = widget()->fontMetrics().height();
- c->returnValue()->setInteger(fm);
- return true;
-}
-bool KviKvsObject_widget::function_screenResolution(KviKvsObjectFunctionCall * c)
-{
- KviKvsArray * a = new KviKvsArray();
- a->set(0,new KviKvsVariant((kvs_int_t)g_pApp->desktop()->width()));
- a->set(1,new KviKvsVariant((kvs_int_t)g_pApp->desktop()->height()));
- c->returnValue()->setArray(a);
- return true;
-}
-
-bool KviKvsObject_widget::function_geometry(KviKvsObjectFunctionCall *c)
-{
- QRect r = widget() ? widget()->geometry() : QRect(0,0,0,0);
- KviKvsArray * a = new KviKvsArray();
- a->set(0,new KviKvsVariant((kvs_int_t)r.x()));
- a->set(1,new KviKvsVariant((kvs_int_t)r.y()));
- a->set(2,new KviKvsVariant((kvs_int_t)r.width()));
- a->set(3,new KviKvsVariant((kvs_int_t)r.height()));
- c->returnValue()->setArray(a);
- return true;
-}
-
-bool KviKvsObject_widget::function_setGeometry(KviKvsObjectFunctionCall *c)
-{
- KviKvsVariant * pXOrArray;
- kvs_int_t iX,iY,iW,iH;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("x_or_array",KVS_PT_VARIANT,0,pXOrArray)
- KVSO_PARAMETER("y",KVS_PT_INT,KVS_PF_OPTIONAL,iY)
- KVSO_PARAMETER("w",KVS_PT_INT,KVS_PF_OPTIONAL,iW)
- KVSO_PARAMETER("h",KVS_PT_INT,KVS_PF_OPTIONAL,iH)
- KVSO_PARAMETERS_END(c)
-
- // this is a little bit tricky: we accept two syntax versions
- // (this is something like a C++ overload)
- // $setGeometry(x,y,w,h) OR $setGeometry($array(x,y,w,h))
-
- // For this purpose we ask the parameter processing engine
- // to return the first parameter as variant and we manually check its data typoe
- // We also set the following three parameters as optional
- // so the user can either pass one or four parameters.
-
- // Because of this trick, we must check the parameter consistency
- // manually.
-
- if(pXOrArray->isArray())
- {
- // the user has passed a complete geometry array as first parameter
- // make sure it has at least 4 elements
- if(pXOrArray->array()->size() < 4)
- {
- c->error(__tr2qs("The array passed as parameter must contain at least 4 elements"));
- return false;
- }
- // we must also manually extract the data from the array
- KviKvsVariant * pX = pXOrArray->array()->at(0);
- KviKvsVariant * pY = pXOrArray->array()->at(1);
- KviKvsVariant * pW = pXOrArray->array()->at(2);
- KviKvsVariant * pH = pXOrArray->array()->at(3);
- // note that some of the array elements may be empty in fact
- // a null value returned by KviKvsArray::at() means that
- // no parameter was set in that place
- if(!(pX && pY && pW && pH))
- {
- c->error(__tr2qs("One of the geometry array parameters is empty"));
- return false;
- }
- if(!(pX->asInteger(iX) && pY->asInteger(iY) && pW->asInteger(iW) && pH->asInteger(iH)))
- {
- c->error(__tr2qs("One of the geometry array parameters didn't evaluate to an integer"));
- return false;
- }
- // ok: the params are correct
- } else {
- // The user passed something else as first parameter
- // make sure that it is an integer.
- // Also make sure that we really have 4 parameters
- if(c->params()->count() < 4)
- {
- c->error(__tr2qs("$setGeometry() requires either an array as first parameter or four integers"));
- return false;
- }
- if(!pXOrArray->asInteger(iX))
- {
- c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer"));
- return false;
- }
- // ok: the params are correct
- }
-
- if(widget())
- widget()->setGeometry(iX,iY,iW,iH);
-
- return true;
-}
-bool KviKvsObject_widget::function_mapToGlobal(KviKvsObjectFunctionCall *c)
-
-{
- if(!widget())return true;
- kvs_int_t iX,iY;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("x",KVS_PT_INT,0,iX)
- KVSO_PARAMETER("y",KVS_PT_INT,0,iY)
- KVSO_PARAMETERS_END(c)
- QPoint point=widget()->mapToGlobal(QPoint(iX,iY));
- KviKvsArray * a = new KviKvsArray();
- a->set(0,new KviKvsVariant((kvs_int_t)point.x()));
- a->set(1,new KviKvsVariant((kvs_int_t)point.y()));
- c->returnValue()->setArray(a);
- return true;
-}
-
-bool KviKvsObject_widget::function_mapFromGlobal(KviKvsObjectFunctionCall *c)
-
-{
- if(!widget())return true;
- kvs_int_t iX,iY;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("x",KVS_PT_INT,0,iX)
- KVSO_PARAMETER("y",KVS_PT_INT,0,iY)
- KVSO_PARAMETERS_END(c)
- QPoint point=widget()->mapFromGlobal(QPoint(iX,iY));
- KviKvsArray * a = new KviKvsArray();
- a->set(0,new KviKvsVariant((kvs_int_t)point.x()));
- a->set(1,new KviKvsVariant((kvs_int_t)point.y()));
- c->returnValue()->setArray(a);
- return true;
-}
-bool KviKvsObject_widget::function_centerToScreen(KviKvsObjectFunctionCall *c)
-{
- if(widget()) widget()->move((g_pApp->desktop()->width() - widget()->width())/2,(g_pApp->desktop()->height() - widget()->height())/2);
- return true;
-}
-
-bool KviKvsObject_widget::function_setPaletteForeground(KviKvsObjectFunctionCall *c)
-{
- KviKvsVariant * pColArray;
- kvs_int_t iColR,iColG,iColB;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("hex_rgb_array_or_red",KVS_PT_VARIANT,0,pColArray)
- KVSO_PARAMETER("green",KVS_PT_INT,KVS_PF_OPTIONAL,iColG)
- KVSO_PARAMETER("blue",KVS_PT_INT,KVS_PF_OPTIONAL,iColB)
- KVSO_PARAMETERS_END(c)
-
- if(pColArray->isArray())
- {
- if(pColArray->array()->size() < 3)
- {
- c->error(__tr2qs("The array passed as parameter must contain at least 3 elements"));
- return false;
- }
- KviKvsVariant * pColR = pColArray->array()->at(0);
- KviKvsVariant * pColG = pColArray->array()->at(1);
- KviKvsVariant * pColB = pColArray->array()->at(2);
-
- if(!(pColR && pColG && pColB))
- {
- c->error(__tr2qs("One of the colors array parameters is empty"));
- return false;
- }
- if(!(pColR->asInteger(iColR) && pColG->asInteger(iColG) && pColB->asInteger(iColB)))
- {
- c->error(__tr2qs("One of the colors array parameters didn't evaluate to an integer"));
- return false;
- }
-
- } else {
- if (c->params()->count()==1)
- {
- bool bOk,bOk1,bOk2;
- QString value;
- pColArray->asString(value);
- int i=0;
- if (value.length()!=6)
- {
- c->warning(__tr2qs("A string of 6 digits hex is required"));
- return true;
- }
- QString buffer(value.mid(0,2));
- iColR=buffer.toInt(&bOk,16);
- buffer=value.mid(2,2);
- iColG=buffer.toInt(&bOk1,16);
- buffer=value.mid(4,2);
- iColB=buffer.toInt(&bOk2,16);
- if (!bOk || !bOk1 || !bOk2)
- {
- c->warning(__tr2qs("Not an hex digits"));
- return true;
- }
- if (widget()) widget()->setPaletteForegroundColor(QColor(iColR,iColG,iColB));
- return true;
- }
-
- if(c->params()->count() < 3)
- {
-
- c->error(__tr2qs("$setForegroundColor requires either an array as first parameter, one hex string or three integers"));
- return false;
- }
- if(!pColArray->asInteger(iColR))
- {
- c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer"));
- return false;
- }
- }
- if (widget()) widget()->setPaletteForegroundColor(QColor(iColR,iColG,iColB));
- return true;
-}
-
-bool KviKvsObject_widget::function_setBackgroundColor(KviKvsObjectFunctionCall *c)
-{
- KviKvsVariant * pColArray;
- kvs_int_t iColR,iColG,iColB;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("hex_rgb_array_or_red",KVS_PT_VARIANT,0,pColArray)
- KVSO_PARAMETER("green",KVS_PT_INT,KVS_PF_OPTIONAL,iColG)
- KVSO_PARAMETER("blue",KVS_PT_INT,KVS_PF_OPTIONAL,iColB)
- KVSO_PARAMETERS_END(c)
-
- if(pColArray->isArray())
- {
- if(pColArray->array()->size() < 3)
- {
- c->error(__tr2qs("The array passed as parameter must contain at least 3 elements"));
- return false;
- }
- KviKvsVariant * pColR = pColArray->array()->at(0);
- KviKvsVariant * pColG = pColArray->array()->at(1);
- KviKvsVariant * pColB = pColArray->array()->at(2);
-
- if(!(pColR && pColG && pColB))
- {
- c->error(__tr2qs("One of the colors array parameters is empty"));
- return false;
- }
- if(!(pColR->asInteger(iColR) && pColG->asInteger(iColG) && pColB->asInteger(iColB)))
- {
- c->error(__tr2qs("One of the colors array parameters didn't evaluate to an integer"));
- return false;
- }
-
- } else {
- if (c->params()->count()==1)
- {
- bool bOk,bOk1,bOk2;
- QString value;
- pColArray->asString(value);
- int i=0;
- if (value.length()!=6)
- {
- c->warning(__tr2qs("A string of 6 digits hex is required"));
- return true;
- }
- QString buffer(value.mid(0,2));
- iColR=buffer.toInt(&bOk,16);
- buffer=value.mid(2,2);
- iColG=buffer.toInt(&bOk1,16);
- buffer=value.mid(4,2);
- iColB=buffer.toInt(&bOk2,16);
- if (!bOk || !bOk1 || !bOk2)
- {
- c->warning(__tr2qs("Not an hex digits"));
- return true;
- }
- if (widget()) widget()->setBackgroundColor(QColor(iColR,iColG,iColB));
- return true;
- }
-
- if(c->params()->count() < 3)
- {
-
- c->error(__tr2qs("$setBackgroundColor requires either an array as first parameter, one hex string or three integers"));
- return false;
- }
- if(!pColArray->asInteger(iColR))
- {
- c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer"));
- return false;
- }
- }
- if (widget()) widget()->setBackgroundColor(QColor(iColR,iColG,iColB));
- return true;
-}
-
-bool KviKvsObject_widget::function_backgroundColor(KviKvsObjectFunctionCall *c)
-{
- if(!widget())return true;
- QColor col = widget()->backgroundColor();
- KviKvsArray * a = new KviKvsArray();
- a->set(0,new KviKvsVariant((kvs_int_t)col.red()));
- a->set(1,new KviKvsVariant((kvs_int_t)col.green()));
- a->set(2,new KviKvsVariant((kvs_int_t)col.blue()));
- c->returnValue()->setArray(a);
- return true;
-}
-
-bool KviKvsObject_widget::function_foregroundColor(KviKvsObjectFunctionCall *c)
-{
- if(!widget())return true;
- QColor col = widget()->foregroundColor();
- KviKvsArray * a = new KviKvsArray();
- a->set(0,new KviKvsVariant((kvs_int_t)col.red()));
- a->set(1,new KviKvsVariant((kvs_int_t)col.green()));
- a->set(2,new KviKvsVariant((kvs_int_t)col.blue()));
- c->returnValue()->setArray(a);
- return true;
-}
-
-bool KviKvsObject_widget::function_parentWidget(KviKvsObjectFunctionCall *c)
-{
- if(!widget())return true;
- if(parentScriptWidget()) c->returnValue()->setHObject(parentObject()->handle());
- else
- c->returnValue()->setHObject((kvs_hobject_t)0);
- return true;
-
-}
-bool KviKvsObject_widget::function_setMouseTracking(KviKvsObjectFunctionCall *c)
-{
- bool bEnabled;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("bEnabled",KVS_PT_BOOL,0,bEnabled)
- KVSO_PARAMETERS_END(c)
- if(widget()) widget()->setMouseTracking(bEnabled);
- return true;
-}
-
-bool KviKvsObject_widget::function_setCaption(KviKvsObjectFunctionCall *c)
-{
- QString szCaption;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("caption",KVS_PT_STRING,0,szCaption)
- KVSO_PARAMETERS_END(c)
- if(widget()) widget()->setCaption(szCaption);
- return true;
-}
-
-bool KviKvsObject_widget::function_caption(KviKvsObjectFunctionCall *c)
-{
- if(widget()) c->returnValue()->setString(widget()->caption().utf8().data());
- return true;
-}
-
-bool KviKvsObject_widget::function_isTopLevel(KviKvsObjectFunctionCall *c)
-{
- if(widget()) c->returnValue()->setBoolean(widget()->isTopLevel());
- return true;
-}
-
-bool KviKvsObject_widget::function_isVisible(KviKvsObjectFunctionCall *c)
-{
- if(widget()) c->returnValue()->setBoolean(widget()->isVisible());
- return true;
-}
-
-bool KviKvsObject_widget::function_raise(KviKvsObjectFunctionCall *)
-{
- if(widget()) widget()->raise();
- return true;
-}
-
-bool KviKvsObject_widget::function_lower(KviKvsObjectFunctionCall *)
-{
- if(widget())widget()->lower();
- return true;
-}
-
-bool KviKvsObject_widget::function_hasFocus(KviKvsObjectFunctionCall *c)
-{
- if(widget()) c->returnValue()->setBoolean(widget()->hasFocus());
- return true;
-}
-
-bool KviKvsObject_widget::function_setFocus(KviKvsObjectFunctionCall *c)
-{
- if (widget())widget()->setFocus();
- return true;
-}
-bool KviKvsObject_widget::function_hide(KviKvsObjectFunctionCall *)
-{
- if(widget())widget()->hide();
- return true;
-}
-
-bool KviKvsObject_widget::function_setToolTip(KviKvsObjectFunctionCall *c)
-{
- QString szTooltip;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("tooltip",KVS_PT_STRING,0,szTooltip)
- KVSO_PARAMETERS_END(c)
- if(widget())QToolTip::add( widget(), szTooltip );
- return true;
-}
-
-bool KviKvsObject_widget::function_x(KviKvsObjectFunctionCall *c)
-{
- if(widget()) c->returnValue()->setInteger(widget()->x());
- return true;
-}
-
-bool KviKvsObject_widget::function_y(KviKvsObjectFunctionCall *c)
-{
- if(widget())c->returnValue()->setInteger(widget()->y());
- return true;
-}
-
-bool KviKvsObject_widget::function_width(KviKvsObjectFunctionCall *c)
-{
- if(widget())c->returnValue()->setInteger(widget()->width());
- return true;
-}
-
-bool KviKvsObject_widget::function_height(KviKvsObjectFunctionCall *c)
-{
- if(widget())c->returnValue()->setInteger(widget()->height());
- return true;
-}
-
-bool KviKvsObject_widget::function_setMinimumWidth(KviKvsObjectFunctionCall *c)
-{
- kvs_int_t iW;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("w",KVS_PT_INT,0,iW)
- KVSO_PARAMETERS_END(c)
- if (widget()) widget()->setMinimumWidth(iW);
- return true;
-}
-
-bool KviKvsObject_widget::function_setMinimumHeight(KviKvsObjectFunctionCall *c)
-{
- kvs_int_t iH;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("h",KVS_PT_INT,0,iH)
- KVSO_PARAMETERS_END(c)
- if (widget()) widget()->setMinimumHeight(iH);
- return true;
-}
-
-bool KviKvsObject_widget::function_setMaximumWidth(KviKvsObjectFunctionCall *c)
-{
- kvs_int_t iW;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("w",KVS_PT_INT,0,iW)
- KVSO_PARAMETERS_END(c)
- if (widget()) widget()->setMaximumWidth(iW);
- return true;
-}
-
-bool KviKvsObject_widget::function_setMaximumHeight(KviKvsObjectFunctionCall *c)
-{
- kvs_int_t iH;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("h",KVS_PT_INT,0,iH)
- KVSO_PARAMETERS_END(c)
- if(widget()) widget()->setMaximumHeight(iH);
- return true;
-}
-
-bool KviKvsObject_widget::function_move(KviKvsObjectFunctionCall *c)
-{
- kvs_int_t iX,iY;
-
- KviKvsVariant * pXOrArray;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("x_or_array",KVS_PT_VARIANT,0,pXOrArray)
- KVSO_PARAMETER("y",KVS_PT_INT,KVS_PF_OPTIONAL,iY)
- KVSO_PARAMETERS_END(c)
- if(pXOrArray->isArray())
- {
- if(pXOrArray->array()->size() < 2)
- {
- c->error(__tr2qs("The array passed as parameter must contain at least 2 elements"));
- return false;
- }
- KviKvsVariant * pX = pXOrArray->array()->at(0);
- KviKvsVariant * pY = pXOrArray->array()->at(1);
- if(!(pX && pY))
- {
- c->error(__tr2qs("One of the move array parameters is empty"));
- return false;
- }
- if(!(pX->asInteger(iX) && pY->asInteger(iY)))
- {
- c->error(__tr2qs("One of the move array parameters didn't evaluate to an integer"));
- return false;
- }
- // ok: the params are correct
- } else {
- if(c->params()->count() < 2)
- {
- c->error(__tr2qs("$move() requires either an array as first parameter or two integers"));
- return false;
- }
- if(!pXOrArray->asInteger(iX))
- {
- c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer"));
- return false;
- }
- // ok: the params are correct
- }
-
- if(!widget())return true;
- widget()->move(QPoint(iX,iY));
- return true;
-}
-bool KviKvsObject_widget::function_sizeHint(KviKvsObjectFunctionCall *c)
-{
- if(!widget())return true;
- QSize sizehint = widget()->sizeHint();
- KviKvsArray * a = new KviKvsArray();
- a->set(0,new KviKvsVariant((kvs_int_t)sizehint.width()));
- a->set(1,new KviKvsVariant((kvs_int_t)sizehint.height()));
- c->returnValue()->setArray(a);
- return true;
-}
-
-bool KviKvsObject_widget::function_resize(KviKvsObjectFunctionCall *c)
-{
- KviKvsVariant * pWOrArray;
- kvs_int_t iW,iH;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("width_or_array",KVS_PT_VARIANT,0,pWOrArray)
- KVSO_PARAMETER("height",KVS_PT_INT,KVS_PF_OPTIONAL,iH)
- KVSO_PARAMETERS_END(c)
- if(pWOrArray->isArray())
- {
- if(pWOrArray->array()->size() < 2)
- {
- c->error(__tr2qs("The array passed as parameter must contain at least 2 elements"));
- return false;
- }
- KviKvsVariant * pW = pWOrArray->array()->at(0);
- KviKvsVariant * pH = pWOrArray->array()->at(1);
- if(!(pW && pH))
- {
- c->error(__tr2qs("One of the resize array parameters is empty"));
- return false;
- }
- if(!(pW->asInteger(iW) && pH->asInteger(iH)))
- {
- c->error(__tr2qs("One of the resize array parameters didn't evaluate to an integer"));
- return false;
- }
- // ok: the params are correct
- } else {
- if(c->params()->count() < 2)
- {
- c->error(__tr2qs("$resize() requires either an array as first parameter or two integers"));
- return false;
- }
- if(!pWOrArray->asInteger(iW))
- {
- c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer"));
- return false;
- }
- // ok: the params are correct
- }
-
- if(!widget())return true;
- widget()->resize(QSize(iW,iH));
- return true;
-}
-bool KviKvsObject_widget::function_setFocusPolicy(KviKvsObjectFunctionCall *c)
-{
- QString szMode;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("focus",KVS_PT_STRING,0,szMode)
- KVSO_PARAMETERS_END(c)
- if(!widget())return true;
- if(KviQString::equalCI(szMode, "TabFocus"))
- widget()->setFocusPolicy(QT_WIDGET_TABFOCUS);
- else
- if(KviQString::equalCI(szMode, "ClickFocus"))
- widget()->setFocusPolicy(QT_WIDGET_CLICKFOCUS);
- else
- if(KviQString::equalCI(szMode, "StrongFocus"))
- widget()->setFocusPolicy(QT_WIDGET_STRONGFOCUS);
- else
- if(KviQString::equalCI(szMode, "NoFocus"))
- widget()->setFocusPolicy(QT_WIDGET_NOFOCUS);
- else c->warning(__tr2qs("Invalid parameters"));
- return true;
-}
-
-bool KviKvsObject_widget::function_setWFlags(KviKvsObjectFunctionCall *c)
-{
- QStringList wflags;
- //Qt::WindowType sum;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("widget_flags",KVS_PT_STRINGLIST,KVS_PF_OPTIONAL,wflags)
- KVSO_PARAMETERS_END(c)
- if (!widget()) return true;
- #ifdef COMPILE_USE_QT4
- Qt::WindowFlags flag,sum=0;
- #else
- int flag,sum=0;
- #endif
- for ( QStringList::Iterator it = wflags.begin(); it != wflags.end(); ++it )
- {
-
- flag=0;
- for(unsigned int j = 0; j < widgettypes_num; j++)
- {
- if(KviQString::equalCI((*it), widgettypes_tbl[j]))
- {
- flag=widgettypes_cod[j];
- break;
- }
- }
- if(flag)
- sum = sum | flag;
- else
- c->warning(__tr2qs("Unknown widget flag '%Q'"),&(*it));
-
- }
-
-#ifdef COMPILE_USE_QT4
- widget()->setWindowFlags(sum);
-#else
- widget()->reparent(widget()->parentWidget(),sum,QPoint(widget()->x(),widget()->y()));
-#endif
- return true;
-}
-
-bool KviKvsObject_widget::function_setFont(KviKvsObjectFunctionCall *c)
-{
-
- QString szFamily,szStyle;
- kvs_int_t uSize;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("size",KVS_PT_UNSIGNEDINTEGER,0,uSize)
- KVSO_PARAMETER("family",KVS_PT_STRING,0,szFamily)
- KVSO_PARAMETER("style",KVS_PT_STRING,0,szStyle)
- KVSO_PARAMETERS_END(c)
- if(!widget())return true;
- QFont font=widget()->font();
- font.setFamily(szFamily);
- font.setPointSize(uSize);
- if(KviQString::equalCI(szStyle,"italic")) font.setItalic(TRUE);
- else if(KviQString::equalCI(szStyle,"bold")) font.setBold(TRUE);
- else if(KviQString::equalCI(szStyle,"underline"))font.setUnderline(TRUE);
- else if(KviQString::equalCI(szStyle,"overline")) font.setOverline(TRUE);
- else if(KviQString::equalCI(szStyle,"strikeout"))font.setStrikeOut(TRUE);
- else if(KviQString::equalCI(szStyle,"fixedpitch")) font.setFixedPitch(TRUE);
- else c->warning(__tr2qs("Unknown style '%Q'"),&szStyle);
- widget()->setFont(font);
- return true;
-}
-
-bool KviKvsObject_widget::function_addWidgetToWrappedLayout(KviKvsObjectFunctionCall *c)
-{
- KviKvsObject *ob;
- kvs_int_t uCol,uRow;
- kvs_hobject_t hObject;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("widget",KVS_PT_HOBJECT,0,hObject)
- KVSO_PARAMETER("col",KVS_PT_UNSIGNEDINTEGER,0,uCol)
- KVSO_PARAMETER("row",KVS_PT_UNSIGNEDINTEGER,0,uRow)
- KVSO_PARAMETERS_END(c)
- ob=KviKvsKernel::instance()->objectController()->lookupObject(hObject);
- if(!widget())return true;
- if (!ob)
- {
- c->warning(__tr2qs("Widget parameter is not an object"));
- return true;
- }
- if (!ob->object())
- {
- c->warning(__tr2qs("Widget parameter is not a valid object"));
- return true;
- }
- QLayout *lay=widget()->layout();
- if (!lay)
- {
- c->warning(__tr2qs("No Layout associated to the widget "));
- return true;
- }
- if(!ob->object()->isWidgetType())
- {
- c->warning(__tr2qs("Can't add a non-widget object"));
- return true;
- }
- lay->add(((QWidget *)(ob->object())));
- return true;
-}
-bool KviKvsObject_widget::function_reparent(KviKvsObjectFunctionCall *c)
-{
- KviKvsObject *ob;
- kvs_hobject_t hObject;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("widget",KVS_PT_HOBJECT,KVS_PF_OPTIONAL,hObject)
- KVSO_PARAMETERS_END(c)
- ob=KviKvsKernel::instance()->objectController()->lookupObject(hObject);
- if(!widget()) return true;
- if(!ob)
- {
- widget()->reparent(0,QPoint(widget()->x(),widget()->y()));
- return true;
- }
- else
- if(!ob->object()->isWidgetType())
- {
- c->warning(__tr("Parent must be a widget object"));
- return true;
- }
- widget()->reparent(((QWidget *)(ob->object())),QPoint(((QWidget *)(ob->object()))->x(),((QWidget *)(ob->object()))->y()));
- return true;
-}
-bool KviKvsObject_widget::function_setIcon(KviKvsObjectFunctionCall *c)
-{
-
- QString icon;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("icon",KVS_PT_STRING,0,icon)
- KVSO_PARAMETERS_END(c)
- if(!widget())return true;
- QPixmap * pix = g_pIconManager->getImage(icon);
- if(pix)widget()->setIcon(*pix);
- return true;
-}
-
-bool KviKvsObject_widget::function_setBackgroundImage(KviKvsObjectFunctionCall *c)
-{
- QString image;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("image",KVS_PT_STRING,0,image)
- KVSO_PARAMETERS_END(c)
- if(!widget())return true;
- QPixmap * pix = g_pIconManager->getImage(image);
- if(pix)widget()->setPaletteBackgroundPixmap(*pix);
- return true;
-}
-bool KviKvsObject_widget::function_globalCursorX(KviKvsObjectFunctionCall *c)
-{
- if(widget())c->returnValue()->setInteger(QCursor::pos().x());
- return true;
-}
-bool KviKvsObject_widget::function_globalCursorY(KviKvsObjectFunctionCall *c)
-{
- if(widget())c->returnValue()->setInteger(QCursor::pos().y());
- return true;
-}
-bool KviKvsObject_widget::function_setMask(KviKvsObjectFunctionCall *c)
-{
- KviKvsObject *obj;
- kvs_hobject_t hObject;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("pixmap",KVS_PT_HOBJECT,0,hObject)
- KVSO_PARAMETERS_END(c)
- obj=KviKvsKernel::instance()->objectController()->lookupObject(hObject);
- if(!widget())return true;
- if (!obj)
- {
- c->warning(__tr2qs("Pixmap parameter is not an object"));
- return true;
- }
- if (!obj->inherits("KviKvsObject_pixmap"))
- {
- c->warning(__tr2qs("Pixmap object required"));
- return true;
- }
- QPixmap * pm=((KviKvsObject_pixmap *)obj)->getPixmap();
-#ifdef COMPILE_USE_QT4
- QBitmap mask(pm->mask());
-#else
- QBitmap mask(*pm->mask());
-#endif
- if (mask.isNull()) c->warning(__tr2qs("Null mask"));
- widget()->setMask(mask);
- return true;
-}
-#ifdef COMPILE_USE_QT4
-bool KviKvsObject_widget::function_setAttribute(KviKvsObjectFunctionCall *c)
-{
- QString attribute;
- bool bFlag;
- KVSO_PARAMETERS_BEGIN(c)
- KVSO_PARAMETER("widget_atribute",KVS_PT_STRING,0,attribute)
- KVSO_PARAMETER("bool_flag",KVS_PT_BOOLEAN,0,bFlag)
- KVSO_PARAMETERS_END(c)
- if (!widget()) return true;
- bool found=false;
- unsigned int j = 0;
- for(; j < widgetattributes_num; j++)
- {
- if(KviQString::equalCI(attribute, widgetattributes_tbl[j]))
- {
- found=true;
- break;
- }
- }
- if(found)widget()->setAttribute(widgetattributes_cod[j],bFlag);
- else c->warning(__tr2qs("Unknown widget attribute '%Q'"),&attribute);
- return true;
-}
-#endif
-
-#include "m_class_widget.moc"
+//============================================================================= +// +// File : class_widget.cpp +// Creation date : Mon Sep 11 16:35:32 CET 2000 by Krzysztof Godlewski +// +// This file is part of the KVirc irc client distribution +// Copyright (C) 1999-2005 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. ,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +// +//============================================================================= + +#include "kvi_malloc.h" +#include "kvi_debug.h" + +#include "kvi_error.h" +#include "kvi_locale.h" +#include "kvi_iconmanager.h" +#include "kvi_window.h" +#include "kvi_out.h" +#include "kvi_mirccntrl.h" +#include "kvi_app.h" +#include "kvi_string.h" +#include <qcursor.h> +#include <qiconset.h> +#include <qcolor.h> +#include <qlayout.h> +#include <qbitmap.h> +#include <qmetaobject.h> +#include "class_widget.h" +#include "class_pixmap.h" + +#ifdef COMPILE_USE_QT4 + #include <QKeyEvent> + #include <QDesktopWidget> +#else + #include <qwidgetlist.h> +#endif + +#include <qwidget.h> +#include <qtooltip.h> +#include <qfont.h> +#include <qvariant.h> + +// FIX ME: WFLAGS +const char * const widgettypes_tbl[] = { + "TopLevel", + "Dialog", + "Popup", + "Desktop", + "Customize", + "Title", + "StaysOnTop", + "SysMenu", + "Minimize", + "Maximize", + "NoAutoErase" + }; +#ifdef COMPILE_USE_QT4 +const Qt::WidgetAttribute widgetattributes_cod[]= { + Qt::WA_OpaquePaintEvent, + Qt::WA_NoSystemBackground, + Qt::WA_PaintOnScreen, + Qt::WA_NoMousePropagation, +}; + +const char * const widgetattributes_tbl[] = { + "opaquePaintEvent", + "noSystemBackground", + "paintOnScreen", + "noMousePropagation", +}; +#define widgetattributes_num (sizeof(widgetattributes_tbl) / sizeof(widgetattributes_tbl[0])) + + +const Qt::WindowType widgettypes_cod[] = { +#else +const int widgettypes_cod[] = { +#endif + Qt::WType_TopLevel, + Qt::WType_Dialog, + Qt::WType_Popup, + Qt::WType_Desktop, + Qt::WStyle_Customize, + Qt::WStyle_Title, + Qt::WStyle_StaysOnTop, + Qt::WStyle_SysMenu, + Qt::WStyle_Minimize, + Qt::WStyle_Maximize, + Qt::WNoAutoErase +}; + + +#ifdef COMPILE_USE_QT4 + + #define QT_WIDGET_TABFOCUS Qt::TabFocus + #define QT_WIDGET_CLICKFOCUS Qt::ClickFocus + #define QT_WIDGET_STRONGFOCUS Qt::StrongFocus + #define QT_WIDGET_NOFOCUS Qt::NoFocus + +#else + #define QT_WIDGET_TABFOCUS QWidget::TabFocus + #define QT_WIDGET_CLICKFOCUS QWidget::ClickFocus + #define QT_WIDGET_STRONGFOCUS QWidget::StrongFocus + #define QT_WIDGET_NOFOCUS QWidget::NoFocus +#endif + + +#define widgettypes_num (sizeof(widgettypes_tbl) / sizeof(widgettypes_tbl[0])) + +/* + @doc: widget + @keyterms: + widget object class + @title: + widget class + @type: + class + @short: + Base class for all widgets + @inherits: + [class]object[/class] + @description: + This object class is the rappresentation of a widget. + All the other widget-type classes inherit from this one. + @functions: + !fn: $show() + Shows this widget and the children. + See also [classfnc]$hide[/classfnc]() and [classfnc]$isVisible[/classfnc]. + !fn: $hide() + Hides this widget (and conseguently all the children). + See also [classfnc]$show[/classfnc]() and [classfnc]$isVisible[/classfnc]. + !fn: $repaint(<bool erase>) + Repaints the widget directly by calling [classfnc]$paintEvent[/classfnc]() immediately.[br] + If erase is TRUE, erases the widget before the $paintEvent() call. + !fn: $x() + Returns the x coordinate of the upper-left corner + of this widget relative to the parent widget, + or to the desktop if this widget is a toplevel one. + !fn: $y() + Returns the y coordinate of the uspper-left corner + of this widget relative to the parent widget, + or to the desktop if this widget is a toplevel one. + !fn: $width() + Returns the width of this widget in pixels. + !fn: $height() + Returns the height of this widget in pixels. + !fn: $geometry() + Returns the widget geometry in this form:[br] + x, y, width, height. + !fn: $setGeometry(<x_or_array>,[<y>,<width>,<heigth>]) + Sets the geometry of this widget. <x> and <y> are relative + to the parent widget or to the desktop (if this widget is + a toplevel one). All the parameters are in pixels. + !fn: $setMinimumWidth(<value>) + Sets the minimum width of this widget to <value>. + The user will not be able to resize the widget to a smaller + value. This value is also used by the [class:layout]layout class[/class]. + !fn: $setMinimumHeight(<value>) + Sets the minimum height of this widget to <value>. + The user will not be able to resize the widget to a smaller + value. This value is also used by the [class:layout]layout class[/class]. + !fn: $setMaximumWidth(<value>) + Sets the maximum width of this widget to <value>. + The user will not be able to resize the widget to a bigger + value. This value is also used by the [class:layout]layout class[/class]. + !fn: $setMaximumHeight(<value>) + Sets the maximum height of this widget to <value>. + The user will not be able to resize the widget to a bigger + value. This value is also used by the [class:layout]layout class[/class]. + !fn: $move(<x_or_array>[,<y>]) + Moves this widget to the coordinate <x> and <y> relative to its + parent widget (or the desktop if this widget is a toplevel one). + This is equivalent to [classfnc]$setGeometry[/classfnc](<x>,<y>, + [classfnc]$width[/classfnc](),[classfnc]$height[/classfnc]()). + !fn: $resize(<w_or_array>,[height]) + Changes the widget's width to <width> and height to <height>. + See also [classfnc]$setGeometry[/classfnc](). + !fn: $isEnabled() + Returns '1' if the widget is enabled , '0' otherwise. + See also [classfnc:widget]$setEnabled[/classfnc](). + !fn: $setEnabled(<bool>) + Sets the widget state to enabled or disabled if <bool> is 1 or 0 respectively. + A disabled widget does not receive keyboard nor mouse input. + !fn: $setCaption(<text>) + Sets the caption of this widget to <text>. + This is meaningful for toplevel widgets only. + !fn: $setToolTip(<tooltip_text>) + Set the tooltip of this widget; the text can contain HTML formatting. + !fn: $window.caption() + Returns the caption text of this widget. + !fn: $isTopLevel() + Returns '1' if this widget is a toplevel (parentless) one, + '0' otherwise. + !fn: $isVisible() + Returns '1' if this widget is currently visible (read: is managed + by the window manager and displayed by the X server; the widget + may be hidden behind other widgets). If the widget is not visible + this function returns '0'. + See also [classfnc]$show[/classfnc]() and [classfnc]$hide[/classfnc](). + !fn: $raise() + Moves this widget to the top of the stack of the widgets relative + to its parent. See also [classfnc]$lower[/classfnc]. + !fn: $lower() + Moves this widget to the bottom of the stack of the widgets relative + to its parent. See also [classfnc]$raise[/classfnc] + !fn: $hasFocus() + Returns '1' if this widget has the keyboard focus. + See also [classfnc]$setFocus[/classfnc]. + !fn: $setFocus() + Sets this widget to be the one that receives keyboard events. + See also [classfnc]$hasFocus[/classfnc] + !fn: $parentWidget() + Returns the object id of the parent widget, or '0' if this + widget is a toplevel one. + !fn: $backgroundColor() + Returns the background color of this widget in hexadecimal + html-like format. For example , for a black bacground you will get + the string "000000" , for a red one , "FF0000", for a white one + "FFFFFF". See also [classfnc]$setBackgroundColor[/classfnc]() + !fn: $setBackgroundColor(<rgb(hex string)_array(red:integer,green:integer,blue_integer)_or_red>,[geen:integer],[blue:integer]) + Sets the background color of this widget to <rgb_value>:valid values are: + - hex string: must be a string with 6 hexadecimal digits (like the ones used to + specify colors in html pages). The first two digits specify + the RED component, the third and fourth digit specify the GREEN component + and the last two specify the BLUE component. + For example "FFFF00" means full red, full green and no blue that gives + a yellow color, "808000" designates a brown color (dark yellow), + "A000A0" is a kind of violet. + - array(red:integer,green:integer,blue:integer) + - red:integer,green:integer,blue:integer. + See also [classfnc]$foregroundColor[/classfnc]. + !fn: $setForegroundColor(<rgb(hex string)_array(red:integer,green:integer,blue_integer)_or_red>,[geen:integer],[blue:integer]) + Sets the foreground color of this widget to <rgb_value>:valid values are: + - hex string: must be a string with 6 hexadecimal digits (like the ones used to + specify colors in html pages). The first two digits specify + the RED component, the third and fourth digit specify the GREEN component + and the last two specify the BLUE component. + For example "FFFF00" means full red, full green and no blue that gives + a yellow color, "808000" designates a brown color (dark yellow), + "A000A0" is a kind of violet. + - array(red:integer,green:integer,blue:integer) + - red:integer,green:integer,blue:integer. + See also [classfnc]$foregroundColor[/classfnc]. + !fn: $foregroundColor() + Returns the foreground color of this widget in hexadecimal + html-like format. + See also [classfnc]$setForegroundColor[/classfnc]. + !fn: $setMouseTracking(<bool>) + Enables or disables the mouse tracking if <bool> is '1' or '0' respectively. + When mouse tracking is enabled you will receive mouse move events + even if no button is pressed, otherwise you will receive it only + when a mouse button is being pressed (so after a mousePressEvent). + !fn: $mousePressEvent(<button>,<x>,<y>) + This function is called when a mouse button is pressed while + the cursor is in this widget. <button> is 0 if the pressed button + is the left one, 1 if the button is the right one and 2 if it is the middle one. + The <x> and <y> coordinates are relative to this widget upper-left corner + and are expressed in pixels. + If you call "[cmd]setreturn[/cmd] 1" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $mouseReleaseEvent(<button>,<x>,<y>) + This function is called when a mouse button is released while + the cursor is in this widget. <button> is 0 if the released button + is the left one, 1 if the button is the right one and 2 if it is the middle one. + The <x> and <y> coordinates are relative to this widget upper-left corner + and are expressed in pixels. + If you call "[cmd]setreturn[/cmd] 1" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $mouseDoubleClickEvent(<button>,<x>,<y>) + This function is called when a mouse button is double clicked while + the cursor is in this widget. <button> is 0 if the double clicked button + is the left one, 1 if the button is the right one and 2 if it is the middle one. + The <x> and <y> coordinates are relative to this widget upper-left corner + and are expressed in pixels. + If you call "[cmd]setreturn[/cmd] 1" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $mouseMoveEvent(<button>,<x>,<y>) + This function is called when the mouse cursor moves inside this widget. + <button> is 0 if the pressed button + is the left one, 1 if the button is the right one and 2 if it is the middle one. + The special value of -1 indicates that no button is being pressed. + The <x> and <y> coordinates are relative to this widget upper-left corner + and are expressed in pixels. + Normally you will receive this event only if a mouse button is being pressed + while moving. If you want to receive it also when the mouse buttons are not + pressed, call [classfnc]$setMouseTracking[/classfnc](). + If you call "[cmd]return[/cmd]$true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $focusInEvent() + This function is called when this widget gains keyboard focus. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $focusOutEvent() + This function is called when this widget looses keyboard focus. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $mouseLeaveEvent() + This function is called when the mouse leaves this widget. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $mouseEnterEvent() + This function is called when the mouse enters this widget. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $showEvent() + This function is called when this widget is being shown. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $hideEvent() + This function is called when this widget is being hidden. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $closeEvent() + This function is called when this widget is going to be closed. + If you call "[cmd]return[/cmd] $true" you will ignore the close event. + The default implementation does nothing. + !fn: $resizeEvent() + This function is called immediately after this widget has been resized. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: $moveEvent() + This function is called immediately after this widget has been moved. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. The default implementation does nothing. + !fn: <tip:string> $maybeTipEvent(<x_tip_pos:integer>,<y_tip_pos:integer>)[QT4 only] + This event handler is called when a eventualy tip is going to be show. + You can be reimplement this event and set a dynamic tool tip by using "[cmd]return[/cmd] <tooltip_string>". + If a tooltip has setted with [classfnc]$setTooltip[/classfnc] the dynamic tooltip will be ignored. + The default implementation does nothing. + !fn: $paintEvent() + This event handler can be reimplemented to repaint all or part of the widget. + It's needed by the Painter class. + It's very useful for drawing flicker free animations or low level special graphic effects. + If you call "[cmd]return[/cmd] $true" you will stop the internal processing + of this event. + The default implementation does nothing. + !fn: $setIcon(<image_id>) + Sets the icon for this widget. This is meaningful only for toplevel widgets. + See the [doc:image_id]image identifier[/doc] documentation for the explaination + of the <image_id> parameter. + !fn: $setBackgroundImage(<image_id>) + Sets the background image for this widget. + See the [doc:image_id]image identifier[/doc] documentation for the explaination + of the <image_id> parameter. + For some kind of widgets, setting a background pixmap may have no effect or + have strange results. Experiment with it. + To unset the background image call [classfnc]$setBackgroundColor[/classfnc] + !fn: $setFont(<size>,<family>,<style>)[br] + Set the font's size, family and stile, valid flag for style are:[br] + [pre] + italic [br] + bold [br] + underline [br] + overline [br] + strikeout [br] + fixedpitch [br] + [/pre] + !fn: $setWFlags(<flag1>, <flag2>, ...) + This function sets widget flags, given as parameters. + Valid flags are: + [pre] + TopLevel - indicates that this widget is a top-level widget[br] + Dialog - indicates that this widget is a top-level window that should be decorated as a dialog[br] + Desktop - indicates that this widget is the desktop[br] + Popup - indicates that this widget is a popup top-level window[br] + NoAutoErase - indicates that this widget paints all its pixels. Updating, resizing, scrolling and focus changes should therefore not erase the widget. + Customize - let's the user to customize the style of the widget.[br] + [br] + Valid parameter for a customized widget are:[br] + Title - gives the window a title bar[br] + StaysOnTop - window stays on top [br] + SysMenu - add a windows system menu[br] + Minimize - add a minimize button for the sysmenu style[br] + Maximize - add a maximixe button for the sysmenu style[br] + [/pre] + !fn: $centerToScreen() + Centers the window on the screen (useful only for toplevel widgets).[br] + The best place to call this function is in $showEvent() + !fn: $setFocusPolicy(<key focus>) + Sets the way the widget accepts keyboard focus.[br] + Valid parameters are: + [pre] + - TabFocus; (widget accepts keyboard focus by tabbing)[br] + - ClickFocus; (widget accepts keyboard focus by clicking)[br] + - StrongFocus; (widget accepts both tabbing/clicking)[br] + - No Focus; (widget does not accept focus at all; this is the default value)[br] + [/pre] + !fn: $keyPressEvent(<key>) + If widget accepts keyboard focus (see [classfnc]$setFocusPolicy[/classfnc] ) this function handles for keys; + In its argument the key pressed.[br] + Special keys are: + [pre] + - Return [br] + - Enter [br] + - Down (cursor arrow down) [br] + - Up (cursor arrow up) [br] + - Left (cursor arrow left) [br] + - Right (cursor arrow right) [br] + - Shift [br] + - Ctrl [br] + - Alt [br] + - CapsLock [br] + - Backspace [br] + - Del [br] + - Esc [br] + - 0 [br] + - 1 [br] + - 2 [br] + - 3 [br] + - 4 [br] + - 5 [br] + - 6 [br] + - 7 [br] + - 8 [br] + - 9 [br] + - + [br] + - - [br] + - * [br] + - / [br] + - ( [br] + - ) [br] + - = [br] + - . [br] + - ^ [br] + + [/pre] + !fn: $mapFromGlobal(<x>,<y>) + Translates the global screen coordinate pos to widget coordinates. + !fn: $mapToGlobal(<x>,<y>) + Translates widget coordinates into the global screen coordinate pos. + !fn: integer $globalCursorX() + Return the x coordinate of mouse pointer global position. + !fn: integer $globalCursorY() + Return the y coordinate of the mo>use pointer global position. + @examples: + [example] + %Widget = $new(widget) + # This is the main container for other elements. + + %Widget->$setCaption("This is the widget title") + + %Widget->$setGeometry(100,200,170,290) + # 100 and 200 are distance (pixel) from the left and the top of father widget (in this case the KVIrc window) + # 300 and 400 are the weight and the height of the widget + + %Widget->%label = $new(label,%Widget) + %Widget->%label->$setText("This is a text label") + %Widget->%label->$setGeometry(10,10,150,20) + + %Widget->%lineedit = $new(lineedit,%Widget) + %Widget->%lineedit->$setText("This is a lineedit") + %Widget->%lineedit->$setGeometry(10,40,150,20) + + %Widget->%multilineedit = $new(multilineedit,%Widget) + %Widget->%multilineedit->$setText("This is a multilineedit") + %Widget->%multilineedit->$setGeometry(10,70,150,40) + + %Widget->%checkbox = $new(checkbox,%Widget) + %Widget->%checkbox->$setText("This is a checkbox") + %Widget->%checkbox->$setGeometry(10,120,150,20) + + %Widget->%combobox = $new(combobox,%Widget) + %Widget->%combobox->$setGeometry(10,150,150,20) + %Widget->%combobox->$insertItem("This is a combobox") + %Widget->%combobox->$insertItem("This is a combobox's item") + + %Widget->%listbox = $new(listbox,%Widget) + %Widget->%listbox->$setGeometry(10,180,150,40) + %Widget->%listbox->$insertItem("This is another item") + %Widget->%listbox->$insertItem("This is a listbox's item") + %Widget->%listbox->$insertItem("This is a listbox") + + %Widget->%radiobutton = $new(radiobutton,%Widget) + %Widget->%radiobutton->$setGeometry(10,230,150,20) + %Widget->%radiobutton->$setText("This is a radiobutton") + + %Widget->%button = $new(button, %Widget) + %Widget->%button->$setText("Close me") + %Widget->%button->$setGeometry(10,260,150,20) + + %Widget->$show() + # This shows the widget + + privateimpl(%Widget->%button, mousePressEvent) { + delete %Widget + # This closes the widget automatically + } + # privateimpl is triggered when user press the button. + # To do that, widget must be a global variable. + [/example] + +*/ + + + + +// +// If you never call c->error() , c->warning() (your function never fails) +// and never call a function that can call c->error() or c->warning() +// you can avoid ENTER_STACK_FRAME and c->leaveStackFrame() +// Just return true. +// c->error() should be called only in really critical situations +// (we have to define better "critical situation") +// if possible , leave the things go after just a c->warning() +// + + // widget() will be never 0 in THIS class + // but in derived classes WILL be + // ... now that I think about it , it + // may happen that widget() will be zero here too: + // If the Qt "physical" widget gets destroyed + // by some external factor (for example when children + // of a wrapper widget destroyed by KVIrc). + // + // as a convention: + // if widget() can be 0 in a class + // the user must have a function to check it + // (sth as object::$hasObject() could do the trick) + // obviously this will happen only in well defined cases + // as in a qtwrapper not yet wrapped or failed to wrap (so + // qtwrapper::$wrap() returned '0' for example) + // or after the widget has been destroyed... + // if widget() is 0 , the functions perform no actions + // return no errors and results that have to be assumed + // as invalid (this allows the minimum overhead: if widget() + +//============================================================================================================= + + + +KVSO_BEGIN_REGISTERCLASS(KviKvsObject_widget,"widget","object") + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"reparent",function_reparent) + // apparence + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"show",function_show) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"hide",function_hide) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"repaint",function_repaint) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"isTopLevel",function_isTopLevel) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"isVisible",function_isVisible) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"raise",function_raise) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"lower",function_lower) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setEnabled",function_setEnabled) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"isEnabled",function_isEnabled) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMouseTracking",function_setMouseTracking) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setCaption",function_setCaption) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"caption",function_caption) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"hasFocus",function_hasFocus) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setFocus",function_setFocus) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setToolTip",function_setToolTip) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setWFlags",function_setWFlags) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setIcon",function_setIcon) + // fonts + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"fontDescent",function_fontDescent) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"fontAscent",function_fontAscent) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"fontMetricsWidth",function_fontMetricsWidth) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"fontMetricsHeight",function_fontMetricsHeight) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setFont",function_setFont) + // geometry + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"screenResolution",function_screenResolution) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"centerToScreen",function_centerToScreen) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"geometry",function_geometry) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setGeometry",function_setGeometry) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"mapToGlobal",function_mapToGlobal) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"mapFromGlobal",function_mapFromGlobal) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"y",function_y) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"x",function_x) + + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"globalCursorX",function_globalCursorX) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"globalCursorY",function_globalCursorY) + + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"width",function_width) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"height",function_height) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMinimumWidth",function_setMinimumWidth) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMinimumHeight",function_setMinimumHeight) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMaximumWidth",function_setMaximumWidth) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMaximumHeight",function_setMaximumHeight) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"move",function_move) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"sizeHint",function_sizeHint) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"resize",function_resize) + + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setFocusPolicy",function_setFocusPolicy) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"addWidgetToWrappedLayout",function_addWidgetToWrappedLayout) + + // colors and image + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setForegroundColor",function_setPaletteForeground) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setBackgroundColor",function_setBackgroundColor) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setBackgroundImage",function_setBackgroundImage) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"backgroundColor",function_backgroundColor) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"foregroundColor",function_foregroundColor) + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setMask",function_setMask) + + // QT4 only +#ifdef COMPILE_USE_QT4 + KVSO_REGISTER_HANDLER(KviKvsObject_widget,"setAttribute",function_setAttribute) +#endif + + // events + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mousePressEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseReleaseEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseDoubleClickEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseMoveEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"focusInEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"focusOutEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseLeaveEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"mouseEnterEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"showEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"hideEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"closeEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"resizeEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"moveEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"paintEvent") + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"keyPressEvent") +#ifdef COMPILE_USE_QT4 + KVSO_REGISTER_STANDARD_NOTHINGRETURN_HANDLER(KviKvsObject_widget,"maybeTipEvent") +#endif + + +KVSO_END_REGISTERCLASS(KviKvsObject_widget) + + +KVSO_BEGIN_CONSTRUCTOR(KviKvsObject_widget,KviKvsObject) +KVSO_END_CONSTRUCTOR(KviKvsObject_widget) + +KVSO_BEGIN_DESTRUCTOR(KviKvsObject_widget) + emit aboutToDie(); +KVSO_END_CONSTRUCTOR(KviKvsObject_widget) + +bool KviKvsObject_widget::init(KviKvsRunTimeContext * pContext,KviKvsVariantList * pParams) +{ + setObject(new QWidget(parentScriptWidget(),getName()),true); + return true; +} + +bool KviKvsObject_widget::eventFilter(QObject *o,QEvent *e) +{ + if(o == object()) + { + bool ret=false; + int aparam; + bool brokenhandler=false; + KviKvsVariant *retv=new KviKvsVariant(ret); + + switch(e->type()) + { + #ifdef COMPILE_USE_QT4 + case QEvent::ToolTip: + { + QHelpEvent *helpEvent = static_cast<QHelpEvent *>(e); + QPoint point=helpEvent->pos(); + QString szTooltip; + KviKvsVariant *tipret=new KviKvsVariant(szTooltip); + KviKvsVariantList params(new KviKvsVariant((kvs_int_t)point.x()),new KviKvsVariant((kvs_int_t)point.y())); + callFunction(this,"maybeTipEvent",tipret,¶ms); + tipret->asString(szTooltip); + QToolTip::showText(helpEvent->globalPos(),szTooltip); + break; + } + #endif + case QEvent::Paint: + { + QRect rect=((QPaintEvent *)e)->rect(); + KviKvsVariantList params(new KviKvsVariant((kvs_int_t)rect.x()),new KviKvsVariant((kvs_int_t)rect.y()),new KviKvsVariant((kvs_int_t)rect.width()),new KviKvsVariant((kvs_int_t)rect.height())); + callFunction(this,"paintEvent",retv,¶ms); + break; + } + + case QEvent::KeyPress: + { + QString tmp=""; + switch(((QKeyEvent *)e)->key()) + { + case Qt::Key_Return: + tmp="Return"; + break; + case Qt::Key_Down: + tmp="Down"; + break; + case Qt::Key_Up: + tmp="Up"; + break; + case Qt::Key_Left: + tmp="Left"; + break; + case Qt::Key_Right: + tmp="Right"; + break; + case Qt::Key_Shift: + tmp="Shift"; + break; + case Qt::Key_Control: + tmp="Ctrl"; + break; + case Qt::Key_Alt: + tmp="Alt"; + break; + case Qt::Key_CapsLock: + tmp="CapsLock"; + break; + case Qt::Key_Backspace: + tmp="Backspace"; + break; + case Qt::Key_Delete: + tmp="Del"; + break; + + case Qt::Key_Enter: + tmp="Enter"; + break; + case Qt::Key_Escape: + tmp="Esc"; + break; + case Qt::Key_0: + tmp="0"; + case Qt::Key_1: + tmp="1"; + break; + case Qt::Key_2: + tmp="2"; + break; + case Qt::Key_3: + tmp="3"; + break; + case Qt::Key_4: + tmp="4"; + break; + case Qt::Key_5: + tmp="5"; + break; + case Qt::Key_6: + tmp="6"; + break; + case Qt::Key_7: + tmp="7"; + break; + case Qt::Key_8: + tmp="8"; + break; + case Qt::Key_9: + tmp="9"; + break; + case Qt::Key_Plus: + tmp="+"; + break; + case Qt::Key_Minus: + tmp="-"; + break; + case Qt::Key_Slash: + tmp="/"; + break; + case Qt::Key_Asterisk: + tmp="*"; + break; + case Qt::Key_Period: + tmp="."; + break; + case Qt::Key_ParenLeft: + tmp="("; + break; + case Qt::Key_ParenRight: + tmp=")"; + break; + case Qt::Key_Equal: + tmp="="; + break; + case Qt::Key_AsciiCircum: + tmp="^"; + break; + default: + if (!((QKeyEvent *)e)->text().isEmpty()) tmp = ((QKeyEvent *)e)->text(); + } + + KviKvsVariantList params(new KviKvsVariant(tmp)); + callFunction(this,"keyPressEvent",0,¶ms); + } + break; + case QEvent::MouseButtonPress: + if(((QMouseEvent *)e)->button() & Qt::LeftButton)aparam = 0; + else { + if(((QMouseEvent *)e)->button() & Qt::RightButton)aparam = 1; + else aparam = 2; + } + if(!callFunction(this,"mousePressEvent",retv,new KviKvsVariantList(new KviKvsVariant((kvs_int_t)aparam),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().x()),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().y()) + ))) brokenhandler = true; // ignore results of a broken event handler + break; + case QEvent::MouseButtonRelease: + if(((QMouseEvent *)e)->button() & Qt::LeftButton)aparam = 0; + else { + if(((QMouseEvent *)e)->button() & Qt::RightButton)aparam = 1; + else aparam = 2; + } + if(!callFunction(this,"mouseReleaseEvent",retv,new KviKvsVariantList(new KviKvsVariant((kvs_int_t)aparam),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().x()),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().y()) + ))) brokenhandler = true; // ignore results of a broken event handler + break; + case QEvent::MouseButtonDblClick: + if(( (QMouseEvent *)e)->button() & Qt::LeftButton)aparam = 0; + else { + if(((QMouseEvent *)e)->button() & Qt::RightButton)aparam = 1; + else aparam = 2; + } + if(!callFunction(this,"mouseDoubleClickEvent",retv,new KviKvsVariantList(new KviKvsVariant((kvs_int_t)aparam),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().x()),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().y()) + ))) brokenhandler = true; // ignore results of a broken event handler + + break; + case QEvent::MouseMove: + if( (((QMouseEvent *)e)->state()) & Qt::LeftButton) aparam = 0; + else + { + if(((QMouseEvent *)e)->state() & Qt::RightButton)aparam = 1; + else + { + if(((QMouseEvent *)e)->state() & Qt::MidButton)aparam = 2; + else aparam = -1; + } + } + if(!callFunction(this,"mouseMoveEvent",retv,new KviKvsVariantList(new KviKvsVariant((kvs_int_t)aparam),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().x()),new KviKvsVariant((kvs_int_t)((QMouseEvent *)e)->pos().y()) + ))) brokenhandler = true; // ignore results of a broken event handler + break; + case QEvent::FocusIn: + if(!callFunction(this,"focusInEvent",retv,0))brokenhandler = true; + break; + case QEvent::FocusOut: + if(!callFunction(this,"focusOutEvent",retv,0))brokenhandler = true; + break; + case QEvent::Resize: + if(!callFunction(this,"resizeEvent",retv,0))brokenhandler = true; + break; + case QEvent::Move: + if(!callFunction(this,"moveEvent",retv,0))brokenhandler = true; + break; + case QEvent::Close: + if(!callFunction(this,"closeEvent",retv,0))brokenhandler = true; + break; + case QEvent::Enter: + if(!callFunction(this,"mouseEnterEvent",retv,0))brokenhandler = true; + break; + case QEvent::Leave: + if(!callFunction(this,"mouseLeaveEvent",retv,0))brokenhandler = true; + break; + case QEvent::Show: + if(!callFunction(this,"showEvent",retv,0))brokenhandler = true; + break; + case QEvent::Hide: + if(!callFunction(this,"hideEvent",retv,0))ret =false; + break; + default: + return KviKvsObject::eventFilter(o,e); + break; + + } + if (!brokenhandler) ret=retv->asBoolean(); + delete retv; + return ret; + /* + if(ret.length() == 1) + { + if(KviQString::equalCI("1",ret))return true; + } + */ + } + + return KviKvsObject::eventFilter(o,e); +} + + +bool KviKvsObject_widget::function_show(KviKvsObjectFunctionCall *c) +{ + if(!widget())return true; // should we warn here ? + widget()->show(); + return true; +} + +bool KviKvsObject_widget::function_setEnabled(KviKvsObjectFunctionCall *c) +{ + bool bEnabled; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("bEnabled",KVS_PT_BOOL,0,bEnabled) + KVSO_PARAMETERS_END(c) + if(!widget())return true; + widget()->setEnabled(bEnabled); + return true; +} +bool KviKvsObject_widget::function_isEnabled(KviKvsObjectFunctionCall *c) +{ + if(!widget()) return true; + c->returnValue()->setBoolean(widget()->isEnabled()); + return true; +} +bool KviKvsObject_widget::function_fontDescent(KviKvsObjectFunctionCall * c) +{ + if(!widget()) return true; + QFontMetrics fm = widget()->fontMetrics(); + int d = fm.descent(); + c->returnValue()->setInteger(d); + return true; +} + +bool KviKvsObject_widget::function_fontAscent(KviKvsObjectFunctionCall * c) +{ + if(!widget()) return true; + QFontMetrics fm = widget()->fontMetrics(); + int d = fm.ascent(); + c->returnValue()->setInteger(d); + return true; + +} + +bool KviKvsObject_widget::function_repaint(KviKvsObjectFunctionCall * c) +{ + bool bEnabled; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("bEnabled",KVS_PT_BOOL,0,bEnabled) + KVSO_PARAMETERS_END(c) + if(!widget()) return true; + widget()->repaint(bEnabled); + return true; +} + +bool KviKvsObject_widget::function_fontMetricsWidth(KviKvsObjectFunctionCall * c) +{ + QString m_szStr; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("string",KVS_PT_STRING,0,m_szStr) + KVSO_PARAMETERS_END(c) + if(!widget()) return true; +// int fm = widget()->fontMetrics().width(m_szStr); + c->returnValue()->setInteger(widget()->fontMetrics().width(m_szStr)); + return true; +} + +bool KviKvsObject_widget::function_fontMetricsHeight(KviKvsObjectFunctionCall * c) +{ + if(!widget())return true; + int fm = widget()->fontMetrics().height(); + c->returnValue()->setInteger(fm); + return true; +} +bool KviKvsObject_widget::function_screenResolution(KviKvsObjectFunctionCall * c) +{ + KviKvsArray * a = new KviKvsArray(); + a->set(0,new KviKvsVariant((kvs_int_t)g_pApp->desktop()->width())); + a->set(1,new KviKvsVariant((kvs_int_t)g_pApp->desktop()->height())); + c->returnValue()->setArray(a); + return true; +} + +bool KviKvsObject_widget::function_geometry(KviKvsObjectFunctionCall *c) +{ + QRect r = widget() ? widget()->geometry() : QRect(0,0,0,0); + KviKvsArray * a = new KviKvsArray(); + a->set(0,new KviKvsVariant((kvs_int_t)r.x())); + a->set(1,new KviKvsVariant((kvs_int_t)r.y())); + a->set(2,new KviKvsVariant((kvs_int_t)r.width())); + a->set(3,new KviKvsVariant((kvs_int_t)r.height())); + c->returnValue()->setArray(a); + return true; +} + +bool KviKvsObject_widget::function_setGeometry(KviKvsObjectFunctionCall *c) +{ + KviKvsVariant * pXOrArray; + kvs_int_t iX,iY,iW,iH; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("x_or_array",KVS_PT_VARIANT,0,pXOrArray) + KVSO_PARAMETER("y",KVS_PT_INT,KVS_PF_OPTIONAL,iY) + KVSO_PARAMETER("w",KVS_PT_INT,KVS_PF_OPTIONAL,iW) + KVSO_PARAMETER("h",KVS_PT_INT,KVS_PF_OPTIONAL,iH) + KVSO_PARAMETERS_END(c) + + // this is a little bit tricky: we accept two syntax versions + // (this is something like a C++ overload) + // $setGeometry(x,y,w,h) OR $setGeometry($array(x,y,w,h)) + + // For this purpose we ask the parameter processing engine + // to return the first parameter as variant and we manually check its data typoe + // We also set the following three parameters as optional + // so the user can either pass one or four parameters. + + // Because of this trick, we must check the parameter consistency + // manually. + + if(pXOrArray->isArray()) + { + // the user has passed a complete geometry array as first parameter + // make sure it has at least 4 elements + if(pXOrArray->array()->size() < 4) + { + c->error(__tr2qs("The array passed as parameter must contain at least 4 elements")); + return false; + } + // we must also manually extract the data from the array + KviKvsVariant * pX = pXOrArray->array()->at(0); + KviKvsVariant * pY = pXOrArray->array()->at(1); + KviKvsVariant * pW = pXOrArray->array()->at(2); + KviKvsVariant * pH = pXOrArray->array()->at(3); + // note that some of the array elements may be empty in fact + // a null value returned by KviKvsArray::at() means that + // no parameter was set in that place + if(!(pX && pY && pW && pH)) + { + c->error(__tr2qs("One of the geometry array parameters is empty")); + return false; + } + if(!(pX->asInteger(iX) && pY->asInteger(iY) && pW->asInteger(iW) && pH->asInteger(iH))) + { + c->error(__tr2qs("One of the geometry array parameters didn't evaluate to an integer")); + return false; + } + // ok: the params are correct + } else { + // The user passed something else as first parameter + // make sure that it is an integer. + // Also make sure that we really have 4 parameters + if(c->params()->count() < 4) + { + c->error(__tr2qs("$setGeometry() requires either an array as first parameter or four integers")); + return false; + } + if(!pXOrArray->asInteger(iX)) + { + c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer")); + return false; + } + // ok: the params are correct + } + + if(widget()) + widget()->setGeometry(iX,iY,iW,iH); + + return true; +} +bool KviKvsObject_widget::function_mapToGlobal(KviKvsObjectFunctionCall *c) + +{ + if(!widget())return true; + kvs_int_t iX,iY; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("x",KVS_PT_INT,0,iX) + KVSO_PARAMETER("y",KVS_PT_INT,0,iY) + KVSO_PARAMETERS_END(c) + QPoint point=widget()->mapToGlobal(QPoint(iX,iY)); + KviKvsArray * a = new KviKvsArray(); + a->set(0,new KviKvsVariant((kvs_int_t)point.x())); + a->set(1,new KviKvsVariant((kvs_int_t)point.y())); + c->returnValue()->setArray(a); + return true; +} + +bool KviKvsObject_widget::function_mapFromGlobal(KviKvsObjectFunctionCall *c) + +{ + if(!widget())return true; + kvs_int_t iX,iY; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("x",KVS_PT_INT,0,iX) + KVSO_PARAMETER("y",KVS_PT_INT,0,iY) + KVSO_PARAMETERS_END(c) + QPoint point=widget()->mapFromGlobal(QPoint(iX,iY)); + KviKvsArray * a = new KviKvsArray(); + a->set(0,new KviKvsVariant((kvs_int_t)point.x())); + a->set(1,new KviKvsVariant((kvs_int_t)point.y())); + c->returnValue()->setArray(a); + return true; +} +bool KviKvsObject_widget::function_centerToScreen(KviKvsObjectFunctionCall *c) +{ + if(widget()) widget()->move((g_pApp->desktop()->width() - widget()->width())/2,(g_pApp->desktop()->height() - widget()->height())/2); + return true; +} + +bool KviKvsObject_widget::function_setPaletteForeground(KviKvsObjectFunctionCall *c) +{ + KviKvsVariant * pColArray; + kvs_int_t iColR,iColG,iColB; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("hex_rgb_array_or_red",KVS_PT_VARIANT,0,pColArray) + KVSO_PARAMETER("green",KVS_PT_INT,KVS_PF_OPTIONAL,iColG) + KVSO_PARAMETER("blue",KVS_PT_INT,KVS_PF_OPTIONAL,iColB) + KVSO_PARAMETERS_END(c) + + if(pColArray->isArray()) + { + if(pColArray->array()->size() < 3) + { + c->error(__tr2qs("The array passed as parameter must contain at least 3 elements")); + return false; + } + KviKvsVariant * pColR = pColArray->array()->at(0); + KviKvsVariant * pColG = pColArray->array()->at(1); + KviKvsVariant * pColB = pColArray->array()->at(2); + + if(!(pColR && pColG && pColB)) + { + c->error(__tr2qs("One of the colors array parameters is empty")); + return false; + } + if(!(pColR->asInteger(iColR) && pColG->asInteger(iColG) && pColB->asInteger(iColB))) + { + c->error(__tr2qs("One of the colors array parameters didn't evaluate to an integer")); + return false; + } + + } else { + if (c->params()->count()==1) + { + bool bOk,bOk1,bOk2; + QString value; + pColArray->asString(value); + int i=0; + if (value.length()!=6) + { + c->warning(__tr2qs("A string of 6 digits hex is required")); + return true; + } + QString buffer(value.mid(0,2)); + iColR=buffer.toInt(&bOk,16); + buffer=value.mid(2,2); + iColG=buffer.toInt(&bOk1,16); + buffer=value.mid(4,2); + iColB=buffer.toInt(&bOk2,16); + if (!bOk || !bOk1 || !bOk2) + { + c->warning(__tr2qs("Not an hex digits")); + return true; + } + if (widget()) widget()->setPaletteForegroundColor(QColor(iColR,iColG,iColB)); + return true; + } + + if(c->params()->count() < 3) + { + + c->error(__tr2qs("$setForegroundColor requires either an array as first parameter, one hex string or three integers")); + return false; + } + if(!pColArray->asInteger(iColR)) + { + c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer")); + return false; + } + } + if (widget()) widget()->setPaletteForegroundColor(QColor(iColR,iColG,iColB)); + return true; +} + +bool KviKvsObject_widget::function_setBackgroundColor(KviKvsObjectFunctionCall *c) +{ + KviKvsVariant * pColArray; + kvs_int_t iColR,iColG,iColB; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("hex_rgb_array_or_red",KVS_PT_VARIANT,0,pColArray) + KVSO_PARAMETER("green",KVS_PT_INT,KVS_PF_OPTIONAL,iColG) + KVSO_PARAMETER("blue",KVS_PT_INT,KVS_PF_OPTIONAL,iColB) + KVSO_PARAMETERS_END(c) + + if(pColArray->isArray()) + { + if(pColArray->array()->size() < 3) + { + c->error(__tr2qs("The array passed as parameter must contain at least 3 elements")); + return false; + } + KviKvsVariant * pColR = pColArray->array()->at(0); + KviKvsVariant * pColG = pColArray->array()->at(1); + KviKvsVariant * pColB = pColArray->array()->at(2); + + if(!(pColR && pColG && pColB)) + { + c->error(__tr2qs("One of the colors array parameters is empty")); + return false; + } + if(!(pColR->asInteger(iColR) && pColG->asInteger(iColG) && pColB->asInteger(iColB))) + { + c->error(__tr2qs("One of the colors array parameters didn't evaluate to an integer")); + return false; + } + + } else { + if (c->params()->count()==1) + { + bool bOk,bOk1,bOk2; + QString value; + pColArray->asString(value); + int i=0; + if (value.length()!=6) + { + c->warning(__tr2qs("A string of 6 digits hex is required")); + return true; + } + QString buffer(value.mid(0,2)); + iColR=buffer.toInt(&bOk,16); + buffer=value.mid(2,2); + iColG=buffer.toInt(&bOk1,16); + buffer=value.mid(4,2); + iColB=buffer.toInt(&bOk2,16); + if (!bOk || !bOk1 || !bOk2) + { + c->warning(__tr2qs("Not an hex digits")); + return true; + } + if (widget()) widget()->setBackgroundColor(QColor(iColR,iColG,iColB)); + return true; + } + + if(c->params()->count() < 3) + { + + c->error(__tr2qs("$setBackgroundColor requires either an array as first parameter, one hex string or three integers")); + return false; + } + if(!pColArray->asInteger(iColR)) + { + c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer")); + return false; + } + } + if (widget()) widget()->setBackgroundColor(QColor(iColR,iColG,iColB)); + return true; +} + +bool KviKvsObject_widget::function_backgroundColor(KviKvsObjectFunctionCall *c) +{ + if(!widget())return true; + QColor col = widget()->backgroundColor(); + KviKvsArray * a = new KviKvsArray(); + a->set(0,new KviKvsVariant((kvs_int_t)col.red())); + a->set(1,new KviKvsVariant((kvs_int_t)col.green())); + a->set(2,new KviKvsVariant((kvs_int_t)col.blue())); + c->returnValue()->setArray(a); + return true; +} + +bool KviKvsObject_widget::function_foregroundColor(KviKvsObjectFunctionCall *c) +{ + if(!widget())return true; + QColor col = widget()->foregroundColor(); + KviKvsArray * a = new KviKvsArray(); + a->set(0,new KviKvsVariant((kvs_int_t)col.red())); + a->set(1,new KviKvsVariant((kvs_int_t)col.green())); + a->set(2,new KviKvsVariant((kvs_int_t)col.blue())); + c->returnValue()->setArray(a); + return true; +} + +bool KviKvsObject_widget::function_parentWidget(KviKvsObjectFunctionCall *c) +{ + if(!widget())return true; + if(parentScriptWidget()) c->returnValue()->setHObject(parentObject()->handle()); + else + c->returnValue()->setHObject((kvs_hobject_t)0); + return true; + +} +bool KviKvsObject_widget::function_setMouseTracking(KviKvsObjectFunctionCall *c) +{ + bool bEnabled; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("bEnabled",KVS_PT_BOOL,0,bEnabled) + KVSO_PARAMETERS_END(c) + if(widget()) widget()->setMouseTracking(bEnabled); + return true; +} + +bool KviKvsObject_widget::function_setCaption(KviKvsObjectFunctionCall *c) +{ + QString szCaption; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("caption",KVS_PT_STRING,0,szCaption) + KVSO_PARAMETERS_END(c) + if(widget()) widget()->setCaption(szCaption); + return true; +} + +bool KviKvsObject_widget::function_caption(KviKvsObjectFunctionCall *c) +{ + if(widget()) c->returnValue()->setString(widget()->caption().utf8().data()); + return true; +} + +bool KviKvsObject_widget::function_isTopLevel(KviKvsObjectFunctionCall *c) +{ + if(widget()) c->returnValue()->setBoolean(widget()->isTopLevel()); + return true; +} + +bool KviKvsObject_widget::function_isVisible(KviKvsObjectFunctionCall *c) +{ + if(widget()) c->returnValue()->setBoolean(widget()->isVisible()); + return true; +} + +bool KviKvsObject_widget::function_raise(KviKvsObjectFunctionCall *) +{ + if(widget()) widget()->raise(); + return true; +} + +bool KviKvsObject_widget::function_lower(KviKvsObjectFunctionCall *) +{ + if(widget())widget()->lower(); + return true; +} + +bool KviKvsObject_widget::function_hasFocus(KviKvsObjectFunctionCall *c) +{ + if(widget()) c->returnValue()->setBoolean(widget()->hasFocus()); + return true; +} + +bool KviKvsObject_widget::function_setFocus(KviKvsObjectFunctionCall *c) +{ + if (widget())widget()->setFocus(); + return true; +} +bool KviKvsObject_widget::function_hide(KviKvsObjectFunctionCall *) +{ + if(widget())widget()->hide(); + return true; +} + +bool KviKvsObject_widget::function_setToolTip(KviKvsObjectFunctionCall *c) +{ + QString szTooltip; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("tooltip",KVS_PT_STRING,0,szTooltip) + KVSO_PARAMETERS_END(c) + if(widget())QToolTip::add( widget(), szTooltip ); + return true; +} + +bool KviKvsObject_widget::function_x(KviKvsObjectFunctionCall *c) +{ + if(widget()) c->returnValue()->setInteger(widget()->x()); + return true; +} + +bool KviKvsObject_widget::function_y(KviKvsObjectFunctionCall *c) +{ + if(widget())c->returnValue()->setInteger(widget()->y()); + return true; +} + +bool KviKvsObject_widget::function_width(KviKvsObjectFunctionCall *c) +{ + if(widget())c->returnValue()->setInteger(widget()->width()); + return true; +} + +bool KviKvsObject_widget::function_height(KviKvsObjectFunctionCall *c) +{ + if(widget())c->returnValue()->setInteger(widget()->height()); + return true; +} + +bool KviKvsObject_widget::function_setMinimumWidth(KviKvsObjectFunctionCall *c) +{ + kvs_int_t iW; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("w",KVS_PT_INT,0,iW) + KVSO_PARAMETERS_END(c) + if (widget()) widget()->setMinimumWidth(iW); + return true; +} + +bool KviKvsObject_widget::function_setMinimumHeight(KviKvsObjectFunctionCall *c) +{ + kvs_int_t iH; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("h",KVS_PT_INT,0,iH) + KVSO_PARAMETERS_END(c) + if (widget()) widget()->setMinimumHeight(iH); + return true; +} + +bool KviKvsObject_widget::function_setMaximumWidth(KviKvsObjectFunctionCall *c) +{ + kvs_int_t iW; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("w",KVS_PT_INT,0,iW) + KVSO_PARAMETERS_END(c) + if (widget()) widget()->setMaximumWidth(iW); + return true; +} + +bool KviKvsObject_widget::function_setMaximumHeight(KviKvsObjectFunctionCall *c) +{ + kvs_int_t iH; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("h",KVS_PT_INT,0,iH) + KVSO_PARAMETERS_END(c) + if(widget()) widget()->setMaximumHeight(iH); + return true; +} + +bool KviKvsObject_widget::function_move(KviKvsObjectFunctionCall *c) +{ + kvs_int_t iX,iY; + + KviKvsVariant * pXOrArray; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("x_or_array",KVS_PT_VARIANT,0,pXOrArray) + KVSO_PARAMETER("y",KVS_PT_INT,KVS_PF_OPTIONAL,iY) + KVSO_PARAMETERS_END(c) + if(pXOrArray->isArray()) + { + if(pXOrArray->array()->size() < 2) + { + c->error(__tr2qs("The array passed as parameter must contain at least 2 elements")); + return false; + } + KviKvsVariant * pX = pXOrArray->array()->at(0); + KviKvsVariant * pY = pXOrArray->array()->at(1); + if(!(pX && pY)) + { + c->error(__tr2qs("One of the move array parameters is empty")); + return false; + } + if(!(pX->asInteger(iX) && pY->asInteger(iY))) + { + c->error(__tr2qs("One of the move array parameters didn't evaluate to an integer")); + return false; + } + // ok: the params are correct + } else { + if(c->params()->count() < 2) + { + c->error(__tr2qs("$move() requires either an array as first parameter or two integers")); + return false; + } + if(!pXOrArray->asInteger(iX)) + { + c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer")); + return false; + } + // ok: the params are correct + } + + if(!widget())return true; + widget()->move(QPoint(iX,iY)); + return true; +} +bool KviKvsObject_widget::function_sizeHint(KviKvsObjectFunctionCall *c) +{ + if(!widget())return true; + QSize sizehint = widget()->sizeHint(); + KviKvsArray * a = new KviKvsArray(); + a->set(0,new KviKvsVariant((kvs_int_t)sizehint.width())); + a->set(1,new KviKvsVariant((kvs_int_t)sizehint.height())); + c->returnValue()->setArray(a); + return true; +} + +bool KviKvsObject_widget::function_resize(KviKvsObjectFunctionCall *c) +{ + KviKvsVariant * pWOrArray; + kvs_int_t iW,iH; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("width_or_array",KVS_PT_VARIANT,0,pWOrArray) + KVSO_PARAMETER("height",KVS_PT_INT,KVS_PF_OPTIONAL,iH) + KVSO_PARAMETERS_END(c) + if(pWOrArray->isArray()) + { + if(pWOrArray->array()->size() < 2) + { + c->error(__tr2qs("The array passed as parameter must contain at least 2 elements")); + return false; + } + KviKvsVariant * pW = pWOrArray->array()->at(0); + KviKvsVariant * pH = pWOrArray->array()->at(1); + if(!(pW && pH)) + { + c->error(__tr2qs("One of the resize array parameters is empty")); + return false; + } + if(!(pW->asInteger(iW) && pH->asInteger(iH))) + { + c->error(__tr2qs("One of the resize array parameters didn't evaluate to an integer")); + return false; + } + // ok: the params are correct + } else { + if(c->params()->count() < 2) + { + c->error(__tr2qs("$resize() requires either an array as first parameter or two integers")); + return false; + } + if(!pWOrArray->asInteger(iW)) + { + c->error(__tr2qs("The first parameter didn't evaluate to an array nor an integer")); + return false; + } + // ok: the params are correct + } + + if(!widget())return true; + widget()->resize(QSize(iW,iH)); + return true; +} +bool KviKvsObject_widget::function_setFocusPolicy(KviKvsObjectFunctionCall *c) +{ + QString szMode; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("focus",KVS_PT_STRING,0,szMode) + KVSO_PARAMETERS_END(c) + if(!widget())return true; + if(KviQString::equalCI(szMode, "TabFocus")) + widget()->setFocusPolicy(QT_WIDGET_TABFOCUS); + else + if(KviQString::equalCI(szMode, "ClickFocus")) + widget()->setFocusPolicy(QT_WIDGET_CLICKFOCUS); + else + if(KviQString::equalCI(szMode, "StrongFocus")) + widget()->setFocusPolicy(QT_WIDGET_STRONGFOCUS); + else + if(KviQString::equalCI(szMode, "NoFocus")) + widget()->setFocusPolicy(QT_WIDGET_NOFOCUS); + else c->warning(__tr2qs("Invalid parameters")); + return true; +} + +bool KviKvsObject_widget::function_setWFlags(KviKvsObjectFunctionCall *c) +{ + QStringList wflags; + //Qt::WindowType sum; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("widget_flags",KVS_PT_STRINGLIST,KVS_PF_OPTIONAL,wflags) + KVSO_PARAMETERS_END(c) + if (!widget()) return true; + #ifdef COMPILE_USE_QT4 + Qt::WindowFlags flag,sum=0; + #else + int flag,sum=0; + #endif + for ( QStringList::Iterator it = wflags.begin(); it != wflags.end(); ++it ) + { + + flag=0; + for(unsigned int j = 0; j < widgettypes_num; j++) + { + if(KviQString::equalCI((*it), widgettypes_tbl[j])) + { + flag=widgettypes_cod[j]; + break; + } + } + if(flag) + sum = sum | flag; + else + c->warning(__tr2qs("Unknown widget flag '%Q'"),&(*it)); + + } + +#ifdef COMPILE_USE_QT4 + widget()->setWindowFlags(sum); +#else + widget()->reparent(widget()->parentWidget(),sum,QPoint(widget()->x(),widget()->y())); +#endif + return true; +} + +bool KviKvsObject_widget::function_setFont(KviKvsObjectFunctionCall *c) +{ + + QString szFamily,szStyle; + kvs_int_t uSize; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("size",KVS_PT_UNSIGNEDINTEGER,0,uSize) + KVSO_PARAMETER("family",KVS_PT_STRING,0,szFamily) + KVSO_PARAMETER("style",KVS_PT_STRING,0,szStyle) + KVSO_PARAMETERS_END(c) + if(!widget())return true; + QFont font=widget()->font(); + font.setFamily(szFamily); + font.setPointSize(uSize); + if(KviQString::equalCI(szStyle,"italic")) font.setItalic(TRUE); + else if(KviQString::equalCI(szStyle,"bold")) font.setBold(TRUE); + else if(KviQString::equalCI(szStyle,"underline"))font.setUnderline(TRUE); + else if(KviQString::equalCI(szStyle,"overline")) font.setOverline(TRUE); + else if(KviQString::equalCI(szStyle,"strikeout"))font.setStrikeOut(TRUE); + else if(KviQString::equalCI(szStyle,"fixedpitch")) font.setFixedPitch(TRUE); + else c->warning(__tr2qs("Unknown style '%Q'"),&szStyle); + widget()->setFont(font); + return true; +} + +bool KviKvsObject_widget::function_addWidgetToWrappedLayout(KviKvsObjectFunctionCall *c) +{ + KviKvsObject *ob; + kvs_int_t uCol,uRow; + kvs_hobject_t hObject; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("widget",KVS_PT_HOBJECT,0,hObject) + KVSO_PARAMETER("col",KVS_PT_UNSIGNEDINTEGER,0,uCol) + KVSO_PARAMETER("row",KVS_PT_UNSIGNEDINTEGER,0,uRow) + KVSO_PARAMETERS_END(c) + ob=KviKvsKernel::instance()->objectController()->lookupObject(hObject); + if(!widget())return true; + if (!ob) + { + c->warning(__tr2qs("Widget parameter is not an object")); + return true; + } + if (!ob->object()) + { + c->warning(__tr2qs("Widget parameter is not a valid object")); + return true; + } + QLayout *lay=widget()->layout(); + if (!lay) + { + c->warning(__tr2qs("No Layout associated to the widget ")); + return true; + } + if(!ob->object()->isWidgetType()) + { + c->warning(__tr2qs("Can't add a non-widget object")); + return true; + } + lay->add(((QWidget *)(ob->object()))); + return true; +} +bool KviKvsObject_widget::function_reparent(KviKvsObjectFunctionCall *c) +{ + KviKvsObject *ob; + kvs_hobject_t hObject; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("widget",KVS_PT_HOBJECT,KVS_PF_OPTIONAL,hObject) + KVSO_PARAMETERS_END(c) + ob=KviKvsKernel::instance()->objectController()->lookupObject(hObject); + if(!widget()) return true; + if(!ob) + { + widget()->reparent(0,QPoint(widget()->x(),widget()->y())); + return true; + } + else + if(!ob->object()->isWidgetType()) + { + c->warning(__tr("Parent must be a widget object")); + return true; + } + widget()->reparent(((QWidget *)(ob->object())),QPoint(((QWidget *)(ob->object()))->x(),((QWidget *)(ob->object()))->y())); + return true; +} +bool KviKvsObject_widget::function_setIcon(KviKvsObjectFunctionCall *c) +{ + + QString icon; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("icon",KVS_PT_STRING,0,icon) + KVSO_PARAMETERS_END(c) + if(!widget())return true; + QPixmap * pix = g_pIconManager->getImage(icon); + if(pix)widget()->setIcon(*pix); + return true; +} + +bool KviKvsObject_widget::function_setBackgroundImage(KviKvsObjectFunctionCall *c) +{ + QString image; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("image",KVS_PT_STRING,0,image) + KVSO_PARAMETERS_END(c) + if(!widget())return true; + QPixmap * pix = g_pIconManager->getImage(image); + if(pix)widget()->setPaletteBackgroundPixmap(*pix); + return true; +} +bool KviKvsObject_widget::function_globalCursorX(KviKvsObjectFunctionCall *c) +{ + if(widget())c->returnValue()->setInteger(QCursor::pos().x()); + return true; +} +bool KviKvsObject_widget::function_globalCursorY(KviKvsObjectFunctionCall *c) +{ + if(widget())c->returnValue()->setInteger(QCursor::pos().y()); + return true; +} +bool KviKvsObject_widget::function_setMask(KviKvsObjectFunctionCall *c) +{ + KviKvsObject *obj; + kvs_hobject_t hObject; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("pixmap",KVS_PT_HOBJECT,0,hObject) + KVSO_PARAMETERS_END(c) + obj=KviKvsKernel::instance()->objectController()->lookupObject(hObject); + if(!widget())return true; + if (!obj) + { + c->warning(__tr2qs("Pixmap parameter is not an object")); + return true; + } + if (!obj->inherits("KviKvsObject_pixmap")) + { + c->warning(__tr2qs("Pixmap object required")); + return true; + } + QPixmap * pm=((KviKvsObject_pixmap *)obj)->getPixmap(); +#ifdef COMPILE_USE_QT4 + QBitmap mask(pm->mask()); +#else + QBitmap mask(*pm->mask()); +#endif + if (mask.isNull()) c->warning(__tr2qs("Null mask")); + widget()->setMask(mask); + return true; +} +#ifdef COMPILE_USE_QT4 +bool KviKvsObject_widget::function_setAttribute(KviKvsObjectFunctionCall *c) +{ + QString attribute; + bool bFlag; + KVSO_PARAMETERS_BEGIN(c) + KVSO_PARAMETER("widget_atribute",KVS_PT_STRING,0,attribute) + KVSO_PARAMETER("bool_flag",KVS_PT_BOOLEAN,0,bFlag) + KVSO_PARAMETERS_END(c) + if (!widget()) return true; + bool found=false; + unsigned int j = 0; + for(; j < widgetattributes_num; j++) + { + if(KviQString::equalCI(attribute, widgetattributes_tbl[j])) + { + found=true; + break; + } + } + if(found)widget()->setAttribute(widgetattributes_cod[j],bFlag); + else c->warning(__tr2qs("Unknown widget attribute '%Q'"),&attribute); + return true; +} +#endif + +#include "m_class_widget.moc" |
